Adds a right-click "View log (API)..." action that fetches a miner's log through
its firmware API and regex-scans it -- the "logs through API" path for PIC
detection and other metrics without SSH.
Per firmware (crates/alkane-gui/src/log_scan.rs, curl-based like the access
probe, stdout drained on a thread so a large log never deadlocks the pipe):
- VNish: POST /api/v1/unlock -> bearer -> GET /api/v1/logs/miner (the full miner
log: PSU init, per-chain chip detection, tuning, errors).
- Stock Antminer: GET /cgi-bin/log.cgi (digest); older models (Z15) that do not
serve it are reported as "no log over its web API".
- WhatsMiner: get_error_code on :4028 (unauthenticated) formatted as the log.
The summary regex reports PIC status ("not present (no-PIC miner)" / "present --
<version line>"), the latest per-chain chip-detection line, and recent errors
from the log history. Creds reuse the round 12 #13 per-firmware defaults (VNish
password, else "admin"; Antminer web login from the saved global creds).
Verified live: VNish S19j Pro (10.7.1.25) log -> "PIC: not present (log reports a
no-PIC miner)" + chains + recent errors; WhatsMiner (10.8.1.45) -> its active
error codes; Z15 (10.5.1.196) -> honest "no log over its web API". Unit tests for
the summary + a headless ALKANE_LOG_SCAN diagnostic; self-test passes.
Note: WhatsMiner fault codes already surface in the Errors column via asic-rs's
get_error_code -> messages; this adds the raw-log view and the PIC scan on top.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Y8h447BPyJR4fioYZvQ9bh
281 lines
12 KiB
Rust
281 lines
12 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") {
|
|
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([
|
|
"-s",
|
|
"-o",
|
|
"/dev/null",
|
|
"-w",
|
|
"%{http_code}",
|
|
"--digest",
|
|
"-u",
|
|
&userpass,
|
|
"--connect-timeout",
|
|
"5",
|
|
"--max-time",
|
|
"9",
|
|
&url,
|
|
]);
|
|
let out = wait_with_timeout(cmd, Duration::from_secs(12))?;
|
|
// 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).
|
|
fn wait_with_timeout(mut cmd: Command, timeout: Duration) -> Result<std::process::Output, String> {
|
|
use std::io::Read;
|
|
cmd.stdout(std::process::Stdio::piped()).stderr(std::process::Stdio::piped());
|
|
let mut child = cmd.spawn().map_err(|e| format!("spawn curl: {e}"))?;
|
|
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();
|
|
return Err("curl timed out".into());
|
|
}
|
|
std::thread::sleep(Duration::from_millis(100));
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
/// 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;
|
|
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::*;
|
|
|
|
#[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=")
|
|
);
|
|
}
|
|
}
|