From 385e110739f371fd397ca1d3dd3ffda4803dcf54 Mon Sep 17 00:00:00 2001 From: noah Date: Tue, 22 Sep 2026 18:45:56 -0600 Subject: [PATCH] review wave 1: fix the critical restore false-success + security/correctness findings From the recursive multi-agent review (18 confirmed findings). This wave clears the critical, four highs, and several mediums/lows: - CRITICAL restore.rs: a Braiins SSH restore reported SUCCESS on a wrong password or unreachable miner. run_with_timeout now captures the exit code and drains stderr on its own thread (also fixing the medium stderr-pipe stall), and a new testable classify_braiins() treats an ssh auth/connection failure (stderr diagnostic, empty stdout, non-zero exit) as failure while still reading a dropped connection / timeout as the expected reboot. Unit-tested. - HIGH restore exclusivity: apply_restore_confirm now refuses when a scan/refresh/ action/flash or another restore is in flight, so this destructive action never overlaps or orphans a running restore handle. - HIGH secrets off the command line: Braiins SSH uses `sshpass -e` (env, not -p), and the access-probe curl passes credentials through a config on stdin (-K -) instead of `-u user:pass`; both were visible in the process list. New masked password field (wxTE_PASSWORD bridge) so the Credentials dialog no longer renders saved passwords in the clear. - MEDIUM correctness: per-board Chip-temp readings are now index-aligned with the boards (a missing middle board shows "-" instead of shifting later boards left). - MEDIUM: saved pool lists (which can hold a pool password) are chmod 0600. - LOW: access-probe curl timeout now reaps the child (no zombie). 95 tests (+classify_braiins) + clippy-clean + selftest green. Co-Authored-By: Claude Opus 4.8 Claude-Session: https://claude.ai/code/session_01Djv3oncM4LxTS5tb61Ako6 --- crates/alkane-gui/src/access_probe.rs | 36 ++++- crates/alkane-gui/src/model.rs | 7 +- crates/alkane-gui/src/pool_prefs.rs | 15 ++ crates/alkane-gui/src/restore.rs | 141 ++++++++++++++---- crates/alkane-gui/src/scan.rs | 31 ++-- crates/alkane-gui/src/ui.rs | 28 +++- .../cpp_src/widgets_bridge.cpp | 7 + .../wx-rs/wx-rs-0.2.0-patched/src/widgets.rs | 6 + 8 files changed, 223 insertions(+), 48 deletions(-) diff --git a/crates/alkane-gui/src/access_probe.rs b/crates/alkane-gui/src/access_probe.rs index 99ea98a2..f4986d1e 100644 --- a/crates/alkane-gui/src/access_probe.rs +++ b/crates/alkane-gui/src/access_probe.rs @@ -64,7 +64,6 @@ pub fn probe_access(ip: &str, make: &str, user: &str, pass: &str) -> Result Result Result Result { - use std::io::Read; +/// black-holed host). `stdin_data`, when set, is written to the child's stdin and +/// the pipe closed -- used to feed a curl config (with the credentials) instead +/// of putting them on the command line (round 18 #12). +fn wait_with_timeout( + mut cmd: Command, + timeout: Duration, + stdin_data: Option<&[u8]>, +) -> Result { + use std::io::{Read, Write}; cmd.stdout(std::process::Stdio::piped()).stderr(std::process::Stdio::piped()); + if stdin_data.is_some() { + cmd.stdin(std::process::Stdio::piped()); + } let mut child = cmd.spawn().map_err(|e| format!("spawn curl: {e}"))?; + if let Some(data) = stdin_data { + if let Some(mut si) = child.stdin.take() { + let _ = si.write_all(data); + } // dropping `si` closes the pipe so curl stops reading the config + } let start = std::time::Instant::now(); loop { match child.try_wait().map_err(|e| e.to_string())? { @@ -111,6 +127,7 @@ fn wait_with_timeout(mut cmd: Command, timeout: Duration) -> Result { if start.elapsed() >= timeout { let _ = child.kill(); + let _ = child.wait(); // reap so we never leave a zombie (round 18 #12) return Err("curl timed out".into()); } std::thread::sleep(Duration::from_millis(100)); @@ -119,6 +136,11 @@ fn wait_with_timeout(mut cmd: Command, timeout: Duration) -> Result String { + s.replace('\\', "\\\\").replace('"', "\\\"") +} + /// Passwords to try for a WhatsMiner access check: a user-set per-firmware /// override (round 12 #13) wins; otherwise the two factory defaults ("admin" for /// V1/V2, "super" for V3). All attempts are non-mutating, so trying both is safe. diff --git a/crates/alkane-gui/src/model.rs b/crates/alkane-gui/src/model.rs index 3bb96e61..c212c6da 100644 --- a/crates/alkane-gui/src/model.rs +++ b/crates/alkane-gui/src/model.rs @@ -1342,7 +1342,12 @@ impl Column { if r.board_temps.is_empty() { if r.chip_temp_c > 0.0 { format!("{:.0}", r.chip_temp_c) } else { String::new() } } else { - r.board_temps.iter().map(|&t| format!("{t:.0}")).collect::>().join(" / ") + // 0.0 == a board with no reading; show "-" so positions align. + r.board_temps + .iter() + .map(|&t| if t > 0.0 { format!("{t:.0}") } else { "-".to_string() }) + .collect::>() + .join(" / ") } } Column::FluidTemp => num(r.fluid_temp_c, 1, " C"), diff --git a/crates/alkane-gui/src/pool_prefs.rs b/crates/alkane-gui/src/pool_prefs.rs index 29c1550d..57c57b0b 100644 --- a/crates/alkane-gui/src/pool_prefs.rs +++ b/crates/alkane-gui/src/pool_prefs.rs @@ -83,9 +83,24 @@ pub fn save_all(field: PoolField, values: &[String]) -> std::io::Result { let _ = std::fs::create_dir_all(dir); } std::fs::write(&p, out.join("\n"))?; + // The password list can hold a pool password; keep every saved list owner-only + // (round 18 #12). + restrict_permissions(&p); Ok(out.len()) } +/// Best-effort tighten a config file to owner-only (0600) on Unix. A no-op +/// elsewhere; a failure is ignored (the file still exists, just not restricted). +fn restrict_permissions(path: &std::path::Path) { + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + let _ = std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600)); + } + #[cfg(not(unix))] + let _ = path; +} + /// Trim every value, then drop empties, values equal to a built-in preset, and /// later exact duplicates (first occurrence wins). Order is otherwise preserved. fn dedupe_saved(presets: &[&str], values: &[String]) -> Vec { diff --git a/crates/alkane-gui/src/restore.rs b/crates/alkane-gui/src/restore.rs index a30efa0d..298a71ce 100644 --- a/crates/alkane-gui/src/restore.rs +++ b/crates/alkane-gui/src/restore.rs @@ -172,28 +172,30 @@ fn restore_braiins(ip: &str, user: &str, pass: &str) -> (bool, String) { return (false, "Braiins restore needs an SSH password (set the SSH login)".into()); } let target = format!("{user}@{ip}"); - // uninstall.sh is on Braiins OS+'s PATH; run it non-interactively. + // sshpass reads the password from $SSHPASS (-e) rather than argv (-p), so it + // never shows up in the process list (round 18 #12). Host-key checking is + // deliberately disabled: these are LAN miners whose SSH host key changes on + // every reflash, so pinning it would break the very revert this performs. + // BatchMode stops any interactive prompt from hanging out the 60 s cap. let mut cmd = Command::new("sshpass"); - cmd.arg("-p").arg(pass).arg("ssh"); + cmd.env("SSHPASS", pass); + cmd.arg("-e").arg("ssh"); cmd.args([ "-o", "StrictHostKeyChecking=no", "-o", "UserKnownHostsFile=/dev/null", + "-o", "BatchMode=yes", "-o", "ConnectTimeout=8", &target, "uninstall.sh || /sbin/uninstall.sh", ]); match run_with_timeout(cmd, Duration::from_secs(60)) { - Ok(out) => { - let s = String::from_utf8_lossy(&out).to_lowercase(); - if s.contains("not found") || s.contains("no such") { - (false, "uninstall.sh not found on the miner".into()) - } else { - (true, "ran uninstall.sh (reverts to stock + reboots)".into()) - } - } + Ok(out) => classify_braiins( + &String::from_utf8_lossy(&out.stdout), + &String::from_utf8_lossy(&out.stderr), + out.code, + out.timed_out, + ), Err(e) => { - // A reboot mid-command commonly drops the SSH connection; treat a - // connection-closed error after the command as likely success. if e.contains("closed") || e.contains("reset") || e.contains("timed out") { (true, "SSH dropped (miner likely rebooting to stock)".into()) } else { @@ -203,6 +205,42 @@ fn restore_braiins(ip: &str, user: &str, pass: &str) -> (bool, String) { } } +/// Decide a Braiins `uninstall.sh` outcome from its captured output. The critical +/// rule (round 18 #12): an SSH auth/connection failure -- which writes its +/// diagnostic to stderr, leaves stdout empty, and exits non-zero -- must be +/// reported as a FAILURE, never a false success. A dropped connection or a +/// timeout after the command started is the expected signature of the reboot. +fn classify_braiins(stdout: &str, stderr: &str, code: Option, timed_out: bool) -> (bool, String) { + let err = stderr.to_lowercase(); + // ssh's own connection/auth failures (exit 255) never reach the remote command. + let conn_fail = [ + "permission denied", + "connection refused", + "could not resolve", + "no route to host", + "connection timed out", + "operation timed out", + "host key verification failed", + "before authentication", + ] + .iter() + .any(|m| err.contains(m)); + if conn_fail { + let why = stderr.lines().map(str::trim).rfind(|l| !l.is_empty()); + return (false, format!("SSH failed: {}", why.unwrap_or("connection/auth error"))); + } + let out = stdout.to_lowercase(); + if out.contains("not found") || out.contains("no such") || err.contains("not found") { + return (false, "uninstall.sh not found on the miner".into()); + } + match code { + Some(0) => (true, "ran uninstall.sh (reverts to stock + reboots)".into()), + None => (true, "SSH dropped (miner likely rebooting to stock)".into()), + _ if timed_out => (true, "SSH timed out (miner likely rebooting to stock)".into()), + Some(c) => (false, format!("uninstall.sh exited {c}: {}", stderr.trim())), + } +} + /// One luxminer :4028 request/response (line-framed, socket closes after reply). fn lux_rpc(ip: &str, payload: &str) -> Result { let addr: SocketAddr = format!("{ip}:4028").parse().map_err(|e| format!("bad addr: {e}"))?; @@ -228,50 +266,101 @@ fn lux_rpc(ip: &str, payload: &str) -> Result { Ok(String::from_utf8_lossy(&buf).trim_matches('\u{0}').to_string()) } -/// curl with a wall-clock cap (small responses; no pipe-drain thread needed). +/// The captured result of a timed subprocess run. +struct CmdOutput { + /// The process exit code, or `None` if it was killed / dropped / timed out. + code: Option, + stdout: Vec, + stderr: Vec, + timed_out: bool, +} + +/// curl with a wall-clock cap. Errors only when the run produced no output and +/// timed out (a black-holed host); otherwise returns stdout even on a non-zero +/// exit (curl prints useful bodies/status on failures). fn curl(args: &[&str]) -> Result { let mut cmd = Command::new("curl"); cmd.args(args); - run_with_timeout(cmd, Duration::from_secs(15)).map(|o| String::from_utf8_lossy(&o).into_owned()) + let out = run_with_timeout(cmd, Duration::from_secs(15))?; + if out.timed_out && out.stdout.is_empty() { + return Err("timed out".into()); + } + Ok(String::from_utf8_lossy(&out.stdout).into_owned()) } -/// Run a command, capture stdout, with a hard wall-clock timeout. -fn run_with_timeout(mut cmd: Command, timeout: Duration) -> Result, String> { +/// Run a command with a hard wall-clock timeout, capturing stdout, stderr, and +/// the exit code. Both pipes are drained on their own threads so a child that +/// writes a lot to stderr can never deadlock against a full pipe (round 18 #12). +fn run_with_timeout(mut cmd: Command, timeout: Duration) -> Result { cmd.stdout(std::process::Stdio::piped()); cmd.stderr(std::process::Stdio::piped()); let mut child = cmd.spawn().map_err(|e| format!("spawn: {e}"))?; let mut stdout = child.stdout.take().ok_or("no stdout")?; - let reader = std::thread::spawn(move || { + let mut stderr = child.stderr.take().ok_or("no stderr")?; + let out_reader = std::thread::spawn(move || { let mut b = Vec::new(); let _ = stdout.read_to_end(&mut b); b }); + let err_reader = std::thread::spawn(move || { + let mut b = Vec::new(); + let _ = stderr.read_to_end(&mut b); + b + }); let start = std::time::Instant::now(); let mut timed_out = false; - loop { + let status = loop { match child.try_wait().map_err(|e| e.to_string())? { - Some(_) => break, + Some(s) => break Some(s), None => { if start.elapsed() >= timeout { let _ = child.kill(); + let _ = child.wait(); // reap so we never leave a zombie timed_out = true; - break; + break None; } std::thread::sleep(Duration::from_millis(50)); } } - } - let out = reader.join().unwrap_or_default(); - if timed_out && out.is_empty() { - return Err("timed out".into()); - } - Ok(out) + }; + Ok(CmdOutput { + code: status.and_then(|s| s.code()), + stdout: out_reader.join().unwrap_or_default(), + stderr: err_reader.join().unwrap_or_default(), + timed_out, + }) } #[cfg(test)] mod tests { use super::*; + #[test] + fn braiins_auth_or_connection_failure_is_not_a_false_success() { + // The critical regression guard (round 18 #12): a wrong password or an + // unreachable miner writes to stderr, leaves stdout empty, and exits + // non-zero -- it must report failure, never "restored". + let (ok, msg) = classify_braiins("", "Permission denied, please try again.", Some(255), false); + assert!(!ok, "wrong password must not report success"); + assert!(msg.to_lowercase().contains("ssh failed"), "{msg}"); + + let (ok, _) = classify_braiins("", "ssh: connect to host 10.0.0.9 port 22: Connection refused", Some(255), false); + assert!(!ok, "unreachable miner must not report success"); + + let (ok, _) = classify_braiins("", "ssh: Could not resolve hostname miner: Name or service not known", Some(255), false); + assert!(!ok, "unresolvable host must not report success"); + + // Genuine outcomes. + let (ok, _) = classify_braiins("uninstalling...\n", "", Some(0), false); + assert!(ok, "clean exit 0 is success"); + let (ok, _) = classify_braiins("", "Connection to 10.0.0.5 closed by remote host.", None, false); + assert!(ok, "connection dropped mid-command (reboot) is success"); + let (ok, _) = classify_braiins("", "", None, true); + assert!(ok, "timeout after the command started (reboot) is success"); + let (ok, _) = classify_braiins("bash: uninstall.sh: command not found\n", "", Some(127), false); + assert!(!ok, "missing uninstall.sh is a failure"); + } + #[test] fn firmware_selects_the_right_flow() { // The dispatcher only recognises the three revertible aftermarket diff --git a/crates/alkane-gui/src/scan.rs b/crates/alkane-gui/src/scan.rs index ce76c44c..fbfac76f 100644 --- a/crates/alkane-gui/src/scan.rs +++ b/crates/alkane-gui/src/scan.rs @@ -644,17 +644,26 @@ async fn to_row(miner: &dyn Miner) -> MinerRow { // alarmingly high and didn't match the temperature the miner itself reports; // the board temperature (~60-79C) is the figure the miner's own UI shows // (round 12 #3). Falls back to the chip temp when no board temp is reported. - let board_temps: Vec = data - .hashboards - .iter() - .filter_map(|b| { - b.board_temperature - .as_ref() - .or(b.outlet_chip_temperature.as_ref()) - .map(|t| t.as_celsius()) - }) - .filter(|&t| t > 0.0) - .collect(); + // Index-aligned with the hashboards (index i == board i): a board with no + // reading is 0.0, NOT dropped, so a missing middle board can't shift the + // others left in the "77 / - / 74" Chip-temp cell (round 18 #12). Collapsed + // to empty when NO board reports a temperature, so the cell falls back to the + // fleet average instead of showing "- / - / -". + let board_temps: Vec = { + let v: Vec = data + .hashboards + .iter() + .map(|b| { + b.board_temperature + .as_ref() + .or(b.outlet_chip_temperature.as_ref()) + .map(|t| t.as_celsius()) + .filter(|&t| t > 0.0) + .unwrap_or(0.0) + }) + .collect(); + if v.iter().all(|&t| t <= 0.0) { Vec::new() } else { v } + }; // Per-board hashrate (TH/s), index-aligned with the hashboards, for the // per-board Health tooltip (round 17 R2). Unlike board_temps this is NOT // filtered/compacted -- index i must stay board i so the tooltip numbering diff --git a/crates/alkane-gui/src/ui.rs b/crates/alkane-gui/src/ui.rs index 22a467a5..dc4b4938 100644 --- a/crates/alkane-gui/src/ui.rs +++ b/crates/alkane-gui/src/ui.rs @@ -291,7 +291,13 @@ fn encode_board_temps_cell(pal: &Palette, temps: &[f64], avg: f64) -> String { if i > 0 { segs.push((None, " / ".to_string())); } - segs.push((Some(temp_color(pal, t)), format!("{t:.0}"))); + // A 0.0 slot means "this board reported no temperature"; show a dash in its + // position so the remaining boards stay aligned (round 18 #12). + if t > 0.0 { + segs.push((Some(temp_color(pal, t)), format!("{t:.0}"))); + } else { + segs.push((None, "-".to_string())); + } } encode_segments(&segs) } @@ -2005,6 +2011,21 @@ impl App { /// keyword). Resolves the per-firmware credentials (VNish password from the /// round 12 #13 defaults; Braiins SSH login from the saved SSH creds). fn apply_restore_confirm(&mut self) { + // Restore-to-stock is destructive and needs exclusive access to the miners; + // refuse if any scan / refresh / action / flash or another restore is + // already in flight, so two operations never hit the same unit and a + // running restore handle is never orphaned by being overwritten (round 18 #12). + if self.flashing + || self.scanning + || self.action.is_some() + || self.refresh.is_some() + || self.restore.is_some() + { + wx_rs::set_status_text("busy (scan/action/restore in progress) -- try again once it finishes"); + self.pending_restore.clear(); + self.restore_dialog.close(0); + return; + } let targets = std::mem::take(&mut self.pending_restore); if targets.is_empty() { self.restore_dialog.close(0); @@ -2633,7 +2654,8 @@ impl App { user_input.set_min_size(150, -1); user_input.set_value(&saved_user); grow.add(user_input, 0, sf::ALIGN_CENTRE_VERTICAL | sf::BORDER_LEFT | sf::BORDER_RIGHT, 6); - let pass_input = Widget::text_ctrl(dlg, false); + // Masked so a saved password is never rendered in the clear (round 18 #12). + let pass_input = Widget::password_ctrl(dlg); pass_input.set_min_size(150, -1); grow.add(pass_input, 1, sf::ALIGN_CENTRE_VERTICAL | sf::BORDER_LEFT | sf::BORDER_RIGHT, 6); root.add_sizer(grow, 0, sf::EXPAND | sf::BORDER_LEFT | sf::BORDER_RIGHT | sf::BORDER_TOP, 6); @@ -2667,7 +2689,7 @@ impl App { user_ctrl.set_min_size(150, -1); user_ctrl.set_value(&user); row.add(user_ctrl, 0, sf::ALIGN_CENTRE_VERTICAL | sf::BORDER_LEFT | sf::BORDER_RIGHT, 6); - let pass_ctrl = Widget::text_ctrl(dlg, false); + let pass_ctrl = Widget::password_ctrl(dlg); // masked (round 18 #12) pass_ctrl.set_min_size(150, -1); pass_ctrl.set_value(&pass); row.add(pass_ctrl, 1, sf::ALIGN_CENTRE_VERTICAL | sf::BORDER_LEFT | sf::BORDER_RIGHT, 6); diff --git a/thirdparty/wx-rs/wx-rs-0.2.0-patched/cpp_src/widgets_bridge.cpp b/thirdparty/wx-rs/wx-rs-0.2.0-patched/cpp_src/widgets_bridge.cpp index 49c8f149..1a10688d 100644 --- a/thirdparty/wx-rs/wx-rs-0.2.0-patched/cpp_src/widgets_bridge.cpp +++ b/thirdparty/wx-rs/wx-rs-0.2.0-patched/cpp_src/widgets_bridge.cpp @@ -776,6 +776,13 @@ void* wxbr_text_ctrl(void* parent, int multiline) { wxDefaultPosition, wxSize(-1, -1), style); } +// A single-line text control that masks its content (wxTE_PASSWORD), for secret +// entry so a saved password is never rendered in the clear (round 18 #12). +void* wxbr_text_ctrl_password(void* parent) { + return (void*)new wxTextCtrl((wxWindow*)parent, wxID_ANY, wxT(""), + wxDefaultPosition, wxSize(-1, -1), wxTE_PASSWORD); +} + int wxbr_text_ctrl_get(void* win, char* buf, int cap) { wxTextCtrl* t = (wxTextCtrl*)win; wxString v = t->GetValue(); diff --git a/thirdparty/wx-rs/wx-rs-0.2.0-patched/src/widgets.rs b/thirdparty/wx-rs/wx-rs-0.2.0-patched/src/widgets.rs index 7c55fda6..f7d64d58 100644 --- a/thirdparty/wx-rs/wx-rs-0.2.0-patched/src/widgets.rs +++ b/thirdparty/wx-rs/wx-rs-0.2.0-patched/src/widgets.rs @@ -36,6 +36,7 @@ mod notsafe { pub fn wxbr_button(parent: *mut c_void, label: *const c_char, id: c_int) -> *mut c_void; pub fn wxbr_bind_click(win: *mut c_void, id: c_int); pub fn wxbr_text_ctrl(parent: *mut c_void, multiline: c_int) -> *mut c_void; + pub fn wxbr_text_ctrl_password(parent: *mut c_void) -> *mut c_void; pub fn wxbr_text_ctrl_get(win: *mut c_void, buf: *mut c_char, cap: c_int) -> c_int; pub fn wxbr_text_ctrl_set(win: *mut c_void, value: *const c_char); pub fn wxbr_text_ctrl_write(win: *mut c_void, value: *const c_char); @@ -438,6 +439,11 @@ impl Widget { Widget(unsafe { notsafe::wxbr_text_ctrl(parent.0, multiline as c_int) }) } + /// A single-line text control that masks its content (for password entry). + pub fn password_ctrl(parent: Widget) -> Widget { + Widget(unsafe { notsafe::wxbr_text_ctrl_password(parent.0) }) + } + pub fn get_value(&self) -> String { let mut buf = vec![0i8; 65536]; let n = unsafe { notsafe::wxbr_text_ctrl_get(self.0, buf.as_mut_ptr(), buf.len() as c_int) };