Skip to content

Provenance

ProvenanceTagger.tag attaches the event's PhyUDM provenance block, signs the event together with that block, then adds the signature to it, so the signature is sent with the event:

"provenance": {
  "signature": "3f1c…",
  "algorithm": "hmac-sha256",
  "key_id": "device-key-1",
  "signed_at": "2026-10-27T10:00:00.123456+00:00",
  "sequence_num": 42,
  "boot_epoch": "5f0c6b1e2d3a4f5e8a9b0c1d2e3f4a5b",
  "agent_id": "agent-1a2b3c4d5e6f",
  "agent_version": "0.1.0",
  "clock_skew_detected": false
}

The HMAC covers signing_payload(event): the event as sent, without null members or provenance.signature, as canonical JSON (sorted keys, no whitespace, non-ASCII escaped). Everything else in the provenance block (signed_at, key_id, sequence_num, boot_epoch, agent id, device attestation) is signed, so it cannot be altered without breaking the signature. key_id is sent when the tagger is given one (AgentConfig.signing_key_id). The signature is lowercase hex. The Rust SDK signs exactly the same bytes, and both are checked against the shared vectors in PhyTrace/test-vectors/provenance-signing.json. To verify a received event, recompute the HMAC over signing_payload_from_dict(received_json) and compare it with provenance["signature"]; no SDK types are needed. PhyTraceAgent adds license metadata as provenance.license before signing (your extensions are left as you set them), and nothing may change the event after tag returns.

Device attestation

With provenance.attestation.enabled, each event's signed provenance block carries a device_attestation entry:

  • With the TPM signer: the agent quotes the TPM's PCRs over a PhyCloud nonce when it starts and then once per interval. Each event references the latest quote: {"mode": "tpm", "quote_id": "...", "quote_status": "verified"}. If a refresh fails, the last quote_id is kept and the error is included.
  • Without a TPM: {"mode": "software", "warning": "no hardware root of trust"}, so a software agent is never mistaken for an attested one.
provenance:
  signer: tpm
  attestation:
    enabled: true
    interval_sec: 3600
    pcrs: "sha256:0,1,2,3,4,5,6,7"

The TPM signer's attestation key (a restricted key at persistent handle 0x81000110 by default) must be registered once, vouched for by the device's signing key: phytrace.enrollment.register_attestation_key(endpoint, operator_key, signer, device_id).

Then bind the keys to the TPM, which proves to PhyCloud that they live in a genuine TPM and gets the device certificate: phytrace.enrollment.bind_hardware(endpoint, operator_key, signer, device_id). The TPM must have an ECC P-256 endorsement key certificate (NV index 0x01c0000a), as the Infineon SLB9670 does.

Attestor

Attestor(signer: Any, endpoint: str, api_key: str, source_id: str, interval_sec: float = 3600.0, pcrs: str = DEFAULT_PCRS, timeout: float = 10.0)

Keeps a current TPM quote registered with PhyCloud.

PARAMETER DESCRIPTION
signer

A TpmSigner (anything with quote(nonce, pcrs)).

TYPE: Any

endpoint

PhyCloud base URL.

TYPE: str

api_key

The device's API key (events:write).

TYPE: str

source_id

The device's source.

TYPE: str

interval_sec

How often to quote.

TYPE: float DEFAULT: 3600.0

pcrs

PCR selection to quote.

TYPE: str DEFAULT: DEFAULT_PCRS

Source code in phytrace/attestation.py
def __init__(
    self,
    signer: Any,
    endpoint: str,
    api_key: str,
    source_id: str,
    interval_sec: float = 3600.0,
    pcrs: str = DEFAULT_PCRS,
    timeout: float = 10.0,
):
    self.signer = signer
    self.source_id = source_id
    self.interval_sec = interval_sec
    self.pcrs = pcrs
    self._client = _Client(endpoint, api_key, timeout)
    self._lock = threading.Lock()
    self._current: dict[str, Any] = {
        "mode": "tpm",
        "quote_id": None,
        "error": "no quote yet",
    }
    self._last_attempt: float | None = None

Methods:

refresh

refresh() -> dict[str, Any]

Quote now and register the quote. Failures are recorded in the attestation block rather than raised, so telemetry keeps flowing.

Source code in phytrace/attestation.py
def refresh(self) -> dict[str, Any]:
    """Quote now and register the quote.  Failures are recorded in the
    attestation block rather than raised, so telemetry keeps flowing."""
    self._last_attempt = time.monotonic()
    try:
        nonce = self._client.post("attestation/nonce", {"source_id": self.source_id})[
            "nonce"
        ]
        quote = self.signer.quote(bytes.fromhex(nonce), self.pcrs)
        stored = self._client.post(
            "attestation/quotes",
            {
                "source_id": self.source_id,
                "nonce": nonce,
                "attest": base64.b64encode(quote.attest).decode("ascii"),
                "signature": quote.signature,
                "pcr_selection": quote.pcr_selection,
            },
        )
        block = {
            "mode": "tpm",
            "quote_id": stored["quote_id"],
            "quote_status": stored["status"],
        }
    except (EnrollmentError, OSError, ValueError, KeyError, RuntimeError) as e:
        logger.warning("TPM attestation failed: %s", e)
        with self._lock:
            previous = self._current.get("quote_id")
        block = {"mode": "tpm", "quote_id": previous, "error": str(e)}
    with self._lock:
        self._current = block
    return block

due

due() -> bool

Whether a refresh is due.

Source code in phytrace/attestation.py
def due(self) -> bool:
    """Whether a refresh is due."""
    return (
        self._last_attempt is None
        or time.monotonic() - self._last_attempt >= self.interval_sec
    )

current

current() -> dict[str, Any]

The attestation block for the next event.

Source code in phytrace/attestation.py
def current(self) -> dict[str, Any]:
    """The attestation block for the next event."""
    with self._lock:
        return dict(self._current)

Sequence numbers and boot epoch

boot_epoch is random and new each time a tagger (and so an agent) starts. sequence_num starts at 1. Set AgentConfig.sequence_path (YAML: provenance.sequence_path) so it never decreases across restarts:

