#!/usr/bin/env python3
# SPDX-License-Identifier: MIT
# Copyright (c) 2026 Verda
"""tdx-attest — whole CPU-side TDX attestation in one wrapper.

Subcommands:

  quote [nonce] [out.json] [--ita-nonce nonce.json]
          guest: generate a quote bound to the nonce -> JSON envelope (default ./att.json).
          Without a nonce the quote binds 64 zero bytes and proves nothing about freshness.
          --ita-nonce binds an Intel Trust Authority verifier nonce (from `ita-nonce`) instead.
  verify att.json [reference.json] [--nonce NONCE]
          any Ubuntu release Intel's DCAP repo serves: verify the envelope locally (QVL,
          anonymous Intel collateral, no key). Exit 0 only for an accepted TCB verdict, a
          non-debug TD, a bound nonce (the --nonce one, else the envelope's) and, with a
          reference file, matching registers.
  verify-ita att.json <eu|us> [reference.json] [--nonce NONCE] [--json]
          anywhere (incl. macOS): submit the envelope to Intel Trust Authority (ITA) via
          REST, save the signed token next to the envelope, verify the token's signature
          against Intel's published key set (JWKS over TLS, RS*/PS* only), then apply the
          same checks as `verify` to its claims: accepted TCB status, non-debug TD, bound
          nonce (and Intel's verifier nonce when the envelope carries one), reference
          registers. --json prints the verified claims.
  ita-nonce <eu|us> [nonce.json]
          verifier: fetch a fresh verifier nonce from ITA (needs ITA_KEY) for the guest to
          bind with `quote --ita-nonce`; ITA then checks freshness itself and signs the nonce
          into the token. Optional: a nonce you choose with `quote <nonce>` and `--nonce`
          on the verifier side gives the same replay protection without this round trip.
  self-check [reference.json] [--json]
          guest: am I a real TD, what is my TCB status (Intel verdict + advisories),
          what OS was measured (MRTD, RTMR0-3 replayed from the CCEL event log; kernel
          and initrd digests compared to /boot and the command line to /proc/cmdline,
          for both direct boot and GRUB), and does it match the reference file if one
          is given. Human output like the AMD snpguest/measure_boot page;
          --json for everything. Exit 0 = all good.
          A self-check convinces the guest, not a remote party: ship the envelope
          from `quote` to an outside verifier for that.

Self-provisioning: on first run (as root) the tool adds Intel's public DCAP apt repository,
installs its own dependencies from it and writes /etc/sgx_default_qcnl.conf pointing the
verification library at Intel's public collateral service (an existing file is kept as
.bak). TDX_ATTEST_NO_SETUP=1 disables that. No Intel accounts needed except ITA mode
(region-paired attestation key).

Envelope JSON fields: quote (base64), nonce (hex), host_key_hash (hex),
made_in (hostname), made_at (unix), tdx (bool true), and ita_nonce (the verifier nonce
object from `ita-nonce`, only with --ita-nonce). Only the quote is signed: it binds the
nonce through REPORTDATA. host_key_hash, made_in and made_at are informational.

Reference file: {"mrtd": "<hex>", "rtmr0": "<hex>", ...}. Keys are TDREPORT registers
(see TD below, except reportdata), case-insensitive; unknown keys and non-hex values are
errors, so a typo cannot silently pin nothing.

Network: outbound only, to Intel (DCAP apt repository, public collateral service, Trust
Authority API and key set). Nothing listens, nothing reports to Verda. The only credential
is ITA_KEY, read from the environment and never written to disk.

Exit codes: 0 passed, 1 usage or setup error, 2 the evidence did not pass.
"""

__version__ = "0.6.0"

import base64, hashlib, hmac, json, os, re, shutil, struct, subprocess, sys, time
import urllib.error, urllib.request
from binascii import unhexlify
from ctypes import (CDLL, POINTER, byref, c_char_p, c_long, c_uint8, c_uint32,
                    c_void_p, create_string_buffer, string_at)

EXIT_FAIL = 2   # the evidence did not pass; die() exits 1 for usage and setup errors

USAGE = ("usage: tdx-attest quote [nonce] [out.json] [--ita-nonce nonce.json] | "
         "verify att.json [reference.json] [--nonce NONCE] | "
         "verify-ita att.json <eu|us> [reference.json] [--nonce NONCE] [--json] | "
         "ita-nonce <eu|us> [nonce.json] | self-check [reference.json] [--json]")

def die(msg): sys.exit("tdx-attest: " + msg)

def note(msg): print("tdx-attest: " + msg, file=sys.stderr)


# ---------------- self-provisioning (deps + collateral config) ----------------
# The customer should only download this tool and run it. Like the AMD measure_boot.sh,
# it installs its own dependencies (Intel's public DCAP packages) and writes the one
# config file the verification library needs: collateral from Intel's public service.
# Disable with TDX_ATTEST_NO_SETUP=1 (air-gapped or pre-provisioned images).

QCNL_CONF = "/etc/sgx_default_qcnl.conf"
QCNL_WANT = {
    "pccs_url": "https://localhost:8081/sgx/certification/v4/",   # unused for verification, kept for the QPL's schema
    "use_secure_cert": True,
    "collateral_service": "https://api.trustedservices.intel.com/sgx/certification/v4/",
    "retry_times": 6, "retry_delay": 10,
    "pck_cache_expire_hours": 168, "verify_collateral_cache_expire_hours": 168,
    "local_cache_only": False,
}
INTEL_REPO_KEY = "https://download.01.org/intel-sgx/sgx_repo/ubuntu/intel-sgx-deb.key"
INTEL_REPO_URL = "https://download.01.org/intel-sgx/sgx_repo/ubuntu"
SGX_LIST = "/etc/apt/sources.list.d/intel-sgx.list"
SGX_KEY = "/etc/apt/keyrings/intel-sgx.asc"

def _have_lib(name):
    try: CDLL(name); return True
    except OSError: return False

def _run(cmd, **kw):
    return subprocess.run(cmd, shell=isinstance(cmd, str), check=False, **kw)

def _os_codename():
    for line in open("/etc/os-release"):
        if line.startswith("VERSION_CODENAME="):
            return line.split("=", 1)[1].strip().strip('"')
    return ""

def _intel_repo_serves(codename):
    """Intel publishes packages for some Ubuntu releases only; check before touching apt."""
    url = "%s/dists/%s/Release" % (INTEL_REPO_URL, codename)
    return bool(codename) and _run(["curl", "-fsL", "-o", "/dev/null", url], stderr=subprocess.DEVNULL).returncode == 0

