samlify 2.12.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 (84) hide show
  1. package/README.md +1 -1
  2. package/build/src/api.js +41 -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 +118 -151
  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 +315 -259
  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 +140 -85
  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 +16 -5
  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 +139 -90
  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/samlify-2.11.0.tgz +0 -0
  64. package/src/api.ts +0 -48
  65. package/src/binding-post.ts +0 -336
  66. package/src/binding-redirect.ts +0 -335
  67. package/src/binding-simplesign.ts +0 -231
  68. package/src/entity-idp.ts +0 -145
  69. package/src/entity-sp.ts +0 -114
  70. package/src/entity.ts +0 -243
  71. package/src/extractor.ts +0 -399
  72. package/src/flow.ts +0 -469
  73. package/src/libsaml.ts +0 -779
  74. package/src/metadata-idp.ts +0 -146
  75. package/src/metadata-sp.ts +0 -203
  76. package/src/metadata.ts +0 -166
  77. package/src/types.ts +0 -127
  78. package/src/urn.ts +0 -210
  79. package/src/utility.ts +0 -259
  80. package/src/validator.ts +0 -44
  81. package/tsconfig.json +0 -41
  82. package/tslint.json +0 -35
  83. package/types.d.ts +0 -2
  84. package/vitest.config.ts +0 -12
