Skip to main content

phytrace_sdk/core/
signer.rs

1//! Signing back ends for provenance signatures.
2//!
3//! [`ProvenanceSigner`](crate::core::provenance::ProvenanceSigner) builds the
4//! signing payload and the provenance block; a [`Signer`] turns the payload
5//! bytes into a signature.  Two are defined:
6//!
7//! | `signer` | `algorithm`   | Key                          | Use                   |
8//! |----------|---------------|------------------------------|-----------------------|
9//! | `hmac`   | `hmac-sha256` | Shared secret                | Development and tests |
10//! | `tpm`    | `es256`       | Non-exportable TPM 2.0 key   | Production (PhyTAU)   |
11//!
12//! [`HmacSigner`] lives here.  The TPM signer is in the separate
13//! `phytrace-tpm` crate so that the SDK does not link the TPM software
14//! stack unless a deployment needs it.  The Python SDK defines the same
15//! signers with the same `signer`, `algorithm` and signature encodings.
16
17use hmac::{Hmac, Mac};
18use sha2::Sha256;
19
20use crate::error::{PhyTraceError, PhyTraceResult};
21
22type HmacSha256 = Hmac<Sha256>;
23
24/// `provenance.algorithm` for ECDSA P-256 with SHA-256.  The signature is
25/// the 64-byte `r || s` (each big-endian, zero-padded to 32 bytes) as
26/// lowercase hex, as in JWS ES256.
27pub const ES256: &str = "es256";
28
29/// `provenance.algorithm` for HMAC-SHA256, signature as lowercase hex.
30pub const HMAC_SHA256: &str = "hmac-sha256";
31
32/// PCRs quoted by default: the firmware and boot-loader measurements.
33pub const DEFAULT_PCRS: &str = "sha256:0,1,2,3,4,5,6,7";
34
35/// A TPM2 quote: the TPM-generated `TPMS_ATTEST` and the attestation key's
36/// ES256 signature over it (hex `r || s`).  Same encoding as the Python
37/// SDK's `Quote`.
38#[derive(Debug, Clone, PartialEq, Eq)]
39pub struct Quote {
40    /// Marshalled `TPMS_ATTEST`.
41    pub attest: Vec<u8>,
42    /// Attestation key's ES256 signature over `attest`, hex `r || s`.
43    pub signature: String,
44    /// The PCR selection quoted, e.g. `sha256:0,1,2,3,4,5,6,7`.
45    pub pcr_selection: String,
46}
47
48/// Produces and checks provenance signatures over signing-payload bytes.
49pub trait Signer: Send + Sync {
50    /// Signer class sent as `provenance.signer`, e.g. `"hmac"` or `"tpm"`.
51    fn signer_class(&self) -> &str;
52
53    /// Algorithm sent as `provenance.algorithm`.
54    fn algorithm(&self) -> &str;
55
56    /// Key identifier sent as `provenance.key_id`.
57    fn key_id(&self) -> Option<&str>;
58
59    /// Sign `payload`, returning the encoded signature.
60    fn sign(&self, payload: &[u8]) -> PhyTraceResult<String>;
61
62    /// Check `signature` over `payload`.
63    fn verify(&self, payload: &[u8], signature: &str) -> PhyTraceResult<bool>;
64
65    /// Hardware-anchored count of agent starts, sent as
66    /// `provenance.boot_counter`.  A TPM signer reads it from a TPM NV
67    /// counter that it increments once per start; it never decreases, so
68    /// receivers can order events by `(boot_counter, sequence_num)` even if
69    /// the sequence state file is rolled back.  `None` for signers without
70    /// one.
71    fn boot_counter(&self) -> Option<u64> {
72        None
73    }
74
75    /// DER `SubjectPublicKeyInfo` of the signing key, for enrolling the
76    /// device with PhyCloud.  `None` for shared-secret signers.
77    fn public_key_der(&self) -> Option<&[u8]> {
78        None
79    }
80
81    /// DER `SubjectPublicKeyInfo` of the attestation key (a restricted TPM
82    /// key), if the signer has one.
83    fn attestation_key_der(&self) -> Option<&[u8]> {
84        None
85    }
86
87    /// TPM2 quote over `pcrs` (e.g. [`DEFAULT_PCRS`]) bound to `nonce`,
88    /// signed by the attestation key.  `None` if the signer cannot quote.
89    fn quote(&self, _nonce: &[u8], _pcrs: &str) -> Option<PhyTraceResult<Quote>> {
90        None
91    }
92}
93
94/// HMAC-SHA256 with a shared secret.  The verifier needs the same secret,
95/// so this proves nothing about which device signed; use it for
96/// development and tests only.
97#[derive(Clone)]
98pub struct HmacSigner {
99    key_id: Option<String>,
100    secret_key: Vec<u8>,
101}
102
103impl HmacSigner {
104    /// Create an HMAC signer from raw key bytes.
105    pub fn new(key_id: Option<String>, secret_key: Vec<u8>) -> Self {
106        Self { key_id, secret_key }
107    }
108}
109
110impl std::fmt::Debug for HmacSigner {
111    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
112        f.debug_struct("HmacSigner")
113            .field("key_id", &self.key_id)
114            .finish_non_exhaustive()
115    }
116}
117
118impl Signer for HmacSigner {
119    fn signer_class(&self) -> &str {
120        "hmac"
121    }
122
123    fn algorithm(&self) -> &str {
124        HMAC_SHA256
125    }
126
127    fn key_id(&self) -> Option<&str> {
128        self.key_id.as_deref()
129    }
130
131    fn sign(&self, payload: &[u8]) -> PhyTraceResult<String> {
132        let mut mac = HmacSha256::new_from_slice(&self.secret_key)
133            .map_err(|e| PhyTraceError::Crypto(format!("Invalid key length: {e}")))?;
134        mac.update(payload);
135        Ok(to_hex(&mac.finalize().into_bytes()))
136    }
137
138    fn verify(&self, payload: &[u8], signature: &str) -> PhyTraceResult<bool> {
139        let expected = self.sign(payload)?;
140        // Constant-time comparison of the hex strings.
141        let diff = expected
142            .bytes()
143            .zip(signature.bytes())
144            .fold(0u8, |acc, (a, b)| acc | (a ^ b));
145        Ok(expected.len() == signature.len() && diff == 0)
146    }
147}
148
149/// Lowercase hex encoding of `bytes`.
150pub fn to_hex(bytes: &[u8]) -> String {
151    let mut out = String::with_capacity(bytes.len() * 2);
152    for b in bytes {
153        crate::core::canonical::push_hex(&mut out, u32::from(*b), 2);
154    }
155    out
156}
157
158#[cfg(test)]
159mod tests {
160    use super::*;
161
162    #[test]
163    fn hmac_signer_round_trip() {
164        let signer = HmacSigner::new(Some("k1".to_string()), b"secret".to_vec());
165        assert_eq!(signer.signer_class(), "hmac");
166        assert_eq!(signer.algorithm(), "hmac-sha256");
167        assert_eq!(signer.key_id(), Some("k1"));
168        let sig = signer.sign(b"payload").unwrap();
169        assert_eq!(sig.len(), 64);
170        assert!(signer.verify(b"payload", &sig).unwrap());
171        assert!(!signer.verify(b"payload!", &sig).unwrap());
172        assert!(!signer.verify(b"payload", sig.get(..62).unwrap()).unwrap());
173    }
174
175    #[test]
176    fn debug_does_not_print_the_secret() {
177        let signer = HmacSigner::new(None, b"top-secret".to_vec());
178        assert!(!format!("{signer:?}").contains("top-secret"));
179    }
180}