-
Notifications
You must be signed in to change notification settings - Fork 89
Expand file tree
/
Copy pathsaml20.js
More file actions
327 lines (266 loc) · 12.9 KB
/
saml20.js
File metadata and controls
327 lines (266 loc) · 12.9 KB
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
var utils = require('./utils'),
Parser = require('xmldom').DOMParser,
SignedXml = require('xml-crypto').SignedXml,
xmlenc = require('xml-encryption'),
moment = require('moment'),
xmlNameValidator = require('xml-name-validator'),
is_uri = require('valid-url').is_uri;
var fs = require('fs');
var path = require('path');
var saml20 = fs.readFileSync(path.join(__dirname, 'saml20.template')).toString();
var documentSigningLocation = 'Assertion';
var NAMESPACE = 'urn:oasis:names:tc:SAML:2.0:assertion';
var algorithms = {
signature: {
'rsa-sha256': 'http://www.w3.org/2001/04/xmldsig-more#rsa-sha256',
'rsa-sha1': 'http://www.w3.org/2000/09/xmldsig#rsa-sha1'
},
digest: {
'sha256': 'http://www.w3.org/2001/04/xmlenc#sha256',
'sha1': 'http://www.w3.org/2000/09/xmldsig#sha1'
}
};
var ResponseSigningLevel = {
ResponseOnly: 'ResponseOnly',
AssertionAndResponse: 'AssertionAndResponse'
}
function getAttributeType(value){
switch(typeof value) {
case "string":
return 'xs:string';
case "boolean":
return 'xs:boolean';
case "number":
// Maybe we should fine-grain this type and check whether it is an integer, float, double xsi:types
return 'xs:double';
default:
return 'xs:anyType';
}
}
function getNameFormat(name){
if (is_uri(name)){
return 'urn:oasis:names:tc:SAML:2.0:attrname-format:uri';
}
// Check that the name is a valid xs:Name -> https://www.w3.org/TR/xmlschema-2/#Name
// xmlNameValidate.name takes a string and will return an object of the form { success, error },
// where success is a boolean
// if it is false, then error is a string containing some hint as to where the match went wrong.
if (xmlNameValidator.name(name).success){
return 'urn:oasis:names:tc:SAML:2.0:attrname-format:basic';
}
// Default value
return 'urn:oasis:names:tc:SAML:2.0:attrname-format:unspecified';
}
/**
* Gets the complete SAML20 response embedding the assertion (encrypted optional) and
* options argument to set attributes for response utilizing the saml20Response.template file.
* @param assertion - the SAML assertion to add to the SAML response.
* @param options - The saml20 class options argument.
* @returns string - SAML20 Full Response with embedded assertion XML.
* @throws assertion argument null or empty error.
*/
function getSamlResponseXml(assertion, options) {
var issueTime = new Date().toISOString();
if (!assertion || assertion.length < 1)
throw new ReferenceError('Assertion XML cannot be empty for parsing while creating SAML20 Response.')
var assertionXml = new Parser().parseFromString(assertion);
var saml20Response = fs.readFileSync(path.join(__dirname, 'saml20Response.template')).toString();
var doc = new Parser().parseFromString(saml20Response.toString());
doc.documentElement.setAttribute('ID', '_' + (options.responseUid));
doc.documentElement.setAttribute('IssueInstant', moment.utc().format('YYYY-MM-DDTHH:mm:ss.SSS[Z]'));
doc.documentElement.setAttribute('Destination', options.destination);
if (options.issuer) {
var issuer = doc.documentElement.getElementsByTagName('saml:Issuer');
issuer[0].textContent = options.issuer;
}
doc.lastChild.appendChild(assertionXml.documentElement);
return doc.toString();
}
/**
* Signs the SAML XML at the Assertion level (default) or the Response Level (optional) using private key and cert.
* @param xmlToSign - The XML in string form containing the XML assertion or response.
* @param options - The saml20 class options argument.
* @returns string - Signed SAML assertion or response depending on option.
* @throws ReferenceError if xml argument sent for signing is null or empty.
*/
function signXml(xmlToSign, options, documentSigningLocation) {
if (!xmlToSign || xmlToSign.length < 1)
throw new ReferenceError('XML to sign cannot be null or empty.')
// 0.10.1 added prefix, but we want to name it signatureNamespacePrefix - This is just to keep supporting prefix
options.signatureNamespacePrefix = options.signatureNamespacePrefix || options.prefix;
options.signatureNamespacePrefix = typeof options.signatureNamespacePrefix === 'string' ? options.signatureNamespacePrefix : '' ;
var cert = utils.pemToCert(options.cert);
var sig = new SignedXml(null, { signatureAlgorithm: algorithms.signature[options.signatureAlgorithm], idAttribute: 'ID' });
var signingLocation = documentSigningLocation || 'Assertion';
sig.addReference("//*[local-name(.)='" + signingLocation + "']",
["http://www.w3.org/2000/09/xmldsig#enveloped-signature", "http://www.w3.org/2001/10/xml-exc-c14n#"],
algorithms.digest[options.digestAlgorithm]);
sig.signingKey = options.key;
var opts = {
location: {
reference: options.xpathToNodeBeforeSignature || "//*[local-name(.)='Issuer']",
action: 'after'
},
prefix: options.signatureNamespacePrefix
};
sig.keyInfoProvider = {
getKeyInfo: function (key, prefix) {
prefix = prefix ? prefix + ':' : prefix;
return "<" + prefix + "X509Data><" + prefix + "X509Certificate>" + cert + "</" + prefix + "X509Certificate></" + prefix + "X509Data>";
}
};
sig.computeSignature(xmlToSign, opts);
return sig.getSignedXml();
}
/**
* Encrypts s SAML assertion and formats with EncryptedAssertion wrapper using provided cert.
* @param assertionToEncrypt - The SAML assertion to encrypt.
* @param options - The saml20 class options argument.
* @returns Promise (resolve, reject) for the embedded ASYNC encrypt function callback wrapper.
*/
var encryptAssertionXml = (assertionToEncrypt, options) =>
new Promise((resolve, reject) => {
var encryptOptions = {
rsa_pub: options.encryptionPublicKey,
pem: options.encryptionCert,
encryptionAlgorithm: options.encryptionAlgorithm || 'http://www.w3.org/2001/04/xmlenc#aes256-cbc',
keyEncryptionAlgorighm: options.keyEncryptionAlgorighm || 'http://www.w3.org/2001/04/xmlenc#rsa-oaep-mgf1p'
};
xmlenc.encrypt(assertionToEncrypt, encryptOptions, function (err, encryptedAssertion) {
if (err) reject(err);
encryptedAssertion = `<saml:EncryptedAssertion xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion">${encryptedAssertion}</saml:EncryptedAssertion>`;
resolve(encryptedAssertion);
});
});
exports.create = function (options, callback) {
if (!options.key)
throw new Error('Expect a private key in pem format');
if (!options.cert)
throw new Error('Expect a public key cert in pem format');
if (options.createSignedSamlResponse) {
if (!options.destination || options.destination.length < 1) {
throw new Error('Expect a SAML Response destination for message to be valid.');
}
options.responseSigningLevel = options.responseSigningLevel || ResponseSigningLevel.ResponseOnly;
options.responseUid = options.responseUid || utils.uid(32);
}
options.signatureAlgorithm = options.signatureAlgorithm || 'rsa-sha256';
options.digestAlgorithm = options.digestAlgorithm || 'sha256';
options.includeAttributeNameFormat = (typeof options.includeAttributeNameFormat !== 'undefined') ? options.includeAttributeNameFormat : true;
options.typedAttributes = (typeof options.typedAttributes !== 'undefined') ? options.typedAttributes : true;
var doc;
try {
doc = new Parser().parseFromString(saml20.toString());
} catch(err){
return utils.reportError(err, callback);
}
doc.documentElement.setAttribute('ID', '_' + (options.uid || utils.uid(32)));
if (options.issuer) {
var issuer = doc.documentElement.getElementsByTagName('saml:Issuer');
issuer[0].textContent = options.issuer;
}
var now = moment.utc();
doc.documentElement.setAttribute('IssueInstant', now.format('YYYY-MM-DDTHH:mm:ss.SSS[Z]'));
var conditions = doc.documentElement.getElementsByTagName('saml:Conditions');
var confirmationData = doc.documentElement.getElementsByTagName('saml:SubjectConfirmationData');
if (options.lifetimeInSeconds) {
conditions[0].setAttribute('NotBefore', now.format('YYYY-MM-DDTHH:mm:ss.SSS[Z]'));
conditions[0].setAttribute('NotOnOrAfter', now.clone().add(options.lifetimeInSeconds, 'seconds').format('YYYY-MM-DDTHH:mm:ss.SSS[Z]'));
confirmationData[0].setAttribute('NotOnOrAfter', now.clone().add(options.lifetimeInSeconds, 'seconds').format('YYYY-MM-DDTHH:mm:ss.SSS[Z]'));
}
if (options.audiences) {
var audienceRestriction = doc.createElementNS(NAMESPACE, 'saml:AudienceRestriction');
var audiences = options.audiences instanceof Array ? options.audiences : [options.audiences];
audiences.forEach(function (audience) {
var element = doc.createElementNS(NAMESPACE, 'saml:Audience');
element.textContent = audience;
audienceRestriction.appendChild(element);
});
conditions[0].appendChild(audienceRestriction);
}
if (options.recipient)
confirmationData[0].setAttribute('Recipient', options.recipient);
if (options.inResponseTo)
confirmationData[0].setAttribute('InResponseTo', options.inResponseTo);
if (options.attributes) {
var statement = doc.createElementNS(NAMESPACE, 'saml:AttributeStatement');
statement.setAttribute('xmlns:xs', 'http://www.w3.org/2001/XMLSchema');
statement.setAttribute('xmlns:xsi', 'http://www.w3.org/2001/XMLSchema-instance');
doc.documentElement.appendChild(statement);
Object.keys(options.attributes).forEach(function(prop) {
if(typeof options.attributes[prop] === 'undefined') return;
// <saml:Attribute AttributeName="name" AttributeNamespace="http://schemas.xmlsoap.org/claims/identity">
// <saml:AttributeValue>Foo Bar</saml:AttributeValue>
// </saml:Attribute>
var attributeElement = doc.createElementNS(NAMESPACE, 'saml:Attribute');
attributeElement.setAttribute('Name', prop);
if (options.includeAttributeNameFormat){
attributeElement.setAttribute('NameFormat', getNameFormat(prop));
}
var values = options.attributes[prop] instanceof Array ? options.attributes[prop] : [options.attributes[prop]];
values.forEach(function (value) {
// Check by type, becase we want to include false values
if (typeof value !== 'undefined') {
// Ignore undefined values in Array
var valueElement = doc.createElementNS(NAMESPACE, 'saml:AttributeValue');
valueElement.setAttribute('xsi:type', options.typedAttributes ? getAttributeType(value) : 'xs:anyType');
valueElement.textContent = value;
attributeElement.appendChild(valueElement);
}
});
if (values && values.filter(function(i){ return typeof i !== 'undefined'; }).length > 0) {
// saml:Attribute must have at least one saml:AttributeValue
statement.appendChild(attributeElement);
}
});
}
doc.getElementsByTagName('saml:AuthnStatement')[0]
.setAttribute('AuthnInstant', now.format('YYYY-MM-DDTHH:mm:ss.SSS[Z]'));
if (options.sessionIndex) {
doc.getElementsByTagName('saml:AuthnStatement')[0]
.setAttribute('SessionIndex', options.sessionIndex);
}
var nameID = doc.documentElement.getElementsByTagNameNS(NAMESPACE, 'NameID')[0];
if (options.nameIdentifier) {
nameID.textContent = options.nameIdentifier;
}
if (options.nameIdentifierFormat) {
nameID.setAttribute('Format', options.nameIdentifierFormat);
}
if( options.authnContextClassRef ) {
var authnCtxClassRef = doc.getElementsByTagName('saml:AuthnContextClassRef')[0];
authnCtxClassRef.textContent = options.authnContextClassRef;
}
var assertion = utils.removeWhitespace(doc.toString());
// Enhanced path - construct a SAML20 response signed at the response
// with embedded (encrypted option) (signed option) assertion
if (options.createSignedSamlResponse) {
if (options.responseSigningLevel === ResponseSigningLevel.AssertionAndResponse) {
assertion = signXml(utils.removeWhitespace(assertion), options, 'Assertion');
}
if (options.encryptionCert) {
encryptAssertionXml(assertion, options)
.then(encryptedAssertion => (callback(null, signSamlResponse(encryptedAssertion))))
.catch((err) => callback(err));
} else {
var signedPlainResponse = signSamlResponse(assertion);
return (callback) ? callback(null, signedPlainResponse) : signedPlainResponse;
}
// Original path - create a simple signed (encrypted option) assertion.
} else {
var signedAssertion = signXml(utils.removeWhitespace(assertion), options, 'Assertion');
if (options.encryptionCert) {
encryptAssertionXml(signedAssertion, options)
.then(encryptedAssertion => callback(null, encryptedAssertion))
.catch((err) => callback(err));
} else {
// Send back signed if not set for encryption
return (callback) ? callback(null, signedAssertion) : signedAssertion;
}
}
// Sign response with inserted assertion (or encrypted assertion)
function signSamlResponse(assertion) {
var samlResponse = getSamlResponseXml(assertion, options);
return signXml(utils.removeWhitespace(samlResponse), options, 'Response');
}
};