evidence_seal/timestamp.py

0daec5b5c087a3caf5ef9718fdcf3f4eb70f070b
evidence-seal/evidence_seal/timestamp.py history · blame · raw

348 lines · 13179 bytes

17 symbols in this file
  1"""Optional RFC 3161 trusted timestamping of manifests.
  2
  3A signature proves *who* sealed the evidence; a timestamp proves the seal
  4existed *by* a certain time — attested by an independent Time-Stamp Authority
  5(TSA), not by the sealer's own clock. The TSA timestamps the manifest's ``id``
  6(itself the hash of every file and all metadata), so one token vouches for the
  7whole package at a point in time.
  8
  9This module builds RFC 3161 requests, submits them to a TSA, and binds the
 10returned token into the manifest. It needs the ``asn1crypto`` package (install
 11``evidence-seal[timestamp]``); the core seal/verify path never imports it.
 12
 13The bound token is stored under a ``timestamp`` key, which — like ``signature``
 14— is excluded from the manifest id, so timestamping never invalidates the id or
 15an existing signature.
 16"""
 17
 18from __future__ import annotations
 19
 20import base64
 21import secrets
 22import urllib.parse
 23import urllib.request
 24from datetime import timezone
 25from pathlib import Path
 26
 27_TSA_CONTENT_TYPE = "application/timestamp-query"
 28_TSA_ACCEPT = "application/timestamp-reply"
 29
 30
 31def _require_asn1():
 32    try:
 33        from asn1crypto import algos, cms, core, tsp
 34    except ImportError as exc:  # pragma: no cover - exercised via a clear message
 35        raise RuntimeError(
 36            "timestamping requires the 'asn1crypto' package — "
 37            "install evidence-seal[timestamp]"
 38        ) from exc
 39    return algos, cms, core, tsp
 40
 41
 42def _require_crypto():
 43    try:
 44        import cryptography  # noqa: F401
 45    except ImportError as exc:  # pragma: no cover - exercised via a clear message
 46        raise RuntimeError(
 47            "verifying a TSA signature requires the 'cryptography' package — "
 48            "install evidence-seal[sign,timestamp]"
 49        ) from exc
 50
 51
 52def build_request(manifest_id_hex: str, cert_req: bool = True) -> bytes:
 53    """Return a DER-encoded RFC 3161 TimeStampReq over a manifest id.
 54
 55    The message imprint is the manifest id (a SHA-256 digest) carried directly
 56    as the hashed message, so the TSA timestamps exactly what the id commits to.
 57    """
 58    algos, _cms, core, tsp = _require_asn1()
 59    request = tsp.TimeStampReq(
 60        {
 61            "version": 1,
 62            "message_imprint": tsp.MessageImprint(
 63                {
 64                    "hash_algorithm": algos.DigestAlgorithm({"algorithm": "sha256"}),
 65                    "hashed_message": bytes.fromhex(manifest_id_hex),
 66                }
 67            ),
 68            "nonce": core.Integer(secrets.randbits(64)),
 69            "cert_req": cert_req,
 70        }
 71    )
 72    return request.dump()
 73
 74
 75def submit(request_der: bytes, tsa_url: str, timeout: float = 30.0) -> bytes:
 76    """POST a TimeStampReq to a TSA and return the raw TimeStampResp bytes.
 77
 78    Network call — the caller is responsible for choosing a trusted TSA URL.
 79    """
 80    scheme = urllib.parse.urlsplit(tsa_url).scheme.lower()
 81    if scheme not in ("http", "https"):
 82        raise ValueError(f"TSA URL must use http or https: {tsa_url}")
 83    req = urllib.request.Request(
 84        tsa_url,
 85        data=request_der,
 86        headers={"Content-Type": _TSA_CONTENT_TYPE, "Accept": _TSA_ACCEPT},
 87        method="POST",
 88    )
 89    with urllib.request.urlopen(req, timeout=timeout) as response:
 90        return response.read()
 91
 92
 93def _extract(token_or_response_der: bytes):
 94    """Return ``(token_contentinfo, tst_info)`` from a token or a TimeStampResp.
 95
 96    Accepts either a bare RFC 3161 token (a CMS ContentInfo) or a full
 97    TimeStampResp (what a TSA returns and a ``.tsr`` file holds).
 98    """
 99    _algos, cms, _core, tsp = _require_asn1()
