-
Notifications
You must be signed in to change notification settings - Fork 89
Expand file tree
/
Copy pathsaml20.js
More file actions
289 lines (256 loc) · 10.5 KB
/
saml20.js
File metadata and controls
289 lines (256 loc) · 10.5 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
var async = require('async');
var moment = require('moment');
var xmlNameValidator = require('xml-name-validator');
var is_uri = require('valid-url').is_uri;
var EncryptXml = require('./xml/encrypt');
var SignXml = require('./xml/sign');
var utils = require('./utils');
const template = `<saml:Assertion xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion" Version="2.0" ID="" IssueInstant="">
<saml:Issuer></saml:Issuer>
<saml:Subject>
<saml:NameID Format="urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified" />
<saml:SubjectConfirmation Method="urn:oasis:names:tc:SAML:2.0:cm:bearer">
<saml:SubjectConfirmationData />
</saml:SubjectConfirmation>
</saml:Subject>
<saml:Conditions />
<saml:AuthnStatement AuthnInstant="">
<saml:AuthnContext>
<saml:AuthnContextClassRef>urn:oasis:names:tc:SAML:2.0:ac:classes:unspecified</saml:AuthnContextClassRef>
</saml:AuthnContext>
</saml:AuthnStatement>
</saml:Assertion>`;
var newSaml20Document = utils.factoryForNode(template);
var NAMESPACE = 'urn:oasis:names:tc:SAML:2.0:assertion';
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';
}
function extractSaml20Options(opts) {
return {
uid: opts.uid,
issuer: opts.issuer,
lifetimeInSeconds: opts.lifetimeInSeconds,
audiences: opts.audiences,
recipient: opts.recipient,
inResponseTo: opts.inResponseTo,
attributes: opts.attributes,
includeAttributeNameFormat: (typeof opts.includeAttributeNameFormat !== 'undefined') ? opts.includeAttributeNameFormat : true,
typedAttributes: (typeof opts.typedAttributes !== 'undefined') ? opts.typedAttributes : true,
sessionIndex: opts.sessionIndex,
nameIdentifier: opts.nameIdentifier,
nameIdentifierFormat: opts.nameIdentifierFormat,
authnContextClassRef: opts.authnContextClassRef
};
}
/**
* Creates a signed SAML 2.0 assertion from the given options.
*
* @param options
*
* // SAML
* @param [options.uid] {string}
* @param [options.issuer] {string}
* @param [options.lifetimeInSeconds] {number}
* @param [options.audiences] {string|string[]}
* @param [options.recipient] {string}
* @param [options.inResponseTo] {string}
* @param [options.attributes]
* @param [options.includeAttributeNameFormat] {boolean}
* @param [options.typedAttributes] {boolean}
* @param [options.sessionIndex] {string}
* @param [options.nameIdentifier] {string}
* @param [options.nameIdentifierFormat] {string}
* @param [options.authnContextClassRef] {string}
*
* // XML Dsig
* @param options.key {Buffer}
* @param options.cert {Buffer}
* @param [options.signatureAlgorithm] {string}
* @param [options.digestAlgorithm] {string}
* @param [options.signatureNamespacePrefix] {string}
* @param [options.xpathToNodeBeforeSignature] {string}
* @param [options.signatureIdAttribute] {String}
*
* // XML encryption
* @param [options.encryptionCert] {Buffer}
* @param [options.encryptionPublicKey] {Buffer}
* @param [options.encryptionAlgorithm] {string}
* @param [options.keyEncryptionAlgorithm] {string}
*
* @param {Function} [callback] required if encrypting
* @return {*}
*/
exports.create = function createSignedAssertion(options, callback) {
return createAssertion(extractSaml20Options(options), {
signXml: SignXml.fromSignXmlOptions(Object.assign({
xpathToNodeBeforeSignature: "//*[local-name(.)='Issuer']",
signatureIdAttribute: 'ID'
}, options)),
encryptXml: EncryptXml.fromEncryptXmlOptions(options)
}, callback);
};
/**
* Creates an **unsigned** SAML 2.0 assertion from the given options.
*
* @param options
*
* // SAML
* @param [options.uid] {string}
* @param [options.issuer] {string}
* @param [options.lifetimeInSeconds] {number}
* @param [options.audiences] {string|string[]}
* @param [options.recipient] {string}
* @param [options.inResponseTo] {string}
* @param [options.attributes]
* @param [options.includeAttributeNameFormat] {boolean}
* @param [options.typedAttributes] {boolean}
* @param [options.sessionIndex] {string}
* @param [options.nameIdentifier] {string}
* @param [options.nameIdentifierFormat] {string}
* @param [options.authnContextClassRef] {string}
*
* // XML encryption
* @param [options.encryptionCert] {Buffer}
* @param [options.encryptionPublicKey] {Buffer}
* @param [options.encryptionAlgorithm] {string}
* @param [options.keyEncryptionAlgorithm] {string}
*
* @param {Function} [callback] required if encrypting
* @return {*}
*/
exports.createUnsignedAssertion = function createUnsignedAssertion(options, callback) {
return createAssertion(extractSaml20Options(options), {
signXml: SignXml.unsigned,
encryptXml: EncryptXml.fromEncryptXmlOptions(options)
}, callback);
};
/**
* @param options SAML options
* @param strategies
* @param strategies.signXml {Function} strategy to sign the assertion
* @param strategies.encryptXml {Function} strategy to encrypt the assertion
* @param callback
* @return {*}
*/
function createAssertion(options, strategies, callback) {
var doc = newSaml20Document();
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 signed;
try {
signed = strategies.signXml(doc);
} catch(err){
return utils.reportError(err, callback);
}
if (strategies.encryptXml === EncryptXml.unencrypted) {
return strategies.encryptXml(signed, callback);
}
async.waterfall([
function (cb) {
strategies.encryptXml(signed, cb)
},
function (encrypted, cb) {
var assertion = '<saml:EncryptedAssertion xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion">' + encrypted + '</saml:EncryptedAssertion>';
cb(null, utils.removeWhitespace(assertion));
},
], callback);
}