forked from steffow/meteor-accounts-saml
-
Notifications
You must be signed in to change notification settings - Fork 0
/
saml_utils.js
executable file
·569 lines (473 loc) · 20.7 KB
/
saml_utils.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
/* globals SAML:true */
'use strict';
/* globals SAML:true */
const zlib = Npm.require('zlib');
const xml2js = Npm.require('xml2js');
const xmlCrypto = Npm.require('xml-crypto');
const crypto = Npm.require('crypto');
const xmldom = Npm.require('xmldom');
const querystring = Npm.require('querystring');
const xmlbuilder = Npm.require('xmlbuilder');
const array2string = Npm.require('arraybuffer-to-string');
// var prefixMatch = new RegExp(/(?!xmlns)^.*:/);
SAML = function(options) {
this.options = this.initialize(options);
};
// var stripPrefix = function(str) {
// return str.replace(prefixMatch, '');
// };
SAML.prototype.initialize = function(options) {
if (!options) {
options = {};
}
if (!options.protocol) {
options.protocol = 'https://';
}
if (!options.path) {
options.path = '/saml/consume';
}
if (!options.issuer) {
options.issuer = 'onelogin_saml';
}
if (options.identifierFormat === undefined) {
options.identifierFormat = 'urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress';
}
if (options.authnContext === undefined) {
options.authnContext = 'urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport';
}
return options;
};
SAML.prototype.generateUniqueID = function() {
const chars = 'abcdef0123456789';
let uniqueID = 'id-';
for (let i = 0; i < 20; i++) {
uniqueID += chars.substr(Math.floor((Math.random() * 15)), 1);
}
return uniqueID;
};
SAML.prototype.generateInstant = function() {
return new Date().toISOString();
};
SAML.prototype.signRequest = function(xml) {
const signer = crypto.createSign('RSA-SHA1');
signer.update(xml);
return signer.sign(this.options.privateKey, 'base64');
};
SAML.prototype.generateAuthorizeRequest = function(req) {
let id = `_${ this.generateUniqueID() }`;
const instant = this.generateInstant();
// Post-auth destination
let callbackUrl;
if (this.options.callbackUrl) {
callbackUrl = this.options.callbackUrl;
} else {
callbackUrl = this.options.protocol + req.headers.host + this.options.path;
}
if (this.options.id) {
id = this.options.id;
}
let request =
`<samlp:AuthnRequest xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol" ID="${ id }" Version="2.0" IssueInstant="${ instant
}" ProtocolBinding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST" AssertionConsumerServiceURL="${ callbackUrl }" Destination="${
this.options.entryPoint }">` +
`<saml:Issuer xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion">${ this.options.issuer }</saml:Issuer>\n`;
if (this.options.identifierFormat) {
request += `<samlp:NameIDPolicy xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol" Format="${ this.options.identifierFormat
}" AllowCreate="true"></samlp:NameIDPolicy>\n`;
}
request +=
'<samlp:RequestedAuthnContext xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol" Comparison="exact">' +
'<saml:AuthnContextClassRef xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion">urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport</saml:AuthnContextClassRef></samlp:RequestedAuthnContext>\n' +
'</samlp:AuthnRequest>';
return request;
};
SAML.prototype.generateLogoutRequest = function(options) {
// options should be of the form
// nameId: <nameId as submitted during SAML SSO>
// sessionIndex: sessionIndex
// --- NO SAMLsettings: <Meteor.setting.saml entry for the provider you want to SLO from
const id = `_${ this.generateUniqueID() }`;
const instant = this.generateInstant();
let request = `${ '<samlp:LogoutRequest xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol" ' +
'xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion" ID="' }${ id }" Version="2.0" IssueInstant="${ instant
}" Destination="${ this.options.idpSLORedirectURL }">` +
`<saml:Issuer xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion">${ this.options.issuer }</saml:Issuer>` +
`<saml:NameID Format="${ this.options.identifierFormat }">${ options.nameID }</saml:NameID>` +
'</samlp:LogoutRequest>';
request = `${ '<samlp:LogoutRequest xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol" ' +
'ID="' }${ id }" ` +
'Version="2.0" ' +
`IssueInstant="${ instant }" ` +
`Destination="${ this.options.idpSLORedirectURL }" ` +
'>' +
`<saml:Issuer xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion">${ this.options.issuer }</saml:Issuer>` +
'<saml:NameID xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion" ' +
'NameQualifier="http://id.init8.net:8080/openam" ' +
`SPNameQualifier="${ this.options.issuer }" ` +
`Format="${ this.options.identifierFormat }">${
options.nameID }</saml:NameID>` +
`<samlp:SessionIndex xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol">${ options.sessionIndex }</samlp:SessionIndex>` +
'</samlp:LogoutRequest>';
if (Meteor.settings.debug) {
console.log('------- SAML Logout request -----------');
console.log(request);
}
return {
request,
id
};
};
SAML.prototype.requestToUrl = function(request, operation, callback) {
const self = this;
zlib.deflateRaw(request, function(err, buffer) {
if (err) {
return callback(err);
}
const base64 = buffer.toString('base64');
let target = self.options.entryPoint;
if (operation === 'logout') {
if (self.options.idpSLORedirectURL) {
target = self.options.idpSLORedirectURL;
}
}
if (target.indexOf('?') > 0) {
target += '&';
} else {
target += '?';
}
// TBD. We should really include a proper RelayState here
let relayState;
if (operation === 'logout') {
// in case of logout we want to be redirected back to the Meteor app.
relayState = Meteor.absoluteUrl();
} else {
relayState = self.options.provider;
}
const samlRequest = {
SAMLRequest: base64,
RelayState: relayState
};
if (self.options.privateCert) {
samlRequest.SigAlg = 'http://www.w3.org/2000/09/xmldsig#rsa-sha1';
samlRequest.Signature = self.signRequest(querystring.stringify(samlRequest));
}
target += querystring.stringify(samlRequest);
if (Meteor.settings.debug) {
console.log(`requestToUrl: ${ target }`);
}
if (operation === 'logout') {
// in case of logout we want to be redirected back to the Meteor app.
return callback(null, target);
} else {
callback(null, target);
}
});
};
SAML.prototype.getAuthorizeUrl = function(req, callback) {
const request = this.generateAuthorizeRequest(req);
this.requestToUrl(request, 'authorize', callback);
};
SAML.prototype.getLogoutUrl = function(req, callback) {
const request = this.generateLogoutRequest(req);
this.requestToUrl(request, 'logout', callback);
};
SAML.prototype.certToPEM = function(cert) {
cert = cert.match(/.{1,64}/g).join('\n');
cert = `-----BEGIN CERTIFICATE-----\n${ cert }`;
cert = `${ cert }\n-----END CERTIFICATE-----\n`;
return cert;
};
// functionfindChilds(node, localName, namespace) {
// var res = [];
// for (var i = 0; i < node.childNodes.length; i++) {
// var child = node.childNodes[i];
// if (child.localName === localName && (child.namespaceURI === namespace || !namespace)) {
// res.push(child);
// }
// }
// return res;
// }
SAML.prototype.validateStatus = function(doc) {
let successStatus = false;
let status = '';
let messageText = '';
const statusNodes = doc.getElementsByTagNameNS('urn:oasis:names:tc:SAML:2.0:protocol', 'StatusCode');
if (statusNodes.length) {
const statusNode = statusNodes[0];
const statusMessage = doc.getElementsByTagNameNS('urn:oasis:names:tc:SAML:2.0:protocol', 'StatusMessage')[0];
if (statusMessage) {
messageText = statusMessage.firstChild.textContent;
}
status = statusNode.getAttribute('Value');
if (status === 'urn:oasis:names:tc:SAML:2.0:status:Success') {
successStatus = true;
}
}
return {
success: successStatus,
message: messageText,
statusCode: status
};
};
SAML.prototype.validateSignature = function(xml, cert) {
const self = this;
const doc = new xmldom.DOMParser().parseFromString(xml);
const signature = xmlCrypto.xpath(doc, '//*[local-name(.)=\'Signature\' and namespace-uri(.)=\'http://www.w3.org/2000/09/xmldsig#\']')[0];
const sig = new xmlCrypto.SignedXml();
sig.keyInfoProvider = {
getKeyInfo( /*key*/ ) {
return '<X509Data></X509Data>';
},
getKey( /*keyInfo*/ ) {
return self.certToPEM(cert);
}
};
sig.loadSignature(signature);
return sig.checkSignature(xml);
};
SAML.prototype.validateLogoutResponse = function(samlResponse, callback) {
const self = this;
const compressedSAMLResponse = new Buffer(samlResponse, 'base64');
zlib.inflateRaw(compressedSAMLResponse, function(err, decoded) {
if (err) {
if (Meteor.settings.debug) {
console.log("Error while inflating." + err);
}
} else {
console.log("construvting new DOM parser: " + Object.prototype.toString.call(decoded));
console.log(">>>>" + decoded);
const doc = new xmldom.DOMParser().parseFromString(array2string(decoded), 'text/xml');
if (doc) {
const response = doc.getElementsByTagNameNS('urn:oasis:names:tc:SAML:2.0:protocol', 'LogoutResponse')[0];
if (response) {
// TBD. Check if this msg corresponds to one we sent
var inResponseTo;
try {
inResponseTo = response.getAttribute('InResponseTo');
if (Meteor.settings.debug) {
console.log(`In Response to: ${ inResponseTo }`);
}
} catch (e) {
if (Meteor.settings.debug) {
console.log("Caught error: " + e);
const msg = doc.getElementsByTagNameNS('urn:oasis:names:tc:SAML:2.0:protocol', 'StatusMessage');
console.log("Unexpected msg from IDP. Does your session still exist at IDP? Idp returned: \n" + msg);
}
}
let statusValidateObj = self.validateStatus(doc);
if (statusValidateObj.success) {
callback(null, inResponseTo);
} else {
callback('Error. Logout not confirmed by IDP', null);
}
} else {
callback('No Response Found', null);
}
}
}
});
};
SAML.prototype.validateResponse = function(samlResponse, relayState, callback) {
const self = this;
const xml = new Buffer(samlResponse, 'base64').toString('utf8');
// We currently use RelayState to save SAML provider
if (Meteor.settings.debug) {
console.log(`Validating response with relay state: ${ xml }`);
}
const parser = new xml2js.Parser({
explicitRoot: true
});
const doc = new xmldom.DOMParser().parseFromString(xml, 'text/xml');
if (doc) {
if (Meteor.settings.debug) {
console.log('Verify status');
}
let statusValidateObj = self.validateStatus(doc);
if (statusValidateObj.success) {
if (Meteor.settings.debug) {
console.log('Status ok');
}
// Verify signature
if (Meteor.settings.debug) {
console.log('Verify signature');
}
if (self.options.cert && !self.validateSignature(xml, self.options.cert)) {
if (Meteor.settings.debug) {
console.log('Signature WRONG');
}
return callback(new Error('Invalid signature'), null, false);
}
if (Meteor.settings.debug) {
console.log('Signature OK');
}
const response = doc.getElementsByTagNameNS('urn:oasis:names:tc:SAML:2.0:protocol', 'Response')[0];
if (response) {
if (Meteor.settings.debug) {
console.log('Got response');
}
const assertion = response.getElementsByTagNameNS('urn:oasis:names:tc:SAML:2.0:assertion', 'Assertion')[0];
if (!assertion) {
return callback(new Error('Missing SAML assertion'), null, false);
}
const profile = {};
if (response.hasAttribute('InResponseTo')) {
profile.inResponseToId = response.getAttribute('InResponseTo');
}
const issuer = assertion.getElementsByTagNameNS('urn:oasis:names:tc:SAML:2.0:assertion', 'Issuer')[0];
if (issuer) {
profile.issuer = issuer.textContent;
}
const subject = assertion.getElementsByTagNameNS('urn:oasis:names:tc:SAML:2.0:assertion', 'Subject')[0];
if (subject) {
const nameID = subject.getElementsByTagNameNS('urn:oasis:names:tc:SAML:2.0:assertion', 'NameID')[0];
if (nameID) {
profile.nameID = nameID.textContent;
if (nameID.hasAttribute('Format')) {
profile.nameIDFormat = nameID.getAttribute('Format');
}
}
}
const authnStatement = assertion.getElementsByTagNameNS('urn:oasis:names:tc:SAML:2.0:assertion', 'AuthnStatement')[0];
if (authnStatement) {
if (authnStatement.hasAttribute('SessionIndex')) {
profile.sessionIndex = authnStatement.getAttribute('SessionIndex');
if (Meteor.settings.debug) {
console.log(`Session Index: ${ profile.sessionIndex }`);
}
} else if (Meteor.settings.debug) {
console.log('No Session Index Found');
}
} else if (Meteor.settings.debug) {
console.log('No AuthN Statement found');
}
const attributeStatement = assertion.getElementsByTagNameNS('urn:oasis:names:tc:SAML:2.0:assertion', 'AttributeStatement')[0];
if (attributeStatement) {
if (Meteor.settings.debug) {
console.log("Attribute Statement found in SAML response: " + attributeStatement);
}
const attributes = attributeStatement.getElementsByTagNameNS('urn:oasis:names:tc:SAML:2.0:assertion', 'Attribute');
if (Meteor.settings.debug) {
console.log("Attributes will be processed: " + attributes.length);
}
if (attributes) {
for (let i = 0; i < attributes.length; i++) {
const values = attributes[i].getElementsByTagNameNS('urn:oasis:names:tc:SAML:2.0:assertion', 'AttributeValue');
let value;
if (values.length === 1) {
value = values[0].textContent;
} else {
value = [];
for (var attributeValue of values) {
value.push(attributeValue.textContent);
}
}
if (Meteor.settings.debug) {
console.log("Name: " + attributes[i]);
console.log(`Adding attrinute from SAML response to profile:` + attributes[i].getAttribute('Name') + " = " + value.textContent);
}
profile[attributes[i].getAttribute('Name')] = value.textContent;
}
} else {
if (Meteor.settings.debug) {
console.log("No Attributes found in SAML attribute statement.");
}
}
if (!profile.mail && profile['urn:oid:0.9.2342.19200300.100.1.3']) {
// See http://www.incommonfederation.org/attributesummary.html for definition of attribute OIDs
profile.mail = profile['urn:oid:0.9.2342.19200300.100.1.3'];
}
if (!profile.email && profile.mail) {
profile.email = profile.mail;
}
} else {
if (Meteor.settings.debug) {
console.log("No Attribute Statement found in SAML response.");
}
}
if (!profile.email && profile.nameID && profile.nameIDFormat && profile.nameIDFormat.indexOf('emailAddress') >= 0) {
profile.email = profile.nameID;
}
if (Meteor.settings.debug) {
console.log(`NameID: ${ JSON.stringify(profile) }`);
}
callback(null, profile, false);
} else {
const logoutResponse = doc.getElementsByTagNameNS('urn:oasis:names:tc:SAML:2.0:protocol', 'LogoutResponse');
if (logoutResponse) {
callback(null, null, true);
} else {
return callback(new Error('Unknown SAML response message'), null, false);
}
}
} else {
return callback(new Error(`Status is: ${ statusValidateObj.statusCode }`), null, false);
}
}
};
let decryptionCert;
SAML.prototype.generateServiceProviderMetadata = function(callbackUrl) {
if (!decryptionCert) {
decryptionCert = this.options.privateCert;
}
if (!this.options.callbackUrl && !callbackUrl) {
throw new Error(
'Unable to generate service provider metadata when callbackUrl option is not set');
}
const metadata = {
'EntityDescriptor': {
'@xmlns': 'urn:oasis:names:tc:SAML:2.0:metadata',
'@xmlns:ds': 'http://www.w3.org/2000/09/xmldsig#',
'@entityID': this.options.issuer,
'SPSSODescriptor': {
'@protocolSupportEnumeration': 'urn:oasis:names:tc:SAML:2.0:protocol',
'SingleLogoutService': {
'@Binding': 'urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect',
'@Location': `${ Meteor.absoluteUrl() }_saml/logout/${ this.options.provider }/`,
'@ResponseLocation': `${ Meteor.absoluteUrl() }_saml/logout/${ this.options.provider }/`
},
'NameIDFormat': this.options.identifierFormat,
'AssertionConsumerService': {
'@index': '1',
'@isDefault': 'true',
'@Binding': 'urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST',
'@Location': callbackUrl
}
}
}
};
if (this.options.privateKey) {
if (!decryptionCert) {
throw new Error(
'Missing decryptionCert while generating metadata for decrypting service provider');
}
decryptionCert = decryptionCert.replace(/-+BEGIN CERTIFICATE-+\r?\n?/, '');
decryptionCert = decryptionCert.replace(/-+END CERTIFICATE-+\r?\n?/, '');
decryptionCert = decryptionCert.replace(/\r\n/g, '\n');
metadata['EntityDescriptor']['SPSSODescriptor']['KeyDescriptor'] = {
'ds:KeyInfo': {
'ds:X509Data': {
'ds:X509Certificate': {
'#text': decryptionCert
}
}
},
'EncryptionMethod': [
// this should be the set that the xmlenc library supports
{
'@Algorithm': 'http://www.w3.org/2001/04/xmlenc#aes256-cbc'
},
{
'@Algorithm': 'http://www.w3.org/2001/04/xmlenc#aes128-cbc'
},
{
'@Algorithm': 'http://www.w3.org/2001/04/xmlenc#tripledes-cbc'
}
]
};
}
return xmlbuilder.create(metadata).end({
pretty: true,
indent: ' ',
newline: '\n'
});
};