Total Complexity | 141 |
Total Lines | 1131 |
Duplicated Lines | 0 % |
Changes | 3 | ||
Bugs | 0 | Features | 0 |
Complex classes like Signature often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.
Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.
While breaking up the class, it is a good idea to analyze how other classes use Signature, and based on these observations, apply Extract Interface, too.
1 | <?php |
||
33 | class Signature |
||
34 | { |
||
35 | /** @var array */ |
||
36 | public array $idNS = []; |
||
37 | |||
38 | /** @var array */ |
||
39 | public array $idKeys = []; |
||
40 | |||
41 | /** @var \SimpleSAML\XMLSecurity\Backend\SignatureBackend|null */ |
||
42 | protected ?SignatureBackend $backend = null; |
||
43 | |||
44 | /** @var \DOMElement */ |
||
45 | protected DOMElement $root; |
||
46 | |||
47 | /** @var \DOMElement|null */ |
||
48 | protected ?DOMElement $sigNode = null; |
||
49 | |||
50 | /** @var \DOMElement */ |
||
51 | protected DOMElement $sigMethodNode; |
||
52 | |||
53 | /** @var \DOMElement */ |
||
54 | protected DOMElement $c14nMethodNode; |
||
55 | |||
56 | /** @var \DOMElement */ |
||
57 | protected DOMElement $sigInfoNode; |
||
58 | |||
59 | /** @var \DOMElement|null */ |
||
60 | protected ?DOMElement $objectNode = null; |
||
61 | |||
62 | /** @var string */ |
||
63 | protected string $signfo; |
||
64 | |||
65 | /** @var string */ |
||
66 | protected string $sigAlg; |
||
67 | |||
68 | /** @var \DOMElement[] */ |
||
69 | protected array $verifiedElements = []; |
||
70 | |||
71 | /** @var string */ |
||
72 | protected string $c14nMethod = C::C14N_EXCLUSIVE_WITHOUT_COMMENTS; |
||
73 | |||
74 | /** @var string */ |
||
75 | protected string $nsPrefix = 'ds:'; |
||
76 | |||
77 | /** @var array */ |
||
78 | protected array $algBlacklist = [ |
||
79 | C::SIG_RSA_SHA1, |
||
80 | C::SIG_HMAC_SHA1, |
||
81 | ]; |
||
82 | |||
83 | /** @var array */ |
||
84 | protected array $references = []; |
||
85 | |||
86 | /** @var bool */ |
||
87 | protected bool $enveloping = false; |
||
88 | |||
89 | |||
90 | /** |
||
91 | * Signature constructor. |
||
92 | * |
||
93 | * @param \DOMElement|string $root The DOM element or a string of data we want to sign. |
||
94 | * @param \SimpleSAML\XMLSecurity\Backend\SignatureBackend|null $backend The backend to use to |
||
95 | * generate or verify signatures. See individual algorithms for defaults. |
||
96 | */ |
||
97 | public function __construct($root, SignatureBackend $backend = null) |
||
98 | { |
||
99 | $this->backend = $backend; |
||
100 | $this->initSignature(); |
||
101 | |||
102 | if (is_string($root)) { |
||
103 | $this->root = $this->addObject($root); |
||
104 | $this->enveloping = true; |
||
105 | } else { |
||
106 | $this->root = $root; |
||
107 | } |
||
108 | } |
||
109 | |||
110 | |||
111 | /** |
||
112 | * Add an object element to the signature containing the given data. |
||
113 | * |
||
114 | * @param \DOMElement|string $data The data we want to envelope inside the signature. |
||
115 | * @param string|null $mimetype An optional mime type to specify. |
||
116 | * @param string|null $encoding An optional encoding to specify. |
||
117 | * |
||
118 | * @return \DOMElement The resulting object element added to the signature. |
||
119 | */ |
||
120 | public function addObject($data, ?string $mimetype = null, ?string $encoding = null): DOMElement |
||
121 | { |
||
122 | if ($this->objectNode === null) { |
||
123 | $this->objectNode = $this->createElement('Object'); |
||
124 | $this->sigNode->appendChild($this->objectNode); |
||
125 | } |
||
126 | |||
127 | if (is_string($mimetype) && !empty($mimetype)) { |
||
128 | $this->objectNode->setAttribute('MimeType', $mimetype); |
||
129 | } |
||
130 | |||
131 | if (is_string($encoding) && !empty($encoding)) { |
||
132 | $this->objectNode->setAttribute('Encoding', $encoding); |
||
133 | } |
||
134 | |||
135 | if ($data instanceof DOMElement) { |
||
136 | $this->objectNode->appendChild($this->sigNode->ownerDocument->importNode($data, true)); |
||
137 | } else { |
||
138 | $this->objectNode->appendChild($this->sigNode->ownerDocument->createTextNode($data)); |
||
139 | } |
||
140 | |||
141 | return $this->objectNode; |
||
142 | } |
||
143 | |||
144 | |||
145 | /** |
||
146 | * Add a reference to a given node (an element or a document). |
||
147 | * |
||
148 | * @param \DOMNode $node A DOMElement that we want to sign, or a DOMDocument if we want to sign the entire document. |
||
149 | * @param string $alg The identifier of a supported digest algorithm to use when processing this reference. |
||
150 | * @param array $transforms An array containing a list of transforms that must be applied to the reference. |
||
151 | * Optional. |
||
152 | * @param array $options An array containing a set of options for this reference. Optional. Supported options are: |
||
153 | * - prefix (string): the XML prefix used in the element being referenced. Defaults to none (no prefix used). |
||
154 | * |
||
155 | * - prefix_ns (string): the namespace associated with the given prefix. Defaults to none (no prefix used). |
||
156 | * |
||
157 | * - id_name (string): the name of the "id" attribute in the referenced element. Defaults to "Id". |
||
158 | * |
||
159 | * - force_uri (boolean): Whether to explicitly add a URI attribute to the reference when referencing a |
||
160 | * DOMDocument or not. Defaults to true. If force_uri is false and $node is a DOMDocument, the URI attribute |
||
161 | * will be completely omitted. |
||
162 | * |
||
163 | * - overwrite (boolean): Whether to overwrite the identifier existing in the element referenced with a new, |
||
164 | * random one, or not. Defaults to true. |
||
165 | * |
||
166 | * @throws \SimpleSAML\XMLSecurity\Exception\InvalidArgumentException If $node is not |
||
167 | * an instance of DOMDocument or DOMElement. |
||
168 | */ |
||
169 | public function addReference(DOMNode $node, string $alg, array $transforms = [], array $options = []): void |
||
170 | { |
||
171 | Assert::isInstanceOfAny( |
||
172 | $node, |
||
173 | [DOMDocument::class, DOMElement::class], |
||
174 | 'Only references to the DOM document or elements are allowed.' |
||
175 | ); |
||
176 | |||
177 | $prefix = @$options['prefix'] ?: null; |
||
178 | $prefixNS = @$options['prefix_ns'] ?: null; |
||
179 | $idName = @$options['id_name'] ?: 'Id'; |
||
180 | $attrName = $prefix ? $prefix . ':' . $idName : $idName; |
||
181 | $forceURI = true; |
||
182 | if (isset($options['force_uri'])) { |
||
183 | $forceURI = $options['force_uri']; |
||
184 | } |
||
185 | $overwrite = true; |
||
186 | if (isset($options['overwrite'])) { |
||
187 | $overwrite = $options['overwrite']; |
||
188 | } |
||
189 | |||
190 | $reference = $this->createElement('Reference'); |
||
191 | $this->sigInfoNode->appendChild($reference); |
||
192 | |||
193 | // register reference |
||
194 | $includeCommentNodes = false; |
||
195 | if ($node instanceof DOMElement) { |
||
196 | $uri = null; |
||
197 | if (!$overwrite) { |
||
198 | $uri = $prefixNS ? $node->getAttributeNS($prefixNS, $idName) : $node->getAttribute($idName); |
||
199 | } |
||
200 | if (empty($uri)) { |
||
201 | $uri = Utils\Random::generateGUID(); |
||
202 | $node->setAttributeNS($prefixNS, $attrName, $uri); |
||
203 | } |
||
204 | |||
205 | if ( |
||
206 | in_array(C::C14N_EXCLUSIVE_WITH_COMMENTS, $transforms) |
||
207 | || in_array(C::C14N_INCLUSIVE_WITH_COMMENTS, $transforms) |
||
208 | ) { |
||
209 | $includeCommentNodes = true; |
||
210 | $reference->setAttribute('URI', "#xpointer($attrName('$uri'))"); |
||
211 | } else { |
||
212 | $reference->setAttribute('URI', '#' . $uri); |
||
213 | } |
||
214 | } elseif ($forceURI) { |
||
215 | // $node is a \DOMDocument, should add a reference to the root element (enveloped signature) |
||
216 | if (in_array($this->c14nMethod, [C::C14N_INCLUSIVE_WITH_COMMENTS, C::C14N_EXCLUSIVE_WITH_COMMENTS])) { |
||
217 | // if we want to use a C14N method that includes comments, the URI must be an xpointer |
||
218 | $reference->setAttribute('URI', '#xpointer(/)'); |
||
219 | } else { |
||
220 | // C14N without comments, we can set an empty URI |
||
221 | $reference->setAttribute('URI', ''); |
||
222 | } |
||
223 | } |
||
224 | |||
225 | // apply and register transforms |
||
226 | $transformList = $this->createElement('Transforms'); |
||
227 | $reference->appendChild($transformList); |
||
228 | |||
229 | if (!empty($transforms)) { |
||
230 | foreach ($transforms as $transform) { |
||
231 | $transformNode = $this->createElement('Transform'); |
||
232 | $transformList->appendChild($transformNode); |
||
233 | |||
234 | if (is_array($transform) && !empty($transform[C::XPATH_URI]['query'])) { |
||
235 | $transformNode->setAttribute('Algorithm', C::XPATH_URI); |
||
236 | $xpNode = $this->createElement('XPath', $transform[C::XPATH_URI]['query']); |
||
237 | $transformNode->appendChild($xpNode); |
||
238 | } else { |
||
239 | $transformNode->setAttribute('Algorithm', $transform); |
||
240 | } |
||
241 | } |
||
242 | } elseif (!empty($this->c14nMethod)) { |
||
243 | $transformNode = $this->createElement('Transform'); |
||
244 | $transformList->appendChild($transformNode); |
||
245 | $transformNode->setAttribute('Algorithm', $this->c14nMethod); |
||
246 | } |
||
247 | |||
248 | $canonicalData = $this->processTransforms($reference, $node, $includeCommentNodes); |
||
249 | $digest = $this->hash($alg, $canonicalData); |
||
250 | |||
251 | $digestMethod = $this->createElement('DigestMethod'); |
||
252 | $reference->appendChild($digestMethod); |
||
253 | $digestMethod->setAttribute('Algorithm', $alg); |
||
254 | |||
255 | $digestValue = $this->createElement('DigestValue', $digest); |
||
256 | $reference->appendChild($digestValue); |
||
257 | |||
258 | if (!in_array($node, $this->references)) { |
||
259 | $this->references[] = $node; |
||
260 | } |
||
261 | } |
||
262 | |||
263 | |||
264 | /** |
||
265 | * Add a set of references to the signature. |
||
266 | * |
||
267 | * @param \DOMNode[] $nodes An array of DOMNode objects to be referred in the signature. |
||
268 | * @param string $alg The identifier of the digest algorithm to use. |
||
269 | * @param array $transforms An array of transforms to apply to each reference. |
||
270 | * @param array $options An array of options. |
||
271 | * |
||
272 | * @throws \SimpleSAML\XMLSecurity\Exception\InvalidArgumentException If any of the nodes in the $nodes |
||
273 | * array is not an instance of DOMDocument or DOMElement. |
||
274 | * |
||
275 | * @see addReference() |
||
276 | */ |
||
277 | public function addReferences(array $nodes, string $alg, array $transforms = [], $options = []): void |
||
278 | { |
||
279 | foreach ($nodes as $node) { |
||
280 | $this->addReference($node, $alg, $transforms, $options); |
||
281 | } |
||
282 | } |
||
283 | |||
284 | |||
285 | /** |
||
286 | * Attach one or more X509 certificates to the signature. |
||
287 | * |
||
288 | * @param \SimpleSAML\XMLSecurity\Key\X509Certificate[] $certs |
||
289 | * An X509Certificate object or an array of them. |
||
290 | * @param boolean $addSubject Whether to add the subject of the certificate or not. |
||
291 | * @param string|false $digest A digest algorithm identifier if the digest of the certificate should be added. False |
||
292 | * otherwise. |
||
293 | * @param boolean $addIssuerSerial Whether to add the serial number of the issuer or not. |
||
294 | * |
||
295 | * @throws \SimpleSAML\XMLSecurity\Exception\InvalidArgumentException If $certs is not a |
||
296 | * X509Certificate object or an array of them. |
||
297 | */ |
||
298 | public function addX509Certificates( |
||
299 | array $certs, |
||
300 | bool $addSubject = false, |
||
301 | $digest = false, |
||
302 | bool $addIssuerSerial = false |
||
303 | ): void { |
||
304 | Assert::allIsInstanceOf($certs, Key\X509Certificate::class); |
||
305 | |||
306 | $certData = []; |
||
307 | |||
308 | foreach ($certs as $cert) { |
||
309 | $details = $cert->getCertificateDetails(); |
||
310 | |||
311 | if ($addSubject && isset($details['subject'])) { |
||
312 | // add subject |
||
313 | $subjectNameValue = $details['issuer']; |
||
314 | if (is_array($details['subject'])) { |
||
315 | $subjectNameValue = CertificateUtils::parseSubject($details['subject']); |
||
316 | } |
||
317 | $certData[] = new X509SubjectName($subjectNameValue); |
||
318 | } |
||
319 | |||
320 | if ($digest !== false) { |
||
321 | // add certificate digest |
||
322 | $fingerprint = base64_encode(hex2bin($cert->getRawThumbprint($digest))); |
||
323 | $certData[] = new X509Digest($fingerprint, $digest); |
||
324 | } |
||
325 | |||
326 | if ($addIssuerSerial && isset($details['issuer']) && isset($details['serialNumber'])) { |
||
327 | $issuerName = CertificateUtils::parseIssuer($details['issuer']); |
||
328 | |||
329 | $certData[] = new X509IssuerSerial($issuerName, $details['serialNumber']); |
||
330 | } |
||
331 | |||
332 | $certData[] = new X509Certificate(CertificateUtils::stripHeaders($cert->getCertificate())); |
||
333 | } |
||
334 | |||
335 | $keyInfoNode = $this->createElement('KeyInfo'); |
||
336 | |||
337 | $certDataNode = new X509Data($certData); |
||
338 | $certDataNode->toXML($keyInfoNode); |
||
339 | |||
340 | if ($this->objectNode === null) { |
||
341 | $this->sigNode->appendChild($keyInfoNode); |
||
342 | } else { |
||
343 | $this->sigNode->insertBefore($keyInfoNode, $this->objectNode); |
||
344 | } |
||
345 | } |
||
346 | |||
347 | |||
348 | /** |
||
349 | * Append a signature as the last child of the signed element. |
||
350 | * |
||
351 | * @return \DOMNode The appended signature. |
||
352 | */ |
||
353 | public function append(): DOMNode |
||
354 | { |
||
355 | return $this->insert(); |
||
356 | } |
||
357 | |||
358 | |||
359 | /** |
||
360 | * Use this signature as an enveloping signature, effectively adding the signed data to a ds:Object element. |
||
361 | * |
||
362 | * @param string|null $mimetype The mime type corresponding to the signed data. |
||
363 | * @param string|null $encoding The encoding corresponding to the signed data. |
||
364 | */ |
||
365 | public function envelop(string $mimetype = null, string $encoding = null): void |
||
368 | } |
||
369 | |||
370 | |||
371 | /** |
||
372 | * Build a new XML digital signature from a given document or node. |
||
373 | * |
||
374 | * @param \DOMNode $node The DOMDocument or DOMElement that contains the signature. |
||
375 | * |
||
376 | * @return Signature A Signature object corresponding to the signature present in the given DOM document or element. |
||
377 | * |
||
378 | * @throws \SimpleSAML\XMLSecurity\Exception\InvalidArgumentException If $node is not |
||
379 | * an instance of DOMDocument or DOMElement. |
||
380 | * @throws \SimpleSAML\XMLSecurity\Exception\NoSignatureFound If there is no signature in the $node. |
||
381 | */ |
||
382 | public static function fromXML(DOMNode $node): Signature |
||
383 | { |
||
384 | Assert::isInstanceOfAny( |
||
385 | $node, |
||
386 | [DOMDocument::class, DOMElement::class], |
||
387 | 'Signatures can only be created from DOM documents or elements' |
||
388 | ); |
||
389 | |||
390 | $signature = self::findSignature($node); |
||
391 | if ($node instanceof DOMDocument) { |
||
392 | $node = $node->documentElement; |
||
393 | } |
||
394 | $dsig = new self($node); |
||
395 | $dsig->setSignatureElement($signature); |
||
396 | return $dsig; |
||
397 | } |
||
398 | |||
399 | |||
400 | /** |
||
401 | * Obtain the list of currently blacklisted algorithms. |
||
402 | * |
||
403 | * Signatures using blacklisted algorithms cannot be created or verified. |
||
404 | * |
||
405 | * @return array An array containing the identifiers of the algorithms blacklisted currently. |
||
406 | */ |
||
407 | public function getBlacklistedAlgorithms(): array |
||
408 | { |
||
409 | return $this->algBlacklist; |
||
410 | } |
||
411 | |||
412 | |||
413 | /** |
||
414 | * Get the list of namespaces to designate ID attributes. |
||
415 | * |
||
416 | * @return array An array of strings with the namespaces used in ID attributes. |
||
417 | */ |
||
418 | public function getIdNamespaces(): array |
||
419 | { |
||
420 | return $this->idNS; |
||
421 | } |
||
422 | |||
423 | |||
424 | /** |
||
425 | * Get a list of attributes used as an ID. |
||
426 | * |
||
427 | * @return array An array of strings with the attributes used as an ID. |
||
428 | */ |
||
429 | public function getIdAttributes(): array |
||
430 | { |
||
431 | return $this->idKeys; |
||
432 | } |
||
433 | |||
434 | |||
435 | /** |
||
436 | * Get the root configured for this signature. |
||
437 | * |
||
438 | * This will be the signed element, whether that's a user-provided XML element or a ds:Object element containing |
||
439 | * the actual data (which can in turn be either XML or not). |
||
440 | * |
||
441 | * @return \DOMElement The root element for this signature. |
||
442 | */ |
||
443 | public function getRoot(): DOMElement |
||
444 | { |
||
445 | return $this->root; |
||
446 | } |
||
447 | |||
448 | |||
449 | /** |
||
450 | * Get the identifier of the algorithm used in this signature. |
||
451 | * |
||
452 | * @return string The identifier of the algorithm used in this signature. |
||
453 | */ |
||
454 | public function getSignatureMethod(): string |
||
455 | { |
||
456 | return $this->sigAlg; |
||
457 | } |
||
458 | |||
459 | |||
460 | /** |
||
461 | * Get a list of elements verified by this signature. |
||
462 | * |
||
463 | * The elements in this list are referenced by the signature and the references verified to be correct. However, |
||
464 | * this doesn't mean the signature is valid, only that the references were so. |
||
465 | * |
||
466 | * Note that the list returned will be empty unless verify() has been called before. |
||
467 | * |
||
468 | * @return \DOMElement[] A list of elements correctly referenced by this signature. An empty list of verify() has |
||
469 | * not been called yet, or if the references couldn't be verified. |
||
470 | */ |
||
471 | public function getVerifiedElements(): array |
||
472 | { |
||
473 | return $this->verifiedElements; |
||
474 | } |
||
475 | |||
476 | |||
477 | /** |
||
478 | * Insert a signature as a child of the signed element, optionally before a given element. |
||
479 | * |
||
480 | * @param \DOMElement|false $before An optional DOM element the signature should be prepended to. |
||
481 | * |
||
482 | * @return \DOMNode The inserted signature. |
||
483 | * |
||
484 | * @throws \SimpleSAML\XMLSecurity\Exception\RuntimeException If this signature is in enveloping mode. |
||
485 | */ |
||
486 | public function insert($before = false): DOMNode |
||
487 | { |
||
488 | Assert::false( |
||
489 | $this->enveloping, |
||
490 | 'Cannot insert the signature in the object it is enveloping.', |
||
491 | RuntimeException::class |
||
492 | ); |
||
493 | |||
494 | $signature = $this->root->ownerDocument->importNode($this->sigNode, true); |
||
495 | |||
496 | if ($before instanceof DOMElement) { |
||
497 | return $this->root->insertBefore($signature, $before); |
||
498 | } |
||
499 | return $this->root->insertBefore($signature); |
||
500 | } |
||
501 | |||
502 | |||
503 | /** |
||
504 | * Prepend a signature as the first child of the signed element. |
||
505 | * |
||
506 | * @return \DOMNode The prepended signature. |
||
507 | */ |
||
508 | public function prepend(): DOMNode |
||
517 | } |
||
518 | |||
519 | |||
520 | /** |
||
521 | * Set the backend to create or verify signatures. |
||
522 | * |
||
523 | * @param SignatureBackend $backend The SignatureBackend implementation to use. See individual algorithms for |
||
524 | * details about the default backends used. |
||
525 | */ |
||
526 | public function setBackend(SignatureBackend $backend): void |
||
527 | { |
||
528 | $this->backend = $backend; |
||
529 | } |
||
530 | |||
531 | |||
532 | /** |
||
533 | * Set the list of currently blacklisted algorithms. |
||
534 | * |
||
535 | * Signatures using blacklisted algorithms cannot be created or verified. |
||
536 | * |
||
537 | * @param array $algs An array containing the identifiers of the algorithms to blacklist. |
||
538 | */ |
||
539 | public function setBlacklistedAlgorithms(array $algs): void |
||
540 | { |
||
541 | $this->algBlacklist = $algs; |
||
542 | } |
||
543 | |||
544 | |||
545 | /** |
||
546 | * Set the canonicalization method used in this signature. |
||
547 | * |
||
548 | * Note that exclusive canonicalization without comments is used by default, so it's not necessary to call |
||
549 | * setCanonicalizationMethod() if that canonicalization method is desired. |
||
550 | * |
||
551 | * @param string $method The identifier of the canonicalization method to use. |
||
552 | * |
||
553 | * @throws \SimpleSAML\XMLSecurity\Exception\InvalidArgumentException If $method is not a valid |
||
554 | * identifier of a supported canonicalization method. |
||
555 | */ |
||
556 | public function setCanonicalizationMethod(string $method): void |
||
557 | { |
||
558 | Assert::oneOf( |
||
559 | $method, |
||
560 | [ |
||
561 | C::C14N_EXCLUSIVE_WITH_COMMENTS, |
||
562 | C::C14N_EXCLUSIVE_WITHOUT_COMMENTS, |
||
563 | C::C14N_INCLUSIVE_WITH_COMMENTS, |
||
564 | C::C14N_INCLUSIVE_WITHOUT_COMMENTS |
||
565 | ], |
||
566 | 'Invalid canonicalization method', |
||
567 | InvalidArgumentException::class |
||
568 | ); |
||
569 | |||
570 | $this->c14nMethod = $method; |
||
571 | $this->c14nMethodNode->setAttribute('Algorithm', $method); |
||
572 | } |
||
573 | |||
574 | |||
575 | /** |
||
576 | * Set the encoding for the signed contents in an enveloping signature. |
||
577 | * |
||
578 | * @param string $encoding The encoding used in the signed contents. |
||
579 | * |
||
580 | * @throws \SimpleSAML\XMLSecurity\Exception\RuntimeException If this is not an enveloping signature. |
||
581 | */ |
||
582 | public function setEncoding(string $encoding): void |
||
583 | { |
||
584 | Assert::true( |
||
585 | $this->enveloping, |
||
586 | 'Cannot set the encoding for non-enveloping signatures.', |
||
587 | RuntimeException::class |
||
588 | ); |
||
589 | |||
590 | $this->root->setAttribute('Encoding', $encoding); |
||
591 | } |
||
592 | |||
593 | |||
594 | /** |
||
595 | * Set a list of attributes used as an ID. |
||
596 | * |
||
597 | * @param array $keys An array of strings with the attributes used as an ID. |
||
598 | */ |
||
599 | public function setIdAttributes(array $keys): void |
||
600 | { |
||
601 | $this->idKeys = $keys; |
||
602 | } |
||
603 | |||
604 | |||
605 | /** |
||
606 | * Set the list of namespaces to designate ID attributes. |
||
607 | * |
||
608 | * @param array $namespaces An array of strings with the namespaces used in ID attributes. |
||
609 | */ |
||
610 | public function setIdNamespaces(array $namespaces): void |
||
611 | { |
||
612 | $this->idNS = $namespaces; |
||
613 | } |
||
614 | |||
615 | |||
616 | /** |
||
617 | * Set the mime type for the signed contents in an enveloping signature. |
||
618 | * |
||
619 | * @param string $mimetype The mime type of the signed contents. |
||
620 | * |
||
621 | * @throws \SimpleSAML\XMLSecurity\Exception\RuntimeException If this is not an enveloping signature. |
||
622 | */ |
||
623 | public function setMimeType(string $mimetype): void |
||
624 | { |
||
625 | Assert::true( |
||
626 | $this->enveloping, |
||
627 | 'Cannot set the mime type for non-enveloping signatures.', |
||
628 | RuntimeException::class |
||
629 | ); |
||
630 | |||
631 | $this->root->setAttribute('MimeType', $mimetype); |
||
632 | } |
||
633 | |||
634 | |||
635 | /** |
||
636 | * Set the signature element to a given one, and initialize the signature from there. |
||
637 | * |
||
638 | * @param \DOMElement $element A DOM element containing an XML signature. |
||
639 | * |
||
640 | * @throws \SimpleSAML\XML\Exception\InvalidDOMElementException If the element does not correspond to an XML |
||
641 | * signature or it is malformed (e.g. there are missing mandatory elements or attributes). |
||
642 | */ |
||
643 | public function setSignatureElement(DOMElement $element): void |
||
644 | { |
||
645 | Assert::same($element->localName, 'Signature', InvalidDOMElementException::class); |
||
646 | Assert::same($element->namespaceURI, Sig::NS, InvalidDOMElementException::class); |
||
647 | |||
648 | $this->sigNode = $element; |
||
649 | |||
650 | $xp = XP::getXPath($this->sigNode->ownerDocument); |
||
651 | |||
652 | $signedInfoNodes = $xp->query('./ds:SignedInfo', $this->sigNode); |
||
653 | |||
654 | Assert::minCount( |
||
655 | $signedInfoNodes, |
||
656 | 1, |
||
657 | 'There is no SignedInfo element in the signature', |
||
658 | RuntimeException::class |
||
659 | ); |
||
660 | $this->sigInfoNode = $signedInfoNodes->item(0); |
||
661 | |||
662 | |||
663 | $this->sigAlg = $xp->evaluate('string(./ds:SignedInfo/ds:SignatureMethod/@Algorithm)', $this->sigNode); |
||
664 | Assert::stringNotEmpty($this->sigAlg, 'Unable to determine SignatureMethod', RuntimeException::class); |
||
665 | |||
666 | $c14nMethodNodes = $xp->query('./ds:CanonicalizationMethod', $this->sigInfoNode); |
||
667 | Assert::minCount( |
||
668 | $c14nMethodNodes, |
||
669 | 1, |
||
670 | 'There is no CanonicalizationMethod in the signature', |
||
671 | RuntimeException::class |
||
672 | ); |
||
673 | |||
674 | $this->c14nMethodNode = $c14nMethodNodes->item(0); |
||
675 | if (!$this->c14nMethodNode->hasAttribute('Algorithm')) { |
||
676 | throw new RuntimeException('CanonicalizationMethod missing required Algorithm attribute'); |
||
677 | } |
||
678 | $this->c14nMethod = $this->c14nMethodNode->getAttribute('Algorithm'); |
||
679 | } |
||
680 | |||
681 | |||
682 | /** |
||
683 | * Sign the document or element. |
||
684 | * |
||
685 | * This method will finish the signature process. It will create an XML signature valid for document or elements |
||
686 | * specified previously with addReference() or addReferences(). If none of those methods have been called previous |
||
687 | * to calling sign() (there are no references in the signature), the $root passed during construction of the |
||
688 | * Signature object will be referenced automatically. |
||
689 | * |
||
690 | * @param \SimpleSAML\XMLSecurity\Key\AbstractKey $key The key to use for signing. Bear in mind that the type of |
||
691 | * this key must be compatible with the types of key accepted by the algorithm specified in $alg. |
||
692 | * @param string $alg The identifier of the signature algorithm to use. See \SimpleSAML\XMLSecurity\Constants. |
||
693 | * @param bool $appendToNode Whether to append the signature as the last child of the root element or not. |
||
694 | * |
||
695 | * @throws \SimpleSAML\XMLSecurity\Exception\InvalidArgumentException If $appendToNode is true and |
||
696 | * this is an enveloping signature. |
||
697 | */ |
||
698 | public function sign(Key\AbstractKey $key, string $alg, bool $appendToNode = false): void |
||
699 | { |
||
700 | Assert::false( |
||
701 | ($this->enveloping && $appendToNode), |
||
702 | 'Cannot append the signature, we are in enveloping mode.', |
||
703 | InvalidArgumentException::class |
||
704 | ); |
||
705 | |||
706 | $this->sigMethodNode->setAttribute('Algorithm', $alg); |
||
707 | $factory = new SignatureAlgorithmFactory($this->algBlacklist); |
||
708 | $signer = $factory->getAlgorithm($alg, $key); |
||
709 | if ($this->backend !== null) { |
||
710 | $signer->setBackend($this->backend); |
||
711 | } |
||
712 | |||
713 | if (empty($this->references)) { |
||
714 | // no references have been added, ref root |
||
715 | $transforms = []; |
||
716 | if (!$this->enveloping) { |
||
717 | $transforms[] = C::XMLDSIG_ENVELOPED; |
||
718 | } |
||
719 | $this->addReference($this->root->ownerDocument, $signer->getDigest(), $transforms, []); |
||
720 | } |
||
721 | |||
722 | if ($appendToNode) { |
||
723 | $this->sigNode = $this->append(); |
||
724 | } elseif (in_array($this->c14nMethod, [C::C14N_INCLUSIVE_WITHOUT_COMMENTS, C::C14N_INCLUSIVE_WITH_COMMENTS])) { |
||
725 | // append Signature to root node for inclusive canonicalization |
||
726 | $restoreSigNode = $this->sigNode; |
||
727 | $this->sigNode = $this->prepend(); |
||
728 | } |
||
729 | |||
730 | $sigValue = base64_encode($signer->sign($this->canonicalizeData($this->sigInfoNode, $this->c14nMethod))); |
||
731 | |||
732 | // remove Signature from node if we added it for c14n |
||
733 | if ( |
||
734 | !$appendToNode && |
||
735 | in_array($this->c14nMethod, [C::C14N_INCLUSIVE_WITHOUT_COMMENTS, C::C14N_INCLUSIVE_WITH_COMMENTS]) |
||
736 | ) { // remove from root in case we added it for inclusive canonicalization |
||
737 | $this->root->removeChild($this->root->lastChild); |
||
738 | /** @var \DOMElement $restoreSigNode */ |
||
739 | $this->sigNode = $restoreSigNode; |
||
740 | } |
||
741 | |||
742 | $sigValueNode = $this->createElement('SignatureValue', $sigValue); |
||
743 | if ($this->sigInfoNode->nextSibling) { |
||
744 | $this->sigInfoNode->nextSibling->parentNode->insertBefore($sigValueNode, $this->sigInfoNode->nextSibling); |
||
745 | } else { |
||
746 | $this->sigNode->appendChild($sigValueNode); |
||
747 | } |
||
748 | } |
||
749 | |||
750 | |||
751 | /** |
||
752 | * Verify this signature with a given key. |
||
753 | * |
||
754 | * @param \SimpleSAML\XMLSecurity\Key\AbstractKey $key The key to use to verify this signature. |
||
755 | * |
||
756 | * @return bool True if the signature can be verified with $key, false otherwise. |
||
757 | * |
||
758 | * @throws \SimpleSAML\XMLSecurity\Exception\RuntimeException If there is no SignatureValue in |
||
759 | * the signature, or we couldn't verify all the references. |
||
760 | */ |
||
761 | public function verify(Key\AbstractKey $key): bool |
||
762 | { |
||
763 | $xp = XP::getXPath($this->sigNode->ownerDocument); |
||
764 | $sigval = $xp->evaluate('string(./ds:SignatureValue)', $this->sigNode); |
||
765 | if (empty($sigval)) { |
||
766 | throw new RuntimeException('Unable to locate SignatureValue'); |
||
767 | } |
||
768 | |||
769 | $siginfo = $this->canonicalizeData($this->sigInfoNode, $this->c14nMethod); |
||
770 | if (!$this->validateReferences()) { |
||
771 | throw new RuntimeException('Unable to verify all references'); |
||
772 | } |
||
773 | |||
774 | $factory = new SignatureAlgorithmFactory($this->algBlacklist); |
||
775 | $alg = $factory->getAlgorithm($this->sigAlg, $key); |
||
776 | if ($this->backend !== null) { |
||
777 | $alg->setBackend($this->backend); |
||
778 | } |
||
779 | return $alg->verify($siginfo, base64_decode($sigval)); |
||
780 | } |
||
781 | |||
782 | |||
783 | /** |
||
784 | * Canonicalize any given node. |
||
785 | * |
||
786 | * @param \DOMNode $node The DOM node that needs canonicalization. |
||
787 | * @param string $c14nMethod The identifier of the canonicalization algorithm to use. |
||
788 | * See \SimpleSAML\XMLSecurity\Constants. |
||
789 | * @param array|null $xpaths An array of xpaths to filter the nodes by. Defaults to null (no filters). |
||
790 | * @param array|null $prefixes An array of namespace prefixes to filter the nodes by. Defaults to null (no filters). |
||
791 | * |
||
792 | * @return string The canonical representation of the given DOM node, according to the algorithm requested. |
||
793 | */ |
||
794 | protected function canonicalizeData( |
||
795 | DOMNode $node, |
||
796 | string $c14nMethod, |
||
797 | array $xpaths = null, |
||
798 | array $prefixes = null |
||
799 | ): string { |
||
800 | $exclusive = false; |
||
801 | $withComments = false; |
||
802 | switch ($c14nMethod) { |
||
803 | case C::C14N_EXCLUSIVE_WITH_COMMENTS: |
||
804 | case C::C14N_INCLUSIVE_WITH_COMMENTS: |
||
805 | $withComments = true; |
||
806 | } |
||
807 | switch ($c14nMethod) { |
||
808 | case C::C14N_EXCLUSIVE_WITH_COMMENTS: |
||
809 | case C::C14N_EXCLUSIVE_WITHOUT_COMMENTS: |
||
810 | $exclusive = true; |
||
811 | } |
||
812 | |||
813 | if ( |
||
814 | is_null($xpaths) |
||
815 | && ($node->ownerDocument !== null) |
||
816 | && $node->isSameNode($node->ownerDocument->documentElement) |
||
817 | ) { |
||
818 | // check for any PI or comments as they would have been excluded |
||
819 | $element = $node; |
||
820 | while ($refNode = $element->previousSibling) { |
||
821 | if ( |
||
822 | (($refNode->nodeType === XML_COMMENT_NODE) && $withComments) |
||
823 | || $refNode->nodeType === XML_PI_NODE |
||
824 | ) { |
||
825 | break; |
||
826 | } |
||
827 | $element = $refNode; |
||
828 | } |
||
829 | if ($refNode == null) { |
||
830 | $node = $node->ownerDocument; |
||
831 | } |
||
832 | } |
||
833 | |||
834 | return $node->C14N($exclusive, $withComments, $xpaths, $prefixes); |
||
835 | } |
||
836 | |||
837 | |||
838 | /** |
||
839 | * Create a new element in this signature. |
||
840 | * |
||
841 | * @param string $name The name of this element. |
||
842 | * @param string|null $content The text contents of the element, or null if it is not supposed to have any text |
||
843 | * contents. Defaults to null. |
||
844 | * @param string $ns The namespace the new element must be created under. Defaults to the standard XMLDSIG |
||
845 | * namespace. |
||
846 | * |
||
847 | * @return \DOMElement A new DOM element with the given name. |
||
848 | */ |
||
849 | protected function createElement( |
||
850 | string $name, |
||
851 | string $content = null, |
||
852 | string $ns = C::XMLDSIGNS |
||
853 | ): DOMElement { |
||
854 | if ($this->sigNode === null) { |
||
855 | // initialize signature |
||
856 | $doc = DOMDocumentFactory::create(); |
||
857 | } else { |
||
858 | $doc = $this->sigNode->ownerDocument; |
||
859 | } |
||
860 | |||
861 | $nsPrefix = $this->nsPrefix; |
||
862 | |||
863 | if ($content !== null) { |
||
864 | return $doc->createElementNS($ns, $nsPrefix . $name, $content); |
||
865 | } |
||
866 | |||
867 | return $doc->createElementNS($ns, $nsPrefix . $name); |
||
868 | } |
||
869 | |||
870 | |||
871 | /** |
||
872 | * Find a signature from a given node. |
||
873 | * |
||
874 | * @param \DOMNode $node A DOMElement node where a signature is expected as a child (enveloped) or a DOMDocument |
||
875 | * node to search for document signatures (one single reference with an empty URI). |
||
876 | * |
||
877 | * @return \DOMElement The signature element. |
||
878 | * |
||
879 | * @throws \SimpleSAML\XMLSecurity\Exception\RuntimeException If there is no DOMDocument element available. |
||
880 | * @throws \SimpleSAML\XMLSecurity\Exception\NoSignatureFound If no signature is found. |
||
881 | */ |
||
882 | protected static function findSignature(DOMNode $node): DOMElement |
||
895 | } |
||
896 | |||
897 | |||
898 | /** |
||
899 | * Compute the hash for some data with a given algorithm. |
||
900 | * |
||
901 | * @param string $alg The identifier of the algorithm to use. |
||
902 | * @param string $data The data to digest. |
||
903 | * @param bool $encode Whether to bas64-encode the result or not. Defaults to true. |
||
904 | * |
||
905 | * @return string The (binary or base64-encoded) digest corresponding to the given data. |
||
906 | * |
||
907 | * @throws \SimpleSAML\XMLSecurity\Exception\InvalidArgumentException If $alg is not a valid |
||
908 | * identifier of a supported digest algorithm. |
||
909 | */ |
||
910 | protected function hash(string $alg, string $data, bool $encode = true): string |
||
911 | { |
||
912 | Assert::keyExists( |
||
913 | C::$DIGEST_ALGORITHMS, |
||
914 | $alg, |
||
915 | 'Unsupported digest method "%s"', |
||
916 | InvalidArgumentException::class |
||
917 | ); |
||
918 | |||
919 | $digest = hash(C::$DIGEST_ALGORITHMS[$alg], $data, true); |
||
920 | return $encode ? base64_encode($digest) : $digest; |
||
921 | } |
||
922 | |||
923 | |||
924 | /** |
||
925 | * Initialize the basic structure of a signature from scratch. |
||
926 | * |
||
927 | */ |
||
928 | protected function initSignature(): void |
||
940 | } |
||
941 | |||
942 | |||
943 | /** |
||
944 | * Process a given reference, by looking for it, processing the specified transforms, canonicalizing the result |
||
945 | * and comparing its corresponding digest. |
||
946 | * |
||
947 | * Verified references will be stored in the "verifiedElements" property. |
||
948 | * |
||
949 | * @param \DOMElement $ref The ds:Reference element to process. |
||
950 | * |
||
951 | * @return bool True if the digest of the processed reference matches the one given, false otherwise. |
||
952 | * |
||
953 | * @throws \SimpleSAML\XMLSecurity\Exception\RuntimeException If the referenced element is missing or |
||
954 | * the reference points to an external document. |
||
955 | * |
||
956 | * @see http://www.w3.org/TR/xmldsig-core/#sec-ReferenceProcessingModel |
||
957 | */ |
||
958 | protected function processReference(DOMElement $ref): bool |
||
959 | { |
||
960 | /* |
||
961 | * Depending on the URI, we may need to remove comments during canonicalization. |
||
962 | * See: http://www.w3.org/TR/xmldsig-core/#sec-ReferenceProcessingModel |
||
963 | */ |
||
964 | $includeCommentNodes = true; |
||
965 | $dataObject = $ref->ownerDocument; |
||
966 | if ($ref->hasAttribute("URI")) { |
||
967 | $uri = $ref->getAttribute('URI'); |
||
968 | if (empty($uri)) { |
||
969 | // this reference identifies the enclosing XML, it should not include comments |
||
970 | $includeCommentNodes = false; |
||
971 | } |
||
972 | $arUrl = parse_url($uri); |
||
973 | if (empty($arUrl['path'])) { |
||
974 | if ($identifier = @$arUrl['fragment']) { |
||
975 | /* |
||
976 | * This reference identifies a node with the given ID by using a URI on the form '#identifier'. |
||
977 | * This should not include comments. |
||
978 | */ |
||
979 | $includeCommentNodes = false; |
||
980 | |||
981 | $xp = XP::getXPath($ref->ownerDocument); |
||
982 | if ($this->idNS && is_array($this->idNS)) { |
||
983 | foreach ($this->idNS as $nspf => $ns) { |
||
984 | $xp->registerNamespace($nspf, $ns); |
||
985 | } |
||
986 | } |
||
987 | $iDlist = '@Id="' . $identifier . '"'; |
||
988 | if (is_array($this->idKeys)) { |
||
989 | foreach ($this->idKeys as $idKey) { |
||
990 | $iDlist .= " or @$idKey='$identifier'"; |
||
991 | } |
||
992 | } |
||
993 | $query = '//*[' . $iDlist . ']'; |
||
994 | $dataObject = $xp->query($query)->item(0); |
||
995 | if ($dataObject === null) { |
||
996 | throw new RuntimeException('Reference not found'); |
||
997 | } |
||
998 | } |
||
999 | } else { |
||
1000 | throw new RuntimeException('Processing of external documents is not supported'); |
||
1001 | } |
||
1002 | } else { |
||
1003 | // this reference identifies the root node with an empty URI, it should not include comments |
||
1004 | $includeCommentNodes = false; |
||
1005 | } |
||
1006 | |||
1007 | $data = $this->processTransforms($ref, $dataObject, $includeCommentNodes); |
||
1008 | if (!$this->validateDigest($ref, $data)) { |
||
1009 | return false; |
||
1010 | } |
||
1011 | |||
1012 | // parse the canonicalized reference... |
||
1013 | $doc = DOMDocumentFactory::create(); |
||
1014 | $doc->loadXML($data); |
||
1015 | $dataObject = $doc->documentElement; |
||
1016 | |||
1017 | // ... and add it to the list of verified elements |
||
1018 | if (!empty($identifier)) { |
||
1019 | $this->verifiedElements[$identifier] = $dataObject; |
||
1020 | } else { |
||
1021 | $this->verifiedElements[] = $dataObject; |
||
1022 | } |
||
1023 | |||
1024 | return true; |
||
1025 | } |
||
1026 | |||
1027 | |||
1028 | /** |
||
1029 | * Process all transforms specified by a given Reference element. |
||
1030 | * |
||
1031 | * @param \DOMElement $ref The Reference element. |
||
1032 | * @param mixed $data The data referenced. |
||
1033 | * @param bool $includeCommentNodes Whether to allow canonicalization with comments or not. |
||
1034 | * |
||
1035 | * @return string The canonicalized data after applying all transforms specified by $ref. |
||
1036 | * |
||
1037 | * @see http://www.w3.org/TR/xmldsig-core/#sec-ReferenceProcessingModel |
||
1038 | */ |
||
1039 | protected function processTransforms(DOMElement $ref, $data, bool $includeCommentNodes = false): string |
||
1116 | } |
||
1117 | |||
1118 | |||
1119 | /** |
||
1120 | * Compute and compare the digest corresponding to some data given to the one specified by a reference. |
||
1121 | * |
||
1122 | * @param \DOMElement $ref The ds:Reference element containing the digest. |
||
1123 | * @param string $data The referenced element, canonicalized, to digest and compare. |
||
1124 | * |
||
1125 | * @return bool True if the resulting digest matches the one in the reference, false otherwise. |
||
1126 | */ |
||
1127 | protected function validateDigest(DOMElement $ref, string $data): bool |
||
1128 | { |
||
1129 | $xp = XP::getXPath($ref->ownerDocument); |
||
1130 | $alg = $xp->evaluate('string(./ds:DigestMethod/@Algorithm)', $ref); |
||
1131 | $computed = $this->hash($alg, $data, false); |
||
1132 | $evaluated = base64_decode($xp->evaluate('string(./ds:DigestValue)', $ref)); |
||
1133 | return Sec::compareStrings($computed, $evaluated); |
||
1134 | } |
||
1135 | |||
1136 | |||
1137 | /** |
||
1138 | * Iterate over the references specified by the signature, apply their transforms, and validate their digests |
||
1139 | * against the referenced elements. |
||
1140 | * |
||
1141 | * @return boolean True if all references could be verified, false otherwise. |
||
1142 | * |
||
1143 | * @throws \SimpleSAML\XMLSecurity\Exception\RuntimeException If there are no references. |
||
1144 | */ |
||
1145 | protected function validateReferences(): bool |
||
1164 | } |
||
1165 | } |
||
1166 |