| 1 |
import os.path |
| 2 |
from base64 import b64encode |
| 3 |
|
| 4 |
from cryptography.hazmat.backends import default_backend |
| 5 |
from cryptography.hazmat.primitives.asymmetric import ec |
| 6 |
from cryptography.hazmat.primitives.asymmetric.padding import PKCS1v15 |
| 7 |
from lxml import etree |
| 8 |
from lxml.etree import Element, SubElement |
| 9 |
|
| 10 |
from signxml import ( |
| 11 |
InvalidInput, |
| 12 |
XMLSignatureProcessor, |
| 13 |
_remove_sig, |
| 14 |
ds_tag, |
| 15 |
dsig11_tag, |
| 16 |
ensure_str, |
| 17 |
iterate_pem, |
| 18 |
long_to_bytes, |
| 19 |
namespaces, |
| 20 |
strip_pem_header, |
| 21 |
) |
| 22 |
|
| 23 |
|
| 24 |
class XMLEnvelopedEnvelopingSigner(XMLSignatureProcessor): |
| 25 |
""" |
| 26 |
A class that signs multiple data by putting the signature enveloped in the |
| 27 |
first data item, and enveloping the others. |
| 28 |
""" |
| 29 |
|
| 30 |
def __init__( |
| 31 |
self, |
| 32 |
signature_algorithm="rsa-sha256", |
| 33 |
digest_algorithm="sha256", |
| 34 |
c14n_algorithm=XMLSignatureProcessor.default_c14n_algorithm, |
| 35 |
): |
| 36 |
self.sign_alg = signature_algorithm |
| 37 |
assert self.sign_alg in self.known_signature_digest_tags or self.sign_alg in self.known_hmac_digest_tags |
| 38 |
assert digest_algorithm in self.known_digest_tags |
| 39 |
self.digest_alg = digest_algorithm |
| 40 |
assert c14n_algorithm in self.known_c14n_algorithms |
| 41 |
self.c14n_alg = c14n_algorithm |
| 42 |
self.namespaces = dict(ds=namespaces.ds) |
| 43 |
self._parser = None |
| 44 |
|
| 45 |
def sign(self, data, key=None, passphrase=None, cert=None, key_name=None, key_info=None, id_attribute=None): |
| 46 |
""" |
| 47 |
Sign the data and return the root element of the resulting XML tree. |
| 48 |
|
| 49 |
:param data: Data to sign - must be a sequence of items to sign. |
| 50 |
:type data_others: Sequence of String, file-like object, or XML ElementTree Element API compatible object |
| 51 |
:param key: |
| 52 |
Key to be used for signing. When signing with a certificate or RSA/DSA/ECDSA key, this can be a string |
| 53 |
containing a PEM-formatted key, or a :py:class:`cryptography.hazmat.primitives.interfaces.RSAPublicKey`, |
| 54 |
:py:class:`cryptography.hazmat.primitives.interfaces.DSAPublicKey`, or |
| 55 |
:py:class:`cryptography.hazmat.primitives.interfaces.EllipticCurvePublicKey` object. When signing with a |
| 56 |
HMAC, this should be a string containing the shared secret. |
| 57 |
:type key: |
| 58 |
string, :py:class:`cryptography.hazmat.primitives.interfaces.RSAPublicKey`, |
| 59 |
:py:class:`cryptography.hazmat.primitives.interfaces.DSAPublicKey`, or |
| 60 |
:py:class:`cryptography.hazmat.primitives.interfaces.EllipticCurvePublicKey` object |
| 61 |
:param passphrase: Passphrase to use to decrypt the key, if any. |
| 62 |
:type passphrase: string |
| 63 |
:param cert: |
| 64 |
X.509 certificate to use for signing. This should be a string containing a PEM-formatted certificate, or an |
| 65 |
array of strings or OpenSSL.crypto.X509 objects containing the certificate and a chain of intermediate |
| 66 |
certificates. |
| 67 |
:type cert: string, array of strings, or array of OpenSSL.crypto.X509 objects |
| 68 |
:param key_name: Add a KeyName element in the KeyInfo element that may be used by the signer to communicate a |
| 69 |
key identifier to the recipient. Typically, KeyName contains an identifier related to the key pair used to |
| 70 |
sign the message. |
| 71 |
:type key_name: string |
| 72 |
:param key_info: A custom KeyInfo element to insert in the signature. Use this to supply |
| 73 |
``<wsse:SecurityTokenReference>`` or other custom key references. |
| 74 |
:type key_info: :py:class:`lxml.etree.Element` |
| 75 |
:param id_attribute: |
| 76 |
Name of the attribute whose value ``URI`` refers to. By default, SignXML will search for "Id", then "ID". |
| 77 |
:type id_attribute: string |
| 78 |
|
| 79 |
:returns: |
| 80 |
A :py:class:`lxml.etree.Element` object representing the root of the XML tree containing the signature and |
| 81 |
the payload data. |
| 82 |
|
| 83 |
To specify the location of an enveloped signature within **data**, insert a |
| 84 |
``<ds:Signature Id="placeholder"></ds:Signature>`` element in **data** (where |
| 85 |
"ds" is the "http://www.w3.org/2000/09/xmldsig#" namespace). This element will |
| 86 |
be replaced by the generated signature, and excised when generating the digest. |
| 87 |
""" |
| 88 |
if id_attribute is not None: |
| 89 |
self.id_attributes = (id_attribute,) |
| 90 |
|
| 91 |
if isinstance(cert, (str, bytes)): |
| 92 |
cert_chain = list(iterate_pem(cert)) |
| 93 |
else: |
| 94 |
cert_chain = cert |
| 95 |
|
| 96 |
sig_root, doc_root, c14n_inputs, reference_uris = self._unpack(data) |
| 97 |
signed_info_element, signature_value_element = self._build_sig(sig_root, reference_uris, c14n_inputs) |
| 98 |
|
| 99 |
if key is None: |
| 100 |
raise InvalidInput('Parameter "key" is required') |
| 101 |
|
| 102 |
signed_info_c14n = self._c14n(signed_info_element, algorithm=self.c14n_alg) |
| 103 |
if self.sign_alg.startswith("hmac-"): |
| 104 |
from cryptography.hazmat.primitives.hmac import HMAC |
| 105 |
|
| 106 |
signer = HMAC( |
| 107 |
key=key, algorithm=self._get_hmac_digest_method_by_tag(self.sign_alg), backend=default_backend() |
| 108 |
) |
| 109 |
signer.update(signed_info_c14n) |
| 110 |
signature_value_element.text = ensure_str(b64encode(signer.finalize())) |
| 111 |
sig_root.append(signature_value_element) |
| 112 |
elif any(self.sign_alg.startswith(i) for i in ["dsa-", "rsa-", "ecdsa-"]): |
| 113 |
if isinstance(key, (str, bytes)): |
| 114 |
from cryptography.hazmat.primitives.serialization import load_pem_private_key |
| 115 |
|
| 116 |
key = load_pem_private_key(key, password=passphrase, backend=default_backend()) |
| 117 |
|
| 118 |
hash_alg = self._get_signature_digest_method_by_tag(self.sign_alg) |
| 119 |
if self.sign_alg.startswith("dsa-"): |
| 120 |
signature = key.sign(signed_info_c14n, algorithm=hash_alg) |
| 121 |
elif self.sign_alg.startswith("ecdsa-"): |
| 122 |
signature = key.sign(signed_info_c14n, signature_algorithm=ec.ECDSA(algorithm=hash_alg)) |
| 123 |
elif self.sign_alg.startswith("rsa-"): |
| 124 |
signature = key.sign(signed_info_c14n, padding=PKCS1v15(), algorithm=hash_alg) |
| 125 |
else: |
| 126 |
raise NotImplementedError() |
| 127 |
if self.sign_alg.startswith("dsa-"): |
| 128 |
# Note: The output of the DSA signer is a DER-encoded ASN.1 sequence of two DER integers. |
| 129 |
from asn1crypto.algos import DSASignature |
| 130 |
|
| 131 |
decoded_signature = DSASignature.load(signature).native |
| 132 |
r = decoded_signature["r"] |
| 133 |
s = decoded_signature["s"] |
| 134 |
signature = long_to_bytes(r).rjust(32, b"\0") + long_to_bytes(s).rjust(32, b"\0") |
| 135 |
|
| 136 |
signature_value_element.text = ensure_str(b64encode(signature)) |
| 137 |
|
| 138 |
if key_info is None: |
| 139 |
key_info = SubElement(sig_root, ds_tag("KeyInfo")) |
| 140 |
if key_name is not None: |
| 141 |
keyname = SubElement(key_info, ds_tag("KeyName")) |
| 142 |
keyname.text = key_name |
| 143 |
|
| 144 |
if cert_chain is None: |
| 145 |
self._serialize_key_value(key, key_info) |
| 146 |
else: |
| 147 |
x509_data = SubElement(key_info, ds_tag("X509Data")) |
| 148 |
for cert in cert_chain: |
| 149 |
x509_certificate = SubElement(x509_data, ds_tag("X509Certificate")) |
| 150 |
if isinstance(cert, (str, bytes)): |
| 151 |
x509_certificate.text = strip_pem_header(cert) |
| 152 |
else: |
| 153 |
from OpenSSL.crypto import FILETYPE_PEM, dump_certificate |
| 154 |
|
| 155 |
x509_certificate.text = strip_pem_header(dump_certificate(FILETYPE_PEM, cert)) |
| 156 |
else: |
| 157 |
sig_root.append(key_info) |
| 158 |
else: |
| 159 |
raise NotImplementedError() |
| 160 |
|
| 161 |
for c14n_input in c14n_inputs[1:]: |
| 162 |
sig_root.append(c14n_input) |
| 163 |
return doc_root |
| 164 |
|
| 165 |
def _unpack(self, data): |
| 166 |
sig_root = Element(ds_tag("Signature"), nsmap=self.namespaces) |
| 167 |
|
| 168 |
if isinstance(data[0], (str, bytes)): |
| 169 |
raise InvalidInput("First data item **must** be an XML element") |
| 170 |
|
| 171 |
doc_root = self.get_root(data[0]) |
| 172 |
|
| 173 |
c14n_inputs = [self.get_root(data[0])] |
| 174 |
|
| 175 |
signature_placeholders = self._findall(doc_root, "Signature[@Id='placeholder']", anywhere=True) |
| 176 |
if len(signature_placeholders) == 0: |
| 177 |
doc_root.append(sig_root) |
| 178 |
elif len(signature_placeholders) == 1: |
| 179 |
sig_root = signature_placeholders[0] |
| 180 |
del sig_root.attrib["Id"] |
| 181 |
for c14n_input in c14n_inputs: |
| 182 |
placeholders = self._findall(c14n_input, "Signature[@Id='placeholder']", anywhere=True) |
| 183 |
if placeholders: |
| 184 |
assert len(placeholders) == 1 |
| 185 |
_remove_sig(placeholders[0]) |
| 186 |
else: |
| 187 |
raise InvalidInput("Enveloped signature input contains more than one placeholder") |
| 188 |
|
| 189 |
reference_uris = [] |
| 190 |
for c14n_input in c14n_inputs: |
| 191 |
payload_id = None |
| 192 |
for id_attribute in self.id_attributes: |
| 193 |
payload_id = c14n_input.get(id_attribute) |
| 194 |
if payload_id: |
| 195 |
break |
| 196 |
reference_uris.append("#{}".format(payload_id) if payload_id else "") |
| 197 |
|
| 198 |
index = 1 |
| 199 |
for enveloped_data in data[1:]: |
| 200 |
c14n_inputs.append(Element(ds_tag("Object"), nsmap=self.namespaces, Id="object-{}".format(index))) |
| 201 |
if isinstance(enveloped_data, (str, bytes)): |
| 202 |
c14n_inputs[index].text = enveloped_data |
| 203 |
else: |
| 204 |
c14n_inputs[index].append(self.get_root(enveloped_data)) |
| 205 |
reference_uris.append("#object-{}".format(index)) |
| 206 |
index += 1 |
| 207 |
|
| 208 |
return sig_root, doc_root, c14n_inputs, reference_uris |
| 209 |
|
| 210 |
def _build_sig(self, sig_root, reference_uris, c14n_inputs): |
| 211 |
signed_info = SubElement(sig_root, ds_tag("SignedInfo"), nsmap=self.namespaces) |
| 212 |
c14n_method = SubElement(signed_info, ds_tag("CanonicalizationMethod"), Algorithm=self.c14n_alg) # noqa:F841 |
| 213 |
if self.sign_alg.startswith("hmac-"): |
| 214 |
algorithm_id = self.known_hmac_digest_tags[self.sign_alg] |
| 215 |
else: |
| 216 |
algorithm_id = self.known_signature_digest_tags[self.sign_alg] |
| 217 |
signature_method = SubElement(signed_info, ds_tag("SignatureMethod"), Algorithm=algorithm_id) # noqa:F841 |
| 218 |
for i, reference_uri in enumerate(reference_uris): |
| 219 |
reference = SubElement(signed_info, ds_tag("Reference"), URI=reference_uri) |
| 220 |
if i == 0: |
| 221 |
transforms = SubElement(reference, ds_tag("Transforms")) |
| 222 |
SubElement(transforms, ds_tag("Transform"), Algorithm=namespaces.ds + "enveloped-signature") |
| 223 |
SubElement(transforms, ds_tag("Transform"), Algorithm=self.c14n_alg) |
| 224 |
digest_method = SubElement( # noqa:F841 |
| 225 |
reference, ds_tag("DigestMethod"), Algorithm=self.known_digest_tags[self.digest_alg] |
| 226 |
) |
| 227 |
digest_value = SubElement(reference, ds_tag("DigestValue")) |
| 228 |
payload_c14n = self._c14n(c14n_inputs[i], algorithm=self.c14n_alg) |
| 229 |
digest = self._get_digest(payload_c14n, self._get_digest_method_by_tag(self.digest_alg)) |
| 230 |
digest_value.text = digest |
| 231 |
signature_value = SubElement(sig_root, ds_tag("SignatureValue")) |
| 232 |
return signed_info, signature_value |
| 233 |
|
| 234 |
def _serialize_key_value(self, key, key_info_element): |
| 235 |
key_value = SubElement(key_info_element, ds_tag("KeyValue")) |
| 236 |
if self.sign_alg.startswith("rsa-"): |
| 237 |
rsa_key_value = SubElement(key_value, ds_tag("RSAKeyValue")) |
| 238 |
modulus = SubElement(rsa_key_value, ds_tag("Modulus")) |
| 239 |
modulus.text = ensure_str(b64encode(long_to_bytes(key.public_key().public_numbers().n))) |
| 240 |
exponent = SubElement(rsa_key_value, ds_tag("Exponent")) |
| 241 |
exponent.text = ensure_str(b64encode(long_to_bytes(key.public_key().public_numbers().e))) |
| 242 |
elif self.sign_alg.startswith("dsa-"): |
| 243 |
dsa_key_value = SubElement(key_value, ds_tag("DSAKeyValue")) |
| 244 |
for field in "p", "q", "g", "y": |
| 245 |
e = SubElement(dsa_key_value, ds_tag(field.upper())) |
| 246 |
|
| 247 |
if field == "y": |
| 248 |
key_params = key.public_key().public_numbers() |
| 249 |
else: |
| 250 |
key_params = key.parameters().parameter_numbers() |
| 251 |
|
| 252 |
e.text = ensure_str(b64encode(long_to_bytes(getattr(key_params, field)))) |
| 253 |
elif self.sign_alg.startswith("ecdsa-"): |
| 254 |
ec_key_value = SubElement(key_value, dsig11_tag("ECKeyValue"), nsmap=dict(dsig11=namespaces.dsig11)) |
| 255 |
named_curve = SubElement( # noqa:F841 |
| 256 |
ec_key_value, dsig11_tag("NamedCurve"), URI=self.known_ecdsa_curve_oids[key.curve.name] |
| 257 |
) |
| 258 |
public_key = SubElement(ec_key_value, dsig11_tag("PublicKey")) |
| 259 |
x = key.public_key().public_numbers().x |
| 260 |
y = key.public_key().public_numbers().y |
| 261 |
public_key.text = ensure_str(b64encode(long_to_bytes(4) + long_to_bytes(x) + long_to_bytes(y))) |
| 262 |
|
| 263 |
|
| 264 |
if __name__ == "__main__": |
| 265 |
signer = XMLEnvelopedEnvelopingSigner() |
| 266 |
|
| 267 |
with open(os.path.join(os.path.dirname(__file__), "test", "example.pem"), "rb") as fh: |
| 268 |
crt = fh.read() |
| 269 |
with open(os.path.join(os.path.dirname(__file__), "test", "example.key"), "rb") as fh: |
| 270 |
key = fh.read() |
| 271 |
|
| 272 |
data = [ |
| 273 |
etree.parse(os.path.join(os.path.dirname(__file__), "test", "example2.xml")), |
| 274 |
etree.parse(os.path.join(os.path.dirname(__file__), "test", "example.xml")), |
| 275 |
] |
| 276 |
|
| 277 |
signed_data = signer.sign(data, key=key, cert=crt) |
| 278 |
signed_data_str = etree.tostring(signed_data) |
| 279 |
with open(os.path.join(os.path.dirname(__file__), "test", "example-125.xml"), "wb") as fh: |
| 280 |
fh.write(signed_data_str) |