-
Notifications
You must be signed in to change notification settings - Fork 189
Expand file tree
/
Copy pathXMLSecurityDSig.php
More file actions
1839 lines (1697 loc) · 68 KB
/
Copy pathXMLSecurityDSig.php
File metadata and controls
1839 lines (1697 loc) · 68 KB
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
<?php
namespace RobRichards\XMLSecLibs;
use DOMDocument;
use DOMElement;
use DOMNode;
use DOMXPath;
use Exception;
use phpseclib3\File\X509;
use RobRichards\XMLSecLibs\Utils\XPath as XPath;
/**
* xmlseclibs.php
*
* Copyright (c) 2007-2026, Robert Richards <rrichards@cdatazone.org>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Robert Richards nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* @author Robert Richards <rrichards@cdatazone.org>
* @copyright 2007-2026 Robert Richards <rrichards@cdatazone.org>
* @license http://www.opensource.org/licenses/bsd-license.php BSD License
*/
class XMLSecurityDSig
{
const XMLDSIGNS = 'http://www.w3.org/2000/09/xmldsig#';
const SHA1 = 'http://www.w3.org/2000/09/xmldsig#sha1';
const SHA256 = 'http://www.w3.org/2001/04/xmlenc#sha256';
const SHA384 = 'http://www.w3.org/2001/04/xmldsig-more#sha384';
const SHA512 = 'http://www.w3.org/2001/04/xmlenc#sha512';
const RIPEMD160 = 'http://www.w3.org/2001/04/xmlenc#ripemd160';
const C14N = 'http://www.w3.org/TR/2001/REC-xml-c14n-20010315';
const C14N_COMMENTS = 'http://www.w3.org/TR/2001/REC-xml-c14n-20010315#WithComments';
const EXC_C14N = 'http://www.w3.org/2001/10/xml-exc-c14n#';
const EXC_C14N_COMMENTS = 'http://www.w3.org/2001/10/xml-exc-c14n#WithComments';
const ENVELOPED = 'http://www.w3.org/2000/09/xmldsig#enveloped-signature';
/** Default maximum XPath transforms allowed per Reference (DoS protection). */
const MAX_XPATH_TRANSFORMS = 5;
/** Default maximum namespaces allowed on a single XPath transform (DoS protection). */
const MAX_XPATH_NAMESPACES = 20;
/**
* Safe-by-default SignatureMethod allowlist applied by verifyDocument().
* SHA-1 based signatures (rsa-sha1, dsa-sha1, hmac-sha1) are intentionally
* excluded; callers that must interoperate with legacy peers can opt in by
* populating $allowedSignatureAlgorithms explicitly.
*/
const DEFAULT_SIGNATURE_ALGORITHMS = array(
XMLSecurityKey::RSA_SHA256,
XMLSecurityKey::RSA_SHA384,
XMLSecurityKey::RSA_SHA512,
XMLSecurityKey::RSA_SHA256_MGF1,
);
/**
* Safe-by-default DigestMethod allowlist applied by verifyDocument().
* SHA-1 and RIPEMD-160 are intentionally excluded.
*/
const DEFAULT_DIGEST_ALGORITHMS = array(
self::SHA256,
self::SHA384,
self::SHA512,
);
const BASE_TEMPLATE = '<Signature xmlns="http://www.w3.org/2000/09/xmldsig#">
<SignedInfo>
<SignatureMethod />
</SignedInfo>
</Signature>';
const BASE_TEMPLATE_NOWS = '<Signature xmlns="http://www.w3.org/2000/09/xmldsig#"><SignedInfo><SignatureMethod /></SignedInfo></Signature>';
/** @var DOMElement|null */
public $sigNode = null;
/** @var array */
public $idKeys = array();
/** @var array */
public $idNS = array();
/**
* Maximum XPath transforms allowed per Reference (DoS protection).
* Defaults to MAX_XPATH_TRANSFORMS; override for stricter or more relaxed limits.
* @var int
*/
public $maxXPathTransforms = self::MAX_XPATH_TRANSFORMS;
/**
* Maximum namespaces allowed on a single XPath transform (DoS protection).
* Defaults to MAX_XPATH_NAMESPACES; override for stricter or more relaxed limits.
* @var int
*/
public $maxXPathNamespaces = self::MAX_XPATH_NAMESPACES;
/**
* Allow XPath (REC-xpath-19991116) Transforms while verifying references.
*
* The XPath Filtering Transform evaluates an arbitrary, document-supplied
* XPath expression during validateReference() -- before any signature
* cryptography runs. The expression is an arbitrary XPath by design, so it
* cannot be sanitized without breaking the feature.
* The maxXPath* caps only bound the count, not the cost of a single expression.
*
* SAML and WS-Security do not use XPath transforms, so this defaults to
* false (reject them on the verification path). Set to true only if you
* must verify signatures that legitimately rely on XPath transforms and you
* trust the document source. Signing is unaffected (the transforms are
* caller-supplied, not attacker-controlled).
*
* @var bool
*/
public $allowXPathTransforms = false;
/**
* Allowlist of acceptable SignatureMethod algorithm URIs.
*
* When null (the default), the low-level verify() primitive imposes no
* restriction, preserving backward compatibility. verifyDocument() applies
* DEFAULT_SIGNATURE_ALGORITHMS when this is null. Set explicitly (e.g.
* add XMLSecurityKey::RSA_SHA1) to widen or narrow the accepted set.
*
* @var array|null
*/
public $allowedSignatureAlgorithms = null;
/**
* Allowlist of acceptable Reference DigestMethod algorithm URIs.
*
* When null (the default), no restriction is imposed by the low-level
* primitives. verifyDocument() applies DEFAULT_DIGEST_ALGORITHMS when null.
*
* @var array|null
*/
public $allowedDigestAlgorithms = null;
/**
* Reject documents that carry a DOCTYPE when locating a Signature.
*
* A DOCTYPE has no legitimate role in a signed XML document, but it enables
* a class of signature-verification bypasses: entity references in ID
* attributes (e.g. Id="&e;") are resolved by getAttribute() yet are
* invisible to the XPath "//*[@Id=...]" reference lookup, due to a libxml2
* hashing bug (same root cause as CVE-2025-23369). The signature then
* validates against one node while the application reads another. Rejecting
* any DOCTYPE closes this vector (and entity-expansion DoS) outright.
*
* Defaults to true (secure). Set to false ONLY if you fully trust the
* document source and require DTD support.
*
* @var bool
*/
public $forbidDoctype = true;
/** @var string|null */
protected $signedInfo = null;
/** @var DOMXPath|null */
protected $xPathCtx = null;
/** @var string|null */
protected $canonicalMethod = null;
/** @var string */
protected $prefix = '';
/** @var string */
protected $searchpfx = 'secdsig';
/**
* This variable contains an associative array of validated nodes.
* @var array|null
*/
protected $validatedNodes = null;
/**
* @param string $prefix
* @param null|array $options Optional flags; use 'stripWhitespace' => true for a compact template
*/
public function __construct($prefix='ds', $options=null)
{
$stripWhitespace = false;
if (is_array($options)) {
$stripWhitespace = !isset($options['stripWhitespace']) ? false : (bool) $options['stripWhitespace'];
}
$template = $stripWhitespace ? self::BASE_TEMPLATE_NOWS : self::BASE_TEMPLATE;
if (! empty($prefix)) {
$this->prefix = $prefix.':';
$search = array("<S", "</S", "xmlns=");
$replace = array("<$prefix:S", "</$prefix:S", "xmlns:$prefix=");
$template = str_replace($search, $replace, $template);
}
$sigdoc = new DOMDocument();
$sigdoc->loadXML($template);
$this->sigNode = $sigdoc->documentElement;
}
/**
* Set an Id attribute on the Signature element.
*
* @param string $id
* @return $this
*/
public function setSignatureId($id)
{
$this->sigNode->setAttribute('Id', $id);
return $this;
}
/**
* Restore pre-4.0 interoperability defaults for signature verification.
*
* Use this only when you must accept documents/peers that rely on
* behaviours 4.0 rejects by default (DOCTYPE, XPath Filtering Transforms,
* uncapped XPath transform counts). Prefer migrating peers and then
* removing the call.
*
* This does NOT weaken cryptographic checks that are always enforced in
* 4.0 (SignatureMethod/key algorithm binding, hash_equals compares,
* fail-closed Reference handling, unknown C14N rejection).
*
* @return $this
*/
public function enableLegacyMode()
{
$this->forbidDoctype = false;
$this->allowXPathTransforms = true;
$this->maxXPathTransforms = PHP_INT_MAX;
$this->maxXPathNamespaces = PHP_INT_MAX;
return $this;
}
/**
* Reset the XPathObj to null
*/
protected function resetXPathObj()
{
$this->xPathCtx = null;
}
/**
* Returns the cached DOMXPath for sigNode's owner document, creating it if needed.
*
* @return DOMXPath|null
*/
protected function getXPathObj()
{
if (empty($this->xPathCtx) && ! empty($this->sigNode)) {
$xpath = new DOMXPath($this->sigNode->ownerDocument);
$xpath->registerNamespace('secdsig', self::XMLDSIGNS);
$this->xPathCtx = $xpath;
}
return $this->xPathCtx;
}
/**
* Generate guid
*
* @param string $prefix Prefix to use for guid. defaults to pfx
*
* @return string The generated guid
*/
public static function generateGUID($prefix='pfx')
{
$uuid = bin2hex(random_bytes(16));
$guid = $prefix.substr($uuid, 0, 8)."-".
substr($uuid, 8, 4)."-".
substr($uuid, 12, 4)."-".
substr($uuid, 16, 4)."-".
substr($uuid, 20, 12);
return $guid;
}
/**
* Generate guid
*
* @param string $prefix Prefix to use for guid. defaults to pfx
*
* @return string The generated guid
*
* @deprecated Method deprecated in Release 1.4.1
*/
public static function generate_GUID($prefix='pfx')
{
return self::generateGUID($prefix);
}
/**
* @param DOMNode $objDoc
* @param int $pos
* @return DOMElement|null
*/
public function locateSignature($objDoc, $pos=0)
{
/* Drop any XPath context bound to a previous document. */
$this->resetXPathObj();
if ($objDoc instanceof DOMDocument) {
$doc = $objDoc;
} else {
$doc = $objDoc->ownerDocument;
}
if ($doc instanceof DOMDocument) {
if ($this->forbidDoctype && $doc->doctype !== null) {
throw new Exception('A DOCTYPE is not allowed in a document being verified');
}
$xpath = new DOMXPath($doc);
$xpath->registerNamespace('secdsig', self::XMLDSIGNS);
$query = ".//secdsig:Signature";
$nodeset = $xpath->query($query, $objDoc);
if ($nodeset === false) {
$this->sigNode = null;
return null;
}
$sigNode = $nodeset->item($pos);
if (! $sigNode instanceof DOMElement) {
$this->sigNode = null;
return null;
}
$this->sigNode = $sigNode;
$query = "./secdsig:SignedInfo";
$nodeset = $xpath->query($query, $this->sigNode);
if ($nodeset !== false && $nodeset->length > 1) {
throw new Exception("Invalid structure - Too many SignedInfo elements found");
}
return $this->sigNode;
}
return null;
}
/**
* @param string $name
* @param null|string $value
* @return DOMElement
*/
public function createNewSignNode($name, $value=null)
{
$doc = $this->sigNode->ownerDocument;
if (! is_null($value)) {
$node = $doc->createElementNS(self::XMLDSIGNS, $this->prefix.$name, $value);
} else {
$node = $doc->createElementNS(self::XMLDSIGNS, $this->prefix.$name);
}
return $node;
}
/**
* @param string $method
* @throws Exception
*/
public function setCanonicalMethod($method)
{
switch ($method) {
case 'http://www.w3.org/TR/2001/REC-xml-c14n-20010315':
case 'http://www.w3.org/TR/2001/REC-xml-c14n-20010315#WithComments':
case 'http://www.w3.org/2001/10/xml-exc-c14n#':
case 'http://www.w3.org/2001/10/xml-exc-c14n#WithComments':
$this->canonicalMethod = $method;
break;
default:
throw new Exception('Invalid Canonical Method');
}
if ($xpath = $this->getXPathObj()) {
$query = './'.$this->searchpfx.':SignedInfo';
$nodeset = $xpath->query($query, $this->sigNode);
$sinfo = ($nodeset !== false) ? $nodeset->item(0) : null;
if ($sinfo instanceof DOMElement) {
$query = './'.$this->searchpfx.':CanonicalizationMethod';
$nodeset = $xpath->query($query, $sinfo);
$canonNode = ($nodeset !== false) ? $nodeset->item(0) : null;
if (! $canonNode instanceof DOMElement) {
$canonNode = $this->createNewSignNode('CanonicalizationMethod');
$sinfo->insertBefore($canonNode, $sinfo->firstChild);
}
$canonNode->setAttribute('Algorithm', $this->canonicalMethod);
}
}
}
/**
* @param DOMNode $node
* @param string $canonicalmethod
* @param null|array $arXPath
* @param null|array $prefixList
* @return string
*/
protected function canonicalizeData($node, $canonicalmethod, $arXPath=null, $prefixList=null)
{
$exclusive = false;
$withComments = false;
switch ($canonicalmethod) {
case 'http://www.w3.org/TR/2001/REC-xml-c14n-20010315':
$exclusive = false;
$withComments = false;
break;
case 'http://www.w3.org/TR/2001/REC-xml-c14n-20010315#WithComments':
$withComments = true;
break;
case 'http://www.w3.org/2001/10/xml-exc-c14n#':
$exclusive = true;
break;
case 'http://www.w3.org/2001/10/xml-exc-c14n#WithComments':
$exclusive = true;
$withComments = true;
break;
default:
throw new Exception('Invalid CanonicalizationMethod: '.$canonicalmethod);
}
if (is_null($arXPath)
&& ($node->ownerDocument !== null)
&& ($node->ownerDocument->documentElement !== null)
&& $node->isSameNode($node->ownerDocument->documentElement)) {
/* Check for any PI or comments as they would have been excluded */
$element = $node;
while ($refnode = $element->previousSibling) {
if ($refnode->nodeType == XML_PI_NODE || (($refnode->nodeType == XML_COMMENT_NODE) && $withComments)) {
break;
}
$element = $refnode;
}
if ($refnode == null) {
$node = $node->ownerDocument;
}
}
$ret = $node->C14N($exclusive, $withComments, $arXPath, $prefixList);
if ($ret === false) {
throw new Exception("Canonicalization failed");
}
return $ret;
}
/**
* @return null|string
*/
public function canonicalizeSignedInfo()
{
$doc = $this->sigNode->ownerDocument;
$canonicalmethod = null;
if ($doc) {
$xpath = $this->getXPathObj();
$query = "./secdsig:SignedInfo";
$nodeset = $xpath->query($query, $this->sigNode);
if ($nodeset->length > 1) {
throw new Exception("Invalid structure - Too many SignedInfo elements found");
}
if ($signInfoNode = $nodeset->item(0)) {
$query = "./secdsig:CanonicalizationMethod";
$nodeset = $xpath->query($query, $signInfoNode);
if ($nodeset->length > 1) {
throw new Exception("Invalid structure - Too many CanonicalizationMethod elements found");
}
$prefixList = null;
$canonNode = $nodeset->item(0);
if ($canonNode instanceof DOMElement) {
$canonicalmethod = $canonNode->getAttribute('Algorithm');
foreach ($canonNode->childNodes as $node)
{
if ($node instanceof DOMElement
&& $node->localName == 'InclusiveNamespaces'
&& $node->namespaceURI === self::EXC_C14N) {
if ($pfx = $node->getAttribute('PrefixList')) {
$arpfx = array_filter(explode(' ', $pfx));
if (count($arpfx) > 0) {
$prefixList = array_merge($prefixList ? $prefixList : array(), $arpfx);
}
}
}
}
}
$query = "./secdsig:SignatureMethod";
$nodeset = $xpath->query($query, $signInfoNode);
if ($nodeset->length > 1) {
throw new Exception("Invalid structure - Too many SignatureMethod elements found");
}
$this->signedInfo = $this->canonicalizeData($signInfoNode, $canonicalmethod, null, $prefixList);
return $this->signedInfo;
}
}
return null;
}
/**
* @param string $digestAlgorithm
* @param string $data
* @param bool $encode
* @return string
* @throws Exception
*/
public function calculateDigest($digestAlgorithm, $data, $encode = true)
{
switch ($digestAlgorithm) {
case self::SHA1:
$alg = 'sha1';
break;
case self::SHA256:
$alg = 'sha256';
break;
case self::SHA384:
$alg = 'sha384';
break;
case self::SHA512:
$alg = 'sha512';
break;
case self::RIPEMD160:
$alg = 'ripemd160';
break;
default:
throw new Exception("Cannot validate digest: Unsupported Algorithm <$digestAlgorithm>");
}
$digest = hash($alg, $data, true);
if ($encode) {
$digest = base64_encode($digest);
}
return $digest;
}
/**
* @param DOMElement $refNode
* @param string $data
* @return bool
*/
public function validateDigest($refNode, $data)
{
$xpath = new DOMXPath($refNode->ownerDocument);
$xpath->registerNamespace('secdsig', self::XMLDSIGNS);
$query = './secdsig:DigestMethod';
$nodeset = $xpath->query($query, $refNode);
if ($nodeset === false || $nodeset->length !== 1) {
throw new Exception('Invalid structure - Expected exactly one DigestMethod element');
}
$digestMethod = $nodeset->item(0);
if (! $digestMethod instanceof DOMElement) {
throw new Exception('Invalid structure - Expected exactly one DigestMethod element');
}
$digestAlgorithm = $digestMethod->getAttribute('Algorithm');
if ($this->allowedDigestAlgorithms !== null
&& ! in_array($digestAlgorithm, $this->allowedDigestAlgorithms, true)) {
throw new Exception("DigestMethod algorithm is not allowed: '$digestAlgorithm'");
}
$digValue = $this->calculateDigest($digestAlgorithm, $data, false);
$query = './secdsig:DigestValue';
$nodeset = $xpath->query($query, $refNode);
if ($nodeset === false || $nodeset->length !== 1) {
throw new Exception('Invalid structure - Expected exactly one DigestValue element');
}
$digestValue = $nodeset->item(0)->textContent;
$decoded = base64_decode($digestValue, true);
if ($decoded === false) {
return false;
}
return hash_equals($digValue, $decoded);
}
/**
* @param DOMElement $refNode
* @param DOMNode $objData
* @param bool $includeCommentNodes
* @param bool $signing
* @return string
* @throws Exception
*/
public function processTransforms($refNode, $objData, $includeCommentNodes = true, $signing = false)
{
$data = $objData;
$xpath = new DOMXPath($refNode->ownerDocument);
$xpath->registerNamespace('secdsig', self::XMLDSIGNS);
$query = './secdsig:Transforms/secdsig:Transform';
$nodelist = $xpath->query($query, $refNode);
$canonicalMethod = 'http://www.w3.org/TR/2001/REC-xml-c14n-20010315';
$arXPath = null;
$prefixList = null;
$xpathTransformCount = 0;
$enveloped = false;
if ($nodelist !== false) {
foreach ($nodelist AS $transform) {
if (! $transform instanceof DOMElement) {
continue;
}
$algorithm = $transform->getAttribute("Algorithm");
switch ($algorithm) {
case 'http://www.w3.org/2001/10/xml-exc-c14n#':
case 'http://www.w3.org/2001/10/xml-exc-c14n#WithComments':
if (!$includeCommentNodes) {
/* We remove comment nodes by forcing it to use a canonicalization
* without comments.
*/
$canonicalMethod = 'http://www.w3.org/2001/10/xml-exc-c14n#';
} else {
$canonicalMethod = $algorithm;
}
$node = $transform->firstChild;
while ($node) {
if ($node instanceof DOMElement
&& $node->localName == 'InclusiveNamespaces'
&& $node->namespaceURI === self::EXC_C14N) {
if ($pfx = $node->getAttribute('PrefixList')) {
$arpfx = array();
$pfxlist = explode(" ", $pfx);
foreach ($pfxlist AS $pfx) {
$val = trim($pfx);
if (! empty($val)) {
$arpfx[] = $val;
}
}
if (count($arpfx) > 0) {
$prefixList = $arpfx;
}
}
break;
}
$node = $node->nextSibling;
}
break;
case 'http://www.w3.org/TR/2001/REC-xml-c14n-20010315':
case 'http://www.w3.org/TR/2001/REC-xml-c14n-20010315#WithComments':
if (!$includeCommentNodes) {
/* We remove comment nodes by forcing it to use a canonicalization
* without comments.
*/
$canonicalMethod = 'http://www.w3.org/TR/2001/REC-xml-c14n-20010315';
} else {
$canonicalMethod = $algorithm;
}
break;
case self::ENVELOPED:
$enveloped = true;
break;
case 'http://www.w3.org/TR/1999/REC-xpath-19991116':
/*
* Reject attacker-controlled XPath transforms on the
* verification path unless explicitly allowed. Signing uses
* caller-supplied transforms and is always permitted.
*/
if (! $signing && ! $this->allowXPathTransforms) {
throw new Exception(
'XPath Transforms are not allowed during verification; set '
. 'XMLSecurityDSig::$allowXPathTransforms = true to enable them'
);
}
$xpathTransformCount++;
if ($xpathTransformCount > $this->maxXPathTransforms) {
throw new Exception(
'Too many XPath Transformations found ('.$nodelist->length.') with a max allowed of '.$this->maxXPathTransforms
);
}
$node = $transform->firstChild;
while ($node) {
if ($node->localName == 'XPath'
&& ($node->namespaceURI === self::XMLDSIGNS || $node->namespaceURI === null || $node->namespaceURI === '')) {
$arXPath = array();
$arXPath['query'] = '(.//. | .//@* | .//namespace::*)['.$node->nodeValue.']';
$arXPath['namespaces'] = array();
$nslist = $xpath->query('./namespace::*', $node);
foreach ($nslist AS $nsnode) {
/* Exclude xml and the default xmlns (empty prefix). */
if ($nsnode->localName != "xml" && $nsnode->localName !== '' && $nsnode->localName !== 'xmlns') {
$arXPath['namespaces'][$nsnode->localName] = $nsnode->nodeValue;
}
}
$nsCount = count($arXPath['namespaces']);
if ($nsCount > $this->maxXPathNamespaces) {
throw new Exception(
'Too many namespaces in XPath Transformation found ('.$nsCount.') with a max allowed of '.$this->maxXPathNamespaces
);
}
break;
}
$node = $node->nextSibling;
}
break;
default:
throw new Exception("Transform algorithm is not supported: '$algorithm'");
}
}
}
$sig = null;
$sigParent = null;
$sigNextSibling = null;
/*
* Temporarily detach an enveloped Signature for canonicalization,
* then restore it so validation does not mutate the caller's DOM.
*/
if ($enveloped) {
$candidate = $this->sigNode;
$ancestor = $data instanceof DOMDocument ? $data->documentElement : $data;
if ($candidate instanceof DOMElement
&& $candidate->parentNode !== null
&& $ancestor !== null
&& ! $candidate->isSameNode($ancestor)) {
$walk = $candidate->parentNode;
while ($walk !== null) {
if ($walk->isSameNode($ancestor)) {
$sig = $candidate;
$sigParent = $sig->parentNode;
$sigNextSibling = $sig->nextSibling;
$sigParent->removeChild($sig);
break;
}
$walk = $walk->parentNode;
}
}
}
try {
$data = $this->canonicalizeData($objData, $canonicalMethod, $arXPath, $prefixList);
} finally {
if ($sig !== null && $sigParent !== null && $sig->parentNode === null) {
$sigParent->insertBefore($sig, $sigNextSibling);
}
}
return $data;
}
/**
* Parse a Reference @URI as a same-document reference.
*
* Only the empty URI and "#id" (non-empty fragment, no scheme/host/path/query)
* are accepted.
*
* @param string $uri
* @return array{identifier: ?string} identifier is null for the empty URI
* @throws Exception
*/
protected function parseSameDocumentURI($uri)
{
if ($uri === '') {
return array('identifier' => null);
}
$arUrl = parse_url($uri);
if ($arUrl === false
|| ! empty($arUrl['scheme'])
|| ! empty($arUrl['host'])
|| ! empty($arUrl['path'])
|| ! empty($arUrl['query'])
|| ! empty($arUrl['user'])
|| ! empty($arUrl['pass'])
|| isset($arUrl['port'])
|| ! array_key_exists('fragment', $arUrl)
|| $arUrl['fragment'] === '') {
throw new Exception('Reference URI must be a same-document reference');
}
return array('identifier' => $arUrl['fragment']);
}
/**
* Resolve the data object for a Reference before digests/transforms run.
*
* @param DOMElement $refNode
* @return array{dataObject: DOMNode, includeCommentNodes: bool, identifier: ?string}
* @throws Exception
*/
protected function resolveReferenceData($refNode)
{
/*
* Same-document references must omit comments from the digest.
* See: http://www.w3.org/TR/xmldsig-core/#sec-ReferenceProcessingModel
*/
$includeCommentNodes = false;
$identifier = null;
if ($refNode->hasAttribute("URI")) {
$uri = $refNode->getAttribute("URI");
$parsed = $this->parseSameDocumentURI($uri);
$identifier = $parsed['identifier'];
if ($identifier !== null) {
$xPath = new DOMXPath($refNode->ownerDocument);
if ($this->idNS) {
foreach ($this->idNS as $nspf => $ns) {
$xPath->registerNamespace($nspf, $ns);
}
}
$iDlist = '@Id="'.XPath::filterAttrValue($identifier, XPath::DOUBLE_QUOTE).'"';
foreach ($this->idKeys as $idKey) {
$attrName = XPath::filterAttrName($idKey);
if ($attrName === '' || $attrName !== $idKey) {
throw new Exception('Invalid idKeys attribute name');
}
$iDlist .= " or @".$attrName.'="'.
XPath::filterAttrValue($identifier, XPath::DOUBLE_QUOTE).'"';
}
$query = '//*['.$iDlist.']';
$nodeset = $xPath->query($query);
if ($nodeset === false || $nodeset->length === 0) {
throw new Exception('Reference URI does not identify a node');
}
if ($nodeset->length > 1) {
throw new Exception('Reference URI identifies multiple nodes');
}
$dataObject = $nodeset->item(0);
} else {
$dataObject = $refNode->ownerDocument;
}
} else {
/* No URI attribute — whole document, comments omitted. */
$dataObject = $refNode->ownerDocument;
}
if (! $dataObject instanceof DOMNode) {
throw new Exception('Reference URI could not be resolved');
}
return array(
'dataObject' => $dataObject,
'includeCommentNodes' => $includeCommentNodes,
'identifier' => $identifier,
);
}
/**
* @param DOMElement $refNode
* @return bool
* @throws Exception
*/
public function processRefNode($refNode)
{
$resolved = $this->resolveReferenceData($refNode);
$data = $this->processTransforms(
$refNode,
$resolved['dataObject'],
$resolved['includeCommentNodes']
);
if (!$this->validateDigest($refNode, $data)) {
return false;
}
/* Add this node to the list of validated nodes. */
if (! empty($resolved['identifier'])) {
$this->validatedNodes[$resolved['identifier']] = $resolved['dataObject'];
} else {
$this->validatedNodes[] = $resolved['dataObject'];
}
return true;
}
/**
* @param DOMElement $refNode
* @return string|null
*/
public function getRefNodeID($refNode)
{
if ($refNode->hasAttribute("URI")) {
$uri = $refNode->getAttribute("URI");
try {
$parsed = $this->parseSameDocumentURI($uri);
} catch (Exception $e) {
return null;
}
return $parsed['identifier'];
}
return null;
}
/**
* @return array
* @throws Exception
*/
public function getRefIDs()
{
$refids = array();
$xpath = $this->getXPathObj();
$query = "./secdsig:SignedInfo[1]/secdsig:Reference";
$nodeset = $xpath->query($query, $this->sigNode);
if ($nodeset->length == 0) {
throw new Exception("Reference nodes not found");
}
foreach ($nodeset AS $refNode) {
if (! $refNode instanceof DOMElement) {
throw new Exception("Reference nodes not found");
}
$refids[] = $this->getRefNodeID($refNode);
}
return $refids;
}
/**
* @return bool
* @throws Exception
*/
public function validateReference()
{
$xpath = $this->getXPathObj();
$query = "./secdsig:SignedInfo[1]/secdsig:Reference";
$nodeset = $xpath->query($query, $this->sigNode);
if ($nodeset->length == 0) {
throw new Exception("Reference nodes not found");
}
/* Initialize/reset the list of validated nodes. */
$this->validatedNodes = array();
/*
* Do not detach the Signature here. PHP's C14N returns an empty string
* for nodes that live under a detached subtree (e.g. ds:Object), which
* would break same-document refs into the Signature. The
* enveloped-signature Transform removes sigNode only when it is a
* proper descendant of the node being digested.
*/
foreach ($nodeset AS $refNode) {
if (! $refNode instanceof DOMElement) {
throw new Exception("Reference validation failed");
}
if (! $this->processRefNode($refNode)) {
/* Clear the list of validated nodes. */
$this->validatedNodes = null;
throw new Exception("Reference validation failed");
}
}
return true;
}
/**
* @param DOMNode $sinfoNode
* @param DOMDocument|DOMElement $node
* @param string $algorithm
* @param null|array $arTransforms
* @param null|array $options
*/
protected function addRefInternal($sinfoNode, $node, $algorithm, $arTransforms=null, $options=null)
{
$prefix = null;
$prefix_ns = null;
$id_name = 'Id';
$overwrite_id = true;
$force_uri = false;
$omit_uri = false;
$transforms_elem = true;
if (is_array($options)) {
$prefix = empty($options['prefix']) ? null : $options['prefix'];
$prefix_ns = empty($options['prefix_ns']) ? null : $options['prefix_ns'];
$id_name = empty($options['id_name']) ? 'Id' : $options['id_name'];
$overwrite_id = !isset($options['overwrite']) ? true : (bool) $options['overwrite'];
$force_uri = !isset($options['force_uri']) ? false : (bool) $options['force_uri'];
$omit_uri = !isset($options['omit_uri']) ? false : (bool) $options['omit_uri'];
$transforms_elem = !isset($options['transforms_elem']) ? true : (bool) $options['transforms_elem'];
}
$attname = $id_name;
if (! empty($prefix)) {
$attname = $prefix.':'.$attname;
}
$refNode = $this->createNewSignNode('Reference');
$sinfoNode->appendChild($refNode);
if (! $omit_uri) {
if (! $node instanceof DOMDocument) {
$uri = null;
if (! $overwrite_id) {
$uri = $prefix_ns ? $node->getAttributeNS($prefix_ns, $id_name) : $node->getAttribute($id_name);
}
if (empty($uri)) {
$uri = self::generateGUID();
$node->setAttributeNS($prefix_ns, $attname, $uri);