| 1 |
#!/usr/bin/env python |
| 2 |
|
| 3 |
import itertools |
| 4 |
import os |
| 5 |
import re |
| 6 |
import sys |
| 7 |
import unittest |
| 8 |
from base64 import b64decode, b64encode |
| 9 |
from concurrent.futures import ThreadPoolExecutor |
| 10 |
from dataclasses import replace |
| 11 |
from datetime import datetime |
| 12 |
from glob import glob |
| 13 |
from xml.etree import ElementTree as stdlibElementTree |
| 14 |
|
| 15 |
import cryptography.exceptions |
| 16 |
from cryptography.hazmat.primitives.asymmetric import dsa, ec, rsa |
| 17 |
from cryptography.x509 import load_der_x509_certificate, load_pem_x509_certificate |
| 18 |
from lxml import etree |
| 19 |
|
| 20 |
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))) |
| 21 |
from signxml import ( # noqa:E402 |
| 22 |
CanonicalizationMethod, |
| 23 |
DigestAlgorithm, |
| 24 |
InvalidCertificate, |
| 25 |
InvalidDigest, |
| 26 |
InvalidInput, |
| 27 |
InvalidSignature, |
| 28 |
SignatureConfiguration, |
| 29 |
SignatureConstructionMethod, |
| 30 |
SignatureMethod, |
| 31 |
SignatureReference, |
| 32 |
VerifyResult, |
| 33 |
XMLSignatureProcessor, |
| 34 |
XMLSigner, |
| 35 |
XMLVerifier, |
| 36 |
methods, |
| 37 |
namespaces, |
| 38 |
) |
| 39 |
from signxml.util import ds_tag # noqa:E402 |
| 40 |
from signxml.xades import ( # noqa:E402 |
| 41 |
XAdESDataObjectFormat, |
| 42 |
XAdESSignatureConfiguration, |
| 43 |
XAdESSignaturePolicy, |
| 44 |
XAdESSigner, |
| 45 |
XAdESVerifier, |
| 46 |
XAdESVerifyResult, |
| 47 |
) |
| 48 |
|
| 49 |
|
| 50 |
class XMLSignerWithSHA1(XMLSigner): |
| 51 |
def check_deprecated_methods(self): |
| 52 |
pass |
| 53 |
|
| 54 |
|
| 55 |
sha1_ok = SignatureConfiguration(signature_methods=list(SignatureMethod), digest_algorithms=list(DigestAlgorithm)) |
| 56 |
hmac_only = SignatureConfiguration( |
| 57 |
signature_methods=[sm for sm in SignatureMethod if "HMAC" in sm.name], digest_algorithms=list(DigestAlgorithm) |
| 58 |
) |
| 59 |
xades_sha1_ok = XAdESSignatureConfiguration( |
| 60 |
signature_methods=list(SignatureMethod), digest_algorithms=list(DigestAlgorithm) |
| 61 |
) |
| 62 |
|
| 63 |
|
| 64 |
def reset_tree(t, method): |
| 65 |
if not isinstance(t, str): |
| 66 |
for s in t.findall(".//ds:Signature", namespaces=namespaces): |
| 67 |
if method == methods.enveloped and s.get("Id") == "placeholder": |
| 68 |
continue |
| 69 |
s.getparent().remove(s) |
| 70 |
|
| 71 |
|
| 72 |
def get_verifier_for_year(year: int): |
| 73 |
class _Verifier(XMLVerifier): |
| 74 |
def get_cert_chain_verifier(self, ca_pem_file): |
| 75 |
verifier = super().get_cert_chain_verifier(ca_pem_file) |
| 76 |
verifier.verification_time = datetime(year, 1, 1) |
| 77 |
return verifier |
| 78 |
|
| 79 |
return _Verifier() |
| 80 |
|
| 81 |
|
| 82 |
class URIResolver(etree.Resolver): |
| 83 |
def resolve(self, url, id, context): |
| 84 |
print(f"Resolving URL '{url}'") |
| 85 |
return None |
| 86 |
|
| 87 |
|
| 88 |
parser = etree.XMLParser(load_dtd=True) |
| 89 |
parser.resolvers.add(URIResolver()) |
| 90 |
|
| 91 |
interop_dir = os.path.join(os.path.dirname(__file__), "interop") |
| 92 |
|
| 93 |
|
| 94 |
class LoadExampleKeys: |
| 95 |
def load_example_keys(self): |
| 96 |
with open(os.path.join(os.path.dirname(__file__), "example.pem"), "rb") as fh: |
| 97 |
crt = fh.read() |
| 98 |
with open(os.path.join(os.path.dirname(__file__), "example.key"), "rb") as fh: |
| 99 |
key = fh.read() |
| 100 |
return crt, key |
| 101 |
|
| 102 |
def load_example_ecdsa_keys(self): |
| 103 |
with open(os.path.join(os.path.dirname(__file__), "example_ecdsa.pem"), "rb") as fh: |
| 104 |
crt = fh.read() |
| 105 |
with open(os.path.join(os.path.dirname(__file__), "example_ecdsa.key"), "rb") as fh: |
| 106 |
key = fh.read() |
| 107 |
return crt, key |
| 108 |
|
| 109 |
|
| 110 |
class TestVerifyXML(unittest.TestCase, LoadExampleKeys): |
| 111 |
def test_example_multi(self): |
| 112 |
cert, _ = self.load_example_keys() |
| 113 |
with open(os.path.join(os.path.dirname(__file__), "example.pem")) as fh: |
| 114 |
cert = fh.read() |
| 115 |
example_file = os.path.join(os.path.dirname(__file__), "example-125.xml") |
| 116 |
XMLVerifier().verify( |
| 117 |
data=etree.parse(example_file), |
| 118 |
x509_cert=cert, |
| 119 |
expect_references=2, |
| 120 |
) |
| 121 |
|
| 122 |
def test_example_multi_unspecified_reference_count(self): |
| 123 |
cert, _ = self.load_example_keys() |
| 124 |
with open(os.path.join(os.path.dirname(__file__), "example.pem")) as fh: |
| 125 |
cert = fh.read() |
| 126 |
example_file = os.path.join(os.path.dirname(__file__), "example-125.xml") |
| 127 |
res = XMLVerifier().verify( |
| 128 |
data=etree.parse(example_file), |
| 129 |
x509_cert=cert, |
| 130 |
expect_references=True, |
| 131 |
) |
| 132 |
|
| 133 |
self.assertIsInstance(res, list) |
| 134 |
self.assertEqual(2, len(res)) |
| 135 |
|
| 136 |
|
| 137 |
class TestSignXML(unittest.TestCase, LoadExampleKeys): |
| 138 |
def setUp(self): |
| 139 |
self.example_xml_files = ( |
| 140 |
os.path.join(os.path.dirname(__file__), "example.xml"), |
| 141 |
os.path.join(os.path.dirname(__file__), "example2.xml"), |
| 142 |
) |
| 143 |
self.keys = dict( |
| 144 |
hmac=b"secret", |
| 145 |
rsa=rsa.generate_private_key(public_exponent=65537, key_size=2048), |
| 146 |
dsa=dsa.generate_private_key(key_size=1024), |
| 147 |
ecdsa=ec.generate_private_key(curve=ec.SECP384R1()), |
| 148 |
) |
| 149 |
|
| 150 |
def test_basic_signxml_statements(self): |
| 151 |
self.assertEqual(SignatureMethod.RSA_SHA256.value, "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256") |
| 152 |
self.assertEqual(SignatureConstructionMethod.enveloped, methods.enveloped) |
| 153 |
with self.assertRaisesRegex(InvalidInput, "Unknown signature construction method"): |
| 154 |
XMLSignerWithSHA1(method=None) |
| 155 |
|
| 156 |
with self.assertRaisesRegex(InvalidInput, "must be an XML element"): |
| 157 |
XMLSigner(signature_algorithm="hmac-sha256").sign("x", key=b"abc") |
| 158 |
|
| 159 |
digest_algs = list(DigestAlgorithm) |
| 160 |
sig_algs = list(SignatureMethod) |
| 161 |
c14n_algs = { |
| 162 |
"http://www.w3.org/2001/10/xml-exc-c14n#", |
| 163 |
"http://www.w3.org/2001/10/xml-exc-c14n#WithComments", |
| 164 |
} |
| 165 |
|
| 166 |
def test_case(case): |
| 167 |
digest_alg, sig_alg, method, c14n_alg = case |
| 168 |
data = [etree.parse(f).getroot() for f in self.example_xml_files] |
| 169 |
# FIXME: data.extend(stdlibElementTree.parse(f).getroot() for f in (self.example_xml_files) |
| 170 |
data.append(stdlibElementTree.parse(self.example_xml_files[0]).getroot()) |
| 171 |
data.append("x y \n z t\n я\n") |
| 172 |
for d in data: |
| 173 |
if isinstance(d, str) and method != methods.enveloping: |
| 174 |
continue |
| 175 |
print(digest_alg.name, sig_alg.name, c14n_alg, method, type(d)) |
| 176 |
reset_tree(d, method) |
| 177 |
signer = XMLSignerWithSHA1( |
| 178 |
method=method, |
| 179 |
signature_algorithm=sig_alg, |
| 180 |
digest_algorithm=digest_alg, |
| 181 |
c14n_algorithm=c14n_alg, |
| 182 |
) |
| 183 |
sig_alg_type = "rsa" if "RSA_MGF1" in sig_alg.name else sig_alg.name.split("_")[0].lower() |
| 184 |
signed = signer.sign( |
| 185 |
d, key=self.keys[sig_alg_type], reference_uri="URI" if method == methods.detached else None |
| 186 |
) |
| 187 |
# print(etree.tostring(signed)) |
| 188 |
hmac_key = self.keys["hmac"] if sig_alg_type == "hmac" else None |
| 189 |
expect_config = hmac_only if sig_alg_type == "hmac" else sha1_ok |
| 190 |
verify_kwargs = dict( |
| 191 |
require_x509=False, hmac_key=hmac_key, validate_schema=True, expect_config=expect_config |
| 192 |
) |
| 193 |
|
| 194 |
if method == methods.detached: |
| 195 |
|
| 196 |
def resolver(uri): |
| 197 |
if isinstance(d, stdlibElementTree.Element): |
| 198 |
return etree.fromstring(stdlibElementTree.tostring(d)) |
| 199 |
else: |
| 200 |
return d |
| 201 |
|
| 202 |
verify_kwargs["uri_resolver"] = resolver |
| 203 |
|
| 204 |
signed_data = etree.tostring(signed) |
| 205 |
XMLVerifier().verify(signed_data, **verify_kwargs) |
| 206 |
XMLVerifier().verify(signed_data, parser=parser, **verify_kwargs) |
| 207 |
res = XMLVerifier().verify(signed_data, id_attribute="Id", **verify_kwargs) |
| 208 |
self.assertIsInstance(res, VerifyResult) |
| 209 |
for attr in "signed_data", "signed_xml", "signature_xml": |
| 210 |
self.assertTrue(hasattr(res, attr)) |
| 211 |
|
| 212 |
if res.signed_xml is not None: |
| 213 |
# Ensure the signature is not part of the signed data |
| 214 |
self.assertIsNone(res.signed_xml.find(".//{http://www.w3.org/2000/09/xmldsig#}Signature")) |
| 215 |
self.assertNotEqual(res.signed_xml.tag, "{http://www.w3.org/2000/09/xmldsig#}Signature") |
| 216 |
|
| 217 |
# Ensure the signature was returned |
| 218 |
self.assertEqual(res.signature_xml.tag, "{http://www.w3.org/2000/09/xmldsig#}Signature") |
| 219 |
|
| 220 |
if method == methods.enveloping: |
| 221 |
with self.assertRaisesRegex(InvalidInput, "Unable to resolve reference URI"): |
| 222 |
XMLVerifier().verify(signed_data, id_attribute="X", **verify_kwargs) |
| 223 |
|
| 224 |
with self.assertRaisesRegex(InvalidInput, "Expected a X.509 certificate based signature"): |
| 225 |
XMLVerifier().verify( |
| 226 |
signed_data, |
| 227 |
hmac_key=hmac_key, |
| 228 |
uri_resolver=verify_kwargs.get("uri_resolver"), |
| 229 |
expect_config=expect_config, |
| 230 |
) |
| 231 |
|
| 232 |
if method != methods.detached: |
| 233 |
with self.assertRaisesRegex(InvalidSignature, "Digest mismatch"): |
| 234 |
mangled_sig = signed_data.replace(b"Austria", b"Mongolia").replace(b"x y", b"a b") |
| 235 |
XMLVerifier().verify(mangled_sig, **verify_kwargs) |
| 236 |
|
| 237 |
with self.assertRaises(cryptography.exceptions.InvalidSignature): |
| 238 |
mangled_sig = signed_data.replace(b"<ds:DigestValue>", b"<ds:DigestValue>!") |
| 239 |
XMLVerifier().verify(mangled_sig, **verify_kwargs) |
| 240 |
|
| 241 |
with self.assertRaises(cryptography.exceptions.InvalidSignature): |
| 242 |
sig_value = re.search(b"<ds:SignatureValue>(.+?)</ds:SignatureValue>", signed_data).group(1) |
| 243 |
mangled_sig = re.sub( |
| 244 |
b"<ds:SignatureValue>(.+?)</ds:SignatureValue>", |
| 245 |
b"<ds:SignatureValue>" + b64encode(b64decode(sig_value)[::-1]) + b"</ds:SignatureValue>", |
| 246 |
signed_data, |
| 247 |
) |
| 248 |
XMLVerifier().verify(mangled_sig, **verify_kwargs) |
| 249 |
|
| 250 |
with self.assertRaises(etree.XMLSyntaxError): |
| 251 |
XMLVerifier().verify("", hmac_key=hmac_key, require_x509=False) |
| 252 |
|
| 253 |
if sig_alg_type == "hmac": |
| 254 |
with self.assertRaisesRegex(InvalidSignature, "Signature mismatch"): |
| 255 |
verify_kwargs["hmac_key"] = b"SECRET" |
| 256 |
XMLVerifier().verify(signed_data, **verify_kwargs) |
| 257 |
|
| 258 |
executor = ThreadPoolExecutor() |
| 259 |
for _ in executor.map(test_case, itertools.product(digest_algs, sig_algs, methods, c14n_algs)): |
| 260 |
pass |
| 261 |
|
| 262 |
def test_x509_certs(self): |
| 263 |
verifier = get_verifier_for_year(2015) |
| 264 |
tree = etree.parse(self.example_xml_files[0]) |
| 265 |
ca_pem_file = os.path.join(os.path.dirname(__file__), "example-ca.pem").encode("utf-8") |
| 266 |
crt, key = self.load_example_keys() |
| 267 |
for method in methods.enveloped, methods.enveloping: |
| 268 |
data = tree.getroot() |
| 269 |
reset_tree(data, method) |
| 270 |
signer = XMLSigner(method=method, signature_algorithm=SignatureMethod.RSA_SHA256) |
| 271 |
signed = signer.sign(data, key=key, cert=crt) |
| 272 |
signed_data = etree.tostring(signed) |
| 273 |
verifier.verify(signed_data, x509_cert=crt) |
| 274 |
verifier.verify(signed_data, x509_cert=load_pem_x509_certificate(crt)) |
| 275 |
verifier.verify(signed_data, x509_cert=crt, cert_subject_name="*.example.com") |
| 276 |
|
| 277 |
with self.assertRaises(ValueError): |
| 278 |
verifier.verify(signed_data, x509_cert=crt[::-1]) |
| 279 |
|
| 280 |
with self.assertRaises(InvalidSignature): |
| 281 |
verifier.verify(signed_data, x509_cert=crt, cert_subject_name="test") |
| 282 |
|
| 283 |
# FIXME: create new test case with reconfigured CA/EKU |
| 284 |
with self.assertRaisesRegex(InvalidCertificate, "required EKU not found"): |
| 285 |
verifier.verify(signed_data, ca_pem_file=ca_pem_file) |
| 286 |
|
| 287 |
with self.assertRaisesRegex(InvalidCertificate, "required EKU not found"): |
| 288 |
verifier.verify(signed_data) |
| 289 |
|
| 290 |
# TODO: negative: verify with wrong cert, wrong CA |
| 291 |
|
| 292 |
def test_xmldsig_interop_examples(self): |
| 293 |
ca_pem_file = os.path.join(os.path.dirname(__file__), "interop", "cacert.pem").encode("utf-8") |
| 294 |
|
| 295 |
verifier = get_verifier_for_year(2015) |
| 296 |
for signature_file in glob(os.path.join(os.path.dirname(__file__), "interop", "*.xml")): |
| 297 |
print("Verifying", signature_file) |
| 298 |
with open(signature_file, "rb") as fh: |
| 299 |
msg = "basicConstraints.cA must not be asserted in an EE certificate" |
| 300 |
with self.assertRaisesRegex(InvalidCertificate, msg): |
| 301 |
verifier.verify(fh.read(), ca_pem_file=ca_pem_file, expect_config=sha1_ok) |
| 302 |
|
| 303 |
def test_xmldsig_interop_TR2012(self): |
| 304 |
def get_x509_cert(**kwargs): |
| 305 |
with open(os.path.join(interop_dir, "TR2012", "rsa-cert.der"), "rb") as fh: |
| 306 |
return [load_der_x509_certificate(fh.read())] |
| 307 |
|
| 308 |
signature_files = glob(os.path.join(interop_dir, "TR2012", "signature*.xml")) |
| 309 |
for signature_file in signature_files: |
| 310 |
print("Verifying", signature_file) |
| 311 |
with open(signature_file, "rb") as fh: |
| 312 |
try: |
| 313 |
sig = fh.read() |
| 314 |
XMLVerifier().verify( |
| 315 |
sig, |
| 316 |
require_x509=False, |
| 317 |
hmac_key=b"testkey" if "hmac" in signature_file else None, |
| 318 |
validate_schema=True, |
| 319 |
cert_resolver=get_x509_cert if "x509digest" in signature_file else None, |
| 320 |
expect_config=hmac_only if "hmac" in signature_file else sha1_ok, |
| 321 |
) |
| 322 |
sig.decode("utf-8") |
| 323 |
except Exception as e: |
| 324 |
if "keyinforeference" in signature_file: |
| 325 |
print("Unsupported test case:", type(e), e) |
| 326 |
elif "x509digest" in signature_file: |
| 327 |
assert isinstance(e, InvalidCertificate) |
| 328 |
else: |
| 329 |
raise |
| 330 |
|
| 331 |
def test_xmldsig_interop(self): |
| 332 |
def resolver(uri): |
| 333 |
if uri == "document.xml": |
| 334 |
with open(os.path.join(interop_dir, "phaos-xmldsig-three", uri), "rb") as fh: |
| 335 |
return fh.read() |
| 336 |
elif uri == "http://www.ietf.org/rfc/rfc3161.txt": |
| 337 |
with open(os.path.join(os.path.dirname(__file__), "rfc3161.txt"), "rb") as fh: |
| 338 |
return fh.read() |
| 339 |
return None |
| 340 |
|
| 341 |
def get_x509_cert(signature_file): |
| 342 |
if "windows_store_signature" in signature_file: |
| 343 |
return open(os.path.join(interop_dir, "xml-crypto", "windows_store_certificate.pem")).read() |
| 344 |
elif "pyXMLSecurity" in signature_file: |
| 345 |
return open(os.path.join(interop_dir, "pyXMLSecurity", "test.pem")).read() |
| 346 |
else: |
| 347 |
return None |
| 348 |
|
| 349 |
def get_ca_pem_file(signature_file): |
| 350 |
if "signature-dsa" in signature_file: |
| 351 |
ca_pem_file = os.path.join(interop_dir, "phaos-xmldsig-three", "certs", "dsa-ca-cert.pem") |
| 352 |
elif "signature-rsa" in signature_file: |
| 353 |
ca_pem_file = os.path.join(interop_dir, "phaos-xmldsig-three", "certs", "rsa-ca-cert.pem") |
| 354 |
elif "aleksey-xmldsig-01-enveloped" in signature_file: |
| 355 |
ca_pem_file = os.path.join(interop_dir, "aleksey-xmldsig-01-enveloped", "cacert.pem") |
| 356 |
elif "aleksey" in signature_file: |
| 357 |
ca_pem_file = os.path.join(interop_dir, "aleksey-xmldsig-01", "cacert.pem") |
| 358 |
elif "wsfederation_metadata" in signature_file: |
| 359 |
ca_pem_file = os.path.join(interop_dir, "xml-crypto", "wsfederation_metadata.pem") |
| 360 |
elif "signature_with_inclusivenamespaces" in signature_file: |
| 361 |
ca_pem_file = os.path.join(interop_dir, "xml-crypto", "signature_with_inclusivenamespaces.pem") |
| 362 |
else: |
| 363 |
return None |
| 364 |
return ca_pem_file.encode("utf-8") |
| 365 |
|
| 366 |
def cert_resolver(x509_issuer_name, x509_serial_number, x509_digest): |
| 367 |
with open(os.path.join(interop_dir, "phaos-xmldsig-three", "certs", "rsa-cert.pem")) as fh: |
| 368 |
return [fh.read()] |
| 369 |
|
| 370 |
signature_files = glob(os.path.join(interop_dir, "*", "signature*.xml")) |
| 371 |
signature_files += glob(os.path.join(interop_dir, "aleksey*", "*.xml")) |
| 372 |
signature_files += glob(os.path.join(interop_dir, "xml-crypto", "*.xml")) |
| 373 |
signature_files += glob(os.path.join(interop_dir, "pyXMLSecurity", "*.xml")) |
| 374 |
for signature_file in signature_files: |
| 375 |
print("Verifying", signature_file) |
| 376 |
hmac_key = None |
| 377 |
expect_config = sha1_ok |
| 378 |
if "hmac" in signature_file: |
| 379 |
hmac_key = b"test" if "phaos" in signature_file else b"secret" |
| 380 |
expect_config = hmac_only |
| 381 |
with open(signature_file, "rb") as fh: |
| 382 |
try: |
| 383 |
sig = fh.read() |
| 384 |
verifier = get_verifier_for_year(2010 if "phaos" in signature_file else 2014) |
| 385 |
verifier.excise_empty_xmlns_declarations = True |
| 386 |
verifier.verify( |
| 387 |
sig, |
| 388 |
require_x509=False, |
| 389 |
hmac_key=hmac_key, |
| 390 |
validate_schema=True, |
| 391 |
uri_resolver=resolver, |
| 392 |
x509_cert=get_x509_cert(signature_file), |
| 393 |
cert_resolver=cert_resolver if "issuer-serial" in signature_file else None, |
| 394 |
ca_pem_file=get_ca_pem_file(signature_file), |
| 395 |
expect_config=expect_config, |
| 396 |
) |
| 397 |
decoded_sig = sig.decode("utf-8") |
| 398 |
if "HMACOutputLength" in decoded_sig or "bad" in signature_file or "expired" in signature_file: |
| 399 |
raise BaseException("Expected an exception to occur") |
| 400 |
except Exception as e: |
| 401 |
unsupported_cases = ( |
| 402 |
"xpath-transform", |
| 403 |
"xslt-transform", |
| 404 |
"xpointer", |
| 405 |
"x509-data-ski", |
| 406 |
"x509-data-subject-name", |
| 407 |
"x509data", |
| 408 |
"signature-x509-ski", |
| 409 |
"signature-x509-is", |
| 410 |
) |
| 411 |
bad_interop_cases = ( |
| 412 |
"signature-big", |
| 413 |
"enveloping-dsa-x509chain", |
| 414 |
"enveloping-sha512-hmac-sha512", |
| 415 |
"enveloping-sha512-rsa-sha512", |
| 416 |
"enveloping-rsa-x509chain", |
| 417 |
"enveloping-sha1-rsa-sha1", |
| 418 |
"enveloping-sha224-rsa-sha224", |
| 419 |
"enveloping-sha256-rsa-sha256", |
| 420 |
"enveloping-sha384-rsa-sha384", |
| 421 |
) |
| 422 |
if signature_file.endswith("expired-cert.xml") or signature_file.endswith( |
| 423 |
"wsfederation_metadata.xml" |
| 424 |
): # noqa |
| 425 |
with self.assertRaisesRegex(InvalidCertificate, "cert is not valid at validation time"): |
| 426 |
raise |
| 427 |
elif signature_file.endswith("invalid_enveloped_transform.xml"): |
| 428 |
self.assertIsInstance(e, InvalidSignature) |
| 429 |
# with self.assertRaisesRegex(ValueError, "Can't remove the root signature node"): |
| 430 |
# raise |
| 431 |
elif "md5" in signature_file or "ripemd160" in signature_file: |
| 432 |
self.assertIsInstance(e, InvalidInput) |
| 433 |
# with self.assertRaisesRegex(InvalidInput, "Algorithm .+ is not recognized"): |
| 434 |
# raise |
| 435 |
elif "HMACOutputLength" in sig.decode("utf-8"): |
| 436 |
self.assertIsInstance(e, (InvalidSignature, InvalidDigest)) |
| 437 |
elif signature_file.endswith("signature-rsa-enveloped-bad-digest-val.xml"): |
| 438 |
# self.assertIsInstance(e, InvalidDigest) |
| 439 |
self.assertIsInstance(e, InvalidCertificate) |
| 440 |
elif signature_file.endswith("signature-rsa-detached-xslt-transform-bad-retrieval-method.xml"): |
| 441 |
self.assertIsInstance(e, InvalidInput) |
| 442 |
elif signature_file.endswith("signature-rsa-enveloped-bad-sig.xml"): |
| 443 |
self.assertIsInstance(e, etree.DocumentInvalid) |
| 444 |
elif signature_file.endswith("signature-x509-crt.xml"): |
| 445 |
self.assertIsInstance(e, InvalidCertificate) |
| 446 |
elif signature_file.endswith("signature-keyname.xml"): |
| 447 |
self.assertIsInstance(e, InvalidInput) |
| 448 |
elif signature_file.endswith("signature-x509-sn.xml"): |
| 449 |
self.assertIsInstance(e, InvalidInput) |
| 450 |
elif signature_file.endswith("signature-x509-crt-crl.xml"): |
| 451 |
self.assertIsInstance(e, InvalidCertificate) |
| 452 |
elif signature_file.endswith("signature-retrievalmethod-rawx509crt.xml"): |
| 453 |
self.assertIsInstance(e, InvalidInput) |
| 454 |
elif signature_file.endswith("merlin-xmldsig-twenty-three/signature.xml"): |
| 455 |
self.assertIsInstance(e, InvalidInput) |
| 456 |
elif any(x in signature_file for x in unsupported_cases): |
| 457 |
print("Unsupported test case:", type(e), e) |
| 458 |
elif any(x in signature_file for x in bad_interop_cases) or "Unable to resolve reference" in str(e): |
| 459 |
print("Bad interop test case:", type(e), e) |
| 460 |
elif "Certificate is missing required extension" in str(e): |
| 461 |
print("IGNORED:", type(e), e) |
| 462 |
elif "certificate must be an X509v3 certificate" in str(e): |
| 463 |
print("IGNORED:", type(e), e) |
| 464 |
elif "basicConstraints.cA must not be asserted in an EE certificate" in str(e): |
| 465 |
print("IGNORED:", type(e), e) |
| 466 |
elif "TR2012" not in signature_file: |
| 467 |
raise |
| 468 |
|
| 469 |
def test_changing_signature_namespace_prefix(self): |
| 470 |
data = etree.parse(self.example_xml_files[0]).getroot() |
| 471 |
signer = XMLSigner() |
| 472 |
signer.namespaces = dict(digi_sign=namespaces["ds"]) |
| 473 |
signed = signer.sign(data, key=self.keys["rsa"]) |
| 474 |
signed_data = etree.tostring(signed) |
| 475 |
expected_match = f'<digi_sign:Signature xmlns:digi_sign="{namespaces["ds"]}">' |
| 476 |
self.assertTrue(re.search(expected_match.encode("ascii"), signed_data)) |
| 477 |
|
| 478 |
def test_changing_signature_namespace_prefix_to_default(self): |
| 479 |
data = etree.parse(self.example_xml_files[0]).getroot() |
| 480 |
signer = XMLSigner() |
| 481 |
ns = dict() |
| 482 |
ns[None] = namespaces["ds"] |
| 483 |
signer.namespaces = ns |
| 484 |
signed = signer.sign(data, key=self.keys["rsa"]) |
| 485 |
signed_data = etree.tostring(signed) |
| 486 |
expected_match = f'<Signature xmlns="{namespaces["ds"]}">' |
| 487 |
self.assertTrue(re.search(expected_match.encode("ascii"), signed_data)) |
| 488 |
|
| 489 |
def test_sign_verify_default_ns_roundtrip(self): |
| 490 |
""" |
| 491 |
Test sign/verify round-trip when using default namespace. |
| 492 |
|
| 493 |
See https://github.com/XML-Security/signxml/issues/275 |
| 494 |
""" |
| 495 |
crt, key = self.load_example_keys() |
| 496 |
data = etree.parse(self.example_xml_files[0]).getroot() |
| 497 |
signer = XMLSigner() |
| 498 |
signer.namespaces = {None: namespaces["ds"]} |
| 499 |
signed = signer.sign(data, key=key, cert=crt) |
| 500 |
|
| 501 |
signed_info = signed.find(".//SignedInfo") |
| 502 |
self.assertIsNotNone(signed_info) |
| 503 |
c14n_output = etree.tostring(signed_info, method="c14n").decode() |
| 504 |
self.assertNotIn('xmlns=""', c14n_output) |
| 505 |
self.assertIn('xmlns="http://www.w3.org/2000/09/xmldsig#"', c14n_output) |
| 506 |
|
| 507 |
signed_data = etree.tostring(signed) |
| 508 |
verifier = XMLVerifier() |
| 509 |
verifier.excise_empty_xmlns_declarations = True |
| 510 |
verifier.verify(signed_data, x509_cert=crt) |
| 511 |
|
| 512 |
def test_elementtree_compat(self): |
| 513 |
data = stdlibElementTree.parse(self.example_xml_files[0]).getroot() |
| 514 |
signer = XMLSigner() |
| 515 |
signer.sign(data, key=self.keys["rsa"]) |
| 516 |
|
| 517 |
saml_test_vectors = [ |
| 518 |
"""<samlp:Response xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol" |
| 519 |
xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion" ID="responseId"> |
| 520 |
<saml:Assertion xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" |
| 521 |
xmlns:xs="http://www.w3.org/2001/XMLSchema" ID="assertionId"> |
| 522 |
<ds:Signature xmlns:ds="http://www.w3.org/2000/09/xmldsig#" Id="placeholder" /> |
| 523 |
</saml:Assertion> |
| 524 |
</samlp:Response>""", |
| 525 |
"""<samlp:Response xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol" |
| 526 |
xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion" Id="responseId"> |
| 527 |
<saml:Assertion xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" |
| 528 |
xmlns:xs="http://www.w3.org/2001/XMLSchema" Id="assertionId"> |
| 529 |
<ds:Signature xmlns:ds="http://www.w3.org/2000/09/xmldsig#" Id="placeholder" /> |
| 530 |
</saml:Assertion> |
| 531 |
<saml:Assertion xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" |
| 532 |
xmlns:xs="http://www.w3.org/2001/XMLSchema" Id="assertion2"> |
| 533 |
</saml:Assertion> |
| 534 |
</samlp:Response>""", |
| 535 |
] |
| 536 |
|
| 537 |
def test_verify_results_with_nonspecific_reference_count(self): |
| 538 |
crt, key = self.load_example_keys() |
| 539 |
data = etree.fromstring(self.saml_test_vectors[0]) |
| 540 |
reference_uri = "assertionId" |
| 541 |
signed_root = XMLSigner().sign(data, reference_uri=reference_uri, key=key, cert=crt) |
| 542 |
res = XMLVerifier().verify(etree.tostring(signed_root), x509_cert=crt, expect_references=True) |
| 543 |
|
| 544 |
self.assertIsInstance(res, list) |
| 545 |
self.assertEqual(1, len(res)) |
| 546 |
|
| 547 |
def test_reference_uris_and_custom_key_info(self): |
| 548 |
crt, key = self.load_example_keys() |
| 549 |
|
| 550 |
# Both ID and Id formats. XPath 1 doesn't have case insensitive attribute search |
| 551 |
for d in self.saml_test_vectors: |
| 552 |
data = etree.fromstring(d) |
| 553 |
reference_uri = ["assertionId", "assertion2"] if "assertion2" in d else "assertionId" |
| 554 |
signed_root = XMLSigner().sign(data, reference_uri=reference_uri, key=key, cert=crt) |
| 555 |
res = XMLVerifier().verify(etree.tostring(signed_root), x509_cert=crt, expect_references=True) |
| 556 |
signed_data_root = res[0].signed_xml |
| 557 |
ref = signed_root.xpath( |
| 558 |
"/samlp:Response/saml:Assertion/ds:Signature/ds:SignedInfo/ds:Reference", |
| 559 |
namespaces={ |
| 560 |
"ds": "http://www.w3.org/2000/09/xmldsig#", |
| 561 |
"saml": "urn:oasis:names:tc:SAML:2.0:assertion", |
| 562 |
"samlp": "urn:oasis:names:tc:SAML:2.0:protocol", |
| 563 |
}, |
| 564 |
) |
| 565 |
self.assertEqual("assertionId", ref[0].attrib["URI"][1:]) |
| 566 |
|
| 567 |
self.assertEqual("{urn:oasis:names:tc:SAML:2.0:assertion}Assertion", signed_data_root.tag) |
| 568 |
|
| 569 |
# Also test with detached signing |
| 570 |
ref_xpath = "/ds:Signature/ds:SignedInfo/ds:Reference" |
| 571 |
signer = XMLSigner(method=methods.detached) |
| 572 |
s = signer.sign(data, reference_uri=reference_uri, key=key, cert=crt) |
| 573 |
self.assertTrue(s.xpath(ref_xpath + "/ds:Transforms", namespaces=namespaces)) |
| 574 |
self.assertTrue(s.xpath(ref_xpath + "/ds:DigestMethod", namespaces=namespaces)) |
| 575 |
self.assertTrue(s.xpath(ref_xpath + "/ds:DigestValue", namespaces=namespaces)) |
| 576 |
|
| 577 |
self.assertTrue(s.xpath("/ds:Signature/ds:KeyInfo/ds:X509Data", namespaces=namespaces)) |
| 578 |
self.assertFalse(s.xpath("/ds:Signature/ds:KeyInfo/ds:KeyValue", namespaces=namespaces)) |
| 579 |
s2 = signer.sign(data, reference_uri=reference_uri, key=key, cert=crt, always_add_key_value=True) |
| 580 |
self.assertTrue(s2.xpath("/ds:Signature/ds:KeyInfo/ds:X509Data", namespaces=namespaces)) |
| 581 |
self.assertTrue(s2.xpath("/ds:Signature/ds:KeyInfo/ds:KeyValue", namespaces=namespaces)) |
| 582 |
|
| 583 |
# Test setting custom key info |
| 584 |
wsse_ns = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" |
| 585 |
with open(os.path.join(os.path.dirname(__file__), "wsse_keyinfo.xml")) as fh: |
| 586 |
custom_key_info = etree.fromstring(fh.read()) |
| 587 |
s3 = signer.sign(data, reference_uri=reference_uri, key=key, cert=crt, key_info=custom_key_info) |
| 588 |
self.assertTrue( |
| 589 |
s3.xpath( |
| 590 |
"/ds:Signature/ds:KeyInfo/wsse:SecurityTokenReference", namespaces=dict(namespaces, wsse=wsse_ns) |
| 591 |
) |
| 592 |
) |
| 593 |
|
| 594 |
# Test setting both X509Data and KeyInfo |
| 595 |
s4 = XMLSigner().sign(data, reference_uri=reference_uri, key=key, cert=crt, always_add_key_value=True) |
| 596 |
try: |
| 597 |
XMLVerifier().verify(s4, x509_cert=crt) |
| 598 |
except InvalidSignature as e: |
| 599 |
self.assertIn("Expected to find 1 references, but found 2", str(e)) |
| 600 |
expect_refs = etree.tostring(s4).decode().count("<ds:Reference") |
| 601 |
XMLVerifier().verify(s4, x509_cert=crt, ignore_ambiguous_key_info=True, expect_references=expect_refs) |
| 602 |
|
| 603 |
def test_inclusive_namespaces_signing(self): |
| 604 |
# Test exclusive canonicalization with InclusiveNamespace PrefixList |
| 605 |
data = etree.fromstring(self.saml_test_vectors[0]) |
| 606 |
reference_uri = "assertionId" |
| 607 |
signer = XMLSigner( |
| 608 |
c14n_algorithm=CanonicalizationMethod.EXCLUSIVE_XML_CANONICALIZATION_1_0, |
| 609 |
signature_algorithm=SignatureMethod.HMAC_SHA256, |
| 610 |
) |
| 611 |
sign_args = dict(data=data, reference_uri=reference_uri, key=b"secret") |
| 612 |
signed_with_insp = signer.sign(inclusive_ns_prefixes=["saml", "samlp", "ds"], **sign_args) |
| 613 |
self.assertEqual( |
| 614 |
signed_with_insp.find(".//ds:SignatureValue", namespaces=namespaces).text, |
| 615 |
"V3HwLySk6TmkPFlqtOU3xCln1Cga7v30rFqy8ZmJITA=", |
| 616 |
) |
| 617 |
signed_without_insp = signer.sign(**sign_args) |
| 618 |
self.assertEqual( |
| 619 |
signed_without_insp.find(".//ds:SignatureValue", namespaces=namespaces).text, |
| 620 |
"2Sk3E2SZwQCqX2STDkplw5JJp1ATAB5wsdRdQBAe/7o=", |
| 621 |
) |
| 622 |
# Test different c14n methods for signature and payload |
| 623 |
ref = SignatureReference( |
| 624 |
URI=reference_uri, c14n_method=CanonicalizationMethod.EXCLUSIVE_XML_CANONICALIZATION_1_0 |
| 625 |
) |
| 626 |
sign_args = dict(data=data, reference_uri=[ref], key=b"secret") |
| 627 |
signed = signer.sign(**sign_args) |
| 628 |
self.assertEqual( |
| 629 |
signed.find(".//ds:SignatureValue", namespaces=namespaces).text, |
| 630 |
"2Sk3E2SZwQCqX2STDkplw5JJp1ATAB5wsdRdQBAe/7o=", |
| 631 |
) |
| 632 |
sign_args["reference_uri"][0] = replace( |
| 633 |
sign_args["reference_uri"][0], c14n_method=CanonicalizationMethod.CANONICAL_XML_1_0 |
| 634 |
) |
| 635 |
signed2 = signer.sign(**sign_args) |
| 636 |
self.assertEqual( |
| 637 |
signed2.find(".//ds:SignatureValue", namespaces=namespaces).text, |
| 638 |
"8GPAVJstDxHyuoJqec8C0ssji4zfdXanu1YHGlWbfx0=", |
| 639 |
) |
| 640 |
|
| 641 |
# Test correct default c14n method for payload when c14n transform metadata is omitted |
| 642 |
def _build_transforms_for_reference(transforms_node, reference, exclude_c14n_transform_element=False): |
| 643 |
etree.SubElement( |
| 644 |
transforms_node, ds_tag("Transform"), Algorithm=SignatureConstructionMethod.enveloped.value |
| 645 |
) |
| 646 |
|
| 647 |
signer._build_transforms_for_reference = _build_transforms_for_reference |
| 648 |
signed3 = signer.sign(**sign_args) |
| 649 |
self.assertEqual( |
| 650 |
signed3.find(".//ds:SignatureValue", namespaces=namespaces).text, |
| 651 |
"/iezjApGBVMMUspj5WyZwIOEw30qLX3Gv576vwFMAbQ=", |
| 652 |
) |
| 653 |
XMLVerifier().verify(signed3, hmac_key=b"secret", require_x509=False) |
| 654 |
|
| 655 |
def test_excision_of_untrusted_comments(self): |
| 656 |
pass # TODO: test comments excision |
| 657 |
|
| 658 |
def test_doctype_rejection(self): |
| 659 |
doc = """<!DOCTYPE samlp:Response [<!ATTLIST saml:Assertion xmlns:saml CDATA "urn:oasis:names:tc:SAML:2.0:assertion">]><samlp:Response xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol" xmlns:saml="urn:oasis:names:tc:SAML:2.0:Assertion"><saml:Assertion Version="2.0" ID="_test"> |
| 660 |
<saml:Subject><saml:NameID>[email protected]</saml:NameID></saml:Subject> |
| 661 |
<ds:Signature xmlns:ds="http://www.w3.org/2000/09/xmldsig#"><ds:SignedInfo><ds:CanonicalizationMethod Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"/><ds:SignatureMethod Algorithm="http://www.w3.org/2001/04/xmldsig-more#rsa-sha256"/><ds:Reference URI="#_test"><ds:Transforms><ds:Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature"/><ds:Transform Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"/></ds:Transforms><ds:DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256"/><ds:DigestValue>qMAYPT7tK9U5s0OuDLgiY7t3uXBgXxmM8doM849sH2g=</ds:DigestValue></ds:Reference></ds:SignedInfo><ds:SignatureValue>VfrFy9IakkV48zDp0NJxdueUPG8Ec9II0I9InWHDaQzIlNm+F8fwdvYU6JEoXoIKHv3Bj8beE9qcNh03xzL/l7DVtKV31YQc0+cylp/5YvkZBZHza643tKKPIXag3tR6Zo/wR+X+e1YuDlbb1oAOcl85Ob9ZPmW7wnVqu27kGratcYbU2vHh4jbYua3ZkPyUajwbw8O5R/LLIg3uko1oWdQxWnmNM9zoxLT3V5O7rYPp/gwvebhYTX6tnxkKrHK7CsslEINRbEDCXbpc0gT9TuADSP/aHrQmFN8eLXahpyBygYnNIdbil4usKfdcf2L13x03OkWiLdhvqMbOQZOV0g==</ds:SignatureValue><ds:KeyInfo><ds:X509Data><ds:X509Certificate>MIIC/zCCAeegAwIBAgIUZd6NULqQQPpHUImmpZ5d8KO0meYwDQYJKoZIhvcNAQEL |
| 662 |
BQAwDzENMAsGA1UEAwwEdGVzdDAeFw0yNjAzMDExNzExNTlaFw0yNjAzMDIxNzEx |
| 663 |
NTlaMA8xDTALBgNVBAMMBHRlc3QwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEK |
| 664 |
AoIBAQDAyHLFxknSg8igmRlNJwSnZ1HzRtaqmLb6THv2cyNdGspvce6LmfOE/0dz |
| 665 |
KEqh7XVhvK3pMfsDi0NEjddyENA+IRZIcjQinBaG6d1+k/LmJybO+SBtopKbOMi2 |
| 666 |
EsjlTbcOj/TzvEkdSJukHvZWd/AfUJcl7YWHTYCeevtad/ko454AfS6fGSWg4HXd |
| 667 |
7s6SI/RlcDW3VAzY19C6bIX8GPVW5aZZg0Dihe2QW1ghN5n/6Etp9No2zooBdV1f |
| 668 |
zq79xvECUdTSwGEvEZz92sxjFnOJKVFZetDuE+BylpYxnc7akiPQZbhHCeiTheiL |
| 669 |
yiDE2BVp6q2zxXuhNjbkXvVLI0qtAgMBAAGjUzBRMB0GA1UdDgQWBBQcgXR3Y2y/ |
| 670 |
jjlgm1DyvNLu/+NN4TAfBgNVHSMEGDAWgBQcgXR3Y2y/jjlgm1DyvNLu/+NN4TAP |
| 671 |
BgNVHRMBAf8EBTADAQH/MA0GCSqGSIb3DQEBCwUAA4IBAQATqMPgzLiUaxJBBvKa |
| 672 |
+TyUTiH/ZFjGY3eYEWxbjzaBvRll8r09rd8roORdPr299EKKfDMn4N9l9X+nYvAY |
| 673 |
//sJ+NO54yO6uiWW6ScOqq9igj5Q6bnNgvuz/5PBai/i/sb8cFKHzY+TEIRnRMBb |
| 674 |
8LAynzKgh9IXyTvjeBCiIT06C0nP4tKIygIoXcESBzzLjOO9rxG9nLqznZYfUKMT |
| 675 |
4h8Lh2DO5VeLsZawPsR9VU99MjrYsMrcHPXdW42KUTY7IpjBcd69xI6lhwTOqOV0 |
| 676 |
TStby5C4JWMZtMpJPwBJjczYSBsxx91OTDzMhQuEqH4WiCOcrBtqLjT7DSj6kAHx |
| 677 |
ea+x |
| 678 |
</ds:X509Certificate></ds:X509Data></ds:KeyInfo></ds:Signature></saml:Assertion></samlp:Response>""" |
| 679 |
|
| 680 |
with self.assertRaises(InvalidInput): |
| 681 |
XMLVerifier().verify(doc) |
| 682 |
|
| 683 |
def test_mismatched_key_value_with_x509_data(self): |
| 684 |
crt, key = self.load_example_keys() |
| 685 |
data = etree.parse(os.path.join(os.path.dirname(__file__), "example.xml")).getroot() |
| 686 |
signer = XMLSigner() |
| 687 |
signed = signer.sign(data, key=key, cert=crt, always_add_key_value=True) |
| 688 |
key_info = signed.find(".//ds:KeyInfo", namespaces=namespaces) |
| 689 |
key_value = key_info.find("ds:KeyValue", namespaces=namespaces) |
| 690 |
key_info.remove(key_value) |
| 691 |
mismatched_key = rsa.generate_private_key(public_exponent=65537, key_size=2048) |
| 692 |
signer._serialize_key_value(mismatched_key, key_info) |
| 693 |
signed_xml = etree.tostring(signed) |
| 694 |
|
| 695 |
with self.assertRaisesRegex( |
| 696 |
InvalidInput, |
| 697 |
"Both X509Data and KeyValue found and they represent different public keys", |
| 698 |
): |
| 699 |
XMLVerifier().verify(signed_xml, x509_cert=crt) |
| 700 |
|
| 701 |
XMLVerifier().verify(signed_xml, x509_cert=crt, ignore_ambiguous_key_info=True) |
| 702 |
|
| 703 |
def test_mismatched_ecdsa_key_value_with_x509_data(self): |
| 704 |
crt, key = self.load_example_ecdsa_keys() |
| 705 |
data = etree.parse(os.path.join(os.path.dirname(__file__), "example.xml")).getroot() |
| 706 |
signer = XMLSigner( |
| 707 |
signature_algorithm=SignatureMethod.ECDSA_SHA384, |
| 708 |
) |
| 709 |
signed = signer.sign(data, key=key, cert=crt, always_add_key_value=True) |
| 710 |
key_info = signed.find(".//ds:KeyInfo", namespaces=namespaces) |
| 711 |
key_value = key_info.find("ds:KeyValue", namespaces=namespaces) |
| 712 |
key_info.remove(key_value) |
| 713 |
mismatched_key = ec.generate_private_key(curve=ec.SECP384R1()) |
| 714 |
signer._serialize_key_value(mismatched_key, key_info) |
| 715 |
signed_xml = etree.tostring(signed) |
| 716 |
|
| 717 |
with self.assertRaisesRegex( |
| 718 |
InvalidInput, |
| 719 |
"Both X509Data and KeyValue found and they represent different public keys", |
| 720 |
): |
| 721 |
XMLVerifier().verify(signed_xml, x509_cert=crt) |
| 722 |
|
| 723 |
XMLVerifier().verify(signed_xml, x509_cert=crt, ignore_ambiguous_key_info=True) |
| 724 |
|
| 725 |
def test_matched_ecdsa_key_value_with_x509_data(self): |
| 726 |
crt, key = self.load_example_ecdsa_keys() |
| 727 |
data = etree.parse(os.path.join(os.path.dirname(__file__), "example.xml")).getroot() |
| 728 |
signer = XMLSigner( |
| 729 |
signature_algorithm=SignatureMethod.ECDSA_SHA384, |
| 730 |
) |
| 731 |
signed = signer.sign(data, key=key, cert=crt, always_add_key_value=True) |
| 732 |
signed_xml = etree.tostring(signed) |
| 733 |
|
| 734 |
XMLVerifier().verify(signed_xml, x509_cert=crt, ignore_ambiguous_key_info=False) |
| 735 |
|
| 736 |
def test_ws_security(self): |
| 737 |
wsse_dir = os.path.join(interop_dir, "ws-security", "ws.js") |
| 738 |
with open(os.path.join(wsse_dir, "examples", "server_public.pem"), "rb") as fh: |
| 739 |
crt = fh.read() |
| 740 |
data = etree.parse(os.path.join(wsse_dir, "test", "unit", "client", "files", "valid wss resp.xml")) |
| 741 |
XMLVerifier().verify(data, x509_cert=crt, validate_schema=False, expect_references=2, expect_config=sha1_ok) |
| 742 |
|
| 743 |
data = etree.parse( |
| 744 |
os.path.join(wsse_dir, "test", "unit", "client", "files", "invalid wss resp - changed content.xml") |
| 745 |
) |
| 746 |
with self.assertRaisesRegex(InvalidDigest, "Digest mismatch for reference 0"): |
| 747 |
XMLVerifier().verify(data, x509_cert=crt, validate_schema=False, expect_references=2, expect_config=sha1_ok) |
| 748 |
|
| 749 |
def test_psha1(self): |
| 750 |
from signxml.util import p_sha1 |
| 751 |
|
| 752 |
a, b, c, d = ( |
| 753 |
"grrlUUfhuNwlvQzQ4bV6TT3wA8ieZPltIf4+H7nIvCE=", |
| 754 |
"YLABh3ZmZyiO5gvVLZe9J4JPd9w59KGeTFwE85XlzxE=", |
| 755 |
"Wv3QzY84KfgwSkn1z3QV+LXEoo3nPraZPysJYtA3u4c=", |
| 756 |
"g/uYZmYX7rOm/X7UV4usrvjIPCiWMWwNZJL0ejvz6Y4=", |
| 757 |
) |
| 758 |
self.assertEqual(p_sha1(a, b), c) |
| 759 |
self.assertEqual(p_sha1(b, a), d) |
| 760 |
|
| 761 |
def test_xml_attacks(self): |
| 762 |
for filename in glob(os.path.join(os.path.dirname(__file__), "defusedxml-test-data", "*.xml")): |
| 763 |
with open(filename, "rb") as fh: |
| 764 |
with self.assertRaises((InvalidInput, etree.XMLSyntaxError)): |
| 765 |
XMLVerifier().verify(fh.read()) |
| 766 |
|
| 767 |
def test_signature_properties_with_detached_method(self): |
| 768 |
doc = etree.Element("Test", attrib={"Id": "mytest"}) |
| 769 |
sigprop = etree.Element("{http://somenamespace}MyCustomProperty") |
| 770 |
sigprop.text = "Some Text" |
| 771 |
cert, key = self.load_example_keys() |
| 772 |
signature = XMLSigner(method=methods.detached).sign( |
| 773 |
doc, cert=cert, key=key, reference_uri="#mytest", signature_properties=sigprop |
| 774 |
) |
| 775 |
fulldoc = b"<root>" + etree.tostring(signature) + etree.tostring(doc) + b"</root>" |
| 776 |
XMLVerifier().verify(etree.fromstring(fulldoc), x509_cert=cert, expect_references=2) |
| 777 |
|
| 778 |
def test_signature_properties_with_detached_method_re_enveloping(self): |
| 779 |
doc = etree.Element("{http://somenamespace}Test", attrib={"Id": "mytest"}) |
| 780 |
sigprop = etree.Element("{http://somenamespace}MyCustomProperty") |
| 781 |
sigprop.text = "Some Text" |
| 782 |
cert, key = self.load_example_keys() |
| 783 |
signer = XMLSigner(method=methods.detached, c14n_algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315") |
| 784 |
signer.namespaces["ns0"] = "http://enveloping.namespace" |
| 785 |
signature = signer.sign(doc, cert=cert, key=key, reference_uri="#mytest", signature_properties=sigprop) |
| 786 |
fulldoc = ( |
| 787 |
b'<ns0:root xmlns:ns0="http://enveloping.namespace">' |
| 788 |
+ etree.tostring(signature) |
| 789 |
+ etree.tostring(doc) |
| 790 |
+ b"</ns0:root>" |
| 791 |
) |
| 792 |
XMLVerifier().verify(etree.fromstring(fulldoc), x509_cert=cert, expect_references=2) |
| 793 |
|
| 794 |
def test_payload_c14n(self): |
| 795 |
doc = etree.fromstring('<abc xmlns="http://example.com"><foo xmlns="">bar</foo></abc>') |
| 796 |
self.assertEqual( |
| 797 |
XMLSignatureProcessor()._c14n(doc, algorithm=CanonicalizationMethod.CANONICAL_XML_1_1), |
| 798 |
b'<abc xmlns="http://example.com"><foo xmlns="">bar</foo></abc>', |
| 799 |
) |
| 800 |
|
| 801 |
def test_xmlns_insulation_of_reference_c14n(self): |
| 802 |
cert, key = self.load_example_keys() |
| 803 |
doc = etree.fromstring( |
| 804 |
'<rDE xmlns="http://example.com/ns1">' |
| 805 |
'<DE Id="target"><dDVId>9</dDVId><gOpeDE><iTipEmi>1</iTipEmi></gOpeDE></DE>' |
| 806 |
"</rDE>" |
| 807 |
) |
| 808 |
root = XMLSigner().sign(doc, cert=cert, key=key, reference_uri="#target") |
| 809 |
XMLVerifier().verify(root, x509_cert=cert) |
| 810 |
|
| 811 |
def test_include_c14n_transform_element_by_default(self): |
| 812 |
cert, key = self.load_example_keys() |
| 813 |
doc = etree.fromstring( |
| 814 |
'<rDE xmlns="http://example.com/ns1">' |
| 815 |
'<DE Id="target"><dDVId>9</dDVId><gOpeDE><!-- comment --><iTipEmi>1</iTipEmi></gOpeDE></DE>' |
| 816 |
"</rDE>" |
| 817 |
) |
| 818 |
root = XMLSigner().sign(doc, cert=cert, key=key, reference_uri="#target") |
| 819 |
XMLVerifier().verify(root, x509_cert=cert) |
| 820 |
transform_elements = root.findall( |
| 821 |
"ds:Signature/ds:SignedInfo/ds:Reference/ds:Transforms/ds:Transform", namespaces=namespaces |
| 822 |
) |
| 823 |
transform_algorithms = [el.attrib["Algorithm"] for el in transform_elements] |
| 824 |
self.assertEqual(len(transform_elements), 2) |
| 825 |
self.assertIn("http://www.w3.org/2000/09/xmldsig#enveloped-signature", transform_algorithms) |
| 826 |
self.assertIn("http://www.w3.org/2006/12/xml-c14n11", transform_algorithms) |
| 827 |
|
| 828 |
def test_exclude_c14n_transform_element_option(self): |
| 829 |
cert, key = self.load_example_keys() |
| 830 |
doc = etree.fromstring( |
| 831 |
'<rDE xmlns="http://example.com/ns1">' |
| 832 |
'<DE Id="target"><dDVId>9</dDVId><gOpeDE><!-- comment --><iTipEmi>1</iTipEmi></gOpeDE></DE>' |
| 833 |
"</rDE>" |
| 834 |
) |
| 835 |
root = XMLSigner(c14n_algorithm=CanonicalizationMethod.CANONICAL_XML_1_0_WITH_COMMENTS).sign( |
| 836 |
doc, cert=cert, key=key, reference_uri="#target", exclude_c14n_transform_element=True |
| 837 |
) |
| 838 |
|
| 839 |
# The default to use is CANONICAL_XML_1_1 (no comments), and since it's not specified in Transforms, |
| 840 |
# verification without specifying the reference canonicalization algorithm should fail. |
| 841 |
self.assertRaises( |
| 842 |
InvalidDigest, |
| 843 |
XMLVerifier().verify, |
| 844 |
root, |
| 845 |
x509_cert=cert, |
| 846 |
) |
| 847 |
|
| 848 |
# However, if we use the right configuration, it should verify correctly |
| 849 |
config = SignatureConfiguration( |
| 850 |
default_reference_c14n_method=CanonicalizationMethod.CANONICAL_XML_1_0_WITH_COMMENTS |
| 851 |
) |
| 852 |
XMLVerifier().verify(root, x509_cert=cert, expect_config=config) |
| 853 |
transform_elements = root.findall( |
| 854 |
"ds:Signature/ds:SignedInfo/ds:Reference/ds:Transforms/ds:Transform", namespaces=namespaces |
| 855 |
) |
| 856 |
transform_algorithms = [el.attrib["Algorithm"] for el in transform_elements] |
| 857 |
self.assertEqual(len(transform_elements), 1) |
| 858 |
self.assertIn("http://www.w3.org/2000/09/xmldsig#enveloped-signature", transform_algorithms) |
| 859 |
self.assertNotIn("http://www.w3.org/2006/12/xml-c14n11", transform_algorithms) |
| 860 |
|
| 861 |
def test_verify_config(self): |
| 862 |
data = etree.parse(self.example_xml_files[0]).getroot() |
| 863 |
cert, key = self.load_example_keys() |
| 864 |
signer = XMLSigner() |
| 865 |
signed = signer.sign(data, cert=cert, key=key) |
| 866 |
verifier = XMLVerifier() |
| 867 |
verifier.verify(signed, x509_cert=cert) |
| 868 |
config = SignatureConfiguration(location="./foo/bar/") |
| 869 |
with self.assertRaisesRegex(InvalidInput, "Expected to find XML element Signature in data"): |
| 870 |
verifier.verify(signed, x509_cert=cert, expect_config=config) |
| 871 |
config = SignatureConfiguration(signature_methods=[]) |
| 872 |
with self.assertRaisesRegex(InvalidInput, "Signature method RSA_SHA256 forbidden by configuration"): |
| 873 |
verifier.verify(signed, x509_cert=cert, expect_config=config) |
| 874 |
config = SignatureConfiguration(digest_algorithms=[DigestAlgorithm.SHA3_512]) |
| 875 |
with self.assertRaisesRegex(InvalidInput, "Digest algorithm SHA256 forbidden by configuration"): |
| 876 |
verifier.verify(signed, x509_cert=cert, expect_config=config) |
| 877 |
config = SignatureConfiguration(digest_algorithms=[]) |
| 878 |
with self.assertRaisesRegex(InvalidInput, "Digest algorithm SHA256 forbidden by configuration"): |
| 879 |
verifier.verify(signed, x509_cert=cert, expect_config=config) |
| 880 |
|
| 881 |
def test_sha1_policy(self): |
| 882 |
data = etree.parse(self.example_xml_files[0]).getroot() |
| 883 |
cert, key = self.load_example_keys() |
| 884 |
with self.assertRaisesRegex(InvalidInput, "SHA1-based algorithms are not supported"): |
| 885 |
XMLSigner(signature_algorithm=SignatureMethod.RSA_SHA1) |
| 886 |
signer = XMLSignerWithSHA1(signature_algorithm=SignatureMethod.RSA_SHA1, digest_algorithm=DigestAlgorithm.SHA1) |
| 887 |
signed = signer.sign(data, cert=cert, key=key) |
| 888 |
verifier = XMLVerifier() |
| 889 |
with self.assertRaisesRegex(InvalidInput, "Signature method RSA_SHA1 forbidden by configuration"): |
| 890 |
verifier.verify(signed, x509_cert=cert) |
| 891 |
verifier.verify(signed, x509_cert=cert, expect_config=sha1_ok) |
| 892 |
|
| 893 |
|
| 894 |
class TestXAdES(unittest.TestCase, LoadExampleKeys): |
| 895 |
expect_references = { |
| 896 |
"factura_ejemplo2_32v1.xml": 3, |
| 897 |
"dss1770.xml": 3, |
| 898 |
"xades-fake-counter-signature.xml": 3, |
| 899 |
"Signature-X-SK_DIT-1.xml": 5, |
| 900 |
"Signature-X-HR_FIN-1.xml": 5, |
| 901 |
"TEST_S1a_C1a_InTL_VALID.xml": 3, |
| 902 |
"Signature-X-CZ_SEF-4.xml": 4, |
| 903 |
"Signature-X-FR_NOT-3.xml": 3, |
| 904 |
"Signature-X-CZ_SEF-5.xml": 4, |
| 905 |
"xades-counter-signature-injected.xml": 3, |
| 906 |
"11068_signed.xml": 3, |
| 907 |
"signature_property_signed.xml": 3, |
| 908 |
"nonconformant-Signature-X-ES-100.xml": 3, |
| 909 |
"nonconformant-Signature-X-ES-103.xml": 3, |
| 910 |
"nonconformant-dss1770.xml": 3, |
| 911 |
} |
| 912 |
signature_policy = XAdESSignaturePolicy( |
| 913 |
Identifier="urn:sbr:signature-policy:xml:2.0", |
| 914 |
Description="Test description", |
| 915 |
DigestMethod=DigestAlgorithm.SHA256, |
| 916 |
DigestValue="sVHhN1eqNH/PZ1B6h//ehyC1OwRQOrz/tJ3ZYaRrBgA=", |
| 917 |
) |
| 918 |
claimed_roles = ["signer"] |
| 919 |
data_object_format = XAdESDataObjectFormat(Description="Important Document", MimeType="text/xml") |
| 920 |
|
| 921 |
def test_xades_roundtrip(self): |
| 922 |
cert, key = self.load_example_keys() |
| 923 |
with open(os.path.join(os.path.dirname(__file__), "example.xml"), "rb") as fh: |
| 924 |
doc = etree.parse(fh) |
| 925 |
signer = XAdESSigner( |
| 926 |
signature_policy=self.signature_policy, |
| 927 |
claimed_roles=self.claimed_roles, |
| 928 |
data_object_format=self.data_object_format, |
| 929 |
) |
| 930 |
signed_doc = signer.sign(doc, key=key, cert=cert) |
| 931 |
|
| 932 |
for ref in signed_doc.findall(".//{http://www.w3.org/2000/09/xmldsig#}Reference"): |
| 933 |
if "SignedProperties" in ref.get("URI"): |
| 934 |
self.assertEqual(ref.get("Type"), "http://uri.etsi.org/01903#SignedProperties") |
| 935 |
|
| 936 |
verifier = XAdESVerifier() |
| 937 |
verify_results = verifier.verify( |
| 938 |
signed_doc, x509_cert=cert, expect_references=3, expect_signature_policy=self.signature_policy |
| 939 |
) |
| 940 |
self.assertIsInstance(verify_results[1], XAdESVerifyResult) |
| 941 |
self.assertTrue(hasattr(verify_results[1], "signed_properties")) |
| 942 |
|
| 943 |
def test_xades_interop_examples(self): |
| 944 |
error_conditions = { |
| 945 |
"altered": InvalidSignature, |
| 946 |
"newlines": InvalidSignature, |
| 947 |
"unsupported-signature-algorithm": InvalidInput, |
| 948 |
"corrupted-cert": etree.DocumentInvalid, # FIXME - flaky validation |
| 949 |
"cert-v2-wrong-digest": InvalidDigest, |
| 950 |
"wrong-sign-cert-digest": InvalidDigest, |
| 951 |
"nonconformant-X_BE_CONN_10": InvalidDigest, |
| 952 |
"sigPolStore-noDigest": InvalidInput, |
| 953 |
} |
| 954 |
for sig_file in glob(os.path.join(os.path.dirname(__file__), "xades", "*.xml")): |
| 955 |
print("Verifying", sig_file) |
| 956 |
with open(sig_file, "rb") as fh: |
| 957 |
doc = etree.parse(fh) |
| 958 |
cert = doc.find(".//{http://www.w3.org/2000/09/xmldsig#}X509Certificate").text |
| 959 |
kwargs = dict( |
| 960 |
x509_cert=cert, |
| 961 |
expect_references=self.expect_references.get(os.path.basename(sig_file), 2), |
| 962 |
expect_config=xades_sha1_ok, |
| 963 |
) |
| 964 |
if "nonconformant" in sig_file: |
| 965 |
kwargs.update(validate_schema=False) |
| 966 |
if "sigPolStore" in sig_file: |
| 967 |
kwargs.update(expect_signature_policy=self.signature_policy) |
| 968 |
for condition, error in error_conditions.items(): |
| 969 |
if condition in sig_file: |
| 970 |
with self.assertRaises(error): |
| 971 |
XAdESVerifier().verify(doc, **kwargs) |
| 972 |
break |
| 973 |
else: |
| 974 |
XAdESVerifier().verify(doc, **kwargs) |
| 975 |
|
| 976 |
|
| 977 |
if __name__ == "__main__": |
| 978 |
unittest.main() |