Fourth review round found further issues, two being gaps in earlier fixes; this clears the actionable ones: - HIGH board_healths() painted a genuinely-undetected board RED when a fault text also named it (e.g. "chain 2 not found" -> Board(2)); an undetected board now stays grey, matching the documented grey-vs-red invariant. Regression-tested. - HIGH the Change-password prompt used an unmasked field (the Credentials dialog was masked in wave 1 but this prompt was missed) -> masked for PromptKind::Password. - MED the WhatsMiner access probe aborted all remaining password candidates on one transient error -> transient errors now skip to the next candidate and never report a confident "locked" when the answer was really indeterminate. - MED config actions / refresh / pools / flash ignored the operator's configured scan timeout (used asic-rs's 10s default) -> configured_factory now applies it, so a slow-link action reaches the same miners a longer-timeout scan found. - MED the auto-rescan loop set a bogus "scanning..." status even when the scan was deferred (mid-flash) -> begin_scan reports whether it started. - LOW is_aml_140mm matched every S21, not just the S21 Pro its doc names -> fixed. - Offline fixtures now reuse scan::infer_pic instead of a diverging copy. Accepted (documented) from this round: miner_probe's argv secrets (diagnostic CLI), the rebuild_table/update_headers sort-marker duplication, the LuxOS substring success check (command-specific reply), restore/flash target snapshot (dialogs are modal), non-cancellable restore/probe batches, Braiins host-key (LAN reflash), and the perf items (per-tick refill, health recompute, linear upsert, cell formatting). 99 tests + clippy-clean + selftest green. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Djv3oncM4LxTS5tb61Ako6
336 lines
14 KiB
Rust
336 lines
14 KiB
Rust
//! Real access / lock-state detection: whether this miner accepts privileged
|
|
//! (credentialed) command writes, or is view-only.
|
|
//!
|
|
//! asic-rs has no lock-state signal (a wrong-password miner just silently
|
|
//! returns fewer fields, because the collector drops the 401). We build the real
|
|
//! check ON TOP of asic-rs: a NON-mutating, digest-authenticated GET to a
|
|
//! privileged endpoint. On Antminer every `/cgi-bin/*.cgi` requires digest auth,
|
|
//! so the HTTP status is decisive -- 200 means our credentials authenticate
|
|
//! (we can write -> unlocked), 401/403 means they are rejected (view-only ->
|
|
//! locked). We probe `get_miner_conf.cgi`, which is read-only (never the
|
|
//! mutating `set_miner_conf.cgi`).
|
|
//!
|
|
//! We shell out to `curl --digest` (already present, supports digest auth)
|
|
//! 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<Aes256>;
|
|
|
|
/// 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`.
|
|
pub fn classify_http_code(code: &str) -> Option<bool> {
|
|
match code.trim() {
|
|
"200" | "204" => Some(false), // authenticated -> unlocked/writable
|
|
"401" | "403" => Some(true), // rejected -> locked/view-only
|
|
_ => None, // 000 (no connect), 404, 5xx, ... -> unknown
|
|
}
|
|
}
|
|
|
|
/// The privileged, read-only endpoint we probe per firmware family. Antminer
|
|
/// stock/aftermarket all gate `get_miner_conf.cgi` behind digest auth.
|
|
fn endpoint(_firmware: &str) -> &'static str {
|
|
"/cgi-bin/get_miner_conf.cgi"
|
|
}
|
|
|
|
/// 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<Option<bool>, String> {
|
|
if make.eq_ignore_ascii_case("whatsminer") {
|
|
// Try the caller's saved scan password first (round 18 #12: it was being
|
|
// ignored for WhatsMiner, so a miner opened with the operator's real
|
|
// password was mis-reported as locked), then the per-firmware override and
|
|
// factory defaults. All attempts are non-mutating.
|
|
let mut candidates = Vec::new();
|
|
if !pass.is_empty() {
|
|
candidates.push(pass.to_string());
|
|
}
|
|
for c in whatsminer_password_candidates() {
|
|
if !candidates.contains(&c) {
|
|
candidates.push(c);
|
|
}
|
|
}
|
|
return Ok(probe_whatsminer_access(ip, &candidates));
|
|
}
|
|
let url = format!("http://{ip}{}", endpoint(make));
|
|
let mut cmd = Command::new("curl");
|
|
cmd.args([
|
|
"-s",
|
|
"-o",
|
|
"/dev/null",
|
|
"-w",
|
|
"%{http_code}",
|
|
"--digest",
|
|
"--connect-timeout",
|
|
"5",
|
|
"--max-time",
|
|
"9",
|
|
"-K",
|
|
"-", // read the rest of the config (the credentials) from stdin
|
|
&url,
|
|
]);
|
|
// The user:pass goes through a curl config on stdin, never argv, so it can't
|
|
// be read from the process list (round 18 #12).
|
|
let config = format!("user = \"{}\"\n", curl_config_quote(&format!("{user}:{pass}")));
|
|
let out = wait_with_timeout(cmd, Duration::from_secs(12), Some(config.as_bytes()))?;
|
|
// curl prints the status code to stdout regardless of exit status (000 on a
|
|
// connection failure), so classify the code rather than the exit status.
|
|
let code = String::from_utf8_lossy(&out.stdout);
|
|
Ok(classify_http_code(&code))
|
|
}
|
|
|
|
/// Run a command with a wall-clock timeout (curl can hang past --max-time on a
|
|
/// 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<std::process::Output, String> {
|
|
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())? {
|
|
Some(status) => {
|
|
let mut stdout = Vec::new();
|
|
let mut stderr = Vec::new();
|
|
if let Some(mut o) = child.stdout.take() {
|
|
let _ = o.read_to_end(&mut stdout);
|
|
}
|
|
if let Some(mut e) = child.stderr.take() {
|
|
let _ = e.read_to_end(&mut stderr);
|
|
}
|
|
return Ok(std::process::Output { status, stdout, stderr });
|
|
}
|
|
None => {
|
|
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));
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
/// Escape a value for a curl `--config` file (double-quoted string).
|
|
fn curl_config_quote(s: &str) -> 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.
|
|
fn whatsminer_password_candidates() -> Vec<String> {
|
|
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()]
|
|
}
|
|
|
|
/// Fetch a WhatsMiner's active fault codes over the unauthenticated :4028
|
|
/// get_error_code command and format them one per line for the log viewer
|
|
/// (round 12 #12). Returns None if the miner does not answer.
|
|
pub fn whatsminer_get_error_code(ip: &str) -> Option<String> {
|
|
let resp = wm_rpc(ip, "{\"command\":\"get_error_code\"}", Duration::from_secs(6)).ok()?;
|
|
let v: serde_json::Value = serde_json::from_str(&resp).ok()?;
|
|
let codes = v.get("Msg").and_then(|m| m.get("error_code")).and_then(|c| c.as_array());
|
|
let mut lines = vec![format!("WhatsMiner get_error_code ({ip}):")];
|
|
match codes {
|
|
Some(arr) if !arr.is_empty() => {
|
|
for entry in arr {
|
|
if let Some(obj) = entry.as_object() {
|
|
for (code, when) in obj {
|
|
lines.push(format!(" error {code}: {}", when.as_str().unwrap_or("")));
|
|
}
|
|
}
|
|
}
|
|
}
|
|
_ => lines.push(" no active error codes".to_string()),
|
|
}
|
|
Some(lines.join("\n"))
|
|
}
|
|
|
|
/// 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<String, String> {
|
|
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<String> {
|
|
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::<ZeroPadding>(&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<bool> {
|
|
let timeout = Duration::from_secs(6);
|
|
let mut reachable = false;
|
|
// A transient error on one candidate must not abandon the others (round 18 #12):
|
|
// skip to the next candidate, but remember it happened so we never report a
|
|
// confident "locked" when the answer was really indeterminate.
|
|
let mut errored = 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(_) => {
|
|
errored = true;
|
|
continue;
|
|
}
|
|
};
|
|
let v: serde_json::Value = match serde_json::from_str(&tok_resp) {
|
|
Ok(v) => v,
|
|
Err(_) => {
|
|
errored = true;
|
|
continue;
|
|
}
|
|
};
|
|
let (Some(salt), Some(newsalt), Some(time)) = v
|
|
.get("Msg")
|
|
.map(|msg| {
|
|
(
|
|
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()),
|
|
)
|
|
})
|
|
.unwrap_or((None, None, None))
|
|
else {
|
|
errored = true;
|
|
continue;
|
|
};
|
|
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(_) => {
|
|
errored = true;
|
|
continue;
|
|
}
|
|
};
|
|
if resp.contains("\"enc\"") {
|
|
return Some(false); // accepted -> unlocked/writable
|
|
}
|
|
// rejected -> try the next candidate password
|
|
}
|
|
// Only report "locked" when we cleanly reached the miner and every candidate
|
|
// was rejected with no transient errors; otherwise the result is indeterminate.
|
|
if reachable && !errored { Some(true) } else { None }
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
#[test]
|
|
fn classify_codes() {
|
|
assert_eq!(classify_http_code("200"), Some(false), "authenticated -> unlocked");
|
|
assert_eq!(classify_http_code("204"), Some(false));
|
|
assert_eq!(classify_http_code("401"), Some(true), "unauthorized -> locked");
|
|
assert_eq!(classify_http_code("403"), Some(true));
|
|
assert_eq!(classify_http_code("000"), None, "no connection -> unknown");
|
|
assert_eq!(classify_http_code("404"), None, "endpoint absent -> unknown");
|
|
assert_eq!(classify_http_code("500"), None);
|
|
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=")
|
|
);
|
|
}
|
|
}
|