-
Notifications
You must be signed in to change notification settings - Fork 475
/
Copy pathsaml.ts
1474 lines (1308 loc) · 49.1 KB
/
saml.ts
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
import Debug from "debug";
const debug = Debug("node-saml");
import * as zlib from "zlib";
import * as crypto from "crypto";
import { URL } from "url";
import * as querystring from "querystring";
import * as util from "util";
import { CacheProvider as InMemoryCacheProvider } from "./inmemory-cache-provider";
import * as algorithms from "./algorithms";
import { signAuthnRequestPost } from "./saml-post-signing";
import { ParsedQs } from "qs";
import {
isValidSamlSigningOptions,
AudienceRestrictionXML,
AuthorizeRequestXML,
CertCallback,
LogoutRequestXML,
SamlIDPListConfig,
SamlIDPEntryConfig,
SamlOptions,
ServiceMetadataXML,
XMLInput,
XMLObject,
XMLOutput,
} from "./types";
import {
AuthenticateOptions,
AuthorizeOptions,
Profile,
SamlConfig,
ErrorWithXmlStatus,
} from "../passport-saml/types";
import { assertRequired } from "./utility";
import {
buildXml2JsObject,
buildXmlBuilderObject,
decryptXml,
parseDomFromString,
parseXml2JsFromString,
validateXmlSignatureForCert,
xpath,
} from "./xml";
const inflateRawAsync = util.promisify(zlib.inflateRaw);
const deflateRawAsync = util.promisify(zlib.deflateRaw);
interface NameID {
value: string | null;
format: string | null;
}
async function processValidlySignedPostRequestAsync(
self: SAML,
doc: XMLOutput,
dom: Document
): Promise<{ profile?: Profile; loggedOut?: boolean }> {
const request = doc.LogoutRequest;
if (request) {
const profile = {} as Profile;
if (request.$.ID) {
profile.ID = request.$.ID;
} else {
throw new Error("Missing SAML LogoutRequest ID");
}
const issuer = request.Issuer;
if (issuer && issuer[0]._) {
profile.issuer = issuer[0]._;
} else {
throw new Error("Missing SAML issuer");
}
const nameID = await self._getNameIdAsync(self, dom);
if (nameID) {
profile.nameID = nameID.value!;
if (nameID.format) {
profile.nameIDFormat = nameID.format;
}
} else {
throw new Error("Missing SAML NameID");
}
const sessionIndex = request.SessionIndex;
if (sessionIndex) {
profile.sessionIndex = sessionIndex[0]._;
}
return { profile, loggedOut: true };
} else {
throw new Error("Unknown SAML request message");
}
}
async function processValidlySignedSamlLogoutAsync(
self: SAML,
doc: XMLOutput,
dom: Document
): Promise<{ profile?: Profile | null; loggedOut?: boolean }> {
const response = doc.LogoutResponse;
const request = doc.LogoutRequest;
if (response) {
return { profile: null, loggedOut: true };
} else if (request) {
return await processValidlySignedPostRequestAsync(self, doc, dom);
} else {
throw new Error("Unknown SAML response message");
}
}
async function promiseWithNameID(nameid: Node): Promise<NameID> {
const format = xpath.selectAttributes(nameid, "@Format");
return {
value: nameid.textContent,
format: format && format[0] && format[0].nodeValue,
};
}
class SAML {
// note that some methods in SAML are not yet marked as private as they are used in testing.
// those methods start with an underscore, e.g. _generateUniqueID
options: SamlOptions;
// This is only for testing
cacheProvider!: InMemoryCacheProvider;
constructor(ctorOptions: SamlConfig) {
this.options = this.initialize(ctorOptions);
this.cacheProvider = this.options.cacheProvider;
}
initialize(ctorOptions: SamlConfig): SamlOptions {
if (!ctorOptions) {
throw new TypeError("SamlOptions required on construction");
}
const options = {
...ctorOptions,
passive: ctorOptions.passive ?? false,
disableRequestedAuthnContext: ctorOptions.disableRequestedAuthnContext ?? false,
additionalParams: ctorOptions.additionalParams ?? {},
additionalAuthorizeParams: ctorOptions.additionalAuthorizeParams ?? {},
additionalLogoutParams: ctorOptions.additionalLogoutParams ?? {},
forceAuthn: ctorOptions.forceAuthn ?? false,
skipRequestCompression: ctorOptions.skipRequestCompression ?? false,
disableRequestAcsUrl: ctorOptions.disableRequestAcsUrl ?? false,
acceptedClockSkewMs: ctorOptions.acceptedClockSkewMs ?? 0,
maxAssertionAgeMs: ctorOptions.maxAssertionAgeMs ?? 0,
path: ctorOptions.path ?? "/saml/consume",
host: ctorOptions.host ?? "localhost",
issuer: ctorOptions.issuer ?? "onelogin_saml",
identifierFormat:
ctorOptions.identifierFormat === undefined
? "urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress"
: ctorOptions.identifierFormat,
wantAssertionsSigned: ctorOptions.wantAssertionsSigned ?? false,
authnContext: ctorOptions.authnContext ?? [
"urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport",
],
validateInResponseTo: ctorOptions.validateInResponseTo ?? false,
cert: assertRequired(ctorOptions.cert, "cert is required"),
requestIdExpirationPeriodMs: ctorOptions.requestIdExpirationPeriodMs ?? 28800000, // 8 hours
cacheProvider:
ctorOptions.cacheProvider ??
new InMemoryCacheProvider({
keyExpirationPeriodMs: ctorOptions.requestIdExpirationPeriodMs,
}),
logoutUrl: ctorOptions.logoutUrl ?? ctorOptions.entryPoint ?? "", // Default to Entry Point
signatureAlgorithm: ctorOptions.signatureAlgorithm ?? "sha1", // sha1, sha256, or sha512
authnRequestBinding: ctorOptions.authnRequestBinding ?? "HTTP-Redirect",
racComparison: ctorOptions.racComparison ?? "exact",
};
/**
* List of possible values:
* - exact : Assertion context must exactly match a context in the list
* - minimum: Assertion context must be at least as strong as a context in the list
* - maximum: Assertion context must be no stronger than a context in the list
* - better: Assertion context must be stronger than all contexts in the list
*/
if (!["exact", "minimum", "maximum", "better"].includes(options.racComparison)) {
throw new TypeError("racComparison must be one of ['exact', 'minimum', 'maximum', 'better']");
}
return options;
}
private getCallbackUrl(host?: string | undefined) {
// Post-auth destination
if (this.options.callbackUrl) {
return this.options.callbackUrl;
} else {
const url = new URL("http://localhost");
if (host) {
url.host = host;
} else {
url.host = this.options.host;
}
if (this.options.protocol) {
url.protocol = this.options.protocol;
}
url.pathname = this.options.path;
return url.toString();
}
}
_generateUniqueID() {
return crypto.randomBytes(10).toString("hex");
}
private generateInstant() {
return new Date().toISOString();
}
private signRequest(samlMessage: querystring.ParsedUrlQueryInput): void {
this.options.privateKey = assertRequired(this.options.privateKey, "privateKey is required");
const samlMessageToSign: querystring.ParsedUrlQueryInput = {};
samlMessage.SigAlg = algorithms.getSigningAlgorithm(this.options.signatureAlgorithm);
const signer = algorithms.getSigner(this.options.signatureAlgorithm);
if (samlMessage.SAMLRequest) {
samlMessageToSign.SAMLRequest = samlMessage.SAMLRequest;
}
if (samlMessage.SAMLResponse) {
samlMessageToSign.SAMLResponse = samlMessage.SAMLResponse;
}
if (samlMessage.RelayState) {
samlMessageToSign.RelayState = samlMessage.RelayState;
}
if (samlMessage.SigAlg) {
samlMessageToSign.SigAlg = samlMessage.SigAlg;
}
signer.update(querystring.stringify(samlMessageToSign));
samlMessage.Signature = signer.sign(this._keyToPEM(this.options.privateKey), "base64");
}
private async generateAuthorizeRequestAsync(
isPassive: boolean,
isHttpPostBinding: boolean,
host: string | undefined
): Promise<string | undefined> {
this.options.entryPoint = assertRequired(this.options.entryPoint, "entryPoint is required");
const id = "_" + this._generateUniqueID();
const instant = this.generateInstant();
if (this.options.validateInResponseTo) {
await this.cacheProvider.saveAsync(id, instant);
}
const request: AuthorizeRequestXML = {
"samlp:AuthnRequest": {
"@xmlns:samlp": "urn:oasis:names:tc:SAML:2.0:protocol",
"@ID": id,
"@Version": "2.0",
"@IssueInstant": instant,
"@ProtocolBinding": "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST",
"@Destination": this.options.entryPoint,
"saml:Issuer": {
"@xmlns:saml": "urn:oasis:names:tc:SAML:2.0:assertion",
"#text": this.options.issuer,
},
},
};
if (isPassive) request["samlp:AuthnRequest"]["@IsPassive"] = true;
if (this.options.forceAuthn) {
request["samlp:AuthnRequest"]["@ForceAuthn"] = true;
}
if (!this.options.disableRequestAcsUrl) {
request["samlp:AuthnRequest"]["@AssertionConsumerServiceURL"] = this.getCallbackUrl(host);
}
if (this.options.identifierFormat != null) {
request["samlp:AuthnRequest"]["samlp:NameIDPolicy"] = {
"@xmlns:samlp": "urn:oasis:names:tc:SAML:2.0:protocol",
"@Format": this.options.identifierFormat,
"@AllowCreate": "true",
};
}
if (!this.options.disableRequestedAuthnContext) {
const authnContextClassRefs: XMLInput[] = [];
(this.options.authnContext as string[]).forEach(function (value) {
authnContextClassRefs.push({
"@xmlns:saml": "urn:oasis:names:tc:SAML:2.0:assertion",
"#text": value,
});
});
request["samlp:AuthnRequest"]["samlp:RequestedAuthnContext"] = {
"@xmlns:samlp": "urn:oasis:names:tc:SAML:2.0:protocol",
"@Comparison": this.options.racComparison,
"saml:AuthnContextClassRef": authnContextClassRefs,
};
}
if (this.options.attributeConsumingServiceIndex != null) {
request["samlp:AuthnRequest"]["@AttributeConsumingServiceIndex"] =
this.options.attributeConsumingServiceIndex;
}
if (this.options.providerName != null) {
request["samlp:AuthnRequest"]["@ProviderName"] = this.options.providerName;
}
if (this.options.scoping != null) {
const scoping: XMLInput = {
"@xmlns:samlp": "urn:oasis:names:tc:SAML:2.0:protocol",
};
if (typeof this.options.scoping.proxyCount === "number") {
scoping["@ProxyCount"] = this.options.scoping.proxyCount;
}
if (this.options.scoping.idpList) {
scoping["samlp:IDPList"] = this.options.scoping.idpList.map(
(idpListItem: SamlIDPListConfig) => {
const formattedIdpListItem: XMLInput = {
"@xmlns:samlp": "urn:oasis:names:tc:SAML:2.0:protocol",
};
if (idpListItem.entries) {
formattedIdpListItem["samlp:IDPEntry"] = idpListItem.entries.map(
(entry: SamlIDPEntryConfig) => {
const formattedEntry: XMLInput = {
"@xmlns:samlp": "urn:oasis:names:tc:SAML:2.0:protocol",
};
formattedEntry["@ProviderID"] = entry.providerId;
if (entry.name) {
formattedEntry["@Name"] = entry.name;
}
if (entry.loc) {
formattedEntry["@Loc"] = entry.loc;
}
return formattedEntry;
}
);
}
if (idpListItem.getComplete) {
formattedIdpListItem["samlp:GetComplete"] = idpListItem.getComplete;
}
return formattedIdpListItem;
}
);
}
if (this.options.scoping.requesterId) {
scoping["samlp:RequesterID"] = this.options.scoping.requesterId;
}
request["samlp:AuthnRequest"]["samlp:Scoping"] = scoping;
}
let stringRequest = buildXmlBuilderObject(request, false);
// TODO: maybe we should always sign here
if (isHttpPostBinding && isValidSamlSigningOptions(this.options)) {
stringRequest = signAuthnRequestPost(stringRequest, this.options);
}
return stringRequest;
}
async _generateLogoutRequest(user: Profile) {
const id = "_" + this._generateUniqueID();
const instant = this.generateInstant();
const request = {
"samlp:LogoutRequest": {
"@xmlns:samlp": "urn:oasis:names:tc:SAML:2.0:protocol",
"@xmlns:saml": "urn:oasis:names:tc:SAML:2.0:assertion",
"@ID": id,
"@Version": "2.0",
"@IssueInstant": instant,
"@Destination": this.options.logoutUrl,
"saml:Issuer": {
"@xmlns:saml": "urn:oasis:names:tc:SAML:2.0:assertion",
"#text": this.options.issuer,
},
"saml:NameID": {
"@Format": user!.nameIDFormat,
"#text": user!.nameID,
},
},
} as LogoutRequestXML;
if (user!.nameQualifier != null) {
request["samlp:LogoutRequest"]["saml:NameID"]["@NameQualifier"] = user!.nameQualifier;
}
if (user!.spNameQualifier != null) {
request["samlp:LogoutRequest"]["saml:NameID"]["@SPNameQualifier"] = user!.spNameQualifier;
}
if (user!.sessionIndex) {
request["samlp:LogoutRequest"]["saml2p:SessionIndex"] = {
"@xmlns:saml2p": "urn:oasis:names:tc:SAML:2.0:protocol",
"#text": user!.sessionIndex,
};
}
await this.cacheProvider.saveAsync(id, instant);
return buildXmlBuilderObject(request, false);
}
_generateLogoutResponse(logoutRequest: Profile) {
const id = "_" + this._generateUniqueID();
const instant = this.generateInstant();
const request = {
"samlp:LogoutResponse": {
"@xmlns:samlp": "urn:oasis:names:tc:SAML:2.0:protocol",
"@xmlns:saml": "urn:oasis:names:tc:SAML:2.0:assertion",
"@ID": id,
"@Version": "2.0",
"@IssueInstant": instant,
"@Destination": this.options.logoutUrl,
"@InResponseTo": logoutRequest.ID,
"saml:Issuer": {
"#text": this.options.issuer,
},
"samlp:Status": {
"samlp:StatusCode": {
"@Value": "urn:oasis:names:tc:SAML:2.0:status:Success",
},
},
},
};
return buildXmlBuilderObject(request, false);
}
async _requestToUrlAsync(
request: string | null | undefined,
response: string | null,
operation: string,
additionalParameters: querystring.ParsedUrlQuery
): Promise<string> {
this.options.entryPoint = assertRequired(this.options.entryPoint, "entryPoint is required");
let buffer: Buffer;
if (this.options.skipRequestCompression) {
buffer = Buffer.from((request || response)!, "utf8");
} else {
buffer = await deflateRawAsync((request || response)!);
}
const base64 = buffer.toString("base64");
let target = new URL(this.options.entryPoint);
if (operation === "logout") {
if (this.options.logoutUrl) {
target = new URL(this.options.logoutUrl);
}
} else if (operation !== "authorize") {
throw new Error("Unknown operation: " + operation);
}
const samlMessage: querystring.ParsedUrlQuery = request
? {
SAMLRequest: base64,
}
: {
SAMLResponse: base64,
};
Object.keys(additionalParameters).forEach((k) => {
samlMessage[k] = additionalParameters[k];
});
if (this.options.privateKey != null) {
if (!this.options.entryPoint) {
throw new Error('"entryPoint" config parameter is required for signed messages');
}
// sets .SigAlg and .Signature
this.signRequest(samlMessage);
}
Object.keys(samlMessage).forEach((k) => {
target.searchParams.set(k, samlMessage[k] as string);
});
return target.toString();
}
_getAdditionalParams(
RelayState: string,
operation: string,
overrideParams?: querystring.ParsedUrlQuery
): querystring.ParsedUrlQuery {
const additionalParams: querystring.ParsedUrlQuery = {};
if (typeof RelayState === "string" && RelayState.length > 0) {
additionalParams.RelayState = RelayState;
}
const optionsAdditionalParams = this.options.additionalParams;
Object.keys(optionsAdditionalParams).forEach(function (k) {
additionalParams[k] = optionsAdditionalParams[k];
});
let optionsAdditionalParamsForThisOperation: Record<string, string> = {};
if (operation == "authorize") {
optionsAdditionalParamsForThisOperation = this.options.additionalAuthorizeParams;
}
if (operation == "logout") {
optionsAdditionalParamsForThisOperation = this.options.additionalLogoutParams;
}
Object.keys(optionsAdditionalParamsForThisOperation).forEach(function (k) {
additionalParams[k] = optionsAdditionalParamsForThisOperation[k];
});
overrideParams = overrideParams ?? {};
Object.keys(overrideParams).forEach(function (k) {
additionalParams[k] = overrideParams![k];
});
return additionalParams;
}
async getAuthorizeUrlAsync(
RelayState: string,
host: string | undefined,
options: AuthorizeOptions
): Promise<string> {
const request = await this.generateAuthorizeRequestAsync(this.options.passive, false, host);
const operation = "authorize";
const overrideParams = options ? options.additionalParams || {} : {};
return await this._requestToUrlAsync(
request,
null,
operation,
this._getAdditionalParams(RelayState, operation, overrideParams)
);
}
async getAuthorizeFormAsync(RelayState: string, host?: string): Promise<string> {
this.options.entryPoint = assertRequired(this.options.entryPoint, "entryPoint is required");
// The quoteattr() function is used in a context, where the result will not be evaluated by javascript
// but must be interpreted by an XML or HTML parser, and it must absolutely avoid breaking the syntax
// of an element attribute.
const quoteattr = function (
s:
| string
| number
| boolean
| undefined
| null
| readonly string[]
| readonly number[]
| readonly boolean[],
preserveCR?: boolean
) {
const preserveCRChar = preserveCR ? " " : "\n";
return (
("" + s) // Forces the conversion to string.
.replace(/&/g, "&") // This MUST be the 1st replacement.
.replace(/'/g, "'") // The 4 other predefined entities, required.
.replace(/"/g, """)
.replace(/</g, "<")
.replace(/>/g, ">")
// Add other replacements here for HTML only
// Or for XML, only if the named entities are defined in its DTD.
.replace(/\r\n/g, preserveCRChar) // Must be before the next replacement.
.replace(/[\r\n]/g, preserveCRChar)
);
};
const request = await this.generateAuthorizeRequestAsync(this.options.passive, true, host);
let buffer: Buffer;
if (this.options.skipRequestCompression) {
buffer = Buffer.from(request!, "utf8");
} else {
buffer = await deflateRawAsync(request!);
}
const operation = "authorize";
const additionalParameters = this._getAdditionalParams(RelayState, operation);
const samlMessage: querystring.ParsedUrlQueryInput = {
SAMLRequest: buffer!.toString("base64"),
};
Object.keys(additionalParameters).forEach((k) => {
samlMessage[k] = additionalParameters[k] || "";
});
const formInputs = Object.keys(samlMessage)
.map((k) => {
return '<input type="hidden" name="' + k + '" value="' + quoteattr(samlMessage[k]) + '" />';
})
.join("\r\n");
return [
"<!DOCTYPE html>",
"<html>",
"<head>",
'<meta charset="utf-8">',
'<meta http-equiv="x-ua-compatible" content="ie=edge">',
"</head>",
'<body onload="document.forms[0].submit()">',
"<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="' + encodeURI(this.options.entryPoint) + '">',
formInputs,
'<input type="submit" value="Submit" />',
"</form>",
'<script>document.forms[0].style.display="none";</script>', // Hide the form if JavaScript is enabled
"</body>",
"</html>",
].join("\r\n");
}
async getLogoutUrlAsync(
user: Profile,
RelayState: string,
options: AuthenticateOptions & AuthorizeOptions
) {
const request = await this._generateLogoutRequest(user);
const operation = "logout";
const overrideParams = options ? options.additionalParams || {} : {};
return await this._requestToUrlAsync(
request,
null,
operation,
this._getAdditionalParams(RelayState, operation, overrideParams)
);
}
getLogoutResponseUrl(
samlLogoutRequest: Profile,
RelayState: string,
options: AuthenticateOptions & AuthorizeOptions,
callback: (err: Error | null, url?: string | null) => void
): void {
util.callbackify(() => this.getLogoutResponseUrlAsync(samlLogoutRequest, RelayState, options))(
callback
);
}
private async getLogoutResponseUrlAsync(
samlLogoutRequest: Profile,
RelayState: string,
options: AuthenticateOptions & AuthorizeOptions // add RelayState,
): Promise<string> {
const response = this._generateLogoutResponse(samlLogoutRequest);
const operation = "logout";
const overrideParams = options ? options.additionalParams || {} : {};
return await this._requestToUrlAsync(
null,
response,
operation,
this._getAdditionalParams(RelayState, operation, overrideParams)
);
}
_certToPEM(cert: string): string {
cert = cert.match(/.{1,64}/g)!.join("\n");
if (cert.indexOf("-BEGIN CERTIFICATE-") === -1) cert = "-----BEGIN CERTIFICATE-----\n" + cert;
if (cert.indexOf("-END CERTIFICATE-") === -1) cert = cert + "\n-----END CERTIFICATE-----\n";
return cert;
}
private async certsToCheck(): Promise<string[]> {
let checkedCerts: string[];
if (typeof this.options.cert === "function") {
checkedCerts = await util
.promisify(this.options.cert as CertCallback)()
.then((certs) => {
certs = assertRequired(certs, "callback didn't return cert");
if (!Array.isArray(certs)) {
certs = [certs];
}
return certs;
});
} else if (Array.isArray(this.options.cert)) {
checkedCerts = this.options.cert;
} else {
checkedCerts = [this.options.cert];
}
checkedCerts.forEach((cert) => {
assertRequired(cert, "unknown cert found");
});
return checkedCerts;
}
// This function checks that the |currentNode| in the |fullXml| document contains exactly 1 valid
// signature of the |currentNode|.
//
// See https://github.com/bergie/passport-saml/issues/19 for references to some of the attack
// vectors against SAML signature verification.
validateSignature(fullXml: string, currentNode: Element, certs: string[]): boolean {
const xpathSigQuery =
".//*[" +
"local-name(.)='Signature' and " +
"namespace-uri(.)='http://www.w3.org/2000/09/xmldsig#' and " +
"descendant::*[local-name(.)='Reference' and @URI='#" +
currentNode.getAttribute("ID") +
"']" +
"]";
const signatures = xpath.selectElements(currentNode, xpathSigQuery);
// This function is expecting to validate exactly one signature, so if we find more or fewer
// than that, reject.
if (signatures.length !== 1) {
return false;
}
const signature = signatures[0];
return certs.some((certToCheck) => {
return validateXmlSignatureForCert(
signature,
this._certToPEM(certToCheck),
fullXml,
currentNode
);
});
}
async validatePostResponseAsync(
container: Record<string, string>
): Promise<{ profile?: Profile | null; loggedOut?: boolean }> {
let xml: string, doc: Document, inResponseTo: string | null;
try {
xml = Buffer.from(container.SAMLResponse, "base64").toString("utf8");
doc = parseDomFromString(xml);
if (!Object.prototype.hasOwnProperty.call(doc, "documentElement"))
throw new Error("SAMLResponse is not valid base64-encoded XML");
const inResponseToNodes = xpath.selectAttributes(
doc,
"/*[local-name()='Response']/@InResponseTo"
);
if (inResponseToNodes) {
inResponseTo = inResponseToNodes.length ? inResponseToNodes[0].nodeValue : null;
await this.validateInResponseTo(inResponseTo);
}
const certs = await this.certsToCheck();
// Check if this document has a valid top-level signature
let validSignature = false;
if (this.validateSignature(xml, doc.documentElement, certs)) {
validSignature = true;
}
const assertions = xpath.selectElements(
doc,
"/*[local-name()='Response']/*[local-name()='Assertion']"
);
const encryptedAssertions = xpath.selectElements(
doc,
"/*[local-name()='Response']/*[local-name()='EncryptedAssertion']"
);
if (assertions.length + encryptedAssertions.length > 1) {
// There's no reason I know of that we want to handle multiple assertions, and it seems like a
// potential risk vector for signature scope issues, so treat this as an invalid signature
throw new Error("Invalid signature: multiple assertions");
}
if (assertions.length == 1) {
if (
(this.options.wantAssertionsSigned || !validSignature) &&
!this.validateSignature(xml, assertions[0], certs)
) {
throw new Error("Invalid signature");
}
return await this.processValidlySignedAssertionAsync(
assertions[0].toString(),
xml,
inResponseTo!
);
}
if (encryptedAssertions.length == 1) {
this.options.decryptionPvk = assertRequired(
this.options.decryptionPvk,
"No decryption key for encrypted SAML response"
);
const encryptedAssertionXml = encryptedAssertions[0].toString();
const decryptedXml = await decryptXml(encryptedAssertionXml, this.options.decryptionPvk);
const decryptedDoc = parseDomFromString(decryptedXml);
const decryptedAssertions = xpath.selectElements(
decryptedDoc,
"/*[local-name()='Assertion']"
);
if (decryptedAssertions.length != 1) throw new Error("Invalid EncryptedAssertion content");
if (
(this.options.wantAssertionsSigned || !validSignature) &&
!this.validateSignature(decryptedXml, decryptedAssertions[0], certs)
) {
throw new Error("Invalid signature from encrypted assertion");
}
return await this.processValidlySignedAssertionAsync(
decryptedAssertions[0].toString(),
xml,
inResponseTo!
);
}
// If there's no assertion, fall back on xml2js response parsing for the status &
// LogoutResponse code.
const xmljsDoc = await parseXml2JsFromString(xml);
const response = xmljsDoc.Response;
if (response) {
const assertion = response.Assertion;
if (!assertion) {
const status = response.Status;
if (status) {
const statusCode = status[0].StatusCode;
if (
statusCode &&
statusCode[0].$.Value === "urn:oasis:names:tc:SAML:2.0:status:Responder"
) {
const nestedStatusCode = statusCode[0].StatusCode;
if (
nestedStatusCode &&
nestedStatusCode[0].$.Value === "urn:oasis:names:tc:SAML:2.0:status:NoPassive"
) {
if (!validSignature) {
throw new Error("Invalid signature: NoPassive");
}
return { profile: null, loggedOut: false };
}
}
// Note that we're not requiring a valid signature before this logic -- since we are
// throwing an error in any case, and some providers don't sign error results,
// let's go ahead and give the potentially more helpful error.
if (statusCode && statusCode[0].$.Value) {
const msgType = statusCode[0].$.Value.match(/[^:]*$/)[0];
if (msgType != "Success") {
let msg = "unspecified";
if (status[0].StatusMessage) {
msg = status[0].StatusMessage[0]._;
} else if (statusCode[0].StatusCode) {
msg = statusCode[0].StatusCode[0].$.Value.match(/[^:]*$/)[0];
}
const statusXml = buildXml2JsObject("Status", status[0]);
throw new ErrorWithXmlStatus(
"SAML provider returned " + msgType + " error: " + msg,
statusXml
);
}
}
}
}
throw new Error("Missing SAML assertion");
} else {
if (!validSignature) {
throw new Error("Invalid signature: No response found");
}
const logoutResponse = xmljsDoc.LogoutResponse;
if (logoutResponse) {
return { profile: null, loggedOut: true };
} else {
throw new Error("Unknown SAML response message");
}
}
} catch (err) {
debug("validatePostResponse resulted in an error: %s", err);
if (this.options.validateInResponseTo != null) {
await this.cacheProvider.removeAsync(inResponseTo!);
}
throw err;
}
}
private async validateInResponseTo(inResponseTo: string | null): Promise<undefined> {
if (this.options.validateInResponseTo) {
if (inResponseTo) {
const result = await this.cacheProvider.getAsync(inResponseTo);
if (!result) throw new Error("InResponseTo is not valid");
return;
} else {
throw new Error("InResponseTo is missing from response");
}
} else {
return;
}
}
async validateRedirectAsync(
container: ParsedQs,
originalQuery: string | null
): Promise<{ profile?: Profile | null; loggedOut?: boolean }> {
const samlMessageType = container.SAMLRequest ? "SAMLRequest" : "SAMLResponse";
const data = Buffer.from(container[samlMessageType] as string, "base64");
const inflated = await inflateRawAsync(data);
const dom = parseDomFromString(inflated.toString());
const doc: XMLOutput = await parseXml2JsFromString(inflated);
samlMessageType === "SAMLResponse"
? await this.verifyLogoutResponse(doc)
: this.verifyLogoutRequest(doc);
await this.hasValidSignatureForRedirect(container, originalQuery);
return await processValidlySignedSamlLogoutAsync(this, doc, dom);
}
private async hasValidSignatureForRedirect(
container: ParsedQs,
originalQuery: string | null
): Promise<boolean | void> {
const tokens = originalQuery!.split("&");
const getParam = (key: string) => {
const exists = tokens.filter((t) => {
return new RegExp(key).test(t);
});
return exists[0];
};
if (container.Signature) {
let urlString = getParam("SAMLRequest") || getParam("SAMLResponse");
if (getParam("RelayState")) {
urlString += "&" + getParam("RelayState");
}
urlString += "&" + getParam("SigAlg");
const certs = await this.certsToCheck();
const hasValidQuerySignature = certs.some((cert) => {
return this.validateSignatureForRedirect(
urlString,
container.Signature as string,
container.SigAlg as string,
cert
);
});
if (!hasValidQuerySignature) {
throw new Error("Invalid query signature");
}
} else {
return true;
}
}
private validateSignatureForRedirect(
urlString: crypto.BinaryLike,
signature: string,
alg: string,
cert: string
) {
// See if we support a matching algorithm, case-insensitive. Otherwise, throw error.
function hasMatch(ourAlgo: string) {
// The incoming algorithm is forwarded as a URL.
// We trim everything before the last # get something we can compare to the Node.js list
const algFromURI = alg.toLowerCase().replace(/.*#(.*)$/, "$1");
return ourAlgo.toLowerCase() === algFromURI;
}
const i = crypto.getHashes().findIndex(hasMatch);
let matchingAlgo;
if (i > -1) {
matchingAlgo = crypto.getHashes()[i];
} else {
throw new Error(alg + " is not supported");
}
const verifier = crypto.createVerify(matchingAlgo);
verifier.update(urlString);
return verifier.verify(this._certToPEM(cert), signature, "base64");
}
private verifyLogoutRequest(doc: XMLOutput) {
this.verifyIssuer(doc.LogoutRequest);
const nowMs = new Date().getTime();
const conditions = doc.LogoutRequest.$;
const conErr = this.checkTimestampsValidityError(
nowMs,
conditions.NotBefore,
conditions.NotOnOrAfter
);
if (conErr) {
throw conErr;
}
}
private async verifyLogoutResponse(doc: XMLOutput) {
const statusCode = doc.LogoutResponse.Status[0].StatusCode[0].$.Value;
if (statusCode !== "urn:oasis:names:tc:SAML:2.0:status:Success")
throw new Error("Bad status code: " + statusCode);
this.verifyIssuer(doc.LogoutResponse);
const inResponseTo = doc.LogoutResponse.$.InResponseTo;
if (inResponseTo) {
return this.validateInResponseTo(inResponseTo);