#!/usr/bin/env python3 """ Standalone Counterfoil receipt verifier: the whole point of the receipt. Give this ONE file plus a receipt to anyone. It re-verifies the receipt fully offline, with no secret, no network, and no Matrix CR Studio code, so a buyer or an auditor checks the evidence without trusting the issuer. Only dependency: `cryptography` (pip install cryptography). Everything else is the Python standard library. python verify_counterfoil.py receipt.json # checks it is OURS python verify_counterfoil.py receipt.json --expect-key python verify_counterfoil.py receipt.json --any-key # skip the identity check python verify_counterfoil.py receipt.json --require-pq # also require the post-quantum seal python verify_counterfoil.py receipt.json --require-time # also require trusted time python verify_counterfoil.py receipt.json --expect-boot-state ref.json # TPM boot state must match python verify_counterfoil.py receipt.json --require-hardware # also require a TPM seal of our chip python verify_counterfoil.py evidence.json # an assessment evidence file python verify_counterfoil.py evidence.json --policy mine.json # does it meet YOUR policy python verify_counterfoil.py receipt.json --attest "Your name or org" # after verifying, sign WHAT THIS FILE COMPUTED # with your own key, into attestation.json Exit code 0 = PASS, 1 = FAIL, 2 = bad usage. Checks (all offline): 1. integrity SHA3-256 hash chain recomputes, links, and closes on seed_anchor 2. claim the presented claim hashes to the sealed SEED payload 3. authenticity Ed25519 seal verifies over the terminal record_hash 4. identity the sealing key is the one you expect. By default that is the Matrix CR Studio key, PUBLISHED_PUBLIC_KEY below, compared in full (all 256 bits). A receipt re-signed with any other key is intact and self-consistent, so checks 1 to 3 alone cannot tell it from ours; only this one can. With --any-key the identity is reported as NOT checked (null), never as passed. --expect-key also takes the 16-character fingerprint a receipt prints, but that is only 64 bits of the key's hash: a determined forger could search for another key that shares it. The verdict says which was compared (`identity_basis`). Give the full key when the answer matters. 5. post-quantum when the receipt carries a `pq_seal`, its ML-DSA-65 (FIPS 204) signature over the same terminal record_hash verifies, by the published post-quantum key unless --any-key or --expect-pq-key. It is reported on its own (`pq_authenticity_ok`, null when the receipt has none). A present seal that fails is never a pass. Where the installed cryptography has no ML-DSA (the browser's does not), this file's own FIPS 204 verifier checks it; `pq_verified_by` names which one did. The classical seal does not cover the post-quantum one, so a copy with it removed still passes checks 1 to 4. --require-pq refuses such a copy; use it for any receipt that must still mean something once Ed25519 can be broken. 6. time when the receipt carries a `time_seal`, each RFC 3161 token in it is checked offline: the time-stamping authority's signature, its key being for time-stamping only, a chain of CAs up to a pinned root key (DigiCert Trusted Root G4, the FreeTSA root), and the token covering this receipt's terminal record_hash. Tokens from two authorities must agree to within ten minutes. The receipt then existed no later than `time_bound` if either authority is honest; the issuer's own clock may not claim a later time, but nothing stops it claiming an earlier one. Reported as `time_ok` (null when there is no time seal). The time seal is outside both signatures, so a token can be removed: --require-time refuses a receipt without tokens from two distinct authorities. No revocation check; the tokens are RSA and ECDSA, not post-quantum. 7. TPM seal when the receipt carries a `hardware_seal`: a key created inside a TPM 2.0 chip, which cannot leave it and which the chip lets sign only while PCR 0-7 (the firmware and boot measurements) hold the quoted values, signed the terminal record_hash, and the chip's attestation key quoted those values over the seal's nonce. By default the attestation key must be ours (PUBLISHED_AK_FINGERPRINT below); --expect-ak names another, --expect-nonce the nonce you supplied. Reported as `hardware_authenticity_ok`, each part apart under `hardware`; null, never true, when no TPM identity is compared (--any-key), since a software key could make a self-consistent seal. --require-hardware refuses a receipt without one. The boot state is compared only to a reference you give (--expect-boot-state, a file of the eight PCR values): `boot_state_ok`, null without one, and a mismatch fails. It does not prove the hash is honest, that the boot state was a good one without your reference, anything after boot, or that the chip itself is trustworthy (no EK certificate is checked). A TPM is not a TEE. 8. policy with --policy FILE, YOUR policy, not ours: which Ed25519, post- quantum and TPM identities may sign, which seals every receipt must carry (post_quantum, trusted_time, hardware), which boot states are acceptable, and which steps, in which order, and which engagement an evidence file must have. Every receipt is verified again under the pins the policy implies, and the answer is `policy_ok`. The schema is strict: an unknown field, or a requirement without keys to check it against, is refused (exit 2), so a typo cannot loosen it. Minimal example: {"counterfoil_policy": 1, "issuer_keys": ["<64 hex>"], "pq_keys": ["<64 hex sha3>"], "require": {"post_quantum": true}, "steps": ["inventory", "rank", "plan"]} It proves the evidence meets the policy you wrote, not that the policy is right or that an unrecorded step did not happen. 9. runtime when the receipt carries an `ima_seal`: the TPM's attestation key quoted PCR 0-10 after the record existed, and the IMA log, given as template hashes only (no paths), replays to the quoted PCR 10. Entry 0 must be boot_aggregate, the SHA-256 of the quoted PCR 0-9, so the log belongs to that boot. The one other entry disclosed in full is the IMA policy file, compared to the published policy. The log is the receipt's `ima_log`, the evidence file's, or --ima-log FILE. Reported as `ima_ok`, each part under `ima`; null when the log was not given or no TPM identity was compared. --require-ima refuses a receipt without it. Presence, not absence: nothing undisclosed can be shown absent, and hashes of public files at standard paths are recognisable. The policy entry shows that policy file was measured in that boot, not that it was in force. The kernel keeps the log, and PCR 8-9 (kernel, command line) are reported, not judged. It says nothing about which tool code ran. A PASS does not prove the signer is honest or that the recorded work was right. It proves the record is unchanged since it was sealed, by the key it names. DECLARING A RECOMPUTATION (--attest) Counterfoil's claim is that a receipt's authority comes from being recomputable by anyone, not from the key that signed it. That claim rests on people actually recomputing. We publish how often an outside party has, and the only honest way to count it is if you tell us; this file never phones home, before or after you use --attest. --attest runs the verification first and then signs the verdict THIS FILE computed, with a key that is yours: the verdict is never something you type in, so nobody can declare a recomputation they did not run without signing a false statement with their own key. The verdict keeps each seal's result apart (the signature, the post-quantum seal, trusted time, the TPM seal), null where the receipt has no such seal and no authorities listed for time. The result is written to a file and nothing is sent anywhere. Send it to contact@matrixcr.ai if you want it counted, or publish it yourself and keep us out of it entirely. The hardware seal's result is recorded too, now that this file checks it. """ import base64 import hashlib import json import sys from datetime import datetime, timedelta, timezone from typing import Any, Dict, List, Optional, Tuple # The Matrix CR Studio receipt-signing key. Also published at # https://matrixcr.ai/counterfoil so you can confirm it independently of this file. # The default identity check compares the whole public key. The fingerprint is the # short label a receipt prints (the first 16 hex characters of the key's SHA3-256), # kept for reading and for display; until 2026-10-06 it was also what the default # check compared, which left 64 bits between a forger and a matching key. PUBLISHED_PUBLIC_KEY = "98f18cac17f6e1899daee286838abd5efe8694830c1501c875b4af423f1ce802" PUBLISHED_FINGERPRINT = "be19cba981ce0e02" # The Matrix CR Studio post-quantum (ML-DSA-65) receipt key, as the SHA3-256 of the # whole 1952-byte public key, so the default check binds all of it. Its first 16 # characters are the fingerprint a receipt prints. Minted 2026-10-17; also listed at # https://matrixcr.ai/counterfoil. Receipts issued before that carry no pq_seal. PUBLISHED_PQ_KEY_SHA3 = "cb9f02178cb2d915e958761fb7689d41420a4cf035b4be51725a8a2762f50135" PQ_ALG = "ml-dsa-65" PQ_CONTEXT = b"counterfoil-receipt-v1/pq-seal" PQ_PUBLIC_KEY_BYTES = 1952 PQ_SIGNATURE_BYTES = 3309 try: from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey from cryptography.exceptions import InvalidSignature except Exception: # pragma: no cover sys.stderr.write("needs the 'cryptography' package: pip install cryptography\n") raise SystemExit(2) def _canon(obj: Any) -> bytes: return json.dumps(obj, sort_keys=True, separators=(",", ":"), default=str).encode() def _payload_hash(payload: Any) -> str: return hashlib.sha3_256(_canon(payload)).hexdigest() def _record_hash(r: Dict[str, Any]) -> str: material = f"{r['seq']}|{r['stage']}|{r['ts_ms']}|{r['payload_hash']}|{r['prev_hash']}" return hashlib.sha3_256(material.encode()).hexdigest() def _key_fingerprint(public_raw: bytes) -> str: return hashlib.sha3_256(public_raw).hexdigest()[:16] def _verify_chain(chain: List[Dict[str, Any]], seed_anchor: Any) -> bool: if not chain: return False prev = "" for r in chain: if r.get("record_hash") != _record_hash(r): return False if r.get("prev_hash") != prev: return False prev = r["record_hash"] for i in range(len(chain) - 1, 0, -1): if chain[i]["prev_hash"] != _record_hash(chain[i - 1]): return False if chain[0]["prev_hash"] != "": return False if seed_anchor is not None and chain[0]["payload_hash"] != seed_anchor: return False return True # >>> BEGIN SHARED TIME-SEAL VERIFIER >>> # Everything between the BEGIN and END markers is copied byte for byte into # verify_counterfoil.py (tests/test_counterfoil_timeseal.py pins the two), so it # uses the standard library and `cryptography` only. LABEL = b"counterfoil-receipt-v1/time-seal:" #: Pinned trust anchors: SHA-256 of the DER SubjectPublicKeyInfo of each root key. A chain #: is accepted when it reaches a certificate carrying one of these keys. Each was read #: from a source independent of the tokens on 2026-10-18: DigiCert Trusted Root G4 from #: the system trust store and from cacerts.digicert.com (valid to 2038-01-15); the FreeTSA #: root from https://freetsa.org/files/cacert.pem (valid to 2041-03-07). TSA_ANCHORS: Dict[str, str] = { "digicert-trusted-root-g4": "59df317bfa9f4f0ab7ca514d7772296aa2c765b87664d08b96e57399e364729c", "freetsa-root-ca": "52c54ba340885605314daa1857c8763b94087d05c636092938d4e2d1818e99b5", } #: The issuer's own clock may run ahead of the authorities' by at most this much. MAX_CLOCK_SKEW = timedelta(minutes=5) #: Two authorities asked within seconds of each other must agree to within this much; a #: wider spread means one of them is wrong, and the seal fails rather than pick one. MAX_TOKEN_SPREAD = timedelta(minutes=10) #: A token larger than this, or carrying more certificates, is refused before parsing. MAX_TOKEN_BYTES = 65536 MAX_TOKEN_CERTS = 8 _OID_SIGNED_DATA = "1.2.840.113549.1.7.2" _OID_TSTINFO = "1.2.840.113549.1.9.16.1.4" _OID_CONTENT_TYPE = "1.2.840.113549.1.9.3" _OID_MESSAGE_DIGEST = "1.2.840.113549.1.9.4" _OID_SIGNING_CERT = "1.2.840.113549.1.9.16.2.12" _OID_SIGNING_CERT_V2 = "1.2.840.113549.1.9.16.2.47" _OID_KP_TIMESTAMPING = "1.3.6.1.5.5.7.3.8" _HASH_OIDS = {"2.16.840.1.101.3.4.2.1": "sha256", "2.16.840.1.101.3.4.2.2": "sha384", "2.16.840.1.101.3.4.2.3": "sha512", "1.3.14.3.2.26": "sha1"} _SIG_OIDS = { # signature algorithm OID -> (scheme, hash name or None = take digestAlgorithm) "1.2.840.113549.1.1.1": ("rsa", None), "1.2.840.113549.1.1.11": ("rsa", "sha256"), "1.2.840.113549.1.1.12": ("rsa", "sha384"), "1.2.840.113549.1.1.13": ("rsa", "sha512"), "1.2.840.10045.4.3.2": ("ecdsa", "sha256"), "1.2.840.10045.4.3.3": ("ecdsa", "sha384"), "1.2.840.10045.4.3.4": ("ecdsa", "sha512"), } _MAX_CHAIN = 5 class _Der: """One DER element: tag byte, the whole encoding, and the content bytes.""" __slots__ = ("body", "raw", "tag") def __init__(self, tag: int, raw: bytes, body: bytes) -> None: self.tag, self.raw, self.body = tag, raw, body def _der_read(buf: bytes, pos: int = 0) -> Tuple["_Der", int]: """Read one definite-length DER element at `pos`. Raises ValueError on anything else: a long-form tag, an indefinite length, or a length running past the buffer.""" if pos + 2 > len(buf): raise ValueError("DER: truncated header") tag = buf[pos] if tag & 0x1F == 0x1F: raise ValueError("DER: multi-byte tags are not used here") n = buf[pos + 1] i = pos + 2 if n & 0x80: k = n & 0x7F if k == 0 or k > 4 or i + k > len(buf) or buf[i] == 0: raise ValueError("DER: bad length") n = int.from_bytes(buf[i:i + k], "big") if n < 0x80: raise ValueError("DER: non-minimal length") i += k end = i + n if end > len(buf): raise ValueError("DER: length past end") return _Der(tag, buf[pos:end], buf[i:end]), end def _der_children(el: "_Der") -> List["_Der"]: out, pos = [], 0 while pos < len(el.body): child, pos = _der_read(el.body, pos) out.append(child) return out def _der_oid(el: "_Der") -> str: if el.tag != 0x06 or not el.body: raise ValueError("DER: expected an OID") arcs, v = [], 0 for b in el.body: v = (v << 7) | (b & 0x7F) if not b & 0x80: arcs.append(v) v = 0 if el.body[-1] & 0x80: raise ValueError("DER: truncated OID") first = min(arcs[0] // 40, 2) # the first two arcs share one subidentifier return ".".join(str(x) for x in [first, arcs[0] - 40 * first, *arcs[1:]]) def _der_int(el: "_Der") -> int: if el.tag != 0x02: raise ValueError("DER: expected an INTEGER") return int.from_bytes(el.body, "big", signed=True) def _gen_time(el: "_Der") -> datetime: if el.tag != 0x18: raise ValueError("DER: expected GeneralizedTime") s = el.body.decode("ascii") if not s.endswith("Z"): raise ValueError("genTime is not UTC") whole, _, frac = s[:-1].partition(".") t = datetime.strptime(whole, "%Y%m%d%H%M%S").replace(tzinfo=timezone.utc) return t + timedelta(microseconds=int((frac + "000000")[:6])) if frac else t def _hash(name: str, data: bytes) -> bytes: return hashlib.new(name, data).digest() def _spki_sha256(cert: Any) -> str: from cryptography.hazmat.primitives import serialization return hashlib.sha256(cert.public_key().public_bytes( serialization.Encoding.DER, serialization.PublicFormat.SubjectPublicKeyInfo)).hexdigest() def _valid_at(cert: Any, when: datetime) -> bool: nb = getattr(cert, "not_valid_before_utc", None) or cert.not_valid_before.replace(tzinfo=timezone.utc) na = getattr(cert, "not_valid_after_utc", None) or cert.not_valid_after.replace(tzinfo=timezone.utc) return bool(nb <= when <= na) def verify_token(token_der: bytes, message: bytes, anchors: Dict[str, str]) -> Dict[str, Any]: """Verify one RFC 3161 TimeStampToken offline. Returns {"ok", "gen_time", "anchor", "tsa_subject", "reason"}; never raises. `message` is what the imprint must hash; `anchors` maps a name to the SHA-256 of a pinned root's SubjectPublicKeyInfo.""" from cryptography import x509 from cryptography.exceptions import InvalidSignature from cryptography.hazmat.primitives import hashes, serialization from cryptography.hazmat.primitives.asymmetric import ec, padding out: Dict[str, Any] = {"ok": False, "gen_time": None, "anchor": None, "tsa_subject": None, "reason": None} try: if len(token_der) > MAX_TOKEN_BYTES: raise ValueError("token larger than this checker accepts") ci, end = _der_read(token_der) if end != len(token_der): raise ValueError("trailing bytes after the token") ci_parts = _der_children(ci) if _der_oid(ci_parts[0]) != _OID_SIGNED_DATA or ci_parts[1].tag != 0xA0: raise ValueError("not a CMS SignedData token") sd = _der_children(_der_children(ci_parts[1])[0]) encap = _der_children(sd[2]) if _der_oid(encap[0]) != _OID_TSTINFO: raise ValueError("the signed content is not a TSTInfo") tst_der = _der_children(encap[1])[0] if len(encap) > 1 and encap[1].tag == 0xA0 else None if tst_der is None or tst_der.tag != 0x04: raise ValueError("TSTInfo is not carried as an OCTET STRING") tst_bytes = tst_der.body certs: List[Any] = [] signer_infos = None for el in sd[3:]: if el.tag == 0xA0: certs = [x509.load_der_x509_certificate(c.raw) for c in _der_children(el)] elif el.tag == 0x31: signer_infos = _der_children(el) if not signer_infos or len(signer_infos) != 1: raise ValueError("expected exactly one SignerInfo") if not certs: raise ValueError("the token carries no certificates (it was requested without certReq)") if len(certs) > MAX_TOKEN_CERTS: raise ValueError("the token carries more certificates than this checker follows") # TSTInfo: the imprint and the time (recorded in the verdict only once it verifies) tst_el, tst_end = _der_read(tst_bytes) if tst_end != len(tst_bytes) or tst_el.tag != 0x30: raise ValueError("TSTInfo is not a single SEQUENCE") tst = _der_children(tst_el) if _der_int(tst[0]) != 1: raise ValueError("TSTInfo version is not 1") imprint = _der_children(tst[2]) imp_alg = _HASH_OIDS.get(_der_oid(_der_children(imprint[0])[0])) if imp_alg not in ("sha256", "sha384", "sha512"): raise ValueError("the imprint uses a hash this checker does not accept") if imprint[1].tag != 0x04 or imprint[1].body != _hash(imp_alg, message): raise ValueError("the token time-stamps a different value") gen_time = _gen_time(tst[4]) # SignerInfo: signed attributes, then the signature over them si = _der_children(signer_infos[0]) digest_alg = _HASH_OIDS.get(_der_oid(_der_children(si[2])[0])) if digest_alg not in ("sha256", "sha384", "sha512"): raise ValueError("the signer's digest algorithm is not accepted") idx = 3 if si[idx].tag != 0xA0: raise ValueError("no signed attributes") signed_attrs = si[idx] sig_alg_oid = _der_oid(_der_children(si[idx + 1])[0]) if si[idx + 2].tag != 0x04: raise ValueError("the signature is not an OCTET STRING") signature = si[idx + 2].body attrs: Dict[str, List["_Der"]] = {} for a in _der_children(signed_attrs): ap = _der_children(a) oid = _der_oid(ap[0]) vals = _der_children(ap[1]) if oid in attrs or len(vals) != 1: raise ValueError("a signed attribute appears twice or carries more than one value") attrs[oid] = vals if _der_oid(attrs[_OID_CONTENT_TYPE][0]) != _OID_TSTINFO: raise ValueError("the contentType attribute is not TSTInfo") md = attrs[_OID_MESSAGE_DIGEST][0] if md.tag != 0x04 or md.body != _hash(digest_alg, tst_bytes): raise ValueError("the messageDigest attribute does not match the TSTInfo") # the signing-certificate attribute names exactly one certificate in the token signer = None if _OID_SIGNING_CERT_V2 in attrs: ess = _der_children(_der_children(_der_children(attrs[_OID_SIGNING_CERT_V2][0])[0])[0]) h_alg = "sha256" if ess[0].tag == 0x30: h_alg = _HASH_OIDS.get(_der_oid(_der_children(ess[0])[0]), "") ess = ess[1:] if h_alg not in ("sha256", "sha384", "sha512"): raise ValueError("ESSCertIDv2 uses a hash this checker does not accept") want = ess[0].body elif _OID_SIGNING_CERT in attrs: ess = _der_children(_der_children(_der_children(attrs[_OID_SIGNING_CERT][0])[0])[0]) h_alg, want = "sha1", ess[0].body # RFC 3161's own ESSCertID else: raise ValueError("no signing-certificate attribute (RFC 3161 section 2.4.2)") for c in certs: if _hash(h_alg, c.public_bytes(serialization.Encoding.DER)) == want: signer = c if signer is None: raise ValueError("no certificate in the token matches the signing-certificate attribute") to_check = b"\x31" + signed_attrs.raw[1:] # signed as a SET OF, not [0] IMPLICIT scheme, sig_hash = _SIG_OIDS.get(sig_alg_oid, (None, None)) h = {"sha256": hashes.SHA256(), "sha384": hashes.SHA384(), "sha512": hashes.SHA512()}[sig_hash or digest_alg] if scheme == "rsa": signer.public_key().verify(signature, to_check, padding.PKCS1v15(), h) elif scheme == "ecdsa": signer.public_key().verify(signature, to_check, ec.ECDSA(h)) else: raise ValueError(f"signature algorithm {sig_alg_oid} is not accepted") # the signer is a time-stamping key and nothing else, marked critical eku = signer.extensions.get_extension_for_class(x509.ExtendedKeyUsage) usages = [u.dotted_string for u in eku.value] if not eku.critical or usages != [_OID_KP_TIMESTAMPING]: raise ValueError("the signer's extended key usage is not exactly timeStamping, critical") out["tsa_subject"] = signer.subject.rfc4514_string()[:200] # The chain, from the signer up to a certificate carrying a PINNED key. The pinned # key is the trust: that certificate's own signature and dates are not checked. # Every certificate below it must be valid at genTime, and every ISSUER on the way # (the pinned one included) must be a CA allowed to sign certificates, within its # path length. Without that, any ordinary leaf under the pinned root could mint # its own time-stamping certificate (found by review, 2026-10-18). cur, below = signer, 0 seen_certs = {id(signer)} for _ in range(_MAX_CHAIN): hit = next((n for n, k in anchors.items() if k == _spki_sha256(cur)), None) if hit: if cur is signer: raise ValueError("the signer's own key is pinned; anchors must be issuers") out["anchor"] = hit break if not _valid_at(cur, gen_time): raise ValueError(f"certificate {cur.subject.rfc4514_string()[:80]} not valid at genTime") issuer = None for c in certs: if c.subject == cur.issuer and id(c) not in seen_certs: try: cur.verify_directly_issued_by(c) except Exception: continue issuer = c break if issuer is None: raise ValueError("the chain does not reach a pinned anchor") # CA certificates between this issuer and the signer: pathLenConstraint counts # them (RFC 5280 4.2.1.9), the signer itself excluded below = 0 if cur is signer else below + 1 bc = issuer.extensions.get_extension_for_class(x509.BasicConstraints).value if not bc.ca: raise ValueError("a certificate in the chain was issued by a non-CA certificate") if bc.path_length is not None and below > bc.path_length: raise ValueError("the chain is longer than an issuer's path length allows") try: ku = issuer.extensions.get_extension_for_class(x509.KeyUsage).value if not ku.key_cert_sign: raise ValueError("an issuer in the chain may not sign certificates") except x509.ExtensionNotFound: pass seen_certs.add(id(issuer)) cur = issuer else: raise ValueError("the chain is longer than this checker follows") out["gen_time"] = gen_time.isoformat() out["ok"] = True except InvalidSignature: out["reason"] = "a signature in the token is invalid" except Exception as e: # malformed input is a failed token, never a crash out["reason"] = f"{type(e).__name__}: {e}"[:200] return out def message_for(terminal: str) -> bytes: return LABEL + terminal.encode() def verify_time_seal(ts: Any, terminal: Optional[str], claimed: Optional[datetime] = None, anchors: Optional[Dict[str, str]] = None, min_authorities: int = 1) -> Dict[str, Any]: """{"ok", "bound", "earliest", "authorities", "tokens", "reason"}. A present time seal passes only when every token verifies over this receipt's own terminal, at least `min_authorities` DISTINCT pinned anchors verified (the names come from the anchors, never from the receipt's labels), their times agree to within MAX_TOKEN_SPREAD, and the issuer's claimed time is not after the earliest of them beyond MAX_CLOCK_SKEW. `bound` is the LATEST token time: the receipt existed no later than that if any one of the authorities is honest. `earliest` holds only if all of them are. The time seal is outside the Ed25519 and ML-DSA seals, so a token can be removed; only `min_authorities` (the checker's --require-time asks for 2) refuses a copy that lost one.""" anchors = TSA_ANCHORS if anchors is None else anchors res: Dict[str, Any] = {"ok": False, "bound": None, "earliest": None, "authorities": [], "tokens": [], "reason": None} if not isinstance(terminal, str): res["reason"] = "time seal: no chain record_hash to seal" return res if not isinstance(ts, dict) or ts.get("alg") != "rfc3161" or ts.get("label") != LABEL.decode(): res["reason"] = "time seal: not an rfc3161 time seal with the receipt label" return res if ts.get("sealed_value") != terminal or ts.get("sealed_field") != "chain[-1].record_hash": res["reason"] = "time seal: sealed_value is not this receipt's terminal record_hash" return res toks = ts.get("tokens") if not isinstance(toks, list) or not toks: res["reason"] = "time seal: no tokens" return res message = message_for(terminal) times = [] for t in toks: try: der = base64.b64decode(str(t.get("token", "")), validate=True) if isinstance(t, dict) else b"" except Exception: der = b"" v = verify_token(der, message, anchors) res["tokens"].append(v) if v["ok"]: times.append(datetime.fromisoformat(v["gen_time"])) bad = [v for v in res["tokens"] if not v["ok"]] if bad: res["reason"] = f"time seal: {len(bad)} token(s) do not verify: {bad[0]['reason']}" return res res["authorities"] = sorted({v["anchor"] for v in res["tokens"]}) earliest, latest = min(times), max(times) res["earliest"], res["bound"] = earliest.isoformat(), latest.isoformat() if latest - earliest > MAX_TOKEN_SPREAD: res["reason"] = (f"time seal: the authorities disagree by {latest - earliest}, more than " f"{MAX_TOKEN_SPREAD}, so neither time is accepted") return res if len(res["authorities"]) < min_authorities: res["reason"] = (f"time seal: {len(res['authorities'])} distinct authority verified, " f"{min_authorities} required") return res if claimed is not None and claimed - earliest > MAX_CLOCK_SKEW: res["reason"] = (f"time seal: the receipt claims {claimed.isoformat()}, after the " f"authorities' {earliest.isoformat()}") return res res["ok"] = True return res # <<< END SHARED TIME-SEAL VERIFIER <<< # ── ML-DSA-65 without the library (FIPS 204, August 2024) ─────────────────────── # The browser's Python (Pyodide, cryptography 47 in wasm) has no ML-DSA, measured # 2026-10-17, so until 2026-11-07 the in-browser checker could only fail a post-quantum # seal closed. This is the FIPS 204 verification (Algorithms 3 and 8) in plain Python: # verify only, every input public, no secret anywhere. It is used only when the installed # cryptography cannot do ML-DSA, and the studio's tests hold it to the library's answer on # real signatures and on mutations of every part of one. Not constant time; verification # handles nothing secret. Measured cost about 0.1 s a signature in CPython, and the site's # 20 in-browser checks (two of them post-quantum) run in about 3 s under Pyodide. _MLDSA_Q = 8380417 _MLDSA_N = 256 _MLDSA_D = 13 _MLDSA_K, _MLDSA_L = 6, 5 _MLDSA_TAU, _MLDSA_LAMBDA, _MLDSA_GAMMA1, _MLDSA_GAMMA2 = 49, 192, 1 << 19, (_MLDSA_Q - 1) // 32 _MLDSA_BETA = _MLDSA_TAU * 4 # tau * eta, eta = 4 _MLDSA_OMEGA = 55 _MLDSA_CTILDE = _MLDSA_LAMBDA // 4 # 48 bytes _MLDSA_PK_BYTES = 32 + 320 * _MLDSA_K # 1952 _MLDSA_SIG_BYTES = _MLDSA_CTILDE + 640 * _MLDSA_L + _MLDSA_OMEGA + _MLDSA_K # 3309 def _mldsa_brv8(x: int) -> int: return int(f"{x:08b}"[::-1], 2) _MLDSA_ZETAS = [pow(1753, _mldsa_brv8(i), _MLDSA_Q) for i in range(_MLDSA_N)] _MLDSA_N_INV = pow(_MLDSA_N, _MLDSA_Q - 2, _MLDSA_Q) # 8347681 def _mldsa_ntt(w: List[int]) -> List[int]: a = list(w) m, length = 0, 128 while length >= 1: start = 0 while start < _MLDSA_N: m += 1 z = _MLDSA_ZETAS[m] for j in range(start, start + length): t = z * a[j + length] % _MLDSA_Q a[j + length] = (a[j] - t) % _MLDSA_Q a[j] = (a[j] + t) % _MLDSA_Q start += 2 * length length //= 2 return a def _mldsa_intt(w: List[int]) -> List[int]: a = list(w) m, length = _MLDSA_N, 1 while length < _MLDSA_N: start = 0 while start < _MLDSA_N: m -= 1 z = -_MLDSA_ZETAS[m] for j in range(start, start + length): t = a[j] a[j] = (t + a[j + length]) % _MLDSA_Q a[j + length] = z * (t - a[j + length]) % _MLDSA_Q start += 2 * length length *= 2 return [x * _MLDSA_N_INV % _MLDSA_Q for x in a] def _mldsa_unpack(data: bytes, bits: int) -> List[int]: """Coefficients of `bits` bits each, least significant bit first (FIPS 204 SimpleBitUnpack, and BitUnpack before its subtraction from b).""" v = int.from_bytes(data, "little") mask = (1 << bits) - 1 return [(v >> (bits * i)) & mask for i in range(len(data) * 8 // bits)] def _mldsa_pack(coeffs: List[int], bits: int) -> bytes: v = 0 for i, c in enumerate(coeffs): v |= c << (bits * i) return v.to_bytes(len(coeffs) * bits // 8, "little") def _mldsa_rej_ntt_poly(seed: bytes) -> List[int]: stream = hashlib.shake_128(seed).digest(840) # 280 tries; extended if ever short out: List[int] = [] pos = 0 while len(out) < _MLDSA_N: if pos + 3 > len(stream): stream = hashlib.shake_128(seed).digest(len(stream) * 2) b0, b1, b2 = stream[pos], stream[pos + 1], stream[pos + 2] & 0x7F pos += 3 z = (b2 << 16) | (b1 << 8) | b0 if z < _MLDSA_Q: out.append(z) return out def _mldsa_sample_in_ball(seed: bytes) -> List[int]: stream = hashlib.shake_256(seed).digest(8 + 512) signs = int.from_bytes(stream[:8], "little") c = [0] * _MLDSA_N pos = 8 for i in range(_MLDSA_N - _MLDSA_TAU, _MLDSA_N): while True: if pos >= len(stream): stream = hashlib.shake_256(seed).digest(len(stream) * 2) j = stream[pos] pos += 1 if j <= i: break c[i] = c[j] c[j] = 1 - 2 * ((signs >> (i + _MLDSA_TAU - _MLDSA_N)) & 1) return c def _mldsa_use_hint(h: int, r: int) -> int: m = (_MLDSA_Q - 1) // (2 * _MLDSA_GAMMA2) # 16 rp = r % _MLDSA_Q r0 = rp % (2 * _MLDSA_GAMMA2) if r0 > _MLDSA_GAMMA2: r0 -= 2 * _MLDSA_GAMMA2 if rp - r0 == _MLDSA_Q - 1: r1, r0 = 0, r0 - 1 else: r1 = (rp - r0) // (2 * _MLDSA_GAMMA2) if h: return (r1 + 1) % m if r0 > 0 else (r1 - 1) % m return r1 def _mldsa_hints(y: bytes) -> Optional[List[List[int]]]: """HintBitUnpack (FIPS 204 Algorithm 21): None for any non-canonical encoding.""" h = [[0] * _MLDSA_N for _ in range(_MLDSA_K)] index = 0 for i in range(_MLDSA_K): end = y[_MLDSA_OMEGA + i] if end < index or end > _MLDSA_OMEGA: return None first = index while index < end: if index > first and y[index - 1] >= y[index]: return None h[i][y[index]] = 1 index += 1 if any(y[index:_MLDSA_OMEGA]): return None return h def _mldsa65_verify(public_key: bytes, message: bytes, signature: bytes, context: bytes = b"") -> bool: """ML-DSA.Verify(pk, M, sigma, ctx) for ML-DSA-65 (FIPS 204 Algorithms 3 and 8).""" if len(public_key) != _MLDSA_PK_BYTES or len(signature) != _MLDSA_SIG_BYTES or len(context) > 255: return False rho, t1_bytes = public_key[:32], public_key[32:] t1 = [_mldsa_unpack(t1_bytes[320 * i:320 * (i + 1)], 10) for i in range(_MLDSA_K)] c_tilde = signature[:_MLDSA_CTILDE] z = [] for i in range(_MLDSA_L): raw = _mldsa_unpack(signature[_MLDSA_CTILDE + 640 * i:_MLDSA_CTILDE + 640 * (i + 1)], 20) z.append([_MLDSA_GAMMA1 - x for x in raw]) h = _mldsa_hints(signature[_MLDSA_CTILDE + 640 * _MLDSA_L:]) if h is None: return False if max(abs(x) for poly in z for x in poly) >= _MLDSA_GAMMA1 - _MLDSA_BETA: return False tr = hashlib.shake_256(public_key).digest(64) m_prime = bytes([0, len(context)]) + context + message mu = hashlib.shake_256(tr + m_prime).digest(64) c_hat = _mldsa_ntt([x % _MLDSA_Q for x in _mldsa_sample_in_ball(c_tilde)]) z_hat = [_mldsa_ntt([x % _MLDSA_Q for x in poly]) for poly in z] w1 = [] for r in range(_MLDSA_K): acc = [0] * _MLDSA_N for s in range(_MLDSA_L): a = _mldsa_rej_ntt_poly(rho + bytes([s, r])) zs = z_hat[s] for j in range(_MLDSA_N): acc[j] += a[j] * zs[j] t1_hat = _mldsa_ntt([(x << _MLDSA_D) % _MLDSA_Q for x in t1[r]]) w = _mldsa_intt([(acc[j] - c_hat[j] * t1_hat[j]) % _MLDSA_Q for j in range(_MLDSA_N)]) w1.append([_mldsa_use_hint(h[r][j], w[j]) for j in range(_MLDSA_N)]) encoded = b"".join(_mldsa_pack(poly, 4) for poly in w1) return hashlib.shake_256(mu + encoded).digest(_MLDSA_CTILDE) == c_tilde def _verify_pq(pq: Any, terminal: Optional[str]) -> Tuple[bool, Optional[str], Optional[str], Optional[str]]: """(ok, fingerprint, sha3 of the whole public key, reason). Never raises.""" if not isinstance(terminal, str): return False, None, None, "post-quantum: no chain record_hash to seal" if not isinstance(pq, dict): return False, None, None, f"post-quantum: seal is not an object ({type(pq).__name__})" if pq.get("alg") != PQ_ALG: return False, None, None, f"post-quantum: unsupported alg {pq.get('alg')!r}" if pq.get("context") != PQ_CONTEXT.decode(): return False, None, None, "post-quantum: context is not the receipt seal context" fp = full = None try: pub_raw = bytes.fromhex(pq["public_key"]) if len(pub_raw) != PQ_PUBLIC_KEY_BYTES: return False, None, None, (f"post-quantum: public key is {len(pub_raw)} bytes, " f"not {PQ_PUBLIC_KEY_BYTES}") full = hashlib.sha3_256(pub_raw).hexdigest() fp = full[:16] if pq.get("key_fingerprint") != fp: return False, fp, full, "post-quantum: key_fingerprint != public_key" if pq.get("sealed_field") != "chain[-1].record_hash": return False, fp, full, "post-quantum: sealed_field is not chain[-1].record_hash" if pq.get("sealed_value") != terminal: return False, fp, full, "post-quantum: sealed_value != terminal record_hash" signature = bytes.fromhex(pq["signature"]) if len(signature) != PQ_SIGNATURE_BYTES: return False, fp, full, (f"post-quantum: signature is {len(signature)} bytes, " f"not {PQ_SIGNATURE_BYTES}") except (KeyError, ValueError, TypeError) as e: return False, fp, full, f"post-quantum: malformed seal ({e})" if pq_engine() == PQ_ENGINE_LIBRARY: try: from cryptography.hazmat.primitives.asymmetric import mldsa except ImportError: # gone since the probe: use the built-in one _PQ_ENGINE[:] = [PQ_ENGINE_BUILTIN] else: try: mldsa.MLDSA65PublicKey.from_public_bytes(pub_raw).verify( signature, terminal.encode(), PQ_CONTEXT) except (InvalidSignature, ValueError, TypeError): return False, fp, full, "post-quantum: ml-dsa-65 signature invalid" except Exception: # the library failed, not the seal: check it here _PQ_ENGINE[:] = [PQ_ENGINE_BUILTIN] else: return True, fp, full, None if not _mldsa65_verify(pub_raw, terminal.encode(), signature, PQ_CONTEXT): return False, fp, full, "post-quantum: ml-dsa-65 signature invalid" return True, fp, full, None PQ_ENGINE_LIBRARY = "cryptography" PQ_ENGINE_BUILTIN = "built-in FIPS 204 verifier" _PQ_ENGINE: List[str] = [] def _pq_library_available() -> bool: """True when this machine's cryptography can verify ML-DSA-65 under a context. Import is not enough: some builds (Pyodide's, measured 2026-10-17) import the module and then raise UnsupportedAlgorithm, so this runs one sign and verify with a key never stored.""" from cryptography.exceptions import UnsupportedAlgorithm try: from cryptography.hazmat.primitives.asymmetric import mldsa key = mldsa.MLDSA65PrivateKey.generate() key.public_key().verify(key.sign(b"probe", PQ_CONTEXT), b"probe", PQ_CONTEXT) return True except (ImportError, AttributeError, UnsupportedAlgorithm): return False # anything else is a fault to see, not a library to blame def pq_engine() -> str: """Which code checks a post-quantum seal here: the cryptography library when it can, otherwise the built-in verifier above. Probed once per run.""" if not _PQ_ENGINE: _PQ_ENGINE.append(PQ_ENGINE_LIBRARY if _pq_library_available() else PQ_ENGINE_BUILTIN) return _PQ_ENGINE[0] def pq_available() -> bool: """True when a post-quantum seal can be checked on this machine. Since 2026-11-07 that is every machine (the built-in verifier needs only hashlib's SHAKE); kept so a caller can still ask, and so the benchmark keeps its out-of-scope path for a runtime without SHAKE.""" return hasattr(hashlib, "shake_128") and hasattr(hashlib, "shake_256") # ── The TPM 2.0 hardware seal, verified offline (2026-11-07) ───────────────────── # Until 2026-11-07 this file refused to pass any receipt carrying a hardware seal, because it # could not check one. This is the same check as the studio's src/tpm_attest.verify_hardware_seal # (its tests hold the two to the same verdict on a real-chip seal and on every tamper), in plain # Python with `cryptography` for ECDSA P-256 only. What it proves: a key created inside a TPM, which # cannot leave it and which the chip lets sign only while PCR 0-7 hold the quoted values, signed this # record hash; the attestation key (AK) quoted those values over the nonce in the seal. What it does # not prove: that the hash is honest (whoever controls the host controls what is hashed), that the # boot state was a good one unless you give a reference (--expect-boot-state), that the TPM itself is # trustworthy (no EK certificate chain is checked), or anything about runtime state after boot. # PCR 0-7 are the firmware and boot measurements. A TPM is not a TEE. PUBLISHED_AK_FINGERPRINT = "sha256:e99c5344233181b301f2a6f6c08592e39501e8e1446bb5c6d162748126d9224f" _HW_PCR_INDICES = (0, 1, 2, 3, 4, 5, 6, 7) _HW_NONCE_BYTES = (16, 32) # A seal made without a relying party's nonce derives it from the record (quote.nonce_rule): # it proves the quote came after the record existed, not that it is fresh for you. _HW_RECORD_NONCE_RULE = "record-v1" _HW_RECORD_NONCE_TAG = b"counterfoil/tpm-quote-nonce/record-v1\x00" _HW_SHA256, _HW_ECC, _HW_NULL, _HW_ECDSA, _HW_P256 = 0x000B, 0x0023, 0x0010, 0x0018, 0x0003 _HW_CC_POLICY_PCR = 0x0000017F _HW_MAGIC, _HW_ST_CERTIFY, _HW_ST_QUOTE = 0xFF544347, 0x8017, 0x8018 _HW_REQUIRED = 0x00000002 | 0x00000010 | 0x00000020 | 0x00040000 # fixedTPM fixedParent sensitiveDataOrigin sign _HW_FORBIDDEN = 0x00000040 | 0x00020000 # userWithAuth decrypt def _hw_tpm2b(buf: bytes, off: int) -> Tuple[bytes, int]: if off + 2 > len(buf): raise ValueError("truncated TPM2B") n = int.from_bytes(buf[off:off + 2], "big") if off + 2 + n > len(buf): raise ValueError("truncated TPM2B body") return buf[off + 2:off + 2 + n], off + 2 + n def _hw_u(buf: bytes, off: int, size: int) -> int: if off + size > len(buf): raise ValueError("truncated integer") return int.from_bytes(buf[off:off + size], "big") def _hw_public(tpm2b: bytes) -> Dict[str, Any]: """TPM2B_PUBLIC of an ECC key (TCG Part 2, 12.2.4).""" t, end = _hw_tpm2b(tpm2b, 0) if end != len(tpm2b): raise ValueError("TPM2B_PUBLIC size mismatch") typ, name_alg, attrs = _hw_u(t, 0, 2), _hw_u(t, 2, 2), _hw_u(t, 4, 4) auth_policy, off = _hw_tpm2b(t, 8) if typ != _HW_ECC: raise ValueError(f"not an ECC public area (type 0x{typ:04x})") sym = _hw_u(t, off, 2); off += 2 if sym != _HW_NULL: off += 4 scheme = _hw_u(t, off, 2); off += 2 scheme_hash = 0 if scheme != _HW_NULL: scheme_hash = _hw_u(t, off, 2); off += 2 curve = _hw_u(t, off, 2); off += 2 kdf = _hw_u(t, off, 2); off += 2 if kdf != _HW_NULL: off += 2 x, off = _hw_tpm2b(t, off) y, off = _hw_tpm2b(t, off) if off != len(t): raise ValueError("trailing bytes in TPMT_PUBLIC") return {"name_alg": name_alg, "attrs": attrs, "auth_policy": auth_policy, "curve": curve, "scheme": scheme, "scheme_hash": scheme_hash, "x": x, "y": y, "raw": t} def _hw_attest(raw: bytes) -> Dict[str, Any]: """TPMS_ATTEST header (TCG Part 2, 10.12.12); `body` is where the type's own part starts.""" magic, typ = _hw_u(raw, 0, 4), _hw_u(raw, 4, 2) _signer, off = _hw_tpm2b(raw, 6) extra, off = _hw_tpm2b(raw, off) off += 8 + 4 + 4 + 1 + 8 # clockInfo (clock, resetCount, restartCount, safe), firmwareVersion if off > len(raw): raise ValueError("truncated TPMS_ATTEST") return {"magic": magic, "type": typ, "extra": extra, "body": off, "raw": raw} def _hw_ecdsa(pem: str, sig_der: bytes, message: bytes) -> Tuple[bool, str]: from cryptography.hazmat.primitives import hashes, serialization from cryptography.hazmat.primitives.asymmetric import ec try: pub = serialization.load_pem_public_key(pem.encode()) if not isinstance(pub, ec.EllipticCurvePublicKey): return False, "not an EC public key" pub.verify(sig_der, message, ec.ECDSA(hashes.SHA256())) return True, "" except Exception as e: # a bad signature or a bad key is a failed check, never a crash return False, type(e).__name__ def _hw_ak_fingerprint(pem: str) -> str: from cryptography.hazmat.primitives import serialization der = serialization.load_pem_public_key(pem.encode()).public_bytes( serialization.Encoding.DER, serialization.PublicFormat.SubjectPublicKeyInfo) return "sha256:" + hashlib.sha256(der).hexdigest() def _hw_pem_is_point(pem: str, x: bytes, y: bytes) -> bool: from cryptography.hazmat.primitives import serialization from cryptography.hazmat.primitives.asymmetric import ec pub = serialization.load_pem_public_key(pem.encode()) if not isinstance(pub, ec.EllipticCurvePublicKey) or not isinstance(pub.curve, ec.SECP256R1): return False n = pub.public_numbers() return n.x == int.from_bytes(x, "big") and n.y == int.from_bytes(y, "big") def _hw_select(indices: Tuple[int, ...]) -> bytes: bm = bytearray(3) for i in indices: bm[i // 8] |= 1 << (i % 8) return bytes(bm) def _hw_policy_pcr(values: List[bytes], indices: Tuple[int, ...]) -> bytes: """TPM2_PolicyPCR from a fresh session (TCG Part 3, 23.7).""" sel = (1).to_bytes(4, "big") + _HW_SHA256.to_bytes(2, "big") + bytes([3]) + _hw_select(indices) return hashlib.sha256(b"\x00" * 32 + _HW_CC_POLICY_PCR.to_bytes(4, "big") + sel + hashlib.sha256(b"".join(values)).digest()).digest() def _boot_reference(path: str) -> Optional[List[str]]: """{"pcr_sha256": [8 hex]} from the file, or None if it is not exactly that.""" try: with open(path, "rb") as fh: doc = json.loads(fh.read(1 << 16)) vals = doc.get("pcr_sha256") if isinstance(doc, dict) else None if (isinstance(vals, list) and len(vals) == len(_HW_PCR_INDICES) and all(isinstance(v, str) and len(v) == 64 and all(c in "0123456789abcdefABCDEF" for c in v) for v in vals)): return [v.lower() for v in vals] except (OSError, ValueError): pass return None def _verify_hardware(seal: Dict[str, Any], record_hash_hex: str, *, expect_ak: str = "", expect_nonce: str = "", boot_reference: Optional[List[str]] = None) -> Dict[str, Any]: """Every guarantee its own boolean; `valid` is their conjunction plus the pins asked for. Never raises: a seal of the wrong shape is a failed seal.""" reasons: List[str] = [] key_hw = certify = policy = quote = signature = False nonce_ok: Optional[bool] = None ak_ok: Optional[bool] = None boot_ok: Optional[bool] = None pcr_values: List[str] = [] try: if seal.get("alg") != "ecdsa-p256-sha256": reasons.append(f"unsupported alg {seal.get('alg')!r}") if seal.get("sealed_value") != record_hash_hex: reasons.append("sealed_value != the receipt's terminal record_hash") key, ak, q, c = seal["key"], seal["ak"], seal["quote"], seal["certify"] key_name = bytes.fromhex(key["name_hex"]) pub = _hw_public(bytes.fromhex(key["tpm2b_public_hex"])) why: List[str] = [] if pub["attrs"] & _HW_REQUIRED != _HW_REQUIRED: why.append(f"key attrs 0x{pub['attrs']:08x} lack fixedTPM|fixedParent|sensitiveDataOrigin|sign") if pub["attrs"] & _HW_FORBIDDEN: why.append(f"key attrs 0x{pub['attrs']:08x} set userWithAuth/decrypt (policy is not the only path)") if not pub["auth_policy"]: why.append("key has an empty authPolicy (not policy-bound)") if pub["curve"] != _HW_P256: why.append(f"key curve 0x{pub['curve']:04x} is not NIST P-256") if pub["scheme"] != _HW_ECDSA or pub["scheme_hash"] != _HW_SHA256: why.append("key scheme is not ECDSA/SHA-256") if pub["name_alg"] != _HW_SHA256: why.append(f"unsupported nameAlg 0x{pub['name_alg']:04x}") elif _HW_SHA256.to_bytes(2, "big") + hashlib.sha256(pub["raw"]).digest() != key_name: why.append("key name does not match its public area (name recompute failed)") if not _hw_pem_is_point(key["public_pem"], pub["x"], pub["y"]): why.append("key public_pem does not match the TPM public point") key_hw = not why reasons += why why = [] try: a = _hw_attest(bytes.fromhex(c["attest_hex"])) if a["magic"] != _HW_MAGIC: why.append("certify: bad TPM_GENERATED magic") if a["type"] != _HW_ST_CERTIFY: why.append(f"certify: attest type 0x{a['type']:04x} is not TPM_ST_ATTEST_CERTIFY") name, off = _hw_tpm2b(a["raw"], a["body"]) _qname, off = _hw_tpm2b(a["raw"], off) if off != len(a["raw"]): why.append("certify: trailing bytes in certify attest") if name != key_name: why.append("certify: attested object name is not the signing key") except Exception as e: why.append(f"certify: parse {type(e).__name__}: {e}") ok, err = _hw_ecdsa(ak["public_pem"], bytes.fromhex(c["signature_der_hex"]), bytes.fromhex(c["attest_hex"])) if not ok: why.append(f"certify: AK signature invalid ({err})") certify = not why reasons += why nonce = bytes.fromhex(q["nonce_hex"]) if not (_HW_NONCE_BYTES[0] <= len(nonce) <= _HW_NONCE_BYTES[1]): reasons.append(f"quote: nonce length {len(nonce)} outside [{_HW_NONCE_BYTES[0]},{_HW_NONCE_BYTES[1]}]") vals = [bytes.fromhex(h) for h in q["pcr_values_hex"]] pcr_values = [v.hex() for v in vals] indices = tuple(int(i) for i in q["pcr_indices"]) why = [] if indices != _HW_PCR_INDICES: why.append(f"quote: PCR indices {list(indices)} are not the house set {list(_HW_PCR_INDICES)}") try: a = _hw_attest(bytes.fromhex(q["attest_hex"])) if a["magic"] != _HW_MAGIC: why.append("quote: bad TPM_GENERATED magic") if a["type"] != _HW_ST_QUOTE: why.append(f"quote: attest type 0x{a['type']:04x} is not TPM_ST_ATTEST_QUOTE") if a["extra"] != nonce: why.append("quote: extraData != nonce") rule = q.get("nonce_rule") if rule is not None and rule != _HW_RECORD_NONCE_RULE: why.append(f"quote: unknown nonce_rule {rule!r}") elif rule is not None and nonce != hashlib.sha256( _HW_RECORD_NONCE_TAG + bytes.fromhex(record_hash_hex)).digest()[:20]: why.append("quote: nonce is not the one derived from this record (nonce_rule)") raw, off = a["raw"], a["body"] count = _hw_u(raw, off, 4); off += 4 sels = [] for _ in range(count): halg, size = _hw_u(raw, off, 2), _hw_u(raw, off + 2, 1); off += 3 sels.append((halg, raw[off:off + size])); off += size digest, off = _hw_tpm2b(raw, off) if off != len(raw): why.append("quote: trailing bytes in quote attest") if sels != [(_HW_SHA256, _hw_select(indices))]: why.append("quote: PCR selection is not sha256 over the declared indices") if len(vals) != len(indices) or any(len(v) != 32 for v in vals): why.append("quote: PCR value list malformed") elif hashlib.sha256(b"".join(vals)).digest() != digest: why.append("quote: pcrDigest != SHA-256(declared PCR values)") except Exception as e: why.append(f"quote: parse {type(e).__name__}: {e}") ok, err = _hw_ecdsa(ak["public_pem"], bytes.fromhex(q["signature_der_hex"]), bytes.fromhex(q["attest_hex"])) if not ok: why.append(f"quote: AK signature invalid ({err})") quote = not why and not any(r.startswith("quote: nonce length") for r in reasons) reasons += why if vals and len(vals) == len(indices): policy = _hw_policy_pcr(vals, indices) == pub["auth_policy"] if not policy: reasons.append("policy: key authPolicy != PolicyPCR(quoted PCR values)") signature, err = _hw_ecdsa(key["public_pem"], bytes.fromhex(seal["signature_der_hex"]), record_hash_hex.encode()) if not signature: reasons.append(f"signature: key signature over the record hash invalid ({err})") if expect_nonce: nonce_ok = str(q["nonce_hex"]).lower() == expect_nonce.strip().lower() if not nonce_ok: reasons.append("nonce: the quote's nonce is not the one you expected") if _hw_ak_fingerprint(ak["public_pem"]) != str(ak.get("fingerprint", "")).lower(): ak_ok = False reasons.append("ak: fingerprint does not match the AK public key") elif expect_ak: ak_ok = str(ak["fingerprint"]).lower() == expect_ak.strip().lower() if not ak_ok: reasons.append(f"ak: TPM identity {ak['fingerprint']} is not the expected {expect_ak}") if boot_reference is not None: boot_ok = quote and [h.lower() for h in boot_reference] == pcr_values if not boot_ok: reasons.append("boot state: the quoted PCR 0-7 values are not the reference you gave" if quote else "boot state: not compared, the quote did not verify") except Exception as e: reasons.append(f"malformed seal: {type(e).__name__}: {e}") valid = (key_hw and certify and policy and quote and signature and nonce_ok is not False and ak_ok is not False and boot_ok is not False and not any(r.startswith(("unsupported alg", "sealed_value", "malformed")) for r in reasons)) return {"valid": valid, "key_hardware_bound_ok": key_hw, "certify_ok": certify, "policy_bound_ok": policy, "quote_ok": quote, "signature_ok": signature, "nonce_ok": nonce_ok, "ak_identity_ok": ak_ok, "boot_state_ok": boot_ok, "ak_fingerprint": (seal.get("ak") or {}).get("fingerprint") if isinstance(seal.get("ak"), dict) else None, "pcr_values_hex": pcr_values, "reasons": reasons} # ── Runtime measurement (Linux IMA), disclosed selectively (2026-11-09) ────────────── # Same check as the studio's src/counterfoil_ima.verify_ima_seal; the tests hold the two to the # same verdict on a real-chip seal and on every tamper. A receipt's `ima_seal` is a quote by the # TPM's attestation key over PCR 0-10, taken after the record existed (nonce derived from it). Its # `ima_log` (or the evidence file's) is the IMA log as template hashes only: no paths, no file # hashes. This file replays them to the quoted PCR 10 (a violation, logged as zeros, is extended as # 0xff*32, the kernel's rule), checks that entry 0 is boot_aggregate = SHA-256(quoted PCR 0-9), and # recomputes the one other entry disclosed in full, the IMA policy file, against the published # policy. Presence, not absence: nothing undisclosed can be shown absent. Hashes of public files at # standard paths are recognisable. The policy entry shows the published policy file was measured in # that boot, not that it was the policy in force. The kernel keeps the log, and PCR 8-9 (on a GRUB # boot, the kernel and its command line) are reported, not judged. Says nothing about which tool code ran. _IMA_PCR_INDICES = tuple(range(0, 11)) _IMA_NONCE_RULE = "ima-record-v1" _IMA_NONCE_TAG = b"counterfoil/ima-quote-nonce/record-v1\x00" _IMA_POLICY_NAME = "/etc/ima/ima-policy" _IMA_DISCLOSABLE = ("boot_aggregate", _IMA_POLICY_NAME) _IMA_MAX_ENTRIES = 1 << 22 # The SHA-256 of the policy file our node loads at boot: the Linux kernel's built-in tcb rules # (security/integrity/ima/ima_policy.c), written out as a file so that loading it locks the policy # and records its fingerprint. A node that loads other rules does not disclose a policy entry. PUBLISHED_IMA_POLICY_SHA256 = "21f68d6873f7dbf7c046bc4da987ba57ca4d7d303980ff116ac08a02cb092c6b" def _ima_template_hash(file_hash_hex: str, name: str) -> str: """ima-ng, sha256 bank: per field a little-endian u32 length then the data; d-ng = "sha256:\\0" + digest, n-ng = name + "\\0".""" d = b"sha256:\x00" + bytes.fromhex(file_hash_hex) n = name.encode() + b"\x00" return hashlib.sha256(len(d).to_bytes(4, "little") + d + len(n).to_bytes(4, "little") + n).hexdigest() def _ima_replay(hashes: List[bytes]) -> bytes: pcr = bytes(32) for th in hashes: pcr = hashlib.sha256(pcr + (b"\xff" * 32 if th == bytes(32) else th)).digest() return pcr def _ima_log_hashes(log: Any) -> List[bytes]: if not isinstance(log, dict): raise ValueError("the IMA log is not an object") if (log.get("ima_log_version") != 1 or log.get("bank") != "sha256" or log.get("template") != "ima-ng" or log.get("violation_rule") != "extend-ff"): raise ValueError("unsupported IMA log (version, bank, template or violation rule)") raw = base64.b64decode(str(log.get("template_hashes_b64", "")).encode(), validate=True) if len(raw) % 32 or len(raw) // 32 > _IMA_MAX_ENTRIES: raise ValueError("the template hash list is not a whole number of hashes, or too long") hashes = [raw[i:i + 32] for i in range(0, len(raw), 32)] if log.get("entries") != len(hashes): raise ValueError("the log's entry count does not match its hashes") return hashes def _verify_ima(seal: Any, record_hash_hex: str, *, log: Any = None, expect_ak: str = "", boot_reference: Optional[List[str]] = None, policy_sha256: str = PUBLISHED_IMA_POLICY_SHA256) -> Dict[str, Any]: """Every guarantee its own boolean; `valid` = the quote verified and nothing present failed. Without a log, log_ok, boot_aggregate_ok and policy_ok are None. Never raises.""" reasons: List[str] = [] quote = False structural = True ak_ok: Optional[bool] = None log_ok: Optional[bool] = None agg_ok: Optional[bool] = None pol_ok: Optional[bool] = None boot_ok: Optional[bool] = None vals: List[bytes] = [] try: if not isinstance(seal, dict): raise ValueError("the IMA seal is not an object") if seal.get("ima_seal_version") != 1: structural = False reasons.append(f"unsupported ima_seal_version {seal.get('ima_seal_version')!r}") if seal.get("sealed_value") != record_hash_hex: structural = False reasons.append("sealed_value != the receipt's terminal record_hash") ak, q = seal["ak"], seal["quote"] why: List[str] = [] nonce = bytes.fromhex(q["nonce_hex"]) if q.get("nonce_rule") != _IMA_NONCE_RULE: why.append(f"unknown nonce_rule {q.get('nonce_rule')!r}") elif nonce != hashlib.sha256(_IMA_NONCE_TAG + bytes.fromhex(record_hash_hex)).digest()[:20]: why.append("the nonce is not the one derived from this record") indices = tuple(int(i) for i in q["pcr_indices"]) if indices != _IMA_PCR_INDICES or q.get("pcr_alg") != "sha256": why.append(f"PCR selection {list(indices)} is not sha256:0-10") vals = [bytes.fromhex(h) for h in q["pcr_values_hex"]] try: a = _hw_attest(bytes.fromhex(q["attest_hex"])) if a["magic"] != _HW_MAGIC: why.append("bad TPM_GENERATED magic") if a["type"] != _HW_ST_QUOTE: why.append(f"attest type 0x{a['type']:04x} is not a quote") if a["extra"] != nonce: why.append("extraData != nonce") raw, off = a["raw"], a["body"] count = _hw_u(raw, off, 4); off += 4 sels = [] for _ in range(count): halg, size = _hw_u(raw, off, 2), _hw_u(raw, off + 2, 1); off += 3 sels.append((halg, raw[off:off + size])); off += size digest, off = _hw_tpm2b(raw, off) if off != len(raw): why.append("trailing bytes in quote attest") if sels != [(_HW_SHA256, _hw_select(_IMA_PCR_INDICES))]: why.append("the signed PCR selection is not sha256:0-10") if len(vals) != len(_IMA_PCR_INDICES) or any(len(v) != 32 for v in vals): why.append("PCR value list malformed") elif hashlib.sha256(b"".join(vals)).digest() != digest: why.append("pcrDigest != SHA-256(declared PCR values)") except Exception as e: why.append(f"parse {type(e).__name__}: {e}") ok, err = _hw_ecdsa(ak["public_pem"], bytes.fromhex(q["signature_der_hex"]), bytes.fromhex(q["attest_hex"])) if not ok: why.append(f"AK signature invalid ({err})") quote = not why reasons += [f"quote: {w}" for w in why] if _hw_ak_fingerprint(ak["public_pem"]) != str(ak.get("fingerprint", "")).lower(): ak_ok = False reasons.append("ak: fingerprint does not match the AK public key") elif expect_ak: ak_ok = str(ak["fingerprint"]).lower() == expect_ak.strip().lower() if not ak_ok: reasons.append(f"ak: TPM identity {ak['fingerprint']} is not the expected {expect_ak}") if boot_reference is not None: boot_ok = bool(quote and [v.hex() for v in vals[:8]] == [h.lower() for h in boot_reference]) if not boot_ok: reasons.append("boot state: the quoted PCR 0-7 are not the reference you gave") meta, disclosed = seal["log"], seal["disclosed"] if (not isinstance(meta, dict) or not isinstance(disclosed, list) or not all(isinstance(d, dict) for d in disclosed)): raise ValueError("log or disclosed is not the right shape") for d in disclosed: if d.get("name") not in _IMA_DISCLOSABLE: structural = False reasons.append(f"disclosed: {d.get('name')!r} is not a name this seal may disclose") if log is not None: hashes: Optional[List[bytes]] = None try: hashes = _ima_log_hashes(log) except Exception as e: log_ok = False reasons.append(f"log: {e}") if hashes is not None: n = meta.get("entry_count") if not isinstance(n, int) or isinstance(n, bool) or not 0 < n <= len(hashes): log_ok = False reasons.append(f"log: entry_count {n!r} is not within the {len(hashes)} hashes given") else: pre = hashes[:n] log_ok = True if hashlib.sha256(b"".join(pre)).hexdigest() != meta.get("prefix_sha256"): log_ok = False reasons.append("log: the first entry_count hashes are not the prefix the seal names") if not quote or _ima_replay(pre) != vals[10]: log_ok = False reasons.append("log: the hashes do not replay to the quoted PCR 10") agg = hashlib.sha256(b"".join(vals[:10])).hexdigest() # a disclosed entry means something only inside a log the chip confirmed for d in (disclosed if log_ok else []): name, i = d.get("name"), d.get("index") try: good = bool(isinstance(i, int) and not isinstance(i, bool) and 0 <= i < n and d.get("alg") == "sha256" and _ima_template_hash(str(d.get("file_hash")), str(name)) == pre[i].hex()) except ValueError: good = False if name == "boot_aggregate": agg_ok = good and i == 0 and d.get("file_hash") == agg and agg_ok is not False if not agg_ok: reasons.append("boot_aggregate: not the log's entry 0, or not SHA-256 " "of the quoted PCR 0-9") elif name == _IMA_POLICY_NAME: pol_ok = good and d.get("file_hash") == policy_sha256 and pol_ok is not False if not pol_ok: reasons.append("policy: the disclosed policy entry is not in the log " "at its index, or is not the published policy") if log_ok and agg_ok is None: agg_ok = False reasons.append("boot_aggregate: not disclosed") except Exception as e: reasons.append(f"malformed IMA seal: {type(e).__name__}: {e}") quote = structural = False valid = bool(quote and structural and ak_ok is not False and log_ok is not False and agg_ok is not False and pol_ok is not False and boot_ok is not False) full = len(vals) == len(_IMA_PCR_INDICES) return {"valid": valid, "quote_ok": quote, "ak_identity_ok": ak_ok, "log_ok": log_ok, "boot_aggregate_ok": agg_ok, "policy_ok": pol_ok, "boot_state_ok": boot_ok, "entry_count": seal.get("log", {}).get("entry_count") if isinstance(seal, dict) and isinstance(seal.get("log"), dict) else None, "pcr8_hex": vals[8].hex() if full else None, "pcr9_hex": vals[9].hex() if full else None, "reasons": reasons} def verify(receipt: Dict[str, Any], expect_key: str = "", expect_pq_key: str = "", require_pq: bool = False, require_time: bool = False, expect_ak: str = "", expect_nonce: str = "", boot_reference: Optional[List[str]] = None, require_hardware: bool = False, ima_log: Any = None, require_ima: bool = False) -> Tuple[bool, Dict[str, Any]]: reasons: List[str] = [] chain = receipt.get("chain") or [] integrity = _verify_chain(chain, receipt.get("seed_anchor")) if not integrity: reasons.append("integrity: hash chain failed (tamper, reorder, or bad closure)") claim_ok = bool(chain) and _payload_hash(receipt.get("claim", {})) == chain[0]["payload_hash"] if not claim_ok: reasons.append("claim: presented claim does not match the sealed seed payload_hash") seal = receipt.get("seal", {}) auth_ok = False fp = None pub_hex = None if not chain: reasons.append("authenticity: no chain to seal") elif seal.get("alg") != "ed25519": reasons.append(f"authenticity: unsupported seal alg {seal.get('alg')!r}") else: try: pub_raw = bytes.fromhex(seal["public_key"]) fp = _key_fingerprint(pub_raw) pub_hex = pub_raw.hex() terminal = chain[-1]["record_hash"] if seal.get("key_fingerprint") != fp: reasons.append("authenticity: key_fingerprint != public_key") elif seal.get("sealed_value") != terminal: reasons.append("authenticity: sealed_value != terminal record_hash") else: Ed25519PublicKey.from_public_bytes(pub_raw).verify( bytes.fromhex(seal["signature"]), terminal.encode()) auth_ok = True except InvalidSignature: reasons.append("authenticity: ed25519 signature invalid") except (KeyError, ValueError, TypeError) as e: reasons.append(f"authenticity: malformed seal ({e})") identity_ok: Optional[bool] = None # None = not checked, never "passed" identity_basis: Optional[str] = None # what was compared, when it was if expect_key: want = str(expect_key).strip().lower() is_hex = bool(want) and all(c in "0123456789abcdef" for c in want) if is_hex and len(want) == 64: # a whole Ed25519 public key identity_basis = "public_key" identity_ok = pub_hex is not None and pub_hex == want if not identity_ok: reasons.append(f"identity: sealed public key {pub_hex} != expected {want}") elif is_hex and len(want) == 16: # the short fingerprint: 64 bits only identity_basis = "fingerprint" identity_ok = fp is not None and fp == want if not identity_ok: reasons.append(f"identity: sealed key {fp} != expected {want}") else: # a typo must not read as a mismatch identity_ok = False reasons.append("identity: the expected key is neither a 64-character public key " f"nor a 16-character fingerprint, in hex (got {len(want)} characters), " "so nothing was compared") # The TPM hardware seal: its own booleans. Absent = null. From 2026-09-23 to 2026-11-07 a # present seal made this file refuse to pass, because it could not check one; now it does. hardware_present = receipt.get("hardware_seal") is not None hw_ok: Optional[bool] = None hw: Dict[str, Any] = {} if hardware_present: seal_hw = receipt.get("hardware_seal") terminal_hw = chain[-1].get("record_hash") if chain and isinstance(chain[-1], dict) else None if not isinstance(seal_hw, dict) or not isinstance(terminal_hw, str): hw = {"valid": False, "reasons": ["the seal is not an object, or there is no chain to seal"]} else: hw = _verify_hardware(seal_hw, terminal_hw, expect_ak=expect_ak, expect_nonce=expect_nonce, boot_reference=boot_reference) hw_ok = bool(hw.get("valid")) reasons.extend(f"hardware: {r}" for r in hw.get("reasons", [])) # Without a TPM identity to compare, a software key could have made every part of a # self-consistent seal, so it is not reported as hardware (AI Family, 2026-11-07). if hw_ok and hw.get("ak_identity_ok") is not True: hw_ok = None reasons.append("hardware: the seal is self-consistent, but no TPM identity was given " "to compare (--expect-ak), and a software key could have made all of " "it, so it is not reported as a hardware seal") elif boot_reference is not None or require_hardware: reasons.append("hardware: a TPM check was asked for (a boot reference, a TPM identity or " "a nonce) and the receipt has no hardware seal, so nothing was compared") boot_ok = hw.get("boot_state_ok") if hardware_present else (False if boot_reference is not None else None) hw_pass = hw_ok is True if require_hardware else hw_ok is not False # The post-quantum seal: its own boolean, its own identity. Absent = null. pq = receipt.get("pq_seal") pq_ok: Optional[bool] = None pq_fp: Optional[str] = None pq_identity_ok: Optional[bool] = None if pq is not None: pq_ok, pq_fp, pq_full, why = _verify_pq( pq, chain[-1].get("record_hash") if chain and isinstance(chain[-1], dict) else None) if why: reasons.append(why) if expect_pq_key: want = str(expect_pq_key).strip().lower() if len(want) not in (16, 64) or not all(c in "0123456789abcdef" for c in want): pq_identity_ok = False reasons.append("post-quantum identity: the expected key is neither a 16-character " "fingerprint nor the 64-character SHA3-256 of the key, in hex, " "so nothing was compared") else: pq_identity_ok = (pq_full if len(want) == 64 else pq_fp) == want if not pq_identity_ok: reasons.append(f"post-quantum identity: sealed key {pq_fp} != expected {want}") elif require_pq: reasons.append("post-quantum: required, and the receipt has no pq_seal (issued " "classical-only, or the seal was removed)") pq_pass = pq_ok is True if require_pq else pq_ok is not False # Trusted time: RFC 3161 tokens from pinned authorities, its own boolean. Absent = null. tseal = receipt.get("time_seal") time_ok: Optional[bool] = None time_detail: Dict[str, Any] = {} if tseal is not None: last = chain[-1] if chain and isinstance(chain[-1], dict) else {} claimed = None ts_ms = last.get("ts_ms") if isinstance(ts_ms, int) and not isinstance(ts_ms, bool) and 0 <= ts_ms < 2 ** 44: claimed = datetime.fromtimestamp(ts_ms / 1000, tz=timezone.utc) rh = last.get("record_hash") try: time_detail = verify_time_seal(tseal, rh if isinstance(rh, str) else None, claimed, min_authorities=2 if require_time else 1) except Exception as exc: # a malformed seal is a failed seal, never a crash time_detail = {"ok": False, "reason": f"time seal: unreadable ({type(exc).__name__})"} time_ok = bool(time_detail.get("ok")) if time_detail.get("reason"): reasons.append(time_detail["reason"]) elif require_time: reasons.append("time seal: required, and the receipt has none") time_pass = time_ok is True if require_time else time_ok is not False # Runtime measurement (IMA): its own boolean. Absent = null. True only when the log replayed # and the TPM identity was compared; a quote with no log, or no identity, is null, not true. iseal = receipt.get("ima_seal") ima_ok: Optional[bool] = None ima: Dict[str, Any] = {} if iseal is not None: last = chain[-1] if chain and isinstance(chain[-1], dict) else {} log = receipt.get("ima_log") if receipt.get("ima_log") is not None else ima_log ima = _verify_ima(iseal, str(last.get("record_hash", "")), log=log, expect_ak=expect_ak, boot_reference=boot_reference) ima_ok = bool(ima.get("valid")) reasons.extend(f"ima: {r}" for r in ima.get("reasons", [])) if ima_ok and ima.get("log_ok") is not True: ima_ok = None reasons.append("ima: the quote verifies, but no log was given, so nothing was replayed") elif ima_ok and ima.get("ak_identity_ok") is not True: ima_ok = None reasons.append("ima: self-consistent, but not compared to a TPM identity (--expect-ak)") elif require_ima: reasons.append("ima: required, and the receipt has no runtime measurement (ima_seal)") ima_pass = ima_ok is True if require_ima else ima_ok is not False valid = (integrity and claim_ok and auth_ok and identity_ok is not False and hw_pass and boot_ok is not False and pq_pass and pq_identity_ok is not False and time_pass and ima_pass) return valid, {"valid": valid, "integrity_ok": integrity, "claim_binding_ok": claim_ok, "authenticity_ok": auth_ok, "identity_ok": identity_ok, "identity_basis": identity_basis, "hardware_seal_present": hardware_present, "hardware_authenticity_ok": hw_ok, "hardware": {k: hw.get(k) for k in ( "key_hardware_bound_ok", "certify_ok", "policy_bound_ok", "quote_ok", "signature_ok", "nonce_ok", "ak_identity_ok", "ak_fingerprint", "pcr_values_hex")} if hardware_present else None, "boot_state_ok": boot_ok, "pq_authenticity_ok": pq_ok, "pq_identity_ok": pq_identity_ok, "pq_key_fingerprint": pq_fp, "pq_verified_by": pq_engine() if pq_ok is not None else None, "time_ok": time_ok, "time_bound": time_detail.get("bound"), "time_authorities": time_detail.get("authorities", []), "ima_ok": ima_ok, "ima": {k: ima.get(k) for k in ( "quote_ok", "ak_identity_ok", "log_ok", "boot_aggregate_ok", "policy_ok", "entry_count", "pcr8_hex", "pcr9_hex")} if iseal is not None else None, "key_fingerprint": fp, "reasons": reasons} _EVIDENCE_VERSION = 1 def _fingerprint(obj: Any) -> str: return "sha3-256:" + hashlib.sha3_256(_canon(obj)).hexdigest() def _d(x: Any) -> Dict[str, Any]: """A dict view of untrusted JSON: anything that is not a dict reads as empty.""" return x if isinstance(x, dict) else {} def verify_evidence(evidence: Dict[str, Any], expect_key: str = "", expect_pq_key: str = "", require_pq: bool = False, require_time: bool = False, expect_ak: str = "", expect_nonce: str = "", boot_reference: Optional[List[str]] = None, require_hardware: bool = False, require_ima: bool = False, ima_log: Any = None) -> Tuple[bool, Dict[str, Any]]: """An assessment evidence file: several receipts, one per step, linked in order, plus the artifacts each receipt fingerprints. Four guarantees, reported separately: receipts_ok, identity_ok (None = not checked), chain_ok, artifacts_ok.""" reasons: List[str] = [] evidence = _d(evidence) receipts = evidence.get("receipts") artifacts = _d(evidence.get("artifacts")) if not isinstance(receipts, list) or not receipts: v = {"valid": False, "receipts_ok": False, "identity_ok": None, "chain_ok": False, "artifacts_ok": False, "steps": [], "reasons": ["no receipts in the file"]} return False, v receipts_ok, chain_ok, artifacts_ok = True, True, True pq_sealed = hw_present = hw_verified = hw_unpinned = boot_matched = time_sealed = 0 ima_present = ima_verified = 0 # one log for the run (each receipt replays its prefix): the file's own, else --ima-log ima_log = evidence.get("ima_log") if evidence.get("ima_log") is not None else ima_log tpm_ids: set = set() ids: List[Optional[bool]] = [] steps: List[Any] = [] prev = None for i, raw in enumerate(receipts): r = _d(raw) try: _, v = verify(r, expect_key=expect_key, expect_pq_key=expect_pq_key, require_pq=require_pq, require_time=require_time, expect_ak=expect_ak, expect_nonce=expect_nonce, boot_reference=boot_reference, require_hardware=require_hardware, ima_log=ima_log, require_ima=require_ima) except Exception as e: # a malformed receipt is a failed receipt v = {"integrity_ok": False, "identity_ok": None, "reasons": [f"malformed: {e}"]} pq_v = v.get("pq_authenticity_ok") pq_sealed += pq_v is True pq_bad = pq_v is False or (require_pq and pq_v is not True) t_v = v.get("time_ok") time_bad = t_v is False or (require_time and t_v is not True) hw_v = v.get("hardware_authenticity_ok") hw_present += isinstance(r.get("hardware_seal"), dict) hw_verified += hw_v is True hw_unpinned += isinstance(r.get("hardware_seal"), dict) and hw_v is None boot_matched += hw_v is True and v.get("boot_state_ok") is True time_sealed += t_v is True if hw_v is True: tpm_ids.add(str(_d(v.get("hardware")).get("ak_fingerprint"))) hw_bad = (hw_v is False or (require_hardware and hw_v is not True) or v.get("boot_state_ok") is False) i_v = v.get("ima_ok") ima_present += isinstance(r.get("ima_seal"), dict) ima_verified += i_v is True ima_bad = i_v is False or (require_ima and i_v is not True) pq_bad = pq_bad or time_bad or hw_bad or ima_bad # any one fails the receipt; reasons say which if not (v.get("integrity_ok") and v.get("claim_binding_ok") and v.get("authenticity_ok")) \ or pq_bad: receipts_ok = False rs = v.get("reasons") reasons.append(f"receipt {i}: " + "; ".join(str(x) for x in rs) if isinstance(rs, list) else f"receipt {i}: failed") idv = v.get("identity_ok") if v.get("pq_identity_ok") is False: idv = False ids.append(idv if isinstance(idv, bool) else None) claim = _d(r.get("claim")) meta = _d(claim.get("meta")) steps.append(meta.get("step")) if meta.get("seq") != i or meta.get("prev_receipt") != prev: chain_ok = False reasons.append(f"receipt {i}: not linked in order") if meta.get("engagement") != evidence.get("engagement"): chain_ok = False reasons.append(f"receipt {i}: belongs to another engagement") calls = claim.get("tool_calls") or [] step = meta.get("step") if step not in artifacts or not calls: artifacts_ok = False reasons.append(f"receipt {i}: no artifact for step {step!r}") elif calls[0].get("output_fingerprint") != _fingerprint(artifacts[step]): artifacts_ok = False reasons.append(f"step {step!r}: artifact is not the output the receipt sealed") chain = r.get("chain") or [] prev = chain[-1].get("record_hash") if chain and isinstance(chain[-1], dict) else None planned = [_d(_d(_d(r).get("claim")).get("meta")).get("planned_steps") for r in receipts] if not planned or any(p != planned[0] for p in planned) or steps != planned[0]: chain_ok = False reasons.append(f"steps {steps} do not match the sealed plan {planned[0] if planned else None}") extra = set(artifacts) - {x for x in steps if isinstance(x, str)} if extra: artifacts_ok = False reasons.append(f"artifacts with no receipt: {sorted(extra)}") # Inputs: each step's input sits in the file and must match its sealed fingerprint, # and the ranking and the plan must be built from THIS inventory (data flow, not just # ordering). inputs = _d(evidence.get("inputs")) for r in receipts: claim = _d(_d(r).get("claim")) step = _d(claim.get("meta")).get("step") calls = claim.get("tool_calls") or [] if step not in inputs or not calls or calls[0].get("args_fingerprint") != _fingerprint(inputs[step]): artifacts_ok = False reasons.append(f"step {step!r}: input missing or not the input the receipt sealed") if set(inputs) - {s for s in steps if isinstance(s, str)}: artifacts_ok = False reasons.append("inputs with no receipt") inv_cbom = _d(artifacts.get("inventory")).get("cbom") for step in ("rank", "plan"): if step in inputs and "inventory" in artifacts: used = _d(inputs[step]).get("cbom") if used is None or _fingerprint(used) != _fingerprint(inv_cbom): chain_ok = False reasons.append(f"the {step} was not built from this file's inventory") if evidence.get("evidence_version") != _EVIDENCE_VERSION: chain_ok = False reasons.append(f"unsupported evidence_version {evidence.get('evidence_version')!r}") identity_ok: Optional[bool] = (False if any(x is False for x in ids) else True if all(x is True for x in ids) else None) valid = receipts_ok and chain_ok and artifacts_ok and identity_ok is not False return valid, {"valid": valid, "receipts_ok": receipts_ok, "identity_ok": identity_ok, "chain_ok": chain_ok, "artifacts_ok": artifacts_ok, "steps": steps, "pq_sealed_receipts": pq_sealed, "hardware_sealed_receipts": hw_present, "hardware_verified_receipts": hw_verified, "hardware_unpinned_receipts": hw_unpinned, "tpm_identities": sorted(tpm_ids), "boot_state_matched_receipts": boot_matched, "time_sealed_receipts": time_sealed, "ima_sealed_receipts": ima_present, "ima_verified_receipts": ima_verified, "reasons": reasons} # ── A policy the VERIFIER brings (2026-11-07) ────────────────────────────────────── # A receipt proves the record is unchanged; it does not say the engagement met a policy. The AI # Family (d0334db59ce6) warned that a policy signed by the issuer proves nothing, so the policy here # is the relying party's own file, read like --expect-key: which keys may sign, which seals each # receipt must carry, which TPM identities and boot states are acceptable, and which steps, in # which order, an evidence file must have. Every receipt is verified again under the pins the # policy implies, and the result is `policy_ok`, apart from the rest. The schema is strict: an # unknown field, or a requirement without the keys to check it against, is refused, so a typo can # never quietly loosen the policy. It proves the evidence meets the policy you wrote. It does not # prove the policy is right, or that a step that was never recorded did not happen. POLICY_VERSION = 1 _POLICY_FIELDS = {"counterfoil_policy", "name", "issuer_keys", "pq_keys", "tpm_identities", "boot_states", "require", "min_time_authorities", "steps", "engagement"} _POLICY_REQUIRE = {"post_quantum", "trusted_time", "hardware"} def _hexlen(v: Any, *lengths: int) -> bool: return (isinstance(v, str) and len(v) in lengths and all(c in "0123456789abcdef" for c in v.lower())) _POLICY_MAX_BYTES = 1 << 20 def load_policy(path: str) -> Tuple[Optional[Dict[str, Any]], str]: """(policy, "") or (None, why it is refused). Keys are normalised to lower case. The policy carries `_sha256`, the hash of exactly the bytes that were parsed.""" try: with open(path, "rb") as fh: raw = fh.read(_POLICY_MAX_BYTES + 1) if len(raw) > _POLICY_MAX_BYTES: return None, "the policy is larger than 1 MiB" doc = json.loads(raw) except (OSError, ValueError) as e: return None, f"cannot read the policy: {type(e).__name__}" if not isinstance(doc, dict): return None, "the policy is not a JSON object" unknown = set(doc) - _POLICY_FIELDS if unknown: return None, f"unknown policy field(s) {sorted(unknown)}: refused, so a typo cannot loosen it" if doc.get("counterfoil_policy") != POLICY_VERSION: return None, f"counterfoil_policy must be {POLICY_VERSION}" req = doc.get("require", {}) if not isinstance(req, dict) or set(req) - _POLICY_REQUIRE \ or not all(isinstance(v, bool) for v in req.values()): return None, f"require takes true or false for {sorted(_POLICY_REQUIRE)}" keys = doc.get("issuer_keys") if not (isinstance(keys, list) and keys and all(_hexlen(k, 16, 64) for k in keys)): return None, "issuer_keys must list at least one Ed25519 public key (64 hex) or fingerprint (16 hex)" for name, lengths, needed_by in (("pq_keys", (16, 64), "post_quantum"), ("tpm_identities", (), "hardware")): vals = doc.get(name) if vals is None: if req.get(needed_by): return None, f"require.{needed_by} needs {name} to check it against" continue ok = isinstance(vals, list) and vals and all( _hexlen(v, *lengths) if lengths else (isinstance(v, str) and v.lower().startswith("sha256:") and _hexlen(v[7:], 64)) for v in vals) if not ok: return None, f"{name} is malformed" states = doc.get("boot_states") if states is not None and not (isinstance(states, list) and states and all( isinstance(st, list) and len(st) == len(_HW_PCR_INDICES) and all(_hexlen(h, 64) for h in st) for st in states)): return None, "boot_states must be a list of lists of eight SHA-256 values (PCR 0-7)" if states is not None and not doc.get("tpm_identities"): return None, "boot_states need tpm_identities: a boot state is only read from a pinned TPM" mta = doc.get("min_time_authorities", 1) if mta not in (1, 2): return None, "min_time_authorities is 1 or 2" steps = doc.get("steps") if steps is not None and not (isinstance(steps, list) and steps and all(isinstance(x, str) for x in steps)): return None, "steps must be a list of step names" if "engagement" in doc and not isinstance(doc["engagement"], str): return None, "engagement must be a string" if "name" in doc and not isinstance(doc["name"], str): return None, "name must be a string" def low(vs: Any) -> Any: return [v.lower() for v in vs] if vs else vs pol = dict(doc, issuer_keys=low(keys), pq_keys=low(doc.get("pq_keys")), tpm_identities=low(doc.get("tpm_identities")), boot_states=[low(st) for st in states] if states else None, require={k: bool(req.get(k)) for k in sorted(_POLICY_REQUIRE)}, min_time_authorities=mta, _sha256=hashlib.sha256(raw).hexdigest()) return pol, "" def _policy_pins(r: Dict[str, Any], pol: Dict[str, Any]) -> Tuple[Dict[str, Any], List[str]]: """The pins to verify one receipt under, chosen from the policy's lists, and why not.""" why: List[str] = [] seal = _d(r.get("seal")) pub, fp = str(seal.get("public_key", "")).lower(), str(seal.get("key_fingerprint", "")).lower() key = next((k for k in pol["issuer_keys"] if k in (pub, fp)), None) if key is None: why.append(f"signed by key {fp or '?'}, which the policy does not allow") pins: Dict[str, Any] = {"expect_key": key or ("0" * 64), "expect_pq_key": "", "expect_ak": "", "boot_reference": None} pq = r.get("pq_seal") if isinstance(pq, dict) and pol.get("pq_keys"): pq_fp = str(pq.get("key_fingerprint", "")).lower() try: pq_full = hashlib.sha3_256(bytes.fromhex(str(pq.get("public_key", "")))).hexdigest() except ValueError: pq_full = "" match = next((k for k in pol["pq_keys"] if k in (pq_fp, pq_full)), None) if match is None: why.append(f"post-quantum key {pq_fp or '?'} is not one the policy allows") pins["expect_pq_key"] = match or ("0" * 64) hw = r.get("hardware_seal") if isinstance(hw, dict) and pol.get("tpm_identities"): ak = str(_d(hw.get("ak")).get("fingerprint", "")).lower() if ak not in pol["tpm_identities"]: why.append(f"TPM identity {ak or '?'} is not one the policy allows") pins["expect_ak"] = ak if ak in pol["tpm_identities"] else "sha256:" + "0" * 64 if pol.get("boot_states"): quoted = [str(h).lower() for h in _d(hw.get("quote")).get("pcr_values_hex", [])] pins["boot_reference"] = next((st for st in pol["boot_states"] if st == quoted), pol["boot_states"][0]) return pins, why def verify_with_policy(doc: Dict[str, Any], pol: Dict[str, Any]) -> Tuple[bool, Dict[str, Any]]: """Verify a receipt or an evidence file against the verifier's policy. `policy_ok` is the policy's own answer; `valid` requires it and every receipt to verify under its pins.""" failures: List[str] = [] req = pol["require"] evidence = "receipts" in doc receipts = [_d(x) for x in doc.get("receipts") or []] if evidence else [doc] if not receipts: failures.append("no receipts") per: List[Dict[str, Any]] = [] for i, r in enumerate(receipts): pins, why = _policy_pins(r, pol) failures += [f"receipt {i}: {w}" for w in why] try: ok_i, v = verify(r, require_pq=req["post_quantum"], require_time=req["trusted_time"] and pol["min_time_authorities"] == 2, require_hardware=req["hardware"], **pins) except Exception as e: # a receipt of an unexpected shape fails the policy, never crashes ok_i, v = False, {"reasons": [f"malformed: {type(e).__name__}"]} if req["trusted_time"]: n_auth = len(v.get("time_authorities") or []) if v.get("time_ok") is True else 0 if n_auth < pol["min_time_authorities"]: failures.append(f"receipt {i}: the policy requires trusted time from " f"{pol['min_time_authorities']} authority(ies), and {n_auth} verified") if not ok_i: failures.append(f"receipt {i}: does not verify under the policy's pins: " + "; ".join(str(x) for x in v.get("reasons", [])[:3])) per.append(v) out: Dict[str, Any] = {"name": pol.get("name"), "receipts": len(receipts)} if evidence: _, ev = verify_evidence(doc) if not (ev.get("chain_ok") and ev.get("artifacts_ok")): failures.append("evidence: the receipts are not linked in order with their artifacts") out["steps"] = ev.get("steps") if pol.get("steps") is not None and ev.get("steps") != pol["steps"]: failures.append(f"evidence: steps {ev.get('steps')} are not the policy's {pol['steps']}") if "engagement" in pol and doc.get("engagement") != pol["engagement"]: failures.append(f"evidence: engagement {doc.get('engagement')!r} is not the policy's") elif pol.get("steps") is not None or "engagement" in pol: failures.append("the policy names steps or an engagement, and this is a single receipt") out["failures"] = failures ok = not failures out["policy_ok"] = ok return ok, {"valid": ok, "policy_ok": ok, "policy": out, "receipts_checked": [{k: v.get(k) for k in ( "valid", "identity_ok", "pq_authenticity_ok", "pq_identity_ok", "time_ok", "hardware_authenticity_ok", "boot_state_ok")} for v in per], "reasons": failures} ATTESTATION_KIND = "counterfoil-recomputation-attestation" ATTESTATION_VERSION = "2" # 2: the verdict carries every per-seal field; 1 predates them def attest(receipt: Dict[str, Any], verdict: Dict[str, Any], *, label: str, key_path: str) -> Dict[str, Any]: """Sign the verdict this file just computed, with the verifier's own key. Byte-compatible with the studio's recomputation ledger: the signature covers the whole attestation minus the signature, canonicalised the same way as every other hash here. """ from cryptography.hazmat.primitives import serialization from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey import datetime import os import secrets import stat chain = receipt.get("chain") or [] if not isinstance(chain, list) or not chain or not isinstance(chain[-1], dict) \ or not str(chain[-1].get("record_hash", "")): raise ValueError("cannot attest: the receipt has no chain ending in a record_hash, " "so there is nothing to name as the subject") if not str(label).strip(): raise ValueError("cannot attest: --attest needs a label saying who you are") if os.path.exists(key_path): mode = stat.S_IMODE(os.stat(key_path).st_mode) if mode & 0o077: raise ValueError(f"refusing to use {key_path}: it is readable by others " f"(mode {oct(mode)}). chmod 600 it, or pass a different --key") with open(key_path, "rb") as fh: loaded = serialization.load_pem_private_key(fh.read(), password=None) if not isinstance(loaded, Ed25519PrivateKey): raise ValueError(f"{key_path} is not an Ed25519 key, and an attestation is signed " f"with Ed25519. Point --key somewhere else.") private = loaded created = False else: private = Ed25519PrivateKey.generate() with open(key_path, "wb") as fh: fh.write(private.private_bytes( encoding=serialization.Encoding.PEM, format=serialization.PrivateFormat.PKCS8, encryption_algorithm=serialization.NoEncryption())) os.chmod(key_path, stat.S_IRUSR | stat.S_IWUSR) created = True pub_raw = private.public_key().public_bytes( encoding=serialization.Encoding.Raw, format=serialization.PublicFormat.Raw) ra: Dict[str, Any] = { "kind": ATTESTATION_KIND, "version": ATTESTATION_VERSION, "subject": str(chain[-1].get("record_hash", "")), "receipt_hash": _payload_hash(receipt), "issuer_key_fingerprint": (receipt.get("seal") or {}).get("key_fingerprint"), "verdict": { "valid": bool(verdict["valid"]), "integrity_ok": bool(verdict["integrity_ok"]), "claim_binding_ok": bool(verdict["claim_binding_ok"]), "authenticity_ok": bool(verdict["authenticity_ok"]), # As computed above, under the pins this run used (the studio's agreement # check leaves it out: two honest runs may pin different TPM identities). "hardware_authenticity_ok": verdict.get("hardware_authenticity_ok"), # Each seal keeps its own result, exactly as computed above: null (and an # empty authority list) means the receipt carries no such seal, never # that the check was skipped. "pq_authenticity_ok": verdict.get("pq_authenticity_ok"), "pq_key_fingerprint": verdict.get("pq_key_fingerprint"), "time_ok": verdict.get("time_ok"), "time_bound": verdict.get("time_bound"), "time_authorities": list(verdict.get("time_authorities") or []), }, "verifier": { "label": str(label), "public_key": pub_raw.hex(), "key_fingerprint": _key_fingerprint(pub_raw), }, "nonce": secrets.token_hex(16), "recomputed_ns": datetime.datetime.now(datetime.timezone.utc).isoformat(), } payload = {k: v for k, v in ra.items() if k != "signature"} ra["signature"] = private.sign(_payload_hash(payload).encode()).hex() ra["_key_created"] = created return ra def benchmark(vectors: Dict[str, Any]) -> Dict[str, Any]: """Run THIS verifier over the published adversarial vector set (M5). The point is that you can reproduce the coverage number yourself with two public downloads and no access to our repo: this file and the vectors file. Detection here is deterministic, because every check is exact: an attack class either always fails verification or is out of scope. So this reports COVERAGE over named attacks, never an invented false-positive rate. Since 2026-11-07 this file checks hardware seals, so `hardware_authenticity_ok` is scored like any other expectation; any key the verdict lacks stays out of scope. The same holds for the post-quantum seal on a machine whose cryptography cannot do ML-DSA-65: every vector carrying a pq_seal is out of scope there, never scored. Its receipts fail closed, so counting the ones expected to fail as detections would credit the missing library, and counting the ones expected to pass as misses would blame the checker for a check it could not run. """ import copy as _copy rows: List[Dict[str, Any]] = [] out_of_scope: Dict[str, int] = {} pq_ok = pq_available() for v in vectors.get("vectors", []): if not pq_ok and isinstance(v.get("receipt"), dict) and "pq_seal" in v["receipt"]: out_of_scope["pq_seal"] = out_of_scope.get("pq_seal", 0) + 1 rows.append({"name": v.get("name"), "attack": v.get("attack"), "status": "out_of_scope", "detected": False, "mismatched": {}, "error": None}) continue expected = dict(v.get("expected", {})) kwargs = v.get("verify_kwargs", {}) or {} expect_key = kwargs.get("expected_fingerprint", "") try: _ok, verdict = verify(_copy.deepcopy(v["receipt"]), expect_key=expect_key, expect_pq_key=kwargs.get("expected_pq_fingerprint") or "", require_pq=bool(kwargs.get("require_pq")), require_time=bool(kwargs.get("require_time")), expect_nonce=kwargs.get("expected_nonce") or "", expect_ak=kwargs.get("expected_ak") or "") error = None except Exception as exc: # a crashing verifier is a failing verifier verdict, error = {}, f"{type(exc).__name__}: {exc}" mismatched = {} in_scope = 0 for key, want in expected.items(): if key not in verdict: out_of_scope[key] = out_of_scope.get(key, 0) + 1 continue in_scope += 1 if verdict[key] != want: mismatched[key] = {"expected": want, "got": verdict[key]} # A vector whose every expectation is out of scope is NOT a detection. Counting # it as one would inflate the number with attacks this verifier cannot even # evaluate, so it is reported separately and left out of the denominator. if in_scope == 0 and error is None: status = "out_of_scope" elif mismatched or error is not None: status = "undetected" else: status = "detected" rows.append({"name": v.get("name"), "attack": v.get("attack"), "status": status, "detected": status == "detected", "mismatched": mismatched, "error": error}) detected = [r for r in rows if r["status"] == "detected"] undetected = [r["name"] for r in rows if r["status"] == "undetected"] skipped = [r["name"] for r in rows if r["status"] == "out_of_scope"] scored = len(detected) + len(undetected) return { "benchmark": "counterfoil-conformance (standalone verifier)", "verifier": "verify_counterfoil.py", "vectors_version": vectors.get("vectors_version"), "attack_vectors": len(rows), "scored": scored, "detected": len(detected), "detection_rate": round(len(detected) / scored, 4) if scored else None, # Panel ac2d5b07 split over whether an unevaluable vector belongs in the # denominator. Both numbers are reported rather than picking one and arguing: # `detection_rate` is over what this verifier can evaluate, and # `coverage_of_all_vectors` counts every vector in the set, so a reader who # thinks an out-of-scope attack is a miss gets that number too. "coverage_of_all_vectors": round(len(detected) / len(rows), 4) if rows else None, "undetected": undetected, "not_scored": skipped, "deterministic": True, "out_of_scope": {k: (f"{n} vector(s) carry it; this machine's cryptography cannot " "verify ML-DSA-65 (pip install -U cryptography)" if k == "pq_seal" else f"{n} vector(s) expect it; this verifier does not check it") for k, n in sorted(out_of_scope.items())}, "pq_checked": pq_ok, "note": ("Coverage over named attack classes, not a probabilistic FP/FN rate: " "every check here is exact. `scored` is the denominator: a vector whose " "expectations this verifier cannot evaluate at all is listed in " "`not_scored` rather than counted as a detection. Reproduce it with this " "file plus the published vectors file, no repo access and no secret."), "rows": rows, } MAX_INPUT_BYTES = 64 * 1024 * 1024 # far above any receipt or evidence file we issue def _read_json(path: str) -> Tuple[Any, Optional[str], int, bytes]: """(value, problem, exit code, the exact bytes read). A file that cannot be read or parsed is a result, never a crash: exit 2 when it cannot be read at all, 1 when it is not a receipt. The bytes are returned so a caller hashes what was parsed, not a second read.""" try: with open(path, "rb") as fh: raw = fh.read(MAX_INPUT_BYTES + 1) except OSError as e: return None, f"cannot read {path}: {e.strerror or e}", 2, b"" if len(raw) > MAX_INPUT_BYTES: return None, f"larger than {MAX_INPUT_BYTES // (1024 * 1024)} MB, so not a receipt", 1, b"" try: return json.loads(raw.decode("utf-8")), None, 0, raw except UnicodeDecodeError: return None, "not UTF-8 text, so not a receipt", 1, raw except (RecursionError, MemoryError): return None, "JSON nested too deeply or too large to be a receipt", 1, raw except ValueError as e: where = f" at line {e.lineno}" if hasattr(e, "lineno") else "" return None, f"not valid JSON ({getattr(e, 'msg', e)}{where})", 1, raw def _main(argv: List[str]) -> int: expect = PUBLISHED_PUBLIC_KEY expect_pq = PUBLISHED_PQ_KEY_SHA3 expect_ak = PUBLISHED_AK_FINGERPRINT expect_nonce = "" boot_reference: Optional[List[str]] = None any_key = "--any-key" in argv # naming a TPM identity, a nonce or a boot state is asking for a hardware seal require_hardware = "--require-hardware" in argv or any( f in argv for f in ("--expect-ak", "--expect-nonce", "--expect-boot-state")) require_pq = "--require-pq" in argv require_time = "--require-time" in argv # naming an IMA log is asking for runtime measurement require_ima = "--require-ima" in argv or "--ima-log" in argv ima_log: Any = None consumed = set() label = key_path = out_path = None for i, a in enumerate(argv): if a == "--expect-key" and i + 1 < len(argv) and not argv[i + 1].startswith("--"): expect = argv[i + 1] consumed.add(i + 1) # a different classical identity is a different issuer: our post-quantum # pin no longer applies unless it is named too. Naming OUR key keeps it. named = expect.strip().lower() if "--expect-pq-key" not in argv and named not in (PUBLISHED_PUBLIC_KEY, PUBLISHED_FINGERPRINT): expect_pq = "" if "--expect-ak" not in argv and named not in (PUBLISHED_PUBLIC_KEY, PUBLISHED_FINGERPRINT): expect_ak = "" if a == "--expect-pq-key": if i + 1 >= len(argv) or argv[i + 1].startswith("--"): sys.stderr.write("--expect-pq-key needs a value\n") return 2 expect_pq = argv[i + 1] consumed.add(i + 1) pin = expect_pq.strip().lower() if len(pin) not in (16, 64) or not all(c in "0123456789abcdef" for c in pin): sys.stderr.write("--expect-pq-key takes the 16-character fingerprint or the " "64-character SHA3-256 of the post-quantum key, in hex\n") return 2 # naming a post-quantum key is asking for one: a receipt without the seal # cannot match it, so it must not pass as if the pin had been compared require_pq = True if a in ("--expect-ak", "--expect-nonce", "--expect-boot-state"): if i + 1 >= len(argv) or argv[i + 1].startswith("--"): sys.stderr.write(f"{a} needs a value\n") return 2 val = argv[i + 1] consumed.add(i + 1) if a == "--expect-ak": v = val.strip().lower() if not (v.startswith("sha256:") and len(v) == 71 and all(c in "0123456789abcdef" for c in v[7:])): sys.stderr.write("--expect-ak takes the TPM identity as sha256:<64 hex>\n") return 2 expect_ak = v elif a == "--expect-nonce": v = val.strip().lower() if not (32 <= len(v) <= 64 and len(v) % 2 == 0 and all(c in "0123456789abcdef" for c in v)): sys.stderr.write("--expect-nonce takes the 16 to 32 byte nonce you supplied, in hex\n") return 2 expect_nonce = v else: boot_reference = _boot_reference(val) if boot_reference is None: sys.stderr.write("--expect-boot-state takes a JSON file with " '{"pcr_sha256": [8 hex SHA-256 values for PCR 0-7]}\n') return 2 if a == "--ima-log": if i + 1 >= len(argv) or argv[i + 1].startswith("--"): sys.stderr.write("--ima-log needs a file (the receipt's IMA log, template hashes only)\n") return 2 consumed.add(i + 1) ima_log, why_log, _c, _r = _read_json(argv[i + 1]) if why_log is not None or not isinstance(ima_log, dict): sys.stderr.write(f"--ima-log: {why_log or 'not a JSON object'}\n") return 2 for flag, target in (("--attest", "label"), ("--key", "key_path"), ("--out", "out_path")): if a == flag: if i + 1 >= len(argv) or argv[i + 1].startswith("--"): sys.stderr.write(f"{flag} needs a value\n") return 2 if target == "label": label = argv[i + 1] elif target == "key_path": key_path = argv[i + 1] else: out_path = argv[i + 1] consumed.add(i + 1) args = [a for i, a in enumerate(argv) if i not in consumed and not a.startswith("--")] if "--benchmark" in argv: if not args: sys.stderr.write("usage: verify_counterfoil.py --benchmark \n") return 2 vectors, problem, code, raw = _read_json(args[0]) if problem is None and not isinstance(vectors, dict): problem, code = "the vectors file is not a JSON object", 1 if problem is not None: sys.stderr.write(f"FAIL: {problem}\n") return code try: report = benchmark(vectors) except Exception as e: # a vectors file of an unexpected shape fails, it never crashes sys.stderr.write(f"FAIL: not a vectors file this checker can run: {type(e).__name__}: {e}\n") return 1 digest = hashlib.sha256(raw).hexdigest() # the bytes that were parsed report["vectors_sha256"] = digest rows = report.pop("rows") print(json.dumps(report, indent=2, sort_keys=True)) marks = {"detected": "ok ", "undetected": "MISS", "out_of_scope": "skip"} for row in rows: print(f" {marks[row['status']]} {row['name']}: {row['attack']}", file=sys.stderr) if report["undetected"]: print(f"FAIL: {len(report['undetected'])} vector(s) not detected", file=sys.stderr) return 1 skipped = len(report["not_scored"]) tail = f", {skipped} out of scope and not scored" if skipped else "" print(f"PASS: {report['detected']}/{report['scored']} named attacks detected{tail}, " f"vectors {digest[:16]}\u2026", file=sys.stderr) return 0 policy_path = None want_policy_sha = "" if "--policy-sha256" in argv and "--policy" not in argv: sys.stderr.write("--policy-sha256 goes with --policy\n") return 2 if "--policy" in argv: i = argv.index("--policy") if i + 1 >= len(argv) or argv[i + 1].startswith("--"): sys.stderr.write("--policy needs a file\n") return 2 policy_path = argv[i + 1] args = [a for a in args if a != policy_path] # A signed in-toto layout names the exact policy it was made from (counterfoil_intoto), # so a different policy.json beside the evidence cannot pass in its place. if "--policy-sha256" in argv: j = argv.index("--policy-sha256") want_policy_sha = argv[j + 1].lower() if j + 1 < len(argv) else "" if len(want_policy_sha) != 64 or any(c not in "0123456789abcdef" for c in want_policy_sha): sys.stderr.write("--policy-sha256 takes the 64-character SHA-256 of the policy file\n") return 2 args = [a for a in args if a.lower() != want_policy_sha] clash = [f for f in ("--any-key", "--expect-key", "--expect-pq-key", "--expect-ak", "--expect-nonce", "--expect-boot-state", "--require-pq", "--require-time", "--require-hardware", "--require-ima", "--ima-log", "--attest") if f in argv] if clash: sys.stderr.write(f"--policy sets the keys and requirements itself; drop {', '.join(clash)}\n") return 2 if any_key and ("--expect-key" in argv or "--expect-pq-key" in argv or "--expect-ak" in argv): sys.stderr.write("use --expect-key / --expect-pq-key / --expect-ak or --any-key, not both\n") return 2 if any_key: expect = expect_pq = expect_ak = "" if not args: sys.stderr.write("usage: verify_counterfoil.py " "[--expect-key | --any-key] " "[--expect-pq-key ] [--require-pq] [--require-time] " "[--expect-ak sha256:] [--expect-nonce ] [--expect-boot-state ] " "[--require-hardware] [--require-ima] [--ima-log ] " "[--policy [--policy-sha256 ]] " "| --benchmark " "[--attest \"your name\" [--key k.pem] [--out attestation.json]]\n") return 2 receipt, problem, code, _raw = _read_json(args[0]) if problem is None and not isinstance(receipt, dict): problem, code = "the top level is not a JSON object, so not a receipt", 1 if problem is not None: print(json.dumps({"valid": False, "reasons": [problem], "expected_key": expect or None}, indent=2)) sys.stderr.write(f"FAIL: {problem}\n") return code if policy_path is not None: pol, why = load_policy(policy_path) if pol is None: sys.stderr.write(f"--policy: {why}\n") return 2 policy_sha = pol["_sha256"] if want_policy_sha and want_policy_sha != policy_sha: sys.stderr.write(f"FAIL: the policy file is not the one named (its SHA-256 is {policy_sha}, " f"expected {want_policy_sha})\n") return 1 ok, verdict = verify_with_policy(receipt, pol) verdict["policy"]["sha256"] = policy_sha print(json.dumps(verdict, indent=2, sort_keys=True)) name = pol.get("name") or "your policy" if ok: print(f"PASS: meets {name} (policy {policy_sha[:16]}), {verdict['policy']['receipts']} " "receipt(s) verified under its keys and requirements. It proves the evidence " "meets the policy you wrote, not that the policy is right", file=sys.stderr) else: print(f"FAIL: does not meet {name} (policy {policy_sha[:16]})", file=sys.stderr) for f in verdict["reasons"][:12]: print(f" - {f}", file=sys.stderr) return 0 if ok else 1 try: if "receipts" in receipt: ok, verdict = verify_evidence(receipt, expect_key=expect, expect_pq_key=expect_pq, require_pq=require_pq, require_time=require_time, expect_ak=expect_ak, expect_nonce=expect_nonce, boot_reference=boot_reference, require_hardware=require_hardware, require_ima=require_ima, ima_log=ima_log) verdict["key_fingerprint"] = None else: ok, verdict = verify(receipt, expect_key=expect, expect_pq_key=expect_pq, require_pq=require_pq, require_time=require_time, expect_ak=expect_ak, expect_nonce=expect_nonce, boot_reference=boot_reference, require_hardware=require_hardware, ima_log=ima_log, require_ima=require_ima) except Exception as e: # a shape no check anticipated fails, it never crashes the checker ok, verdict = False, {"valid": False, "reasons": [f"malformed receipt: {type(e).__name__}: {e}"]} if not isinstance(verdict, dict): # never expected; fail closed rather than crash ok, verdict = False, {"valid": False, "reasons": ["the checker produced no verdict"]} verdict["expected_key"] = expect or None verdict["expected_pq_key"] = expect_pq or None try: text = json.dumps(verdict, indent=2) except (TypeError, ValueError) as e: ok, text = False, json.dumps({"valid": False, "reasons": [f"verdict could not be written: {e}"]}, indent=2) print(text) if label is not None: if "receipts" in (receipt if isinstance(receipt, dict) else {}): sys.stderr.write("--attest takes a single receipt, not an evidence file\n") return 2 try: ra = attest(receipt, verdict, label=label, key_path=key_path or "counterfoil_verifier_key.pem") except (ValueError, OSError) as e: sys.stderr.write(f"{e}\n") return 2 created = ra.pop("_key_created") dest = out_path or "attestation.json" with open(dest, "w", encoding="utf-8") as fh: fh.write(json.dumps(ra, indent=2, sort_keys=True)) if created: print(f"made a new signing key at {key_path or 'counterfoil_verifier_key.pem'} " f"(keep it if you want later attestations to come from the same identity)", file=sys.stderr) print(f"wrote {dest}: verifier {ra['verifier']['key_fingerprint']} over subject " f"{ra['subject'][:16]}…, verdict valid={ra['verdict']['valid']}. Nothing was sent " f"anywhere. Send it to contact@matrixcr.ai to have it counted, or publish it " f"yourself.", file=sys.stderr) if not ok: print("FAIL", file=sys.stderr) elif verdict["identity_ok"] is None: print(f"PASS, but the signer identity was NOT checked: sealed by key " f"{verdict.get('key_fingerprint') or 'as named in each receipt'}. Drop --any-key to require the " f"Matrix CR Studio key ({PUBLISHED_FINGERPRINT}).", file=sys.stderr) else: what = (f"{len(verdict['steps'])} linked steps" if "steps" in verdict else f"key {verdict['key_fingerprint']}") how = (", full public key matched" if len(expect.strip()) == 64 else " (identity matched on the 16-character fingerprint only, which is 64 bits; " "give --expect-key the full 64-character public key for an exact match)") print(f"PASS: intact, and sealed by {what}{how}", file=sys.stderr) if ok: pqv = verdict.get("pq_authenticity_ok") if pqv is True: pinned = (verdict.get("expected_pq_key") or "").lower() fp_pq = verdict.get("pq_key_fingerprint") if verdict.get("pq_identity_ok") is not True: who = f"post-quantum key {fp_pq}, identity NOT checked" elif PUBLISHED_PQ_KEY_SHA3 and pinned in (PUBLISHED_PQ_KEY_SHA3, PUBLISHED_PQ_KEY_SHA3[:16]): who = "the published post-quantum key" else: who = f"post-quantum key {fp_pq}, as you expected" if verdict.get("pq_identity_ok") is True and len(pinned) == 16: who += " (matched on the 16-character fingerprint only)" print(f" post-quantum seal (ML-DSA-65) verified, {who}", file=sys.stderr) elif "pq_sealed_receipts" in verdict: n, total = verdict["pq_sealed_receipts"], len(verdict.get("steps") or []) if n == 0: print(f" classical seals only (Ed25519). None of the {total} receipts carries a " "post-quantum seal; --require-pq would fail this file", file=sys.stderr) else: print(f" post-quantum seal (ML-DSA-65) verified on {n} of {total} receipts" + ("" if n == total else "; the others are classical only, and --require-pq would fail this file"), file=sys.stderr) elif "pq_authenticity_ok" in verdict: print(" classical seal only (Ed25519). No post-quantum seal on this receipt; " "--require-pq refuses receipts like this one", file=sys.stderr) # Said where people read it, not only in the JSON (AI Family, 2026-11-07). Only when a # seal verified: a failed one already says so, and this line must not read as assurance. builtin_checked = (verdict.get("pq_verified_by") == PQ_ENGINE_BUILTIN if "pq_verified_by" in verdict else bool(verdict.get("pq_sealed_receipts")) and pq_engine() == PQ_ENGINE_BUILTIN) if builtin_checked and verdict.get("pq_authenticity_ok") is not False: print(" the post-quantum check was done by this file's own FIPS 204 code, because " "the cryptography package here could not check ML-DSA. That code is not a " "validated module. For a check you rely on, run this file where cryptography " "has ML-DSA, and the library does it", file=sys.stderr) if verdict.get("hardware_authenticity_ok") is True: hwd = verdict.get("hardware") or {} # True needs a matched TPM identity (see verify), so this names the expected one print(f" TPM seal verified: a key that cannot leave TPM {hwd.get('ak_fingerprint')}, " "the identity you expect, signed this record while PCR 0-7 held the quoted values", file=sys.stderr) boot = verdict.get("boot_state_ok") if boot is True: print(" boot state: PCR 0-7 match the reference you gave", file=sys.stderr) elif boot is None: print(" boot state: not compared to a reference, so this says the chip signed in " "some boot state, not a good one (--expect-boot-state)", file=sys.stderr) elif verdict.get("hardware_seal_present") and verdict.get("hardware_authenticity_ok") is None: print(" TPM seal: self-consistent, but not compared to a TPM identity, so not reported " "as hardware (--expect-ak)", file=sys.stderr) if "hardware_sealed_receipts" in verdict: # an evidence file: one line per seal kind total = len(verdict.get("steps") or []) hv = verdict["hardware_verified_receipts"] if hv: print(f" TPM seal verified on {hv} of {total} receipts: a key that cannot leave TPM " f"{', '.join(verdict.get('tpm_identities') or [])}, the identity you expect, " "signed each one while PCR 0-7 held the quoted values", file=sys.stderr) if verdict.get("boot_state_matched_receipts") == hv: print(" boot state: PCR 0-7 match the reference you gave on each of them", file=sys.stderr) else: print(" boot state: not compared to a reference, so this says the chip signed in " "some boot state, not a good one (--expect-boot-state)", file=sys.stderr) hu = verdict.get("hardware_unpinned_receipts", 0) if hu: print(f" TPM seal on {hu} of {total} receipts: self-consistent, but not compared " "to a TPM identity, so not reported as hardware (--expect-ak)", file=sys.stderr) tn = verdict.get("time_sealed_receipts", 0) if tn: print(f" time: trusted time (RFC 3161, pinned roots) verified on {tn} of {total} receipts", file=sys.stderr) else: print(" time: no trusted time on these receipts, so their dates are the issuer's own " "clock; --require-time refuses files like this one", file=sys.stderr) if verdict.get("ima_ok") is True: im = verdict.get("ima") or {} print(f" runtime: {im.get('entry_count')} IMA log entries replay to the PCR 10 this TPM " "quoted after the record existed; the log is this boot's (boot_aggregate)" + ("; the published IMA policy file was measured in that boot" if im.get("policy_ok") else "; no policy entry was disclosed"), file=sys.stderr) print(" runtime: presence, not absence. Only the disclosed entries are shown; nothing " "else can be shown absent, and this says nothing about which tool code ran", file=sys.stderr) elif verdict.get("ima") is not None and verdict.get("ima_ok") is None: print(" runtime: the IMA quote verifies, but the log was not replayed or no TPM " "identity was compared, so it is not reported (--ima-log, --expect-ak)", file=sys.stderr) if verdict.get("ima_sealed_receipts"): total = len(verdict.get("steps") or []) print(f" runtime: IMA log replayed to the quoted PCR 10 on {verdict['ima_verified_receipts']} " f"of {total} receipts. Presence, not absence; nothing about which tool code ran", file=sys.stderr) if verdict.get("time_ok") is True: auths = verdict.get("time_authorities") or [] print(f" time: existed no later than {verdict.get('time_bound')}, by " f"{' and '.join(auths)} (RFC 3161, pinned roots)" + ("" if len(auths) >= 2 else "; one authority only, so this time rests on that one operator"), file=sys.stderr) elif "time_ok" in verdict: print(" time: no trusted time on this receipt, so its date is the issuer's own " "clock; --require-time refuses receipts like this one", file=sys.stderr) return 0 if ok else 1 if __name__ == "__main__": raise SystemExit(_main(sys.argv[1:]))