Skip to main content

phytrace_sdk/core/
enrollment.rs

1//! Register a device's keys with PhyCloud (issues #397, #453), and bind
2//! them to the device's TPM (issue #452).
3//!
4//! PhyCloud only trusts ES256 event signatures from keys enrolled for the
5//! event's source, and TPM quotes signed by the device's registered
6//! attestation key.  These helpers run once on the device, with an
7//! operator credential that has the `devices:write` scope; afterwards the
8//! device sends events with its normal `events:write` key.  They mirror
9//! the Python SDK's `phytrace.enrollment`.
10//!
11//! ```no_run
12//! # async fn run(signer: std::sync::Arc<dyn phytrace_sdk::core::signer::Signer>)
13//! #     -> phytrace_sdk::PhyTraceResult<()> {
14//! use phytrace_sdk::core::enrollment::{enroll_device, register_attestation_key};
15//!
16//! let device = enroll_device(
17//!     "https://api.phycloud.phyware.io", "operator-key", signer.as_ref(),
18//!     "turtlebot4-lite-01", Some("SLB9670-0001"),
19//! ).await?;
20//! let device_id = device["device_id"].as_str().unwrap_or_default();
21//! register_attestation_key("https://api.phycloud.phyware.io", "operator-key",
22//!     signer.as_ref(), device_id).await?;
23//! # Ok(()) }
24//! ```
25
26use base64::{engine::general_purpose::STANDARD as BASE64, Engine};
27use serde_json::{json, Value};
28use sha2::{Digest, Sha256};
29
30use crate::core::attestation::api_base;
31use crate::core::signer::{to_hex, Quote, Signer, ES256};
32use crate::error::{PhyTraceError, PhyTraceResult};
33
34/// The message a device signs to prove it holds the key it enrolls.
35pub fn enrollment_message(nonce: &str, source_id: &str) -> String {
36    format!("phycloud-device-enroll:v1:{nonce}:{source_id}")
37}
38
39/// The message a device's signing key signs to vouch for its AK.
40pub fn ak_registration_message(nonce: &str, ak_key_id: &str) -> String {
41    format!("phycloud-ak-register:v1:{nonce}:{ak_key_id}")
42}
43
44/// PEM `PUBLIC KEY` block for a DER `SubjectPublicKeyInfo`.
45pub fn public_key_pem(der: &[u8]) -> String {
46    let b64 = BASE64.encode(der);
47    let mut pem = String::from("-----BEGIN PUBLIC KEY-----\n");
48    for chunk in b64.as_bytes().chunks(64) {
49        pem.push_str(&String::from_utf8_lossy(chunk));
50        pem.push('\n');
51    }
52    pem.push_str("-----END PUBLIC KEY-----\n");
53    pem
54}
55
56/// Enroll `signer`'s key as the device for `source_id`; returns PhyCloud's
57/// device record.  Fails with HTTP 409 if the source already has an active
58/// device (use [`rotate_device_key`]).
59pub async fn enroll_device(
60    endpoint: &str,
61    api_key: &str,
62    signer: &dyn Signer,
63    source_id: &str,
64    serial: Option<&str>,
65) -> PhyTraceResult<Value> {
66    let pem = signing_pem(signer)?;
67    let client = Client::new(endpoint, api_key);
68    let nonce = client.nonce().await?;
69    client
70        .post(
71            "devices",
72            json!({
73                "source_id": source_id,
74                "serial": serial,
75                "public_key_pem": pem,
76                "algorithm": ES256,
77                "nonce": nonce,
78                "proof": signer.sign(enrollment_message(&nonce, source_id).as_bytes())?,
79            }),
80        )
81        .await
82}
83
84/// Replace device `device_id`'s key with `signer`'s; the old key is
85/// retired, so events signed before the rotation still verify.
86pub async fn rotate_device_key(
87    endpoint: &str,
88    api_key: &str,
89    signer: &dyn Signer,
90    device_id: &str,
91    source_id: &str,
92) -> PhyTraceResult<Value> {
93    let pem = signing_pem(signer)?;
94    let client = Client::new(endpoint, api_key);
95    let nonce = client.nonce().await?;
96    client
97        .post(
98            &format!("devices/{device_id}/keys"),
99            json!({
100                "public_key_pem": pem,
101                "algorithm": ES256,
102                "nonce": nonce,
103                "proof": signer.sign(enrollment_message(&nonce, source_id).as_bytes())?,
104            }),
105        )
106        .await
107}
108
109/// Register `signer`'s attestation key for enrolled device `device_id`,
110/// vouched for by its signing key.  Returns the device's AKs.
111pub async fn register_attestation_key(
112    endpoint: &str,
113    api_key: &str,
114    signer: &dyn Signer,
115    device_id: &str,
116) -> PhyTraceResult<Value> {
117    let ak_der = signer.attestation_key_der().ok_or_else(|| {
118        PhyTraceError::Provenance("signer has no attestation key; use a TPM signer".to_string())
119    })?;
120    let ak_key_id = to_hex(&Sha256::digest(ak_der));
121    let client = Client::new(endpoint, api_key);
122    let nonce = client.nonce().await?;
123    client
124        .post(
125            &format!("devices/{device_id}/attestation-key"),
126            json!({
127                "public_key_pem": public_key_pem(ak_der),
128                "nonce": nonce,
129                "proof": signer.sign(ak_registration_message(&nonce, &ak_key_id).as_bytes())?,
130            }),
131        )
132        .await
133}
134
135/// The TPM operations hardware-bound enrollment needs (issue #452);
136/// `phytrace_tpm::TpmSigner` implements it.
137pub trait HardwareIdentity {
138    /// The TPM manufacturer's ECC P-256 EK certificate (DER).
139    fn ek_certificate(&self) -> PhyTraceResult<Vec<u8>>;
140    /// The attestation key's marshalled `TPMT_PUBLIC`.
141    fn ak_public_area(&self) -> &[u8];
142    /// The signing key's marshalled `TPMT_PUBLIC`.
143    fn signing_public_area(&self) -> &[u8];
144    /// `TPM2_ActivateCredential` with the EK and the attestation key.
145    fn activate_credential(
146        &self,
147        credential_blob: &[u8],
148        encrypted_secret: &[u8],
149    ) -> PhyTraceResult<Vec<u8>>;
150    /// `TPM2_Certify` of the signing key by the attestation key over
151    /// `nonce`.
152    fn certify_signing_key(&self, nonce: &[u8]) -> PhyTraceResult<Quote>;
153}
154
155/// Prove to PhyCloud that the device's keys live in its TPM: send the EK
156/// certificate (and any intermediate CA certificates, DER) and the keys'
157/// public areas, answer PhyCloud's credential challenge with
158/// `TPM2_ActivateCredential`, and certify the signing key with the
159/// attestation key.  Returns the device, whose `hardware` block carries
160/// the device certificate if PhyCloud has a device CA.  The attestation
161/// key must already be registered ([`register_attestation_key`]).
162pub async fn bind_hardware(
163    endpoint: &str,
164    api_key: &str,
165    tpm: &dyn HardwareIdentity,
166    device_id: &str,
167    ek_chain: &[Vec<u8>],
168) -> PhyTraceResult<Value> {
169    let client = Client::new(endpoint, api_key);
170    let challenge = client
171        .post(
172            &format!("devices/{device_id}/hardware/challenge"),
173            json!({
174                "ek_certificate": BASE64.encode(tpm.ek_certificate()?),
175                "ek_chain": ek_chain.iter().map(|c| BASE64.encode(c)).collect::<Vec<_>>(),
176                "ak_public": BASE64.encode(tpm.ak_public_area()),
177                "signing_public": BASE64.encode(tpm.signing_public_area()),
178            }),
179        )
180        .await?;
181    let field = |name: &str| {
182        challenge
183            .get(name)
184            .and_then(Value::as_str)
185            .map(str::to_string)
186            .ok_or_else(|| PhyTraceError::Provenance(format!("challenge has no {name}")))
187    };
188    let decode = |name: &str| {
189        BASE64
190            .decode(field(name)?)
191            .map_err(|e| PhyTraceError::Provenance(format!("challenge {name}: {e}")))
192    };
193    let secret =
194        tpm.activate_credential(&decode("credential_blob")?, &decode("encrypted_secret")?)?;
195    let nonce = hex_decode(&field("certify_nonce")?)
196        .ok_or_else(|| PhyTraceError::Provenance("certify_nonce is not hex".to_string()))?;
197    let certify = tpm.certify_signing_key(&nonce)?;
198    client
199        .post(
200            &format!("devices/{device_id}/hardware/activate"),
201            json!({
202                "challenge_id": field("challenge_id")?,
203                "secret": to_hex(&secret),
204                "certify_attest": BASE64.encode(&certify.attest),
205                "certify_signature": certify.signature,
206            }),
207        )
208        .await
209}
210
211fn hex_decode(s: &str) -> Option<Vec<u8>> {
212    if s.len() % 2 != 0 {
213        return None;
214    }
215    (0..s.len())
216        .step_by(2)
217        .map(|i| u8::from_str_radix(s.get(i..i + 2)?, 16).ok())
218        .collect()
219}
220
221fn signing_pem(signer: &dyn Signer) -> PhyTraceResult<String> {
222    match signer.public_key_der() {
223        Some(der) if signer.algorithm() == ES256 => Ok(public_key_pem(der)),
224        _ => Err(PhyTraceError::Provenance(
225            "signer has no ES256 public key; enroll a TPM signer".to_string(),
226        )),
227    }
228}
229
230struct Client {
231    http: reqwest::Client,
232    base: String,
233    api_key: String,
234}
235
236impl Client {
237    fn new(endpoint: &str, api_key: &str) -> Self {
238        Self {
239            http: reqwest::Client::new(),
240            base: api_base(endpoint),
241            api_key: api_key.to_string(),
242        }
243    }
244
245    async fn nonce(&self) -> PhyTraceResult<String> {
246        self.post("devices/challenge", json!({}))
247            .await?
248            .get("nonce")
249            .and_then(Value::as_str)
250            .map(str::to_string)
251            .ok_or_else(|| PhyTraceError::Provenance("challenge has no nonce".to_string()))
252    }
253
254    async fn post(&self, path: &str, body: Value) -> PhyTraceResult<Value> {
255        let response = self
256            .http
257            .post(format!("{}/{path}", self.base))
258            .bearer_auth(&self.api_key)
259            .json(&body)
260            .send()
261            .await
262            .map_err(|e| PhyTraceError::Transport(format!("{path}: {e}")))?;
263        let status = response.status();
264        let value: Value = response.json().await.unwrap_or(Value::Null);
265        if !status.is_success() {
266            let message = value
267                .get("message")
268                .and_then(Value::as_str)
269                .unwrap_or("request failed");
270            return Err(PhyTraceError::Transport(format!(
271                "{path}: HTTP {status}: {message}"
272            )));
273        }
274        Ok(value)
275    }
276}