07ccff4241
tools/gs-probe (own workspace, never published): `probe serverinfo | pair | apps | launch <app-id> | quit | unpair` against one host address, driving DomiStream's pairing, HTTP, RTSP, ENet, control, video and audio state machines over real sockets. Structured JSONL log per run (requests, answers, timings, the U each record bears on, parser errors with their bytes), secrets redacted (rikey, pairing values; PIN never logged; registered key hex scrubbed from every line). Test-only client key and cert in --out. Video: frames, decode-ready frames, FEC recoveries, losses, elementary-stream dump, live U14 parity check; audio: packets, losses, decrypting vs plain receivers (U17), packet dump and offline U16 solver (`solve-audio-fec`). START_A/START_B/PERIODIC_PING/IDR bodies come from the command line (U10). docs/LIVE-INTEROP.md: the sitting's run book (preparation, sequence S0-S5 with the U each step settles, variants, log reading, where each fact lands in PROTOCOL.md and the code, stop-and-report rule, clean-up, Mark's timeline). Built and unit-tested only (41 tests, clippy -D warnings, fmt); never run against a host.
148 lines
5.6 KiB
Rust
148 lines
5.6 KiB
Rust
//! 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<Vec<u8>, 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<Identity, String> {
|
|
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<Option<(ServerCert, String)>, 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"));
|
|
}
|
|
}
|