-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathsaml_sp.js
1375 lines (1179 loc) · 52.9 KB
/
saml_sp.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
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* JavaScript functions for providing SAML SP with NGINX Plus
*
* Copyright (C) 2023 Nginx, Inc.
*/
export default {
handleSingleSignOn, // Process SAML Response form IdP
handleSingleLogout, // Process SAML LogoutRequest and LogoutResponse from IdP
handleAllMessages, // Process all SAML messages from IdP
initiateSingleSignOn, // Initiate SAML SSO by redirecting to IdP
initiateSingleLogout // Initiate SAML SLO by redirecting to IdP
};
const xml = require("xml");
const zlib = require("zlib");
const querystring = require("querystring");
const fs = require("fs");
const initiateSingleSignOn = produceSAMLMessage.bind(null, "AuthnRequest");
const initiateSingleLogout = produceSAMLMessage.bind(null, "LogoutRequest");
const handleSingleSignOn = handleSAMLMessage.bind(null, ["Response"]);
const handleSingleLogout = handleSAMLMessage.bind(null, ["LogoutRequest", "LogoutResponse"]);
const handleAllMessages = handleSAMLMessage.bind(null, ["Response", "LogoutRequest", "LogoutResponse"]);
/**
* Processing incoming SAML messages (Response, LogoutResponse, LogoutRequest).
* @param {Array} messageType - Array of expected SAML message types.
* @param {object} r - The request object.
*/
async function handleSAMLMessage(messageType, r) {
let id;
try {
let nameID, node;
/* Extract SAML parameters from the HTTP request */
const params = extractSAMLParameters(r);
/* Parse the SAML message for an XML document */
let root = xml.parse(params.SAMLResponse).$root;
/* Check the message type and validate the configuration */
messageType = checkSAMLMessageType(root, messageType);
const opt = parseConfigurationOptions(r, messageType);
/* Process the message header and verify the issuer */
id = processSAMLMessageHeader(r, opt, root);
checkIssuer(root.Issuer, opt.idpEntityID);
/* Verify the SAML signature if required */
opt.wantSignedResponse && await verifySAMLSignature(root, opt.verifyKeys);
/* Check for SAML replay attacks */
checkReplayAttack(r, id, messageType);
/* Handle different SAML message types */
switch (messageType) {
case 'Response':
/* Verify the SAML Response status */
verifyResponseStatus(root.Status);
/* Decrypt the Encrypted Assertion if present */
if (root.EncryptedAssertion) {
root = await decryptSAML(root.EncryptedAssertion, opt.decryptKey);
}
/* Process the Assertion header and verify the issuer */
opt.assertionId = processSAMLMessageHeader(r, opt, root.Assertion);
checkIssuer(root.Assertion.Issuer, opt.idpEntityID);
/* Verify the SAML Assertion signature if required */
opt.wantSignedAssertion && await verifySAMLSignature(root.Assertion, opt.verifyKeys);
/* Exctract NameID, NameIDFormat and check the SubjectConfirmation if present */
node = root.Assertion.Subject.NameID ? root.Assertion.Subject.NameID
: root.Assertion.Subject.EncryptedID || null;
nameID = await extractNameID(node, opt.decryptKey);
checkSubjectConfirmation(root.Assertion.Subject.SubjectConfirmation,
opt.allowedClockSkew);
/* Parse the Asserttion Conditions and Authentication Statement */
checkConditions(root.Assertion.Conditions, opt.spEntityID, opt.allowedClockSkew);
const authnStatement = parseAuthnStatement(root.Assertion.AuthnStatement, null,
opt.allowedClockSkew);
/* Set session cookie and save SAML variables and attributes */
const sessionCookie = setSessionCookie(r);
saveSAMLVariables(r, nameID, authnStatement);
saveSAMLAttributes(r, root.Assertion.AttributeStatement);
/* Redirect the user after successful login */
postLoginRedirect(r, params.RelayState || opt.relayState);
r.variables.saml_access_granted = '1';
r.log("SAML SP success, creating session " + sessionCookie);
return;
case 'LogoutRequest':
/* Exctract NameID and NameIDFormat */
node = root.NameID ? root.NameID : root.EncryptedID || null;
nameID = await extractNameID(node, opt.decryptKey);
/* Define necessary parameters needed to create a SAML LogoutResponse */
opt.nameID = nameID[0];
opt.inResponseTo = id;
opt.relayState = params.RelayState;
/* Rewrite the LogoutResponse URL if configured */
opt.idpServiceURL = opt.logoutResponseURL || opt.idpServiceURL;
/* Issue a SAML LogoutResponse */
await produceSAMLMessage('LogoutResponse', r, opt);
return;
case 'LogoutResponse':
/* Verify the SAML LogoutResponse status */
verifyResponseStatus(root.Status);
/* Clear the session cookie and redirect the user */
clearSession(r);
postLogoutRedirect(r, params.RelayState);
return;
}
} catch (e) {
samlError(r, 500, id, e);
}
}
function samlError(r, http_code, id, e) {
let msg = r.variables.saml_debug ? e.stack : "ReferenceError: " + e.message;
r.error(`SAML SSO Error: ReferenceID: ${id} ${msg}`);
r.variables.internal_error_message += `ReferenceID: ${id}`;
r.variables.internal_error_details = msg;
r.return(http_code);
}
/**
* Processes the SAML message header, validating the required fields and checking optional
* fields, such as Destination, according to the SAML 2.0 Core specification:
* https://docs.oasis-open.org/security/saml/v2.0/saml-core-2.0-os.pdf
*
* - ID attribute (Required, see section 1.3.4): A unique identifier for the SAML message.
* - InResponseTo attribute (Optional, see section 3.2.2 for SSO and 3.7.3.1 for SLO):
* Indicates that the SAML message is a response to a previous request.
* - IssueInstant attribute (Required, see section 1.3.4): The timestamp when the SAML message
* was issued.
* - Destination attribute (Optional, see section 3.2.2 for SSO and 3.7.3.1 for SLO):
* The intended recipient of the SAML message.
*
* @param {Object} r - The incoming request object.
* @param {Object} opt - An object containing the SP options, including the SP Service URL.
* @param {Object} root - The SAML root element containing the message header.
* @returns {string} - The SAML message ID attribute.
* @throws {Error} - If the SAML message header contains invalid or unsupported values.
*/
function processSAMLMessageHeader(r, opt, root) {
const type = root.$name;
/* Check XML namespace for SAML message (Required) */
const expectedNs = type === 'Assertion'
? 'urn:oasis:names:tc:SAML:2.0:assertion'
: 'urn:oasis:names:tc:SAML:2.0:protocol';
if (root.$ns !== expectedNs) {
throw Error(`Unsupported XML namespace: "${root.$ns}" for ${type}`);
}
/* Check SAML message version (Required) */
if (root.$attr$Version !== "2.0") {
throw Error (`Unsupported SAML Version: "${root.$attr$Version}"`);
}
/* Check the date and time when the SAML message was issued (Required) */
const issueInstant = root.$attr$IssueInstant;
if (!issueInstant) {
throw Error("IssueInstant attribute is missing in the SAML message");
}
const issueInstantDate = new Date(issueInstant);
checkTimeValidity(issueInstantDate, null, opt.allowedClockSkew);
/* Check SAML message ID (Required) */
const id = root.$attr$ID;
if (!id) {
throw Error (`ID attribute is missing in the ${type} element`);
}
const inResponseTo = root.$attr$InResponseTo;
if (inResponseTo) {
/* SP-initiated SSO or SLO */
r.variables.saml_request_id = inResponseTo;
if (r.variables.saml_request_redeemed != '1') {
throw Error (`InResponseTo attribute value "${inResponseTo}" ` +
`not found in key-value storage for ${type} message`);
}
}
/* Check Destination if present (Optional) */
const destination = root.$attr$Destination;
if (destination && destination !== opt.spServiceURL) {
throw Error (`The SAML Destination "${destination}" does not match ` +
`SP ACS URL "${opt.spServiceURL}"`);
}
return id;
}
/**
* Checks the Issuer element in the SAML message according to the SAML 2.0 Core specification:
* https://docs.oasis-open.org/security/saml/v2.0/saml-core-2.0-os.pdf
*
* The Issuer element (section 2.2.5) contains the SAML authority's unique identifier.
* This function checks if the issuer in the SAML message matches the expected IdP EntityID.
*
* @param {Object} root - The SAML Issuer element.
* @param {string} idpEntityId - The expected IdP EntityID.
* @throws {Error} - If the Issuer in the SAML message does not match the expected IdP EntityID.
*/
function checkIssuer(root, idpEntityId) {
const issuer = root.$text;
if (issuer && issuer !== idpEntityId) {
throw Error (`Issuer "${issuer}" does not match IdP EntityID "${idpEntityId}"`);
}
}
/**
* Verifies the SAML response status.
*
* According to SAML 2.0 Core specification (section 3.2.2.2):
* https://docs.oasis-open.org/security/saml/v2.0/saml-core-2.0-os.pdf
* The <StatusCode> element contains the primary status code indicating the
* success or failure of the corresponding request. The <StatusMessage> and
* <StatusDetail> elements provide additional information.
*
* @param {Object} root - A SAML status XMLDoc object returned by xml.parse().
* @throws {Error} - If the SAML status is not "Success".
*/
function verifyResponseStatus (root) {
if (!root) {
throw Error("The Status element is missing in the SAML response");
}
if (!root.StatusCode || !root.StatusCode.$attr$Value) {
throw Error("The StatusCode element is missing in the Status");
}
const statusCode = root.StatusCode.$attr$Value;
const success = "urn:oasis:names:tc:SAML:2.0:status:Success";
if (statusCode !== success) {
let message = "StatusCode: " + statusCode;
if (root.statusMessage) {
message += ", SatusMessage: " + root.statusMessage.$text;
}
if (root.statusDetail) {
message += ", StatusDetail: " + JSON.stringify(root.statusDetail);
}
throw Error(message);
}
}
/**
* Extracts the NameID value and format from the given SAML root element, optionally
* decrypting it if it's encrypted.
*
* @param {Object} root - The SAML root element containing the NameID or EncryptedID.
* @param {string} keyData - The private key to decrypt the EncryptedID, if present.
* @returns {Promise<[string, string]>} - A promise that resolves to a tuple containing the
* NameID value and format.
* @throws {Error} - If the NameID element is missing in the Subject.
*/
async function extractNameID(root, keyData) {
if (!root) {
throw Error("NameID element is missing in the Subject");
}
const isEncrypted = root.$name === 'EncryptedID';
if (isEncrypted) {
root = (await decryptSAML(root, keyData)).NameID;
}
return [root.$text, root.$attr$Format];
}
/**
* Checks the SubjectConfirmation element in the SAML response.
*
* According to SAML 2.0 Core specification (section 2.4.1.1 and 2.4.1.2):
* https://docs.oasis-open.org/security/saml/v2.0/saml-core-2.0-os.pdf
* The <SubjectConfirmation> element is used to provide additional
* information required to confirm the subject. The most common method is
* "urn:oasis:names:tc:SAML:2.0:cm:bearer".
*
* @param {Object} root - A SAML SubjectConfirmation XMLDoc object returned by xml.parse().
* @param {number} [allowedClockSkew] - The allowed clock skew in seconds.
* @throws {Error} - If the SubjectConfirmationData is missing or the subject has expired.
*/
function checkSubjectConfirmation(root, allowedClockSkew) {
if (!root) {
return;
}
if (root.$attr$Method === "urn:oasis:names:tc:SAML:2.0:cm:bearer") {
root = root.SubjectConfirmationData;
if (!root) {
throw new Error('SubjectConfirmationData element is missing in the ' +
'SubjectConfirmation');
}
const notOnOrAfter = root.$attr$NotOnOrAfter ? new Date(root.$attr$NotOnOrAfter) : null;
checkTimeValidity(null, notOnOrAfter, allowedClockSkew);
}
}
/**
* Checks the Conditions element in the SAML Assertion.
*
* According to SAML 2.0 Core specification (section 2.5.1.1):
* https://docs.oasis-open.org/security/saml/v2.0/saml-core-2.0-os.pdf
* The <Conditions> element is used to specify conditions that must be evaluated
* when assessing the validity of and/or evaluating an assertion.
*
* @param {Object} root - A SAML Conditions XMLDoc object returned by xml.parse().
* @param {string} spEntityId - The EntityID of the Service Provider (SP).
* @param {number} [allowedClockSkew] - The allowed clock skew in seconds.
* @throws {Error} - If Conditions element is missing or the assertion is not valid or expired.
* Also throws an error if the audience restriction is not satisfied.
*/
function checkConditions(root, spEntityId, allowedClockSkew) {
if (!root) {
throw Error("Conditions element is missing in the Assertion");
}
const notBefore = root.$attr$NotBefore ? new Date(root.$attr$NotBefore) : null;
const notOnOrAfter = root.$attr$NotOnOrAfter ? new Date(root.$attr$NotOnOrAfter) : null;
checkTimeValidity(notBefore, notOnOrAfter, allowedClockSkew);
/* Check the audience restriction */
if (root.AudienceRestriction && root.AudienceRestriction.Audience) {
let audience = root.AudienceRestriction.Audience.$text;
if (!Array.isArray(audience)) {
audience = [audience];
}
const spFound = audience.indexOf(spEntityId) !== -1;
if (!spFound) {
throw Error("The Assertion is not intended for this Service Provider. " +
`Expected audience: ${spEntityId}, received: ${audience}`);
}
}
}
/**
* Parses the AuthnStatement element in the SAML Assertion.
*
* According to SAML 2.0 Core specification (section 2.7.2):
* https://docs.oasis-open.org/security/saml/v2.0/saml-core-2.0-os.pdf
* The <AuthnStatement> element describes the act of authentication performed
* on the principal by the identity provider (IdP).
*
* @param {Object} root - A SAML AuthnStatement XMLDoc object returned by xml.parse().
* @param {number} [maxAuthenticationAge] - The maximum age (in seconds) of the authentication
* statement. If provided, the function will check
* if the AuthnInstant is within the allowed age.
* @param {number} [allowedClockSkew] - The allowed clock skew in seconds.
* @throws {Error} - If AuthnInstant, SessionNotOnOrAfter, or AuthnContext elements are missing,
* invalid, or expired.
* @returns {Object} - An object with SessionIndex and AuthnContextClassRef properties.
*/
function parseAuthnStatement(root, maxAuthenticationAge, allowedClockSkew) {
/* AuthnStatement element is optional */
if (!root) {
return;
}
const authnInstant = root.$attr$AuthnInstant;
if (!authnInstant) {
throw Error("The AuthnInstant attribute is missing in the AuthnStatement");
}
/* Placeholder for future maxAuthenticationAge conf option */
if (maxAuthenticationAge) {
const authnInstantDate = new Date(authnInstant);
const now = new Date();
if (now.getTime() - authnInstantDate.getTime() > maxAuthenticationAge*1000) {
return false;
}
}
const sessionIndex = root.$attr$SessionIndex || null;
const sessionNotOnOrAfter = root.$attr$SessionNotOnOrAfter ?
new Date(root.$attr$SessionNotOnOrAfter) : null;
checkTimeValidity(null, sessionNotOnOrAfter, allowedClockSkew);
root = root.AuthnContext;
if (!root) {
throw Error('The AuthnContext element is missing in the AuthnStatement');
}
if (!root.AuthnContextClassRef) {
throw Error('The AuthnContextClassRef element is missing in the AuthnContext');
}
const authnContextClassRef = root.AuthnContextClassRef.$text;
return [sessionIndex, authnContextClassRef];
}
/**
* Checks if the current time is within the allowed time range specified by
* notBefore and notOnOrAfter.
*
* @param {Date} notBefore - The notBefore time.
* @param {Date} notOnOrAfter - The notOnOrAfter time.
* @param {number} [allowedClockSkew] - Allowed clock skew in seconds.
* @throws {Error} - If the current time is outside the allowed time range.
*/
function checkTimeValidity(notBefore, notOnOrAfter, allowedClockSkew) {
const now = new Date();
if (notBefore && notBefore > new Date(now.getTime() + allowedClockSkew * 1000)) {
throw Error(`The Assertion is not yet valid. Current time is ${now} ` +
`and NotBefore is ${notBefore}. ` +
`Allowed clock skew is ${allowedClockSkew} seconds.`);
}
if (notOnOrAfter && notOnOrAfter < new Date(now.getTime() - allowedClockSkew * 1000)) {
throw Error(`The Assertion has expired. Current time is ${now} ` +
`and NotOnOrAfter is ${notOnOrAfter}. ` +
`Allowed clock skew is ${allowedClockSkew} seconds.`);
}
}
function saveSAMLVariables(r, nameID, authnStatement) {
r.variables.saml_name_id = nameID[0];
r.variables.saml_name_id_format = nameID[1];
if (authnStatement) {
if (authnStatement[0]) {
try {
r.variables.saml_session_index = authnStatement[0];
} catch(e) {}
}
try {
r.variables.saml_authn_context_class_ref = authnStatement[1];
} catch(e) {}
}
}
/**
* Extracts attributes from a SAML attribute statement and returns them as an object.
*
* @param {Object} root - A SAML attribute statement XMLDoc object returned by xml.parse().
* @returns {Object} - An object containing the attributes, with the attribute names as keys and
* attribute values as arrays of values.
*/
function getAttributes(root) {
return root.reduce((a, v) => {
a[v.$attr$Name] = v.$tags$AttributeValue.reduce((a, v) => {
a.push(v.$text);
return a;
}, []);
return a;
}, {});
}
function saveSAMLAttributes(r, root) {
if (!root) {
return;
}
let attrs = getAttributes(root.$tags$Attribute);
for (var attributeName in attrs) {
if (attrs.hasOwnProperty(attributeName)) {
var attributeValue = attrs[attributeName];
/* If the attribute name is a URI, take only the last part after the last "/" */
if (attributeName.includes("http://") || attributeName.includes("https://")) {
attributeName = attributeName.substring(attributeName.lastIndexOf('/')+1);
}
/* Save attributeName and value to the key-value store */
try {
r.variables['saml_attrib_' + attributeName] = attributeValue;
} catch(e) {}
}
}
}
function extractSAMLParameters(r) {
try {
const payload = getPayload(r);
if (!payload) {
throw Error("Unsupported HTTP method");
}
return parsePayload(payload, r.method);
} catch (e) {
throw Error(`Failed to extract SAMLRequest or SAMLResponse parameter ` +
`from the ${r.method} request: ${e.message}`);
}
}
function getPayload(r) {
switch (r.method) {
case 'GET':
return r.variables.arg_SAMLResponse || r.variables.arg_SAMLRequest ? r.variables.args
: null;
case 'POST':
return r.headersIn['Content-Type'] === 'application/x-www-form-urlencoded'
&& r.requestText.length ? r.requestText : null;
default:
return null;
}
}
function parsePayload(payload, method) {
const params = querystring.parse(payload);
let samlResponse = Buffer.from(decodeURIComponent(params.SAMLResponse || params.SAMLRequest),
'base64');
let relayState = decodeURIComponent(params.RelayState || "")
if (method === "GET") {
samlResponse = zlib.inflateRawSync(samlResponse);
}
return {SAMLResponse: samlResponse, RelayState: relayState};
}
function checkSAMLMessageType(root, messageType) {
const type = root.$name;
if (!messageType.includes(type)) {
throw Error(`Unsupported SAML message type: "${messageType}"`);
}
return type;
}
/**
* Generates a random string ID with a specified length.
*
* @param {number} keyLength - Length of the generated ID. If it's less than 20,
* the default value of 20 will be used.
* @returns {string} - A randomly generated string ID in hexadecimal format.
*/
function generateID(keyLength) {
keyLength = keyLength > 20 ? keyLength : 20;
let buf = Buffer.alloc(keyLength);
return (crypto.getRandomValues(buf)).toString('hex');
}
function setSessionCookie(r) {
/* Generate cookie_auth_token */
const authToken = "_" + generateID();
/* Save cookie_auth_token to keyval to store SAML session data */
r.variables.cookie_auth_token = authToken;
/* Set cookie_auth_token in the cookie */
r.headersOut["Set-Cookie"] = `auth_token=${authToken}; ${r.variables.saml_cookie_flags}`;
return authToken;
}
/**
* Checks for potential replay attacks by verifying if a SAML message ID has already been used.
*
* According to SAML 2.0 Core specification (section 1.3.4):
* https://docs.oasis-open.org/security/saml/v2.0/saml-core-2.0-os.pdf
* Replay attacks can be prevented by ensuring that each SAML message ID is unique and
* is not reused within a reasonable time frame.
*
* @param {Object} r - The request object.
* @param {string} id - The SAML message ID.
* @param {string} type - The SAML message type (e.g., 'Response' or 'LogoutResponse').
* @throws {Error} - If a replay attack is detected (the SAML message ID has already been used).
*/
function checkReplayAttack(r, id, type) {
r.variables.saml_response_id = id;
if (r.variables.saml_response_redeemed === '1') {
throw Error (`An attempt to reuse a ${type} ID was detected: ` +
`ID "${id}" has already been redeemed`);
}
r.variables.saml_response_redeemed = '1';
}
function postLoginRedirect(r, relayState) {
/* If RelayState is not set in the case of IDP-initiated SSO, redirect to the root */
relayState = relayState || r.variables.cookie_auth_redir || '/';
const redirectUrl = (r.variables.redirect_base || '') + relayState;
r.return(302, redirectUrl);
}
function postLogoutRedirect(r, relayState) {
let redirectUrl = r.variables.redirect_base || '';
redirectUrl += relayState;
r.return(302, redirectUrl);
}
function clearSession(r) {
r.log("SAML logout for " + r.variables.saml_name_id);
r.variables.saml_access_granted = "-";
r.variables.saml_name_id = "-";
const cookieFlags = r.variables.saml_cookie_flags;
const expired = 'Expires=Thu, 01 Jan 1970 00:00:00 GMT; ';
r.headersOut['Set-Cookie'] = [
"auth_token=; " + expired + cookieFlags,
"auth_redir=; " + expired + cookieFlags
];
}
/**
* Generates an outgoing SAML message based on the messageType parameter.
* @param {string} messageType - The type of the SAML message (AuthnRequest, LogoutRequest, or LogoutResponse).
* @param {object} r - The NGINX request object.
* @param {object} opt - Optional object containing configuration options.
* @returns {Promise<void>}
* @throws {Error} - If there is an issue processing the SAML request.
*/
async function produceSAMLMessage(messageType, r, opt) {
let id;
try {
/* Validate SAML message type */
validateMessageType(messageType);
/**
* Parse configuration options based on messageType. For the case of the LogoutResponse,
* we reuse the 'opt' object, since it defines by the LogoutRequest.
*/
opt = opt || parseConfigurationOptions(r, messageType);
/* Generate a unique ID for the SAML message */
id = "_" + generateID(20);
/* Handle messageType actions */
switch (messageType) {
case "AuthnRequest":
/* Save the original request uri to the "auth_redir" cookie */
setAuthRedirCookie(r);
break;
case "LogoutRequest":
/**
* Perform simple session termination if SAML SLO is disabled or if the
* session has already expired or not found.
*/
if (!opt.nameID || opt.isSLODisabled) {
clearSession(r)
postLogoutRedirect(r, opt.relayState);
return;
}
break;
case "LogoutResponse":
/* Obtain the status code for the LogoutResponse message */
opt.statusCode = getLogoutStatusCode(r.variables.saml_name_id, opt.nameID)
break;
}
/* Create the SAML message based on messageType */
const xmlDoc = await createSAMLMessage(opt, id, messageType);
/* Clear session if LogoutResponse StatusCode is Success */
(opt.statusCode === 'urn:oasis:names:tc:SAML:2.0:status:Success') && clearSession(r);
/* Determine whether the HTTP response should be sent via POST or GET and dispatch */
const isPost = opt.requestBinding === 'HTTP-POST';
const postParam = messageType === 'LogoutResponse' ? 'SAMLResponse' : 'SAMLRequest';
dispatchResponse(r, xmlDoc, opt.idpServiceURL, opt.relayState, postParam, isPost);
/* Set SAML request ID and redeemed flag */
r.variables.saml_request_id = id;
r.variables.saml_request_redeemed = "1";
} catch (e) {
samlError(r, 500, id, e);
}
}
/**
* Validates the messageType, ensuring that it is one of the allowed values.
* @param {string} messageType - The type of the SAML message.
* @throws {Error} - If the messageType is not one of the allowed values.
*/
function validateMessageType(messageType) {
const allowedMessageTypes = ['AuthnRequest', 'LogoutRequest', 'LogoutResponse'];
if (!allowedMessageTypes.includes(messageType)) {
throw new Error(`Invalid messageType: ${messageType}. ` +
`Allowed values are: ${allowedMessageTypes.join(', ')}`);
}
}
function setAuthRedirCookie(r) {
r.headersOut['Set-Cookie'] = [
"auth_redir=" + r.variables.request_uri + "; " + r.variables.saml_cookie_flags
];
}
function getLogoutStatusCode(sessionNameID, requestNameID) {
/* If no session exists, return Logout Success */
if (!sessionNameID || sessionNameID === '-') {
return 'urn:oasis:names:tc:SAML:2.0:status:Success';
}
/* If session exists, return Logout Success if NameID matches */
return requestNameID === sessionNameID
? 'urn:oasis:names:tc:SAML:2.0:status:Success'
: 'urn:oasis:names:tc:SAML:2.0:status:Requester';
}
async function createSAMLMessage(opt, id, messageType) {
const handlers = {
AuthnRequest: () => ({
assertionConsumerServiceURL: ` AssertionConsumerServiceURL="${opt.spServiceURL}"`,
protocolBinding: ' ProtocolBinding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST"',
forceAuthn: opt.forceAuthn ? ' ForceAuthn="true"' : null,
nameIDPolicy: `<samlp:NameIDPolicy Format="${opt.nameIDFormat}" AllowCreate="true"/>`,
}),
LogoutRequest: () => ({
nameID: `<saml:NameID>${opt.nameID}</saml:NameID>`,
}),
LogoutResponse: () => ({
inResponseTo: ` InResponseTo="${opt.inResponseTo}"`,
status: `<samlp:Status><samlp:StatusCode Value="${opt.statusCode}"/></samlp:Status>`,
}),
};
const handlerResult = handlers[messageType]();
const assertionConsumerServiceURL = handlerResult.assertionConsumerServiceURL || "";
const protocolBinding = handlerResult.protocolBinding || "";
const forceAuthn = handlerResult.forceAuthn || "";
const nameIDPolicy = handlerResult.nameIDPolicy || "";
const nameID = handlerResult.nameID || "";
const inResponseTo = handlerResult.inResponseTo || "";
const status = handlerResult.status || "";
let message =
`<samlp:${messageType}` +
' xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol"' +
' xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion"' +
' Version="2.0"' +
` ID="${id}"` +
` IssueInstant="${new Date().toISOString()}"` +
` Destination="${opt.idpServiceURL}"` +
inResponseTo +
assertionConsumerServiceURL +
protocolBinding +
forceAuthn +
'>' +
`<saml:Issuer>${opt.spEntityID}</saml:Issuer>` +
`${opt.isSigned ? samlSignatureTemplate(id) : ''}` +
nameID +
nameIDPolicy +
status +
`</samlp:${messageType}>`;
let root;
try {
root = (xml.parse(message)).$root;
} catch (e) {
throw Error(`Failed to create ${messageType} from XML template: ${e.message}`);
}
if (opt.isSigned) {
try {
const rootSignature = root.Signature;
await digestSAML(rootSignature, true);
await signatureSAML(rootSignature, opt.signKey, true);
} catch (e) {
throw Error(`Failed to sign ${messageType}: ${e.message}`);
}
}
return xml.serializeToString(root);
}
/**
* Generates a SAML signature XML template with the provided ID.
*
* @param {string} id - The ID to use as a reference within the signature template.
* @returns {string} - The SAML signature XML template with the specified ID.
*/
function samlSignatureTemplate(id) {
const signTemplate =
'<ds:Signature xmlns:ds="http://www.w3.org/2000/09/xmldsig#">' +
'<ds:SignedInfo>' +
'<ds:CanonicalizationMethod Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#" />' +
'<ds:SignatureMethod Algorithm="http://www.w3.org/2001/04/xmldsig-more#rsa-sha256" />' +
`<ds:Reference URI="#${id}">` +
'<ds:Transforms>' +
'<ds:Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature" />' +
'<ds:Transform Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#" />' +
'</ds:Transforms>' +
'<ds:DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256" />' +
'<ds:DigestValue></ds:DigestValue>' +
'</ds:Reference>' +
'</ds:SignedInfo>' +
'<ds:SignatureValue></ds:SignatureValue>' +
'</ds:Signature>';
return signTemplate;
}
function postFormTemplate(samlMessage, idpServiceUrl, relayState, messageType ) {
relayState = relayState ? `<input type="hidden" name="RelayState" value="${relayState}" />` : "";
return `
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>NGINX SAML SSO</title>
</head>
<body>
<script>
window.onload = function() {
document.getElementById("submitButton").style.display = "none";
document.forms[0].submit();
};
</script>
<noscript>
<p><strong>Note:</strong>
Since your browser does not support JavaScript,
you must press the button below once to proceed.</p>
</noscript>
<form method="post" action="${idpServiceUrl}">
<input type="submit" id="submitButton"/>
<input type="hidden" name="${messageType}" value="${samlMessage}" />
${relayState}
<noscript>
<button type="submit" class="btn">Continue Login</button>
</noscript>
</form>
</body>
</html>`;
}
/**
* Dispatches a SAML response to the IdP service URL using either HTTP-POST or HTTP-Redirect binding.
*
* @param {object} r - The NJS HTTP request object.
* @param {string} root - The SAML response XML string.
* @param {string} idpServiceUrl - The IdP service URL where the response should be sent.
* @param {string} relayState - The RelayState parameter value to include with the response.
* @param {string} postParam - The name of the POST parameter to use for sending the encoded XML.
* @param {boolean} isPost - If true, use HTTP-POST binding; otherwise, use HTTP-Redirect binding.
* @returns {object} - The NJS HTTP response object with appropriate headers and content.
*/
function dispatchResponse(r, root, idpServiceUrl, relayState, postParam, isPost) {
let encodedXml;
// Set outgoing headers for the response
r.headersOut['Content-Type'] = "text/html";
if (isPost) {
// Encode the XML string as base64 for the HTTP-POST binding
encodedXml = Buffer.from(root).toString("base64");
// Return the response with the POST form template
return r.return(200, postFormTemplate(encodedXml, idpServiceUrl, relayState, postParam));
} else {
// Compress and encode the XML string as base64 for the HTTP-Redirect binding
const compressedXml = zlib.deflateRawSync(root);
encodedXml = Buffer.from(compressedXml).toString("base64");
// Construct the IdP service URL with the encoded XML and RelayState (if provided)
const url = `${idpServiceUrl}?${postParam}=${encodeURIComponent(encodedXml)}` +
`${relayState ? `&RelayState=${relayState}` : ""}`;
// Return the response with a 302 redirect to the constructed URL
return r.return(302, url);
}
}
/*
* verifySAMLSignature() implements a verify clause
* from Profiles for the OASIS SAML V2.0
* 4.1.4.3 <Response> Message Processing Rules
* Verify any signatures present on the assertion(s) or the response
*
* verification is done in accordance with
* Assertions and Protocols for the OASIS SAML V2.0
* 5.4 XML Signature Profile
*
* The following signature algorithms are supported:
* - http://www.w3.org/2001/04/xmldsig-more#rsa-sha256
* - http://www.w3.org/2000/09/xmldsig#rsa-sha1
*
* The following digest algorithms are supported:
* - http://www.w3.org/2000/09/xmldsig#sha1
* - http://www.w3.org/2001/04/xmlenc#sha256
*
* @param root an XMLDoc object returned by xml.parse().
* @param keyDataArray is array of SubjectPublicKeyInfo in PKCS#1 format.
*/
async function verifySAMLSignature(root, keyDataArray) {
const type = root.$name;
const rootSignature = root.Signature;
if (!rootSignature) {
throw Error(`Message is unsigned`);
}
const errors = [];
for (let i = 0; i < keyDataArray.length; i++) {
try {
const digestResult = await digestSAML(rootSignature);
const signatureResult = await signatureSAML(rootSignature, keyDataArray[i]);
if (digestResult && signatureResult) {
return;
} else {
errors.push(`Key index ${i}: signature verification failed`);
}
} catch (e) {
errors.push(e.message);
}
}
throw Error(`Error verifying ${type} message signature: ${errors.join(', ')}`);
}
async function digestSAML(signature, produce) {
const parent = signature.$parent;
const signedInfo = signature.SignedInfo;
const reference = signedInfo.Reference;
/* Sanity check. */
const URI = reference.$attr$URI;
const ID = parent.$attr$ID;
if (URI != `#${ID}`) {
throw Error(`signed reference URI ${URI} does not point to the parent ${ID}`);
}
/*
* Assertions and Protocols for the OASIS SAML V2.0
* 5.4.4 Transforms
*
* Signatures in SAML messages SHOULD NOT contain transforms other than
* the http://www.w3.org/2000/09/xmldsig#enveloped-signature and
* canonicalization transforms http://www.w3.org/2001/10/xml-exc-c14n# or
* http://www.w3.org/2001/10/xml-exc-c14n#WithComments.
*/
const transforms = reference.Transforms.$tags$Transform;
const transformAlgs = transforms.map(t => t.$attr$Algorithm);
if (transformAlgs[0] != 'http://www.w3.org/2000/09/xmldsig#enveloped-signature') {
throw Error(`unexpected digest transform ${transforms[0]}`);
}
if (!transformAlgs[1].startsWith('http://www.w3.org/2001/10/xml-exc-c14n#')) {
throw Error(`unexpected digest transform ${transforms[1]}`);
}
const namespaces = transforms[1].InclusiveNamespaces;
const prefixList = namespaces ? namespaces.$attr$PrefixList: null;
const withComments = transformAlgs[1].slice(39) == 'WithComments';
let hash;
const alg = reference.DigestMethod.$attr$Algorithm;
switch (alg) {
case "http://www.w3.org/2000/09/xmldsig#sha1":
hash = "SHA-1";
break;
case "http://www.w3.org/2001/04/xmlenc#sha256":
hash = "SHA-256";
break;
default:
throw Error(`unexpected digest Algorithm ${alg}`);
}
const c14n = xml.exclusiveC14n(parent, signature, withComments, prefixList);
const dgst = await crypto.subtle.digest(hash, c14n);
const b64dgst = Buffer.from(dgst).toString('base64');
if (produce) {
signedInfo.Reference.DigestValue.$text = b64dgst;
return b64dgst;
}
const expectedDigest = signedInfo.Reference.DigestValue.$text;
return expectedDigest === b64dgst;
}
function keyPem2Der(pem, type) {
const pemJoined = pem.toString().split('\n').join('');
const pemHeader = `-----BEGIN ${type} KEY-----`;
const pemFooter = `-----END ${type} KEY-----`;
const pemContents = pemJoined.substring(pemHeader.length, pemJoined.length - pemFooter.length);