samlify 2.11.0 → 2.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (83) hide show
  1. package/README.md +1 -1
  2. package/build/src/api.js +52 -3
  3. package/build/src/api.js.map +1 -1
  4. package/build/src/binding-post.js +236 -182
  5. package/build/src/binding-post.js.map +1 -1
  6. package/build/src/binding-redirect.js +303 -215
  7. package/build/src/binding-redirect.js.map +1 -1
  8. package/build/src/binding-simplesign.js +285 -137
  9. package/build/src/binding-simplesign.js.map +1 -1
  10. package/build/src/entity-idp.js +130 -47
  11. package/build/src/entity-idp.js.map +1 -1
  12. package/build/src/entity-sp.js +81 -39
  13. package/build/src/entity-sp.js.map +1 -1
  14. package/build/src/entity.js +100 -62
  15. package/build/src/entity.js.map +1 -1
  16. package/build/src/extractor.js +119 -155
  17. package/build/src/extractor.js.map +1 -1
  18. package/build/src/flow.js +100 -96
  19. package/build/src/flow.js.map +1 -1
  20. package/build/src/libsaml.js +318 -261
  21. package/build/src/libsaml.js.map +1 -1
  22. package/build/src/metadata-idp.js +60 -30
  23. package/build/src/metadata-idp.js.map +1 -1
  24. package/build/src/metadata-sp.js +51 -41
  25. package/build/src/metadata-sp.js.map +1 -1
  26. package/build/src/metadata.js +47 -43
  27. package/build/src/metadata.js.map +1 -1
  28. package/build/src/options.js +73 -0
  29. package/build/src/options.js.map +1 -0
  30. package/build/src/urn.js +28 -1
  31. package/build/src/urn.js.map +1 -1
  32. package/build/src/utility.js +165 -83
  33. package/build/src/utility.js.map +1 -1
  34. package/build/src/validator.js +27 -10
  35. package/build/src/validator.js.map +1 -1
  36. package/package.json +17 -7
  37. package/types/src/api.d.ts +33 -3
  38. package/types/src/binding-post.d.ts +67 -34
  39. package/types/src/binding-redirect.d.ts +58 -31
  40. package/types/src/binding-simplesign.d.ts +77 -21
  41. package/types/src/entity-idp.d.ts +40 -31
  42. package/types/src/entity-sp.d.ts +37 -27
  43. package/types/src/entity.d.ts +71 -77
  44. package/types/src/extractor.d.ts +31 -22
  45. package/types/src/flow.d.ts +24 -2
  46. package/types/src/libsaml.d.ts +172 -118
  47. package/types/src/metadata-idp.d.ts +27 -11
  48. package/types/src/metadata-sp.d.ts +29 -19
  49. package/types/src/metadata.d.ts +59 -34
  50. package/types/src/options.d.ts +37 -0
  51. package/types/src/types.d.ts +250 -24
  52. package/types/src/urn.d.ts +7 -0
  53. package/types/src/utility.d.ts +144 -89
  54. package/types/src/validator.d.ts +21 -0
  55. package/.circleci/config.yml +0 -98
  56. package/.editorconfig +0 -19
  57. package/.github/FUNDING.yml +0 -1
  58. package/.github/workflows/deploy-docs.yml +0 -56
  59. package/.pre-commit.sh +0 -15
  60. package/.snyk +0 -4
  61. package/Makefile +0 -25
  62. package/index.ts +0 -28
  63. package/src/api.ts +0 -36
  64. package/src/binding-post.ts +0 -336
  65. package/src/binding-redirect.ts +0 -335
  66. package/src/binding-simplesign.ts +0 -231
  67. package/src/entity-idp.ts +0 -145
  68. package/src/entity-sp.ts +0 -114
  69. package/src/entity.ts +0 -243
  70. package/src/extractor.ts +0 -399
  71. package/src/flow.ts +0 -469
  72. package/src/libsaml.ts +0 -777
  73. package/src/metadata-idp.ts +0 -146
  74. package/src/metadata-sp.ts +0 -203
  75. package/src/metadata.ts +0 -166
  76. package/src/types.ts +0 -127
  77. package/src/urn.ts +0 -210
  78. package/src/utility.ts +0 -231
  79. package/src/validator.ts +0 -44
  80. package/tsconfig.json +0 -41
  81. package/tslint.json +0 -35
  82. package/types.d.ts +0 -2
  83. package/vitest.config.ts +0 -12