def ensure_deps(need):
    """need: subset of {"attest", "verify"}. Installs libtdx-attest / QVL + QPL via apt when missing."""
    if os.environ.get("TDX_ATTEST_NO_SETUP"): return
    missing = []
    if "attest" in need and not _have_lib("libtdx_attest.so.1"): missing.append("libtdx-attest")
    if "verify" in need and not _have_lib("libsgx_dcap_quoteverify.so.1"): missing += ["libsgx-dcap-quote-verify", "libsgx-dcap-default-qpl"]
    if not missing: return
    if os.geteuid() != 0: die("missing %s; run as root once so they can be installed, or install them yourself" % ", ".join(missing))
    added = False
    if not os.path.exists(SGX_LIST):
        codename = _os_codename()
        if not _intel_repo_serves(codename):
            die("Intel's DCAP repository has no packages for this OS release (%s); use an Ubuntu "
                "release it serves, or install %s yourself" % (codename or "unknown", ", ".join(missing)))
        note("adding Intel's DCAP apt repository (%s)" % codename)
        os.makedirs(os.path.dirname(SGX_KEY), exist_ok=True)
        if _run(["curl", "-fsSL", INTEL_REPO_KEY, "-o", SGX_KEY]).returncode != 0: die("cannot fetch Intel's repo key")
        with open(SGX_LIST, "w") as f:
            f.write("deb [signed-by=%s arch=amd64] %s %s main\n" % (SGX_KEY, INTEL_REPO_URL, codename))
        added = True
    note("installing %s" % " ".join(missing))
    r = _run("apt-get update -qq && DEBIAN_FRONTEND=noninteractive apt-get install -y -qq " + " ".join(missing))
    if r.returncode != 0:
        if added:   # don't leave a source behind that makes every later apt-get update fail
            for p in (SGX_LIST, SGX_KEY):
                try: os.remove(p)
                except OSError: pass
        die("apt-get install failed for " + " ".join(missing))

def ensure_qcnl():
    """Point the verification library at Intel's public collateral service unless a real PCCS is configured."""
    if os.environ.get("TDX_ATTEST_NO_SETUP"): return
    try:
        cur = json.loads("\n".join(l for l in open(QCNL_CONF) if not l.strip().startswith("//")))
    except Exception:
        cur = None
    if cur and cur.get("collateral_service"): return                      # already fine (Intel or a PCCS with collateral)
    if cur and "localhost" not in cur.get("pccs_url", "localhost"): return  # a real PCCS is configured: leave it alone
    if os.geteuid() != 0: die("%s has no collateral source; run as root once to write it" % QCNL_CONF)
    kept = ""
    if os.path.exists(QCNL_CONF) and not os.path.exists(QCNL_CONF + ".bak"):
        shutil.copy2(QCNL_CONF, QCNL_CONF + ".bak")
        kept = "; previous file kept as %s.bak" % QCNL_CONF
    with open(QCNL_CONF, "w") as f: json.dump(QCNL_WANT, f, indent=2)
    note("wrote %s (collateral from Intel PCS%s)" % (QCNL_CONF, kept))

# ---------------- quote ----------------

def lib_attest():
    try:
        return CDLL("libtdx_attest.so.1")
    except OSError:
        die("cannot load libtdx_attest.so.1: quotes can only be generated inside a TDX guest "
            "(run as root once so the tool can install Intel's libtdx-attest)")

def make_quote(report_data: bytes) -> bytes:
    if len(report_data) > 64: die("report data is %d bytes; REPORTDATA holds at most 64" % len(report_data))
    L = lib_attest()
    rd = (c_uint8 * 64)(*report_data.ljust(64, b"\x00"))
    q = POINTER(c_uint8)(); qs = c_uint32(0)
    r = L.tdx_att_get_quote(byref(rd), None, 0, None,
                            byref(q), byref(qs), 0)
    if r != 0: die("tdx_att_get_quote error %d" % r)
    blob = string_at(q, qs.value)
    L.tdx_att_free_quote(q)
    return blob

def read_hostkey():
    v = os.environ.get("TDX_ATTEST_KEY_HASH")   # explicit override of the envelope's host_key_hash field
    if v:
        return v
    for p in ("/etc/ssh/ssh_host_ed25519_key.pub",
              "/etc/ssh/ssh_host_rsa_key.pub"):
        if os.path.exists(p):
            with open(p, "rb") as f:
                return hashlib.sha384(f.read()).hexdigest()
    return None

def parse_nonce(arg):
    """nonce: hex bytes if valid hex, else SHA-384 of the text (with a notice, since a non-hex
    value is usually a mistyped hex nonce). At most 64 bytes: that is all REPORTDATA holds."""
    try:
        nonce = unhexlify(arg)
    except Exception:
        note("nonce is not valid hex; binding the SHA-384 of the text instead")
        nonce = hashlib.sha384(arg.encode()).digest()
    if len(nonce) > 64: die("nonce is %d bytes; REPORTDATA holds at most 64" % len(nonce))
    return nonce

def load_ita_nonce(path):
    """nonce.json written by `ita-nonce`: {"val": b64, "iat": b64, "signature": b64}.
    Returns (the object as ITA expects it back, the 64-byte REPORTDATA the guest must bind)."""
    try:
        vn = json.load(open(path))
        val = base64.b64decode(vn["val"], validate=True)
        iat = base64.b64decode(vn["iat"], validate=True)
        base64.b64decode(vn["signature"], validate=True)
    except (OSError, ValueError, KeyError, TypeError) as e:
        die("cannot read ITA nonce file %s: %s" % (path, e))
    return {"val": vn["val"], "iat": vn["iat"], "signature": vn["signature"]}, ita_report_data(val, iat)

def ita_report_data(val: bytes, iat: bytes) -> bytes:
    """ITA recomputes REPORTDATA as SHA-512(val || iat || runtime_data); we send no runtime_data."""
    return hashlib.sha512(val + iat).digest()

def cmd_quote(argv):
    args, ita_path = [], None
    it = iter(argv)
    for a in it:
        if a == "--ita-nonce":
            ita_path = next(it, None)
            if ita_path is None: die("--ita-nonce needs a file")
        else:
            args.append(a)
    if len(args) > 2: die(USAGE)
    ita_nonce = None
    if ita_path is not None:
        if args and not args[0].endswith(".json"):
            die("give either a nonce or --ita-nonce, not both")
        if args: args.insert(0, None)              # only an output path was given
        ita_nonce, nonce = load_ita_nonce(ita_path)
    elif args:
        nonce = parse_nonce(args[0])
    else:
        nonce = b"\x00" * 64
        note("no nonce given: REPORTDATA is 64 zero bytes, so this quote proves the platform "
             "and its measurements but not freshness; a verifier should issue a nonce "
             "(openssl rand -hex 32) and pass it here")
    ensure_deps({"attest"})
    q = make_quote(nonce)
    envj = {
        "quote": base64.b64encode(q).decode(),
        "nonce": nonce.hex(),
        "host_key_hash": read_hostkey(),
        "made_in": os.uname().nodename,
        "tdx": True,
        "made_at": int(time.time()),
    }
    if ita_nonce is not None:
        envj["ita_nonce"] = ita_nonce
    out = args[1] if len(args) > 1 else "./att.json"
    with open(out, "w") as f: json.dump(envj, f, indent=2)
    print("wrote %s (%d quote bytes%s)" % (out, len(q), ", Intel verifier nonce bound" if ita_nonce else ""))

# ---------------- quote layout, verdicts, reference values ----------------

VLIB = "libsgx_dcap_quoteverify.so.1"