100
101    def _tst_of(content_info):
102        return content_info["content"]["encap_content_info"]["content"].parsed
103
104    # Try a full response first; fall back to a bare token.
105    try:
106        response = tsp.TimeStampResp.load(token_or_response_der)
107        status = response["status"]["status"].native
108        token = response["time_stamp_token"]
109        tst = _tst_of(token)  # forces a parse; raises if this was not a response
110    except Exception:
111        token = cms.ContentInfo.load(token_or_response_der)
112        return token, _tst_of(token), None
113    return token, tst, status
114
115
116def parse_token(token_or_response_der: bytes) -> dict:
117    """Extract the human-facing fields from a timestamp token."""
118    _token, tst, _status = _extract(token_or_response_der)
119    gen_time = tst["gen_time"].native.astimezone(timezone.utc)
120    tsa = None
121    if tst["tsa"].native is not None:
122        tsa = str(tst["tsa"].native)
123    return {
124        "imprint": tst["message_imprint"]["hashed_message"].native.hex(),
125        "imprint_algorithm": tst["message_imprint"]["hash_algorithm"]["algorithm"].native,
126        "gen_time": gen_time.strftime("%Y-%m-%dT%H:%M:%SZ"),
127        "serial_number": str(tst["serial_number"].native),
128        "tsa": tsa,
129    }
130
131
132def apply_timestamp(manifest: dict, token_or_response_der: bytes) -> dict:
133    """Bind a TSA token into *manifest* after checking it timestamps its id.
134
135    Raises ``ValueError`` if the token's message imprint does not equal the
136    manifest id — a token for anything else must never be attached.
137    """
138    token, _tst, _status = _extract(token_or_response_der)
139    fields = parse_token(token_or_response_der)
140
141    if fields["imprint_algorithm"] != "sha256" or fields["imprint"] != manifest.get("id"):
142        raise ValueError("token does not timestamp this manifest's id")
143
144    stamped = dict(manifest)
145    stamped["timestamp"] = {
146        "format": "rfc3161",
147        "imprint_algorithm": fields["imprint_algorithm"],
148        "imprint": fields["imprint"],
149        "gen_time": fields["gen_time"],
150        "serial_number": fields["serial_number"],
151        "tsa": fields["tsa"],
152        "token": base64.b64encode(token.dump()).decode(),
153    }
154    return stamped
155
156
157def verify_timestamp(manifest: dict, tsa_cert: bytes | None = None) -> tuple[bool, str]:
158    """Verify a manifest's embedded timestamp.
159
160    Returns ``(ok, message)``. Always checks that the stored token timestamps the
161    current manifest id. When *tsa_cert* (PEM or DER bytes) is given, the token's
162    RFC 3161 CMS signature is also verified against that certificate — proving
163    the timestamp really was issued by that authority.
164    """
165    block = manifest.get("timestamp")
166    if not block:
167        return False, "manifest is not timestamped"
168    if block.get("format") != "rfc3161":
169        return False, f"unsupported timestamp format: {block.get('format')}"
170
171    try:
172        token_der = base64.b64decode(block["token"])
173        fields = parse_token(token_der)
174    except Exception as exc:
175        return False, f"timestamp token is unreadable: {exc}"
176
177    if fields["imprint_algorithm"] != "sha256" or fields["imprint"] != manifest.get("id"):
178        return False, "timestamp does not match the manifest id"
179
180    tsa = f" by {fields['tsa']}" if fields["tsa"] else ""
181    bound = f"timestamped at {fields['gen_time']}{tsa}"
182
183    if tsa_cert is None:
184        return True, bound
185
186    sig_ok, sig_message = verify_token_signature(token_der, tsa_cert)
187    return sig_ok, f"{bound}; {sig_message}"
188
189
190# --------------------------------------------------------------------------- #
191# Full RFC 3161 CMS signature verification
192# --------------------------------------------------------------------------- #
193
194# asn1crypto hash names -> cryptography hash classes for the algorithms a TSA
195# realistically signs with.
196_HASHES = {
197    "sha1": "SHA1",
198    "sha224": "SHA224",
199    "sha256": "SHA256",
200    "sha384": "SHA384",
201    "sha512": "SHA512",
202}
203
204
205def _load_certificate(cert_bytes: bytes):
206    from cryptography import x509
207
208    try:
209        return x509.load_pem_x509_certificate(cert_bytes)
210    except ValueError:
211        return x509.load_der_x509_certificate(cert_bytes)
212
213
214def _hash_instance(name: str):
215    from cryptography.hazmat.primitives import hashes
216
217    if name not in _HASHES:
218        raise ValueError(f"unsupported digest algorithm: {name}")
219    return getattr(hashes, _HASHES[name])()
220
221
222def _verify_raw(public_key, signature: bytes, data: bytes, sig_algo: str, hash_name: str) -> None:
223    """Verify *signature* over *data*, raising on any failure."""
224    from cryptography.hazmat.primitives.asymmetric import ec, padding
225
226    if sig_algo == "rsassa_pkcs1v15":
227        public_key.verify(signature, data, padding.PKCS1v15(), _hash_instance(hash_name))
228    elif sig_algo == "rsassa_pss":
229        digest = _hash_instance(hash_name)
230        public_key.verify(
231            signature,
232            data,
233            padding.PSS(mgf=padding.MGF1(digest), salt_length=padding.PSS.DIGEST_LENGTH),
234            digest,
235        )
236    elif sig_algo == "ecdsa":
237        public_key.verify(signature, data, ec.ECDSA(_hash_instance(hash_name)))
238    elif sig_algo in ("ed25519", "ed448"):
239        public_key.verify(signature, data)
240    else:
241        raise ValueError(f"unsupported signature algorithm: {sig_algo}")
242
243
244def _signer_matches_cert(signer_info, cert) -> bool:
245    """True if the SignerInfo identifies the supplied certificate."""
246    sid = signer_info["sid"]
247    if sid.name == "issuer_and_serial_number":
248        return sid.chosen["serial_number"].native == cert.serial_number
249    # subject_key_identifier: compare against the cert's SKI extension.
250    from cryptography import x509
251
252    try:
253        ski = cert.extensions.get_extension_for_class(x509.SubjectKeyIdentifier).value
254    except x509.ExtensionNotFound:
255        return False
256    return sid.chosen.native == ski.digest
257
258
259def _has_timestamping_eku(cert) -> bool:
260    from cryptography import x509
261    from cryptography.x509.oid import ExtendedKeyUsageOID
262
263    try:
264        eku = cert.extensions.get_extension_for_class(x509.ExtendedKeyUsage).value
265    except x509.ExtensionNotFound:
266        return False
267    return ExtendedKeyUsageOID.TIME_STAMPING in eku
268
269
270def _signed_attr(signed_attrs, attr_type):
271    for attr in signed_attrs:
272        if attr["type"].native == attr_type:
273            return attr["values"][0].native
274    return None
275
276
277def verify_token_signature(token_or_response_der: bytes, cert_bytes: bytes) -> tuple[bool, str]:
278    """Verify a token's CMS signature against a TSA certificate.
279
280    Checks, in order: the certificate carries the timeStamping extended key
281    usage; it identifies the token's signer; ``gen_time`` falls within its
282    validity window; the signed message digest matches the timestamped content;
283    and the signature verifies. Returns ``(ok, message)``.
284
285    This authenticates the token against the certificate you supply. Establishing
286    that the certificate itself is trusted (chain to a known root) is left to the
287    caller — supply a TSA certificate you already trust.
288    """
289    import hashlib
290
291    _require_asn1()
292    _require_crypto()
293
294    try:
295        token, tst, _status = _extract(token_or_response_der)
296        signed_data = token["content"]
297        signer_info = signed_data["signer_infos"][0]
298    except Exception as exc:
299        return False, f"TSA signature: token is unreadable ({exc})"
300
301    try:
302        cert = _load_certificate(cert_bytes)
303    except ValueError as exc:
304        return False, f"TSA signature: cannot load certificate ({exc})"
305
306    if not _has_timestamping_eku(cert):
307        return False, "TSA signature: certificate lacks the timeStamping extended key usage"
308    if not _signer_matches_cert(signer_info, cert):
309        return False, "TSA signature: certificate does not match the token's signer"
310
311    gen_time = tst["gen_time"].native.astimezone(timezone.utc)
312    if not (cert.not_valid_before_utc <= gen_time <= cert.not_valid_after_utc):
313        return False, "TSA signature: gen_time is outside the certificate validity window"
314
315    econtent = signed_data["encap_content_info"]["content"].parsed.dump()
316    digest_name = signer_info["digest_algorithm"]["algorithm"].native
317    signed_attrs = signer_info["signed_attrs"]
318
319    if signed_attrs.native is not None:
320        recorded = _signed_attr(signed_attrs, "message_digest")
321        if recorded is None or recorded != hashlib.new(digest_name, econtent).digest():
322            return False, "TSA signature: signed message digest does not match the token content"
323        signed_bytes = signed_attrs.untag().dump()
324    else:
325        signed_bytes = econtent
326
327    sig_algo = signer_info["signature_algorithm"].signature_algo
328    # For rsassa_pkcs1v15 the OID carries no hash, and asn1crypto raises rather
329    # than returning None — fall back to the SignerInfo digest algorithm.
330    try:
331        hash_name = signer_info["signature_algorithm"].hash_algo or digest_name
332    except ValueError:
333        hash_name = digest_name
334    try:
335        _verify_raw(
336            cert.public_key(), signer_info["signature"].native, signed_bytes, sig_algo, hash_name
337        )
338    except ValueError as exc:
339        return False, f"TSA signature: {exc}"
340    except Exception as exc:
341        return False, f"TSA signature is INVALID ({type(exc).__name__})"
342
343    return True, f"TSA signature valid ({cert.subject.rfc4514_string()})"
344
345
346def load_der(path: str | Path) -> bytes:
347    """Read a DER file (a ``.tsq`` request or ``.tsr`` response)."""
348    return Path(path).read_bytes()