package/src/libsaml.ts DELETED
@@ -1,777 +0,0 @@
1
- /**
2
- * @file SamlLib.js
3
- * @author tngan
4
- * @desc A simple library including some common functions
5
- */
6
-
7
- import utility, { flattenDeep, isString } from './utility';
8
- import { algorithms, wording, namespace } from './urn';
9
- import { select, SelectReturnType } from 'xpath';
10
-
11
- function toNodeArray(result: SelectReturnType): Node[] {
12
- if (Array.isArray(result)) return result;
13
- if (result != null && typeof result === 'object' && 'nodeType' in (result as object)) return [result as Node];
14
- return [];
15
- }
16
- import { MetadataInterface } from './metadata';
17
- import nrsa, { SigningSchemeHash } from 'node-rsa';
18
- import { SignedXml } from 'xml-crypto';
19
- import * as xmlenc from '@authenio/xml-encryption';
20
- import { extract } from './extractor';
21
- import camelCase from 'camelcase';
22
- import { getContext } from './api';
23
- import xmlEscape from 'xml-escape';
24
- import * as fs from 'fs';
25
- import {DOMParser} from '@xmldom/xmldom';
26
-
27
- const signatureAlgorithms = algorithms.signature;
28
- const digestAlgorithms = algorithms.digest;
29
- const certUse = wording.certUse;
30
- const urlParams = wording.urlParams;
31
-
32
- export interface SignatureConstructor {
33
- rawSamlMessage: string;
34
- referenceTagXPath?: string;
35
- privateKey: string;
36
- privateKeyPass?: string;
37
- signatureAlgorithm: string;
38
- signingCert: string | Buffer;
39
- isBase64Output?: boolean;
40
- signatureConfig?: any;
41
- isMessageSigned?: boolean;
42
- transformationAlgorithms?: string[];
43
- }
44
-
45
- export interface SignatureVerifierOptions {
46
- metadata?: MetadataInterface;
47
- keyFile?: string;
48
- signatureAlgorithm?: string;
49
- }
50
-
51
- export interface ExtractorResult {
52
- [key: string]: any;
53
- signature?: string | string[];
54
- issuer?: string | string[];
55
- nameID?: string;
56
- notexist?: boolean;
57
- }
58
-
59
- export interface LoginResponseAttribute {
60
- name: string;
61
- nameFormat: string; //
62
- valueXsiType: string; //
63
- valueTag: string;
64
- valueXmlnsXs?: string;
65
- valueXmlnsXsi?: string;
66
- }
67
-
68
- export interface LoginResponseAdditionalTemplates {
69
- attributeStatementTemplate?: AttributeStatementTemplate;
70
- attributeTemplate?: AttributeTemplate;
71
- }
72
-
73
- export interface BaseSamlTemplate {
74
- context: string;
75
- }
76
-
77
- export interface LoginResponseTemplate extends BaseSamlTemplate {
78
- attributes?: LoginResponseAttribute[];
79
- additionalTemplates?: LoginResponseAdditionalTemplates;
80
- }
81
- export interface AttributeStatementTemplate extends BaseSamlTemplate { }
82
-
83
- export interface AttributeTemplate extends BaseSamlTemplate { }
84
-
85
- export interface LoginRequestTemplate extends BaseSamlTemplate { }
86
-
87
- export interface LogoutRequestTemplate extends BaseSamlTemplate { }
88
-
89
- export interface LogoutResponseTemplate extends BaseSamlTemplate { }
90
-
91
- export type KeyUse = 'signing' | 'encryption';
92
-
93
- export interface KeyComponent {
94
- [key: string]: any;
95
- }
96
-
97
- export interface LibSamlInterface {
98
- getQueryParamByType: (type: string) => string;
99
- createXPath: (local, isExtractAll?: boolean) => string;
100
- replaceTagsByValue: (rawXML: string, tagValues: any) => string;
101
- attributeStatementBuilder: (attributes: LoginResponseAttribute[], attributeTemplate: AttributeTemplate, attributeStatementTemplate: AttributeStatementTemplate) => string;
102
- constructSAMLSignature: (opts: SignatureConstructor) => string;
103
- verifySignature: (xml: string, opts: SignatureVerifierOptions) => [boolean, any];
104
- createKeySection: (use: KeyUse, cert: string | Buffer) => {};
105
- constructMessageSignature: (octetString: string, key: string, passphrase?: string, isBase64?: boolean, signingAlgorithm?: string) => string;
106
-
107
- verifyMessageSignature: (metadata, octetString: string, signature: string | Buffer, verifyAlgorithm?: string) => boolean;
108
- getKeyInfo: (x509Certificate: string, signatureConfig?: any) => void;
109
- encryptAssertion: (sourceEntity, targetEntity, entireXML: string) => Promise<string>;
110
- decryptAssertion: (here, entireXML: string) => Promise<[string, any]>;
111
-
112
- getSigningScheme: (sigAlg: string) => string | null;
113
- getDigestMethod: (sigAlg: string) => string | null;
114
-
115
- nrsaAliasMapping: any;
116
- defaultLoginRequestTemplate: LoginRequestTemplate;
117
- defaultLoginResponseTemplate: LoginResponseTemplate;
118
- defaultAttributeStatementTemplate: AttributeStatementTemplate;
119
- defaultAttributeTemplate: AttributeTemplate;
120
- defaultLogoutRequestTemplate: LogoutRequestTemplate;
121
- defaultLogoutResponseTemplate: LogoutResponseTemplate;
122
- }
123
-
124
- const libSaml = () => {
125
-
126
- /**
127
- * @desc helper function to get back the query param for redirect binding for SLO/SSO
128
- * @type {string}
129
- */
130
- function getQueryParamByType(type: string) {
131
- if ([urlParams.logoutRequest, urlParams.samlRequest].indexOf(type) !== -1) {
132
- return 'SAMLRequest';
133
- }
134
- if ([urlParams.logoutResponse, urlParams.samlResponse].indexOf(type) !== -1) {
135
- return 'SAMLResponse';
136
- }
137
- throw new Error('ERR_UNDEFINED_QUERY_PARAMS');
138
- }
139
- /**
140
- *
141
- */
142
- const nrsaAliasMapping = {
143
- 'http://www.w3.org/2000/09/xmldsig#rsa-sha1': 'pkcs1-sha1',
144
- 'http://www.w3.org/2001/04/xmldsig-more#rsa-sha256': 'pkcs1-sha256',
145
- 'http://www.w3.org/2001/04/xmldsig-more#rsa-sha512': 'pkcs1-sha512',
146
- };
147
- /**
148
- * @desc Default login request template
149
- * @type {LoginRequestTemplate}
150
- */
151
- const defaultLoginRequestTemplate = {
152
- context: '<samlp:AuthnRequest 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="{IssueInstant}" Destination="{Destination}" ProtocolBinding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST" AssertionConsumerServiceURL="{AssertionConsumerServiceURL}"><saml:Issuer>{Issuer}</saml:Issuer><samlp:NameIDPolicy Format="{NameIDFormat}" AllowCreate="{AllowCreate}"/></samlp:AuthnRequest>',
153
- };
154
- /**
155
- * @desc Default logout request template
156
- * @type {LogoutRequestTemplate}
157
- */
158
- const defaultLogoutRequestTemplate = {
159
- context: '<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="{IssueInstant}" Destination="{Destination}"><saml:Issuer>{Issuer}</saml:Issuer><saml:NameID Format="{NameIDFormat}">{NameID}</saml:NameID></samlp:LogoutRequest>',
160
- };
161
-
162
- /**
163
- * @desc Default AttributeStatement template
164
- * @type {AttributeStatementTemplate}
165
- */
166
- const defaultAttributeStatementTemplate = {
167
- context: '<saml:AttributeStatement>{Attributes}</saml:AttributeStatement>',
168
- };
169
-
170
- /**
171
- * @desc Default Attribute template
172
- * @type {AttributeTemplate}
173
- */
174
- const defaultAttributeTemplate = {
175
- context: '<saml:Attribute Name="{Name}" NameFormat="{NameFormat}"><saml:AttributeValue xmlns:xs="{ValueXmlnsXs}" xmlns:xsi="{ValueXmlnsXsi}" xsi:type="{ValueXsiType}">{Value}</saml:AttributeValue></saml:Attribute>',
176
- };
177
-
178
- /**
179
- * @desc Default login response template
180
- * @type {LoginResponseTemplate}
181
- */
182
- const defaultLoginResponseTemplate = {
183
- context: '<samlp:Response 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="{IssueInstant}" Destination="{Destination}" InResponseTo="{InResponseTo}"><saml:Issuer>{Issuer}</saml:Issuer><samlp:Status><samlp:StatusCode Value="{StatusCode}"/></samlp:Status><saml:Assertion xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion" ID="{AssertionID}" Version="2.0" IssueInstant="{IssueInstant}"><saml:Issuer>{Issuer}</saml:Issuer><saml:Subject><saml:NameID Format="{NameIDFormat}">{NameID}</saml:NameID><saml:SubjectConfirmation Method="urn:oasis:names:tc:SAML:2.0:cm:bearer"><saml:SubjectConfirmationData NotOnOrAfter="{SubjectConfirmationDataNotOnOrAfter}" Recipient="{SubjectRecipient}" InResponseTo="{InResponseTo}"/></saml:SubjectConfirmation></saml:Subject><saml:Conditions NotBefore="{ConditionsNotBefore}" NotOnOrAfter="{ConditionsNotOnOrAfter}"><saml:AudienceRestriction><saml:Audience>{Audience}</saml:Audience></saml:AudienceRestriction></saml:Conditions>{AuthnStatement}{AttributeStatement}</saml:Assertion></samlp:Response>',
184
- attributes: [],
185
- additionalTemplates: {
186
- 'attributeStatementTemplate': defaultAttributeStatementTemplate,
187
- 'attributeTemplate': defaultAttributeTemplate
188
- }
189
- };
190
- /**
191
- * @desc Default logout response template
192
- * @type {LogoutResponseTemplate}
193
- */
194
- const defaultLogoutResponseTemplate = {
195
- context: '<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="{IssueInstant}" Destination="{Destination}" InResponseTo="{InResponseTo}"><saml:Issuer>{Issuer}</saml:Issuer><samlp:Status><samlp:StatusCode Value="{StatusCode}"/></samlp:Status></samlp:LogoutResponse>',
196
- };
197
- /**
198
- * @private
199
- * @desc Get the signing scheme alias by signature algorithms, used by the node-rsa module
200
- * @param {string} sigAlg signature algorithm
201
- * @return {string/null} signing algorithm short-hand for the module node-rsa
202
- */
203
- function getSigningScheme(sigAlg?: string): SigningSchemeHash {
204
- if (sigAlg) {
205
- const algAlias = nrsaAliasMapping[sigAlg];
206
- if (!(algAlias === undefined)) {
207
- return algAlias;
208
- }
209
- }
210
- return nrsaAliasMapping[signatureAlgorithms.RSA_SHA1];
211
- }
212
- /**
213
- * @private
214
- * @desc Get the digest algorithms by signature algorithms
215
- * @param {string} sigAlg signature algorithm
216
- * @return {string/undefined} digest algorithm
217
- */
218
- function getDigestMethod(sigAlg: string): string | undefined {
219
- return digestAlgorithms[sigAlg];
220
- }
221
- /**
222
- * @public
223
- * @desc Create XPath
224
- * @param {string/object} local parameters to create XPath
225
- * @param {boolean} isExtractAll define whether returns whole content according to the XPath
226
- * @return {string} xpath
227
- */
228
- function createXPath(local, isExtractAll?: boolean): string {
229
- if (isString(local)) {
230
- return isExtractAll === true ? "//*[local-name(.)='" + local + "']/text()" : "//*[local-name(.)='" + local + "']";
231
- }
232
- return "//*[local-name(.)='" + local.name + "']/@" + local.attr;
233
- }
234
-
235
- /**
236
- * @private
237
- * @desc Tag normalization
238
- * @param {string} prefix prefix of the tag
239
- * @param {content} content normalize it to capitalized camel case
240
- * @return {string}
241
- */
242
- function tagging(prefix: string, content: string): string {
243
- const camelContent = camelCase(content, {locale: 'en-us'});
244
- return prefix + camelContent.charAt(0).toUpperCase() + camelContent.slice(1);
245
- }
246
-
247
- function escapeTag(replacement: unknown): (...args: string[]) => string {
248
- return (_match: string, quote?: string) => {
249
- const text: string = (replacement === null || replacement === undefined) ? '' : String(replacement);
250
-
251
- // not having a quote means this interpolation isn't for an attribute, and so does not need escaping
252
- return quote ? `${quote}${xmlEscape(text)}` : text;
253
- }
254
- }
255
-
256
- return {
257
-
258
- createXPath,
259
- getQueryParamByType,
260
- defaultLoginRequestTemplate,
261
- defaultLoginResponseTemplate,
262
- defaultAttributeStatementTemplate,
263
- defaultAttributeTemplate,
264
- defaultLogoutRequestTemplate,
265
- defaultLogoutResponseTemplate,
266
-
267
- /**
268
- * @desc Replace the tag (e.g. {tag}) inside the raw XML
269
- * @param {string} rawXML raw XML string used to do keyword replacement
270
- * @param {array} tagValues tag values
271
- * @return {string}
272
- */
273
- replaceTagsByValue(rawXML: string, tagValues: Record<string, unknown>): string {
274
- Object.keys(tagValues).forEach(t => {
275
- rawXML = rawXML.replace(
276
- new RegExp(`("?)\\{${t}\\}`, 'g'),
277
- escapeTag(tagValues[t])
278
- );
279
- });
280
- return rawXML;
281
- },
282
- /**
283
- * @desc Helper function to build the AttributeStatement tag
284
- * @param {LoginResponseAttribute} attributes an array of attribute configuration
285
- * @param {AttributeTemplate} attributeTemplate the attribute tag template to be used
286
- * @param {AttributeStatementTemplate} attributeStatementTemplate the attributeStatement tag template to be used
287
- * @return {string}
288
- */
289
- attributeStatementBuilder(
290
- attributes: LoginResponseAttribute[],
291
- attributeTemplate: AttributeTemplate = defaultAttributeTemplate,
292
- attributeStatementTemplate: AttributeStatementTemplate = defaultAttributeStatementTemplate
293
- ): string {
294
- const attr = attributes.map(({ name, nameFormat, valueTag, valueXsiType, valueXmlnsXs, valueXmlnsXsi }) => {
295
- const defaultValueXmlnsXs = 'http://www.w3.org/2001/XMLSchema';
296
- const defaultValueXmlnsXsi = 'http://www.w3.org/2001/XMLSchema-instance';
297
- let attributeLine = attributeTemplate.context;
298
- attributeLine = attributeLine.replace('{Name}', name);
299
- attributeLine = attributeLine.replace('{NameFormat}', nameFormat);
300
- attributeLine = attributeLine.replace('{ValueXmlnsXs}', valueXmlnsXs ? valueXmlnsXs : defaultValueXmlnsXs);
301
- attributeLine = attributeLine.replace('{ValueXmlnsXsi}', valueXmlnsXsi ? valueXmlnsXsi : defaultValueXmlnsXsi);
302
- attributeLine = attributeLine.replace('{ValueXsiType}', valueXsiType);
303
- attributeLine = attributeLine.replace('{Value}', `{${tagging('attr', valueTag)}}`);
304
- return attributeLine;
305
- }).join('');
306
- return attributeStatementTemplate.context.replace('{Attributes}', attr);
307
- },
308
-
309
- /**
310
- * @desc Construct the XML signature for POST binding
311
- * @param {string} rawSamlMessage request/response xml string
312
- * @param {string} referenceTagXPath reference uri
313
- * @param {string} privateKey declares the private key
314
- * @param {string} passphrase passphrase of the private key [optional]
315
- * @param {string|buffer} signingCert signing certificate
316
- * @param {string} signatureAlgorithm signature algorithm
317
- * @param {string[]} transformationAlgorithms canonicalization and transformation Algorithms
318
- * @return {string} base64 encoded string
319
- */
320
- constructSAMLSignature(opts: SignatureConstructor) {
321
- const {
322
- rawSamlMessage,
323
- referenceTagXPath,
324
- privateKey,
325
- privateKeyPass,
326
- signatureAlgorithm = signatureAlgorithms.RSA_SHA256,
327
- transformationAlgorithms = [
328
- 'http://www.w3.org/2000/09/xmldsig#enveloped-signature',
329
- 'http://www.w3.org/2001/10/xml-exc-c14n#',
330
- ],
331
- signingCert,
332
- signatureConfig,
333
- isBase64Output = true,
334
- isMessageSigned = false,
335
- } = opts;
336
- const sig = new SignedXml();
337
- // Add assertion sections as reference
338
- const digestAlgorithm = getDigestMethod(signatureAlgorithm);
339
- if (referenceTagXPath) {
340
- sig.addReference({
341
- xpath: referenceTagXPath,
342
- transforms: transformationAlgorithms,
343
- digestAlgorithm: digestAlgorithm
344
- });
345
- }
346
- if (isMessageSigned) {
347
- sig.addReference({
348
- // reference to the root node
349
- xpath: '/*',
350
- transforms: transformationAlgorithms,
351
- digestAlgorithm
352
- });
353
- }
354
- sig.signatureAlgorithm = signatureAlgorithm;
355
- sig.publicCert = this.getKeyInfo(signingCert, signatureConfig).getKey();
356
- sig.getKeyInfoContent = this.getKeyInfo(signingCert, signatureConfig).getKeyInfo;
357
- sig.privateKey = utility.readPrivateKey(privateKey, privateKeyPass, true);
358
- sig.canonicalizationAlgorithm = 'http://www.w3.org/2001/10/xml-exc-c14n#';
359
-
360
- if (signatureConfig) {
361
- sig.computeSignature(rawSamlMessage, signatureConfig);
362
- } else {
363
- sig.computeSignature(rawSamlMessage);
364
- }
365
- return isBase64Output !== false ? utility.base64Encode(sig.getSignedXml()) : sig.getSignedXml();
366
- },
367
- /**
368
- * @desc Verify the XML signature
369
- * @param {string} xml xml
370
- * @param {SignatureVerifierOptions} opts cert declares the X509 certificate
371
- * @return {[boolean, string | null]} - A tuple where:
372
- * - The first element is `true` if the signature is valid, `false` otherwise.
373
- * - The second element is the cryptographically authenticated assertion node as a string, or `null` if not found.
374
- */
375
- verifySignature(xml: string, opts: SignatureVerifierOptions) : [boolean, string | null] {
376
- const { dom } = getContext();
377
- const doc = dom.parseFromString(xml);
378
-
379
- const docParser = new DOMParser();
380
- // In order to avoid the wrapping attack, we have changed to use absolute xpath instead of naively fetching the signature element
381
- // message signature (logout response / saml response)
382
- const messageSignatureXpath = "/*[contains(local-name(), 'Response') or contains(local-name(), 'Request')]/*[local-name(.)='Signature']";
383
- // assertion signature (logout response / saml response)
384
- const assertionSignatureXpath = "/*[contains(local-name(), 'Response') or contains(local-name(), 'Request')]/*[local-name(.)='Assertion']/*[local-name(.)='Signature']";
385
- // check if there is a potential malicious wrapping signature
386
- const wrappingElementsXPath = "/*[contains(local-name(), 'Response')]/*[local-name(.)='Assertion']/*[local-name(.)='Subject']/*[local-name(.)='SubjectConfirmation']/*[local-name(.)='SubjectConfirmationData']//*[local-name(.)='Assertion' or local-name(.)='Signature']";
387
-
388
- // select the signature node
389
- let selection: Node[] = [];
390
- const messageSignatureNode = toNodeArray(select(messageSignatureXpath, doc));
391
- const assertionSignatureNode = toNodeArray(select(assertionSignatureXpath, doc));
392
- const wrappingElementNode = toNodeArray(select(wrappingElementsXPath, doc));
393
-
394
- selection = selection.concat(messageSignatureNode);
395
- selection = selection.concat(assertionSignatureNode);
396
-
397
- // try to catch potential wrapping attack
398
- if (wrappingElementNode.length !== 0) {
399
- throw new Error('ERR_POTENTIAL_WRAPPING_ATTACK');
400
- }
401
-
402
- // guarantee to have a signature in saml response
403
- if (selection.length === 0) {
404
- return [false, null]; // we return false now
405
- }
406
-
407
- // need to refactor later on
408
- for (const signatureNode of selection){
409
- const sig = new SignedXml();
410
- let verified = false;
411
-
412
- sig.signatureAlgorithm = opts.signatureAlgorithm!;
413
-
414
- if (!opts.keyFile && !opts.metadata) {
415
- throw new Error('ERR_UNDEFINED_SIGNATURE_VERIFIER_OPTIONS');
416
- }
417
-
418
- if (opts.keyFile) {
419
- sig.publicCert = fs.readFileSync(opts.keyFile)
420
- }
421
-
422
- if (opts.metadata) {
423
-
424
- const certificateNode = toNodeArray(select(".//*[local-name(.)='X509Certificate']", signatureNode));
425
- // certificate in metadata
426
- let metadataCert: any = opts.metadata.getX509Certificate(certUse.signing);
427
- // flattens the nested array of Certificates from each KeyDescriptor
428
- if (Array.isArray(metadataCert)) {
429
- metadataCert = flattenDeep(metadataCert);
430
- } else if (typeof metadataCert === 'string') {
431
- metadataCert = [metadataCert];
432
- }
433
- // normalise the certificate string
434
- metadataCert = metadataCert.map(utility.normalizeCerString);
435
-
436
- // no certificate in node response nor metadata
437
- if (certificateNode.length === 0 && metadataCert.length === 0) {
438
- throw new Error('NO_SELECTED_CERTIFICATE');
439
- }
440
-
441
- // certificate node in response
442
- if (certificateNode.length !== 0) {
443
- const certEl = certificateNode[0] as Element;
444
- const x509CertificateData = certEl.textContent ?? '';
445
- const x509Certificate = utility.normalizeCerString(x509CertificateData);
446
-
447
- if (
448
- metadataCert.length >= 1 &&
449
- !metadataCert.find(cert => cert.trim() === x509Certificate.trim())
450
- ) {
451
- // keep this restriction for rolling certificate usage
452
- // to make sure the response certificate is one of those specified in metadata
453
- throw new Error('ERROR_UNMATCH_CERTIFICATE_DECLARATION_IN_METADATA');
454
- }
455
-
456
- sig.publicCert = this.getKeyInfo(x509Certificate).getKey();
457
-
458
- } else {
459
- // Select first one from metadata
460
- sig.publicCert = this.getKeyInfo(metadataCert[0]).getKey();
461
- }
462
- }
463
-
464
- sig.loadSignature(signatureNode);
465
-
466
- verified = sig.checkSignature(doc.toString());
467
-
468
- // immediately throw error when any one of the signature is failed to get verified
469
- if (!verified) {
470
- continue;
471
- // throw new Error('ERR_FAILED_TO_VERIFY_SIGNATURE');
472
- }
473
- // Require there to be at least one reference that was signed
474
- if (!(sig.getSignedReferences().length >= 1)) {
475
- throw new Error('NO_SIGNATURE_REFERENCES')
476
- }
477
- const signedVerifiedXML = sig.getSignedReferences()[0];
478
- const rootNode = docParser.parseFromString(signedVerifiedXML, 'text/xml').documentElement;
479
- // process the verified signature:
480
- // case 1, rootSignedDoc is a response:
481
- if (rootNode.localName === 'Response') {
482
- // try getting the Xml from the first assertion
483
- const assertions = toNodeArray(select(
484
- "./*[local-name()='Assertion']",
485
- rootNode
486
- ));
487
-
488
- const encryptedAssertions = toNodeArray(select(
489
- "./*[local-name()='EncryptedAssertion']",
490
- rootNode
491
- ));
492
- // now we can process the assertion as an assertion
493
- if (assertions.length === 1) {
494
- return [true, assertions[0].toString()];
495
- } else if (encryptedAssertions.length >= 1) {
496
- return [true, rootNode.toString()]; // we need to return a Response node, which will be decrypted later
497
- } else {
498
- // something has gone seriously wrong here.
499
- // we don't have any assertion to give back
500
- return [true, null]
501
- }
502
- } else if (rootNode.localName === 'Assertion') {
503
- return [true, rootNode.toString()];
504
- } else {
505
- return [true, null]; // signature is valid. But there is no assertion node here. It could be metadata node, hence return null
506
- }
507
- };
508
- return [false, null]; // we didn't verify anything, none of the signatures are valid
509
-
510
-
511
- /*
512
- // response must be signed, either entire document or assertion
513
- // default we will take the assertion section under root
514
- if (messageSignatureNode.length === 1) {
515
- const node = select("/*[contains(local-name(), 'Response') or contains(local-name(), 'Request')]/*[local-name(.)='Assertion']", doc);
516
- if (node.length === 1) {
517
- assertionNode = node[0].toString();
518
- }
519
- }
520
-
521
- if (assertionSignatureNode.length === 1) {
522
- const verifiedAssertionInfo = extract(assertionSignatureNode[0].toString(), [{
523
- key: 'refURI',
524
- localPath: ['Signature', 'SignedInfo', 'Reference'],
525
- attributes: ['URI']
526
- }]);
527
- // get the assertion supposed to be the one should be verified
528
- const desiredAssertionInfo = extract(doc.toString(), [{
529
- key: 'id',
530
- localPath: ['~Response', 'Assertion'],
531
- attributes: ['ID']
532
- }]);
533
- // 5.4.2 References
534
- // SAML assertions and protocol messages MUST supply a value for the ID attribute on the root element of
535
- // the assertion or protocol message being signed. The assertion’s or protocol message's root element may
536
- // or may not be the root element of the actual XML document containing the signed assertion or protocol
537
- // message (e.g., it might be contained within a SOAP envelope).
538
- // Signatures MUST contain a single <ds:Reference> containing a same-document reference to the ID
539
- // attribute value of the root element of the assertion or protocol message being signed. For example, if the
540
- // ID attribute value is "foo", then the URI attribute in the <ds:Reference> element MUST be "#foo".
541
- if (verifiedAssertionInfo.refURI !== `#${desiredAssertionInfo.id}`) {
542
- throw new Error('ERR_POTENTIAL_WRAPPING_ATTACK');
543
- }
544
- const verifiedDoc = extract(doc.toString(), [{
545
- key: 'assertion',
546
- localPath: ['~Response', 'Assertion'],
547
- attributes: [],
548
- context: true
549
- }]);
550
- assertionNode = verifiedDoc.assertion.toString();
551
- }
552
-
553
- return [verified, assertionNode];*/
554
- },
555
- /**
556
- * @desc Helper function to create the key section in metadata (abstraction for signing and encrypt use)
557
- * @param {string} use type of certificate (e.g. signing, encrypt)
558
- * @param {string} certString declares the certificate String
559
- * @return {object} object used in xml module
560
- */
561
- createKeySection(use: KeyUse, certString: string | Buffer): KeyComponent {
562
- return {
563
- ['KeyDescriptor']: [
564
- {
565
- _attr: { use },
566
- },
567
- {
568
- ['ds:KeyInfo']: [
569
- {
570
- _attr: {
571
- 'xmlns:ds': 'http://www.w3.org/2000/09/xmldsig#',
572
- },
573
- },
574
- {
575
- ['ds:X509Data']: [{
576
- 'ds:X509Certificate': utility.normalizeCerString(certString),
577
- }],
578
- },
579
- ],
580
- }],
581
- };
582
- },
583
- /**
584
- * @desc Constructs SAML message
585
- * @param {string} octetString see "Bindings for the OASIS Security Assertion Markup Language (SAML V2.0)" P.17/46
586
- * @param {string} key declares the pem-formatted private key
587
- * @param {string} passphrase passphrase of private key [optional]
588
- * @param {string} signingAlgorithm signing algorithm
589
- * @return {string} message signature
590
- */
591
- constructMessageSignature(
592
- octetString: string,
593
- key: string,
594
- passphrase?: string,
595
- isBase64?: boolean,
596
- signingAlgorithm?: string
597
- ) {
598
- // Default returning base64 encoded signature
599
- // Embed with node-rsa module
600
- const decryptedKey = new nrsa(
601
- utility.readPrivateKey(key, passphrase),
602
- undefined,
603
- {
604
- signingScheme: getSigningScheme(signingAlgorithm),
605
- }
606
- );
607
- const signature = decryptedKey.sign(octetString);
608
- // Use private key to sign data
609
- return isBase64 !== false ? signature.toString('base64') : signature;
610
- },
611
- /**
612
- * @desc Verifies message signature
613
- * @param {Metadata} metadata metadata object of identity provider or service provider
614
- * @param {string} octetString see "Bindings for the OASIS Security Assertion Markup Language (SAML V2.0)" P.17/46
615
- * @param {string} signature context of XML signature
616
- * @param {string} verifyAlgorithm algorithm used to verify
617
- * @return {boolean} verification result
618
- */
619
- verifyMessageSignature(
620
- metadata,
621
- octetString: string,
622
- signature: string | Buffer,
623
- verifyAlgorithm?: string
624
- ) {
625
- const signCert = metadata.getX509Certificate(certUse.signing);
626
- const signingScheme = getSigningScheme(verifyAlgorithm);
627
- const key = new nrsa(utility.getPublicKeyPemFromCertificate(signCert), 'public', { signingScheme });
628
- return key.verify(Buffer.from(octetString), Buffer.from(signature));
629
- },
630
- /**
631
- * @desc Get the public key in string format
632
- * @param {string} x509Certificate certificate
633
- * @return {string} public key
634
- */
635
- getKeyInfo(x509Certificate: string, signatureConfig: any = {}) {
636
- const prefix = signatureConfig.prefix ? `${signatureConfig.prefix}:` : '';
637
- return {
638
- getKeyInfo: () => {
639
- return `<${prefix}X509Data><${prefix}X509Certificate>${x509Certificate}</${prefix}X509Certificate></${prefix}X509Data>`;
640
- },
641
- getKey: () => {
642
- return utility.getPublicKeyPemFromCertificate(x509Certificate).toString();
643
- },
644
- };
645
- },
646
- /**
647
- * @desc Encrypt the assertion section in Response
648
- * @param {Entity} sourceEntity source entity
649
- * @param {Entity} targetEntity target entity
650
- * @param {string} xml response in xml string format
651
- * @return {Promise} a promise to resolve the finalized xml
652
- */
653
- encryptAssertion(sourceEntity, targetEntity, xml?: string) {
654
- // Implement encryption after signature if it has
655
- return new Promise<string>((resolve, reject) => {
656
-
657
- if (!xml) {
658
- return reject(new Error('ERR_UNDEFINED_ASSERTION'));
659
- }
660
-
661
- const sourceEntitySetting = sourceEntity.entitySetting;
662
- const targetEntityMetadata = targetEntity.entityMeta;
663
- const { dom } = getContext();
664
- const doc = dom.parseFromString(xml);
665
- const assertions = select("//*[local-name(.)='Assertion']", doc) as Node[];
666
- if (!Array.isArray(assertions) || assertions.length === 0) {
667
- throw new Error('ERR_NO_ASSERTION');
668
- }
669
- if (assertions.length > 1) {
670
- throw new Error('ERR_MULTIPLE_ASSERTION');
671
- }
672
- const rawAssertionNode = assertions[0];
673
-
674
- // Perform encryption depends on the setting, default is false
675
- if (sourceEntitySetting.isAssertionEncrypted) {
676
-
677
- const publicKeyPem = utility.getPublicKeyPemFromCertificate(targetEntityMetadata.getX509Certificate(certUse.encrypt));
678
-
679
- xmlenc.encrypt(rawAssertionNode.toString(), {
680
- // use xml-encryption module
681
- rsa_pub: Buffer.from(publicKeyPem), // public key from certificate
682
- pem: Buffer.from(`-----BEGIN CERTIFICATE-----${targetEntityMetadata.getX509Certificate(certUse.encrypt)}-----END CERTIFICATE-----`),
683
- encryptionAlgorithm: sourceEntitySetting.dataEncryptionAlgorithm,
684
- keyEncryptionAlgorithm: sourceEntitySetting.keyEncryptionAlgorithm,
685
- }, (err, res) => {
686
- if (err) {
687
- console.error(err);
688
- return reject(new Error('ERR_EXCEPTION_OF_ASSERTION_ENCRYPTION'));
689
- }
690
- if (!res) {
691
- return reject(new Error('ERR_UNDEFINED_ENCRYPTED_ASSERTION'));
692
- }
693
- const { encryptedAssertion: encAssertionPrefix } = sourceEntitySetting.tagPrefix;
694
- const encryptAssertionDoc = dom.parseFromString(`<${encAssertionPrefix}:EncryptedAssertion xmlns:${encAssertionPrefix}="${namespace.names.assertion}">${res}</${encAssertionPrefix}:EncryptedAssertion>`);
695
- doc.documentElement.replaceChild(encryptAssertionDoc.documentElement, rawAssertionNode);
696
- return resolve(utility.base64Encode(doc.toString()));
697
- });
698
- } else {
699
- return resolve(utility.base64Encode(xml)); // No need to do encryption
700
- }
701
- });
702
- },
703
- /**
704
- * @desc Decrypt the assertion section in Response
705
- * @param {string} type only accept SAMLResponse to proceed decryption
706
- * @param {Entity} here this entity
707
- * @param {Entity} from from the entity where the message is sent
708
- * @param {string} entireXML response in xml string format
709
- * @return {function} a promise to get back the entire xml with decrypted assertion
710
- */
711
- decryptAssertion(here, entireXML: string) {
712
- return new Promise<[string, any]>((resolve, reject) => {
713
- // Implement decryption first then check the signature
714
- if (!entireXML) {
715
- return reject(new Error('ERR_UNDEFINED_ASSERTION'));
716
- }
717
- // Perform encryption depends on the setting of where the message is sent, default is false
718
- const hereSetting = here.entitySetting;
719
- const { dom } = getContext();
720
- const doc = dom.parseFromString(entireXML);
721
- const encryptedAssertions = select("/*[contains(local-name(), 'Response')]/*[local-name(.)='EncryptedAssertion']", doc) as Node[];
722
- if (!Array.isArray(encryptedAssertions) || encryptedAssertions.length === 0) {
723
- throw new Error('ERR_UNDEFINED_ENCRYPTED_ASSERTION');
724
- }
725
- if (encryptedAssertions.length > 1) {
726
- throw new Error('ERR_MULTIPLE_ASSERTION');
727
- }
728
- const encAssertionNode = encryptedAssertions[0];
729
-
730
- return xmlenc.decrypt(encAssertionNode.toString(), {
731
- key: utility.readPrivateKey(hereSetting.encPrivateKey, hereSetting.encPrivateKeyPass),
732
- }, (err, res) => {
733
- if (err) {
734
- console.error(err);
735
- return reject(new Error('ERR_EXCEPTION_OF_ASSERTION_DECRYPTION'));
736
- }
737
- if (!res) {
738
- return reject(new Error('ERR_UNDEFINED_ENCRYPTED_ASSERTION'));
739
- }
740
- const rawAssertionDoc = dom.parseFromString(res);
741
- doc.documentElement.replaceChild(rawAssertionDoc.documentElement, encAssertionNode);
742
- return resolve([doc.toString(), res]);
743
- });
744
- });
745
- },
746
- /**
747
- * @desc Check if the xml string is valid and bounded
748
- */
749
- async isValidXml(input: string) {
750
-
751
- // check if global api contains the validate function
752
- const { validate } = getContext();
753
-
754
- /**
755
- * user can write a validate function that always returns
756
- * a resolved promise and skip the validator even in
757
- * production, user will take the responsibility if
758
- * they intend to skip the validation
759
- */
760
- if (!validate) {
761
-
762
- // otherwise, an error will be thrown
763
- return Promise.reject('Your application is potentially vulnerable because no validation function found. Please read the documentation on how to setup the validator. (https://github.com/tngan/samlify#installation)');
764
-
765
- }
766
-
767
- try {
768
- return await validate(input);
769
- } catch (e) {
770
- throw e;
771
- }
772
-
773
- },
774
- };
775
- };
776
-
777
- export default libSaml();