-
Notifications
You must be signed in to change notification settings - Fork 118
Expand file tree
/
Copy pathsamlp.js
More file actions
296 lines (247 loc) · 10.5 KB
/
samlp.js
File metadata and controls
296 lines (247 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
290
291
292
293
294
295
296
var saml20 = require('saml').Saml20;
var SignedXml = require('xml-crypto').SignedXml;
var xpath = require('xpath');
var xtend = require('xtend');
var utils = require('./utils');
var templates = require('./templates');
var encoders = require('./encoders');
var PassportProfileMapper = require('./claims/PassportProfileMapper');
var constants = require('./constants');
function buildSamlResponse(options) {
var SAMLResponse = templates.samlresponse({
id: '_' + utils.generateUniqueID(),
instant: utils.generateInstant(),
destination: options.destination || options.audience,
inResponseTo: options.inResponseTo,
issuer: options.issuer,
samlStatusCode: options.samlStatusCode,
samlStatusMessage: options.samlStatusMessage,
assertion: options.samlAssertion || ''
});
if (options.signResponse) {
options.signatureNamespacePrefix = typeof options.signatureNamespacePrefix === 'string' ? options.signatureNamespacePrefix : '';
var cannonicalized = SAMLResponse
.replace(/\r\n/g, '')
.replace(/\n/g, '')
.replace(/>(\s*)</g, '><') //unindent
.trim();
var sig = new SignedXml(null, {
signatureAlgorithm: constants.ALGORITHMS.SIGNATURE[options.signatureAlgorithm]
});
sig.addReference(
constants.ELEMENTS.RESPONSE.SIGNATURE_LOCATION_PATH,
["http://www.w3.org/2000/09/xmldsig#enveloped-signature", "http://www.w3.org/2001/10/xml-exc-c14n#"],
constants.ALGORITHMS.DIGEST[options.digestAlgorithm]);
sig.signingKey = options.key;
var pem = encoders.removeHeaders(options.cert);
sig.keyInfoProvider = {
getKeyInfo: function (key, prefix) {
prefix = prefix ? prefix + ':' : prefix;
return "<" + prefix + "X509Data><" + prefix + "X509Certificate>" + pem + "</" + prefix + "X509Certificate></" + prefix + "X509Data>";
}
};
sig.computeSignature(cannonicalized, { prefix: options.signatureNamespacePrefix, location: { action: 'after', reference: "//*[local-name(.)='Issuer']" } });
SAMLResponse = sig.getSignedXml();
}
return SAMLResponse;
}
function nameIdentiferNotFoundErrorMessage(options) {
var baseMessage = 'No attribute was found to generate the nameIdentifier. We tried with: ';
var probes = Array.isArray(options.nameIdentifierProbes) ? options.nameIdentifierProbes.join(', ') : '';
return baseMessage + probes;
}
function makeSamlConfig(opts) {
return Object.assign(
{
profileMapper: PassportProfileMapper,
},
opts,
{
signAssertion: typeof opts.signAssertion !== 'boolean' || opts.signAssertion,
signatureNamespacePrefix: typeof opts.signatureNamespacePrefix === 'string' ? opts.signatureNamespacePrefix : ''
}
);
}
function getSamlResponse(samlConfig, user, callback) {
var options = makeSamlConfig(samlConfig);
var profileMap = options.profileMapper(user);
var claims = profileMap.getClaims(options);
var ni = profileMap.getNameIdentifier(options);
if (!ni || !ni.nameIdentifier) {
var error = new Error(nameIdentiferNotFoundErrorMessage(options));
error.context = { user: user };
return callback(error);
}
var createAssertion = options.signAssertion ? saml20.create : saml20.createUnsignedAssertion;
createAssertion.call(saml20, {
signatureAlgorithm: options.signatureAlgorithm,
digestAlgorithm: options.digestAlgorithm,
cert: options.cert,
key: options.key,
issuer: options.issuer,
lifetimeInSeconds: options.lifetimeInSeconds || 3600,
audiences: options.audience,
attributes: claims,
nameIdentifier: ni.nameIdentifier,
nameIdentifierFormat: ni.nameIdentifierFormat || options.nameIdentifierFormat,
recipient: options.recipient,
inResponseTo: options.inResponseTo,
authnContextClassRef: options.authnContextClassRef,
encryptionPublicKey: options.encryptionPublicKey,
encryptionCert: options.encryptionCert,
sessionIndex: options.sessionIndex,
typedAttributes: options.typedAttributes,
includeAttributeNameFormat: options.includeAttributeNameFormat,
signatureNamespacePrefix: options.signatureNamespacePrefix
}, function (err, samlAssertion) {
if (err) return callback(err);
var SAMLResponse;
try {
SAMLResponse = buildSamlResponse(Object.assign({}, options, {
samlAssertion: samlAssertion,
samlStatusCode: options.samlStatusCode || constants.STATUS.SUCCESS
}));
} catch (err) {
return callback(err);
}
callback(null, SAMLResponse);
});
}
/**
* SAML Protocol middleware.
*
* This middleware creates a SAML endpoint based on the user logged in identity.
*
* options:
* - profileMapper(profile) a ProfileMapper implementation to convert a user profile to claims (PassportProfile).
* - getUserFromRequest(req) a function that given a request returns the user. By default req.user
* - issuer string
* - cert the public certificate
* - key the private certificate to sign all tokens
* - postUrl function (SAMLRequest, request, callback)
* - responseHandler(SAMLResponse, options, request, response, next) a function that handles the response. Defaults to HTML POST to postUrl.
*
* @param {[type]} options [description]
* @return {[type]} [description]
*/
module.exports.auth = function (options) {
options.getUserFromRequest = options.getUserFromRequest || function (req) { return req.user; };
options.signatureAlgorithm = options.signatureAlgorithm || 'rsa-sha256';
options.digestAlgorithm = options.digestAlgorithm || 'sha256';
if (typeof options.getPostURL !== 'function') {
throw new Error('getPostURL is required');
}
return function (req, res, next) {
var opts = xtend({}, options || {}); // clone options
if (req.method === 'GET' && req.query.Signature) {
opts.signature = req.query.Signature;
opts.sigAlg = req.query.SigAlg;
opts.relayState = opts.RelayState || req.query.RelayState;
}
function execute(postUrl, audience, req, res, next) {
var user = opts.getUserFromRequest(req);
if (!user) {
const err = new Error('SAML unauthorized');
err.status = 401;
return next(err);
}
opts.audience = audience;
opts.postUrl = postUrl;
getSamlResponse(opts, user, function (err, SAMLResponse) {
if (err) return next(err);
var response = new Buffer(SAMLResponse);
if (opts.responseHandler) {
opts.responseHandler(response, opts, req, res, next);
} else {
res.set('Content-Type', 'text/html');
res.send(templates.form({
type: 'SAMLResponse',
callback: postUrl,
RelayState: opts.RelayState || (req.query || {}).RelayState || (req.body || {}).RelayState || '',
token: response.toString('base64')
}));
}
});
}
utils.parseSamlRequest(req, (req.query || {}).SAMLRequest || (req.body || {}).SAMLRequest, "AUTHN_REQUEST", opts, function (err, samlRequestDom) {
if (err) return next(err);
var audience = opts.audience;
if (samlRequestDom) {
if (!audience) {
var issuer = xpath.select("//*[local-name(.)='Issuer' and namespace-uri(.)='urn:oasis:names:tc:SAML:2.0:assertion']/text()", samlRequestDom);
if (issuer && issuer.length > 0)
audience = issuer[0].textContent;
}
var id = samlRequestDom.documentElement.getAttribute('ID');
if (id) opts.inResponseTo = opts.inResponseTo || id;
}
opts.getPostURL(audience, samlRequestDom, req, function (err, postUrl) {
if (err) { return next(err); }
if (!postUrl) {
const error = new Error('SAML unauthorized error, postUrl not received');
error.status = 401;
return next(error);
}
execute(postUrl, audience, req, res, next);
});
});
};
};
module.exports.parseRequest = function (req, options, callback) {
if (typeof options === 'function') {
callback = options;
options = {};
}
var samlRequest = (req.query || {}).SAMLRequest || (req.body || {}).SAMLRequest;
if (!samlRequest)
return callback();
utils.parseSamlRequest(req, samlRequest, "AUTHN_REQUEST", options, function (err, samlRequestDom) {
if (err) {
return callback(err);
}
var data = {};
var issuer = xpath.select("//*[local-name(.)='Issuer' and namespace-uri(.)='urn:oasis:names:tc:SAML:2.0:assertion']/text()", samlRequestDom);
if (issuer && issuer.length > 0) data.issuer = issuer[0].textContent;
var subject = xpath.select("//*[local-name(.)='Subject' and namespace-uri(.)='urn:oasis:names:tc:SAML:2.0:assertion']/*[local-name(.)='NameID']", samlRequestDom);
if (subject && subject.length > 0) data.subject = subject[0].textContent;
var assertionConsumerUrl = samlRequestDom.documentElement.getAttribute('AssertionConsumerServiceURL');
if (assertionConsumerUrl) data.assertionConsumerServiceURL = assertionConsumerUrl;
var destination = samlRequestDom.documentElement.getAttribute('Destination');
if (destination) data.destination = destination;
var forceAuthn = samlRequestDom.documentElement.getAttribute('ForceAuthn');
if (forceAuthn) data.forceAuthn = forceAuthn;
var id = samlRequestDom.documentElement.getAttribute('ID');
if (id) data.id = id;
var requestedAuthnContextClassRefElements = xpath.select(constants.ELEMENTS.AUTHN_REQUEST.AUTHN_CONTEXT_CLASS_REF_PATH, samlRequestDom)
if (requestedAuthnContextClassRefElements && requestedAuthnContextClassRefElements.length === 1) {
data.requestedAuthnContext = {};
data.requestedAuthnContext.authnContextClassRef = requestedAuthnContextClassRefElements[0].textContent;
}
callback(null, data);
});
};
module.exports.getSamlResponse = getSamlResponse;
module.exports.sendError = function (options) {
// https://docs.oasis-open.org/security/saml/v2.0/saml-core-2.0-os.pdf
function renderResponse(res, postUrl) {
var error = options.error || {};
options.samlStatusCode = error.code || constants.STATUS.RESPONDER;
options.samlStatusMessage = error.description;
var SAMLResponse = buildSamlResponse(options);
var response = new Buffer(SAMLResponse);
res.set('Content-Type', 'text/html');
res.send(templates.form({
type: 'SAMLResponse',
callback: postUrl,
RelayState: options.RelayState,
token: response.toString('base64')
}));
}
return function (req, res, next) {
options.getPostURL(req, function (err, postUrl) {
if (err) return next(err);
if (!postUrl) return next(new Error('postUrl is required'));
renderResponse(res, postUrl);
});
};
};