From 26fd0a8b03bc300598862133df757a75c905efc3 Mon Sep 17 00:00:00 2001 From: SteamSmith <341182916+SteamSmith@users.noreply.github.com> Date: Thu, 5 Nov 2026 00:10:05 -0500 Subject: [PATCH] fix(control): random owner-only token file, constant-time compare, close on failed auth The desktop control server had its own token code (hashed RandomState, default-permission file in the shared temp dir, plain ==, unlimited guesses on one connection). It now uses the automation crate's server_token and token_matches, which the CLI already used. Co-Authored-By: Claude Sonnet 5.5 --- Cargo.lock | 1 + apps/materialcraft/Cargo.toml | 1 + apps/materialcraft/src/control_server.rs | 52 ++++++++++--------- apps/materialcraft/src/control_server.test.rs | 16 ++++++ crates/automation/src/security.rs | 19 ++++++- 5 files changed, 63 insertions(+), 26 deletions(-) create mode 100644 apps/materialcraft/src/control_server.test.rs diff --git a/Cargo.lock b/Cargo.lock index 9e520a8c..c19655d7 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2313,6 +2313,7 @@ dependencies = [ "egui", "image", "log", + "materialcraft-automation", "materialcraft-engine", "materialcraft-ui-egui", "serde_json", diff --git a/apps/materialcraft/Cargo.toml b/apps/materialcraft/Cargo.toml index 64a1ca49..7b5a2caa 100644 --- a/apps/materialcraft/Cargo.toml +++ b/apps/materialcraft/Cargo.toml @@ -12,6 +12,7 @@ workspace = true [dependencies] materialcraft-engine = { workspace = true } +materialcraft-automation = { workspace = true } materialcraft-ui-egui = { workspace = true } eframe = { workspace = true, features = ["default_fonts", "wgpu", "accesskit", "wayland", "x11", "persistence"] } egui = { workspace = true } diff --git a/apps/materialcraft/src/control_server.rs b/apps/materialcraft/src/control_server.rs index a094e2dc..95484964 100644 --- a/apps/materialcraft/src/control_server.rs +++ b/apps/materialcraft/src/control_server.rs @@ -14,27 +14,31 @@ use serde_json::{Value, json}; /// Requests larger than this are rejected (screenshots go the other way). const MAX_REQUEST: u64 = 8 << 20; -fn token(port: u16) -> String { - if let Ok(t) = std::env::var("MATERIALCRAFT_CONTROL_TOKEN") - && t.len() >= 16 - { - return t; +#[cfg(test)] +#[path = "control_server.test.rs"] +mod tests; + +/// The token comes from the OS random generator and is written owner-only (shared with the CLI's +/// `serve`). Without a token the server does not start. +fn token(port: u16) -> Option { + match materialcraft_automation::security::server_token(port) { + Ok((token, path)) => { + if let Some(path) = path { + eprintln!("materialcraft: control token written to {}", path.display()); + } + Some(token) + } + Err(e) => { + eprintln!("materialcraft: control server not started: {e}"); + None + } } - use std::hash::{BuildHasher, Hasher}; - let mut out = String::new(); - for i in 0..4u64 { - let mut h = std::collections::hash_map::RandomState::new().build_hasher(); - h.write_u64(i ^ u64::from(std::process::id())); - h.write_u128(std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_nanos()).unwrap_or(0)); - out.push_str(&format!("{:016x}", h.finish())); - } - let path = std::env::temp_dir().join(format!("materialcraft-control-{port}.token")); - if let Err(e) = std::fs::write(&path, &out) { - eprintln!("materialcraft: could not write the control token to {}: {e}", path.display()); - } else { - eprintln!("materialcraft: control token written to {}", path.display()); - } - out +} + +/// Whether a first request authenticates: an `auth` call carrying exactly the server's token, +/// compared without an early exit. +fn auth_ok(token: &str, method: &str, params: &Value) -> bool { + method == "auth" && params.get("token").and_then(Value::as_str).is_some_and(|t| materialcraft_automation::security::token_matches(token, t)) } pub fn start(port: u16, ctx: egui::Context) -> Receiver { @@ -46,7 +50,7 @@ pub fn start(port: u16, ctx: egui::Context) -> Receiver { return rx; } }; - let token = token(port); + let Some(token) = token(port) else { return rx }; eprintln!("materialcraft: control server listening on 127.0.0.1:{port}"); std::thread::spawn(move || { for stream in listener.incoming().flatten() { @@ -90,7 +94,7 @@ fn serve(stream: TcpStream, token: &str, tx: Sender, ctx: egui:: let method = msg.get("method").and_then(Value::as_str).unwrap_or("").to_string(); let params = msg.get("params").cloned().unwrap_or(json!({})); let mut reply = if !authed { - let ok = method == "auth" && params.get("token").and_then(Value::as_str) == Some(token); + let ok = auth_ok(token, &method, ¶ms); authed = ok; if ok { json!({"ok": true}) } else { json!({"ok": false, "error": "authenticate first: {\"method\":\"auth\",\"params\":{\"token\":…}}"}) } } else { @@ -104,10 +108,8 @@ fn serve(stream: TcpStream, token: &str, tx: Sender, ctx: egui:: if let Some(o) = reply.as_object_mut() { o.insert("id".into(), id); } + // A failed authentication closes the connection, so guesses cost a reconnect each. if writeln!(out, "{reply}").is_err() || out.flush().is_err() || !authed { - if !authed { - continue; - } break; } } diff --git a/apps/materialcraft/src/control_server.test.rs b/apps/materialcraft/src/control_server.test.rs new file mode 100644 index 00000000..50b02a30 --- /dev/null +++ b/apps/materialcraft/src/control_server.test.rs @@ -0,0 +1,16 @@ +#[cfg(test)] +mod auth_tests { + use crate::control_server::auth_ok; + use serde_json::json; + + #[test] + fn only_the_exact_token_on_an_auth_request_passes() { + let token = "0123456789abcdef0123456789abcdef"; + assert!(auth_ok(token, "auth", &json!({"token": token}))); + assert!(!auth_ok(token, "auth", &json!({"token": "0123456789abcdef0123456789abcdee"}))); + assert!(!auth_ok(token, "auth", &json!({"token": "short"}))); + assert!(!auth_ok(token, "auth", &json!({}))); + assert!(!auth_ok(token, "auth", &json!({"token": 5}))); + assert!(!auth_ok(token, "command.run", &json!({"token": token}))); + } +} diff --git a/crates/automation/src/security.rs b/crates/automation/src/security.rs index 165fda18..673fc4b5 100644 --- a/crates/automation/src/security.rs +++ b/crates/automation/src/security.rs @@ -63,7 +63,9 @@ pub fn server_token(port: u16) -> Result<(String, Option), AutomationEr let token = generate_token()?; let path = token_file(port); let mut o = std::fs::OpenOptions::new(); - o.write(true).create(true).truncate(true); + // Remove what is there first (a symlink is removed, not followed), then create exclusively. + let _ = std::fs::remove_file(&path); + o.write(true).create_new(true); #[cfg(unix)] std::os::unix::fs::OpenOptionsExt::mode(&mut o, 0o600); let res = o.open(&path).and_then(|mut f| std::io::Write::write_all(&mut f, token.as_bytes())); @@ -149,6 +151,21 @@ mod tests { assert!(client_token(1, Some(format!(" {a}\n"))).is_ok()); } + /// A stale (or planted) file at the token path is replaced, never written through. + #[test] + fn the_token_file_replaces_a_stale_file() { + if std::env::var(TOKEN_ENV).is_ok() { + return; + } + let port = 59_871; + let path = token_file(port); + std::fs::write(&path, "stale contents").unwrap(); + let (token, written) = server_token(port).unwrap(); + assert_eq!(written.as_deref(), Some(path.as_path())); + assert_eq!(std::fs::read_to_string(&path).unwrap(), token); + let _ = std::fs::remove_file(&path); + } + #[test] fn oversized_lines_are_skipped() { let input = format!("{}\n{{\"ok\":1}}\n", "x".repeat(MAX_REQUEST_BYTES + 10));