1717import time
1818import traceback
1919from _collections_abc import Mapping , MutableMapping
20- from collections .abc import Sequence
20+ from collections .abc import Iterable , Sequence
2121from copy import copy
2222from datetime import datetime , timedelta , timezone
2323from 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+
274277def _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+
399450class CertInfo :
400451 """Lightweight wrapper around a parsed X.509 certificate.
401452
0 commit comments