package/src/libsaml.ts DELETED
@@ -1,779 +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, escapeXPathValue } 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 './utility';
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
- const escaped = escapeXPathValue(local);
231
- return isExtractAll === true ? "//*[local-name(.)=" + escaped + "]/text()" : "//*[local-name(.)=" + escaped + "]";
232
- }
233
- return "//*[local-name(.)=" + escapeXPathValue(local.name) + "]/@" + local.attr;
234
- }
235
-
236
- /**
237
- * @private
238
- * @desc Tag normalization
239
- * @param {string} prefix prefix of the tag
240
- * @param {content} content normalize it to capitalized camel case
241
- * @return {string}
242
- */
243
- function tagging(prefix: string, content: string): string {
244
- const camelContent = camelCase(content);
245
- return prefix + camelContent.charAt(0).toUpperCase() + camelContent.slice(1);
246
- }
247
-
248
- function escapeTag(replacement: unknown): (...args: string[]) => string {
249
- return (_match: string, quote?: string) => {
250
- const text: string = (replacement === null || replacement === undefined) ? '' : String(replacement);
251
-
252
- // not having a quote means this interpolation isn't for an attribute, and so does not need escaping
253
- return quote ? `${quote}${xmlEscape(text)}` : text;
254
- }
255
- }
256
-
257
- return {
258
-
259
- createXPath,
260
- getQueryParamByType,
261
- defaultLoginRequestTemplate,
262
- defaultLoginResponseTemplate,
263
- defaultAttributeStatementTemplate,
264
- defaultAttributeTemplate,
265
- defaultLogoutRequestTemplate,
266
- defaultLogoutResponseTemplate,
267
-
268
- /**
269
- * @desc Replace the tag (e.g. {tag}) inside the raw XML
270
- * @param {string} rawXML raw XML string used to do keyword replacement
271
- * @param {array} tagValues tag values
272
- * @return {string}
273
- */
274
- replaceTagsByValue(rawXML: string, tagValues: Record<string, unknown>): string {
275
- Object.keys(tagValues).forEach(t => {
276
- rawXML = rawXML.replace(
277
- new RegExp(`("?)\\{${t}\\}`, 'g'),
278
- escapeTag(tagValues[t])
279
- );
280
- });
281
- return rawXML;
282
- },
283
- /**
284
- * @desc Helper function to build the AttributeStatement tag
285
- * @param {LoginResponseAttribute} attributes an array of attribute configuration
286
- * @param {AttributeTemplate} attributeTemplate the attribute tag template to be used
287
- * @param {AttributeStatementTemplate} attributeStatementTemplate the attributeStatement tag template to be used
288
- * @return {string}
289
- */
290
- attributeStatementBuilder(
291
- attributes: LoginResponseAttribute[],
292
- attributeTemplate: AttributeTemplate = defaultAttributeTemplate,
293
- attributeStatementTemplate: AttributeStatementTemplate = defaultAttributeStatementTemplate
294
- ): string {
295
- const attr = attributes.map(({ name, nameFormat, valueTag, valueXsiType, valueXmlnsXs, valueXmlnsXsi }) => {
296
- const defaultValueXmlnsXs = 'http://www.w3.org/2001/XMLSchema';
297
- const defaultValueXmlnsXsi = 'http://www.w3.org/2001/XMLSchema-instance';
298
- let attributeLine = attributeTemplate.context;
299
- attributeLine = attributeLine.replace('{Name}', name);
300
- attributeLine = attributeLine.replace('{NameFormat}', nameFormat);
301
- attributeLine = attributeLine.replace('{ValueXmlnsXs}', valueXmlnsXs ? valueXmlnsXs : defaultValueXmlnsXs);
302
- attributeLine = attributeLine.replace('{ValueXmlnsXsi}', valueXmlnsXsi ? valueXmlnsXsi : defaultValueXmlnsXsi);
303
- attributeLine = attributeLine.replace('{ValueXsiType}', valueXsiType);
304
- attributeLine = attributeLine.replace('{Value}', `{${tagging('attr', valueTag)}}`);
305
- return attributeLine;
306
- }).join('');
307
- return attributeStatementTemplate.context.replace('{Attributes}', attr);
308
- },
309
-
310
- /**
311
- * @desc Construct the XML signature for POST binding
312
- * @param {string} rawSamlMessage request/response xml string
313
- * @param {string} referenceTagXPath reference uri
314
- * @param {string} privateKey declares the private key
315
- * @param {string} passphrase passphrase of the private key [optional]
316
- * @param {string|buffer} signingCert signing certificate
317
- * @param {string} signatureAlgorithm signature algorithm
318
- * @param {string[]} transformationAlgorithms canonicalization and transformation Algorithms
319
- * @return {string} base64 encoded string
320
- */
321
- constructSAMLSignature(opts: SignatureConstructor) {
322
- const {
323
- rawSamlMessage,
324
- referenceTagXPath,
325
- privateKey,
326
- privateKeyPass,
327
- signatureAlgorithm = signatureAlgorithms.RSA_SHA256,
328
- transformationAlgorithms = [
329
- 'http://www.w3.org/2000/09/xmldsig#enveloped-signature',
330
- 'http://www.w3.org/2001/10/xml-exc-c14n#',
331
- ],
332
- signingCert,
333
- signatureConfig,
334
- isBase64Output = true,
335
- isMessageSigned = false,
336
- } = opts;
337
- const sig = new SignedXml();
338
- // Add assertion sections as reference
339
- const digestAlgorithm = getDigestMethod(signatureAlgorithm);
340
- if (referenceTagXPath) {
341
- sig.addReference({
342
- xpath: referenceTagXPath,
343
- transforms: transformationAlgorithms,
344
- digestAlgorithm: digestAlgorithm
345
- });
346
- }
347
- if (isMessageSigned) {
348
- sig.addReference({
349
- // reference to the root node
350
- xpath: '/*',
351
- transforms: transformationAlgorithms,
352
- digestAlgorithm
353
- });
354
- }
355
- sig.signatureAlgorithm = signatureAlgorithm;
356
- sig.publicCert = this.getKeyInfo(signingCert, signatureConfig).getKey();
357
- sig.getKeyInfoContent = this.getKeyInfo(signingCert, signatureConfig).getKeyInfo;
358
- sig.privateKey = utility.readPrivateKey(privateKey, privateKeyPass, true);
359
- sig.canonicalizationAlgorithm = 'http://www.w3.org/2001/10/xml-exc-c14n#';
360
-
361
- if (signatureConfig) {
362
- sig.computeSignature(rawSamlMessage, signatureConfig);
363
- } else {
364
- sig.computeSignature(rawSamlMessage);
365
- }
366
- return isBase64Output !== false ? utility.base64Encode(sig.getSignedXml()) : sig.getSignedXml();
367
- },
368
- /**
369
- * @desc Verify the XML signature
370
- * @param {string} xml xml
371
- * @param {SignatureVerifierOptions} opts cert declares the X509 certificate
372
- * @return {[boolean, string | null]} - A tuple where:
373
- * - The first element is `true` if the signature is valid, `false` otherwise.
374
- * - The second element is the cryptographically authenticated assertion node as a string, or `null` if not found.
375
- */
376
- verifySignature(xml: string, opts: SignatureVerifierOptions) : [boolean, string | null] {
377
- const { dom } = getContext();
378
- const doc = dom.parseFromString(xml);
379
-
380
- const { dom: contextDom } = getContext();
381
- const docParser = contextDom;
382
- // In order to avoid the wrapping attack, we have changed to use absolute xpath instead of naively fetching the signature element
383
- // message signature (logout response / saml response)
384
- const messageSignatureXpath = "/*[contains(local-name(), 'Response') or contains(local-name(), 'Request')]/*[local-name(.)='Signature']";
385
- // assertion signature (logout response / saml response)
386
- const assertionSignatureXpath = "/*[contains(local-name(), 'Response') or contains(local-name(), 'Request')]/*[local-name(.)='Assertion']/*[local-name(.)='Signature']";
387
- // check if there is a potential malicious wrapping signature
388
- 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']";
389
-
390
- // select the signature node
391
- let selection: Node[] = [];
392
- const messageSignatureNode = toNodeArray(select(messageSignatureXpath, doc));
393
- const assertionSignatureNode = toNodeArray(select(assertionSignatureXpath, doc));
394
- const wrappingElementNode = toNodeArray(select(wrappingElementsXPath, doc));
395
-
396
- selection = selection.concat(messageSignatureNode);
397
- selection = selection.concat(assertionSignatureNode);
398
-
399
- // try to catch potential wrapping attack
400
- if (wrappingElementNode.length !== 0) {
401
- throw new Error('ERR_POTENTIAL_WRAPPING_ATTACK');
402
- }
403
-
404
- // guarantee to have a signature in saml response
405
- if (selection.length === 0) {
406
- return [false, null]; // we return false now
407
- }
408
-
409
- // need to refactor later on
410
- for (const signatureNode of selection){
411
- const sig = new SignedXml();
412
- let verified = false;
413
-
414
- sig.signatureAlgorithm = opts.signatureAlgorithm!;
415
-
416
- if (!opts.keyFile && !opts.metadata) {
417
- throw new Error('ERR_UNDEFINED_SIGNATURE_VERIFIER_OPTIONS');
418
- }
419
-
420
- if (opts.keyFile) {
421
- sig.publicCert = fs.readFileSync(opts.keyFile)
422
- }
423
-
424
- if (opts.metadata) {
425
-
426
- const certificateNode = toNodeArray(select(".//*[local-name(.)='X509Certificate']", signatureNode));
427
- // certificate in metadata
428
- let metadataCert: any = opts.metadata.getX509Certificate(certUse.signing);
429
- // flattens the nested array of Certificates from each KeyDescriptor
430
- if (Array.isArray(metadataCert)) {
431
- metadataCert = flattenDeep(metadataCert);
432
- } else if (typeof metadataCert === 'string') {
433
- metadataCert = [metadataCert];
434
- }
435
- // normalise the certificate string
436
- metadataCert = metadataCert.map(utility.normalizeCerString);
437
-
438
- // no certificate in node response nor metadata
439
- if (certificateNode.length === 0 && metadataCert.length === 0) {
440
- throw new Error('NO_SELECTED_CERTIFICATE');
441
- }
442
-
443
- // certificate node in response
444
- if (certificateNode.length !== 0) {
445
- const certEl = certificateNode[0] as Element;
446
- const x509CertificateData = certEl.textContent ?? '';
447
- const x509Certificate = utility.normalizeCerString(x509CertificateData);
448
-
449
- if (
450
- metadataCert.length >= 1 &&
451
- !metadataCert.find(cert => cert.trim() === x509Certificate.trim())
452
- ) {
453
- // keep this restriction for rolling certificate usage
454
- // to make sure the response certificate is one of those specified in metadata
455
- throw new Error('ERROR_UNMATCH_CERTIFICATE_DECLARATION_IN_METADATA');
456
- }
457
-
458
- sig.publicCert = this.getKeyInfo(x509Certificate).getKey();
459
-
460
- } else {
461
- // Select first one from metadata
462
- sig.publicCert = this.getKeyInfo(metadataCert[0]).getKey();
463
- }
464
- }
465
-
466
- sig.loadSignature(signatureNode);
467
-
468
- verified = sig.checkSignature(doc.toString());
469
-
470
- // immediately throw error when any one of the signature is failed to get verified
471
- if (!verified) {
472
- continue;
473
- // throw new Error('ERR_FAILED_TO_VERIFY_SIGNATURE');
474
- }
475
- // Require there to be at least one reference that was signed
476
- if (!(sig.getSignedReferences().length >= 1)) {
477
- throw new Error('NO_SIGNATURE_REFERENCES')
478
- }
479
- const signedVerifiedXML = sig.getSignedReferences()[0];
480
- const rootNode = docParser.parseFromString(signedVerifiedXML, 'text/xml').documentElement;
481
- // process the verified signature:
482
- // case 1, rootSignedDoc is a response:
483
- if (rootNode.localName === 'Response') {
484
- // try getting the Xml from the first assertion
485
- const assertions = toNodeArray(select(
486
- "./*[local-name()='Assertion']",
487
- rootNode
488
- ));
489
-
490
- const encryptedAssertions = toNodeArray(select(
491
- "./*[local-name()='EncryptedAssertion']",
492
- rootNode
493
- ));
494
- // now we can process the assertion as an assertion
495
- if (assertions.length === 1) {
496
- return [true, assertions[0].toString()];
497
- } else if (encryptedAssertions.length >= 1) {
498
- return [true, rootNode.toString()]; // we need to return a Response node, which will be decrypted later
499
- } else {
500
- // something has gone seriously wrong here.
501
- // we don't have any assertion to give back
502
- return [true, null]
503
- }
504
- } else if (rootNode.localName === 'Assertion') {
505
- return [true, rootNode.toString()];
506
- } else {
507
- return [true, null]; // signature is valid. But there is no assertion node here. It could be metadata node, hence return null
508
- }
509
- };
510
- return [false, null]; // we didn't verify anything, none of the signatures are valid
511
-
512
-
513
- /*
514
- // response must be signed, either entire document or assertion
515
- // default we will take the assertion section under root
516
- if (messageSignatureNode.length === 1) {
517
- const node = select("/*[contains(local-name(), 'Response') or contains(local-name(), 'Request')]/*[local-name(.)='Assertion']", doc);
518
- if (node.length === 1) {
519
- assertionNode = node[0].toString();
520
- }
521
- }
522
-
523
- if (assertionSignatureNode.length === 1) {
524
- const verifiedAssertionInfo = extract(assertionSignatureNode[0].toString(), [{
525
- key: 'refURI',
526
- localPath: ['Signature', 'SignedInfo', 'Reference'],
527
- attributes: ['URI']
528
- }]);
529
- // get the assertion supposed to be the one should be verified
530
- const desiredAssertionInfo = extract(doc.toString(), [{
531
- key: 'id',
532
- localPath: ['~Response', 'Assertion'],
533
- attributes: ['ID']
534
- }]);
535
- // 5.4.2 References
536
- // SAML assertions and protocol messages MUST supply a value for the ID attribute on the root element of
537
- // the assertion or protocol message being signed. The assertion’s or protocol message's root element may
538
- // or may not be the root element of the actual XML document containing the signed assertion or protocol
539
- // message (e.g., it might be contained within a SOAP envelope).
540
- // Signatures MUST contain a single <ds:Reference> containing a same-document reference to the ID
541
- // attribute value of the root element of the assertion or protocol message being signed. For example, if the
542
- // ID attribute value is "foo", then the URI attribute in the <ds:Reference> element MUST be "#foo".
543
- if (verifiedAssertionInfo.refURI !== `#${desiredAssertionInfo.id}`) {
544
- throw new Error('ERR_POTENTIAL_WRAPPING_ATTACK');
545
- }
546
- const verifiedDoc = extract(doc.toString(), [{
547
- key: 'assertion',
548
- localPath: ['~Response', 'Assertion'],
549
- attributes: [],
550
- context: true
551
- }]);
552
- assertionNode = verifiedDoc.assertion.toString();
553
- }
554
-
555
- return [verified, assertionNode];*/
556
- },
557
- /**
558
- * @desc Helper function to create the key section in metadata (abstraction for signing and encrypt use)
559
- * @param {string} use type of certificate (e.g. signing, encrypt)
560
- * @param {string} certString declares the certificate String
561
- * @return {object} object used in xml module
562
- */
563
- createKeySection(use: KeyUse, certString: string | Buffer): KeyComponent {
564
- return {
565
- ['KeyDescriptor']: [
566
- {
567
- _attr: { use },
568
- },
569
- {
570
- ['ds:KeyInfo']: [
571
- {
572
- _attr: {
573
- 'xmlns:ds': 'http://www.w3.org/2000/09/xmldsig#',
574
- },
575
- },
576
- {
577
- ['ds:X509Data']: [{
578
- 'ds:X509Certificate': utility.normalizeCerString(certString),
579
- }],
580
- },
581
- ],
582
- }],
583
- };
584
- },
585
- /**
586
- * @desc Constructs SAML message
587
- * @param {string} octetString see "Bindings for the OASIS Security Assertion Markup Language (SAML V2.0)" P.17/46
588
- * @param {string} key declares the pem-formatted private key
589
- * @param {string} passphrase passphrase of private key [optional]
590
- * @param {string} signingAlgorithm signing algorithm
591
- * @return {string} message signature
592
- */
593
- constructMessageSignature(
594
- octetString: string,
595
- key: string,
596
- passphrase?: string,
597
- isBase64?: boolean,
598
- signingAlgorithm?: string
599
- ) {
600
- // Default returning base64 encoded signature
601
- // Embed with node-rsa module
602
- const decryptedKey = new nrsa(
603
- utility.readPrivateKey(key, passphrase),
604
- undefined,
605
- {
606
- signingScheme: getSigningScheme(signingAlgorithm),
607
- }
608
- );
609
- const signature = decryptedKey.sign(octetString);
610
- // Use private key to sign data
611
- return isBase64 !== false ? signature.toString('base64') : signature;
612
- },
613
- /**
614
- * @desc Verifies message signature
615
- * @param {Metadata} metadata metadata object of identity provider or service provider
616
- * @param {string} octetString see "Bindings for the OASIS Security Assertion Markup Language (SAML V2.0)" P.17/46
617
- * @param {string} signature context of XML signature
618
- * @param {string} verifyAlgorithm algorithm used to verify
619
- * @return {boolean} verification result
620
- */
621
- verifyMessageSignature(
622
- metadata,
623
- octetString: string,
624
- signature: string | Buffer,
625
- verifyAlgorithm?: string
626
- ) {
627
- const signCert = metadata.getX509Certificate(certUse.signing);
628
- const signingScheme = getSigningScheme(verifyAlgorithm);
629
- const key = new nrsa(utility.getPublicKeyPemFromCertificate(signCert), 'public', { signingScheme });
630
- return key.verify(Buffer.from(octetString), Buffer.from(signature));
631
- },
632
- /**
633
- * @desc Get the public key in string format
634
- * @param {string} x509Certificate certificate
635
- * @return {string} public key
636
- */
637
- getKeyInfo(x509Certificate: string, signatureConfig: any = {}) {
638
- const prefix = signatureConfig.prefix ? `${signatureConfig.prefix}:` : '';
639
- return {
640
- getKeyInfo: () => {
641
- return `<${prefix}X509Data><${prefix}X509Certificate>${x509Certificate}</${prefix}X509Certificate></${prefix}X509Data>`;
642
- },
643
- getKey: () => {
644
- return utility.getPublicKeyPemFromCertificate(x509Certificate).toString();
645
- },
646
- };
647
- },
648
- /**
649
- * @desc Encrypt the assertion section in Response
650
- * @param {Entity} sourceEntity source entity
651
- * @param {Entity} targetEntity target entity
652
- * @param {string} xml response in xml string format
653
- * @return {Promise} a promise to resolve the finalized xml
654
- */
655
- encryptAssertion(sourceEntity, targetEntity, xml?: string) {
656
- // Implement encryption after signature if it has
657
- return new Promise<string>((resolve, reject) => {
658
-
659
- if (!xml) {
660
- return reject(new Error('ERR_UNDEFINED_ASSERTION'));
661
- }
662
-
663
- const sourceEntitySetting = sourceEntity.entitySetting;
664
- const targetEntityMetadata = targetEntity.entityMeta;
665
- const { dom } = getContext();
666
- const doc = dom.parseFromString(xml);
667
- const assertions = select("//*[local-name(.)='Assertion']", doc) as Node[];
668
- if (!Array.isArray(assertions) || assertions.length === 0) {
669
- throw new Error('ERR_NO_ASSERTION');
670
- }
671
- if (assertions.length > 1) {
672
- throw new Error('ERR_MULTIPLE_ASSERTION');
673
- }
674
- const rawAssertionNode = assertions[0];
675
-
676
- // Perform encryption depends on the setting, default is false
677
- if (sourceEntitySetting.isAssertionEncrypted) {
678
-
679
- const publicKeyPem = utility.getPublicKeyPemFromCertificate(targetEntityMetadata.getX509Certificate(certUse.encrypt));
680
-
681
- xmlenc.encrypt(rawAssertionNode.toString(), {
682
- // use xml-encryption module
683
- rsa_pub: Buffer.from(publicKeyPem), // public key from certificate
684
- pem: Buffer.from(`-----BEGIN CERTIFICATE-----${targetEntityMetadata.getX509Certificate(certUse.encrypt)}-----END CERTIFICATE-----`),
685
- encryptionAlgorithm: sourceEntitySetting.dataEncryptionAlgorithm,
686
- keyEncryptionAlgorithm: sourceEntitySetting.keyEncryptionAlgorithm,
687
- }, (err, res) => {
688
- if (err) {
689
- console.error(err);
690
- return reject(new Error('ERR_EXCEPTION_OF_ASSERTION_ENCRYPTION'));
691
- }
692
- if (!res) {
693
- return reject(new Error('ERR_UNDEFINED_ENCRYPTED_ASSERTION'));
694
- }
695
- const { encryptedAssertion: encAssertionPrefix } = sourceEntitySetting.tagPrefix;
696
- const encryptAssertionDoc = dom.parseFromString(`<${encAssertionPrefix}:EncryptedAssertion xmlns:${encAssertionPrefix}="${namespace.names.assertion}">${res}</${encAssertionPrefix}:EncryptedAssertion>`);
697
- doc.documentElement.replaceChild(encryptAssertionDoc.documentElement, rawAssertionNode);
698
- return resolve(utility.base64Encode(doc.toString()));
699
- });
700
- } else {
701
- return resolve(utility.base64Encode(xml)); // No need to do encryption
702
- }
703
- });
704
- },
705
- /**
706
- * @desc Decrypt the assertion section in Response
707
- * @param {string} type only accept SAMLResponse to proceed decryption
708
- * @param {Entity} here this entity
709
- * @param {Entity} from from the entity where the message is sent
710
- * @param {string} entireXML response in xml string format
711
- * @return {function} a promise to get back the entire xml with decrypted assertion
712
- */
713
- decryptAssertion(here, entireXML: string) {
714
- return new Promise<[string, any]>((resolve, reject) => {
715
- // Implement decryption first then check the signature
716
- if (!entireXML) {
717
- return reject(new Error('ERR_UNDEFINED_ASSERTION'));
718
- }
719
- // Perform encryption depends on the setting of where the message is sent, default is false
720
- const hereSetting = here.entitySetting;
721
- const { dom } = getContext();
722
- const doc = dom.parseFromString(entireXML);
723
- const encryptedAssertions = select("/*[contains(local-name(), 'Response')]/*[local-name(.)='EncryptedAssertion']", doc) as Node[];
724
- if (!Array.isArray(encryptedAssertions) || encryptedAssertions.length === 0) {
725
- throw new Error('ERR_UNDEFINED_ENCRYPTED_ASSERTION');
726
- }
727
- if (encryptedAssertions.length > 1) {
728
- throw new Error('ERR_MULTIPLE_ASSERTION');
729
- }
730
- const encAssertionNode = encryptedAssertions[0];
731
-
732
- return xmlenc.decrypt(encAssertionNode.toString(), {
733
- key: utility.readPrivateKey(hereSetting.encPrivateKey, hereSetting.encPrivateKeyPass),
734
- }, (err, res) => {
735
- if (err) {
736
- console.error(err);
737
- return reject(new Error('ERR_EXCEPTION_OF_ASSERTION_DECRYPTION'));
738
- }
739
- if (!res) {
740
- return reject(new Error('ERR_UNDEFINED_ENCRYPTED_ASSERTION'));
741
- }
742
- const rawAssertionDoc = dom.parseFromString(res);
743
- doc.documentElement.replaceChild(rawAssertionDoc.documentElement, encAssertionNode);
744
- return resolve([doc.toString(), res]);
745
- });
746
- });
747
- },
748
- /**
749
- * @desc Check if the xml string is valid and bounded
750
- */
751
- async isValidXml(input: string) {
752
-
753
- // check if global api contains the validate function
754
- const { validate } = getContext();
755
-
756
- /**
757
- * user can write a validate function that always returns
758
- * a resolved promise and skip the validator even in
759
- * production, user will take the responsibility if
760
- * they intend to skip the validation
761
- */
762
- if (!validate) {
763
-
764
- // otherwise, an error will be thrown
765
- 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)');
766
-
767
- }
768
-
769
- try {
770
- return await validate(input);
771
- } catch (e) {
772
- throw e;
773
- }
774
-
775
- },
776
- };
777
- };
778
-
779
- export default libSaml();