Debian Codegraph @

signxml/verifier.py

raw
1 from base64 import b64decode
2 from dataclasses import dataclass, replace
3 from typing import Callable, FrozenSet, List, Optional, Tuple, Union
4 from warnings import warn
5
6 import cryptography.exceptions
7 from cryptography import x509
8 from cryptography.hazmat.primitives.asymmetric import dsa, ec, rsa, utils
9 from cryptography.hazmat.primitives.asymmetric.padding import MGF1, PSS, AsymmetricPadding, PKCS1v15
10 from cryptography.hazmat.primitives.hmac import HMAC
11 from cryptography.hazmat.primitives.serialization import Encoding, PublicFormat, load_der_public_key
12 from lxml import etree
13
14 from .algorithms import (
15 CanonicalizationMethod,
16 DigestAlgorithm,
17 SignatureConstructionMethod,
18 SignatureMethod,
19 digest_algorithm_implementations,
20 )
21 from .exceptions import InvalidCertificate, InvalidDigest, InvalidInput, InvalidSignature, SignXMLException
22 from .processor import XMLSignatureProcessor
23 from .util import (
24 X509CertChainVerifier,
25 _remove_sig,
26 add_pem_header,
27 bits_to_bytes_unit,
28 bytes_to_long,
29 ds_tag,
30 namespaces,
31 )
32
33
34 @dataclass(frozen=True)
35 class SignatureConfiguration:
36 """
37 A container holding signature settings that will be used to assert properties of the signature.
38 """
39
40 require_x509: bool = True
41 """
42 If ``True``, a valid X.509 certificate-based signature with an established chain of trust is required to
43 pass validation. If ``False``, other types of valid signatures (e.g. HMAC or RSA public key) are accepted.
44
45 Ensure you establish trust: to specify an HMAC shared secret that will be required to be used by the signature, use
46 the ``hmac_key`` parameter. If ``require_x509`` is ``False`` and no ``hmac_key`` is set, any valid XML signature
47 satisfying the other SignatureConfiguration parameters will be accepted, regardless of the key used. You must then
48 establish trust by examining the ``VerifyResult`` contents, in particular asserting on the value of ``signature_key``.
49 """
50
51 location: str = ".//"
52 """
53 XPath location where the signature tag will be expected. By default, the signature tag is expected to be a child of
54 the top level element (i.e. enveloped at the top level). If your signature is enveloping (i.e. the ``ds:Signature``
55 tag is itself the top level tag), it is recommended that you set this to ``./``. If your signature is nested
56 elsewhere in the document, you can reference the full path as ``./{ns}Tag1/{ns}Tag2/{ns}Tag3/``. If you wish to
57 search for the signature anywhere in the document, you can set this to ``.//``.
58 """
59
60 expect_references: Union[int, bool] = 1
61 """
62 Number of references to expect in the signature. If this is not 1, an array of VerifyResults is returned.
63 If set to a non-integer, any number of references is accepted (otherwise a mismatch raises an error).
64 """
65
66 signature_methods: FrozenSet[SignatureMethod] = frozenset(sm for sm in SignatureMethod if "SHA1" not in sm.name)
67 """
68 Set of acceptable signature methods (signature algorithms). Any signature generated using an algorithm not listed
69 here will fail verification. It is recommended that you restrict this set to only methods expected to be used in
70 signatures handled by your application.
71 """
72
73 digest_algorithms: FrozenSet[DigestAlgorithm] = frozenset(da for da in DigestAlgorithm if "SHA1" not in da.name)
74 """
75 Set of acceptable digest algorithms. Any signature or reference transform generated using an algorithm not listed
76 here will cause verification to fail. It is recommended that you restrict this set to only methods expected to be
77 used in signatures handled by your application.
78 """
79
80 ignore_ambiguous_key_info: bool = False
81 """
82 Ignore the presence of a KeyValue element when X509Data is present in the signature and used for verifying.
83 The presence of both elements is an ambiguity and a security hazard. The public key used to sign the
84 document is already encoded in the certificate (which is in X509Data), so the verifier must either ignore
85 KeyValue or make sure it matches what's in the certificate. When set to ``False``, SignXML compares KeyValue
86 (and DEREncodedKeyValue) against the X.509 certificate and raises InvalidInput on mismatch. Set this to
87 ``True`` to bypass the check and validate the signature using X509Data only.
88 """
89
90 default_reference_c14n_method: CanonicalizationMethod = CanonicalizationMethod.CANONICAL_XML_1_1
91 """
92 The default canonicalization method to use for referenced data structures, if there is no canonicalization
93 algorithm specified in the Transforms element. In most cases, it should not be necessary to override this
94 setting; SignedInfo should include every transformation that were applied to the reference before creating
95 the digests and signature, but there are some uses of XML Signatures where the canonicalization method is
96 fixed, and not added to the Transforms. This setting can be used to validate signatures in those use-cases.
97 """
98
99
100 @dataclass(frozen=True)
101 class VerifyResult:
102 """
103 This is a dataclass representing structured data returned by :func:`signxml.XMLVerifier.verify`. The results of a
104 verification contain the signed bytes, the parsed signed XML, the parsed signature XML, and the key that was used
105 to verify the signature. Example usage:
106
107 verified_data = signxml.XMLVerifier().verify(input_data).signed_xml
108 """
109
110 signed_data: bytes
111 "The binary data as it was signed"
112
113 signed_xml: Optional[etree._Element]
114 "The signed data parsed as XML (or None if parsing failed)"
115
116 signature_xml: etree._Element
117 "The signature element parsed as XML"
118
119 signature_key: bytes
120 "The cryptographic key that was used to verify the signature, in PEM format (for asymmetric keys) or raw secret bytes (for HMAC keys)"
121
122
123 class XMLVerifier(XMLSignatureProcessor):
124 """
125 Create a new XML Signature Verifier object, which can be used to verify multiple pieces of data.
126 """
127
128 def _get_signature(self, root):
129 if root.tag == ds_tag("Signature"):
130 return root
131 else:
132 return self._find(root, "Signature", xpath=self.config.location)
133
134 def _verify_signature_with_pubkey(
135 self,
136 *,
137 signed_info_c14n: bytes,
138 raw_signature: bytes,
139 signature_alg: SignatureMethod,
140 key_value: Optional[etree._Element] = None,
141 der_encoded_key_value: Optional[etree._Element] = None,
142 signing_certificate: Optional[x509.Certificate] = None,
143 ) -> Tuple[bytes, Union[bytes, dsa.DSAPublicKey, rsa.RSAPublicKey, ec.EllipticCurvePublicKey]]:
144 if der_encoded_key_value is not None:
145 assert der_encoded_key_value.text is not None
146 key = load_der_public_key(b64decode(der_encoded_key_value.text))
147 elif signing_certificate is not None:
148 key = signing_certificate.public_key()
149 elif key_value is None:
150 raise InvalidInput("Expected one of key_value, der_encoded_key_value, or signing_certificate to be set")
151
152 digest_alg_impl = digest_algorithm_implementations[signature_alg]()
153 if signature_alg.name.startswith("ECDSA_"):
154 if key_value is not None:
155 ec_key_value = self._find(key_value, "dsig11:ECKeyValue")
156 named_curve = self._find(ec_key_value, "dsig11:NamedCurve")
157 public_key = self._find(ec_key_value, "dsig11:PublicKey")
158 key_data = b64decode(public_key.text)[1:]
159 x = bytes_to_long(key_data[: len(key_data) // 2])
160 y = bytes_to_long(key_data[len(key_data) // 2 :])
161 curve_class = self.known_ecdsa_curves[named_curve.get("URI")]
162 ecpn = ec.EllipticCurvePublicNumbers(x=x, y=y, curve=curve_class()) # type: ignore[abstract]
163 key = ecpn.public_key()
164 elif not isinstance(key, ec.EllipticCurvePublicKey):
165 raise InvalidInput("DER encoded key value does not match specified signature algorithm")
166 signature_for_ecdsa = self._encode_dss_signature(raw_signature, key.key_size)
167 key.verify(signature_for_ecdsa, data=signed_info_c14n, signature_algorithm=ec.ECDSA(digest_alg_impl))
168 elif signature_alg.name.startswith("DSA_"):
169 if key_value is not None:
170 dsa_key_value = self._find(key_value, "DSAKeyValue")
171 p = self._get_long(dsa_key_value, "P")
172 q = self._get_long(dsa_key_value, "Q")
173 g = self._get_long(dsa_key_value, "G", require=False)
174 y = self._get_long(dsa_key_value, "Y")
175 dsapn = dsa.DSAPublicNumbers(y=y, parameter_numbers=dsa.DSAParameterNumbers(p=p, q=q, g=g))
176 key = dsapn.public_key()
177 elif not isinstance(key, dsa.DSAPublicKey):
178 raise InvalidInput("DER encoded key value does not match specified signature algorithm")
179 # TODO: supply meaningful key_size_bits for signature length assertion
180 dss_signature = self._encode_dss_signature(raw_signature, len(raw_signature) * 8 // 2)
181 key.verify(dss_signature, data=signed_info_c14n, algorithm=digest_alg_impl)
182 elif signature_alg.name.startswith("RSA_") or signature_alg.name.startswith("SHA"):
183 if key_value is not None:
184 rsa_key_value = self._find(key_value, "RSAKeyValue")
185 modulus = self._get_long(rsa_key_value, "Modulus")
186 exponent = self._get_long(rsa_key_value, "Exponent")
187 key = rsa.RSAPublicNumbers(e=exponent, n=modulus).public_key()
188 elif not isinstance(key, rsa.RSAPublicKey):
189 raise InvalidInput("DER encoded key value does not match specified signature algorithm")
190 if signature_alg.name.startswith("RSA_"):
191 padding: AsymmetricPadding = PKCS1v15()
192 else:
193 padding = PSS(mgf=MGF1(algorithm=digest_alg_impl), salt_length=digest_alg_impl.digest_size)
194 key.verify(raw_signature, data=signed_info_c14n, padding=padding, algorithm=digest_alg_impl)
195 else:
196 raise InvalidInput(f"Unsupported signature algorithm {signature_alg}")
197 return signed_info_c14n, key
198
199 def _encode_dss_signature(self, raw_signature: bytes, key_size_bits: int) -> bytes:
200 want_raw_signature_len = bits_to_bytes_unit(key_size_bits) * 2
201 if len(raw_signature) != want_raw_signature_len:
202 raise InvalidSignature(
203 "Expected %d byte SignatureValue, got %d" % (want_raw_signature_len, len(raw_signature))
204 )
205 int_len = len(raw_signature) // 2
206 r = bytes_to_long(raw_signature[:int_len])
207 s = bytes_to_long(raw_signature[int_len:])
208 return utils.encode_dss_signature(r, s)
209
210 def _get_inclusive_ns_prefixes(self, transform_node):
211 inclusive_namespaces = transform_node.find("./ec:InclusiveNamespaces[@PrefixList]", namespaces=namespaces)
212 if inclusive_namespaces is None:
213 return None
214 else:
215 return inclusive_namespaces.get("PrefixList").split(" ")
216
217 def _apply_transforms(
218 self,
219 payload,
220 *,
221 transforms_node: etree._Element,
222 signature: etree._Element,
223 ):
224 transforms, c14n_applied = [], False
225 if transforms_node is not None:
226 transforms = self._findall(transforms_node, "Transform")
227
228 for transform in transforms:
229 if transform.get("Algorithm") == SignatureConstructionMethod.enveloped.value:
230 _remove_sig(signature, idempotent=True)
231
232 for transform in transforms:
233 if transform.get("Algorithm") == "http://www.w3.org/2000/09/xmldsig#base64":
234 payload = b64decode(payload.text)
235
236 for transform in transforms:
237 algorithm = transform.get("Algorithm")
238 try:
239 c14n_algorithm_from_transform = CanonicalizationMethod(algorithm)
240 except ValueError:
241 continue
242 inclusive_ns_prefixes = self._get_inclusive_ns_prefixes(transform)
243
244 # Create a separate copy of the node so we can modify the tree and avoid any c14n inconsistencies from
245 # namespaces propagating from parent nodes. The lxml docs recommend using copy.deepcopy for this, but it
246 # doesn't seem to preserve namespaces. It would be nice to find a less heavy-handed way of doing this.
247 payload = self._fromstring(self._tostring(payload))
248
249 payload = self._c14n(
250 payload, algorithm=c14n_algorithm_from_transform, inclusive_ns_prefixes=inclusive_ns_prefixes
251 )
252 c14n_applied = True
253
254 if not c14n_applied and not isinstance(payload, (str, bytes)):
255 # Create a separate copy of the node, see above
256 payload = self._fromstring(self._tostring(payload))
257 payload = self._c14n(payload, algorithm=self.config.default_reference_c14n_method)
258 return payload
259
260 def get_cert_chain_verifier(self, ca_pem_file):
261 return X509CertChainVerifier(ca_pem_file=ca_pem_file)
262
263 def _match_key_values(self, key_value, der_encoded_key_value, signing_cert, signature_alg):
264 if self.config.ignore_ambiguous_key_info is True:
265 return
266 cert_pub_key = signing_cert.public_key()
267 # If both X509Data and KeyValue are present, match one against the other and raise an error on mismatch
268 if key_value is not None:
269 match_result = self._check_key_value_matches_cert_public_key(key_value, cert_pub_key, signature_alg)
270 if match_result is False:
271 raise InvalidInput(
272 "Both X509Data and KeyValue found and they represent different public keys. "
273 "Use verify(ignore_ambiguous_key_info=True) to ignore KeyValue and validate "
274 "using X509Data only."
275 )
276
277 # If both X509Data and DEREncodedKeyValue are present, match one against the other and raise an error on
278 # mismatch
279 if der_encoded_key_value is not None:
280 match_result = self._check_der_key_value_matches_cert_public_key(
281 der_encoded_key_value, signing_cert.public_key(), signature_alg
282 )
283 if match_result is False:
284 raise InvalidInput(
285 "Both X509Data and DEREncodedKeyValue found and they represent different "
286 "public keys. Use verify(ignore_ambiguous_key_info=True) to ignore "
287 "DEREncodedKeyValue and validate using X509Data only."
288 )
289
290 def check_digest_alg_expected(self, digest_alg):
291 if digest_alg not in self.config.digest_algorithms:
292 raise InvalidInput(f"Digest algorithm {digest_alg.name} forbidden by configuration")
293
294 def check_signature_alg_expected(self, signature_alg):
295 if signature_alg not in self.config.signature_methods:
296 raise InvalidInput(f"Signature method {signature_alg.name} forbidden by configuration")
297
298 def verify(
299 self,
300 data,
301 *,
302 x509_cert: Optional[Union[str, x509.Certificate]] = None,
303 cert_subject_name: Optional[str] = None,
304 cert_resolver: Optional[Callable] = None,
305 ca_pem_file: Optional[Union[str, bytes]] = None,
306 hmac_key: Optional[bytes] = None,
307 validate_schema: bool = True,
308 parser=None,
309 uri_resolver: Optional[Callable] = None,
310 id_attribute: Optional[str] = None,
311 expect_config: SignatureConfiguration = SignatureConfiguration(),
312 **deprecated_kwargs,
313 ) -> Union[VerifyResult, List[VerifyResult]]:
314 """
315 Verify the XML signature supplied in the data and return a list of :class:`VerifyResult` data structures
316 representing the data signed by the signature, or raise an exception if the signature is not valid. By default,
317 this requires the signature to be generated using a valid X.509 certificate. To enable other means of signature
318 validation, set ``expect_config`` to a configuration with the **require_x509** parameter set to `False`.
319
320 .. admonition:: See what is signed
321
322 It is important to understand and follow the best practice rule of "See what is signed" when verifying XML
323 signatures. The gist of this rule is: if your application neglects to verify that the information it trusts is
324 what was actually signed, the attacker can supply a valid signature but point you to malicious data that wasn't
325 signed by that signature.
326
327 In SignXML, you can ensure that the information signed is what you expect to be signed by only trusting the
328 data returned by ``XMLVerifier.verify()``. The ``signed_xml`` attribute of the return value is the XML node or string
329 that was signed. We also recommend that you assert the expected location for the signature within the document:
330
331 .. code-block:: python
332
333 from signxml import XMLVerifier, SignatureConfiguration
334 config = SignatureConfiguration(location="./")
335 XMLVerifier(...).verify(..., expect_config=config)
336
337 Depending on the canonicalization method used by the signature, comments in the XML data may not be subject to
338 signing, so may need to be untrusted. If so, they are excised from the return value of ``verify()``.
339
340 **Recommended reading:** http://www.w3.org/TR/xmldsig-bestpractices/#practices-applications
341
342 .. admonition:: Establish trust
343
344 If you do not supply any keyword arguments to ``verify()``, the default behavior is to trust **any** valid XML
345 signature generated using a valid X.509 certificate trusted by your system's CA store. This means anyone can
346 get an SSL certificate and generate a signature that you will trust. To establish trust in the signer, use the
347 ``x509_cert`` argument to specify a certificate that was pre-shared out-of-band (e.g. via SAML metadata, as
348 shown in :ref:`Verifying SAML assertions <verifying-saml-assertions>`), or ``cert_subject_name`` to specify a
349 subject name that must be in the signing X.509 certificate given by the signature (verified as if it were a
350 domain name), or ``ca_pem_file`` to give a custom CA.
351
352 :param data: Signature data to verify
353 :type data: String, file-like object, or XML ElementTree Element API compatible object
354 :param x509_cert:
355 A trusted external X.509 certificate, given as a PEM-formatted string or cryptography.x509.Certificate
356 object, to use for verification. Overrides any X.509 certificate information supplied by the signature. If
357 left set to ``None``, requires that the signature supply a valid X.509 certificate chain that validates
358 against the known certificate authorities. Implies **require_x509=True**.
359 :param cert_subject_name:
360 Subject Common Name to check the signing X.509 certificate against. Implies **require_x509=True**.
361 :param cert_resolver:
362 Function to use to resolve trusted X.509 certificates when X509IssuerSerial and X509Digest references are
363 found in the signature. The function is called with the keyword arguments ``x509_issuer_name``,
364 ``x509_serial_number`` and ``x509_digest``, and is expected to return an iterable of one or more
365 strings containing a PEM-formatted certificate and a chain of intermediate certificates, if needed.
366 Implies **require_x509=True**.
367 :param ca_pem_file:
368 Filename of a PEM file containing certificate authority information to use when verifying certificate-based
369 signatures.
370 :param hmac_key: If using HMAC, a string containing the shared secret.
371 :param validate_schema: Whether to validate **data** against the XML Signature schema.
372 :param parser:
373 Custom XML parser instance to use when parsing **data**. The default parser arguments used by SignXML are:
374 ``resolve_entities=False``. See https://lxml.de/FAQ.html#how-do-i-use-lxml-safely-as-a-web-service-endpoint.
375 :type parser: :class:`lxml.etree.XMLParser` compatible parser
376 :param uri_resolver:
377 Function to use to resolve reference URIs that are not empty and don't start with "#" (such references are
378 only expected in detached signatures; if you don't expect such signatures, leave this unset to prevent them
379 from validating). The function is called with a single string argument containing the URI to be resolved,
380 and is expected to return a :class:`lxml.etree._Element` node or bytes.
381 :param id_attribute:
382 Name of the attribute whose value ``URI`` refers to. By default, SignXML will search for "Id", then "ID".
383 :param expect_config:
384 Expected signature configuration. Pass a :class:`SignatureConfiguration` object to describe expected
385 properties of the verified signature. Signatures with unexpected configurations will fail validation.
386 :param deprecated_kwargs:
387 Direct application of the parameters **require_x509**, **expect_references**, and
388 **ignore_ambiguous_key_info** is deprecated. Use **expect_config** instead.
389
390 :raises: :class:`signxml.exceptions.InvalidSignature`
391 """
392 self.hmac_key = hmac_key
393 if hmac_key is not None:
394 if expect_config.signature_methods == SignatureConfiguration().signature_methods: # default value
395 expect_config = replace(
396 expect_config,
397 signature_methods=frozenset(sm for sm in SignatureMethod if sm.name.startswith("HMAC")),
398 )
399 elif any(not sm.name.startswith("HMAC") for sm in expect_config.signature_methods):
400 raise InvalidInput("When hmac_key is set, all expected signature methods must use HMAC")
401
402 self.config = expect_config
403 if deprecated_kwargs:
404 self.config = replace(expect_config, **deprecated_kwargs)
405 self._parser = parser
406
407 if x509_cert or cert_resolver:
408 self.config = replace(self.config, require_x509=True)
409
410 if x509_cert and str(type(x509_cert)) == "<class 'OpenSSL.crypto.X509'>":
411 warn(
412 "SignXML received a PyOpenSSL object as x509_cert input. Please pass a Cryptography.X509 object instead.",
413 DeprecationWarning,
414 )
415 x509_cert = x509_cert.to_cryptography() # type: ignore[union-attr]
416
417 self.x509_cert = x509_cert
418
419 if id_attribute is not None:
420 self.id_attributes = (id_attribute,)
421
422 root = self.get_root(data)
423 signature_ref = self._get_signature(root)
424
425 # We could do a deep copy here, but it wouldn't preserve root level namespaces
426 signature = self._fromstring(self._tostring(signature_ref))
427
428 if validate_schema:
429 self.validate_schema(signature)
430
431 signed_info = self._find(signature, "SignedInfo")
432 c14n_method = self._find(signed_info, "CanonicalizationMethod")
433 c14n_algorithm = CanonicalizationMethod(c14n_method.get("Algorithm"))
434 inclusive_ns_prefixes = self._get_inclusive_ns_prefixes(c14n_method)
435 signature_method = self._find(signed_info, "SignatureMethod")
436 signature_value = self._find(signature, "SignatureValue")
437 signature_alg = SignatureMethod(signature_method.get("Algorithm"))
438 self.check_signature_alg_expected(signature_alg)
439 raw_signature = b64decode(signature_value.text)
440 x509_data = signature.find("ds:KeyInfo/ds:X509Data", namespaces=namespaces)
441 key_value = signature.find("ds:KeyInfo/ds:KeyValue", namespaces=namespaces)
442 der_encoded_key_value = signature.find("ds:KeyInfo/dsig11:DEREncodedKeyValue", namespaces=namespaces)
443 signed_info_c14n = self._c14n(
444 signed_info, algorithm=c14n_algorithm, inclusive_ns_prefixes=inclusive_ns_prefixes
445 )
446
447 if x509_data is not None or self.config.require_x509:
448 if self.x509_cert is None:
449 if x509_data is None:
450 raise InvalidInput("Expected a X.509 certificate based signature")
451 certs = [cert.text for cert in self._findall(x509_data, "X509Certificate")]
452 if len(certs) == 0:
453 x509_iss = x509_data.find("ds:X509IssuerSerial/ds:X509IssuerName", namespaces=namespaces)
454 x509_sn = x509_data.find("ds:X509IssuerSerial/ds:X509SerialNumber", namespaces=namespaces)
455 x509_digest = x509_data.find("dsig11:X509Digest", namespaces=namespaces)
456 if cert_resolver and any(i is not None for i in (x509_iss, x509_sn, x509_digest)):
457 cert_chain = cert_resolver(
458 x509_issuer_name=x509_iss.text if x509_iss is not None else None,
459 x509_serial_number=x509_sn.text if x509_sn is not None else None,
460 x509_digest=x509_digest.text if x509_digest is not None else None,
461 )
462 if len(cert_chain) == 0:
463 raise InvalidCertificate("No certificate found for given X509 data")
464 if not all(isinstance(c, x509.Certificate) for c in cert_chain):
465 cert_chain = [x509.load_pem_x509_certificate(add_pem_header(cert)) for cert in cert_chain]
466 else:
467 msg = "Expected to find an X509Certificate element in the signature"
468 msg += " (X509SubjectName, X509SKI are not supported)"
469 raise InvalidInput(msg)
470 else:
471 cert_chain = [x509.load_pem_x509_certificate(add_pem_header(cert)) for cert in certs]
472
473 cert_verifier = self.get_cert_chain_verifier(ca_pem_file=ca_pem_file)
474
475 signing_cert = cert_verifier.verify(cert_chain)
476 elif isinstance(self.x509_cert, x509.Certificate):
477 signing_cert = self.x509_cert
478 else:
479 signing_cert = x509.load_pem_x509_certificate(add_pem_header(self.x509_cert))
480
481 if cert_subject_name is not None:
482 cn_oid = x509.oid.NameOID.COMMON_NAME
483 subject_cn_from_signing_cert = signing_cert.subject.get_attributes_for_oid(cn_oid)[0].value
484 if subject_cn_from_signing_cert != cert_subject_name:
485 raise InvalidSignature("Certificate subject common name mismatch")
486
487 try:
488 verified_signed_info_c14n, key_used = self._verify_signature_with_pubkey(
489 signed_info_c14n=signed_info_c14n,
490 raw_signature=raw_signature,
491 signing_certificate=signing_cert,
492 signature_alg=signature_alg,
493 )
494 except cryptography.exceptions.InvalidSignature as e:
495 raise InvalidSignature(f"Signature verification failed: {e}")
496
497 self._match_key_values(
498 key_value=key_value,
499 der_encoded_key_value=der_encoded_key_value,
500 signing_cert=signing_cert,
501 signature_alg=signature_alg,
502 )
503 elif signature_alg.name.startswith("HMAC_"):
504 if self.hmac_key is None:
505 raise InvalidInput('Parameter "hmac_key" is required when verifying a HMAC signature')
506
507 signer = HMAC(key=self.hmac_key, algorithm=digest_algorithm_implementations[signature_alg]())
508 signer.update(signed_info_c14n)
509 try:
510 signer.verify(raw_signature)
511 verified_signed_info_c14n = signed_info_c14n
512 except cryptography.exceptions.InvalidSignature:
513 raise InvalidSignature("Signature mismatch (HMAC)")
514 key_used = self.hmac_key
515 else:
516 if key_value is None and der_encoded_key_value is None:
517 raise InvalidInput("Expected to find either KeyValue or X509Data XML element in KeyInfo")
518
519 verified_signed_info_c14n, key_used = self._verify_signature_with_pubkey(
520 signed_info_c14n=signed_info_c14n,
521 raw_signature=raw_signature,
522 key_value=key_value,
523 der_encoded_key_value=der_encoded_key_value,
524 signature_alg=signature_alg,
525 )
526
527 verified_signed_info = self._fromstring(verified_signed_info_c14n)
528 verify_results: List[VerifyResult] = []
529 for idx, reference in enumerate(self._findall(verified_signed_info, "Reference")):
530 verify_results.append(
531 self._verify_reference(reference, idx, root, uri_resolver, c14n_algorithm, signature, key_used)
532 )
533
534 if type(self.config.expect_references) is int and len(verify_results) != self.config.expect_references:
535 msg = "Expected to find {} references, but found {}"
536 raise InvalidSignature(msg.format(self.config.expect_references, len(verify_results)))
537
538 return (
539 verify_results[0]
540 if type(self.config.expect_references) is int and self.config.expect_references == 1
541 else verify_results
542 )
543
544 def _verify_reference(
545 self,
546 reference,
547 index,
548 root,
549 uri_resolver,
550 c14n_algorithm,
551 signature,
552 signature_key_used,
553 ):
554 copied_root = self._fromstring(self._tostring(root))
555 copied_signature_ref = self._get_signature(copied_root)
556 transforms = self._find(reference, "Transforms", require=False)
557 digest_method_alg_name = self._find(reference, "DigestMethod").get("Algorithm")
558 digest_value = self._find(reference, "DigestValue")
559 payload = self._resolve_reference(copied_root, reference, uri_resolver=uri_resolver)
560 payload_c14n = self._apply_transforms(
561 payload,
562 transforms_node=transforms,
563 signature=copied_signature_ref,
564 )
565 digest_alg = DigestAlgorithm(digest_method_alg_name)
566 self.check_digest_alg_expected(digest_alg)
567
568 if b64decode(digest_value.text) != self._get_digest(payload_c14n, digest_alg):
569 raise InvalidDigest(f"Digest mismatch for reference {index} ({reference.get('URI')})")
570
571 # We return the signed XML (and only that) to ensure no access to unsigned data happens.
572 # Note it is essential to roundtrip the payload and render it from canonicalized XML, to avoid returning
573 # untrusted comments, avoid text nodes being broken up even after comments are excised, etc.
574 try:
575 payload_c14n_xml = self._fromstring(payload_c14n)
576 except etree.XMLSyntaxError:
577 payload_c14n_xml = None
578
579 if isinstance(signature_key_used, bytes):
580 signature_key = signature_key_used
581 else:
582 signature_key = signature_key_used.public_bytes(Encoding.PEM, PublicFormat.SubjectPublicKeyInfo)
583 return VerifyResult(payload_c14n, payload_c14n_xml, signature, signature_key=signature_key)
584
585 def validate_schema(self, signature):
586 last_exception = None
587 for schema in self.schemas():
588 try:
589 schema.assertValid(signature)
590 return
591 except Exception as e:
592 last_exception = e
593 if last_exception is not None:
594 raise last_exception
595 raise SignXMLException("Invalid state")
596
597 def _check_key_value_matches_cert_public_key(self, key_value, public_key, signature_alg: SignatureMethod):
598 if signature_alg.name.startswith("ECDSA_") and isinstance(public_key, ec.EllipticCurvePublicKey):
599 ec_key_value = self._find(key_value, "dsig11:ECKeyValue")
600 named_curve = self._find(ec_key_value, "dsig11:NamedCurve")
601 pub_key = self._find(ec_key_value, "dsig11:PublicKey")
602 key_data = b64decode(pub_key.text)[1:]
603 x = bytes_to_long(key_data[: len(key_data) // 2])
604 y = bytes_to_long(key_data[len(key_data) // 2 :])
605 curve_class = self.known_ecdsa_curves[named_curve.get("URI")]
606
607 pubk_curve = public_key.public_numbers().curve
608 pubk_x = public_key.public_numbers().x
609 pubk_y = public_key.public_numbers().y
610
611 return isinstance(pubk_curve, curve_class) and x == pubk_x and y == pubk_y
612
613 elif signature_alg.name.startswith("DSA_") and isinstance(public_key, dsa.DSAPublicKey):
614 dsa_key_value = self._find(key_value, "DSAKeyValue")
615 p = self._get_long(dsa_key_value, "P")
616 q = self._get_long(dsa_key_value, "Q")
617 g = self._get_long(dsa_key_value, "G", require=False)
618
619 pubk_p = public_key.public_numbers().parameter_numbers.p
620 pubk_q = public_key.public_numbers().parameter_numbers.q
621 pubk_g = public_key.public_numbers().parameter_numbers.g
622
623 return p == pubk_p and q == pubk_q and g == pubk_g
624
625 elif signature_alg.name.startswith("RSA_") and isinstance(public_key, rsa.RSAPublicKey):
626 rsa_key_value = self._find(key_value, "RSAKeyValue")
627 n = self._get_long(rsa_key_value, "Modulus")
628 e = self._get_long(rsa_key_value, "Exponent")
629
630 pubk_n = public_key.public_numbers().n
631 pubk_e = public_key.public_numbers().e
632
633 return n == pubk_n and e == pubk_e
634
635 raise NotImplementedError()
636
637 def _check_der_key_value_matches_cert_public_key(self, der_encoded_key_value, public_key, signature_alg):
638 # TODO: Add a test case for this functionality
639 der_public_key = load_der_public_key(b64decode(der_encoded_key_value.text))
640
641 if (
642 signature_alg.name.startswith("ECDSA_")
643 and isinstance(der_public_key, ec.EllipticCurvePublicKey)
644 and isinstance(public_key, ec.EllipticCurvePublicKey)
645 ):
646 curve_class = der_public_key.public_numbers().curve
647 x = der_public_key.public_numbers().x
648 y = der_public_key.public_numbers().y
649
650 pubk_curve = public_key.public_numbers().curve
651 pubk_x = public_key.public_numbers().x
652 pubk_y = public_key.public_numbers().y
653
654 return curve_class == pubk_curve and x == pubk_x and y == pubk_y
655
656 elif (
657 signature_alg.name.startswith("DSA_")
658 and isinstance(der_public_key, dsa.DSAPublicKey)
659 and isinstance(public_key, dsa.DSAPublicKey)
660 ):
661 p = der_public_key.public_numbers().parameter_numbers.p
662 q = der_public_key.public_numbers().parameter_numbers.q
663 g = der_public_key.public_numbers().parameter_numbers.g
664
665 pubk_p = public_key.public_numbers().parameter_numbers.p
666 pubk_q = public_key.public_numbers().parameter_numbers.q
667 pubk_g = public_key.public_numbers().parameter_numbers.g
668
669 return p == pubk_p and q == pubk_q and g == pubk_g
670
671 elif (
672 signature_alg.name.startswith("RSA_")
673 and isinstance(der_public_key, rsa.RSAPublicKey)
674 and isinstance(public_key, rsa.RSAPublicKey)
675 ):
676 n = der_public_key.public_numbers().n
677 e = der_public_key.public_numbers().e
678
679 pubk_n = public_key.public_numbers().n
680 pubk_e = public_key.public_numbers().e
681
682 return n == pubk_n and e == pubk_e
683
684 raise NotImplementedError()
685
686 def _get_long(self, element, query, require=True):
687 result = self._find(element, query, require=require)
688 if result is not None:
689 result = bytes_to_long(b64decode(result.text))
690 return result