Debian Codegraph @

signxml/processor.py

raw
1 import importlib.resources
2 import logging
3 import threading
4 from functools import lru_cache
5 from typing import Any, List, Tuple
6 from xml.etree import ElementTree as stdlibElementTree
7
8 from cryptography.hazmat.primitives.asymmetric import ec
9 from cryptography.hazmat.primitives.hashes import Hash
10 from lxml import etree
11
12 from .algorithms import CanonicalizationMethod, DigestAlgorithm, digest_algorithm_implementations
13 from .exceptions import InvalidInput
14 from .util import namespaces
15
16 logger = logging.getLogger(__name__)
17
18
19 @lru_cache
20 def get_schema(schema_file: str) -> etree.XMLSchema:
21 pkg_name = "signxml.xades.schemas" if schema_file.startswith("XAdES") else "signxml.schemas"
22
23 pkg_resources = importlib.resources.files(pkg_name)
24 with pkg_resources.joinpath(schema_file).open("r") as schema_fh:
25 return etree.XMLSchema(etree.parse(schema_fh))
26
27
28 class XMLProcessor:
29 _schemas: List[Any] = []
30 schema_files: List[Any] = []
31 _default_parser, _parser = None, None
32
33 @classmethod
34 def schemas(cls):
35 with threading.Lock():
36 if len(cls._schemas) == 0:
37 for schema_file in cls.schema_files:
38 cls._schemas.append(get_schema(schema_file))
39 return cls._schemas
40
41 @property
42 def parser(self):
43 if self._parser is None:
44 if self._default_parser is None:
45 self._default_parser = etree.XMLParser(resolve_entities=False)
46 return self._default_parser
47 return self._parser
48
49 def _fromstring(self, xml_string, **kwargs):
50 xml_node = etree.fromstring(xml_string, parser=self.parser, **kwargs)
51 docinfo = etree.ElementTree(xml_node).docinfo
52 if docinfo.internalDTD is not None or docinfo.externalDTD is not None:
53 raise InvalidInput("DTD declarations are not supported in XML input")
54 for entity in xml_node.iter(etree.Entity):
55 raise InvalidInput("Entities are not supported in XML input")
56 return xml_node
57
58 def _tostring(self, xml_node, **kwargs):
59 return etree.tostring(xml_node, **kwargs)
60
61 def get_root(self, data):
62 if isinstance(data, (str, bytes)):
63 return self._fromstring(data)
64 elif isinstance(data, stdlibElementTree.Element):
65 # TODO: add debug level logging statement re: performance impact here
66 return self._fromstring(stdlibElementTree.tostring(data, encoding="utf-8"))
67 else:
68 # Create a separate copy of the node so we can modify the tree and avoid any c14n inconsistencies from
69 # namespaces propagating from parent nodes. The lxml docs recommend using copy.deepcopy for this, but it
70 # doesn't seem to preserve namespaces. It would be nice to find a less heavy-handed way of doing this.
71 return self._fromstring(self._tostring(data))
72
73
74 class XMLSignatureProcessor(XMLProcessor):
75 schema_files = ["xmldsig1-schema.xsd"]
76
77 # See https://tools.ietf.org/html/rfc5656
78 # ec.SECT* curves have been de-registered due to CVE-2026-26007
79 # (https://github.com/pyca/cryptography/security/advisories/GHSA-r6ph-v2qm-q3c2)
80 # List of disabled curves:
81 # "urn:oid:1.3.132.0.1": ec.SECT163K1,
82 # "urn:oid:1.3.132.0.26": ec.SECT233K1,
83 # "urn:oid:1.3.132.0.27": ec.SECT233R1,
84 # "urn:oid:1.3.132.0.16": ec.SECT283R1,
85 # "urn:oid:1.3.132.0.36": ec.SECT409K1,
86 # "urn:oid:1.3.132.0.37": ec.SECT409R1,
87 # "urn:oid:1.3.132.0.38": ec.SECT571K1
88 known_ecdsa_curves = {
89 "urn:oid:1.2.840.10045.3.1.7": ec.SECP256R1,
90 "urn:oid:1.3.132.0.34": ec.SECP384R1,
91 "urn:oid:1.3.132.0.35": ec.SECP521R1,
92 "urn:oid:1.2.840.10045.3.1.1": ec.SECP192R1,
93 "urn:oid:1.3.132.0.33": ec.SECP224R1,
94 }
95 known_ecdsa_curve_oids = {ec().name: oid for oid, ec in known_ecdsa_curves.items()} # type: ignore[abstract]
96
97 excise_empty_xmlns_declarations = False
98
99 id_attributes: Tuple[str, ...] = ("Id", "ID", "id", "xml:id")
100
101 def _get_digest(self, data, algorithm: DigestAlgorithm):
102 algorithm_implementation = digest_algorithm_implementations[algorithm]()
103 hasher = Hash(algorithm=algorithm_implementation)
104 hasher.update(data)
105 return hasher.finalize()
106
107 def _find(self, element, query, require=True, xpath=""):
108 namespace = "ds"
109 if ":" in query:
110 namespace, _, query = query.partition(":")
111 result = element.find(f"{xpath}{namespace}:{query}", namespaces=namespaces)
112
113 if require and result is None:
114 raise InvalidInput(f"Expected to find XML element {query} in {element.tag}")
115 return result
116
117 def _findall(self, element, query, xpath=""):
118 namespace = "ds"
119 if ":" in query:
120 namespace, _, query = query.partition(":")
121 return element.findall(f"{xpath}{namespace}:{query}", namespaces=namespaces)
122
123 def _c14n(self, nodes, algorithm: CanonicalizationMethod, inclusive_ns_prefixes=None):
124 exclusive, with_comments = False, False
125
126 if algorithm.value.startswith("http://www.w3.org/2001/10/xml-exc-c14n#"):
127 exclusive = True
128 if algorithm.value.endswith("#WithComments"):
129 with_comments = True
130
131 if not isinstance(nodes, list):
132 nodes = [nodes]
133
134 c14n = b""
135 for node in nodes:
136 c14n += etree.tostring(
137 node,
138 method="c14n",
139 exclusive=exclusive,
140 with_comments=with_comments,
141 inclusive_ns_prefixes=inclusive_ns_prefixes,
142 )
143 if exclusive is False and self.excise_empty_xmlns_declarations is True:
144 # Incorrect legacy behavior. See also:
145 # - https://github.com/XML-Security/signxml/issues/193
146 # - http://www.w3.org/TR/xml-c14n, "namespace axis"
147 # - http://www.w3.org/TR/xml-c14n2/#sec-Namespace-Processing
148 c14n = c14n.replace(b' xmlns=""', b"")
149 logger.debug("Canonicalized string (exclusive=%s, with_comments=%s): %s", exclusive, with_comments, c14n)
150 return c14n
151
152 def _resolve_reference(self, doc_root, reference, uri_resolver=None):
153 uri = reference.get("URI")
154 if uri is None:
155 raise InvalidInput("References without URIs are not supported")
156 elif uri == "":
157 return doc_root
158 elif uri.startswith("#xpointer("):
159 raise InvalidInput("XPointer references are not supported")
160 # doc_root.xpath(uri.lstrip("#"))[0]
161 elif uri.startswith("#"):
162 for id_attribute in self.id_attributes:
163 xpath_query = f"//*[@*[local-name() = '{id_attribute}']=$uri]"
164 results = doc_root.xpath(xpath_query, uri=uri.lstrip("#"))
165 if len(results) > 1:
166 raise InvalidInput(f"Ambiguous reference URI {uri} resolved to {len(results)} nodes")
167 elif len(results) == 1:
168 return results[0]
169 raise InvalidInput(f"Unable to resolve reference URI: {uri}")
170 else:
171 if uri_resolver is None:
172 raise InvalidInput(f"External URI dereferencing is not configured: {uri}")
173 result = uri_resolver(uri)
174 if result is None:
175 raise InvalidInput(f"Unable to resolve reference URI: {uri}")
176 return result