# sgx_ql_qv_result_t: OK is 0, everything else lives at 0xA001.. (not 1..10)
VERDICTS = {0x0000: "OK", 0xA001: "CONFIG_NEEDED", 0xA002: "OUT_OF_DATE",
            0xA003: "OUT_OF_DATE_CONFIG_NEEDED", 0xA004: "INVALID_SIGNATURE",
            0xA005: "REVOKED", 0xA006: "UNSPECIFIED", 0xA007: "SW_HARDENING_NEEDED",
            0xA008: "CONFIG_AND_SW_HARDENING_NEEDED", 0xA009: "TD_RELAUNCH_ADVISED",
            0xA00A: "TD_RELAUNCH_ADVISED_CONFIG_NEEDED"}
# quote3_error_t codes you actually meet from tdx_qv_verify_quote
QL_ERRORS = {0xE001: "UNEXPECTED", 0xE002: "INVALID_PARAMETER (ctypes marshalling?)",
             0xE019: "NO_QUOTE_COLLATERAL_DATA: QPL could not fetch collateral; set "
                     "\"collateral_service\" to Intel PCS in /etc/sgx_default_qcnl.conf",
             0xE01F: "PLATFORM_LIB_UNAVAILABLE: libdcap_quoteprov.so.1 (libsgx-dcap-default-qpl) missing",
             0xE033: "QUOTE_FORMAT_UNSUPPORTED"}
# Verdicts a policy may accept besides OK; override with TDX_ATTEST_ACCEPT="OK,SW_HARDENING_NEEDED".
# A bad signature, a revoked platform or an unspecified result is never accepted, whatever it says.
ACCEPT = {v.strip() for v in (os.environ.get("TDX_ATTEST_ACCEPT") or "OK").split(",") if v.strip()}
NEVER_ACCEPT = {"INVALID_SIGNATURE", "REVOKED", "UNSPECIFIED"}

def verdict_name(rc, vr):
    return VERDICTS.get(vr, "0x%X" % vr) if rc == 0 else "n/a"   # vr is meaningless unless rc == 0

def chain_ok(rc, verdict):
    """Signature, PCK chain, CRLs and QE identity held. QVL reports a bad signature or a revoked
    platform as a verdict with rc == 0, so rc alone does not mean the chain is good."""
    return rc == 0 and verdict in VERDICTS.values() and verdict not in NEVER_ACCEPT

def verdict_accepted(verdict):
    return verdict in ACCEPT and verdict not in NEVER_ACCEPT

# TDREPORT body offsets inside a v4 quote (48-byte header first). Two of these are
# cross-validated at runtime by the self-check: REPORTDATA against the nonce we chose, and
# RTMR0-3 against the CCEL event-log replay. If either check fails, do not trust the rest.
TD = {"tee_tcb_svn": (48, 16), "mrseam": (64, 48), "mrsignerseam": (112, 48),
      "td_attributes": (168, 8), "xfam": (176, 8), "mrtd": (184, 48),
      "mrconfigid": (232, 48), "mrowner": (280, 48), "mrownerconfig": (328, 48),
      "rtmr0": (376, 48), "rtmr1": (424, 48), "rtmr2": (472, 48), "rtmr3": (520, 48),
      "reportdata": (568, 64)}
MEASUREMENTS = ("mrtd", "rtmr0", "rtmr1", "rtmr2", "rtmr3")

def is_tdx_v4(q: bytes) -> bool:
    return len(q) >= 1020 and q[0] == 4 and q[4:6] == b"\x81\x00"

def td_body(q: bytes) -> dict:
    return {k: q[o:o + n].hex() for k, (o, n) in TD.items()}

def td_debug(b: dict) -> bool:
    return bool(int.from_bytes(bytes.fromhex(b["td_attributes"]), "little") & 1)

def load_reference(path):
    """{"mrtd": hex, "rtmr0": hex, ...} -> lower-cased dict. Unknown keys and non-hex values
    are errors, so a typo cannot silently pin nothing."""
    try:
        raw = json.load(open(path))
    except (OSError, ValueError) as e:
        die("cannot read reference file %s: %s" % (path, e))
    allowed = [k for k in TD if k != "reportdata"]
    if not isinstance(raw, dict) or not raw:
        die("%s: expected a JSON object such as {\"mrtd\": \"<hex>\"}" % path)
    ref = {}
    for k, v in raw.items():
        key = str(k).lower()
        if key not in allowed:
            die("%s: unknown register %r (use %s)" % (path, k, ", ".join(allowed)))
        if not isinstance(v, str) or not re.fullmatch(r"[0-9a-fA-F]+", v):
            die("%s: %s must be a hex string" % (path, k))
        ref[key] = v.lower()
    return ref

def compare_reference(b, ref):
    return {k: ("MATCH" if b[k] == v else "MISMATCH") for k, v in ref.items()}

def load_envelope(path):
    """-> (envelope dict, raw quote bytes), with a clear error instead of a traceback."""
    try:
        envj = json.load(open(path))
        q = base64.b64decode(envj["quote"], validate=True)
    except (OSError, ValueError, KeyError, TypeError) as e:
        die("cannot read envelope %s: %s" % (path, e))
    if not envj.get("tdx"): die("envelope has tdx=false")
    return envj, q

def qvl_verify(q: bytes, want_supplemental=False):
    """tdx_qv_verify_quote with explicit C signatures. Returns (rc, verdict code,
    collateral_expired, supplemental blob); the blob carries the advisory IDs and is empty
    unless asked for. Explicit argtypes matter: without them ctypes passes a Python 0 as a
    4-byte int into the 8-byte p_supplemental_data slot, the library sees a garbage pointer
    with size 0 and answers 0xE002 INVALID_PARAMETER before it even looks at the quote."""
    try:
        L = CDLL(VLIB)
    except OSError:
        die("cannot load %s: local verification needs Linux with Intel's DCAP packages (the tool "
            "installs them as root on Ubuntu); from any other machine use verify-ita" % VLIB)
    size = c_uint32(0)
    if want_supplemental:
        g = L.tdx_qv_get_quote_supplemental_data_size
        g.argtypes = [POINTER(c_uint32)]; g.restype = c_uint32
        if g(byref(size)) != 0:
            size = c_uint32(0)
    buf = create_string_buffer(size.value) if size.value else None
    f = L.tdx_qv_verify_quote
    f.argtypes = [c_char_p, c_uint32, c_void_p, c_long, POINTER(c_uint32),
                  POINTER(c_uint32), c_void_p, c_uint32, c_void_p]
    f.restype = c_uint32
    ce = c_uint32(0); vr = c_uint32(0)
    rc = f(q, len(q), None, int(time.time()), byref(ce), byref(vr), None, size.value, buf)
    return rc, vr.value, ce.value, (bytes(buf) if buf is not None else b"")

def tcb_problems(rc, verdict, ce):
    """What is wrong with Intel's answer, in the order a reader should fix it."""
    P = []
    if rc != 0:
        P.append("quote verification failed: 0x%X %s" % (rc, QL_ERRORS.get(rc, "")))
    elif not chain_ok(rc, verdict):
        P.append("quote rejected by Intel's verification: %s" % verdict)
    elif not verdict_accepted(verdict):
        P.append("TCB verdict %s not in accepted set %s" % (verdict, sorted(ACCEPT - NEVER_ACCEPT)))
    if ce:
        P.append("collateral expired")
    return P

