1use 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
34pub fn enrollment_message(nonce: &str, source_id: &str) -> String {
36 format!("phycloud-device-enroll:v1:{nonce}:{source_id}")
37}
38
39pub fn ak_registration_message(nonce: &str, ak_key_id: &str) -> String {
41 format!("phycloud-ak-register:v1:{nonce}:{ak_key_id}")
42}
43
44pub 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
56pub 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
84pub 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
109pub 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
135pub trait HardwareIdentity {
138 fn ek_certificate(&self) -> PhyTraceResult<Vec<u8>>;
140 fn ak_public_area(&self) -> &[u8];
142 fn signing_public_area(&self) -> &[u8];
144 fn activate_credential(
146 &self,
147 credential_blob: &[u8],
148 encrypted_secret: &[u8],
149 ) -> PhyTraceResult<Vec<u8>>;
150 fn certify_signing_key(&self, nonce: &[u8]) -> PhyTraceResult<Quote>;
153}
154
155pub 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}