-
Notifications
You must be signed in to change notification settings - Fork 89
Expand file tree
/
Copy pathsaml20.js
More file actions
268 lines (224 loc) · 10.6 KB
/
saml20.js
File metadata and controls
268 lines (224 loc) · 10.6 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
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 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'
}
};
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';
}
/**
*
* @param {object} options
* @param options.key
* @param options.cert
* @param {string} [options.signatureAlgorithm]
* @param {string} [options.digestAlgorithm]
* @param {boolean} [options.includeAttributeNameFormat=true]
* @param [options.typedAttributes]
* @param {string} [options.issuer] Issuer of the SAML assertion
* @param [options.lifetimeInSeconds] timeframe in which this assertion is valid
* @param [options.recipient] recipient for the confirmation data
* @param [options.audiences]
* @param {string} [options.inResponseTo] SAML SubjectConfirmationData@InResponseTo
* @param {object} [options.attributes] assertion attributes. {@link https://github.com/auth0/node-saml/issues/33 Do not pass an empty object}
* @param [options.sessionIndex] session this assertion applies to
* @param {int} [options.sessionNotOnOrAfterSeconds] after this timestamp, the service provider must reauthenticate
* @param {string} [options.nameIdentifier] SAML nameID
* @param [options.nameIdentifierFormat] SAML nameID format
* @param [options.authnContextClassRef]
* @param [options.xpathToNodeBeforeSignature]
* @param [options.encryptionCert]
* @param [options.encryptionPublicKey]
* @param [options.encryptionAlgorithm]
* @param [options.keyEncryptionAlgorighm] {@link https://github.com/auth0/node-xml-encryption/issues/19 note spelling}
* @param {string} [options.prefix]
* @param {string|number} [options.signatureNamespacePrefix]
* @param {string} [options.uid] SAML document ID
* @param {function<T>} [callback] required if options.encryptionCert is specified
* @return {string|T|null}
* @template T
*/
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');
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;
// 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' });
sig.addReference("//*[local-name(.)='Assertion']",
["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;
sig.keyInfoProvider = {
getKeyInfo: function (key, prefix) {
prefix = prefix ? prefix + ':' : prefix;
return "<" + prefix + "X509Data><" + prefix + "X509Certificate>" + cert + "</" + prefix + "X509Certificate></" + prefix + "X509Data>";
}
};
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);
}
if (options.sessionNotOnOrAfterSeconds) {
doc.getElementsByTagName('saml:AuthnStatement')[0]
.setAttribute('SessionNotOnOrAfter', moment.unix(options.sessionNotOnOrAfterSeconds).utc().format('YYYY-MM-DDTHH:mm:ss.SSS[Z]'));
}
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 token = utils.removeWhitespace(doc.toString());
var signed;
try {
var opts = {
location: {
reference: options.xpathToNodeBeforeSignature || "//*[local-name(.)='Issuer']",
action: 'after'
},
prefix: options.signatureNamespacePrefix
};
sig.computeSignature(token, opts);
signed = sig.getSignedXml();
} catch(err){
return utils.reportError(err, callback);
}
if (!options.encryptionCert) {
if (callback)
return callback(null, signed);
else
return signed;
}
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(signed, encryptOptions, function(err, encrypted) {
if (err) return callback(err);
encrypted = '<saml:EncryptedAssertion xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion">' + encrypted + '</saml:EncryptedAssertion>';
callback(null, utils.removeWhitespace(encrypted));
});
};