Passed
Pull Request — master (#3)
by Tim
02:01
created

Signature::validateReferences()   A

Complexity

Conditions 5
Paths 6

Size

Total Lines 19
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 5
eloc 10
c 1
b 0
f 0
nc 6
nop 0
dl 0
loc 19
rs 9.6111
1
<?php
2
3
namespace SimpleSAML\XMLSecurity;
4
5
use DOMDocument;
6
use DOMElement;
7
use DOMNode;
8
use SimpleSAML\Assert\Assert;
9
use SimpleSAML\XML\DOMDocumentFactory;
10
use SimpleSAML\XML\Exception\InvalidDOMElementException;
11
use SimpleSAML\XMLSecurity\Alg\Signature\SignatureAlgorithmFactory;
12
use SimpleSAML\XMLSecurity\Backend\SignatureBackend;
13
use SimpleSAML\XMLSecurity\Constants as C;
14
use SimpleSAML\XMLSecurity\Exception\InvalidArgumentException;
15
use SimpleSAML\XMLSecurity\Exception\NoSignatureFound;
16
use SimpleSAML\XMLSecurity\Exception\RuntimeException;
17
use SimpleSAML\XMLSecurity\Key;
18
use SimpleSAML\XMLSecurity\Utils\Certificate as CertificateUtils;
19
use SimpleSAML\XMLSecurity\Utils\Security as Sec;
20
use SimpleSAML\XMLSecurity\Utils\XPath as XP;
21
use SimpleSAML\XMLSecurity\XML\ds\Signature as Sig;
22
use SimpleSAML\XMLSecurity\XML\ds\Transform;
23
use SimpleSAML\XMLSecurity\XML\ds\X509Certificate;
24
use SimpleSAML\XMLSecurity\XML\ds\X509Data;
25
use SimpleSAML\XMLSecurity\XML\ds\X509Digest;
26
use SimpleSAML\XMLSecurity\XML\ds\X509IssuerSerial;
0 ignored issues
show
Bug introduced by
The type SimpleSAML\XMLSecurity\XML\ds\X509IssuerSerial was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
27
use SimpleSAML\XMLSecurity\XML\ds\X509SubjectName;
28
29
/**
30
 * Class implementing XML digital signatures.
31
 *
32
 * @package SimpleSAML\XMLSecurity
33
 */
34
class Signature
35
{
36
    /** @var array */
37
    public array $idNS = [];
38
39
    /** @var array */
40
    public array $idKeys = [];
41
42
    /** @var \SimpleSAML\XMLSecurity\Backend\SignatureBackend|null */
43
    protected ?SignatureBackend $backend = null;
44
45
    /** @var \DOMElement */
46
    protected DOMElement $root;
47
48
    /** @var \DOMElement|null */
49
    protected ?DOMElement $sigNode = null;
50
51
    /** @var \DOMElement */
52
    protected DOMElement $sigMethodNode;
53
54
    /** @var \DOMElement */
55
    protected DOMElement $c14nMethodNode;
56
57
    /** @var \DOMElement */
58
    protected DOMElement $sigInfoNode;
59
60
    /** @var \DOMElement|null */
61
    protected ?DOMElement $objectNode = null;
62
63
    /** @var string */
64
    protected string $signfo;
65
66
    /** @var string */
67
    protected string $sigAlg;
68
69
    /** @var \DOMElement[] */
70
    protected array $verifiedElements = [];
71
72
    /** @var string */
73
    protected string $c14nMethod = C::C14N_EXCLUSIVE_WITHOUT_COMMENTS;
74
75
    /** @var string */
76
    protected string $nsPrefix = 'ds:';
77
78
    /** @var array */
79
    protected array $algBlacklist = [
80
        C::SIG_RSA_SHA1,
81
        C::SIG_HMAC_SHA1,
82
    ];
83
84
    /** @var array */
85
    protected array $references = [];
86
87
    /** @var bool */
88
    protected bool $enveloping = false;
89
90
91
    /**
92
     * Signature constructor.
93
     *
94
     * @param \DOMElement|string $root The DOM element or a string of data we want to sign.
95
     * @param \SimpleSAML\XMLSecurity\Backend\SignatureBackend|null $backend The backend to use to
96
     *   generate or verify signatures. See individual algorithms for defaults.
97
     */
98
    public function __construct($root, SignatureBackend $backend = null)
99
    {
100
        $this->backend = $backend;
101
        $this->initSignature();
102
103
        if (is_string($root)) {
104
            $this->root = $this->addObject($root);
105
            $this->enveloping = true;
106
        } else {
107
            $this->root = $root;
108
        }
109
    }
110
111
112
    /**
113
     * Add an object element to the signature containing the given data.
114
     *
115
     * @param \DOMElement|string $data The data we want to envelope inside the signature.
116
     * @param string|null $mimetype An optional mime type to specify.
117
     * @param string|null $encoding An optional encoding to specify.
118
     *
119
     * @return \DOMElement The resulting object element added to the signature.
120
     */
121
    public function addObject($data, ?string $mimetype = null, ?string $encoding = null): DOMElement
122
    {
123
        if ($this->objectNode === null) {
124
            $this->objectNode = $this->createElement('Object');
125
            $this->sigNode->appendChild($this->objectNode);
0 ignored issues
show
Bug introduced by
The method appendChild() does not exist on null. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

125
            $this->sigNode->/** @scrutinizer ignore-call */ 
126
                            appendChild($this->objectNode);

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
Bug introduced by
$this->objectNode of type null is incompatible with the type DOMNode expected by parameter $node of DOMNode::appendChild(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

125
            $this->sigNode->appendChild(/** @scrutinizer ignore-type */ $this->objectNode);
Loading history...
126
        }
127
128
        if (is_string($mimetype) && !empty($mimetype)) {
129
            $this->objectNode->setAttribute('MimeType', $mimetype);
0 ignored issues
show
Bug introduced by
The method setAttribute() does not exist on null. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

129
            $this->objectNode->/** @scrutinizer ignore-call */ 
130
                               setAttribute('MimeType', $mimetype);

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
130
        }
131
132
        if (is_string($encoding) && !empty($encoding)) {
133
            $this->objectNode->setAttribute('Encoding', $encoding);
134
        }
135
136
        if ($data instanceof DOMElement) {
137
            $this->objectNode->appendChild($this->sigNode->ownerDocument->importNode($data, true));
0 ignored issues
show
Bug introduced by
The method importNode() does not exist on null. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

137
            $this->objectNode->appendChild($this->sigNode->ownerDocument->/** @scrutinizer ignore-call */ importNode($data, true));

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
138
        } else {
139
            $this->objectNode->appendChild($this->sigNode->ownerDocument->createTextNode($data));
140
        }
141
142
        return $this->objectNode;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this->objectNode could return the type null which is incompatible with the type-hinted return DOMElement. Consider adding an additional type-check to rule them out.
Loading history...
143
    }
144
145
146
    /**
147
     * Add a reference to a given node (an element or a document).
148
     *
149
     * @param \DOMNode $node A DOMElement that we want to sign, or a DOMDocument if we want to sign the entire document.
150
     * @param string $alg The identifier of a supported digest algorithm to use when processing this reference.
151
     * @param array $transforms An array containing a list of transforms that must be applied to the reference.
152
     * Optional.
153
     * @param array $options An array containing a set of options for this reference. Optional. Supported options are:
154
     *   - prefix (string): the XML prefix used in the element being referenced. Defaults to none (no prefix used).
155
     *
156
     *   - prefix_ns (string): the namespace associated with the given prefix. Defaults to none (no prefix used).
157
     *
158
     *   - id_name (string): the name of the "id" attribute in the referenced element. Defaults to "Id".
159
     *
160
     *   - force_uri (boolean): Whether to explicitly add a URI attribute to the reference when referencing a
161
     *     DOMDocument or not. Defaults to true. If force_uri is false and $node is a DOMDocument, the URI attribute
162
     *     will be completely omitted.
163
     *
164
     *   - overwrite (boolean): Whether to overwrite the identifier existing in the element referenced with a new,
165
     *     random one, or not. Defaults to true.
166
     *
167
     * @throws \SimpleSAML\XMLSecurity\Exception\InvalidArgumentException If $node is not
168
     *   an instance of DOMDocument or DOMElement.
169
     */
170
    public function addReference(DOMNode $node, string $alg, array $transforms = [], array $options = []): void
171
    {
172
        Assert::isInstanceOfAny(
173
            $node,
174
            [DOMDocument::class, DOMElement::class],
175
            'Only references to the DOM document or elements are allowed.'
176
        );
177
178
        $prefix = @$options['prefix'] ?: null;
179
        $prefixNS = @$options['prefix_ns'] ?: null;
180
        $idName = @$options['id_name'] ?: 'Id';
181
        $attrName = $prefix ? $prefix . ':' . $idName : $idName;
182
        $forceURI = true;
183
        if (isset($options['force_uri'])) {
184
            $forceURI = $options['force_uri'];
185
        }
186
        $overwrite = true;
187
        if (isset($options['overwrite'])) {
188
            $overwrite = $options['overwrite'];
189
        }
190
191
        $reference = $this->createElement('Reference');
192
        $this->sigInfoNode->appendChild($reference);
193
194
        // register reference
195
        $includeCommentNodes = false;
196
        if ($node instanceof DOMElement) {
197
            $uri = null;
198
            if (!$overwrite) {
199
                $uri = $prefixNS ? $node->getAttributeNS($prefixNS, $idName) : $node->getAttribute($idName);
200
            }
201
            if (empty($uri)) {
202
                $uri = Utils\Random::generateGUID();
203
                $node->setAttributeNS($prefixNS, $attrName, $uri);
204
            }
205
206
            if (
207
                in_array(C::C14N_EXCLUSIVE_WITH_COMMENTS, $transforms)
208
                || in_array(C::C14N_INCLUSIVE_WITH_COMMENTS, $transforms)
209
            ) {
210
                $includeCommentNodes = true;
211
                $reference->setAttribute('URI', "#xpointer($attrName('$uri'))");
212
            } else {
213
                $reference->setAttribute('URI', '#' . $uri);
214
            }
215
        } elseif ($forceURI) {
216
            // $node is a \DOMDocument, should add a reference to the root element (enveloped signature)
217
            if (in_array($this->c14nMethod, [C::C14N_INCLUSIVE_WITH_COMMENTS, C::C14N_EXCLUSIVE_WITH_COMMENTS])) {
218
                // if we want to use a C14N method that includes comments, the URI must be an xpointer
219
                $reference->setAttribute('URI', '#xpointer(/)');
220
            } else {
221
                // C14N without comments, we can set an empty URI
222
                $reference->setAttribute('URI', '');
223
            }
224
        }
225
226
        // apply and register transforms
227
        $transformList = $this->createElement('Transforms');
228
        $reference->appendChild($transformList);
229
230
        if (!empty($transforms)) {
231
            foreach ($transforms as $transform) {
232
                if (is_array($transform) && !empty($transform[C::XPATH_URI]['query'])) {
233
                    $t = new Transform(C::XPATH_URI, [new Chunk($transform[C::XPATH_URI]['query'])]);
0 ignored issues
show
Bug introduced by
The type SimpleSAML\XMLSecurity\Chunk was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
234
                } else {
235
                    $t = new Transform($transform);
236
                }
237
                $t->toXML($transformList);
238
            }
239
        } elseif (!empty($this->c14nMethod)) {
240
            $t = new Transform($this->c14nMethod);
241
            $t->toXML($transformList);
242
        }
243
244
        $canonicalData = $this->processTransforms($reference, $node, $includeCommentNodes);
245
        $digest = $this->hash($alg, $canonicalData);
246
247
        $digestMethod = new DigestMethod($alg);
0 ignored issues
show
Bug introduced by
The type SimpleSAML\XMLSecurity\DigestMethod was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
248
        $digestMethod->toXML($reference);
249
250
        $digestValue = $this->createElement('DigestValue', $digest);
251
        $reference->appendChild($digestValue);
252
253
        if (!in_array($node, $this->references)) {
254
            $this->references[] = $node;
255
        }
256
    }
257
258
259
    /**
260
     * Add a set of references to the signature.
261
     *
262
     * @param \DOMNode[] $nodes An array of DOMNode objects to be referred in the signature.
263
     * @param string $alg The identifier of the digest algorithm to use.
264
     * @param array $transforms An array of transforms to apply to each reference.
265
     * @param array $options An array of options.
266
     *
267
     * @throws \SimpleSAML\XMLSecurity\Exception\InvalidArgumentException If any of the nodes in the $nodes
268
     *   array is not an instance of DOMDocument or DOMElement.
269
     *
270
     * @see addReference()
271
     */
272
    public function addReferences(array $nodes, string $alg, array $transforms = [], $options = []): void
273
    {
274
        foreach ($nodes as $node) {
275
            $this->addReference($node, $alg, $transforms, $options);
276
        }
277
    }
278
279
280
    /**
281
     * Attach one or more X509 certificates to the signature.
282
     *
283
     * @param \SimpleSAML\XMLSecurity\Key\X509Certificate[] $certs
284
     *   An X509Certificate object or an array of them.
285
     * @param boolean $addSubject Whether to add the subject of the certificate or not.
286
     * @param string|false $digest A digest algorithm identifier if the digest of the certificate should be added. False
287
     * otherwise.
288
     * @param boolean $addIssuerSerial Whether to add the serial number of the issuer or not.
289
     *
290
     * @throws \SimpleSAML\XMLSecurity\Exception\InvalidArgumentException If $certs is not a
291
     *   X509Certificate object or an array of them.
292
     */
293
    public function addX509Certificates(
294
        array $certs,
295
        bool $addSubject = false,
296
        $digest = false,
297
        bool $addIssuerSerial = false
298
    ): void {
299
        Assert::allIsInstanceOf($certs, Key\X509Certificate::class);
300
301
        $certData = [];
302
303
        foreach ($certs as $cert) {
304
            $details = $cert->getCertificateDetails();
305
306
            if ($addSubject && isset($details['subject'])) {
307
                // add subject
308
                $subjectNameValue = $details['issuer'];
309
                if (is_array($details['subject'])) {
310
                    $parts = [];
311
                    foreach ($details['subject'] as $key => $value) {
312
                        if (is_array($value)) {
313
                            foreach ($value as $valueElement) {
314
                                array_unshift($parts, $key . '=' . $valueElement);
315
                            }
316
                        } else {
317
                            array_unshift($parts, $key . '=' . $value);
318
                        }
319
                    }
320
                    $subjectNameValue = implode(',', $parts);
321
                }
322
                $certData[] = new X509SubjectName($subjectNameValue);
323
            }
324
325
            if ($digest !== false) {
326
                // add certificate digest
327
                $fingerprint = base64_encode(hex2bin($cert->getRawThumbprint($digest)));
328
                $certData[] = new X509Digest($fingerprint, $digest);
329
            }
330
331
            if ($addIssuerSerial && isset($details['issuer']) && isset($details['serialNumber'])) {
332
                $issuerName = CertificateUtils::parseIssuer($details['issuer']);
0 ignored issues
show
Bug introduced by
The method parseIssuer() does not exist on SimpleSAML\XMLSecurity\Utils\Certificate. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

332
                /** @scrutinizer ignore-call */ 
333
                $issuerName = CertificateUtils::parseIssuer($details['issuer']);

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
333
334
                $certData[] = new X509IssuerSerial($issuerName, $details['serialNumber']);
335
            }
336
337
            $certData[] = new X509Certificate(CertificateUtils::stripHeaders($cert->getCertificate()));
338
        }
339
340
        $keyInfoNode = $this->createElement('KeyInfo');
341
342
        $certDataNode = new X509Data($certData);
343
        $certDataNode->toXML($keyInfoNode);
344
345
        if ($this->objectNode === null) {
346
            $this->sigNode->appendChild($keyInfoNode);
347
        } else {
348
            $this->sigNode->insertBefore($keyInfoNode, $this->objectNode);
349
        }
350
    }
351
352
353
    /**
354
     * Append a signature as the last child of the signed element.
355
     *
356
     * @return \DOMNode The appended signature.
357
     */
358
    public function append(): DOMNode
359
    {
360
        return $this->insert();
361
    }
362
363
364
    /**
365
     * Use this signature as an enveloping signature, effectively adding the signed data to a ds:Object element.
366
     *
367
     * @param string|null $mimetype The mime type corresponding to the signed data.
368
     * @param string|null $encoding The encoding corresponding to the signed data.
369
     */
370
    public function envelop(string $mimetype = null, string $encoding = null): void
371
    {
372
        $this->root = $this->addObject($this->root, $mimetype, $encoding);
373
    }
374
375
376
    /**
377
     * Build a new XML digital signature from a given document or node.
378
     *
379
     * @param \DOMNode $node The DOMDocument or DOMElement that contains the signature.
380
     *
381
     * @return Signature A Signature object corresponding to the signature present in the given DOM document or element.
382
     *
383
     * @throws \SimpleSAML\XMLSecurity\Exception\InvalidArgumentException If $node is not
384
     *   an instance of DOMDocument or DOMElement.
385
     * @throws \SimpleSAML\XMLSecurity\Exception\NoSignatureFound If there is no signature in the $node.
386
     */
387
    public static function fromXML(DOMNode $node): Signature
388
    {
389
        Assert::isInstanceOfAny(
390
            $node,
391
            [DOMDocument::class, DOMElement::class],
392
            'Signatures can only be created from DOM documents or elements'
393
        );
394
395
        $signature = self::findSignature($node);
396
        if ($node instanceof DOMDocument) {
397
            $node = $node->documentElement;
398
        }
399
        $dsig = new self($node);
400
        $dsig->setSignatureElement($signature);
401
        return $dsig;
402
    }
403
404
405
    /**
406
     * Obtain the list of currently blacklisted algorithms.
407
     *
408
     * Signatures using blacklisted algorithms cannot be created or verified.
409
     *
410
     * @return array An array containing the identifiers of the algorithms blacklisted currently.
411
     */
412
    public function getBlacklistedAlgorithms(): array
413
    {
414
        return $this->algBlacklist;
415
    }
416
417
418
    /**
419
     * Get the list of namespaces to designate ID attributes.
420
     *
421
     * @return array An array of strings with the namespaces used in ID attributes.
422
     */
423
    public function getIdNamespaces(): array
424
    {
425
        return $this->idNS;
426
    }
427
428
429
    /**
430
     * Get a list of attributes used as an ID.
431
     *
432
     * @return array An array of strings with the attributes used as an ID.
433
     */
434
    public function getIdAttributes(): array
435
    {
436
        return $this->idKeys;
437
    }
438
439
440
    /**
441
     * Get the root configured for this signature.
442
     *
443
     * This will be the signed element, whether that's a user-provided XML element or a ds:Object element containing
444
     * the actual data (which can in turn be either XML or not).
445
     *
446
     * @return \DOMElement The root element for this signature.
447
     */
448
    public function getRoot(): DOMElement
449
    {
450
        return $this->root;
451
    }
452
453
454
    /**
455
     * Get the identifier of the algorithm used in this signature.
456
     *
457
     * @return string The identifier of the algorithm used in this signature.
458
     */
459
    public function getSignatureMethod(): string
460
    {
461
        return $this->sigAlg;
462
    }
463
464
465
    /**
466
     * Get a list of elements verified by this signature.
467
     *
468
     * The elements in this list are referenced by the signature and the references verified to be correct. However,
469
     * this doesn't mean the signature is valid, only that the references were so.
470
     *
471
     * Note that the list returned will be empty unless verify() has been called before.
472
     *
473
     * @return \DOMElement[] A list of elements correctly referenced by this signature. An empty list of verify() has
474
     * not been called yet, or if the references couldn't be verified.
475
     */
476
    public function getVerifiedElements(): array
477
    {
478
        return $this->verifiedElements;
479
    }
480
481
482
    /**
483
     * Insert a signature as a child of the signed element, optionally before a given element.
484
     *
485
     * @param \DOMElement|false $before An optional DOM element the signature should be prepended to.
486
     *
487
     * @return \DOMNode The inserted signature.
488
     *
489
     * @throws \SimpleSAML\XMLSecurity\Exception\RuntimeException If this signature is in enveloping mode.
490
     */
491
    public function insert($before = false): DOMNode
492
    {
493
        Assert::false(
494
            $this->enveloping,
495
            'Cannot insert the signature in the object it is enveloping.',
496
            RuntimeException::class
497
        );
498
499
        $signature = $this->root->ownerDocument->importNode($this->sigNode, true);
0 ignored issues
show
Bug introduced by
It seems like $this->sigNode can also be of type null; however, parameter $node of DOMDocument::importNode() does only seem to accept DOMNode, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

499
        $signature = $this->root->ownerDocument->importNode(/** @scrutinizer ignore-type */ $this->sigNode, true);
Loading history...
Bug introduced by
The method importNode() does not exist on null. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

499
        /** @scrutinizer ignore-call */ 
500
        $signature = $this->root->ownerDocument->importNode($this->sigNode, true);

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
500
501
        if ($before instanceof DOMElement) {
502
            return $this->root->insertBefore($signature, $before);
503
        }
504
        return $this->root->insertBefore($signature);
505
    }
506
507
508
    /**
509
     * Prepend a signature as the first child of the signed element.
510
     *
511
     * @return \DOMNode The prepended signature.
512
     */
513
    public function prepend(): DOMNode
514
    {
515
        foreach ($this->root->childNodes as $child) {
516
            // look for the first child element, if any
517
            if ($child instanceof \DOMElement) {
518
                return $this->insert($child);
519
            }
520
        }
521
        return $this->append();
522
    }
523
524
525
    /**
526
     * Set the backend to create or verify signatures.
527
     *
528
     * @param SignatureBackend $backend The SignatureBackend implementation to use. See individual algorithms for
529
     * details about the default backends used.
530
     */
531
    public function setBackend(SignatureBackend $backend): void
532
    {
533
        $this->backend = $backend;
534
    }
535
536
537
    /**
538
     * Set the list of currently blacklisted algorithms.
539
     *
540
     * Signatures using blacklisted algorithms cannot be created or verified.
541
     *
542
     * @param array $algs An array containing the identifiers of the algorithms to blacklist.
543
     */
544
    public function setBlacklistedAlgorithms(array $algs): void
545
    {
546
        $this->algBlacklist = $algs;
547
    }
548
549
550
    /**
551
     * Set the canonicalization method used in this signature.
552
     *
553
     * Note that exclusive canonicalization without comments is used by default, so it's not necessary to call
554
     * setCanonicalizationMethod() if that canonicalization method is desired.
555
     *
556
     * @param string $method The identifier of the canonicalization method to use.
557
     *
558
     * @throws \SimpleSAML\XMLSecurity\Exception\InvalidArgumentException If $method is not a valid
559
     *   identifier of a supported canonicalization method.
560
     */
561
    public function setCanonicalizationMethod(string $method): void
562
    {
563
        Assert::oneOf(
564
            $method,
565
            [
566
                C::C14N_EXCLUSIVE_WITH_COMMENTS,
567
                C::C14N_EXCLUSIVE_WITHOUT_COMMENTS,
568
                C::C14N_INCLUSIVE_WITH_COMMENTS,
569
                C::C14N_INCLUSIVE_WITHOUT_COMMENTS
570
            ],
571
            'Invalid canonicalization method',
572
            InvalidArgumentException::class
573
        );
574
575
        $this->c14nMethod = $method;
576
        $this->c14nMethodNode->setAttribute('Algorithm', $method);
577
    }
578
579
580
    /**
581
     * Set the encoding for the signed contents in an enveloping signature.
582
     *
583
     * @param string $encoding The encoding used in the signed contents.
584
     *
585
     * @throws \SimpleSAML\XMLSecurity\Exception\RuntimeException If this is not an enveloping signature.
586
     */
587
    public function setEncoding(string $encoding): void
588
    {
589
        Assert::true(
590
            $this->enveloping,
591
            'Cannot set the encoding for non-enveloping signatures.',
592
            RuntimeException::class
593
        );
594
595
        $this->root->setAttribute('Encoding', $encoding);
596
    }
597
598
599
    /**
600
     * Set a list of attributes used as an ID.
601
     *
602
     * @param array $keys An array of strings with the attributes used as an ID.
603
     */
604
    public function setIdAttributes(array $keys): void
605
    {
606
        $this->idKeys = $keys;
607
    }
608
609
610
    /**
611
     * Set the list of namespaces to designate ID attributes.
612
     *
613
     * @param array $namespaces An array of strings with the namespaces used in ID attributes.
614
     */
615
    public function setIdNamespaces(array $namespaces): void
616
    {
617
        $this->idNS = $namespaces;
618
    }
619
620
621
    /**
622
     * Set the mime type for the signed contents in an enveloping signature.
623
     *
624
     * @param string $mimetype The mime type of the signed contents.
625
     *
626
     * @throws \SimpleSAML\XMLSecurity\Exception\RuntimeException If this is not an enveloping signature.
627
     */
628
    public function setMimeType(string $mimetype): void
629
    {
630
        Assert::true(
631
            $this->enveloping,
632
            'Cannot set the mime type for non-enveloping signatures.',
633
            RuntimeException::class
634
        );
635
636
        $this->root->setAttribute('MimeType', $mimetype);
637
    }
638
639
640
    /**
641
     * Set the signature element to a given one, and initialize the signature from there.
642
     *
643
     * @param \DOMElement $element A DOM element containing an XML signature.
644
     *
645
     * @throws \SimpleSAML\XML\Exception\InvalidDOMElementException If the element does not correspond to an XML
646
     *   signature or it is malformed (e.g. there are missing mandatory elements or attributes).
647
     */
648
    public function setSignatureElement(DOMElement $element): void
649
    {
650
        Assert::same($element->localName, 'Signature', InvalidDOMElementException::class);
651
        Assert::same($element->namespaceURI, Sig::NS, InvalidDOMElementException::class);
652
653
        $this->sigNode = $element;
654
655
        $xp = XP::getXPath($this->sigNode->ownerDocument);
0 ignored issues
show
Bug introduced by
It seems like $this->sigNode->ownerDocument can also be of type null; however, parameter $doc of SimpleSAML\XMLSecurity\Utils\XPath::getXPath() does only seem to accept DOMDocument, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

655
        $xp = XP::getXPath(/** @scrutinizer ignore-type */ $this->sigNode->ownerDocument);
Loading history...
656
657
        $signedInfoNodes = $xp->query('./ds:SignedInfo', $this->sigNode);
658
659
        Assert::minCount(
660
            $signedInfoNodes,
661
            1,
662
            'There is no SignedInfo element in the signature',
663
            RuntimeException::class
664
        );
665
        $this->sigInfoNode = $signedInfoNodes->item(0);
666
667
668
        $this->sigAlg = $xp->evaluate('string(./ds:SignedInfo/ds:SignatureMethod/@Algorithm)', $this->sigNode);
669
        Assert::stringNotEmpty($this->sigAlg, 'Unable to determine SignatureMethod', RuntimeException::class);
670
671
        $c14nMethodNodes = $xp->query('./ds:CanonicalizationMethod', $this->sigInfoNode);
672
        Assert::minCount(
673
            $c14nMethodNodes,
674
            1,
675
            'There is no CanonicalizationMethod in the signature',
676
            RuntimeException::class
677
        );
678
679
        $this->c14nMethodNode = $c14nMethodNodes->item(0);
680
        if (!$this->c14nMethodNode->hasAttribute('Algorithm')) {
681
            throw new RuntimeException('CanonicalizationMethod missing required Algorithm attribute');
682
        }
683
        $this->c14nMethod = $this->c14nMethodNode->getAttribute('Algorithm');
684
    }
685
686
687
    /**
688
     * Sign the document or element.
689
     *
690
     * This method will finish the signature process. It will create an XML signature valid for document or elements
691
     * specified previously with addReference() or addReferences(). If none of those methods have been called previous
692
     * to calling sign() (there are no references in the signature), the $root passed during construction of the
693
     * Signature object will be referenced automatically.
694
     *
695
     * @param \SimpleSAML\XMLSecurity\Key\AbstractKey $key The key to use for signing. Bear in mind that the type of
696
     *   this key must be compatible with the types of key accepted by the algorithm specified in $alg.
697
     * @param string $alg The identifier of the signature algorithm to use. See \SimpleSAML\XMLSecurity\Constants.
698
     * @param bool $appendToNode Whether to append the signature as the last child of the root element or not.
699
     *
700
     * @throws \SimpleSAML\XMLSecurity\Exception\InvalidArgumentException If $appendToNode is true and
701
     *   this is an enveloping signature.
702
     */
703
    public function sign(Key\AbstractKey $key, string $alg, bool $appendToNode = false): void
704
    {
705
        Assert::false(
706
            ($this->enveloping && $appendToNode),
707
            'Cannot append the signature, we are in enveloping mode.',
708
            InvalidArgumentException::class
709
        );
710
711
        $this->sigMethodNode->setAttribute('Algorithm', $alg);
712
        $factory = new SignatureAlgorithmFactory($this->algBlacklist);
713
        $signer = $factory->getAlgorithm($alg, $key);
714
        if ($this->backend !== null) {
715
            $signer->setBackend($this->backend);
716
        }
717
718
        if (empty($this->references)) {
719
            // no references have been added, ref root
720
            $transforms = [];
721
            if (!$this->enveloping) {
722
                $transforms[] = C::XMLDSIG_ENVELOPED;
723
            }
724
            $this->addReference($this->root->ownerDocument, $signer->getDigest(), $transforms, []);
0 ignored issues
show
Bug introduced by
It seems like $this->root->ownerDocument can also be of type null; however, parameter $node of SimpleSAML\XMLSecurity\Signature::addReference() does only seem to accept DOMNode, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

724
            $this->addReference(/** @scrutinizer ignore-type */ $this->root->ownerDocument, $signer->getDigest(), $transforms, []);
Loading history...
725
        }
726
727
        if ($appendToNode) {
728
            $this->sigNode = $this->append();
729
        } elseif (in_array($this->c14nMethod, [C::C14N_INCLUSIVE_WITHOUT_COMMENTS, C::C14N_INCLUSIVE_WITH_COMMENTS])) {
730
            // append Signature to root node for inclusive canonicalization
731
            $restoreSigNode = $this->sigNode;
732
            $this->sigNode = $this->prepend();
733
        }
734
735
        $sigValue = base64_encode($signer->sign($this->canonicalizeData($this->sigInfoNode, $this->c14nMethod)));
736
737
        // remove Signature from node if we added it for c14n
738
        if (
739
            !$appendToNode &&
740
            in_array($this->c14nMethod, [C::C14N_INCLUSIVE_WITHOUT_COMMENTS, C::C14N_INCLUSIVE_WITH_COMMENTS])
741
        ) { // remove from root in case we added it for inclusive canonicalization
742
            $this->root->removeChild($this->root->lastChild);
0 ignored issues
show
Bug introduced by
It seems like $this->root->lastChild can also be of type null; however, parameter $child of DOMNode::removeChild() does only seem to accept DOMNode, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

742
            $this->root->removeChild(/** @scrutinizer ignore-type */ $this->root->lastChild);
Loading history...
743
            /** @var \DOMElement $restoreSigNode */
744
            $this->sigNode = $restoreSigNode;
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $restoreSigNode does not seem to be defined for all execution paths leading up to this point.
Loading history...
745
        }
746
747
        $sigValueNode = $this->createElement('SignatureValue', $sigValue);
748
        if ($this->sigInfoNode->nextSibling) {
749
            $this->sigInfoNode->nextSibling->parentNode->insertBefore($sigValueNode, $this->sigInfoNode->nextSibling);
0 ignored issues
show
Bug introduced by
The method insertBefore() does not exist on null. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

749
            $this->sigInfoNode->nextSibling->parentNode->/** @scrutinizer ignore-call */ 
750
                                                         insertBefore($sigValueNode, $this->sigInfoNode->nextSibling);

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
750
        } else {
751
            $this->sigNode->appendChild($sigValueNode);
752
        }
753
    }
754
755
756
    /**
757
     * Verify this signature with a given key.
758
     *
759
     * @param \SimpleSAML\XMLSecurity\Key\AbstractKey $key The key to use to verify this signature.
760
     *
761
     * @return bool True if the signature can be verified with $key, false otherwise.
762
     *
763
     * @throws \SimpleSAML\XMLSecurity\Exception\RuntimeException If there is no SignatureValue in
764
     *   the signature, or we couldn't verify all the references.
765
     */
766
    public function verify(Key\AbstractKey $key): bool
767
    {
768
        $xp = XP::getXPath($this->sigNode->ownerDocument);
0 ignored issues
show
Bug introduced by
It seems like $this->sigNode->ownerDocument can also be of type null; however, parameter $doc of SimpleSAML\XMLSecurity\Utils\XPath::getXPath() does only seem to accept DOMDocument, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

768
        $xp = XP::getXPath(/** @scrutinizer ignore-type */ $this->sigNode->ownerDocument);
Loading history...
769
        $sigval = $xp->evaluate('string(./ds:SignatureValue)', $this->sigNode);
770
        if (empty($sigval)) {
771
            throw new RuntimeException('Unable to locate SignatureValue');
772
        }
773
774
        $siginfo = $this->canonicalizeData($this->sigInfoNode, $this->c14nMethod);
775
        if (!$this->validateReferences()) {
776
            throw new RuntimeException('Unable to verify all references');
777
        }
778
779
        $factory = new SignatureAlgorithmFactory($this->algBlacklist);
780
        $alg = $factory->getAlgorithm($this->sigAlg, $key);
781
        if ($this->backend !== null) {
782
            $alg->setBackend($this->backend);
783
        }
784
        return $alg->verify($siginfo, base64_decode($sigval));
785
    }
786
787
788
    /**
789
     * Canonicalize any given node.
790
     *
791
     * @param \DOMNode $node The DOM node that needs canonicalization.
792
     * @param string $c14nMethod The identifier of the canonicalization algorithm to use.
793
     * See \SimpleSAML\XMLSecurity\Constants.
794
     * @param array|null $xpaths An array of xpaths to filter the nodes by. Defaults to null (no filters).
795
     * @param array|null $prefixes An array of namespace prefixes to filter the nodes by. Defaults to null (no filters).
796
     *
797
     * @return string The canonical representation of the given DOM node, according to the algorithm requested.
798
     */
799
    protected function canonicalizeData(
800
        DOMNode $node,
801
        string $c14nMethod,
802
        array $xpaths = null,
803
        array $prefixes = null
804
    ): string {
805
        $exclusive = false;
806
        $withComments = false;
807
        switch ($c14nMethod) {
808
            case C::C14N_EXCLUSIVE_WITH_COMMENTS:
809
            case C::C14N_INCLUSIVE_WITH_COMMENTS:
810
                $withComments = true;
811
        }
812
        switch ($c14nMethod) {
813
            case C::C14N_EXCLUSIVE_WITH_COMMENTS:
814
            case C::C14N_EXCLUSIVE_WITHOUT_COMMENTS:
815
                $exclusive = true;
816
        }
817
818
        if (
819
            is_null($xpaths)
820
            && ($node->ownerDocument !== null)
821
            && $node->isSameNode($node->ownerDocument->documentElement)
822
        ) {
823
            // check for any PI or comments as they would have been excluded
824
            $element = $node;
825
            while ($refNode = $element->previousSibling) {
826
                if (
827
                    (($refNode->nodeType === XML_COMMENT_NODE) && $withComments)
828
                    || $refNode->nodeType === XML_PI_NODE
829
                ) {
830
                    break;
831
                }
832
                $element = $refNode;
833
            }
834
            if ($refNode == null) {
835
                $node = $node->ownerDocument;
836
            }
837
        }
838
839
        return $node->C14N($exclusive, $withComments, $xpaths, $prefixes);
840
    }
841
842
843
    /**
844
     * Create a new element in this signature.
845
     *
846
     * @param string $name The name of this element.
847
     * @param string|null $content The text contents of the element, or null if it is not supposed to have any text
848
     * contents. Defaults to null.
849
     * @param string $ns The namespace the new element must be created under. Defaults to the standard XMLDSIG
850
     * namespace.
851
     *
852
     * @return \DOMElement A new DOM element with the given name.
853
     */
854
    protected function createElement(
855
        string $name,
856
        string $content = null,
857
        string $ns = C::XMLDSIGNS
858
    ): DOMElement {
859
        if ($this->sigNode === null) {
860
            // initialize signature
861
            $doc = DOMDocumentFactory::create();
862
        } else {
863
            $doc = $this->sigNode->ownerDocument;
864
        }
865
866
        $nsPrefix = $this->nsPrefix;
867
868
        if ($content !== null) {
869
            return $doc->createElementNS($ns, $nsPrefix . $name, $content);
870
        }
871
872
        return $doc->createElementNS($ns, $nsPrefix . $name);
873
    }
874
875
876
    /**
877
     * Find a signature from a given node.
878
     *
879
     * @param \DOMNode $node A DOMElement node where a signature is expected as a child (enveloped) or a DOMDocument
880
     * node to search for document signatures (one single reference with an empty URI).
881
     *
882
     * @return \DOMElement The signature element.
883
     *
884
     * @throws \SimpleSAML\XMLSecurity\Exception\RuntimeException If there is no DOMDocument element available.
885
     * @throws \SimpleSAML\XMLSecurity\Exception\NoSignatureFound If no signature is found.
886
     */
887
    protected static function findSignature(DOMNode $node): DOMElement
888
    {
889
        $doc = $node instanceof DOMDocument ? $node : $node->ownerDocument;
890
891
        Assert::notNull($doc, 'Cannot search for signatures, no DOM document available', RuntimeException::class);
892
893
        $xp = XP::getXPath($doc);
0 ignored issues
show
Bug introduced by
It seems like $doc can also be of type null; however, parameter $doc of SimpleSAML\XMLSecurity\Utils\XPath::getXPath() does only seem to accept DOMDocument, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

893
        $xp = XP::getXPath(/** @scrutinizer ignore-type */ $doc);
Loading history...
894
        $nodeset = $xp->query('./ds:Signature', $node);
895
896
        if ($nodeset->length === 0) {
897
            throw new NoSignatureFound();
898
        }
899
        return $nodeset->item(0);
0 ignored issues
show
Bug Best Practice introduced by
The expression return $nodeset->item(0) returns the type null which is incompatible with the type-hinted return DOMElement.
Loading history...
900
    }
901
902
903
    /**
904
     * Compute the hash for some data with a given algorithm.
905
     *
906
     * @param string $alg The identifier of the algorithm to use.
907
     * @param string $data The data to digest.
908
     * @param bool $encode Whether to bas64-encode the result or not. Defaults to true.
909
     *
910
     * @return string The (binary or base64-encoded) digest corresponding to the given data.
911
     *
912
     * @throws \SimpleSAML\XMLSecurity\Exception\InvalidArgumentException If $alg is not a valid
913
     *   identifier of a supported digest algorithm.
914
     */
915
    protected function hash(string $alg, string $data, bool $encode = true): string
916
    {
917
        Assert::keyExists(
918
            C::$DIGEST_ALGORITHMS,
919
            $alg,
920
            'Unsupported digest method "%s"',
921
            InvalidArgumentException::class
922
        );
923
924
        $digest = hash(C::$DIGEST_ALGORITHMS[$alg], $data, true);
925
        return $encode ? base64_encode($digest) : $digest;
926
    }
927
928
929
    /**
930
     * Initialize the basic structure of a signature from scratch.
931
     *
932
     */
933
    protected function initSignature(): void
934
    {
935
        $this->sigNode = $this->createElement('Signature');
936
        $this->sigInfoNode = $this->createElement('SignedInfo');
937
        $this->c14nMethodNode = $this->createElement('CanonicalizationMethod');
938
        $this->c14nMethodNode->setAttribute('Algorithm', $this->c14nMethod);
939
        $this->sigMethodNode = $this->createElement('SignatureMethod');
940
941
        $this->sigInfoNode->appendChild($this->c14nMethodNode);
942
        $this->sigInfoNode->appendChild($this->sigMethodNode);
943
        $this->sigNode->appendChild($this->sigInfoNode);
944
        $this->sigNode->ownerDocument->appendChild($this->sigNode);
945
    }
946
947
948
    /**
949
     * Process a given reference, by looking for it, processing the specified transforms, canonicalizing the result
950
     * and comparing its corresponding digest.
951
     *
952
     * Verified references will be stored in the "verifiedElements" property.
953
     *
954
     * @param \DOMElement $ref The ds:Reference element to process.
955
     *
956
     * @return bool True if the digest of the processed reference matches the one given, false otherwise.
957
     *
958
     * @throws \SimpleSAML\XMLSecurity\Exception\RuntimeException If the referenced element is missing or
959
     *   the reference points to an external document.
960
     *
961
     * @see http://www.w3.org/TR/xmldsig-core/#sec-ReferenceProcessingModel
962
     */
963
    protected function processReference(DOMElement $ref): bool
964
    {
965
        /*
966
         * Depending on the URI, we may need to remove comments during canonicalization.
967
         * See: http://www.w3.org/TR/xmldsig-core/#sec-ReferenceProcessingModel
968
         */
969
        $includeCommentNodes = true;
970
        $dataObject = $ref->ownerDocument;
971
        if ($ref->hasAttribute("URI")) {
972
            $uri = $ref->getAttribute('URI');
973
            if (empty($uri)) {
974
                // this reference identifies the enclosing XML, it should not include comments
975
                $includeCommentNodes = false;
976
            }
977
            $arUrl = parse_url($uri);
978
            if (empty($arUrl['path'])) {
979
                if ($identifier = @$arUrl['fragment']) {
980
                    /*
981
                     * This reference identifies a node with the given ID by using a URI on the form '#identifier'.
982
                     * This should not include comments.
983
                     */
984
                    $includeCommentNodes = false;
985
986
                    $xp = XP::getXPath($ref->ownerDocument);
0 ignored issues
show
Bug introduced by
It seems like $ref->ownerDocument can also be of type null; however, parameter $doc of SimpleSAML\XMLSecurity\Utils\XPath::getXPath() does only seem to accept DOMDocument, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

986
                    $xp = XP::getXPath(/** @scrutinizer ignore-type */ $ref->ownerDocument);
Loading history...
987
                    if ($this->idNS && is_array($this->idNS)) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->idNS of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
988
                        foreach ($this->idNS as $nspf => $ns) {
989
                            $xp->registerNamespace($nspf, $ns);
990
                        }
991
                    }
992
                    $iDlist = '@Id="' . $identifier . '"';
993
                    if (is_array($this->idKeys)) {
0 ignored issues
show
introduced by
The condition is_array($this->idKeys) is always true.
Loading history...
994
                        foreach ($this->idKeys as $idKey) {
995
                            $iDlist .= " or @$idKey='$identifier'";
996
                        }
997
                    }
998
                    $query = '//*[' . $iDlist . ']';
999
                    $dataObject = $xp->query($query)->item(0);
1000
                    if ($dataObject === null) {
1001
                        throw new RuntimeException('Reference not found');
1002
                    }
1003
                }
1004
            } else {
1005
                throw new RuntimeException('Processing of external documents is not supported');
1006
            }
1007
        } else {
1008
            // this reference identifies the root node with an empty URI, it should not include comments
1009
            $includeCommentNodes = false;
1010
        }
1011
1012
        $data = $this->processTransforms($ref, $dataObject, $includeCommentNodes);
1013
        if (!$this->validateDigest($ref, $data)) {
1014
            return false;
1015
        }
1016
1017
        // parse the canonicalized reference...
1018
        $doc = DOMDocumentFactory::create();
1019
        $doc->loadXML($data);
1020
        $dataObject = $doc->documentElement;
1021
1022
        // ... and add it to the list of verified elements
1023
        if (!empty($identifier)) {
1024
            $this->verifiedElements[$identifier] = $dataObject;
1025
        } else {
1026
            $this->verifiedElements[] = $dataObject;
1027
        }
1028
1029
        return true;
1030
    }
1031
1032
1033
    /**
1034
     * Process all transforms specified by a given Reference element.
1035
     *
1036
     * @param \DOMElement $ref The Reference element.
1037
     * @param mixed $data The data referenced.
1038
     * @param bool $includeCommentNodes Whether to allow canonicalization with comments or not.
1039
     *
1040
     * @return string The canonicalized data after applying all transforms specified by $ref.
1041
     *
1042
     * @see http://www.w3.org/TR/xmldsig-core/#sec-ReferenceProcessingModel
1043
     */
1044
    protected function processTransforms(DOMElement $ref, $data, bool $includeCommentNodes = false): string
1045
    {
1046
        if (!($data instanceof DOMNode)) {
1047
            return $data;
1048
        }
1049
1050
        $xp = XP::getXPath($ref->ownerDocument);
0 ignored issues
show
Bug introduced by
It seems like $ref->ownerDocument can also be of type null; however, parameter $doc of SimpleSAML\XMLSecurity\Utils\XPath::getXPath() does only seem to accept DOMDocument, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

1050
        $xp = XP::getXPath(/** @scrutinizer ignore-type */ $ref->ownerDocument);
Loading history...
1051
        $transforms = $xp->query('./ds:Transforms/ds:Transform', $ref);
1052
        $canonicalMethod = C::C14N_EXCLUSIVE_WITHOUT_COMMENTS;
1053
        $arXPath = null;
1054
        $prefixList = null;
1055
        foreach ($transforms as $transform) {
1056
            /** @var \DOMElement $transform */
1057
            $algorithm = $transform->getAttribute("Algorithm");
1058
            switch ($algorithm) {
1059
                case C::C14N_EXCLUSIVE_WITHOUT_COMMENTS:
1060
                case C::C14N_EXCLUSIVE_WITH_COMMENTS:
1061
                    if (!$includeCommentNodes) {
1062
                        // remove comment nodes by forcing it to use a canonicalization without comments
1063
                        $canonicalMethod = C::C14N_EXCLUSIVE_WITHOUT_COMMENTS;
1064
                    } else {
1065
                        $canonicalMethod = $algorithm;
1066
                    }
1067
1068
                    $node = $transform->firstChild;
1069
                    while ($node) {
1070
                        if ($node->localName === 'InclusiveNamespaces') {
1071
                            if ($pfx = $node->getAttribute('PrefixList')) {
1072
                                $arpfx = [];
1073
                                $pfxlist = explode(" ", $pfx);
1074
                                foreach ($pfxlist as $pfx) {
1075
                                    $val = trim($pfx);
1076
                                    if (! empty($val)) {
1077
                                        $arpfx[] = $val;
1078
                                    }
1079
                                }
1080
                                if (count($arpfx) > 0) {
1081
                                    $prefixList = $arpfx;
1082
                                }
1083
                            }
1084
                            break;
1085
                        }
1086
                        $node = $node->nextSibling;
1087
                    }
1088
                    break;
1089
                case C::C14N_INCLUSIVE_WITHOUT_COMMENTS:
1090
                case C::C14N_INCLUSIVE_WITH_COMMENTS:
1091
                    if (!$includeCommentNodes) {
1092
                        // remove comment nodes by forcing it to use a canonicalization without comments
1093
                        $canonicalMethod = C::C14N_INCLUSIVE_WITHOUT_COMMENTS;
1094
                    } else {
1095
                        $canonicalMethod = $algorithm;
1096
                    }
1097
1098
                    break;
1099
                case C::XPATH_URI:
1100
                    $node = $transform->firstChild;
1101
                    while ($node) {
1102
                        if ($node->localName == 'XPath') {
1103
                            $arXPath = [];
1104
                            $arXPath['query'] = '(.//. | .//@* | .//namespace::*)[' . $node->nodeValue . ']';
1105
                            $arXpath['namespaces'] = [];
1106
                            $nslist = $xp->query('./namespace::*', $node);
1107
                            foreach ($nslist as $nsnode) {
1108
                                if ($nsnode->localName != "xml") {
1109
                                    $arXPath['namespaces'][$nsnode->localName] = $nsnode->nodeValue;
1110
                                }
1111
                            }
1112
                            break;
1113
                        }
1114
                        $node = $node->nextSibling;
1115
                    }
1116
                    break;
1117
            }
1118
        }
1119
1120
        return $this->canonicalizeData($data, $canonicalMethod, $arXPath, $prefixList);
1121
    }
1122
1123
1124
    /**
1125
     * Compute and compare the digest corresponding to some data given to the one specified by a reference.
1126
     *
1127
     * @param \DOMElement $ref The ds:Reference element containing the digest.
1128
     * @param string $data The referenced element, canonicalized, to digest and compare.
1129
     *
1130
     * @return bool True if the resulting digest matches the one in the reference, false otherwise.
1131
     */
1132
    protected function validateDigest(DOMElement $ref, string $data): bool
1133
    {
1134
        $xp = XP::getXPath($ref->ownerDocument);
0 ignored issues
show
Bug introduced by
It seems like $ref->ownerDocument can also be of type null; however, parameter $doc of SimpleSAML\XMLSecurity\Utils\XPath::getXPath() does only seem to accept DOMDocument, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

1134
        $xp = XP::getXPath(/** @scrutinizer ignore-type */ $ref->ownerDocument);
Loading history...
1135
        $alg = $xp->evaluate('string(./ds:DigestMethod/@Algorithm)', $ref);
1136
        $computed = $this->hash($alg, $data, false);
1137
        $evaluated = base64_decode($xp->evaluate('string(./ds:DigestValue)', $ref));
1138
        return Sec::compareStrings($computed, $evaluated);
1139
    }
1140
1141
1142
    /**
1143
     * Iterate over the references specified by the signature, apply their transforms, and validate their digests
1144
     * against the referenced elements.
1145
     *
1146
     * @return boolean True if all references could be verified, false otherwise.
1147
     *
1148
     * @throws \SimpleSAML\XMLSecurity\Exception\RuntimeException If there are no references.
1149
     */
1150
    protected function validateReferences(): bool
1151
    {
1152
        $doc = $this->sigNode->ownerDocument;
1153
1154
        if (!$doc->documentElement->isSameNode($this->sigNode) && $this->sigNode->parentNode !== null) {
0 ignored issues
show
Bug introduced by
It seems like $this->sigNode can also be of type null; however, parameter $otherNode of DOMNode::isSameNode() does only seem to accept DOMNode, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

1154
        if (!$doc->documentElement->isSameNode(/** @scrutinizer ignore-type */ $this->sigNode) && $this->sigNode->parentNode !== null) {
Loading history...
1155
            // enveloped signature, remove it
1156
            $this->sigNode->parentNode->removeChild($this->sigNode);
0 ignored issues
show
Bug introduced by
It seems like $this->sigNode can also be of type null; however, parameter $child of DOMNode::removeChild() does only seem to accept DOMNode, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

1156
            $this->sigNode->parentNode->removeChild(/** @scrutinizer ignore-type */ $this->sigNode);
Loading history...
1157
        }
1158
1159
        $xp = XP::getXPath($doc);
0 ignored issues
show
Bug introduced by
It seems like $doc can also be of type null; however, parameter $doc of SimpleSAML\XMLSecurity\Utils\XPath::getXPath() does only seem to accept DOMDocument, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

1159
        $xp = XP::getXPath(/** @scrutinizer ignore-type */ $doc);
Loading history...
1160
        $refNodes = $xp->query('./ds:SignedInfo/ds:Reference', $this->sigNode);
1161
        Assert::minCount($refNodes, 1, 'There are no Reference nodes', RuntimeException::class);
1162
1163
        $verified = true;
1164
        foreach ($refNodes as $refNode) {
1165
            $verified = $this->processReference($refNode) && $verified;
1166
        }
1167
1168
        return $verified;
1169
    }
1170
}
1171