provenance:
  sequence_path: /var/lib/phytrace/sequence.json

The counter reserves numbers ahead of use, so a crash can skip numbers but never reuses one, and PhyTraceAgent.stop() records the exact position so a clean restart has no gap. An unreadable state file raises SequenceStateError at start rather than restarting from 1. With a state file (production mode), reset_sequence() raises; without one the counter is in memory and can be reset, for development and tests.

Merkle batch signing

A TPM 2.0 makes roughly 5 to 50 ECDSA signatures per second, far fewer than the event rate of a busy robot. With batch signing the agent signs one batch statement per batch instead of every event:

  1. Each event is numbered and gets its provenance block, without a signature.
  2. The events are hashed into a Merkle tree (RFC 9162: leaf SHA-256(0x00 ‖ payload), node SHA-256(0x01 ‖ left ‖ right)). An event's leaf payload is its usual signing payload, without provenance.batch.
  3. The signer (the TPM key) signs the canonical JSON of the statement: type (udm.merkle-batch.v1, as PhyUDM defines it; PhyCloud also accepts the earlier phytrace.merkle-batch.v1), batch_id, root, leaf_count, first_sequence/last_sequence, boot_epoch, boot_counter, key_id, attestation (the TPM quote reference in force) and signed_at.
  4. Each event carries provenance.batch: the statement, its signature, the event's leaf_index and its inclusion proof (audit path, hex).

Every event still verifies on its own: check the statement's signature, then that the proof leads from the event's leaf to the statement's root, and that the event's sequence number, boot epoch and key match the statement. PhyCloud does this on ingest; the result is the usual signature_status. Changing, reordering or moving an event between positions breaks its proof.

provenance:
  batch_signing:
    enabled: true
    max_size: 64         # most events per signature
    max_latency_ms: 500  # longest an event waits for its batch

A batch is signed when it is full or when its first event has waited max_latency_ms (and at shutdown), so batch signing adds up to that much latency.

Session-key fallback (not used). The alternative is to have the TPM certify a software key held in RAM and sign every event with that. It is faster, but the event-signing key is then exportable: anyone who can read the agent's memory (root on the device, a memory dump) can sign events until the key expires, and nothing distinguishes those signatures from genuine ones. Merkle batching keeps every signature inside the TPM, so PhyTrace does not use a session key.

verify_batch_event

verify_batch_event(event: dict[str, Any], verify_signature: Any) -> bool

Verify a batch-signed event (JSON form): the statement's signature, checked with verify_signature(payload, signature), and the event's inclusion proof and provenance against the statement.

Source code in phytrace/core/provenance.py
def verify_batch_event(event: dict[str, Any], verify_signature: Any) -> bool:
    """Verify a batch-signed event (JSON form): the statement's signature,
    checked with ``verify_signature(payload, signature)``, and the event's
    inclusion proof and provenance against the statement."""
    from phytrace.core.merkle import STATEMENT_TYPE, leaf_hash, root_from_proof

    provenance = event.get("provenance") or {}
    batch = provenance.get("batch") or {}
    statement = batch.get("statement") or {}
    signature = batch.get("signature")
    if not isinstance(signature, str) or not verify_signature(
        canonical_json(statement).encode("utf-8"), signature
    ):
        return False
    sequence = provenance.get("sequence_num")
    if (
        statement.get("type") != STATEMENT_TYPE
        or provenance.get("boot_epoch") != statement.get("boot_epoch")
        or provenance.get("key_id") != statement.get("key_id")
        or not isinstance(sequence, int)
        or not statement.get("first_sequence", 0) <= sequence <= statement.get("last_sequence", -1)
    ):
        return False
    try:
        proof = [bytes.fromhex(p) for p in batch.get("proof", [])]
        root = bytes.fromhex(statement["root"])
        leaf = leaf_hash(leaf_payload_from_dict(event).encode("utf-8"))
        return root_from_proof(batch["leaf_index"], statement["leaf_count"], leaf, proof) == root
    except (KeyError, TypeError, ValueError):
        return False

Signers

The signature comes from a pluggable Signer (phytrace.core.signers), and the block records which one as provenance.signer:

signer algorithm Key Use
hmac hmac-sha256 Shared secret (signing_key) Development and tests
tpm es256 Non-exportable TPM 2.0 P-256 key Production

To sign with a TPM, install the tpm extra (pip install "phytrace[tpm]", which needs the system libtss2 library) and select it in the agent config:

provenance:
  signer: tpm
  tpm:
    tcti: device:/dev/tpmrm0      # or swtpm:host=127.0.0.1,port=2321
    key_handle: "0x81000100"
    counter_index: "0x01000100"   # TPM NV boot counter
  sequence_path: /var/lib/phytrace/sequence.json

On first use the key is created inside the TPM and made persistent at key_handle; later runs reuse it. Each start also increments a TPM NV counter at counter_index and sends the new value, signed, as provenance.boot_counter. The TPM never lets it decrease, so order events by (boot_counter, sequence_num): rolling back the sequence state file cannot make new events look older. key_id is the hex SHA-256 of the key's DER public key, and TpmSigner.public_key_pem gives the key to enroll with PhyCloud. The signature is hex r || s; check it with verify_es256(public_key_der, signing_payload_from_dict(event), signature).

To make the key boot-bound (it signs only while the PCRs match a release-approved boot; see Boot-bound signing keys), add the release authority's public key and its approvals. Use a new key_handle: an existing key cannot gain a policy.

provenance:
  signer: tpm
  tpm:
    key_handle: "0x81000120"
    boot_policy:
      authority: /etc/phytrace/release-key.pem
      approvals: /etc/phytrace/boot-approvals.json

If the PCRs match no approval, sending raises phytrace.core.boot_policy.BootStateError.

boot_policy