# ---------------- verify (QVL, local Linux) ----------------

def cmd_verify(argv):
    args, nonce_arg = [], None
    it = iter(argv)
    for a in it:
        if a == "--nonce":
            nonce_arg = next(it, None)
            if nonce_arg is None: die("--nonce needs a value")
        else:
            args.append(a)
    if not 1 <= len(args) <= 2: die(USAGE)
    ref = load_reference(args[1]) if len(args) == 2 else {}
    expect = parse_nonce(nonce_arg) if nonce_arg is not None else None
    if expect is None:
        note("no --nonce given: checking the nonce recorded in the envelope; compare it with the one you issued")
    ensure_deps({"verify"}); ensure_qcnl()
    envj, q = load_envelope(args[0])
    if not is_tdx_v4(q):
        die("not a TDX v4 quote (len=%d version=%d tee=%s)" % (len(q), q[0], q[4:6].hex()))
    b = td_body(q)

    rc, vr, ce, _ = qvl_verify(q)
    verdict = verdict_name(rc, vr)
    P = tcb_problems(rc, verdict, ce)
    status = ("fail[0x%X %s]" % (rc, QL_ERRORS.get(rc, "?")) if rc != 0 else
              "ok" if chain_ok(rc, verdict) else "fail")
    print("verify=%s  verdict=%s  collateral_expired=%d" % (status, verdict, ce))

    debug = td_debug(b)
    print("TD debug: %s" % ("ENABLED" if debug else "DISABLED"))
    if debug:
        P.append("TD DEBUG attribute set: host can inspect this TD")

    if expect is None:
        try: expect = unhexlify(envj.get("nonce") or "")
        except ValueError: die("envelope nonce is not hex")
    bound = bytes.fromhex(b["reportdata"]) == expect.ljust(64, b"\x00")
    print("BIND: %s (REPORTDATA at offset %d)" % ("matches" if bound else "MISMATCH", TD["reportdata"][0]))
    if not bound:
        P.append("REPORTDATA does not match the nonce")

    for k in MEASUREMENTS:
        print("%s: %s" % (k.upper(), b[k]))
    for k, res in compare_reference(b, ref).items():
        print("Reference %-11s: %s" % (k.upper(), res))
        if res != "MATCH":
            P.append("%s differs from reference" % k)
    if envj.get("host_key_hash"):
        print("envelope host_key_hash:", envj["host_key_hash"])
    print()
    if P:
        print("FAIL: " + "; ".join(P))
        return EXIT_FAIL
    print("PASS: genuine Intel TDX quote, TCB %s, nonce bound%s" % (verdict, ", reference matched" if ref else ""))
    return 0


# ---------------- self-check (guest: real TD? TCB? OS measurement?) ----------------

def advisories(supp: bytes):
    """Intel security advisory IDs for this TCB level. Found by scanning the supplemental
    blob for the ASCII list instead of trusting a struct offset."""
    return sorted(set(m.decode() for m in re.findall(rb"INTEL-SA-\d{5}", supp)))

CCEL_DATA = "/sys/firmware/acpi/tables/data/CCEL"
EV_NO_ACTION = 0x3
HASH_LEN = {0x0004: 20, 0x000B: 32, 0x000C: 48, 0x000D: 64}   # TPM_ALG_SHA1/256/384/512

class CCELError(Exception):
    """The event log is present but not parseable; the self-check reports it and fails that line only."""

def ccel_events(data):
    """Parse the TCG2 'crypto agile' event log TDVF writes. Yields (mr_index, type, sha384, event).
    Raises CCELError on a truncated or malformed log instead of a struct/index traceback."""
    def need(off, n):
        if off + n > len(data):
            raise CCELError("truncated at byte %d (log is %d bytes)" % (off, len(data)))
    off = 0
    # first entry: TCG_PCClientPCREvent (Spec ID Event03), fixed SHA1-sized digest
    need(off, 32)
    idx, etype = struct.unpack_from("<II", data, off); off += 8
    off += 20
    (esz,) = struct.unpack_from("<I", data, off); off += 4
    need(off, esz); off += esz
    while off + 12 <= len(data):
        idx, etype, count = struct.unpack_from("<III", data, off); off += 12
        if idx == 0xFFFFFFFF or count == 0:
            break
        if count > 8:
            raise CCELError("event at byte %d claims %d digests" % (off - 12, count))
        d384 = None
        for _ in range(count):
            need(off, 2)
            (alg,) = struct.unpack_from("<H", data, off); off += 2
            n = HASH_LEN.get(alg)
            if n is None:
                raise CCELError("unknown digest algorithm 0x%04x at byte %d" % (alg, off - 2))
            need(off, n)
            if alg == 0x000C:
                d384 = data[off:off + n]
            off += n
        need(off, 4)
        (esz,) = struct.unpack_from("<I", data, off); off += 4
        need(off, esz)
        ev = data[off:off + esz]; off += esz
        yield idx, etype, d384, ev

def ccel_replay():
    """Recompute RTMR0-3 from the log. Returns (status, {rtmrN: hex} or None, [event dicts] or None);
    status is "ok", "absent" or "unparseable: <why>"."""
    if not os.path.exists(CCEL_DATA):
        return "absent", None, None
    regs = {i: b"\x00" * 48 for i in range(4)}
    events = []
    try:
        data = open(CCEL_DATA, "rb").read()
        for idx, etype, d, ev in ccel_events(data):
            if etype == EV_NO_ACTION or d is None or not (1 <= idx <= 4):
                continue
            r = idx - 1                      # CCEL MR index 1..4 == RTMR0..3 (0 = MRTD, never extended)
            regs[r] = hashlib.sha384(regs[r] + d).digest()
            txt = ev.decode("utf-16-le", "ignore") if etype == 0x8000000A else ev.decode("ascii", "ignore")
            txt = "".join(ch for ch in txt if 32 <= ord(ch) < 127)[:300]
            events.append({"reg": "rtmr%d" % r, "type": "0x%x" % etype, "digest": d.hex(), "text": txt})
    except (CCELError, struct.error, OSError, ValueError) as e:
        return "unparseable: %s" % e, None, None
    return "ok", {"rtmr%d" % i: regs[i].hex() for i in range(4)}, events

def sha384_file(path):
    h = hashlib.sha384()
    with open(path, "rb") as f:
        for chunk in iter(lambda: f.read(1 << 20), b""):
            h.update(chunk)
    return h.hexdigest()

