Debian Codegraph @

signxml/xades/xades.py

raw
1 """
2 Signature and digest algorithms supported by XAdES are described in ETSI TS 119 312.
3 Digest algorithms:
4 - SHA-224 FIPS Publication 180-4
5 - SHA-256 FIPS Publication 180-4
6 - SHA-384 FIPS Publication 180-4
7 - SHA-512 FIPS Publication 180-4
8 - SHA-512/256 FIPS Publication 180-4
9 - SHA3-256 FIPS Publication 202
10 - SHA3-384 FIPS Publication 202
11 - SHA3-512 FIPS Publication 202
12 Signature algorithms:
13 - RSA-PKCS#1v1_5 IETF RFC 3447
14 - RSA-PSS IETF RFC 3447
15 - DSA (FF-DLOG DSA) FIPS Publication 186-4 [2], ISO/IEC 14888-3
16 - EC-DSA (EC-DLOG EC-DSA) FIPS Publication 186-4
17 - EC-SDSA-opt (EC-DLOG EC-Schnorr) ISO/IEC 14888-3
18 We do not yet support all of them here (issue 206 tracks the implementation of RFC 6931 identifiers required for that).
19 The main difference with plain XML Signature is that HMAC algorithms are not supported, and SHA1 is deprecated.
20 """
21
22 import datetime
23 import os
24 import secrets
25 from base64 import b64decode, b64encode
26 from dataclasses import astuple, dataclass
27 from functools import wraps
28 from typing import Dict, List, Optional, Union
29
30 from cryptography import x509
31 from cryptography.hazmat.primitives.serialization import Encoding
32 from lxml.etree import SubElement, _Element
33
34 from .. import SignatureConfiguration, VerifyResult, XMLSignatureProcessor, XMLSigner, XMLVerifier
35 from ..algorithms import DigestAlgorithm, digest_algorithm_implementations
36 from ..exceptions import InvalidDigest, InvalidInput
37 from ..util import SigningSettings, add_pem_header, ds_tag, namespaces, xades_tag
38
39
40 @dataclass(frozen=True)
41 class XAdESSignatureConfiguration(SignatureConfiguration):
42 """
43 A subclass of :class:`signxml.SignatureConfiguration`, with default overrides as described below.
44 """
45
46 expect_references: Union[int, bool] = 3
47 """
48 By default, XAdES signatures carry 3 references (the original data reference, the KeyInfo (X.509 certificate)
49 reference, and the signed properties reference). Signatures can carry more references if more data or extensions
50 are present. Specify the expected number of references here.
51 """
52
53
54 @dataclass(frozen=True)
55 class XAdESSignaturePolicy:
56 Identifier: str
57 Description: str
58 DigestMethod: DigestAlgorithm
59 DigestValue: str
60
61
62 @dataclass(frozen=True)
63 class XAdESDataObjectFormat:
64 Description: str = "Default XAdES payload description"
65 MimeType: str = "text/xml"
66
67
68 @dataclass(frozen=True)
69 class XAdESVerifyResult(VerifyResult):
70 """
71 A subclass of :class:`signxml.VerifyResult`. See VerifyResult for attribute semantics not covered here.
72 """
73
74 signed_properties: _Element
75 "The XAdES SignedProperties element that was verified as signed by the signature"
76
77
78 class XAdESProcessor(XMLSignatureProcessor):
79 schema_files = ["XAdESv141.xsd", "XAdES01903v141-201601.xsd", "XAdES01903v141-201506.xsd"]
80 _schema_dir = os.path.normpath(os.path.join(os.path.dirname(__file__), "schemas"))
81
82
83 class XAdESSigner(XAdESProcessor, XMLSigner):
84 """
85 Create a new XAdES Signature Signer object, which can be used to hold configuration information and sign multiple
86 pieces of data. This is a subclass of :class:`signxml.XMLSigner`; all of its configuration semantics are supported.
87
88 :param signature_policy:
89 If you need your XAdES signature to carry the **SignaturePolicyIdentifier** element, use this parameter to pass
90 a :class:`XAdESSignaturePolicy` object carrying strings and the digest method identifier for the element.
91 :param claimed_roles:
92 If you need your XAdES signature to carry the **SignerRole/ClaimedRoles** element, use this parameter to pass a
93 list of strings to use as text for the **ClaimedRole** tags.
94 :param data_object_format:
95 If you need your XAdES signature to carry the **DataObjectFormat** element, use this parameter to pass a
96 :class:`XAdESDataObjectFormat` object carrying the Description and MimeType strings for the element.
97 :param xml_signer_args:
98 Parameters to pass to the :class:`signxml.XMLSigner` constructor.
99 """
100
101 use_deprecated_legacy_signing_certificate: bool = False
102
103 def __init__(
104 self,
105 signature_policy: Optional[XAdESSignaturePolicy] = None,
106 claimed_roles: Optional[List] = None,
107 data_object_format: Optional[XAdESDataObjectFormat] = None,
108 **xml_signer_args,
109 ) -> None:
110 super().__init__(**xml_signer_args)
111 if self.sign_alg.name.startswith("HMAC_"):
112 raise Exception("HMAC signatures are not supported by XAdES")
113 self.signature_annotators.append(self._build_xades_ds_object)
114 self._tokens_used: Dict[str, bool] = {}
115 self.signed_signature_properties_annotators = [
116 self.add_signing_time,
117 self.add_signing_certificate,
118 self.add_signature_policy_identifier,
119 self.add_signature_production_place,
120 self.add_signer_role,
121 ]
122 self.signed_data_object_properties_annotators = [
123 self.add_data_object_format,
124 ]
125 self.signature_policy = signature_policy
126 self.claimed_roles = claimed_roles
127 if data_object_format is None:
128 data_object_format = XAdESDataObjectFormat()
129 self.data_object_format = data_object_format
130 self.namespaces.update(xades=namespaces.xades)
131
132 @wraps(XMLSigner.sign)
133 def sign(self, data, always_add_key_value: bool = True, **kwargs) -> _Element: # type: ignore[override]
134 return super().sign(data=data, always_add_key_value=always_add_key_value, **kwargs)
135
136 def _get_token(self, length=4):
137 for _ in range(9000):
138 token = secrets.token_hex(length).upper()
139 if token in self._tokens_used:
140 continue
141 self._tokens_used[token] = True
142 return token
143
144 def _build_xades_ds_object(self, sig_root, signing_settings: SigningSettings):
145 ds_object = SubElement(sig_root, ds_tag("Object"), nsmap=self.namespaces)
146 sig_root.append(ds_object)
147 if "Id" not in sig_root.keys():
148 sig_root.set("Id", f"SignXMLSignature{self._get_token()}")
149 key_info = self._find(sig_root, "KeyInfo")
150 if "Id" not in key_info.keys():
151 key_info.set("Id", f"SignXMLCertificate{self._get_token()}")
152
153 qualifying_properties = SubElement(
154 ds_object, xades_tag("QualifyingProperties"), nsmap=self.namespaces, Target=f"#{sig_root.get('Id')}"
155 )
156 signed_properties = SubElement(
157 qualifying_properties,
158 xades_tag("SignedProperties"),
159 nsmap=self.namespaces,
160 Id=f"{sig_root.get('Id')}-SignedProperties{self._get_token()}",
161 )
162 signed_signature_properties = SubElement(
163 signed_properties, xades_tag("SignedSignatureProperties"), nsmap=self.namespaces
164 )
165 for ssp_annotator in self.signed_signature_properties_annotators:
166 ssp_annotator(signed_signature_properties, sig_root=sig_root, signing_settings=signing_settings)
167 signed_data_object_properties = SubElement(
168 signed_properties, xades_tag("SignedDataObjectProperties"), nsmap=self.namespaces
169 )
170 for dop_annotator in self.signed_data_object_properties_annotators:
171 dop_annotator(signed_data_object_properties, sig_root=sig_root, signing_settings=signing_settings)
172 self._add_reference_to_signed_info(
173 sig_root, signed_properties, Type="http://uri.etsi.org/01903#SignedProperties"
174 )
175 self._add_reference_to_signed_info(sig_root, key_info)
176
177 def _add_reference_to_signed_info(self, sig_root, node_to_reference, **attrs):
178 signed_info = self._find(sig_root, "SignedInfo")
179 reference = SubElement(signed_info, ds_tag("Reference"), nsmap=self.namespaces)
180 reference.set("URI", f"#{node_to_reference.get('Id')}")
181 for attr_name, attr_value in attrs.items():
182 reference.set(attr_name, attr_value)
183 SubElement(reference, ds_tag("DigestMethod"), nsmap=self.namespaces, Algorithm=self.digest_alg.value)
184 digest_value_node = SubElement(reference, ds_tag("DigestValue"), nsmap=self.namespaces)
185 node_to_reference_c14n = self._c14n(node_to_reference, algorithm=self.c14n_alg)
186 digest = self._get_digest(node_to_reference_c14n, algorithm=self.digest_alg)
187 digest_value_node.text = b64encode(digest).decode()
188
189 def add_signing_time(self, signed_signature_properties, sig_root, signing_settings: SigningSettings):
190 signing_time = SubElement(signed_signature_properties, xades_tag("SigningTime"), nsmap=self.namespaces)
191 # TODO: make configurable
192 signing_time.text = datetime.datetime.now(datetime.timezone.utc).isoformat(timespec="seconds")
193
194 def add_signing_certificate(self, signed_signature_properties, sig_root, signing_settings: SigningSettings):
195 # Emit both legacy SigningCertificate (SHA1 + IssuerSerial) and SigningCertificateV2
196 signing_cert_v2 = SubElement(
197 signed_signature_properties, xades_tag("SigningCertificateV2"), nsmap=self.namespaces
198 )
199 assert signing_settings.cert_chain is not None
200 for cert in signing_settings.cert_chain:
201 if isinstance(cert, x509.Certificate):
202 loaded_cert = cert
203 else:
204 loaded_cert = x509.load_pem_x509_certificate(add_pem_header(cert))
205 der_encoded_cert = loaded_cert.public_bytes(Encoding.DER)
206 cert_digest_bytes = self._get_digest(der_encoded_cert, algorithm=self.digest_alg)
207
208 # Legacy SigningCertificate
209 if self.use_deprecated_legacy_signing_certificate:
210 cert_digest_sha1_bytes = self._get_digest(der_encoded_cert, algorithm=DigestAlgorithm.SHA1)
211 signing_cert = SubElement(
212 signed_signature_properties, xades_tag("SigningCertificate"), nsmap=self.namespaces
213 )
214
215 cert_node_legacy = SubElement(signing_cert, xades_tag("Cert"), nsmap=self.namespaces)
216 cert_digest = SubElement(cert_node_legacy, xades_tag("CertDigest"), nsmap=self.namespaces)
217 SubElement(
218 cert_digest, ds_tag("DigestMethod"), nsmap=self.namespaces, Algorithm=DigestAlgorithm.SHA1.value
219 )
220 digest_value_node = SubElement(cert_digest, ds_tag("DigestValue"), nsmap=self.namespaces)
221 digest_value_node.text = b64encode(cert_digest_sha1_bytes).decode()
222 issuer_serial = SubElement(cert_node_legacy, xades_tag("IssuerSerial"), nsmap=self.namespaces)
223 issuer_name = SubElement(issuer_serial, ds_tag("X509IssuerName"), nsmap=self.namespaces)
224 issuer_name.text = "C={C},O={O},OU={OU},CN={CN}".format( # type:ignore[str-bytes-safe]
225 C=loaded_cert.issuer.get_attributes_for_oid(x509.oid.NameOID.COUNTRY_NAME)[0].value,
226 O=loaded_cert.issuer.get_attributes_for_oid(x509.oid.NameOID.ORGANIZATION_NAME)[0].value,
227 OU=loaded_cert.issuer.get_attributes_for_oid(x509.oid.NameOID.ORGANIZATIONAL_UNIT_NAME)[0].value,
228 CN=loaded_cert.issuer.get_attributes_for_oid(x509.oid.NameOID.COMMON_NAME)[0].value,
229 )
230 serial_number = SubElement(issuer_serial, ds_tag("X509SerialNumber"), nsmap=self.namespaces)
231 serial_number.text = str(loaded_cert.serial_number)
232
233 # SigningCertificateV2 (current default)
234 cert_node = SubElement(signing_cert_v2, xades_tag("Cert"), nsmap=self.namespaces)
235 cert_digest = SubElement(cert_node, xades_tag("CertDigest"), nsmap=self.namespaces)
236 SubElement(cert_digest, ds_tag("DigestMethod"), nsmap=self.namespaces, Algorithm=self.digest_alg.value)
237 digest_value_node = SubElement(cert_digest, ds_tag("DigestValue"), nsmap=self.namespaces)
238 digest_value_node.text = b64encode(cert_digest_bytes).decode()
239
240 # issuer_serial_number = loaded_cert.get_serial_number()
241 # issuer_serial_bytes = long_to_bytes(issuer_serial_number)
242 # issuer_serial_v2 = SubElement(cert_node, xades_tag("IssuerSerialV2"), nsmap=self.namespaces)
243 # issuer_serial_v2.text = b64encode(issuer_serial_bytes).decode()
244
245 def add_signature_policy_identifier(self, signed_signature_properties, sig_root, signing_settings: SigningSettings):
246 if self.signature_policy is not None:
247 signature_policy_identifier = SubElement(
248 signed_signature_properties, xades_tag("SignaturePolicyIdentifier"), nsmap=self.namespaces
249 )
250 signature_policy_id = SubElement(
251 signature_policy_identifier, xades_tag("SignaturePolicyId"), nsmap=self.namespaces
252 )
253 sig_policy_id = SubElement(signature_policy_id, xades_tag("SigPolicyId"), nsmap=self.namespaces)
254 identifier = SubElement(sig_policy_id, xades_tag("Identifier"), nsmap=self.namespaces)
255 identifier.text = self.signature_policy.Identifier
256 description = SubElement(sig_policy_id, xades_tag("Description"), nsmap=self.namespaces)
257 description.text = self.signature_policy.Description
258 sig_policy_hash = SubElement(signature_policy_id, xades_tag("SigPolicyHash"), nsmap=self.namespaces)
259 digest_alg = DigestAlgorithm(self.signature_policy.DigestMethod)
260 SubElement(sig_policy_hash, ds_tag("DigestMethod"), nsmap=self.namespaces, Algorithm=digest_alg.value)
261 digest_value_node = SubElement(sig_policy_hash, ds_tag("DigestValue"), nsmap=self.namespaces)
262 digest_value_node.text = self.signature_policy.DigestValue
263
264 def add_signature_production_place(self, signed_signature_properties, sig_root, signing_settings: SigningSettings):
265 # SignatureProductionPlace or SignatureProductionPlaceV2
266 pass
267
268 def add_signer_role(self, signed_signature_properties, sig_root, signing_settings: SigningSettings):
269 # SignerRole or SignerRoleV2
270 if not self.claimed_roles:
271 return
272 signer_role = SubElement(signed_signature_properties, xades_tag("SignerRole"), nsmap=self.namespaces)
273 claimed_roles = SubElement(signer_role, xades_tag("ClaimedRoles"), nsmap=self.namespaces)
274 for claimed_role in self.claimed_roles:
275 claimed_role_node = SubElement(claimed_roles, xades_tag("ClaimedRole"), nsmap=self.namespaces)
276 claimed_role_node.text = claimed_role
277
278 def add_data_object_format(self, signed_data_object_properties, sig_root, signing_settings: SigningSettings):
279 signed_info = self._find(sig_root, "ds:SignedInfo")
280 reference = self._find(signed_info, "ds:Reference")
281 if "Id" not in reference.keys():
282 reference.set("Id", f"SignXMLReference{self._get_token()}")
283 data_object_format = SubElement(
284 signed_data_object_properties,
285 xades_tag("DataObjectFormat"),
286 nsmap=self.namespaces,
287 ObjectReference=f"#{reference.get('Id')}",
288 )
289 description = SubElement(data_object_format, xades_tag("Description"), nsmap=self.namespaces)
290 description.text = self.data_object_format.Description
291 mime_type = SubElement(data_object_format, xades_tag("MimeType"), nsmap=self.namespaces)
292 mime_type.text = self.data_object_format.MimeType
293
294
295 class XAdESVerifier(XAdESProcessor, XMLVerifier):
296 """
297 Create a new XAdES Signature Verifier object, which can be used to verify multiple pieces of data.
298 """
299
300 # TODO: document/support SignatureTimeStamp / timestamp attestation
301 # SignatureTimeStamp is required by certain profiles but is an unsigned property
302 def _verify_signing_time(self, verify_result: VerifyResult):
303 pass
304
305 def _verify_cert_digest(self, signing_cert_node, expect_cert):
306 for cert in self._findall(signing_cert_node, "xades:Cert"):
307 cert_digest = self._find(cert, "xades:CertDigest")
308 digest_alg = DigestAlgorithm(self._find(cert_digest, "DigestMethod").get("Algorithm"))
309 digest_value = self._find(cert_digest, "DigestValue")
310 # check spec for specific method of retrieving cert
311 digest_alg_impl = digest_algorithm_implementations[digest_alg]()
312 if b64decode(digest_value.text) != expect_cert.fingerprint(digest_alg_impl):
313 raise InvalidDigest("Digest mismatch for certificate digest")
314
315 def _verify_cert_digests(self, verify_result: VerifyResult):
316 x509_data = verify_result.signature_xml.find("ds:KeyInfo/ds:X509Data", namespaces=namespaces)
317 cert_from_key_info = x509.load_pem_x509_certificate(
318 add_pem_header(self._find(x509_data, "X509Certificate").text)
319 )
320 signed_signature_props = self._find(verify_result.signed_xml, "xades:SignedSignatureProperties")
321 signing_cert = self._find(signed_signature_props, "xades:SigningCertificate", require=False)
322 signing_cert_v2 = self._find(signed_signature_props, "xades:SigningCertificateV2", require=False)
323 if signing_cert is None and signing_cert_v2 is None:
324 raise InvalidInput("Expected to find XML element xades:SigningCertificate or xades:SigningCertificateV2")
325 if signing_cert is not None and signing_cert_v2 is not None:
326 raise InvalidInput("Expected to find exactly one of xades:SigningCertificate or xades:SigningCertificateV2")
327 if signing_cert is not None:
328 self._verify_cert_digest(signing_cert, expect_cert=cert_from_key_info)
329 elif signing_cert_v2 is not None:
330 self._verify_cert_digest(signing_cert_v2, expect_cert=cert_from_key_info)
331
332 def _verify_signature_policy(self, verify_result: VerifyResult, expect_signature_policy: XAdESSignaturePolicy):
333 signed_signature_props = self._find(verify_result.signed_xml, "xades:SignedSignatureProperties")
334 signature_policy_id = signed_signature_props.find(
335 "xades:SignaturePolicyIdentifier/xades:SignaturePolicyId", namespaces=namespaces
336 )
337 if signature_policy_id is not None:
338 sig_policy_id = self._find(signature_policy_id, "xades:SigPolicyId")
339 identifier = self._find(sig_policy_id, "xades:Identifier")
340 if identifier.text != expect_signature_policy.Identifier:
341 raise InvalidInput(
342 f"Expected to find signature policy identifier {expect_signature_policy.Identifier}, "
343 f"but found {identifier.text}"
344 )
345 sig_policy_hash = self._find(signature_policy_id, "xades:SigPolicyHash")
346 digest_alg = DigestAlgorithm(self._find(sig_policy_hash, "DigestMethod").get("Algorithm"))
347 if digest_alg != expect_signature_policy.DigestMethod:
348 raise InvalidInput(
349 f"Expected to find signature digest algorithm {expect_signature_policy.DigestMethod}, "
350 f"but found {digest_alg}"
351 )
352 digest_value = self._find(sig_policy_hash, "DigestValue")
353 if b64decode(digest_value.text) != b64decode(expect_signature_policy.DigestValue):
354 raise InvalidInput("Digest mismatch for signature policy hash")
355
356 def _verify_signed_properties(self, verify_result):
357 self._verify_signing_time(verify_result)
358 self._verify_cert_digests(verify_result)
359 if self.expect_signature_policy:
360 self._verify_signature_policy(
361 verify_result=verify_result, expect_signature_policy=self.expect_signature_policy
362 )
363 return self._find(verify_result.signed_xml, "xades:SignedSignatureProperties")
364
365 def verify( # type: ignore[override]
366 self,
367 data,
368 *,
369 expect_signature_policy: Optional[XAdESSignaturePolicy] = None,
370 expect_config: XAdESSignatureConfiguration = XAdESSignatureConfiguration(),
371 **xml_verifier_args,
372 ) -> List[XAdESVerifyResult]:
373 """
374 Verify the XAdES signature supplied in the data and return a list of :class:`XAdESVerifyResult` data structures
375 representing the data signed by the signature, or raise an exception if the signature is not valid. This method
376 is a wrapper around :meth:`signxml.XMLVerifier.verify`; see its documentation for more details and arguments it
377 supports.
378
379 :param expect_signature_policy:
380 If you need to assert that the verified XAdES signature carries specific data in the
381 **SignaturePolicyIdentifier** element, use this parameter to pass a :class:`XAdESSignaturePolicy` object
382 carrying strings and the digest method identifier for the element.
383 :param expect_config:
384 Expected signature configuration. Pass a :class:`XAdESSignatureConfiguration` object to describe expected
385 properties of the verified signature. Signatures with unexpected configurations will fail validation.
386 :param xml_verifier_args:
387 Parameters to pass to :meth:`signxml.XMLVerifier.verify`.
388 """
389 self.expect_signature_policy = expect_signature_policy
390 if expect_config.require_x509 is not True:
391 raise InvalidInput("XAdES signatures require X509")
392 verify_results = super().verify(data, expect_config=expect_config, **xml_verifier_args)
393 if not isinstance(verify_results, list):
394 raise InvalidInput("Expected to find multiple references in signature")
395 for i, verify_result in enumerate(verify_results):
396 if verify_result.signed_xml is None:
397 continue
398 if verify_result.signed_xml.tag == xades_tag("SignedProperties"):
399 verify_results[i] = XAdESVerifyResult( # type: ignore[misc]
400 *astuple(verify_result), signed_properties=self._verify_signed_properties(verify_result)
401 )
402 break
403 else:
404 raise InvalidInput("Expected to find a xades:SignedProperties element")
405
406 # TODO: assert all mandatory signed properties are set
407 return verify_results # type: ignore[return-value]