Boot-bound signing keys (issue #532).

The TPM signing key cannot leave the TPM, but anything that can open the TPM could make it sign. A boot policy makes the TPM refuse to sign unless the PCRs match a boot that a release authority approved:

  • The key is created with authPolicy = PolicyAuthorize(authority) and without userWithAuth, so its empty password no longer works.
  • Each release ships an approval: the PolicyPCR digest of its known-good PCR values, signed by the authority. New firmware or kernel releases ship new approvals, so devices keep signing without re-enrollment.
  • Before each signature the agent runs PolicyPCR (which takes the TPM's current PCR values) and PolicyAuthorize with an approval. If the PCRs differ from every approved boot, the TPM refuses.

All digests here are TPM 2.0 policy digests (Part 1 §19.7, Part 3 §23) with SHA-256::

authority name   = 0x000b || SHA-256(TPMT_PUBLIC of the authority key)
key authPolicy   = H(H(0^32 || TPM_CC_PolicyAuthorize || name) || POLICY_REF)
approved policy  = H(0^32 || TPM_CC_PolicyPCR || TPML_PCR_SELECTION
                     || H(selected PCR values))
approval message = H(approved policy || POLICY_REF)   (ES256-signed)

PhyTrace/test-vectors/boot-policy.json pins these for the Python and Rust SDKs and PhyCloud.

Attributes

POLICY_REF module-attribute

POLICY_REF = b'phytau-boot-policy-v1'

policyRef of every PhyTAU boot policy, so the authority's other signatures (e.g. on attestation reference values) can never authorize it.

AUTHORITY_ATTRIBUTES module-attribute

AUTHORITY_ATTRIBUTES = SIGN_ENCRYPT | USER_WITH_AUTH

Attributes of the authority key as loaded into the TPM; part of its name, so every implementation must use the same.

Classes

BootStateError

Bases: RuntimeError

The TPM's PCRs match no approved boot, so the boot-bound key will not sign. The device booted something other than an approved release.

Approval dataclass

Approval(pcr_selection: str, approved_policy: bytes, signature: str, label: str = '')

A release's approved boot: its PolicyPCR digest signed by the authority (ES256 over :func:approval_digest, hex r || s).

BootPolicy dataclass

BootPolicy(authority_public_key_der: bytes, approvals: tuple[Approval, ...])

The authority whose approvals unlock the signing key, and the approvals this device may boot with.

Methods:
load classmethod
load(authority_pem: str, approvals_json: str) -> BootPolicy

From the authority's PEM public key and a JSON list of approvals (or a single approval).

Source code in phytrace/core/boot_policy.py
@classmethod
def load(cls, authority_pem: str, approvals_json: str) -> BootPolicy:
    """From the authority's PEM public key and a JSON list of approvals
    (or a single approval)."""
    from cryptography.hazmat.primitives import serialization

    key = serialization.load_pem_public_key(authority_pem.encode())
    der = key.public_bytes(
        serialization.Encoding.DER, serialization.PublicFormat.SubjectPublicKeyInfo
    )
    data = json.loads(approvals_json)
    items = data if isinstance(data, list) else [data]
    return cls(der, tuple(Approval.from_json(a) for a in items))

Functions:

authority_public

authority_public(public_key_der: bytes) -> bytes

Marshalled TPMT_PUBLIC of the authority's P-256 key, as loaded with TPM2_LoadExternal.

Source code in phytrace/core/boot_policy.py
def authority_public(public_key_der: bytes) -> bytes:
    """Marshalled ``TPMT_PUBLIC`` of the authority's P-256 key, as loaded
    with ``TPM2_LoadExternal``."""
    x, y = _point(public_key_der)
    return b"".join(
        [
            _u16(TPM_ALG_ECC),
            _u16(TPM_ALG_SHA256),
            _u32(AUTHORITY_ATTRIBUTES),
            _u16(0),  # authPolicy
            _u16(TPM_ALG_NULL),  # symmetric
            _u16(TPM_ALG_ECDSA),
            _u16(TPM_ALG_SHA256),
            _u16(TPM_ECC_NIST_P256),
            _u16(TPM_ALG_NULL),  # kdf
            _u16(32),
            x,
            _u16(32),
            y,
        ]
    )

authority_name

authority_name(public_key_der: bytes) -> bytes

TPM name of the authority key.

Source code in phytrace/core/boot_policy.py
def authority_name(public_key_der: bytes) -> bytes:
    """TPM name of the authority key."""
    return _u16(TPM_ALG_SHA256) + _sha256(authority_public(public_key_der))

key_auth_policy

key_auth_policy(public_key_der: bytes) -> bytes

authPolicy of a signing key bound to public_key_der's approvals.

Source code in phytrace/core/boot_policy.py
def key_auth_policy(public_key_der: bytes) -> bytes:
    """``authPolicy`` of a signing key bound to ``public_key_der``'s approvals."""
    step = _sha256(
        bytes(32), _u32(TPM_CC_POLICY_AUTHORIZE), authority_name(public_key_der)
    )
    return _sha256(step, POLICY_REF)

parse_selection

parse_selection(selection: str) -> list[int]

PCR indices of "sha256:8,9"; only SHA-256 banks are supported.

Source code in phytrace/core/boot_policy.py
def parse_selection(selection: str) -> list[int]:
    """PCR indices of ``"sha256:8,9"``; only SHA-256 banks are supported."""
    bank, _, indices = selection.partition(":")
    if bank != "sha256" or not indices:
        raise ValueError(f"PCR selection must be sha256:<indices>, got {selection!r}")
    pcrs = sorted({int(i) for i in indices.split(",")})
    if any(not 0 <= i < 24 for i in pcrs):
        raise ValueError(f"PCR index out of range in {selection!r}")
    return pcrs

pcr_selection_bytes

pcr_selection_bytes(selection: str) -> bytes

Marshalled TPML_PCR_SELECTION with one SHA-256 bank.

Source code in phytrace/core/boot_policy.py
def pcr_selection_bytes(selection: str) -> bytes:
    """Marshalled ``TPML_PCR_SELECTION`` with one SHA-256 bank."""
    bitmap = bytearray(3)
    for i in parse_selection(selection):
        bitmap[i // 8] |= 1 << (i % 8)
    return _u32(1) + _u16(TPM_ALG_SHA256) + bytes([3]) + bytes(bitmap)

pcr_policy

pcr_policy(selection: str, pcr_values: dict[int, bytes]) -> bytes

PolicyPCR digest for the given PCR values (index → 32 bytes).

Source code in phytrace/core/boot_policy.py
def pcr_policy(selection: str, pcr_values: dict[int, bytes]) -> bytes:
    """``PolicyPCR`` digest for the given PCR values (index → 32 bytes)."""
    pcrs = parse_selection(selection)
    missing = [i for i in pcrs if i not in pcr_values]
    if missing:
        raise ValueError(f"no value for PCR {missing}")
    pcr_digest = _sha256(*(pcr_values[i] for i in pcrs))
    return _sha256(
        bytes(32), _u32(TPM_CC_POLICY_PCR), pcr_selection_bytes(selection), pcr_digest
    )

approval_digest

approval_digest(approved_policy: bytes) -> bytes

The digest the authority signs (aHash of TPM2_PolicyAuthorize).

Source code in phytrace/core/boot_policy.py
def approval_digest(approved_policy: bytes) -> bytes:
    """The digest the authority signs (``aHash`` of ``TPM2_PolicyAuthorize``)."""
    return _sha256(approved_policy, POLICY_REF)

sign_approval

sign_approval(private_key: Any, selection: str, pcr_values: dict[int, bytes], label: str = '') -> Approval

Approve a boot (release tooling). private_key is a cryptography P-256 private key. Needs cryptography.

Source code in phytrace/core/boot_policy.py
def sign_approval(
    private_key: Any, selection: str, pcr_values: dict[int, bytes], label: str = ""
) -> Approval:
    """Approve a boot (release tooling).  ``private_key`` is a
    ``cryptography`` P-256 private key.  Needs ``cryptography``."""
    from cryptography.hazmat.primitives import hashes
    from cryptography.hazmat.primitives.asymmetric import ec, utils

    approved = pcr_policy(selection, pcr_values)
    der = private_key.sign(
        approval_digest(approved), ec.ECDSA(utils.Prehashed(hashes.SHA256()))
    )
    r, s = utils.decode_dss_signature(der)
    return Approval(
        pcr_selection=selection,
        approved_policy=approved,
        signature=(r.to_bytes(32, "big") + s.to_bytes(32, "big")).hex(),
        label=label,
    )

verify_approval

verify_approval(public_key_der: bytes, approval: Approval) -> bool

Check an approval's signature (as the TPM will). Needs cryptography.

Source code in phytrace/core/boot_policy.py
def verify_approval(public_key_der: bytes, approval: Approval) -> bool:
    """Check an approval's signature (as the TPM will).  Needs
    ``cryptography``."""
    from cryptography.exceptions import InvalidSignature
    from cryptography.hazmat.primitives import hashes, serialization
    from cryptography.hazmat.primitives.asymmetric import ec, utils

    try:
        raw = bytes.fromhex(approval.signature)
    except ValueError:
        return False
    if len(raw) != 64:
        return False
    key = serialization.load_der_public_key(public_key_der)
    if not isinstance(key, ec.EllipticCurvePublicKey):
        return False
    der = utils.encode_dss_signature(
        int.from_bytes(raw[:32], "big"), int.from_bytes(raw[32:], "big")
    )
    try:
        key.verify(
            der,
            approval_digest(approval.approved_policy),
            ec.ECDSA(utils.Prehashed(hashes.SHA256())),
        )
    except InvalidSignature:
        return False
    return True

Signer

Bases: ABC

Produces and checks provenance signatures over signing-payload bytes.

Attributes

signer_class instance-attribute

signer_class: str

Sent as provenance.signer, e.g. "hmac" or "tpm".

algorithm instance-attribute

algorithm: str

Sent as provenance.algorithm.

key_id class-attribute instance-attribute

key_id: str | None = None

Sent as provenance.key_id.

boot_counter class-attribute instance-attribute

boot_counter: int | None = None

Hardware-anchored count of agent starts, sent as provenance.boot_counter. A TPM signer reads it from a TPM NV counter that it increments once per start; it never decreases, so receivers can order events by (boot_counter, sequence_num) even if the sequence state file is rolled back. None for signers without one.

Methods:

sign abstractmethod

sign(payload: bytes) -> str

Sign payload, returning the encoded signature.

Source code in phytrace/core/signers.py
@abstractmethod
def sign(self, payload: bytes) -> str:
    """Sign ``payload``, returning the encoded signature."""

verify abstractmethod

verify(payload: bytes, signature: str) -> bool

Check signature over payload.

Source code in phytrace/core/signers.py
@abstractmethod
def verify(self, payload: bytes, signature: str) -> bool:
    """Check ``signature`` over ``payload``."""

close

close() -> None

Release any resources (e.g. the TPM connection).

Source code in phytrace/core/signers.py
def close(self) -> None:  # noqa: B027 - optional hook, no-op by default
    """Release any resources (e.g. the TPM connection)."""

HmacSigner

HmacSigner(secret_key: bytes, key_id: str | None = None)

Bases: Signer

HMAC-SHA256 with a shared secret.

The verifier needs the same secret, so this proves nothing about which device signed; use it for development and tests only.

Source code in phytrace/core/signers.py
def __init__(self, secret_key: bytes, key_id: str | None = None):
    self._secret_key = secret_key
    self.key_id = key_id

TpmSigner

TpmSigner(tcti: str | None = None, key_handle: int = DEFAULT_KEY_HANDLE, counter_index: int = DEFAULT_COUNTER_INDEX, ak_handle: int = DEFAULT_AK_HANDLE, boot_policy: BootPolicy | None = None, owner_auth: bytes | None = None, endorsement_auth: bytes | None = None)

Bases: Signer

ES256 signer backed by a non-exportable TPM 2.0 key.

On first use the key is created under the owner storage hierarchy with fixedTPM | fixedParent | sensitiveDataOrigin and made persistent at key_handle; later runs reuse it. Each open also increments a TPM NV counter at counter_index (defined on first use) and exposes the new value as :attr:boot_counter. A second, restricted key at ak_handle is the attestation key (AK): restricted keys only sign data the TPM itself produced, so its signature on a :meth:quote cannot be forged with the unrestricted event-signing key. Every signing command runs in an HMAC session salted with the storage primary key, with parameter encryption on, so commands and responses on the bus are integrity-protected and the digest is encrypted.

PARAMETER DESCRIPTION
tcti

TCTI connection string, e.g. device:/dev/tpmrm0 or swtpm:host=127.0.0.1,port=2321. Defaults to PHYTRACE_TPM_TCTI, then TPM2TOOLS_TCTI, then device:/dev/tpmrm0.

TYPE: str | None DEFAULT: None

key_handle

Persistent handle of the signing key.

TYPE: int DEFAULT: DEFAULT_KEY_HANDLE

counter_index

NV index of the boot counter.

TYPE: int DEFAULT: DEFAULT_COUNTER_INDEX

ak_handle

Persistent handle of the attestation key.

TYPE: int DEFAULT: DEFAULT_AK_HANDLE

boot_policy

Bind the signing key to approved boots (issue #532). The key is created with authPolicy = PolicyAuthorize of the policy's authority and without userWithAuth, and every signature runs PolicyPCR + PolicyAuthorize with one of the policy's approvals. If the PCRs match no approval, :meth:sign raises :class:~phytrace.core.boot_policy.BootStateError; there is no fallback. A key made without a boot policy cannot become boot-bound: use a new key_handle and re-enroll.

TYPE: BootPolicy | None DEFAULT: None

owner_auth

Password of the owner hierarchy, once the device has been taken ownership of (issue #423). Only needed to create keys, the boot counter or the storage root key, or to read the EK certificate; an agent whose keys exist does not need it. The storage root key is used from its persistent handle (:data:~phytrace.core.tpm_policy.SRK_HANDLE) when present.

TYPE: bytes | None DEFAULT: None

endorsement_auth

Password of the endorsement hierarchy, needed to recreate the EK for hardware binding once it is set.

TYPE: bytes | None DEFAULT: None

RAISES DESCRIPTION
ImportError

if tpm2-pytss is not installed.

RuntimeError

if the handle or NV index holds something else, or the key at key_handle does not match boot_policy.

Source code in phytrace/core/signers.py
def __init__(
    self,
    tcti: str | None = None,
    key_handle: int = DEFAULT_KEY_HANDLE,
    counter_index: int = DEFAULT_COUNTER_INDEX,
    ak_handle: int = DEFAULT_AK_HANDLE,
    boot_policy: BootPolicy | None = None,
    owner_auth: bytes | None = None,
    endorsement_auth: bytes | None = None,
):
    from tpm2_pytss import ESAPI, ESYS_TR

    self._lock = threading.Lock()
    self._boot_policy = boot_policy
    self._tickets: dict[bytes, Any] = {}
    tcti = (
        tcti
        or os.environ.get("PHYTRACE_TPM_TCTI")
        or os.environ.get("TPM2TOOLS_TCTI")
        or "device:/dev/tpmrm0"
    )
    self._ectx: Any = ESAPI(tcti)
    try:
        if owner_auth is not None:
            self._ectx.tr_set_auth(ESYS_TR.OWNER, owner_auth)
        if endorsement_auth is not None:
            self._ectx.tr_set_auth(ESYS_TR.ENDORSEMENT, endorsement_auth)
        self._open(key_handle, counter_index, ak_handle)
    except BaseException:
        self._ectx.close()
        raise
    self.public_key_der = _P256_SPKI_PREFIX + self._public_point
    self.key_id = hashlib.sha256(self.public_key_der).hexdigest()
    self.ak_public_key_der = _P256_SPKI_PREFIX + self._ak_point
    self.ak_key_id = hashlib.sha256(self.ak_public_key_der).hexdigest()

Attributes

boot_bound property

boot_bound: bool

Whether the signing key only signs after an approved boot.

public_key_pem property

public_key_pem: str

The signing key's public key as PEM, for enrolling the device.

Methods:

quote

quote(nonce: bytes, pcrs: str = DEFAULT_PCRS) -> Quote

TPM2 quote over pcrs, bound to nonce (a PhyCloud challenge, carried as the quote's extraData), signed by the attestation key.

Source code in phytrace/core/signers.py
def quote(self, nonce: bytes, pcrs: str = DEFAULT_PCRS) -> Quote:
    """TPM2 quote over ``pcrs``, bound to ``nonce`` (a PhyCloud
    challenge, carried as the quote's ``extraData``), signed by the
    attestation key."""
    with self._lock:
        attest, signature = self._ectx.quote(self._ak, pcrs, nonce, session1=self._session)
    ecdsa = signature.signature.ecdsa
    r = _pad32(bytes(ecdsa.signatureR))
    s = _pad32(bytes(ecdsa.signatureS))
    return Quote(attest=bytes(attest), signature=(r + s).hex(), pcr_selection=pcrs)

ek_certificate

ek_certificate() -> bytes

The TPM manufacturer's ECC EK certificate (DER).

Source code in phytrace/core/signers.py
def ek_certificate(self) -> bytes:  # pragma: no cover
    """The TPM manufacturer's ECC EK certificate (DER)."""
    with self._lock:
        return self._ek()[0]

ek_public

ek_public() -> Any

The EK's TPMT_PUBLIC.

Source code in phytrace/core/signers.py
def ek_public(self) -> Any:  # pragma: no cover
    """The EK's ``TPMT_PUBLIC``."""
    with self._lock:
        ek = self._create_ek()
        try:
            return self._ectx.read_public(ek)[0].publicArea
        finally:
            self._ectx.flush_context(ek)

public_area

public_area() -> bytes

The signing key's marshalled TPMT_PUBLIC.

Source code in phytrace/core/signers.py
def public_area(self) -> bytes:  # pragma: no cover
    """The signing key's marshalled ``TPMT_PUBLIC``."""
    with self._lock:
        return self._ectx.read_public(self._key)[0].publicArea.marshal()

ak_public_area

ak_public_area() -> bytes

The attestation key's marshalled TPMT_PUBLIC.

Source code in phytrace/core/signers.py
def ak_public_area(self) -> bytes:  # pragma: no cover
    """The attestation key's marshalled ``TPMT_PUBLIC``."""
    with self._lock:
        return self._ectx.read_public(self._ak)[0].publicArea.marshal()

ak_name

ak_name() -> bytes

The attestation key's TPM name.

Source code in phytrace/core/signers.py
def ak_name(self) -> bytes:  # pragma: no cover
    """The attestation key's TPM name."""
    with self._lock:
        return bytes(self._ectx.read_public(self._ak)[1])

activate_credential

activate_credential(credential_blob: bytes, encrypted_secret: bytes) -> bytes

TPM2_ActivateCredential: recover the secret PhyCloud encrypted to this TPM's EK for the attestation key. Only the TPM holding both keys can do this.

Source code in phytrace/core/signers.py
def activate_credential(  # pragma: no cover
    self, credential_blob: bytes, encrypted_secret: bytes
) -> bytes:
    """``TPM2_ActivateCredential``: recover the secret PhyCloud encrypted
    to this TPM's EK for the attestation key.  Only the TPM holding both
    keys can do this."""
    from tpm2_pytss import (
        ESYS_TR,
        TPM2_ALG,
        TPM2_SE,
        TPM2B_ENCRYPTED_SECRET,
        TPM2B_ID_OBJECT,
        TPMT_SYM_DEF,
    )

    with self._lock:
        ek = self._create_ek()
        policy = None
        try:
            # The EK's default policy: PolicySecret(TPM_RH_ENDORSEMENT).
            policy = self._ectx.start_auth_session(
                tpm_key=ESYS_TR.NONE,
                bind=ESYS_TR.NONE,
                session_type=TPM2_SE.POLICY,
                symmetric=TPMT_SYM_DEF(algorithm=TPM2_ALG.NULL),
                auth_hash=TPM2_ALG.SHA256,
            )
            self._ectx.policy_secret(ESYS_TR.ENDORSEMENT, policy, b"", b"", b"", 0)
            secret = self._ectx.activate_credential(
                self._ak,
                ek,
                TPM2B_ID_OBJECT(credential_blob),
                TPM2B_ENCRYPTED_SECRET(encrypted_secret),
                session1=ESYS_TR.PASSWORD,
                session2=policy,
            )
        finally:
            if policy is not None:
                self._ectx.flush_context(policy)
            self._ectx.flush_context(ek)
    return bytes(secret)

certify_signing_key

certify_signing_key(nonce: bytes) -> Quote

TPM2_Certify of the signing key by the attestation key, bound to nonce: proves the signing key is an object in this TPM.

Source code in phytrace/core/signers.py
def certify_signing_key(self, nonce: bytes) -> Quote:  # pragma: no cover
    """``TPM2_Certify`` of the signing key by the attestation key, bound
    to ``nonce``: proves the signing key is an object in this TPM."""
    from tpm2_pytss import ESYS_TR, TPM2_ALG, TPMT_SIG_SCHEME

    with self._lock:
        attest, signature = self._ectx.certify(
            self._key,
            self._ak,
            nonce,
            TPMT_SIG_SCHEME(scheme=TPM2_ALG.NULL),
            session1=ESYS_TR.PASSWORD,
            session2=ESYS_TR.PASSWORD,
        )
    ecdsa = signature.signature.ecdsa
    r = _pad32(bytes(ecdsa.signatureR))
    s = _pad32(bytes(ecdsa.signatureS))
    return Quote(attest=bytes(attest), signature=(r + s).hex(), pcr_selection="")

verify_es256

verify_es256(public_key_der: bytes, payload: bytes, signature: str) -> bool

Check an ES256 provenance signature (hex r || s) over payload against a DER SubjectPublicKeyInfo. Needs cryptography.

Source code in phytrace/core/signers.py
def verify_es256(public_key_der: bytes, payload: bytes, signature: str) -> bool:
    """Check an ES256 provenance signature (hex ``r || s``) over ``payload``
    against a DER ``SubjectPublicKeyInfo``.  Needs ``cryptography``."""
    from cryptography.exceptions import InvalidSignature
    from cryptography.hazmat.primitives import hashes, serialization
    from cryptography.hazmat.primitives.asymmetric import ec
    from cryptography.hazmat.primitives.asymmetric.utils import encode_dss_signature

    try:
        raw = bytes.fromhex(signature)
    except ValueError:
        return False
    if len(raw) != 64:
        return False
    key = serialization.load_der_public_key(public_key_der)
    if not isinstance(key, ec.EllipticCurvePublicKey):
        raise ValueError("not an elliptic-curve public key")
    der_sig = encode_dss_signature(
        int.from_bytes(raw[:32], "big"), int.from_bytes(raw[32:], "big")
    )
    try:
        key.verify(der_sig, payload, ec.ECDSA(hashes.SHA256()))
    except InvalidSignature:
        return False
    return True

signing_payload

signing_payload

signing_payload(event: UDMEvent) -> str

The exact text an event's HMAC signature is computed over.

The event as sent (event.to_dict()), with null object members and provenance.signature removed (and the block itself if nothing else is in it), rendered as :func:canonical_json. The rest of the provenance block (sequence-bearing metadata, key id, timestamps, device attestation) is signed along with the event, so none of it can be changed without breaking the signature. The Rust SDK computes the same bytes from the same JSON; the shared vectors in PhyTrace/test-vectors/provenance-signing.json pin this down.

Source code in phytrace/core/provenance.py
def signing_payload(event: UDMEvent) -> str:
    """The exact text an event's HMAC signature is computed over.

    The event as sent (``event.to_dict()``), with ``null`` object members and
    ``provenance.signature`` removed (and the block itself if nothing else is
    in it), rendered as :func:`canonical_json`.
    The rest of the provenance block (sequence-bearing metadata, key id,
    timestamps, device attestation) is signed along with the event, so none
    of it can be changed without breaking the signature.
    The Rust SDK computes the same bytes
    from the same JSON; the shared vectors in
    ``PhyTrace/test-vectors/provenance-signing.json`` pin this down.
    """
    return signing_payload_from_dict(event.to_dict())

signing_payload_from_dict

signing_payload_from_dict(event: dict[str, Any]) -> str

:func:signing_payload for an event already in JSON form, e.g. as received over the wire. No SDK types are needed to verify.

Source code in phytrace/core/provenance.py
def signing_payload_from_dict(event: dict[str, Any]) -> str:
    """:func:`signing_payload` for an event already in JSON form, e.g. as
    received over the wire.  No SDK types are needed to verify."""
    stripped = _strip_nulls(event)
    provenance = stripped.get("provenance")
    if isinstance(provenance, dict):
        provenance.pop("signature", None)
        if not provenance:
            del stripped["provenance"]
    return canonical_json(stripped)

canonical_json

canonical_json(value: Any) -> str

Canonical JSON: sorted keys, no whitespace, non-ASCII escaped.

Byte-identical to the Rust SDK's and PhyCloud's canonical_json.

Source code in phytrace/core/provenance.py
def canonical_json(value: Any) -> str:
    """Canonical JSON: sorted keys, no whitespace, non-ASCII escaped.

    Byte-identical to the Rust SDK's and PhyCloud's ``canonical_json``.
    """
    return json.dumps(value, sort_keys=True, separators=(",", ":"), ensure_ascii=True)

ProvenanceTagger

ProvenanceTagger

ProvenanceTagger(source_id: str, signing_key: bytes | None = None, include_device_attestation: bool = False, agent_version: str = '0.1.0', key_id: str | None = None, sequence_path: str | None = None, signer: Signer | None = None, attestor: Any = None)

Tags events with provenance metadata for trust verification.

Provenance includes: - Capture timestamp (from source clock) - Send timestamp (when leaving SDK) - Sequence number (monotonic; never decreases across restarts when sequence_path is set) and a random boot epoch per tagger - Source signature (if signing key provided) - SDK version - Agent ID (unique per agent instance)

Initialize the provenance tagger.

PARAMETER DESCRIPTION
source_id

Identifier of the source system

TYPE: str

signing_key

Optional key for signing events (HMAC-SHA256)

TYPE: bytes | None DEFAULT: None

include_device_attestation

Whether to include device attestation

TYPE: bool DEFAULT: False

agent_version

SDK/agent version string

TYPE: str DEFAULT: '0.1.0'

key_id

Optional identifier of the signing key, sent (and signed) in the provenance block

TYPE: str | None DEFAULT: None

signer

Optional signing back end, e.g. a :class:~phytrace.core.signers.TpmSigner. Takes precedence over signing_key/key_id, which build an :class:~phytrace.core.signers.HmacSigner.

TYPE: Signer | None DEFAULT: None

attestor

Optional :class:~phytrace.attestation.Attestor whose latest TPM quote reference is used as the device attestation (implies include_device_attestation).

TYPE: Any DEFAULT: None

sequence_path

Optional state file for the sequence counter. When set, sequence numbers never decrease across restarts (production mode) and reset_sequence is refused. When unset the counter is in memory and restarts from 1.

TYPE: str | None DEFAULT: None

RAISES DESCRIPTION
SequenceStateError

if sequence_path exists but is unreadable.

Source code in phytrace/core/provenance.py
def __init__(
    self,
    source_id: str,
    signing_key: bytes | None = None,
    include_device_attestation: bool = False,
    agent_version: str = "0.1.0",
    key_id: str | None = None,
    sequence_path: str | None = None,
    signer: Signer | None = None,
    attestor: Any = None,
):
    """
    Initialize the provenance tagger.

    Args:
        source_id: Identifier of the source system
        signing_key: Optional key for signing events (HMAC-SHA256)
        include_device_attestation: Whether to include device attestation
        agent_version: SDK/agent version string
        key_id: Optional identifier of the signing key, sent (and
            signed) in the provenance block
        signer: Optional signing back end, e.g. a
            :class:`~phytrace.core.signers.TpmSigner`.  Takes precedence
            over ``signing_key``/``key_id``, which build an
            :class:`~phytrace.core.signers.HmacSigner`.
        attestor: Optional :class:`~phytrace.attestation.Attestor`
            whose latest TPM quote reference is used as the device
            attestation (implies ``include_device_attestation``).
        sequence_path: Optional state file for the sequence counter.
            When set, sequence numbers never decrease across restarts
            (production mode) and ``reset_sequence`` is refused.  When
            unset the counter is in memory and restarts from 1.

    Raises:
        SequenceStateError: if ``sequence_path`` exists but is unreadable.
    """
    self.source_id = source_id
    self.signing_key = signing_key
    self.include_device_attestation = include_device_attestation or attestor is not None
    self.attestor = attestor
    self.agent_version = agent_version
    if signer is None and signing_key:
        signer = HmacSigner(signing_key, key_id=key_id)
    self.signer = signer
    self.key_id = signer.key_id if signer is not None else key_id

    # Generate a unique agent instance ID
    self.agent_id = f"agent-{uuid.uuid4().hex[:12]}"

    # Monotonic sequence counter, and a random ID for this run so a
    # receiver can tell a restart from a replay
    self._sequence = SequenceCounter(sequence_path)
    self.boot_epoch = uuid.uuid4().hex

    # Track last capture time for clock skew detection
    self._last_capture_time: datetime | None = None

Attributes

persistent_sequence property

persistent_sequence: bool

Whether sequence numbers survive restarts (production mode).

current_sequence property

current_sequence: int

Get the current sequence number.

Methods:

tag

tag(event: UDMEvent) -> TaggedEvent

Add provenance metadata to event.

Sets sent_at and sequence_num, attaches the provenance block (including any device attestation) as event.provenance, then signs the event together with that block and adds the signature to it. Anything that changes the event or its provenance after this call invalidates the signature.

PARAMETER DESCRIPTION
event

The UDM event to tag

TYPE: UDMEvent

RETURNS DESCRIPTION
TaggedEvent

TaggedEvent with provenance metadata

Source code in phytrace/core/provenance.py
def tag(self, event: UDMEvent) -> TaggedEvent:
    """
    Add provenance metadata to event.

    Sets `sent_at` and `sequence_num`, attaches the provenance block
    (including any device attestation) as `event.provenance`, then signs
    the event together with that block and adds the signature to it.
    Anything that changes the event or its provenance after this call
    invalidates the signature.

    Args:
        event: The UDM event to tag

    Returns:
        TaggedEvent with provenance metadata
    """
    device_attestation = (
        self._get_device_attestation() if self.include_device_attestation else None
    )
    provenance = self._prepare(event, device_attestation)

    # Sign the event and its provenance block, then add the signature
    if self.signer:
        provenance.signature = self._sign_event(event)
        event.provenance = provenance.to_wire()

    return TaggedEvent(event=event, provenance=provenance)

tag_batch

tag_batch(events: list[UDMEvent]) -> list[TaggedEvent]

Tag events and sign them as one Merkle batch (issue #392).

Each event is numbered and gets its provenance block; the events are hashed into a Merkle tree and the signer signs only the batch statement (root, sequence range, boot epoch and counter, key, attestation), once for the whole batch. Each event's provenance.batch carries the statement, its signature and the event's inclusion proof, so it verifies on its own (:func:verify_batch_event).

Source code in phytrace/core/provenance.py
def tag_batch(self, events: list[UDMEvent]) -> list[TaggedEvent]:
    """Tag ``events`` and sign them as one Merkle batch (issue #392).

    Each event is numbered and gets its provenance block; the events are
    hashed into a Merkle tree and the signer signs only the batch
    statement (root, sequence range, boot epoch and counter, key,
    attestation), once for the whole batch.  Each event's
    ``provenance.batch`` carries the statement, its signature and the
    event's inclusion proof, so it verifies on its own
    (:func:`verify_batch_event`).
    """
    from phytrace.core.merkle import (
        STATEMENT_TYPE,
        audit_path,
        batch_block,
        leaf_hash,
        merkle_root,
    )

    if not self.signer:
        raise ValueError("No signer configured")
    if not events:
        return []
    device_attestation = (
        self._get_device_attestation() if self.include_device_attestation else None
    )
    prepared = [self._prepare(event, device_attestation) for event in events]
    leaves = [
        leaf_hash(leaf_payload_from_dict(event.to_dict()).encode("utf-8")) for event in events
    ]
    memo: dict = {}
    sequences = [p.sequence_num for p in prepared]
    statement: dict[str, Any] = {
        "type": STATEMENT_TYPE,
        "batch_id": uuid.uuid4().hex,
        "root": merkle_root(leaves, memo).hex(),
        "leaf_count": len(events),
        "first_sequence": min(sequences),
        "last_sequence": max(sequences),
        "boot_epoch": self.boot_epoch,
        "signed_at": now_utc().isoformat(),
    }
    if self.signer.boot_counter is not None:
        statement["boot_counter"] = self.signer.boot_counter
    if self.signer.key_id is not None:
        statement["key_id"] = self.signer.key_id
    if device_attestation is not None:
        statement["attestation"] = device_attestation
    signature = self.signer.sign(canonical_json(statement).encode("utf-8"))
    tagged = []
    for index, (event, provenance) in enumerate(zip(events, prepared, strict=True)):
        proof = audit_path(index, leaves, memo)
        provenance.batch = batch_block(statement, signature, index, proof)
        event.provenance = provenance.to_wire()
        tagged.append(TaggedEvent(event=event, provenance=provenance))
    return tagged

reset_sequence

reset_sequence() -> None

Reset an in-memory sequence counter (development and tests).

RAISES DESCRIPTION
RuntimeError

in production mode (sequence_path set), where the counter must never decrease.

Source code in phytrace/core/provenance.py
def reset_sequence(self) -> None:
    """Reset an in-memory sequence counter (development and tests).

    Raises:
        RuntimeError: in production mode (``sequence_path`` set), where
            the counter must never decrease.
    """
    self._sequence.reset()
    self._last_capture_time = None

close

close() -> None

Persist the sequence counter's exact position (clean shutdown) and release the signer (e.g. the TPM connection).

Source code in phytrace/core/provenance.py
def close(self) -> None:
    """Persist the sequence counter's exact position (clean shutdown)
    and release the signer (e.g. the TPM connection)."""
    self._sequence.close()
    if self.signer:
        self.signer.close()

ProvenanceMetadata

ProvenanceMetadata dataclass

ProvenanceMetadata(agent_id: str, agent_version: str, sequence_num: int, captured_at: datetime, sent_at: datetime, clock_skew_detected: bool = False, signature: str | None = None, signature_algorithm: str | None = None, device_attestation: dict[str, Any] | None = None, key_id: str | None = None, boot_epoch: str | None = None, signer: str | None = None, boot_counter: int | None = None, batch: dict[str, Any] | None = None, license: dict[str, Any] | None = None)

Provenance metadata added to events.

Methods:

to_wire

to_wire() -> dict[str, Any]

Render as the PhyUDM provenance block sent with the event.

signature, key_id, algorithm and signed_at are the schema's named fields (matching the Rust SDK); the rest are additional properties. Everything except signature is covered by the signature, so the block is complete before signing.

Source code in phytrace/core/provenance.py
def to_wire(self) -> dict[str, Any]:
    """Render as the PhyUDM `provenance` block sent with the event.

    `signature`, `key_id`, `algorithm` and `signed_at` are the schema's
    named fields (matching the Rust SDK); the rest are additional
    properties.  Everything except `signature` is covered by the
    signature, so the block is complete before signing.
    """
    block: dict[str, Any] = {
        "agent_id": self.agent_id,
        "agent_version": self.agent_version,
        "signed_at": self.sent_at.isoformat(),
        "sequence_num": self.sequence_num,
        "clock_skew_detected": self.clock_skew_detected,
    }
    if self.boot_epoch is not None:
        block["boot_epoch"] = self.boot_epoch
    if self.signature_algorithm is not None:
        block["algorithm"] = self.signature_algorithm
    if self.signer is not None:
        block["signer"] = self.signer
    if self.boot_counter is not None:
        block["boot_counter"] = self.boot_counter
    if self.key_id is not None:
        block["key_id"] = self.key_id
    if self.signature is not None:
        block["signature"] = self.signature
    if self.device_attestation is not None:
        block["device_attestation"] = self.device_attestation
    if self.batch is not None:
        block["batch"] = self.batch
    if self.license is not None:
        block["license"] = self.license
    return block