def authenticode_sha384(path):
    """SHA-384 of a PE/COFF image the way firmware measures an EFI application it loads
    (the Authenticode "PE image hash": the file minus its checksum field, the certificate
    table directory entry and the certificate table, sections in file order). A TDVF logs
    this digest for a kernel booted directly (QEMU -kernel); it is not the plain file hash.
    Returns None for a file that is not a PE image."""
    with open(path, "rb") as f:
        data = f.read()
    try:
        (pe,) = struct.unpack_from("<I", data, 0x3C)
        if data[pe:pe + 4] != b"PE\0\0":
            return None
        coff = pe + 4
        (nsec,) = struct.unpack_from("<H", data, coff + 2)
        (opt_size,) = struct.unpack_from("<H", data, coff + 16)
        opt = coff + 20
        (magic,) = struct.unpack_from("<H", data, opt)
        plus = magic == 0x20B                      # PE32+ (x86_64 kernels)
        checksum = opt + 64
        (hdr_size,) = struct.unpack_from("<I", data, opt + 60)
        (n_dirs,) = struct.unpack_from("<I", data, opt + (108 if plus else 92))
        sec_dir = opt + (112 if plus else 96) + 4 * 8   # IMAGE_DIRECTORY_ENTRY_SECURITY
        h = hashlib.sha384()
        h.update(data[:checksum])
        if n_dirs > 4:
            (_cert_va, cert_size) = struct.unpack_from("<II", data, sec_dir)
            h.update(data[checksum + 4:sec_dir])
            h.update(data[sec_dir + 8:hdr_size])
        else:
            cert_size = 0
            h.update(data[checksum + 4:hdr_size])
        done = hdr_size
        secs = []
        for i in range(nsec):
            raw_size, raw_ptr = struct.unpack_from("<II", data, opt + opt_size + 40 * i + 16)
            if raw_size:
                secs.append((raw_ptr, raw_size))
        for ptr, size in sorted(secs):
            h.update(data[ptr:ptr + size])
            done += size
        extra = len(data) - done - cert_size
        if extra > 0:
            h.update(data[done:done + extra])
        return h.hexdigest()
    except struct.error:
        return None

EV_EVENT_TAG = 0x6                            # kernel EFI stub: initrd, LoadOptions
EV_EFI_BOOT_SERVICES_APPLICATION = 0x80000003  # firmware: an EFI application it loaded

def _boot_file(text):
    """A GRUB file event naming a kernel or initrd: '/vmlinuz', '/boot/vmlinuz-6.8.0-45-generic',
    '(hd0,gpt16)/initrd.img-6.8.0-45-generic'. Returns (key, path) or None."""
    if " " in text:
        return None
    path = re.sub(r"^\([^)]*\)", "", text)
    base = os.path.basename(path)
    for key, prefix in (("kernel", "vmlinuz"), ("initrd", "initrd")):
        if path.startswith("/") and base.startswith(prefix):
            return key, path
    return None

def _artifact(shown, path, measured, hasher, how):
    cands = [os.path.join("/boot", path.lstrip("/")), path]
    disk = next((c for c in cands if os.path.isfile(c)), None)
    try:
        match = disk is not None and hasher(disk) == measured
    except OSError:
        match = False
    return {"path": shown, "measured": measured, "on_disk": disk, "match": match, "how": how}

def boot_artifacts(events):
    """Kernel, initrd and command line as they were measured, and whether they equal what is on
    disk now. Two boot paths leave different events:
      GRUB (disk boot): GRUB measures every file it reads (text = path, digest = file contents)
        and the command line as text ('kernel_cmdline: ...').
      Direct boot (Verda CVMs; QEMU -kernel/-initrd/-append): the firmware measures the kernel
        as the EFI application it loads (digest = Authenticode PE image hash, device path ends
        in 'kernel'); the kernel's EFI stub then measures its load options ('LOADED_IMAGE::
        LoadOptions', digest = UTF-16LE command line plus NUL) and the initrd ('Linux initrd',
        digest = initrd contents). The command line text is not in the log, so it is read
        from /proc/cmdline and checked against that digest."""
    out = {"kernel": None, "initrd": None, "cmdline": None, "cmdline_match": None}
    if not events:
        return out
    for e in events:
        t, etype = e["text"], int(e["type"], 16)
        if t.startswith("kernel_cmdline: "):
            out["cmdline"] = t[len("kernel_cmdline: "):]
        hit = _boot_file(t)
        if hit and out[hit[0]] is None:
            out[hit[0]] = _artifact(t, hit[1], e["digest"], sha384_file, "GRUB file digest")
        if etype == EV_EFI_BOOT_SERVICES_APPLICATION and t.endswith("kernel") and out["kernel"] is None:
            out["kernel"] = _artifact("/boot/vmlinuz", "/boot/vmlinuz", e["digest"], authenticode_sha384,
                                      "PE image hash, direct boot")
        if etype == EV_EVENT_TAG and "Linux initrd" in t and out["initrd"] is None:
            out["initrd"] = _artifact("/boot/initrd.img", "/boot/initrd.img", e["digest"], sha384_file,
                                      "EFI stub, direct boot")
        if etype == EV_EVENT_TAG and "LOADED_IMAGE::LoadOptions" in t and out["cmdline"] is None:
            try:
                cmd = open("/proc/cmdline").read().rstrip("\n")
            except OSError:
                continue
            raw = cmd.encode("utf-16-le")
            out["cmdline"] = cmd
            out["cmdline_match"] = e["digest"] in (hashlib.sha384(raw + b"\0\0").hexdigest(),
                                                   hashlib.sha384(raw).hexdigest())
    return out

def selfcheck_facts(ref):
    out = {"is_td": {}, "tcb": {}, "measurements": {}, "boot": {}, "reference": {}, "problems": []}
    P = out["problems"]

    # 1. Is this a real TD?  The signed quote is the real proof; the local hints are context.
    cpuinfo = open("/proc/cpuinfo").read()
    out["is_td"]["cpu_flag_tdx_guest"] = " tdx_guest" in cpuinfo
    out["is_td"]["dev_tdx_guest"] = os.path.exists("/dev/tdx_guest")
    nonce = os.urandom(32)
    q = make_quote(hashlib.sha512(nonce).digest())
    b = td_body(q)
    out["is_td"]["quote_version"] = q[0]
    out["is_td"]["tee_type"] = q[4:6].hex()
    out["is_td"]["cert_data_type"] = int.from_bytes(q[764:766], "little")
    out["is_td"]["nonce_bound"] = bytes.fromhex(b["reportdata"]) == hashlib.sha512(nonce).digest()
    if not is_tdx_v4(q):
        P.append("quote is not a TDX v4 quote")
    if not out["is_td"]["nonce_bound"]:
        P.append("REPORTDATA does not match our nonce: offsets wrong or stale quote")
    out["is_td"]["td_attributes"] = b["td_attributes"]
    out["is_td"]["debug"] = td_debug(b)
    if out["is_td"]["debug"]:
        P.append("TD DEBUG attribute set: host can inspect this TD")

    # 2. TCB: Intel's verdict on this platform (signature, PCK chain, CRLs, QE identity, TCB level)
    rc, vr, ce, supp = qvl_verify(q, want_supplemental=True)
    verdict = verdict_name(rc, vr)
    out["tcb"] = {"qvl_rc": "0x%X" % rc, "verdict": verdict, "chain_ok": chain_ok(rc, verdict),
                  "collateral_expired": bool(ce),
                  "advisories": advisories(supp) if rc == 0 else [],
                  "tee_tcb_svn": b["tee_tcb_svn"], "mrseam": b["mrseam"]}
    P.extend(tcb_problems(rc, verdict, ce))

    # 3. OS measurement: what the quote says, and whether the event log replays to the same values
    out["measurements"] = {k: b[k] for k in MEASUREMENTS}
    status, replay, events = ccel_replay()
    if status != "ok":
        out["measurements"]["ccel_replay"] = status
        if status != "absent":
            P.append("event log %s; RTMRs cannot be tied to boot events" % status)
    else:
        bad = [k for k in replay if replay[k] != b[k]]
        out["measurements"]["ccel_replay"] = "MATCH" if not bad else "MISMATCH " + ",".join(bad)
        out["measurements"]["events"] = events
        if bad:
            P.append("event log does not replay to quoted " + ",".join(bad))
    fw = "/boot/OVMF.inteltdx.fd"
    out["boot"] = boot_artifacts(events)
    out["boot"]["firmware"] = {"path": fw, "sha384": sha384_file(fw)} if os.path.isfile(fw) else None
    for key in ("kernel", "initrd"):
        a = out["boot"].get(key)
        if a and a["on_disk"] and not a["match"]:
            P.append("%s on disk differs from the measured %s" % (key, key))
    if out["boot"].get("cmdline_match") is False:
        P.append("/proc/cmdline differs from the measured command line (LoadOptions)")

    # 4. Reference values, if given (validated by load_reference)
    for k, res in compare_reference(b, ref).items():
        out["reference"][k] = res
        if res != "MATCH":
            P.append("%s differs from reference" % k)
    out["result"] = "PASS" if not P else "FAIL"
    return out

