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 lastquote_idis 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 TYPE: |
endpoint | PhyCloud base URL. TYPE: |
api_key | The device's API key ( TYPE: |
source_id | The device's source. TYPE: |
interval_sec | How often to quote. TYPE: |
pcrs | PCR selection to quote. TYPE: |
Source code in phytrace/attestation.py
Methods:¶
refresh ¶
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
due ¶
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:
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:
- Each event is numbered and gets its provenance block, without a signature.
- The events are hashed into a Merkle tree (RFC 9162: leaf
SHA-256(0x00 ‖ payload), nodeSHA-256(0x01 ‖ left ‖ right)). An event's leaf payload is its usual signing payload, withoutprovenance.batch. - 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 earlierphytrace.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) andsigned_at. - Each event carries
provenance.batch: the statement, its signature, the event'sleaf_indexand its inclusionproof(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 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
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 withoutuserWithAuth, so its empty password no longer works. - Each release ships an approval: the
PolicyPCRdigest 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) andPolicyAuthorizewith 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 ¶
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 ¶
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 ¶
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
Functions:¶
authority_public ¶
authority_name ¶
key_auth_policy ¶
authPolicy of a signing key bound to public_key_der's approvals.
Source code in phytrace/core/boot_policy.py
parse_selection ¶
PCR indices of "sha256:8,9"; only SHA-256 banks are supported.
Source code in phytrace/core/boot_policy.py
pcr_selection_bytes ¶
Marshalled TPML_PCR_SELECTION with one SHA-256 bank.
Source code in phytrace/core/boot_policy.py
pcr_policy ¶
PolicyPCR digest for the given PCR values (index → 32 bytes).
Source code in phytrace/core/boot_policy.py
approval_digest ¶
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
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
Signer ¶
Bases: ABC
Produces and checks provenance signatures over signing-payload bytes.
Attributes¶
signer_class instance-attribute ¶
Sent as provenance.signer, e.g. "hmac" or "tpm".
boot_counter class-attribute instance-attribute ¶
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 ¶
verify abstractmethod ¶
HmacSigner ¶
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
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. TYPE: |
key_handle | Persistent handle of the signing key. TYPE: |
counter_index | NV index of the boot counter. TYPE: |
ak_handle | Persistent handle of the attestation key. TYPE: |
boot_policy | Bind the signing key to approved boots (issue #532). The key is created with TYPE: |
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: TYPE: |
endorsement_auth | Password of the endorsement hierarchy, needed to recreate the EK for hardware binding once it is set. TYPE: |
| RAISES | DESCRIPTION |
|---|---|
ImportError | if |
RuntimeError | if the handle or NV index holds something else, or the key at |
Source code in phytrace/core/signers.py
Attributes¶
public_key_pem property ¶
The signing key's public key as PEM, for enrolling the device.
Methods:¶
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
ek_certificate ¶
ek_public ¶
The EK's TPMT_PUBLIC.
public_area ¶
ak_public_area ¶
ak_name ¶
activate_credential ¶
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
certify_signing_key ¶
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
verify_es256 ¶
Check an ES256 provenance signature (hex r || s) over payload against a DER SubjectPublicKeyInfo. Needs cryptography.
Source code in phytrace/core/signers.py
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
signing_payload_from_dict ¶
: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
canonical_json ¶
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
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: |
signing_key | Optional key for signing events (HMAC-SHA256) TYPE: |
include_device_attestation | Whether to include device attestation TYPE: |
agent_version | SDK/agent version string TYPE: |
key_id | Optional identifier of the signing key, sent (and signed) in the provenance block TYPE: |
signer | Optional signing back end, e.g. a :class: TYPE: |
attestor | Optional :class: TYPE: |
sequence_path | Optional state file for the sequence counter. When set, sequence numbers never decrease across restarts (production mode) and TYPE: |
| RAISES | DESCRIPTION |
|---|---|
SequenceStateError | if |
Source code in phytrace/core/provenance.py
Attributes¶
persistent_sequence property ¶
Whether sequence numbers survive restarts (production mode).
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: |
| RETURNS | DESCRIPTION |
|---|---|
TaggedEvent | TaggedEvent with provenance metadata |
Source code in phytrace/core/provenance.py
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
reset_sequence ¶
Reset an in-memory sequence counter (development and tests).
| RAISES | DESCRIPTION |
|---|---|
RuntimeError | in production mode ( |
Source code in phytrace/core/provenance.py
close ¶
Persist the sequence counter's exact position (clean shutdown) and release the signer (e.g. the TPM connection).
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 ¶
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.