Skip to content

Commit abc546a

Browse files
authored
Merge pull request #351 from theseal/jocar-multiple-certs-attempt-2
Support multiple certificates for key rollover
2 parents 18854ce + 22d8e68 commit abc546a

9 files changed

Lines changed: 181 additions & 44 deletions

File tree

‎README.rst‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,7 @@ Features
4141
Dependencies
4242
============
4343

44-
* pybergshamra >= 0.11.0 (XML signatures and PKCS#11 support)
44+
* pybergshamra >= 0.11.1 (XML signatures and PKCS#11 support)
4545
* pyuppsala >= 0.11.0 (XML processing)
4646
* pygments
4747
* gunicorn (for the standalone pyffd server)

‎docs/index.rst‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ SAML metadata.
1313
size including edugain.org.
1414

1515
**pyFF** supports producing and validating digital signatures on SAML metadata using
16-
the pybergshamra package (0.11.0 or newer), which supports PKCS#11 and other mechanisms for
16+
the pybergshamra package (0.11.1 or newer), which supports PKCS#11 and other mechanisms for
1717
talking to HSMs and other cryptographic hardware.
1818

1919
**pyFF** is also a complete implementation of the SAML metadata query protocol as

‎pyproject.toml‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ dependencies = [
2727
"pyramid>=2.1",
2828
"pytz>=2025.2",
2929
"pyuppsala>=0.13.0",
30-
"pybergshamra>=0.11.0",
30+
"pybergshamra>=0.11.1",
3131
"pyyaml>=3.10",
3232
"redis>=5.3.0",
3333
"redis-collections>=0.13.0",

‎src/pyff/builtins.py‎

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -693,7 +693,8 @@ def load(req: Plumbing.Request, *opts):
693693
- ``as``: name the resource, e.g. to refer to it in later pipeline steps.
694694
- ``verify``: check the XML signature of the resource, using either a PEM certificate file or a SHA-1
695695
fingerprint of the signing certificate. With a fingerprint, the certificate embedded in the signature is
696-
used and the fingerprint pins it.
696+
used and the fingerprint pins it. ``verify`` may be repeated to support key rollovers; a signature by any
697+
one of the given certificates (or fingerprints) is accepted. Certificates and fingerprints cannot be mixed.
697698
- ``via``: name of a ``when`` clause in the same pipeline that is applied to the loaded metadata, for
698699
example to remove entities with ``fork merge remove``.
699700
- ``cleanup``: name of a ``when`` clause used to pre-process the parsed metadata before it is validated.
@@ -718,7 +719,7 @@ def load(req: Plumbing.Request, *opts):
718719
log.debug(f"load parsing '{stripped}'")
719720
r = stripped.split()
720721

721-
assert len(r) in range(1, 8), PipeException(
722+
assert len(r) in range(1, 12), PipeException(
722723
"Usage: load resource [as url] [[verify] verification] [via pipeline] [cleanup pipeline]"
723724
)
724725

@@ -736,7 +737,7 @@ def load(req: Plumbing.Request, *opts):
736737
if elt == "as":
737738
child_opts.alias = value
738739
elif elt == "verify":
739-
child_opts.verify = value
740+
child_opts.verify = [*(child_opts.verify or []), value]
740741
elif elt == "via":
741742
child_opts.via.append(PipelineCallback(value, req, store=req.md.store))
742743
elif elt == "cleanup":
@@ -748,7 +749,7 @@ def load(req: Plumbing.Request, *opts):
748749
"Usage: load resource [as url] [[verify] verification] [via pipeline]* [cleanup pipeline]*"
749750
)
750751
else:
751-
child_opts.verify = elt
752+
child_opts.verify = [*(child_opts.verify or []), elt]
752753

753754
# override anything in child_opts with what is in opts
754755
child_opts = child_opts.model_copy(update=_opts)

‎src/pyff/resource.py‎

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@
1818
from urllib.parse import quote as urlescape
1919

2020
import requests
21-
from pydantic import BaseModel, ConfigDict, Field
21+
from pydantic import BaseModel, ConfigDict, Field, field_validator
2222
from pyuppsala.etree import ElementTree
2323
from requests.adapters import Response
2424

@@ -204,8 +204,9 @@ def text(self):
204204

205205
class ResourceOpts(BaseModel):
206206
alias: str | None = Field(None, alias='as') # TODO: Rename to 'name'?
207-
# a certificate (file) or a SHA1 fingerprint to use for signature verification
208-
verify: str | None = None
207+
# certificates (file or PEM text) or SHA1 fingerprints to use for signature verification; a signature by any
208+
# one of them is accepted, which allows key rollovers
209+
verify: list[str] | None = None
209210
# TODO: move classes to make the correct typing work: Iterable[Union[Lambda, PipelineCallback]] = Field([])
210211
via: list[Callable] = Field([])
211212
# A list of callbacks that can be used to pre-process parsed metadata before validation. Use as a clue-bat.
@@ -219,6 +220,11 @@ class ResourceOpts(BaseModel):
219220
verify_tls: bool = False
220221
model_config = ConfigDict(arbitrary_types_allowed=True)
221222

223+
@field_validator('verify', mode='before')
224+
@classmethod
225+
def _wrap_single_verify(cls, value):
226+
return [value] if isinstance(value, str) else value
227+
222228
def to_dict(self) -> dict[str, Any]:
223229
res = self.model_dump()
224230
# Compensate for the 'alias' field options

‎src/pyff/samlmd.py‎

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@
2020
from pyff.utils import (
2121
Lambda,
2222
b2u,
23+
b64_to_pem,
2324
cert_dict,
2425
check_signature,
2526
collect_attr,
@@ -112,7 +113,7 @@ def parse_saml_metadata(
112113

113114
expire_time_offset = metadata_expiration(t)
114115

115-
t = check_signature(t, opts.verify)
116+
t = check_signature(t, opts.verify, source=base_url)
116117

117118
trust_info = None
118119
extensions = t.find('{{{}}}Extensions'.format(NS['md']))
@@ -305,23 +306,22 @@ def parse(self, resource: Resource, content: str) -> EidasMDParserInfo:
305306
if location:
306307
certs = cert_dict(ml)
307308
fingerprints = list(certs.keys())
308-
fp = None
309-
if len(fingerprints) > 0:
310-
fp = fingerprints[0]
311309

312310
ep = ml.find("{{{}}}Endpoint".format(NS['ser']))
313-
if ep is not None and fp is not None:
311+
if ep is not None and fingerprints:
314312
args = dict(
315313
country_code=mdl.get('Territory'),
316314
hide_from_discovery=str2bool(ep.get('HideFromDiscovery', 'false')),
317315
)
318316
log.debug(
319317
"MDSL[{}]: {} verified by {} for country {}".format(
320-
info.scheme_territory, location, fp, args.get('country_code')
318+
info.scheme_territory, location, ', '.join(fingerprints), args.get('country_code')
321319
)
322320
)
323321
child_opts = resource.opts.model_copy(update={'alias': None}, deep=True)
324-
child_opts.verify = fp
322+
# The listed certificates are the trusted signers; all of them are accepted so that a
323+
# key rollover can list both the old and the new certificate.
324+
child_opts.verify = [b64_to_pem(cert_b64) for cert_b64 in certs.values()]
325325
r = resource.add_child(location, child_opts)
326326

327327
# this is specific post-processing for MDSL files

‎src/pyff/test/test_pipeline.py‎

Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -770,6 +770,85 @@ def test_read_xml_rejects_bad_arguments(self):
770770
with pytest.raises(OSError):
771771
self.exec_pipeline("- read_xml:\n file: /nonexistent.xml\n")
772772

773+
def test_verify_with_multiple_certificates_and_fingerprints(self):
774+
"""A key rollover lists several signers; any one of them must verify."""
775+
import datetime
776+
import hashlib
777+
778+
from cryptography import x509
779+
from cryptography.hazmat.primitives import hashes, serialization
780+
from cryptography.hazmat.primitives.asymmetric import rsa
781+
from cryptography.x509.oid import NameOID
782+
783+
from pyff.constants import NS
784+
from pyff.exceptions import MetadataException
785+
from pyff.utils import check_signature
786+
787+
other_key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
788+
name = x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, 'other')])
789+
now = datetime.datetime.now(datetime.timezone.utc)
790+
other_cert = (
791+
x509.CertificateBuilder()
792+
.subject_name(name)
793+
.issuer_name(name)
794+
.public_key(other_key.public_key())
795+
.serial_number(x509.random_serial_number())
796+
.not_valid_before(now)
797+
.not_valid_after(now + datetime.timedelta(days=2))
798+
.sign(other_key, hashes.SHA256())
799+
)
800+
801+
with open(self.public_keyspec, 'rb') as fd:
802+
signer_cert = x509.load_pem_x509_certificate(fd.read())
803+
804+
def fingerprint(cert):
805+
return hashlib.sha1(cert.public_bytes(serialization.Encoding.DER)).hexdigest()
806+
807+
tmpdir = tempfile.mkdtemp()
808+
try:
809+
src = os.path.join(tmpdir, 'mdsl.xml')
810+
other_pem = os.path.join(tmpdir, 'other.pem')
811+
with open(src, 'w') as fd:
812+
fd.write(
813+
f'<ser:MetadataServiceList xmlns:ser="{NS["ser"]}" Version="1">'
814+
'<ser:IssuerName>Test</ser:IssuerName></ser:MetadataServiceList>'
815+
)
816+
with open(other_pem, 'wb') as fd:
817+
fd.write(other_cert.public_bytes(serialization.Encoding.PEM))
818+
res, _md = self.exec_pipeline(
819+
f"""
820+
- read_xml:
821+
file: {src}
822+
- sign:
823+
key: {self.private_keyspec}
824+
cert: {self.public_keyspec}
825+
"""
826+
)
827+
828+
t = root(res)
829+
other_pem_text = other_cert.public_bytes(serialization.Encoding.PEM).decode()
830+
signer_pem_text = signer_cert.public_bytes(serialization.Encoding.PEM).decode()
831+
for keys in (
832+
[other_pem, self.public_keyspec],
833+
[self.public_keyspec, other_pem],
834+
[other_pem_text, signer_pem_text],
835+
[signer_pem_text, other_pem_text],
836+
[fingerprint(other_cert), fingerprint(signer_cert)],
837+
[fingerprint(signer_cert), fingerprint(other_cert)],
838+
):
839+
check_signature(t, keys, only_one_signature=True)
840+
841+
with pytest.raises(MetadataException):
842+
check_signature(t, other_pem)
843+
with pytest.raises(MetadataException):
844+
check_signature(t, [other_pem_text])
845+
with pytest.raises(MetadataException, match="does not match"):
846+
check_signature(t, fingerprint(other_cert))
847+
with pytest.raises(MetadataException, match="cannot be mixed"):
848+
check_signature(t, [other_pem, fingerprint(signer_cert)])
849+
finally:
850+
shutil.rmtree(tmpdir)
851+
773852
def test_signing_and_validation(self):
774853
self.output = tempfile.NamedTemporaryFile('w').name
775854
_res_s, _md_s, _ctx_s = self.run_pipeline("signer.fd", self)

‎src/pyff/utils.py‎

Lines changed: 74 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@
1717
import time
1818
import traceback
1919
from _collections_abc import Mapping, MutableMapping
20-
from collections.abc import Sequence
20+
from collections.abc import Iterable, Sequence
2121
from copy import copy
2222
from datetime import datetime, timedelta, timezone
2323
from email.utils import parsedate
@@ -271,6 +271,9 @@ def redis():
271271
return thread_data.redis
272272

273273

274+
PEM_CERT_PREFIX = '-----BEGIN CERTIFICATE-----'
275+
276+
274277
def _looks_like_sha1_fingerprint(key: str) -> bool:
275278
"""Return True if ``key`` looks like a SHA1 certificate fingerprint.
276279
@@ -283,39 +286,71 @@ def _looks_like_sha1_fingerprint(key: str) -> bool:
283286
return len(candidate) == 40 and all(c in '0123456789abcdefABCDEF' for c in candidate)
284287

285288

286-
def check_signature(t: ElementTree, key: Optional[str], only_one_signature: bool = False) -> ElementTree:
289+
def check_signature(
290+
t: ElementTree,
291+
key: Optional[Union[str, Iterable[str]]],
292+
only_one_signature: bool = False,
293+
source: Optional[str] = None,
294+
) -> ElementTree:
287295
"""Verify the XML signature on ``t`` using pybergshamra.
288296
289-
``key`` is either the path to a PEM-encoded X.509 certificate (the trusted
290-
signer) or a SHA1 fingerprint of the expected signing certificate. When a
291-
fingerprint is supplied the certificate embedded in the signature's KeyInfo
292-
is used to verify, and the fingerprint is checked against it afterwards.
297+
``key`` is one verifier or an iterable of them, which allows key rollovers:
298+
the signature is accepted if it was made by any one of them. A verifier is
299+
either a path to a PEM-encoded X.509 certificate file, the PEM text of a
300+
certificate, or a SHA1 fingerprint of the expected signing certificate.
301+
Fingerprints cannot be mixed with certificates.
302+
303+
Certificates are the trusted signing keys. When fingerprints are supplied
304+
the certificate embedded in the signature's KeyInfo is used to verify, and
305+
the fingerprint is checked against it afterwards.
306+
307+
``source`` (typically the URL) is only used to identify the signed document in log messages.
293308
"""
294309
if key is None:
295310
return t
296311

297-
log.debug(f"verifying signature using {key}")
312+
of_source = f" of {source}" if source else ""
313+
314+
items = [key] if isinstance(key, str) else list(key)
315+
items = [item.strip() for item in items if item.strip()]
316+
if not items:
317+
raise MetadataException("No certificate or fingerprint given to verify the signature")
318+
319+
log.debug(f"verifying signature{of_source} using {len(items)} verifier(s)")
298320

299321
mgr = pybergshamra.KeysManager()
300322
ctx = pybergshamra.DsigContext(mgr)
301323

302-
pinned_fingerprint = None
303-
if _looks_like_sha1_fingerprint(key) and not os.path.exists(key):
324+
is_fingerprint = [
325+
not item.startswith(PEM_CERT_PREFIX) and _looks_like_sha1_fingerprint(item) and not os.path.exists(item)
326+
for item in items
327+
]
328+
if any(is_fingerprint) and not all(is_fingerprint):
329+
raise MetadataException("Certificates and fingerprints cannot be mixed in a single verification")
330+
331+
pinned_fingerprints: set[str] = set()
332+
if all(is_fingerprint):
304333
# Fingerprint pinning: trust the cert carried inside the signature's
305-
# KeyInfo/X509Data, then compare its SHA1 to the pinned fingerprint.
334+
# KeyInfo/X509Data, then compare its SHA1 to the pinned fingerprints.
306335
# The fingerprint is the trust anchor here, so PKI chain validation is
307336
# disabled (insecure) - the embedded signing cert is typically
308337
# self-signed and would otherwise fail to chain to a trusted root.
309-
pinned_fingerprint = key.replace(':', '').replace(' ', '').strip().lower()
338+
pinned_fingerprints = {item.replace(':', '').replace(' ', '').lower() for item in items}
310339
ctx.enabled_key_data_x509 = True
311340
ctx.trusted_keys_only = False
312341
ctx.insecure = True
313342
else:
314-
# Trusted-cert path: load the PEM certificate and require it as the
315-
# only acceptable signing key (skip inline KeyInfo extraction).
316-
with open(key, 'rb') as fd:
317-
cert_key = pybergshamra.load_x509_cert_pem(fd.read())
318-
mgr.add_key(cert_key)
343+
# Trusted-cert path: load the PEM certificates and require them as the
344+
# only acceptable signing keys (skip inline KeyInfo extraction).
345+
cert_keys = []
346+
for item in items:
347+
if item.startswith(PEM_CERT_PREFIX):
348+
pem = item.encode()
349+
else:
350+
with open(item, 'rb') as fd:
351+
pem = fd.read()
352+
cert_keys.append(pybergshamra.load_x509_cert_pem(pem))
353+
mgr.add_keys(cert_keys)
319354
ctx.trusted_keys_only = True
320355

321356
relt = root(t)
@@ -340,16 +375,25 @@ def check_signature(t: ElementTree, key: Optional[str], only_one_signature: bool
340375
"XML metadata contains %d signatures - exactly 1 is required" % len(references)
341376
)
342377

343-
if pinned_fingerprint is not None:
378+
# The leaf certificate that verified the signature: the matching trusted key
379+
# in certificate mode, the one embedded in KeyInfo in fingerprint mode.
380+
chain = result.key_info.x509_chain if result.key_info is not None else []
381+
actual_fingerprint = hashlib.sha1(chain[0]).hexdigest().lower() if chain else None
382+
if actual_fingerprint is not None:
383+
log.debug(
384+
f"signature{of_source} verified by certificate "
385+
+ ":".join(actual_fingerprint[i : i + 2] for i in range(0, len(actual_fingerprint), 2))
386+
)
387+
388+
if pinned_fingerprints:
344389
# Confirm the certificate that actually verified the signature matches
345-
# the pinned fingerprint (SHA1 over the DER-encoded leaf certificate).
346-
chain = result.key_info.x509_chain if result.key_info is not None else []
347-
if not chain:
390+
# one of the pinned fingerprints (SHA1 over the DER-encoded leaf certificate).
391+
if actual_fingerprint is None:
348392
raise MetadataException("No certificate found in signature to match fingerprint")
349-
actual_fingerprint = hashlib.sha1(chain[0]).hexdigest().lower()
350-
if actual_fingerprint != pinned_fingerprint:
393+
if actual_fingerprint not in pinned_fingerprints:
351394
raise MetadataException(
352-
f"Signing certificate fingerprint {actual_fingerprint} does not match expected {pinned_fingerprint}"
395+
f"Signing certificate fingerprint {actual_fingerprint} does not match expected "
396+
f"{', '.join(sorted(pinned_fingerprints))}"
353397
)
354398

355399
# Anti-wrapping: the old code returned the verified reference subtree as the
@@ -396,6 +440,13 @@ def cert_dict(t):
396440
return certs
397441

398442

443+
def b64_to_pem(cert_b64: str) -> str:
444+
"""Wrap the base64 text of a DER certificate (as found in ``X509Certificate``) as PEM."""
445+
body = "".join(cert_b64.split())
446+
lines = [body[i : i + 64] for i in range(0, len(body), 64)]
447+
return "\n".join([PEM_CERT_PREFIX, *lines, "-----END CERTIFICATE-----", ""])
448+
449+
399450
class CertInfo:
400451
"""Lightweight wrapper around a parsed X.509 certificate.
401452

0 commit comments

Comments
 (0)