Debian Codegraph @

signxml/signer.py

raw
1 from base64 import b64encode
2 from dataclasses import dataclass, replace
3 from typing import List, Optional, Union
4
5 from cryptography import x509
6 from cryptography.hazmat.primitives.asymmetric import dsa, ec, rsa, utils
7 from cryptography.hazmat.primitives.asymmetric.padding import MGF1, PSS, PKCS1v15
8 from cryptography.hazmat.primitives.hmac import HMAC
9 from cryptography.hazmat.primitives.serialization import Encoding, load_pem_private_key
10 from lxml.etree import Element, QName, SubElement, _Element
11
12 from .algorithms import (
13 CanonicalizationMethod,
14 DigestAlgorithm,
15 SignatureConstructionMethod,
16 SignatureMethod,
17 digest_algorithm_implementations,
18 )
19 from .exceptions import InvalidInput
20 from .processor import XMLSignatureProcessor
21 from .util import (
22 SigningSettings,
23 _remove_sig,
24 bits_to_bytes_unit,
25 ds_tag,
26 dsig11_tag,
27 ec_tag,
28 ensure_bytes,
29 iterate_pem,
30 long_to_bytes,
31 namespaces,
32 strip_pem_header,
33 )
34
35
36 @dataclass(frozen=True)
37 class SignatureReference:
38 """
39 A container representing a signature reference (pointer to data covered by the signature). A signature can include
40 one or more references. The integrity of each reference is attested by including the digest (hash) of its value.
41 """
42
43 URI: str
44 """
45 The reference URI, for example ``#elementId`` to refer to an element whose Id attribute is set to ``elementId``.
46 """
47
48 c14n_method: Optional[CanonicalizationMethod] = None
49 """
50 Use this parameter to set a canonicalization method for the reference value that is distinct from that for the
51 signature itself.
52 """
53
54 inclusive_ns_prefixes: Optional[List] = None
55 """
56 When using exclusive XML canonicalization, use this parameter to provide a list of XML namespace prefixes whose
57 declarations should be preserved when canonicalizing the reference value (**InclusiveNamespaces PrefixList**).
58 """
59
60
61 class XMLSigner(XMLSignatureProcessor):
62 """
63 Create a new XML Signature Signer object, which can be used to hold configuration information and sign multiple
64 pieces of data.
65
66 :param method:
67 ``signxml.methods.enveloped``, ``signxml.methods.enveloping``, or ``signxml.methods.detached``. See
68 :class:`SignatureConstructionMethod` for details.
69 :param signature_algorithm:
70 Algorithm that will be used to generate the signature. See :class:`SignatureMethod` for the list of algorithm
71 IDs supported.
72 :param digest_algorithm:
73 Algorithm that will be used to hash the data during signature generation. See :class:`DigestAlgorithm` for the
74 list of algorithm IDs supported.
75 :param c14n_algorithm:
76 Algorithm that will be used to canonicalize (serialize in a reproducible way) the XML that is signed. See
77 :class:`CanonicalizationMethod` for the list of algorithm IDs supported.
78 """
79
80 signature_annotators: List
81 """
82 A list of callables that will be called at signature creation time to annotate the content to be signed before
83 signing. You can use this to register a custom signature decorator as follows:
84
85 .. code-block:: python
86
87 def my_annotator(sig_root, signing_settings):
88 ...
89 sig_root.append(my_custom_node)
90
91 signer = XMLSigner()
92 signer.signature_annotators.append(my_annotator)
93 signed = signer.sign(data, ...)
94 """
95
96 def __init__(
97 self,
98 method: SignatureConstructionMethod = SignatureConstructionMethod.enveloped,
99 signature_algorithm: Union[SignatureMethod, str] = SignatureMethod.RSA_SHA256,
100 digest_algorithm: Union[DigestAlgorithm, str] = DigestAlgorithm.SHA256,
101 c14n_algorithm: Union[CanonicalizationMethod, str] = CanonicalizationMethod.CANONICAL_XML_1_1,
102 ):
103 if method is None or method not in SignatureConstructionMethod:
104 raise InvalidInput(f"Unknown signature construction method {method}")
105 self.construction_method = method
106 if isinstance(signature_algorithm, str) and "#" not in signature_algorithm:
107 self.sign_alg = SignatureMethod.from_fragment(signature_algorithm)
108 else:
109 self.sign_alg = SignatureMethod(signature_algorithm)
110 if isinstance(digest_algorithm, str) and "#" not in digest_algorithm:
111 self.digest_alg = DigestAlgorithm.from_fragment(digest_algorithm)
112 else:
113 self.digest_alg = DigestAlgorithm(digest_algorithm)
114 self.check_deprecated_methods()
115 self.c14n_alg = CanonicalizationMethod(c14n_algorithm)
116 self.namespaces = dict(ds=namespaces.ds)
117 self._parser = None
118 self.signature_annotators = [self._add_key_info]
119
120 def _ds_tag(self, tag):
121 """
122 Create a QName for the ds namespace, respecting the configured namespace mapping.
123
124 When the default namespace is set to the ds namespace ({None: namespaces.ds}),
125 elements should be created without an explicit namespace so they inherit from
126 the nsmap context. This avoids spurious xmlns="" undeclarations in C14N output.
127
128 See https://github.com/XML-Security/signxml/issues/275
129 """
130 if None in self.namespaces and self.namespaces[None] == namespaces.ds: # type:ignore[index]
131 return QName(None, tag)
132 return ds_tag(tag)
133
134 def check_deprecated_methods(self):
135 if "SHA1" in self.sign_alg.name or "SHA1" in self.digest_alg.name:
136 msg = "SHA1-based algorithms are not supported in the default configuration because they are not secure"
137 raise InvalidInput(msg)
138
139 def sign(
140 self,
141 data,
142 *,
143 key: Optional[Union[str, bytes, rsa.RSAPrivateKey, dsa.DSAPrivateKey, ec.EllipticCurvePrivateKey]] = None,
144 passphrase: Optional[bytes] = None,
145 cert: Optional[Union[str, List[str], List[x509.Certificate]]] = None,
146 reference_uri: Optional[Union[str, List[str], List[SignatureReference]]] = None,
147 key_name: Optional[str] = None,
148 key_info: Optional[_Element] = None,
149 id_attribute: Optional[str] = None,
150 always_add_key_value: bool = False,
151 inclusive_ns_prefixes: Optional[List[str]] = None,
152 signature_properties: Optional[Union[_Element, List[_Element]]] = None,
153 exclude_c14n_transform_element: bool = False,
154 ) -> _Element:
155 """
156 Sign the data and return the root element of the resulting XML tree.
157
158 :param data: Data to sign
159 :type data: String, file-like object, or XML ElementTree Element API compatible object
160 :param key:
161 Key to be used for signing. When signing with a certificate or RSA/DSA/ECDSA key, this can be a string/bytes
162 containing a PEM-formatted key, or a :class:`cryptography.hazmat.primitives.asymmetric.rsa.RSAPrivateKey`,
163 :class:`cryptography.hazmat.primitives.asymmetric.dsa.DSAPrivateKey`, or
164 :class:`cryptography.hazmat.primitives.asymmetric.ec.EllipticCurvePrivateKey` object. When signing with a
165 HMAC, this should be a string containing the shared secret.
166 :param passphrase: Passphrase to use to decrypt the key, if any.
167 :param cert:
168 X.509 certificate to use for signing. This should be a string containing a PEM-formatted certificate, or an
169 array of strings or :class:`cryptography.x509.Certificate` objects containing the certificate and a chain
170 of intermediate certificates.
171 :param reference_uri:
172 Custom reference URI or list of reference URIs to incorporate into the signature. When ``method`` is set to
173 ``detached`` or ``enveloped``, reference URIs are set to this value and only the referenced elements are
174 signed. To specify extra options specific to each reference URI, pass a list of one or more
175 :class:`SignatureReference` objects.
176 :param key_name: Add a KeyName element in the KeyInfo element that may be used by the signer to communicate a
177 key identifier to the recipient. Typically, KeyName contains an identifier related to the key pair used to
178 sign the message.
179 :param key_info:
180 A custom KeyInfo element to insert in the signature. Use this to supply ``<wsse:SecurityTokenReference>``
181 or other custom key references. An example value can be found here:
182 https://github.com/XML-Security/signxml/blob/master/test/wsse_keyinfo.xml
183 :param id_attribute:
184 Name of the attribute whose value ``URI`` refers to. By default, SignXML will search for "Id", then "ID".
185 :param always_add_key_value:
186 Write the key value to the KeyInfo element even if a X509 certificate is present. Use of this parameter
187 is discouraged, as it introduces an ambiguity and a security hazard. The public key used to sign the
188 document is already encoded in the certificate (which is in X509Data), so the verifier must either ignore
189 KeyValue or make sure it matches what's in the certificate. This parameter is provided for compatibility
190 purposes only.
191 :param inclusive_ns_prefixes:
192 Provide a list of XML namespace prefixes whose declarations should be preserved when canonicalizing the
193 signature (**InclusiveNamespaces PrefixList**).
194
195 To specify this value separately for reference canonicalizaition, pass a list of one or more
196 :class:`SignatureReference` objects as the ``reference_uri`` keyword argument, and set the
197 ``inclusive_ns_prefixes`` attribute on those objects.
198 :param signature_properties:
199 One or more Elements that are to be included in the SignatureProperies section when using the detached
200 method.
201 :param exclude_c14n_transform_element:
202 When set to True, the c14n algorithm is not added to the signature's Transforms element. By default,
203 all transforms including canonicalization are added to the Transforms element, and in most cases this
204 is the correct approach. Only set this to True if you need to comply with a specification where the
205 c14n algorithm is fixed, and the specification forbids mentioning the algorithm.
206
207 :returns:
208 A :class:`lxml.etree._Element` object representing the root of the XML tree containing the signature and
209 the payload data.
210
211 To specify the location of an enveloped signature within **data**, insert a
212 ``<ds:Signature Id="placeholder"></ds:Signature>`` element in **data** (where
213 "ds" is the ``http://www.w3.org/2000/09/xmldsig#`` namespace). This element will
214 be replaced by the generated signature, and excised when generating the digest.
215 """
216 if id_attribute is not None:
217 self.id_attributes = (id_attribute,)
218
219 if isinstance(cert, (str, bytes)):
220 cert_chain = list(iterate_pem(cert))
221 if len(cert_chain) == 0:
222 raise InvalidInput("No PEM-encoded certificates found in string cert input data")
223 else:
224 cert_chain = cert # type:ignore[assignment]
225
226 input_references = self._preprocess_reference_uri(reference_uri)
227
228 signing_settings = SigningSettings(
229 key=None,
230 key_name=key_name,
231 key_info=key_info,
232 always_add_key_value=always_add_key_value,
233 cert_chain=cert_chain,
234 )
235
236 if key is None:
237 raise InvalidInput('Parameter "key" is required')
238 elif not self.sign_alg.name.startswith("HMAC_"):
239 if isinstance(key, (str, bytes)):
240 signing_settings.key = load_pem_private_key(ensure_bytes(key), password=passphrase)
241 else:
242 signing_settings.key = key
243
244 sig_root, doc_root, c14n_inputs, references = self._unpack(data, input_references)
245
246 if self.construction_method == SignatureConstructionMethod.detached and signature_properties is not None:
247 references.append(SignatureReference(URI="#prop"))
248 if signature_properties is not None and not isinstance(signature_properties, list):
249 signature_properties = [signature_properties]
250 signature_properties_el = self._build_signature_properties(signature_properties)
251 c14n_inputs.append(signature_properties_el)
252
253 signed_info_node, signature_value_node = self._build_sig(
254 sig_root,
255 references=references,
256 c14n_inputs=c14n_inputs,
257 inclusive_ns_prefixes=inclusive_ns_prefixes,
258 exclude_c14n_transform_element=exclude_c14n_transform_element,
259 )
260
261 for signature_annotator in self.signature_annotators:
262 signature_annotator(sig_root, signing_settings=signing_settings)
263
264 signed_info_c14n = self._c14n(
265 signed_info_node, algorithm=self.c14n_alg, inclusive_ns_prefixes=inclusive_ns_prefixes
266 )
267 if self.sign_alg.name.startswith("HMAC_"):
268 signer = HMAC(key=key, algorithm=digest_algorithm_implementations[self.sign_alg]()) # type:ignore[arg-type]
269 signer.update(signed_info_c14n)
270 signature_value_node.text = b64encode(signer.finalize()).decode()
271 sig_root.append(signature_value_node)
272 elif any(self.sign_alg.name.startswith(i) for i in ["DSA_", "RSA_", "ECDSA_", "SHA"]):
273 hash_alg = digest_algorithm_implementations[self.sign_alg]()
274 if self.sign_alg.name.startswith("DSA_"):
275 signature = signing_settings.key.sign(signed_info_c14n, algorithm=hash_alg)
276 elif self.sign_alg.name.startswith("ECDSA_"):
277 signature = signing_settings.key.sign(
278 signed_info_c14n, signature_algorithm=ec.ECDSA(algorithm=hash_alg)
279 )
280 elif self.sign_alg.name.startswith("RSA_"):
281 signature = signing_settings.key.sign(signed_info_c14n, padding=PKCS1v15(), algorithm=hash_alg)
282 elif self.sign_alg.name.startswith("SHA"):
283 # See https://www.rfc-editor.org/rfc/rfc9231.html#section-2.3.10
284 padding = PSS(mgf=MGF1(algorithm=hash_alg), salt_length=hash_alg.digest_size)
285 signature = signing_settings.key.sign(signed_info_c14n, padding=padding, algorithm=hash_alg)
286 else:
287 raise NotImplementedError()
288 if self.sign_alg.name.startswith("DSA_") or self.sign_alg.name.startswith("ECDSA_"):
289 # Note: The output of the DSA and ECDSA signers is a DER-encoded ASN.1 sequence of two DER integers.
290 (r, s) = utils.decode_dss_signature(signature)
291 int_len = bits_to_bytes_unit(signing_settings.key.key_size)
292 signature = long_to_bytes(r, blocksize=int_len) + long_to_bytes(s, blocksize=int_len)
293
294 signature_value_node.text = b64encode(signature).decode()
295 else:
296 raise NotImplementedError()
297
298 if self.construction_method == SignatureConstructionMethod.enveloping:
299 for c14n_input in c14n_inputs:
300 doc_root.append(c14n_input)
301
302 if self.construction_method == SignatureConstructionMethod.detached and signature_properties is not None:
303 sig_root.append(signature_properties_el)
304
305 return doc_root if self.construction_method == SignatureConstructionMethod.enveloped else sig_root
306
307 def _preprocess_reference_uri(self, reference_uris):
308 if reference_uris is None:
309 return None
310 if isinstance(reference_uris, (str, bytes)):
311 reference_uris = [reference_uris]
312 references = list(
313 ref if isinstance(ref, SignatureReference) else SignatureReference(URI=ref) for ref in reference_uris
314 )
315 return references
316
317 def _add_key_info(self, sig_root, signing_settings: SigningSettings):
318 if self.sign_alg.name.startswith("HMAC_"):
319 return
320 if signing_settings.key_info is None:
321 key_info = SubElement(sig_root, self._ds_tag("KeyInfo"))
322 if signing_settings.key_name is not None:
323 keyname = SubElement(key_info, self._ds_tag("KeyName"))
324 keyname.text = signing_settings.key_name
325
326 if signing_settings.cert_chain is None or signing_settings.always_add_key_value:
327 self._serialize_key_value(signing_settings.key, key_info)
328
329 if signing_settings.cert_chain is not None:
330 assert len(signing_settings.cert_chain) > 0
331 x509_data = SubElement(key_info, self._ds_tag("X509Data"))
332 for cert in signing_settings.cert_chain:
333 x509_certificate = SubElement(x509_data, self._ds_tag("X509Certificate"))
334 if isinstance(cert, (str, bytes)):
335 x509_certificate.text = strip_pem_header(cert)
336 else:
337 x509_certificate.text = strip_pem_header(cert.public_bytes(Encoding.PEM))
338 else:
339 sig_root.append(signing_settings.key_info)
340
341 def _get_c14n_inputs_from_references(self, doc_root, references: List[SignatureReference]):
342 c14n_inputs, new_references = [], []
343 for reference in references:
344 uri = reference.URI if reference.URI.startswith("#") else "#" + reference.URI
345 c14n_inputs.append(self.get_root(self._resolve_reference(doc_root, {"URI": uri})))
346 new_references.append(replace(reference, URI=uri))
347 return c14n_inputs, new_references
348
349 def _unpack(self, data, references: List[SignatureReference]):
350 sig_root = Element(self._ds_tag("Signature"), nsmap=self.namespaces)
351 if self.construction_method == SignatureConstructionMethod.enveloped:
352 if isinstance(data, (str, bytes)):
353 raise InvalidInput("When using enveloped signature, **data** must be an XML element")
354 doc_root = self.get_root(data)
355 c14n_inputs = [self.get_root(data)]
356 if references is not None:
357 # Only sign the referenced element(s)
358 c14n_inputs, references = self._get_c14n_inputs_from_references(doc_root, references)
359
360 signature_placeholders = self._findall(doc_root, "Signature[@Id='placeholder']", xpath=".//")
361 if len(signature_placeholders) == 0:
362 doc_root.append(sig_root)
363 elif len(signature_placeholders) == 1:
364 sig_root = signature_placeholders[0]
365 del sig_root.attrib["Id"]
366 for c14n_input in c14n_inputs:
367 placeholders = self._findall(c14n_input, "Signature[@Id='placeholder']", xpath=".//")
368 if placeholders:
369 assert len(placeholders) == 1
370 _remove_sig(placeholders[0])
371 else:
372 raise InvalidInput("Enveloped signature input contains more than one placeholder")
373
374 if references is None:
375 # Set default reference URIs based on signed data ID attribute values
376 references = []
377 for c14n_input in c14n_inputs:
378 payload_id = c14n_input.get("Id", c14n_input.get("ID"))
379 uri = "#{}".format(payload_id) if payload_id is not None else ""
380 references.append(SignatureReference(URI=uri))
381 elif self.construction_method == SignatureConstructionMethod.detached:
382 doc_root = self.get_root(data)
383 if references is None:
384 uri = "#{}".format(data.get("Id", data.get("ID", "object")))
385 references = [SignatureReference(URI=uri)]
386 c14n_inputs = [self.get_root(data)]
387 try:
388 c14n_inputs, references = self._get_c14n_inputs_from_references(doc_root, references)
389 except InvalidInput: # Dummy reference URI
390 c14n_inputs = [self.get_root(data)]
391 elif self.construction_method == SignatureConstructionMethod.enveloping:
392 doc_root = sig_root
393 c14n_inputs = [Element(self._ds_tag("Object"), nsmap=self.namespaces, Id="object")]
394 if isinstance(data, (str, bytes)):
395 c14n_inputs[0].text = data
396 else:
397 c14n_inputs[0].append(self.get_root(data))
398 references = [SignatureReference(URI="#object")]
399 return sig_root, doc_root, c14n_inputs, references
400
401 def _build_transforms_for_reference(
402 self, *, transforms_node: _Element, reference: SignatureReference, exclude_c14n_transform_element: bool = True
403 ):
404 assert reference.c14n_method is not None
405 if self.construction_method == SignatureConstructionMethod.enveloped:
406 SubElement(
407 transforms_node, self._ds_tag("Transform"), Algorithm=SignatureConstructionMethod.enveloped.value
408 )
409 if not exclude_c14n_transform_element:
410 SubElement(transforms_node, self._ds_tag("Transform"), Algorithm=reference.c14n_method.value)
411 else:
412 if not exclude_c14n_transform_element:
413 c14n_xform = SubElement(
414 transforms_node,
415 self._ds_tag("Transform"),
416 Algorithm=reference.c14n_method.value,
417 )
418 if reference.inclusive_ns_prefixes:
419 SubElement(
420 c14n_xform, ec_tag("InclusiveNamespaces"), PrefixList=" ".join(reference.inclusive_ns_prefixes)
421 )
422
423 def _build_sig(
424 self, sig_root, references, c14n_inputs, inclusive_ns_prefixes, exclude_c14n_transform_element=False
425 ):
426 signed_info = SubElement(sig_root, self._ds_tag("SignedInfo"), nsmap=self.namespaces)
427 sig_c14n_method = SubElement(signed_info, self._ds_tag("CanonicalizationMethod"), Algorithm=self.c14n_alg.value)
428 if inclusive_ns_prefixes:
429 SubElement(sig_c14n_method, ec_tag("InclusiveNamespaces"), PrefixList=" ".join(inclusive_ns_prefixes))
430
431 SubElement(signed_info, self._ds_tag("SignatureMethod"), Algorithm=self.sign_alg.value)
432 for i, reference in enumerate(references):
433 if reference.c14n_method is None:
434 reference = replace(reference, c14n_method=self.c14n_alg)
435 if reference.inclusive_ns_prefixes is None:
436 reference = replace(reference, inclusive_ns_prefixes=inclusive_ns_prefixes)
437 reference_node = SubElement(signed_info, self._ds_tag("Reference"), URI=reference.URI)
438 transforms = SubElement(reference_node, self._ds_tag("Transforms"))
439 self._build_transforms_for_reference(
440 transforms_node=transforms,
441 reference=reference,
442 exclude_c14n_transform_element=exclude_c14n_transform_element,
443 )
444 SubElement(reference_node, self._ds_tag("DigestMethod"), Algorithm=self.digest_alg.value)
445 digest_value = SubElement(reference_node, self._ds_tag("DigestValue"))
446 payload_c14n = self._c14n(
447 c14n_inputs[i], algorithm=reference.c14n_method, inclusive_ns_prefixes=reference.inclusive_ns_prefixes
448 )
449 digest = self._get_digest(payload_c14n, algorithm=self.digest_alg)
450 digest_value.text = b64encode(digest).decode()
451 signature_value = SubElement(sig_root, self._ds_tag("SignatureValue"))
452 return signed_info, signature_value
453
454 def _build_signature_properties(self, signature_properties):
455 # FIXME: make this use the annotator API
456 obj = Element(self._ds_tag("Object"), attrib={"Id": "prop"}, nsmap=self.namespaces)
457 signature_properties_el = Element(self._ds_tag("SignatureProperties"))
458 for i, el in enumerate(signature_properties):
459 signature_property = Element(
460 self._ds_tag("SignatureProperty"),
461 attrib={
462 "Id": el.attrib.pop("Id", f"sigprop{i}"),
463 "Target": el.attrib.pop("Target", f"#sigproptarget{i}"),
464 },
465 )
466 signature_property.append(el)
467 signature_properties_el.append(signature_property)
468 obj.append(signature_properties_el)
469 return obj
470
471 def _serialize_key_value(self, key, key_info_node):
472 """
473 Add the public components of the key to the signature (see https://www.w3.org/TR/xmldsig-core2/#sec-KeyValue).
474 """
475 key_value = SubElement(key_info_node, self._ds_tag("KeyValue"))
476 if self.sign_alg.name.startswith("RSA_") or self.sign_alg.name.startswith("SHA"):
477 rsa_key_value = SubElement(key_value, self._ds_tag("RSAKeyValue"))
478 modulus = SubElement(rsa_key_value, self._ds_tag("Modulus"))
479 modulus.text = b64encode(long_to_bytes(key.public_key().public_numbers().n)).decode()
480 exponent = SubElement(rsa_key_value, self._ds_tag("Exponent"))
481 exponent.text = b64encode(long_to_bytes(key.public_key().public_numbers().e)).decode()
482 elif self.sign_alg.name.startswith("DSA_"):
483 dsa_key_value = SubElement(key_value, self._ds_tag("DSAKeyValue"))
484 for field in "p", "q", "g", "y":
485 e = SubElement(dsa_key_value, self._ds_tag(field.upper()))
486
487 if field == "y":
488 key_params = key.public_key().public_numbers()
489 else:
490 key_params = key.parameters().parameter_numbers()
491
492 e.text = b64encode(long_to_bytes(getattr(key_params, field))).decode()
493 elif self.sign_alg.name.startswith("ECDSA_"):
494 ec_key_value = SubElement(key_value, dsig11_tag("ECKeyValue"), nsmap=dict(dsig11=namespaces.dsig11))
495 named_curve = SubElement( # noqa:F841
496 ec_key_value, dsig11_tag("NamedCurve"), URI=self.known_ecdsa_curve_oids[key.curve.name]
497 )
498 public_key = SubElement(ec_key_value, dsig11_tag("PublicKey"))
499 x = key.public_key().public_numbers().x
500 y = key.public_key().public_numbers().y
501 public_key.text = b64encode(long_to_bytes(4) + long_to_bytes(x) + long_to_bytes(y)).decode()