def _line(ok, text):
    print("[ %s ] - %s" % ("PASS" if ok else "FAIL", text))

def print_human(o):
    t, c, m, bt, r = o["is_td"], o["tcb"], o["measurements"], o["boot"], o["reference"]
    _line(t["cpu_flag_tdx_guest"] and t["dev_tdx_guest"], "TDX guest: %s" % ("ENABLED" if t["cpu_flag_tdx_guest"] else "NOT DETECTED"))
    _line(t["quote_version"] == 4 and t["tee_type"] == "8100" and t["cert_data_type"] == 6 and t["nonce_bound"],
          "Quote: v%d TDX, PCK chain embedded, nonce bound" % t["quote_version"])
    _line(not t["debug"], "TD debug: %s" % ("ENABLED" if t["debug"] else "DISABLED"))
    print()
    if c["qvl_rc"] != "0x0":
        _line(False, "Quote verification failed: %s %s" % (c["qvl_rc"], QL_ERRORS.get(int(c["qvl_rc"], 16), "")))
    elif not c["chain_ok"]:
        _line(False, "Quote rejected against Intel root: %s" % c["verdict"])
    else:
        _line(True, "Quote verified against Intel root (signature, PCK chain, CRLs, QE identity)")
    _line(c["chain_ok"] and verdict_accepted(c["verdict"]) and not c["collateral_expired"],
          "TCB status: %s  (advisories: %s)" % (c["verdict"], ", ".join(c["advisories"]) or "none"))
    print("TEE TCB SVN          : %s" % c["tee_tcb_svn"])
    print("TDX module (MRSEAM)  : %s" % c["mrseam"])
    print()
    fw = bt.get("firmware")
    print("Firmware (TDVF)      : %s" % ("%s  sha384 %s" % (fw["path"], fw["sha384"]) if fw else "n/a (no /boot/OVMF.inteltdx.fd in this guest)"))
    for key, label in (("kernel", "Kernel"), ("initrd", "Initrd")):
        a = bt.get(key)
        if a:
            st = "MATCH on disk" if a["match"] else ("MISMATCH on disk" if a["on_disk"] else "file not found on disk")
            print("%-21s: %s  measured sha384 %s  %s  (%s)" % (label, a["path"], a["measured"][:16] + "...", st, a["how"]))
        else:
            print("%-21s: n/a (no kernel event in the log)" % label)
    cm = bt.get("cmdline")
    if cm is None:
        print("Cmdline              : n/a (no kernel_cmdline or LoadOptions event in the log)")
    elif bt.get("cmdline_match") is None:
        print("Cmdline              : %s  (GRUB measured text)" % cm)
    else:
        print("Cmdline              : %s  %s" % (cm, "MATCH measured (LoadOptions)" if bt["cmdline_match"]
                                                else "MISMATCH: /proc/cmdline differs from the measured LoadOptions"))
    print()
    print("MRTD                 : %s" % m["mrtd"])
    for i in range(4):
        print("RTMR%d                : %s" % (i, m["rtmr%d" % i]))
    print("Event log replay     : %s" % m.get("ccel_replay"))
    for k, v in r.items():
        print("Reference %-11s: %s" % (k.upper(), v))
    print()
    if o["result"] == "PASS":
        print("PASS: genuine Intel TDX guest, TCB %s, boot chain measured and consistent" % c["verdict"])
    else:
        print("FAIL: " + "; ".join(o["problems"]))

def cmd_selfcheck(argv):
    as_json = "--json" in argv
    argv = [a for a in argv if a != "--json"]
    if len(argv) > 1: die(USAGE)
    ref = load_reference(argv[0]) if argv else {}
    ensure_deps({"attest", "verify"}); ensure_qcnl()
    out = selfcheck_facts(ref)
    if as_json:
        print(json.dumps(out, indent=2))
    else:
        print_human(out)
    return 0 if out["result"] == "PASS" else EXIT_FAIL

# ---------------- verify via ITA (curl-worthy anywhere) ----------------
# Intel Trust Authority: POST the quote, get back a JWT signed by Intel. The token is only
# worth something once its signature is checked against Intel's published key set, so this
# section carries a small JWS verifier (RSA PKCS#1 v1.5 and RSA-PSS, pure Python, no extra
# packages) and the claim checks that mirror `verify`. The key set is fetched over TLS from
# Intel's portal: that TLS connection is the trust anchor; the x5c chain inside the key set
# is not re-walked. A jku/x5u header in the token is ignored on purpose: the key location is
# fixed per region, never taken from the token itself.

ITA = {"eu": {"api": "https://api.eu.trustauthority.intel.com", "jwks": "https://portal.eu.trustauthority.intel.com/certs"},
       "us": {"api": "https://api.trustauthority.intel.com",    "jwks": "https://portal.trustauthority.intel.com/certs"}}
ITA_ATTEST = "/appraisal/v1/attest"   # JSON {"quote": b64[, "verifier_nonce": {...}]} -> {"token": "<jwt>"}
ITA_NONCE = "/appraisal/v1/nonce"     # GET -> {"val": b64, "iat": b64, "signature": b64}
ITA_ISSUER = "Intel Trust Authority"
JWT_LEEWAY = 60                       # seconds of clock skew tolerated on exp/nbf

def ita_key():
    return os.environ.get("ITA_KEY") or die("set ITA_KEY (region-paired key from portal.trustauthority.intel.com)")

