//! The probe's own state in `--out/identity/`: its client id, its test-only key and certificate (generated on the //! first run), and the host certificate pinned by `probe pair`. Nothing here is a real device's key; the folder //! stays out of git and is deleted after the sitting. use std::fs; use std::io::Write; use std::net::IpAddr; use std::path::{Path, PathBuf}; use std::time::{SystemTime, UNIX_EPOCH}; use domistream::RandomSource; use domistream::pairing::{ClientIdentity, ServerCert}; /// Largest state file read back. const MAX_STATE_FILE: u64 = 16 * 1024; pub const UNIQUE_ID_FILE: &str = "uniqueid.txt"; pub const CERT_FILE: &str = "client-cert.der"; pub const KEY_FILE: &str = "client-key.pk8"; pub const HOST_CERT_FILE: &str = "host-cert.der"; pub const HOST_ADDR_FILE: &str = "host-address.txt"; pub fn identity_dir(out: &Path) -> PathBuf { out.join("identity") } fn read_capped(path: &Path) -> Result, String> { let len = fs::metadata(path).map_err(|e| format!("{}: {e}", path.display()))?.len(); if len > MAX_STATE_FILE { return Err(format!("{}: larger than {MAX_STATE_FILE} bytes", path.display())); } fs::read(path).map_err(|e| format!("{}: {e}", path.display())) } fn write_new(path: &Path, data: &[u8]) -> Result<(), String> { let mut f = fs::File::options().write(true).create_new(true).open(path).map_err(|e| format!("{}: {e}", path.display()))?; f.write_all(data).and_then(|()| f.sync_all()).map_err(|e| format!("{}: {e}", path.display())) } /// 16 upper-case hex characters, as the crate's own clients use. pub fn new_unique_id(rng: &mut dyn RandomSource) -> String { let mut b = [0u8; 8]; rng.fill(&mut b); crate::log::hex(&b).to_ascii_uppercase() } pub fn valid_unique_id(s: &str) -> bool { s.len() == 16 && s.bytes().all(|b| b.is_ascii_hexdigit()) } /// The probe's identity. pub struct Identity { pub unique_id: String, pub client: ClientIdentity, /// Generated by this run (else loaded). pub created: bool, } /// Loads the identity, or makes one on the first run. Never prints or logs the key. pub fn load_or_create(out: &Path, common_name: &str, rng: &mut dyn RandomSource) -> Result { let dir = identity_dir(out); fs::create_dir_all(&dir).map_err(|e| format!("{}: {e}", dir.display()))?; let (id_path, cert_path, key_path) = (dir.join(UNIQUE_ID_FILE), dir.join(CERT_FILE), dir.join(KEY_FILE)); if cert_path.exists() || key_path.exists() || id_path.exists() { let unique_id = String::from_utf8(read_capped(&id_path)?).map_err(|_| "uniqueid.txt is not text".to_owned())?; let unique_id = unique_id.trim().to_owned(); if !valid_unique_id(&unique_id) { return Err(format!("{}: not 16 hex characters", id_path.display())); } let client = ClientIdentity::from_der(&read_capped(&cert_path)?, &read_capped(&key_path)?) .map_err(|e| format!("stored identity refused: {e}"))?; return Ok(Identity { unique_id, client, created: false }); } let now = SystemTime::now().duration_since(UNIX_EPOCH).map_err(|_| "the clock is before 1970".to_owned())?; // A day of slack for a host whose clock is behind. let not_before = i64::try_from(now.as_secs()).unwrap_or(i64::MAX) - 86_400; let client = ClientIdentity::generate(rng, common_name, not_before).map_err(|e| format!("key generation: {e}"))?; let unique_id = new_unique_id(rng); write_new(&cert_path, client.cert_der())?; write_new(&key_path, client.key_pkcs8_der())?; write_new(&id_path, unique_id.as_bytes())?; Ok(Identity { unique_id, client, created: true }) } /// The pinned host certificate and the address it was paired at, if `probe pair` succeeded before. pub fn load_host_cert(out: &Path) -> Result, String> { let dir = identity_dir(out); let path = dir.join(HOST_CERT_FILE); if !path.exists() { return Ok(None); } let cert = ServerCert::from_der(&read_capped(&path)?).map_err(|e| format!("stored host certificate refused: {e}"))?; let addr = read_capped(&dir.join(HOST_ADDR_FILE)) .map(|b| String::from_utf8_lossy(&b).trim().to_owned()) .unwrap_or_default(); Ok(Some((cert, addr))) } /// Stores the host certificate after pairing (replacing an older one). pub fn save_host_cert(out: &Path, cert: &ServerCert, host: IpAddr) -> Result<(), String> { let dir = identity_dir(out); let (path, addr) = (dir.join(HOST_CERT_FILE), dir.join(HOST_ADDR_FILE)); for p in [&path, &addr] { if p.exists() { fs::remove_file(p).map_err(|e| format!("{}: {e}", p.display()))?; } } write_new(&path, cert.der())?; write_new(&addr, host.to_string().as_bytes()) } /// Forgets the host certificate (after `probe unpair`). pub fn forget_host_cert(out: &Path) -> Result<(), String> { let dir = identity_dir(out); for p in [dir.join(HOST_CERT_FILE), dir.join(HOST_ADDR_FILE)] { if p.exists() { fs::remove_file(&p).map_err(|e| format!("{}: {e}", p.display()))?; } } Ok(()) } #[cfg(test)] mod tests { use super::*; struct Counter(u8); impl RandomSource for Counter { fn fill(&mut self, dest: &mut [u8]) { for b in dest { self.0 = self.0.wrapping_add(0x3B); *b = self.0; } } } #[test] fn unique_ids_are_16_upper_hex() { let id = new_unique_id(&mut Counter(0)); assert!(valid_unique_id(&id), "{id}"); assert_eq!(id, id.to_ascii_uppercase()); assert!(!valid_unique_id("0123")); assert!(!valid_unique_id("0123456789ABCDEG")); } }