From 3ba32113715a5ad9685e2354e8ad923cce8a9f7f Mon Sep 17 00:00:00 2001 From: noah Date: Sun, 20 Sep 2026 09:29:43 -0600 Subject: [PATCH] GUI round 12 (#8b, part 1): correct WhatsMiner lock/access with the :4028 token API WhatsMiners were shown "locked/unauthenticated" even with their default login. Two causes, both fixed: - The access probe hit an Antminer-only endpoint (/cgi-bin/get_miner_conf.cgi via curl --digest) for EVERY make; WhatsMiners answer 307 there, so the check was always indeterminate. Added a real WhatsMiner check over its :4028 token API: get_token (unauthenticated) -> derive the AES key from the password (md5crypt + SHA256, the same scheme the vendored asic-rs whatsminer backend uses) -> send a NON-mutating encrypted `summary`. An encrypted reply means the password was accepted (unlocked); a plaintext "enc json load err" means rejected (locked). probe_access now branches on the miner brand. Candidate passwords: a per-firmware override (round 12 #13) if set, else the factory defaults admin (V1/V2) and super (V3); all attempts are non-mutating so trying both is safe. - The scan-time lock guess (!caps.any_control()) falsely marked older WhatsMiners locked because they route to the asic-rs V1 backend, which declares no control commands even though the miner is controllable via the token API. WhatsMiner lock state is now left unknown at scan time and decided by the real probe. Live-verified on the fleet: older 20220422.18.REL units (10.8.1.176, 10.7.1.196) and newer M30S+ (10.8.1.45) all report UNLOCKED with the default admin login; the Antminer digest path is unchanged (Z15 -> 200 with root/root -> unlocked). Added a headless `ALKANE_ACCESS_PROBE=" "` diagnostic and a deterministic AES unit test. Self-test passes. Note: this is the access/lock half of #8b. Implementing the full reverse- engineered WhatsMiner command set (control + monitoring over the token API) is tracked separately. Co-Authored-By: Claude Opus 4.8 Claude-Session: https://claude.ai/code/session_01Y8h447BPyJR4fioYZvQ9bh --- Cargo.lock | 6 + crates/alkane-gui/Cargo.toml | 8 ++ crates/alkane-gui/src/access_probe.rs | 154 +++++++++++++++++++++++++- crates/alkane-gui/src/main.rs | 18 +++ crates/alkane-gui/src/scan.rs | 18 ++- crates/alkane-gui/src/ui.rs | 5 +- 6 files changed, 197 insertions(+), 12 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index d338249a..6a2ca8e1 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -76,13 +76,19 @@ dependencies = [ name = "alkane-gui" version = "0.1.0" dependencies = [ + "aes", "alkane-core", "alkane-discovery", "asic-rs", + "base64 0.21.7", + "ecb", "futures-util", + "hex", + "md5crypt", "measurements", "serde", "serde_json", + "sha2", "tokio", "wx-rs", ] diff --git a/crates/alkane-gui/Cargo.toml b/crates/alkane-gui/Cargo.toml index 3f0b86f6..1c812212 100644 --- a/crates/alkane-gui/Cargo.toml +++ b/crates/alkane-gui/Cargo.toml @@ -19,3 +19,11 @@ tokio = { version = "1", features = ["rt"] } futures-util = "0.3" serde = { version = "1", features = ["derive"] } serde_json = "1" +# WhatsMiner :4028 token-auth access check (round 12 #8b) -- same crates the +# vendored asic-rs whatsminer backend uses, so no new versions enter the lock. +md5crypt = "1" +sha2 = "0.10" +aes = "0.8" +ecb = "0.1" +base64 = "0.21" +hex = "0.4" diff --git a/crates/alkane-gui/src/access_probe.rs b/crates/alkane-gui/src/access_probe.rs index 9001069b..31dd3ecf 100644 --- a/crates/alkane-gui/src/access_probe.rs +++ b/crates/alkane-gui/src/access_probe.rs @@ -14,10 +14,29 @@ //! rather than add an HTTP+digest crate, so the offline/vendored build is //! unaffected. `Some(true)` = locked, `Some(false)` = unlocked, `None` = //! indeterminate (unreachable, or an endpoint/vendor this probe doesn't cover). +//! +//! WhatsMiner has no such digest-gated web endpoint (it returns a 307 redirect +//! for the Antminer paths, so the curl probe always read "indeterminate" and the +//! table fell back to a capability guess that marked older units "locked" even +//! with the default login -- round 12 #8b). Instead we run the WhatsMiner +//! :4028 token handshake: `get_token` (unauthenticated) yields a salt, we derive +//! the AES key from the password, and send a NON-mutating encrypted `summary`. +//! An encrypted reply means the key (hence password) was accepted -> unlocked; +//! a plaintext `enc json load err` means it was rejected -> locked. +use std::io::{Read, Write}; +use std::net::{SocketAddr, TcpStream}; use std::process::Command; use std::time::Duration; +use aes::Aes256; +use aes::cipher::{BlockEncryptMut, KeyInit, block_padding::ZeroPadding}; +use base64::Engine; +use base64::engine::general_purpose::STANDARD as BASE64; +use sha2::{Digest, Sha256}; + +type Aes256EcbEnc = ecb::Encryptor; + /// Classify a miner's access state from an HTTP status code string (curl's /// `%{http_code}` output). Conservative: anything other than a clear /// authenticated/unauthorized answer is `None`. @@ -35,12 +54,16 @@ fn endpoint(_firmware: &str) -> &'static str { "/cgi-bin/get_miner_conf.cgi" } -/// Probe one miner's access state over its web API with the given credentials. -/// Returns `Ok(Some(true/false))` on a decisive lock/unlock answer, `Ok(None)` -/// if reachable-but-indeterminate or a vendor this probe doesn't cover, or -/// `Err` only on a failure to run curl at all. -pub fn probe_access(ip: &str, firmware: &str, user: &str, pass: &str) -> Result, String> { - let url = format!("http://{ip}{}", endpoint(firmware)); +/// Probe one miner's access state. `make` is the miner brand ("Whatsminer" / +/// "Antminer"): WhatsMiner uses the :4028 token handshake, everything else the +/// digest-auth web probe. Returns `Ok(Some(true/false))` on a decisive +/// lock/unlock answer, `Ok(None)` if indeterminate, `Err` only on a probe that +/// could not run at all. +pub fn probe_access(ip: &str, make: &str, user: &str, pass: &str) -> Result, String> { + if make.eq_ignore_ascii_case("whatsminer") { + return Ok(probe_whatsminer_access(ip, &whatsminer_password_candidates())); + } + let url = format!("http://{ip}{}", endpoint(make)); let userpass = format!("{user}:{pass}"); let mut cmd = Command::new("curl"); cmd.args([ @@ -96,6 +119,114 @@ fn wait_with_timeout(mut cmd: Command, timeout: Duration) -> Result Vec { + if let Some((_, pass)) = crate::credentials::load_firmware_credentials().get("WhatsMiner Stock") { + if !pass.is_empty() { + return vec![pass.clone()]; + } + } + vec!["admin".to_string(), "super".to_string()] +} + +/// One WhatsMiner :4028 request/response (the miner closes the socket after it +/// replies). Returns the NUL-trimmed body. +fn wm_rpc(ip: &str, payload: &str, timeout: Duration) -> Result { + let addr: SocketAddr = format!("{ip}:4028") + .parse() + .map_err(|e| format!("bad address {ip}: {e}"))?; + let mut stream = TcpStream::connect_timeout(&addr, timeout).map_err(|e| e.to_string())?; + stream.set_read_timeout(Some(timeout)).ok(); + stream.set_write_timeout(Some(timeout)).ok(); + stream.write_all(payload.as_bytes()).map_err(|e| e.to_string())?; + let mut buf = Vec::new(); + let mut chunk = [0u8; 4096]; + loop { + match stream.read(&mut chunk) { + Ok(0) => break, + Ok(n) => { + buf.extend_from_slice(&chunk[..n]); + if buf.len() > 1 << 20 { + break; // cap a runaway response + } + } + Err(_) => break, + } + } + Ok(String::from_utf8_lossy(&buf).trim_matches('\u{0}').to_string()) +} + +/// AES-256-ECB encrypt `data` under SHA256(pwd_md5), base64-encoded -- the exact +/// scheme the WhatsMiner btminer API expects (mirrors the vendored asic-rs +/// whatsminer v2 backend). +fn wm_aes_ecb_enc(pwd_md5: &str, data: &str) -> Option { + let key = Sha256::digest(pwd_md5.as_bytes()); // 32 bytes + let mut buffer = data.as_bytes().to_vec(); + while !buffer.len().is_multiple_of(16) { + buffer.push(0); + } + let ct = Aes256EcbEnc::new_from_slice(&key) + .ok()? + .encrypt_padded_mut::(&mut buffer, data.len()) + .ok()?; + Some(BASE64.encode(ct)) +} + +/// Check a WhatsMiner's access via the :4028 token handshake, trying each +/// candidate password. Returns `Some(false)` (unlocked) on the first password +/// the miner accepts, `Some(true)` (locked) if all are rejected, `None` if the +/// miner is unreachable or speaks an unexpected dialect. Non-mutating: only +/// `get_token` and a read-only `summary` are ever sent. +fn probe_whatsminer_access(ip: &str, passwords: &[String]) -> Option { + let timeout = Duration::from_secs(6); + let mut reachable = false; + for pass in passwords { + // 1. get_token (no auth) -> salt / newsalt / time. + let tok_resp = match wm_rpc(ip, "{\"command\":\"get_token\"}", timeout) { + Ok(s) => s, + Err(_) => return None, + }; + let v: serde_json::Value = match serde_json::from_str(&tok_resp) { + Ok(v) => v, + Err(_) => return None, + }; + let Some(msg) = v.get("Msg") else { return None }; + let (Some(salt), Some(newsalt), Some(time)) = ( + msg.get("salt").and_then(|s| s.as_str()), + msg.get("newsalt").and_then(|s| s.as_str()), + msg.get("time").and_then(|s| s.as_str()), + ) else { + return None; + }; + reachable = true; + // 2. Derive the md5crypt password hash + write-token from the password. + let crypted = md5crypt::md5crypt(pass.as_bytes(), salt.as_bytes()); + let full = String::from_utf8_lossy(&crypted); + let Some(pwd_md5) = full.split('$').nth(3) else { continue }; + let sign_crypted = md5crypt::md5crypt(format!("{pwd_md5}{time}").as_bytes(), newsalt.as_bytes()); + let sign_full = String::from_utf8_lossy(&sign_crypted); + let host_sign = sign_full.split('$').nth(3).unwrap_or(""); + // 3. Send an encrypted, read-only `summary`. If the AES key (from the + // password) is right the miner replies encrypted; if wrong it returns + // a plaintext "enc json load err". + let cmd = format!("{{\"command\":\"summary\",\"token\":\"{host_sign}\"}}"); + let Some(enc) = wm_aes_ecb_enc(pwd_md5, &cmd) else { continue }; + let payload = format!("{{\"enc\":1,\"data\":\"{enc}\"}}"); + let resp = match wm_rpc(ip, &payload, timeout) { + Ok(s) => s, + Err(_) => return None, + }; + if resp.contains("\"enc\"") { + return Some(false); // accepted -> unlocked/writable + } + // rejected -> try the next candidate password + } + // Reached the miner and every candidate password was rejected -> locked. + if reachable { Some(true) } else { None } +} + #[cfg(test)] mod tests { use super::*; @@ -112,4 +243,15 @@ mod tests { assert_eq!(classify_http_code(" 200 "), Some(false), "whitespace tolerated"); assert_eq!(classify_http_code(""), None); } + + #[test] + fn whatsminer_aes_ecb_matches_reference() { + // Deterministic vector from the verified btminer scheme: AES-256-ECB over + // SHA256(pwd_md5), zero-padded, base64. Guards the WhatsMiner access + // handshake crypto (round 12 #8b) without needing a live miner. + assert_eq!( + wm_aes_ecb_enc("abc123def456", "{\"command\":\"summary\"}").as_deref(), + Some("jn5Wru/5hhMtU1IgamxLoUd/YTxaLTxEeiCQxu5pO+Q=") + ); + } } diff --git a/crates/alkane-gui/src/main.rs b/crates/alkane-gui/src/main.rs index e0ecef69..e1557b4c 100644 --- a/crates/alkane-gui/src/main.rs +++ b/crates/alkane-gui/src/main.rs @@ -21,6 +21,24 @@ fn main() { std::process::exit(run_selftest()); } + // Headless access-probe check: `ALKANE_ACCESS_PROBE=" "` prints the + // lock state the real access probe computes (no GUI, no wx), so the WhatsMiner + // :4028 token check and the Antminer digest check can be verified directly. + if let Some(spec) = std::env::var_os("ALKANE_ACCESS_PROBE") { + let spec = spec.to_string_lossy(); + let mut it = spec.split_whitespace(); + let ip = it.next().unwrap_or(""); + let make = it.next().unwrap_or(""); + let (user, pass) = credentials::load_credentials().unwrap_or_default(); + match access_probe::probe_access(ip, make, &user, &pass) { + Ok(Some(true)) => println!("ACCESS {ip} {make}: LOCKED"), + Ok(Some(false)) => println!("ACCESS {ip} {make}: UNLOCKED"), + Ok(None) => println!("ACCESS {ip} {make}: INDETERMINATE"), + Err(e) => println!("ACCESS {ip} {make}: ERROR {e}"), + } + std::process::exit(0); + } + // Bootstrap the wx app + main frame (upstream bridge). wx_rs::init_app("alkane-toolkit", 1280, 800); // Follow the system light/dark appearance. diff --git a/crates/alkane-gui/src/scan.rs b/crates/alkane-gui/src/scan.rs index f97a402d..e7e364db 100644 --- a/crates/alkane-gui/src/scan.rs +++ b/crates/alkane-gui/src/scan.rs @@ -568,9 +568,17 @@ async fn to_row(miner: &dyn Miner) -> MinerRow { // on-board SSH/I2C probe -- a separate feature). let pic_present = if model.to_lowercase().contains("nopic") { Some(false) } else { None }; // Access: locked/view-only when the miner exposes no writable control at - // all, otherwise unlocked. Inferred from capabilities (asic-rs has no direct - // lock-state field). - let write_locked = Some(!caps.any_control()); + // all, otherwise unlocked. Inferred from asic-rs capabilities (there is no + // direct lock-state field). WhatsMiner is the exception: it is controllable + // over its :4028 token API regardless of which commands the matched asic-rs + // backend implements, so this heuristic falsely marks older units "locked". + // Leave it unknown and let the real access probe (the :4028 token check) + // decide (round 12 #8b). + let write_locked = if brand.eq_ignore_ascii_case("whatsminer") { + None + } else { + Some(!caps.any_control()) + }; // Per-hashboard health for the Boards status dots (round 11 #10): green = // present & hashing, red = present but idle/faulty, grey = expected but not // detected. Boards keep asic-rs's reported order (board 1 first); any boards @@ -1146,11 +1154,11 @@ pub fn start_access_probe( let thread_cancel = cancel.clone(); let err_tx = tx.clone(); let res = std::thread::Builder::new().name("access-probe".into()).spawn(move || { - for (ip, fw) in targets { + for (ip, make) in targets { if thread_cancel.load(Ordering::Relaxed) { break; } - let (locked, error) = match crate::access_probe::probe_access(&ip, &fw, &user, &pass) { + let (locked, error) = match crate::access_probe::probe_access(&ip, &make, &user, &pass) { Ok(v) => (v, None), Err(e) => (None, Some(e)), }; diff --git a/crates/alkane-gui/src/ui.rs b/crates/alkane-gui/src/ui.rs index aa54e224..bf2c4990 100644 --- a/crates/alkane-gui/src/ui.rs +++ b/crates/alkane-gui/src/ui.rs @@ -1455,10 +1455,13 @@ impl App { wx_rs::set_status_text("an access check is already running"); return; } + // Pass the brand (make), not the firmware family: the access probe picks + // its strategy by make (WhatsMiner :4028 token vs Antminer web digest), + // and "Stock" alone can't tell them apart (round 12 #8b). let targets: Vec<(String, String)> = self .selected_rows() .iter() - .map(|r| (r.ip.clone(), r.firmware.clone())) + .map(|r| (r.ip.clone(), r.brand.clone())) .collect(); if targets.is_empty() { return;