def http_json(url, data=None, headers=None, what="request"):
    req = urllib.request.Request(url, data=data, headers=dict(headers or {}))
    try:
        with urllib.request.urlopen(req, timeout=60) as resp:
            return json.loads(resp.read().decode())
    except urllib.error.HTTPError as e:
        die("%s: HTTP %d: %s" % (what, e.code, e.read().decode("utf-8", "replace")[:300]))
    except (urllib.error.URLError, OSError, ValueError) as e:
        die("%s failed: %s" % (what, e))

def _b64url(s):
    s = s.encode() if isinstance(s, str) else s
    return base64.urlsafe_b64decode(s + b"=" * (-len(s) % 4))

def _claim_bytes(v):
    """A register claim as bytes, whether ITA encodes it as hex or base64; None if neither."""
    if not isinstance(v, str): return None
    if re.fullmatch(r"(?:[0-9a-fA-F]{2})+", v): return bytes.fromhex(v)
    try: return base64.b64decode(v, validate=True)
    except ValueError: return None

# RSA signature verification (RFC 8017) for the JWS algorithms Intel uses; "none" and HMAC
# algorithms are rejected before we get here, so a token can never pick a weaker scheme.
JWS_ALGS = {"RS256": ("sha256", "pkcs1"), "RS384": ("sha384", "pkcs1"), "RS512": ("sha512", "pkcs1"),
            "PS256": ("sha256", "pss"), "PS384": ("sha384", "pss"), "PS512": ("sha512", "pss")}
DIGEST_INFO = {"sha256": bytes.fromhex("3031300d060960864801650304020105000420"),
               "sha384": bytes.fromhex("3041300d060960864801650304020205000430"),
               "sha512": bytes.fromhex("3051300d060960864801650304020305000440")}

