-
Notifications
You must be signed in to change notification settings - Fork 117
/
Copy pathlogout.js
381 lines (317 loc) · 15.6 KB
/
logout.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
var templates = require('./templates');
var xpath = require('xpath');
var DOMParser = require('xmldom').DOMParser;
var utils = require('./utils');
var trim_xml = require('./trim_xml');
var signers = require('./signers');
var SessionStore = require('flowstate').SessionStore;
var SessionParticipants = require('./sessionParticipants');
var zlib = require('zlib');
var qs = require('querystring');
var xtend = require('xtend');
var constants = require('./constants');
var BINDINGS = constants.BINDINGS;
var STATUS = constants.STATUS;
// Analyze if we should merge session handler and store
module.exports.logout = function (options) {
options.sessionParticipants = options.sessionParticipants || new SessionParticipants();
options.clearIdPSession = options.clearIdPSession || function (cb){ return cb(); };
options.store = options.store || new SessionStore({ key: '_logoutState'});
function prepareAndSendLogoutRequest(sessionParticipants, transactionId, req, res, next) {
// Finished if there are no more session - finish logout
if (!sessionParticipants.hasElements()) { return finalize(transactionId, req, res, next); }
sessionParticipants.getFirst(function (err, participant) {
// Store the sessionIndex in session so when the logout request comes back we can use that to validate
var logoutRequestState = { transactionId: transactionId, sessionIndex: participant.sessionIndex, issuer: participant.serviceProviderId, nameId: participant.nameId };
options.store.save(req, logoutRequestState, function (err, relayState) {
if (err) return next(err);
// Use session to generate SAML Request
var logoutRequest = templates.logoutrequest({
ID: utils.generateUniqueID(),
IssueInstant: utils.getRoundTripDateFormat(),
Issuer: options.issuer, // IdP identifier
NameID: { value: participant.nameId, Format: participant.nameIdFormat },
SessionIndex: participant.sessionIndex,
Destination: participant.serviceProviderLogoutURL
});
options.destination = participant.serviceProviderLogoutURL;
options.relayState = relayState;
// Send logout request
prepareAndSendToken(req, res, 'LOGOUT_REQUEST', logoutRequest, options, next);
});
});
}
function finalize(transactionId, req, res, next) {
options.store.load(req, transactionId, {destroy: true}, function (err, transaction) {
if (err) { return next(err); }
var isPartialLogout = transaction && transaction.global_status === 'failed';
options.clearIdPSession(function (err) {
// If there was an issue cleaning the session, reply with partial logout
if (err) { isPartialLogout = true; }
// No data - It was an IdP initated flow
if (!transaction || !transaction.parsedRequest){
return res.send(200);
}
var data = transaction.parsedRequest;
// Data is the parsedSamlRequest - Reply with this information
var logoutResponse = templates.logoutresponse({
id: '_' + utils.generateUniqueID(),
instant: utils.generateInstant(),
inResponseTo: data.id,
destination: data.serviceProviderLogoutURL || options.destination, // Destination taken from session (matches issuer from the LogoutRequest with session serviceProviderId)
issuer: options.issuer, // IdP is the Issuer for this LogoutResponse
samlStatusCode: isPartialLogout ? STATUS.PARTIAL_LOGOUT : STATUS.SUCCESS,
samlStatusMessage: options.samlStatusMessage,
});
// Update reference to include signature
options.reference = constants.ELEMENTS.LOGOUT_RESPONSE.SIGNATURE_LOCATION_PATH;
options.destination = data.serviceProviderLogoutURL || options.destination;
// We stored the relay state of the initial request
options.relayState = transaction.relayState;
prepareAndSendToken(req, res, 'LOGOUT_RESPONSE', logoutResponse, options, next);
});
});
}
function validateSamlResponse(req, sessionParticipant, cb) {
var SAMLResponse = req.query.SAMLResponse || req.body.SAMLResponse;
function parseAndValidate(err, buffer) {
if (err) { return cb(err); }
var xml = new DOMParser().parseFromString(buffer.toString());
var parsedResponse = {};
// status code
var statusCodes = xml.getElementsByTagNameNS('urn:oasis:names:tc:SAML:2.0:protocol', 'StatusCode');
var statusCodeXml = statusCodes[0];
if (statusCodeXml) {
parsedResponse.status = statusCodeXml.getAttribute('Value');
// status sub code
var statusSubCodeXml = statusCodes[1];
if (statusSubCodeXml) {
parsedResponse.subCode = statusSubCodeXml.getAttribute('Value');
}
}
// status message
var samlStatusMsgXml = xml.getElementsByTagNameNS('urn:oasis:names:tc:SAML:2.0:protocol', 'StatusMessage')[0];
if (samlStatusMsgXml) {
parsedResponse.message = samlStatusMsgXml.textContent;
}
// status detail
var samlStatusDetailXml = xml.getElementsByTagNameNS('urn:oasis:names:tc:SAML:2.0:protocol', 'StatusDetail')[0];
if (samlStatusDetailXml) {
parsedResponse.detail = samlStatusDetailXml.textContent;
}
// Issuer
var issuer = xml.getElementsByTagNameNS('urn:oasis:names:tc:SAML:2.0:assertion', 'Issuer')[0];
if (issuer) {
parsedResponse.issuer = issuer.textContent;
}
req.parsedSAMLResponse = parsedResponse;
if (!sessionParticipant.cert) {
// If there's no certificate to check the signature, let it pass
return cb(null, parsedResponse);
}
// validate signature
try {
var validationOptions = xtend({signingCert: sessionParticipant.cert}, options);
utils.validateSignature(req, 'LOGOUT_RESPONSE', xml, validationOptions);
} catch (e) {
return cb(e);
}
cb(null, parsedResponse);
}
if (req.body.SAMLResponse || !options.deflate) {
// HTTP-POST or HTTP-Redirect without deflate encoding
return parseAndValidate(null, new Buffer(SAMLResponse, 'base64'));
}
// Default: HTTP-Redirect with deflate encoding
zlib.inflateRaw(new Buffer(SAMLResponse, 'base64'), parseAndValidate);
}
return function (req, res, next) {
try {
// SP Initated flow.
if (req.query.SAMLRequest || req.body.SAMLRequest) {
var opts = {
getCredentials: function getCredentials(issuer, sessionIndex, nameId, cb) {
options.sessionParticipants.get(issuer, sessionIndex, nameId, function (err, session) {
if (err) { return cb(err); }
if (!session) { return cb(new Error('Invalid Session Participant')) };
if (!session.cert) { return cb(); };
return cb(null, {
cert: session.cert,
thumbprint: session.thumbprint
});
});
}
};
parseIncomingLogoutRequest(req, req.query.SAMLRequest || req.body.SAMLRequest, opts, function (err, requestData) {
if (err) { return next(err); }
if (!requestData.issuer) {
return next(new Error('SAML Request with no issuer. Issuer is a mandatory element.'));
}
options.sessionParticipants.get(requestData.issuer, requestData.sessionIndex, requestData.nameId, function (err, session) {
if (err) { return next(err); }
if (!session && !options.destination) { return next(new Error('Invalid Session Participant')); }
// We should store who requested the logout, so we can reply back with LogoutResponse
var spData = {
parsedRequest: {
id: requestData.id,
serviceProviderLogoutURL: (session|| {}).serviceProviderLogoutURL || options.destination
},
relayState: req.query.RelayState || (req.body && req.body.RelayState)
};
options.store.save(req, spData, function (err, transactionId) {
if (err) { return next(err); }
// We remove the session from the LogoutRequest Originator.
// This session is already saved in the store.
// We should not send a LogoutRequest to that session
// Only a LogoutResponse when there are no other session participants active
options.sessionParticipants.remove(requestData.issuer, requestData.sessionIndex, requestData.nameId, function (err) {
if (err) { return next(err); }
prepareAndSendLogoutRequest(options.sessionParticipants, transactionId, req, res, next);
});
});
});
});
// Logout flow in progress, incoming SAMLResponse from SP. (Could be SP initiated or IdP initiated)
} else if (req.query.SAMLResponse || req.body.SAMLResponse) {
function process(state, transactionId) {
// LogoutResponse was OK, we remove the session participant from the IdP
options.sessionParticipants.remove(state.issuer, state.sessionIndex, state.nameId, function (err) {
if(err) return next(err);
// Continue with next session if any
prepareAndSendLogoutRequest(options.sessionParticipants, transactionId, req, res, next);
});
}
// Verify that the state sent to the SP matches the one returned
var h = req.query.RelayState || (req.body && req.body.RelayState);
options.store.load(req, h, {destroy: true}, function (err, state) {
if (err) { return next(err); }
if (!state) { return next(new Error('Invalid RelayState')); }
options.sessionParticipants.get(state.issuer, state.sessionIndex, state.nameId, function (err, sessionParticipant) {
if (err) { return next(err); }
if (!sessionParticipant) { return next(new Error('Invalid Session Participant')) };
// If there are sessions left, keep sending LogoutRequest to Session Participants. If not finish
validateSamlResponse(req, sessionParticipant, function (err, logoutResponse) {
if (err) { return next(err); }
var transactionId = state.transactionId;
if (logoutResponse.status === STATUS.SUCCESS) {
return process(state, transactionId);
}
// Mark global status as partial logout if a logout does not succeed
options.store.load(req, transactionId, function (err, globalState) {
globalState.global_status = 'failed';
options.store.update(req, transactionId, globalState, function (err) {
if (err) { return next(err); }
// TODO: Review - because we need to remove the session that replied, but send the response to the originator
process(state, transactionId);
});
});
});
});
});
// IdP initated - Start flow - In this case we will show a 200 when complete
} else {
options.store.save(req, {}, function (err, transactionId) {
prepareAndSendLogoutRequest(options.sessionParticipants, transactionId, req, res, next);
});
}
} catch (e) {
return next(e);
}
};
};
/**
* Parse the SP initiated Logout Request.
* This Logout Request is incoming from the SAML SP into the SAML IdP.
* @returns {Object} The Logout Request data as a JSON Object
*/
function parseIncomingLogoutRequest(req, samlRequest, options, callback) {
var type = "LOGOUT_REQUEST";
utils.parseSamlRequest(req, samlRequest, type, options, function (err, logoutRequestDom) {
if (err) { return callback(err); }
var data = {};
var issuer = xpath.select(constants.ELEMENTS[type].ISSUER_PATH, logoutRequestDom);
if (issuer && issuer.length > 0) { data.issuer = issuer[0].textContent; }
var sessionIndex = xpath.select("//*[local-name(.)='SessionIndex']/text()", logoutRequestDom);
if (sessionIndex && sessionIndex.length > 0) { data.sessionIndex = sessionIndex[0].textContent; }
var nameId = xpath.select("//*[local-name(.)='NameID']", logoutRequestDom);
if (nameId && nameId.length > 0) {
data.nameId = nameId[0].textContent;
data.nameIdFormat = nameId[0].getAttribute('Format');
}
var destination = logoutRequestDom.documentElement.getAttribute('Destination');
if (destination) { data.destination = destination; }
var id = logoutRequestDom.documentElement.getAttribute('ID');
if (id) data.id = id;
var signature = xpath.select(options.signaturePath || constants.ELEMENTS[type].SIGNATURE_VALIDATION_PATH, logoutRequestDom);
if (signature && signature.length > 0) { data.signature = signature[0].textContent; }
callback(null, data);
});
}
function prepareAndSendToken(req, res, element_type, token, options, cb) {
var type = constants.ELEMENTS[element_type].PROP;
var send = function (params) {
if (options.protocolBinding !== BINDINGS.HTTP_REDIRECT) {
// HTTP-POST
res.set('Content-Type', 'text/html');
return res.send(templates.form({
type: type,
callback: options.destination,
RelayState: params.RelayState,
token: params[type]
}));
}
// HTTP-Redirect
var samlResponseUrl = utils.appendQueryString(options.destination, params);
res.redirect(samlResponseUrl);
};
var params = {};
params[type] = null;
params.RelayState = options.relayState || '';
// canonical request
token = trim_xml(token);
if (options.protocolBinding !== BINDINGS.HTTP_REDIRECT || !options.deflate) {
// HTTP-POST or HTTP-Redirect without deflate encoding
try {
token = signers.signXml(options, token);
} catch (err) {
return cb(err);
}
params[type] = new Buffer(token).toString('base64');
return send(params);
}
// Default: HTTP-Redirect with deflate encoding (http://docs.oasis-open.org/security/saml/v2.0/saml-bindings-2.0-os.pdf - section 3.4.4.1)
zlib.deflateRaw(new Buffer(token), function (err, buffer) {
if (err) return cb(err);
params[type] = buffer.toString('base64');
// construct the Signature: a string consisting of the concatenation of the SAMLResponse,
// RelayState (if present) and SigAlg query string parameters (each one URLencoded)
if (params.RelayState === '') {
// if there is no RelayState value, the parameter should be omitted from the signature computation
delete params.RelayState;
}
params.SigAlg = signers.getSigAlg(options);
params.Signature = signers.sign(options, qs.stringify(params));
send(params);
});
}
module.exports.sendLogoutError = function(options){
return function(req, res, next){
if (!options.destination) {
return next(new Error('Destination not specified'));
}
var error = options.error || {};
var logoutResponse = templates.logoutresponse({
id: '_' + utils.generateUniqueID(),
instant: utils.generateInstant(),
inResponseTo: options.inResponseTo,
destination: options.destination,
issuer: options.issuer,
samlStatusCode: error.code || STATUS.RESPONDER,
samlStatusMessage: error.description
});
// Signature location
options.reference = constants.ELEMENTS.LOGOUT_RESPONSE.SIGNATURE_LOCATION_PATH;
options.relayState = options.relayState || req.query.RelayState || (req.body || {}).RelayState;
return prepareAndSendToken(req, res, 'LOGOUT_RESPONSE', logoutResponse, options, next);
};
};