-
Notifications
You must be signed in to change notification settings - Fork 176
/
Copy pathsigned-xml.ts
1095 lines (958 loc) · 38 KB
/
signed-xml.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 type {
CanonicalizationAlgorithmType,
CanonicalizationOrTransformationAlgorithm,
ComputeSignatureOptions,
GetKeyInfoContentArgs,
HashAlgorithm,
HashAlgorithmType,
Reference,
SignatureAlgorithm,
SignatureAlgorithmType,
SignedXmlOptions,
CanonicalizationOrTransformAlgorithmType,
ErrorFirstCallback,
CanonicalizationOrTransformationAlgorithmProcessOptions,
} from "./types";
import * as xpath from "xpath";
import * as xmldom from "@xmldom/xmldom";
import * as utils from "./utils";
import * as c14n from "./c14n-canonicalization";
import * as execC14n from "./exclusive-canonicalization";
import * as envelopedSignatures from "./enveloped-signature";
import * as hashAlgorithms from "./hash-algorithms";
import * as signatureAlgorithms from "./signature-algorithms";
import * as crypto from "crypto";
export class SignedXml {
idMode?: "wssecurity";
idAttributes: string[];
/**
* A {@link Buffer} or pem encoded {@link String} containing your private key
*/
privateKey?: crypto.KeyLike;
publicCert?: crypto.KeyLike;
/**
* One of the supported signature algorithms.
* @see {@link SignatureAlgorithmType}
*/
signatureAlgorithm: SignatureAlgorithmType = "http://www.w3.org/2000/09/xmldsig#rsa-sha1";
/**
* Rules used to convert an XML document into its canonical form.
*/
canonicalizationAlgorithm: CanonicalizationAlgorithmType =
"http://www.w3.org/2001/10/xml-exc-c14n#";
/**
* It specifies a list of namespace prefixes that should be considered "inclusive" during the canonicalization process.
*/
inclusiveNamespacesPrefixList: string[] = [];
namespaceResolver: XPathNSResolver = {
lookupNamespaceURI: function (/* prefix */) {
throw new Error("Not implemented");
},
};
implicitTransforms: ReadonlyArray<CanonicalizationOrTransformAlgorithmType> = [];
keyInfoAttributes: { [attrName: string]: string } = {};
getKeyInfoContent = SignedXml.getKeyInfoContent;
getCertFromKeyInfo = SignedXml.getCertFromKeyInfo;
// Internal state
private id = 0;
private signedXml = "";
private signatureXml = "";
private signatureNode: Node | null = null;
private signatureValue = "";
private originalXmlWithIds = "";
private keyInfo: Node | null = null;
/**
* Contains the references that were signed.
* @see {@link Reference}
*/
references: Reference[] = [];
/**
* Contains validation errors (if any) after {@link checkSignature} method is called
*/
validationErrors: string[] = [];
/**
* To add a new transformation algorithm create a new class that implements the {@link TransformationAlgorithm} interface, and register it here. More info: {@link https://github.com/node-saml/xml-crypto#customizing-algorithms|Customizing Algorithms}
*/
CanonicalizationAlgorithms: Record<
CanonicalizationOrTransformAlgorithmType,
new () => CanonicalizationOrTransformationAlgorithm
> = {
"http://www.w3.org/TR/2001/REC-xml-c14n-20010315": c14n.C14nCanonicalization,
"http://www.w3.org/TR/2001/REC-xml-c14n-20010315#WithComments":
c14n.C14nCanonicalizationWithComments,
"http://www.w3.org/2001/10/xml-exc-c14n#": execC14n.ExclusiveCanonicalization,
"http://www.w3.org/2001/10/xml-exc-c14n#WithComments":
execC14n.ExclusiveCanonicalizationWithComments,
"http://www.w3.org/2000/09/xmldsig#enveloped-signature": envelopedSignatures.EnvelopedSignature,
};
/**
* To add a new hash algorithm create a new class that implements the {@link HashAlgorithm} interface, and register it here. More info: {@link https://github.com/node-saml/xml-crypto#customizing-algorithms|Customizing Algorithms}
*/
HashAlgorithms: Record<HashAlgorithmType, new () => HashAlgorithm> = {
"http://www.w3.org/2000/09/xmldsig#sha1": hashAlgorithms.Sha1,
"http://www.w3.org/2001/04/xmlenc#sha256": hashAlgorithms.Sha256,
"http://www.w3.org/2001/04/xmlenc#sha512": hashAlgorithms.Sha512,
};
/**
* To add a new signature algorithm create a new class that implements the {@link SignatureAlgorithm} interface, and register it here. More info: {@link https://github.com/node-saml/xml-crypto#customizing-algorithms|Customizing Algorithms}
*/
SignatureAlgorithms: Record<SignatureAlgorithmType, new () => SignatureAlgorithm> = {
"http://www.w3.org/2000/09/xmldsig#rsa-sha1": signatureAlgorithms.RsaSha1,
"http://www.w3.org/2001/04/xmldsig-more#rsa-sha256": signatureAlgorithms.RsaSha256,
"http://www.w3.org/2001/04/xmldsig-more#rsa-sha512": signatureAlgorithms.RsaSha512,
// Disabled by default due to key confusion concerns.
// 'http://www.w3.org/2000/09/xmldsig#hmac-sha1': SignatureAlgorithms.HmacSha1
};
static defaultNsForPrefix = {
ds: "http://www.w3.org/2000/09/xmldsig#",
};
/**
* The SignedXml constructor provides an abstraction for sign and verify xml documents. The object is constructed using
* @param options {@link SignedXmlOptions}
*/
constructor(options: SignedXmlOptions = {}) {
const {
idMode,
idAttribute,
privateKey,
publicCert,
signatureAlgorithm,
canonicalizationAlgorithm,
inclusiveNamespacesPrefixList,
implicitTransforms,
keyInfoAttributes,
getKeyInfoContent,
getCertFromKeyInfo,
} = options;
// Options
this.idMode = idMode;
this.idAttributes = ["Id", "ID", "id"];
if (idAttribute) {
this.idAttributes.unshift(idAttribute);
}
this.privateKey = privateKey;
this.publicCert = publicCert;
this.signatureAlgorithm = signatureAlgorithm ?? this.signatureAlgorithm;
this.canonicalizationAlgorithm = canonicalizationAlgorithm ?? this.canonicalizationAlgorithm;
if (typeof inclusiveNamespacesPrefixList === "string") {
this.inclusiveNamespacesPrefixList = inclusiveNamespacesPrefixList.split(" ");
} else if (utils.isArrayHasLength(inclusiveNamespacesPrefixList)) {
this.inclusiveNamespacesPrefixList = inclusiveNamespacesPrefixList;
}
this.implicitTransforms = implicitTransforms ?? this.implicitTransforms;
this.keyInfoAttributes = keyInfoAttributes ?? this.keyInfoAttributes;
this.getKeyInfoContent = getKeyInfoContent ?? this.getKeyInfoContent;
this.getCertFromKeyInfo = getCertFromKeyInfo ?? this.getCertFromKeyInfo;
this.CanonicalizationAlgorithms;
this.HashAlgorithms;
this.SignatureAlgorithms;
}
/**
* Due to key-confusion issues, it's risky to have both hmac
* and digital signature algorithms enabled at the same time.
* This enables HMAC and disables other signing algorithms.
*/
enableHMAC(): void {
this.SignatureAlgorithms = {
"http://www.w3.org/2000/09/xmldsig#hmac-sha1": signatureAlgorithms.HmacSha1,
};
this.getKeyInfoContent = () => null;
}
/**
* Builds the contents of a KeyInfo element as an XML string.
*
* For example, if the value of the prefix argument is 'foo', then
* the resultant XML string will be "<foo:X509Data></foo:X509Data>"
*
* @return an XML string representation of the contents of a KeyInfo element, or `null` if no `KeyInfo` element should be included
*/
static getKeyInfoContent({ publicCert, prefix }: GetKeyInfoContentArgs): string | null {
if (publicCert == null) {
return null;
}
prefix = prefix ? `${prefix}:` : "";
let x509Certs = "";
if (Buffer.isBuffer(publicCert)) {
publicCert = publicCert.toString("latin1");
}
let publicCertMatches: string[] = [];
if (typeof publicCert === "string") {
publicCertMatches = publicCert.match(utils.EXTRACT_X509_CERTS) || [];
}
if (publicCertMatches.length > 0) {
x509Certs = publicCertMatches
.map((c) => `<X509Certificate>${utils.pemToDer(c).toString("base64")}</X509Certificate>`)
.join("");
}
return `<${prefix}X509Data>${x509Certs}</${prefix}X509Data>`;
}
/**
* Returns the value of the signing certificate based on the contents of the
* specified KeyInfo.
*
* @param keyInfo KeyInfo element (@see https://www.w3.org/TR/2008/REC-xmldsig-core-20080610/#sec-X509Data)
* @return the signing certificate as a string in PEM format
*/
static getCertFromKeyInfo(keyInfo?: Node | null): string | null {
if (keyInfo != null) {
const certs = xpath.select1(".//*[local-name(.)='X509Certificate']", keyInfo);
if (xpath.isNodeLike(certs)) {
return utils.derToPem(certs.textContent || "", "CERTIFICATE");
}
}
return null;
}
/**
* Validates the signature of the provided XML document synchronously using the configured key info provider.
*
* @param xml The XML document containing the signature to be validated.
* @returns `true` if the signature is valid
* @throws Error if no key info resolver is provided.
*/
checkSignature(xml: string): boolean;
/**
* Validates the signature of the provided XML document synchronously using the configured key info provider.
*
* @param xml The XML document containing the signature to be validated.
* @param callback Callback function to handle the validation result asynchronously.
* @throws Error if the last parameter is provided and is not a function, or if no key info resolver is provided.
*/
checkSignature(xml: string, callback: (error: Error | null, isValid?: boolean) => void): void;
checkSignature(
xml: string,
callback?: (error: Error | null, isValid?: boolean) => void,
): unknown {
if (callback != null && typeof callback !== "function") {
throw new Error("Last parameter must be a callback function");
}
this.validationErrors = [];
this.signedXml = xml;
const doc = new xmldom.DOMParser().parseFromString(xml);
if (!this.validateReferences(doc)) {
if (callback) {
callback(new Error("Could not validate references"));
return;
}
return false;
}
const signedInfoCanon = this.getCanonSignedInfoXml(doc);
const signer = this.findSignatureAlgorithm(this.signatureAlgorithm);
const key = this.getCertFromKeyInfo(this.keyInfo) || this.publicCert || this.privateKey;
if (key == null) {
throw new Error("KeyInfo or publicCert or privateKey is required to validate signature");
}
if (callback) {
signer.verifySignature(signedInfoCanon, key, this.signatureValue, callback);
} else {
const res = signer.verifySignature(signedInfoCanon, key, this.signatureValue);
if (res === false) {
this.validationErrors.push(
`invalid signature: the signature value ${this.signatureValue} is incorrect`,
);
}
return res;
}
}
getCanonSignedInfoXml(doc: Document) {
if (this.signatureNode == null) {
throw new Error("No signature found.");
}
const signedInfo = utils.findChildren(this.signatureNode, "SignedInfo");
if (signedInfo.length === 0) {
throw new Error("could not find SignedInfo element in the message");
}
if (
this.canonicalizationAlgorithm === "http://www.w3.org/TR/2001/REC-xml-c14n-20010315" ||
this.canonicalizationAlgorithm ===
"http://www.w3.org/TR/2001/REC-xml-c14n-20010315#WithComments"
) {
if (!doc || typeof doc !== "object") {
throw new Error(
"When canonicalization method is non-exclusive, whole xml dom must be provided as an argument",
);
}
}
/**
* Search for ancestor namespaces before canonicalization.
*/
const ancestorNamespaces = utils.findAncestorNs(doc, "//*[local-name()='SignedInfo']");
const c14nOptions = {
ancestorNamespaces: ancestorNamespaces,
};
return this.getCanonXml([this.canonicalizationAlgorithm], signedInfo[0], c14nOptions);
}
getCanonReferenceXml(doc: Document, ref: Reference, node: Node) {
/**
* Search for ancestor namespaces before canonicalization.
*/
if (Array.isArray(ref.transforms)) {
ref.ancestorNamespaces = utils.findAncestorNs(doc, ref.xpath, this.namespaceResolver);
}
const c14nOptions = {
inclusiveNamespacesPrefixList: ref.inclusiveNamespacesPrefixList,
ancestorNamespaces: ref.ancestorNamespaces,
};
return this.getCanonXml(ref.transforms, node, c14nOptions);
}
/** @deprecated */
validateSignatureValue(doc: Document): boolean;
/** @deprecated */
validateSignatureValue(doc: Document, callback: ErrorFirstCallback<boolean>): void;
/** @deprecated */
validateSignatureValue(doc: Document, callback?: ErrorFirstCallback<boolean>): boolean | void {
if (callback) {
this.checkSignature(doc.toString(), callback);
} else {
return this.checkSignature(doc.toString());
}
}
calculateSignatureValue(doc: Document, callback?: ErrorFirstCallback<string>) {
const signedInfoCanon = this.getCanonSignedInfoXml(doc);
const signer = this.findSignatureAlgorithm(this.signatureAlgorithm);
if (this.privateKey == null) {
throw new Error("Private key is required to compute signature");
}
if (typeof callback === "function") {
signer.getSignature(signedInfoCanon, this.privateKey, callback);
} else {
this.signatureValue = signer.getSignature(signedInfoCanon, this.privateKey);
}
}
findSignatureAlgorithm(name: SignatureAlgorithmType) {
const algo = this.SignatureAlgorithms[name];
if (algo) {
return new algo();
} else {
throw new Error(`signature algorithm '${name}' is not supported`);
}
}
findCanonicalizationAlgorithm(name: CanonicalizationOrTransformAlgorithmType) {
const algo = this.CanonicalizationAlgorithms[name];
if (algo) {
return new algo();
} else {
throw new Error(`canonicalization algorithm '${name}' is not supported`);
}
}
findHashAlgorithm(name: HashAlgorithmType) {
const algo = this.HashAlgorithms[name];
if (algo) {
return new algo();
} else {
throw new Error(`hash algorithm '${name}' is not supported`);
}
}
validateElementAgainstReferences(elem: Element, doc: Document): Reference {
for (const ref of this.references) {
const uri = ref.uri?.[0] === "#" ? ref.uri.substring(1) : ref.uri;
let targetElem: xpath.SelectSingleReturnType;
for (const attr of this.idAttributes) {
const elemId = elem.getAttribute(attr);
if (uri === elemId) {
targetElem = elem;
ref.xpath = `//*[@*[local-name(.)='${attr}']='${uri}']`;
break; // found the correct element, no need to check further
}
}
// @ts-expect-error FIXME: xpath types are wrong
if (!xpath.isNodeLike(targetElem)) {
continue;
}
const canonXml = this.getCanonReferenceXml(doc, ref, targetElem);
const hash = this.findHashAlgorithm(ref.digestAlgorithm);
const digest = hash.getHash(canonXml);
if (utils.validateDigestValue(digest, ref.digestValue)) {
return ref;
}
}
throw new Error("No references passed validation");
}
validateReference(ref: Reference, doc: Document) {
const uri = ref.uri?.[0] === "#" ? ref.uri.substring(1) : ref.uri;
let elem: xpath.SelectSingleReturnType;
if (uri === "") {
elem = xpath.select1("//*", doc);
} else if (uri?.indexOf("'") !== -1) {
// xpath injection
throw new Error("Cannot validate a uri with quotes inside it");
} else {
let num_elements_for_id = 0;
for (const attr of this.idAttributes) {
const tmp_elemXpath = `//*[@*[local-name(.)='${attr}']='${uri}']`;
const tmp_elem = xpath.select(tmp_elemXpath, doc);
if (utils.isArrayHasLength(tmp_elem)) {
num_elements_for_id += tmp_elem.length;
if (num_elements_for_id > 1) {
throw new Error(
"Cannot validate a document which contains multiple elements with the " +
"same value for the ID / Id / Id attributes, in order to prevent " +
"signature wrapping attack.",
);
}
elem = tmp_elem[0];
ref.xpath = tmp_elemXpath;
}
}
}
// @ts-expect-error FIXME: xpath types are wrong
if (!xpath.isNodeLike(elem)) {
const validationError = new Error(
`invalid signature: the signature references an element with uri ${ref.uri} but could not find such element in the xml`,
);
this.validationErrors.push(validationError.message);
return false;
}
const canonXml = this.getCanonReferenceXml(doc, ref, elem);
const hash = this.findHashAlgorithm(ref.digestAlgorithm);
const digest = hash.getHash(canonXml);
if (!utils.validateDigestValue(digest, ref.digestValue)) {
const validationError = new Error(
`invalid signature: for uri ${ref.uri} calculated digest is ${digest} but the xml to validate supplies digest ${ref.digestValue}`,
);
this.validationErrors.push(validationError.message);
return false;
}
return true;
}
validateReferences(doc: Document) {
for (const ref of this.references) {
if (!this.validateReference(ref, doc)) {
return false;
}
}
return true;
}
/**
* Loads the signature information from the provided XML node or string.
*
* @param signatureNode The XML node or string representing the signature.
*/
loadSignature(signatureNode: Node | string): void {
if (typeof signatureNode === "string") {
this.signatureNode = signatureNode = new xmldom.DOMParser().parseFromString(signatureNode);
} else {
this.signatureNode = signatureNode;
}
this.signatureXml = signatureNode.toString();
const nodes = xpath.select(
".//*[local-name(.)='CanonicalizationMethod']/@Algorithm",
signatureNode,
);
if (!utils.isArrayHasLength(nodes)) {
throw new Error("could not find CanonicalizationMethod/@Algorithm element");
}
if (xpath.isAttribute(nodes[0])) {
this.canonicalizationAlgorithm = nodes[0].value as CanonicalizationAlgorithmType;
}
const signatureAlgorithm = xpath.select1(
".//*[local-name(.)='SignatureMethod']/@Algorithm",
signatureNode,
);
if (xpath.isAttribute(signatureAlgorithm)) {
this.signatureAlgorithm = signatureAlgorithm.value as SignatureAlgorithmType;
}
this.references = [];
const references = xpath.select(
".//*[local-name(.)='SignedInfo']/*[local-name(.)='Reference']",
signatureNode,
);
if (!utils.isArrayHasLength(references)) {
throw new Error("could not find any Reference elements");
}
for (const reference of references) {
this.loadReference(reference);
}
const signatureValue = xpath.select1(
".//*[local-name(.)='SignatureValue']/text()",
signatureNode,
);
if (xpath.isTextNode(signatureValue)) {
this.signatureValue = signatureValue.data.replace(/\r?\n/g, "");
}
const keyInfo = xpath.select1(".//*[local-name(.)='KeyInfo']", signatureNode);
if (xpath.isNodeLike(keyInfo)) {
this.keyInfo = keyInfo;
}
}
/**
* Load the reference xml node to a model
*
*/
loadReference(refNode: Node) {
let nodes = utils.findChildren(refNode, "DigestMethod");
if (nodes.length === 0) {
throw new Error(`could not find DigestMethod in reference ${refNode.toString()}`);
}
const digestAlgoNode = nodes[0];
const attr = utils.findAttr(digestAlgoNode, "Algorithm");
if (!attr) {
throw new Error(`could not find Algorithm attribute in node ${digestAlgoNode.toString()}`);
}
const digestAlgo = attr.value;
nodes = utils.findChildren(refNode, "DigestValue");
if (nodes.length === 0) {
throw new Error(`could not find DigestValue node in reference ${refNode.toString()}`);
}
const firstChild = nodes[0].firstChild;
if (!firstChild || !("data" in firstChild)) {
throw new Error(`could not find the value of DigestValue in ${nodes[0].toString()}`);
}
const digestValue = firstChild.data;
const transforms: string[] = [];
let inclusiveNamespacesPrefixList: string[] = [];
nodes = utils.findChildren(refNode, "Transforms");
if (nodes.length !== 0) {
const transformsNode = nodes[0];
const transformsAll = utils.findChildren(transformsNode, "Transform");
for (const transform of transformsAll) {
const transformAttr = utils.findAttr(transform, "Algorithm");
if (transformAttr) {
transforms.push(transformAttr.value);
}
}
// This is a little strange, we are looking for children of the last child of `transformsNode`
const inclusiveNamespaces = utils.findChildren(
transformsAll[transformsAll.length - 1],
"InclusiveNamespaces",
);
if (utils.isArrayHasLength(inclusiveNamespaces)) {
// Should really only be one prefix list, but maybe there's some circumstances where more than one to let's handle it
inclusiveNamespacesPrefixList = inclusiveNamespaces
.flatMap((namespace) => (namespace.getAttribute("PrefixList") ?? "").split(" "))
.filter((value) => value.length > 0);
}
if (utils.isArrayHasLength(this.implicitTransforms)) {
this.implicitTransforms.forEach(function (t) {
transforms.push(t);
});
}
/**
* DigestMethods take an octet stream rather than a node set. If the output of the last transform is a node set, we
* need to canonicalize the node set to an octet stream using non-exclusive canonicalization. If there are no
* transforms, we need to canonicalize because URI dereferencing for a same-document reference will return a node-set.
* @see:
* https://www.w3.org/TR/xmldsig-core1/#sec-DigestMethod
* https://www.w3.org/TR/xmldsig-core1/#sec-ReferenceProcessingModel
* https://www.w3.org/TR/xmldsig-core1/#sec-Same-Document
*/
if (
transforms.length === 0 ||
transforms[transforms.length - 1] ===
"http://www.w3.org/2000/09/xmldsig#enveloped-signature"
) {
transforms.push("http://www.w3.org/TR/2001/REC-xml-c14n-20010315");
}
this.addReference({
transforms,
digestAlgorithm: digestAlgo,
uri: xpath.isElement(refNode) ? utils.findAttr(refNode, "URI")?.value : undefined,
digestValue,
inclusiveNamespacesPrefixList,
isEmptyUri: false,
});
}
}
/**
* Adds a reference to the signature.
*
* @param xpath The XPath expression to select the XML nodes to be referenced.
* @param transforms An array of transform algorithms to be applied to the selected nodes. Defaults to ["http://www.w3.org/2001/10/xml-exc-c14n#"].
* @param digestAlgorithm The digest algorithm to use for computing the digest value. Defaults to "http://www.w3.org/2000/09/xmldsig#sha1".
* @param uri The URI identifier for the reference. If empty, an empty URI will be used.
* @param digestValue The expected digest value for the reference.
* @param inclusiveNamespacesPrefixList The prefix list for inclusive namespace canonicalization.
* @param isEmptyUri Indicates whether the URI is empty. Defaults to `false`.
*/
addReference({
xpath,
transforms = ["http://www.w3.org/2001/10/xml-exc-c14n#"],
digestAlgorithm = "http://www.w3.org/2000/09/xmldsig#sha1",
uri = "",
digestValue,
inclusiveNamespacesPrefixList = [],
isEmptyUri = false,
}: Partial<Reference> & Pick<Reference, "xpath">): void {
this.references.push({
xpath,
transforms,
digestAlgorithm,
uri,
digestValue,
inclusiveNamespacesPrefixList,
isEmptyUri,
});
}
/**
* Compute the signature of the given XML (using the already defined settings).
*
* @param xml The XML to compute the signature for.
* @param callback A callback function to handle the signature computation asynchronously.
* @returns void
* @throws TypeError If the xml can not be parsed.
*/
computeSignature(xml: string): void;
/**
* Compute the signature of the given XML (using the already defined settings).
*
* @param xml The XML to compute the signature for.
* @param callback A callback function to handle the signature computation asynchronously.
* @returns void
* @throws TypeError If the xml can not be parsed.
*/
computeSignature(xml: string, callback: ErrorFirstCallback<SignedXml>): void;
/**
* Compute the signature of the given XML (using the already defined settings).
*
* @param xml The XML to compute the signature for.
* @param opts An object containing options for the signature computation.
* @returns If no callback is provided, returns `this` (the instance of SignedXml).
* @throws TypeError If the xml can not be parsed, or Error if there were invalid options passed.
*/
computeSignature(xml: string, options: ComputeSignatureOptions): void;
/**
* Compute the signature of the given XML (using the already defined settings).
*
* @param xml The XML to compute the signature for.
* @param opts An object containing options for the signature computation.
* @param callback A callback function to handle the signature computation asynchronously.
* @returns void
* @throws TypeError If the xml can not be parsed, or Error if there were invalid options passed.
*/
computeSignature(
xml: string,
options: ComputeSignatureOptions,
callback: ErrorFirstCallback<SignedXml>,
): void;
computeSignature(
xml: string,
options?: ComputeSignatureOptions | ErrorFirstCallback<SignedXml>,
callbackParam?: ErrorFirstCallback<SignedXml>,
): void {
let callback: ErrorFirstCallback<SignedXml>;
if (typeof options === "function" && callbackParam == null) {
callback = options as ErrorFirstCallback<SignedXml>;
options = {} as ComputeSignatureOptions;
} else {
callback = callbackParam as ErrorFirstCallback<SignedXml>;
options = (options ?? {}) as ComputeSignatureOptions;
}
const doc = new xmldom.DOMParser().parseFromString(xml);
let xmlNsAttr = "xmlns";
const signatureAttrs: string[] = [];
let currentPrefix: string;
const validActions = ["append", "prepend", "before", "after"];
const prefix = options.prefix;
const attrs = options.attrs || {};
const location = options.location || {};
const existingPrefixes = options.existingPrefixes || {};
this.namespaceResolver = {
lookupNamespaceURI: function (prefix) {
return prefix ? existingPrefixes[prefix] : null;
},
};
// defaults to the root node
location.reference = location.reference || "/*";
// defaults to append action
location.action = location.action || "append";
if (validActions.indexOf(location.action) === -1) {
const err = new Error(
`location.action option has an invalid action: ${
location.action
}, must be any of the following values: ${validActions.join(", ")}`,
);
if (!callback) {
throw err;
} else {
callback(err);
return;
}
}
// automatic insertion of `:`
if (prefix) {
xmlNsAttr += `:${prefix}`;
currentPrefix = `${prefix}:`;
} else {
currentPrefix = "";
}
Object.keys(attrs).forEach(function (name) {
if (name !== "xmlns" && name !== xmlNsAttr) {
signatureAttrs.push(`${name}="${attrs[name]}"`);
}
});
// add the xml namespace attribute
signatureAttrs.push(`${xmlNsAttr}="http://www.w3.org/2000/09/xmldsig#"`);
let signatureXml = `<${currentPrefix}Signature ${signatureAttrs.join(" ")}>`;
signatureXml += this.createSignedInfo(doc, prefix);
signatureXml += this.getKeyInfo(prefix);
signatureXml += `</${currentPrefix}Signature>`;
this.originalXmlWithIds = doc.toString();
let existingPrefixesString = "";
Object.keys(existingPrefixes).forEach(function (key) {
existingPrefixesString += `xmlns:${key}="${existingPrefixes[key]}" `;
});
// A trick to remove the namespaces that already exist in the xml
// This only works if the prefix and namespace match with those in the xml
const dummySignatureWrapper = `<Dummy ${existingPrefixesString}>${signatureXml}</Dummy>`;
const nodeXml = new xmldom.DOMParser().parseFromString(dummySignatureWrapper);
// Because we are using a dummy wrapper hack described above, we know there will be a `firstChild`
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
const signatureDoc = nodeXml.documentElement.firstChild!;
const referenceNode = xpath.select1(location.reference, doc);
if (!xpath.isNodeLike(referenceNode)) {
const err2 = new Error(
`the following xpath cannot be used because it was not found: ${location.reference}`,
);
if (!callback) {
throw err2;
} else {
callback(err2);
return;
}
}
if (location.action === "append") {
referenceNode.appendChild(signatureDoc);
} else if (location.action === "prepend") {
referenceNode.insertBefore(signatureDoc, referenceNode.firstChild);
} else if (location.action === "before") {
if (referenceNode.parentNode == null) {
throw new Error(
"`location.reference` refers to the root node (by default), so we can't insert `before`",
);
}
referenceNode.parentNode.insertBefore(signatureDoc, referenceNode);
} else if (location.action === "after") {
if (referenceNode.parentNode == null) {
throw new Error(
"`location.reference` refers to the root node (by default), so we can't insert `after`",
);
}
referenceNode.parentNode.insertBefore(signatureDoc, referenceNode.nextSibling);
}
this.signatureNode = signatureDoc;
const signedInfoNodes = utils.findChildren(this.signatureNode, "SignedInfo");
if (signedInfoNodes.length === 0) {
const err3 = new Error("could not find SignedInfo element in the message");
if (!callback) {
throw err3;
} else {
callback(err3);
return;
}
}
const signedInfoNode = signedInfoNodes[0];
if (typeof callback === "function") {
// Asynchronous flow
this.calculateSignatureValue(doc, (err, signature) => {
if (err) {
callback(err);
} else {
this.signatureValue = signature || "";
signatureDoc.insertBefore(this.createSignature(prefix), signedInfoNode.nextSibling);
this.signatureXml = signatureDoc.toString();
this.signedXml = doc.toString();
callback(null, this);
}
});
} else {
// Synchronous flow
this.calculateSignatureValue(doc);
signatureDoc.insertBefore(this.createSignature(prefix), signedInfoNode.nextSibling);
this.signatureXml = signatureDoc.toString();
this.signedXml = doc.toString();
}
}
getKeyInfo(prefix) {
const currentPrefix = prefix ? `${prefix}:` : "";
let keyInfoAttrs = "";
if (this.keyInfoAttributes) {
Object.keys(this.keyInfoAttributes).forEach((name) => {
keyInfoAttrs += ` ${name}="${this.keyInfoAttributes[name]}"`;
});
}
const keyInfoContent = this.getKeyInfoContent({ publicCert: this.publicCert, prefix });
if (keyInfoAttrs || keyInfoContent) {
return `<${currentPrefix}KeyInfo${keyInfoAttrs}>${keyInfoContent}</${currentPrefix}KeyInfo>`;
}
return "";
}
/**
* Generate the Reference nodes (as part of the signature process)
*
*/
createReferences(doc, prefix) {
let res = "";
prefix = prefix || "";
prefix = prefix ? `${prefix}:` : prefix;
for (const ref of this.references) {
const nodes = xpath.selectWithResolver(ref.xpath ?? "", doc, this.namespaceResolver);
if (!utils.isArrayHasLength(nodes)) {
throw new Error(
`the following xpath cannot be signed because it was not found: ${ref.xpath}`,
);
}
for (const node of nodes) {
if (ref.isEmptyUri) {
res += `<${prefix}Reference URI="">`;
} else {
const id = this.ensureHasId(node);
ref.uri = id;
res += `<${prefix}Reference URI="#${id}">`;
}
res += `<${prefix}Transforms>`;
for (const trans of ref.transforms || []) {
const transform = this.findCanonicalizationAlgorithm(trans);
res += `<${prefix}Transform Algorithm="${transform.getAlgorithmName()}"`;
if (utils.isArrayHasLength(ref.inclusiveNamespacesPrefixList)) {
res += ">";
res += `<InclusiveNamespaces PrefixList="${ref.inclusiveNamespacesPrefixList.join(
" ",
)}" xmlns="${transform.getAlgorithmName()}"/>`;
res += `</${prefix}Transform>`;
} else {
res += " />";
}
}
const canonXml = this.getCanonReferenceXml(doc, ref, node);
const digestAlgorithm = this.findHashAlgorithm(ref.digestAlgorithm);
res +=
`</${prefix}Transforms>` +
`<${prefix}DigestMethod Algorithm="${digestAlgorithm.getAlgorithmName()}" />` +
`<${prefix}DigestValue>${digestAlgorithm.getHash(canonXml)}</${prefix}DigestValue>` +
`</${prefix}Reference>`;
}
}
return res;
}
getCanonXml(
transforms: Reference["transforms"],
node: Node,
options: CanonicalizationOrTransformationAlgorithmProcessOptions = {},
) {
options.defaultNsForPrefix = options.defaultNsForPrefix ?? SignedXml.defaultNsForPrefix;
options.signatureNode = this.signatureNode;
const canonXml = node.cloneNode(true); // Deep clone
let transformedXml: string = canonXml.toString();
transforms.forEach((transformName) => {
const transform = this.findCanonicalizationAlgorithm(transformName);
transformedXml = transform.process(canonXml, options).toString();
//TODO: currently transform.process may return either Node or String value (enveloped transformation returns Node, exclusive-canonicalization returns String).
//This either needs to be more explicit in the API, or all should return the same.
//exclusive-canonicalization returns String since it builds the Xml by hand. If it had used xmldom it would incorrectly minimize empty tags
//to <x/> instead of <x></x> and also incorrectly handle some delicate line break issues.
//enveloped transformation returns Node since if it would return String consider this case:
//<x xmlns:p='ns'><p:y/></x>
//if only y is the node to sign then a string would be <p:y/> without the definition of the p namespace. probably xmldom toString() should have added it.
});
return transformedXml;
}
/**
* Ensure an element has Id attribute. If not create it with unique value.
* Work with both normal and wssecurity Id flavour
*/
ensureHasId(node) {
let attr;
if (this.idMode === "wssecurity") {
attr = utils.findAttr(
node,
"Id",
"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd",
);
} else {
this.idAttributes.some((idAttribute) => {
attr = utils.findAttr(node, idAttribute);
return !!attr; // This will break the loop as soon as a truthy attr is found.
});
}
if (attr) {
return attr.value;
}
//add the attribute
const id = `_${this.id++}`;
if (this.idMode === "wssecurity") {
node.setAttributeNS(
"http://www.w3.org/2000/xmlns/",
"xmlns:wsu",
"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd",
);