def _mgf1(seed, length, hname):
    hlen = hashlib.new(hname).digest_size
    return b"".join(hashlib.new(hname, seed + c.to_bytes(4, "big")).digest()
                    for c in range((length + hlen - 1) // hlen))[:length]

def rsa_verify(n, e, msg, sig, alg):
    """RSASSA-PKCS1-v1_5 or RSASSA-PSS (salt length = hash length, RFC 7518 §3.5)."""
    hname, scheme = JWS_ALGS[alg]
    k = (n.bit_length() + 7) // 8
    if len(sig) != k: return False
    s = int.from_bytes(sig, "big")
    if s >= n: return False
    em = pow(s, e, n).to_bytes(k, "big")
    h = hashlib.new(hname, msg).digest()
    if scheme == "pkcs1":
        t = DIGEST_INFO[hname] + h
        if k < len(t) + 11: return False
        return hmac.compare_digest(em, b"\x00\x01" + b"\xff" * (k - len(t) - 3) + b"\x00" + t)
    hlen = slen = len(h)
    embits = n.bit_length() - 1
    emlen = (embits + 7) // 8
    if emlen < k:
        if em[0] != 0: return False
        em = em[1:]
    if emlen < hlen + slen + 2 or em[-1] != 0xBC: return False
    masked_db, h2 = em[:emlen - hlen - 1], em[emlen - hlen - 1:-1]
    top = 8 * emlen - embits
    if top and masked_db[0] >> (8 - top): return False
    db = bytes(a ^ b for a, b in zip(masked_db, _mgf1(h2, len(masked_db), hname)))
    if top:
        db = bytes([db[0] & (0xFF >> top)]) + db[1:]
    ps = emlen - hlen - slen - 2
    if any(db[:ps]) or db[ps] != 0x01: return False
    return hmac.compare_digest(h2, hashlib.new(hname, b"\x00" * 8 + h + db[-slen:]).digest())

def verify_jwt(tok, region):
    """-> (header, claims, problems). Dies unless the signature verifies against an RSA key from
    Intel's key set for the region; exp/nbf violations are reported as problems (exit 2)."""
    parts = tok.split(".")
    if len(parts) != 3: die("token is not a compact JWS")
    try:
        hdr = json.loads(_b64url(parts[0])); claims = json.loads(_b64url(parts[1])); sig = _b64url(parts[2])
    except (ValueError, TypeError) as e:
        die("token is not decodable: %s" % e)
    if not isinstance(hdr, dict) or not isinstance(claims, dict): die("token header or payload is not an object")
    alg = hdr.get("alg")
    if alg not in JWS_ALGS: die("token alg %r is not an RSA signature algorithm; refusing" % alg)
    kid = hdr.get("kid")
    keys = http_json(ITA[region]["jwks"], headers={"Accept": "application/json"}, what="key set fetch")
    keys = keys.get("keys") if isinstance(keys, dict) else None
    cands = [k for k in (keys or []) if isinstance(k, dict) and k.get("kty") == "RSA"
             and (kid is None or k.get("kid") == kid) and (not k.get("alg") or k["alg"] == alg)]
    if not cands: die("no RSA key for kid %r/%s in Intel's key set %s" % (kid, alg, ITA[region]["jwks"]))
    msg = (parts[0] + "." + parts[1]).encode()
    for k in cands:
        try:
            n = int.from_bytes(_b64url(k["n"]), "big"); e = int.from_bytes(_b64url(k["e"]), "big")
        except (KeyError, ValueError, TypeError):
            continue
        if n > 2 and e > 1 and rsa_verify(n, e, msg, sig, alg):
            break
    else:
        die("token signature does not verify against Intel's key set (kid %r, %s)" % (kid, alg))
    P, now = [], time.time()
    exp, nbf = claims.get("exp"), claims.get("nbf")
    if isinstance(exp, (int, float)) and now > exp + JWT_LEEWAY: P.append("token expired at %d" % exp)
    if isinstance(nbf, (int, float)) and now < nbf - JWT_LEEWAY: P.append("token not valid before %d" % nbf)
    return hdr, claims, P

def ita_verdict(s):
    """ITA's attester_tcb_status ('UpToDate', 'OutOfDate', 'SWHardeningNeeded', ...) -> QVL verdict name,
    so one TDX_ATTEST_ACCEPT policy covers both verifiers."""
    if not s: return "UNSPECIFIED"
    s = str(s)
    if s in VERDICTS.values(): return s
    t = re.sub(r"(?<=[a-z0-9])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])", "_", s).upper().replace("CONFIGURATION", "CONFIG")
    return "OK" if t == "UP_TO_DATE" else t

def cmd_ita_nonce(argv):
    if not 1 <= len(argv) <= 2 or argv[0] not in ITA: die(USAGE)
    region, out = argv[0], (argv[1] if len(argv) > 1 else "./ita-nonce.json")
    vn = http_json(ITA[region]["api"] + ITA_NONCE,
                   headers={"x-api-key": ita_key(), "Accept": "application/json"},
                   what="Intel Trust Authority nonce")
    try:
        val = base64.b64decode(vn["val"], validate=True); iat = base64.b64decode(vn["iat"], validate=True)
        vn = {"val": vn["val"], "iat": vn["iat"], "signature": vn["signature"]}
    except (KeyError, ValueError, TypeError) as e:
        die("unexpected nonce answer from Intel Trust Authority: %s" % e)
    with open(out, "w") as f: json.dump(vn, f, indent=2)
    print("wrote %s; copy it into the guest and run there: tdx-attest quote --ita-nonce %s att.json"
          % (out, os.path.basename(out)))
    print("REPORTDATA the guest will bind: %s" % ita_report_data(val, iat).hex())
    return 0

def cmd_verify_ita(argv):
    as_json = "--json" in argv
    args, nonce_arg = [], None
    it = iter(a for a in argv if a != "--json")
    for a in it:
        if a == "--nonce":
            nonce_arg = next(it, None)
            if nonce_arg is None: die("--nonce needs a value")
        else:
            args.append(a)
    if not 2 <= len(args) <= 3 or args[1] not in ITA: die(USAGE)
    path, region = args[0], args[1]
    ref = load_reference(args[2]) if len(args) == 3 else {}
    envj, q = load_envelope(path)
    if not is_tdx_v4(q):
        die("not a TDX v4 quote (len=%d version=%d tee=%s)" % (len(q), q[0], q[4:6].hex()))

    ita_nonce = envj.get("ita_nonce")
    if ita_nonce is not None:
        if nonce_arg is not None: die("the envelope binds an Intel verifier nonce; --nonce does not apply")
        try:
            expect = ita_report_data(base64.b64decode(ita_nonce["val"], validate=True),
                                     base64.b64decode(ita_nonce["iat"], validate=True))
            ita_nonce = {k: ita_nonce[k] for k in ("val", "iat", "signature")}
        except (KeyError, ValueError, TypeError) as e:
            die("envelope ita_nonce is malformed: %s" % e)
    elif nonce_arg is not None:
        expect = parse_nonce(nonce_arg)
    else:
        try: expect = unhexlify(envj.get("nonce") or "")
        except ValueError: die("envelope nonce is not hex")
        note("no --nonce given: checking the nonce recorded in the envelope; compare it with the one you issued")

    body = {"quote": envj["quote"]}
    if ita_nonce is not None:
        body["verifier_nonce"] = ita_nonce
    ans = http_json(ITA[region]["api"] + ITA_ATTEST, data=json.dumps(body).encode(),
                    headers={"x-api-key": ita_key(), "Accept": "application/json", "Content-Type": "application/json"},
                    what="Intel Trust Authority attest")
    tok = ans.get("token") if isinstance(ans, dict) else None
    if not isinstance(tok, str): die("Intel Trust Authority answered without a token: %s" % json.dumps(ans)[:300])
    out = os.path.splitext(path)[0] + ".ita.jwt"
    with open(out, "w") as f: f.write(tok + "\n")
    note("wrote %s (Intel's signed attestation token)" % out)

    hdr, claims, P = verify_jwt(tok, region)
    if as_json:
        print(json.dumps(claims, indent=2))
    exp = claims.get("exp")
    exp_s = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime(exp)) if isinstance(exp, (int, float)) else "n/a"
    print("Token: signature verified against Intel's key set (kid %s, %s), expires %s" % (hdr.get("kid"), hdr.get("alg"), exp_s))
    if claims.get("iss") not in (None, ITA_ISSUER):
        note("token issuer is %r, expected %r" % (claims.get("iss"), ITA_ISSUER))
    if str(claims.get("attester_type", "TDX")).upper() != "TDX":
        P.append("attester_type is %s, not TDX" % claims.get("attester_type"))
    tdx = claims.get("tdx") if isinstance(claims.get("tdx"), dict) else claims

    raw = claims.get("attester_tcb_status")
    verdict = ita_verdict(raw)
    adv = claims.get("attester_advisory_ids") or []
    print("TCB status: %s%s  (advisories: %s)" % (verdict, " [%s]" % raw if raw and str(raw) != verdict else "",
                                                 ", ".join(map(str, adv)) or "none"))
    if verdict in NEVER_ACCEPT or verdict not in VERDICTS.values():
        P.append("quote rejected by Intel Trust Authority: %s" % (raw or verdict))
    elif not verdict_accepted(verdict):
        P.append("TCB verdict %s not in accepted set %s" % (verdict, sorted(ACCEPT - NEVER_ACCEPT)))

    debug = bool(tdx.get("tdx_is_debuggable") or tdx.get("tdx_td_attributes_debug") or claims.get("dbgstat") == "enabled")
    attrs = _claim_bytes(tdx.get("tdx_td_attributes"))
    if attrs and len(attrs) == 8:
        debug = debug or bool(int.from_bytes(attrs, "little") & 1)
    print("TD debug: %s" % ("ENABLED" if debug else "DISABLED"))
    if debug:
        P.append("TD DEBUG attribute set: host can inspect this TD")

    rd = _claim_bytes(tdx.get("tdx_report_data"))
    bound = rd is not None and rd == expect.ljust(64, b"\x00")
    print("BIND: %s (tdx_report_data claim)" % ("matches" if bound else "MISMATCH"))
    if rd is None:
        P.append("token carries no tdx_report_data claim; the nonce cannot be checked")
    elif not bound:
        P.append("tdx_report_data does not match the nonce")
    if ita_nonce is not None:
        vn = claims.get("verifier_nonce")
        ok = isinstance(vn, dict) and vn.get("val") == ita_nonce["val"] and vn.get("iat") == ita_nonce["iat"]
        print("Verifier nonce: %s" % ("confirmed by Intel" if ok else "NOT in the token"))
        if not ok:
            P.append("token does not carry the verifier nonce we sent")

    for k in MEASUREMENTS:
        v = _claim_bytes(tdx.get("tdx_" + k))
        print("%s: %s" % (k.upper(), v.hex() if v else "n/a"))
    for k, v in ref.items():
        got = _claim_bytes(tdx.get("tdx_" + k))
        res = "ABSENT" if got is None else ("MATCH" if got.hex() == v else "MISMATCH")
        print("Reference %-11s: %s" % (k.upper(), res))
        if res != "MATCH":
            P.append("%s %s" % (k, "missing from the token" if res == "ABSENT" else "differs from reference"))
    print()
    if P:
        print("FAIL: " + "; ".join(P))
        return EXIT_FAIL
    print("PASS: Intel Trust Authority token verified, TCB %s, nonce bound%s" % (verdict, ", reference matched" if ref else ""))
    return 0

def main():
    if len(sys.argv) < 2: die(USAGE)
    mode, args = sys.argv[1], sys.argv[2:]
    ignored = sorted(ACCEPT & NEVER_ACCEPT)
    if ignored:
        note("TDX_ATTEST_ACCEPT lists %s; those verdicts are always rejected" % ", ".join(ignored))
    if mode == "quote": cmd_quote(args)
    elif mode == "self-check": sys.exit(cmd_selfcheck(args))
    elif mode == "verify": sys.exit(cmd_verify(args))
    elif mode == "verify-ita": sys.exit(cmd_verify_ita(args))
    elif mode == "ita-nonce": sys.exit(cmd_ita_nonce(args))
    elif mode in ("-V", "--version"): print("tdx-attest " + __version__)
    else: die("unknown mode %r\n%s" % (mode, USAGE))

if __name__ == "__main__":
    main()
