diff --git a/crates/alkane-cli/src/main.rs b/crates/alkane-cli/src/main.rs index 14d37dd7..6c58d8a5 100644 --- a/crates/alkane-cli/src/main.rs +++ b/crates/alkane-cli/src/main.rs @@ -22,6 +22,7 @@ use alkane_flash::preflight::{preflight, PreflightOptions}; use alkane_flash::stock; use alkane_flash::stock::{InPlaceOptions, InPlaceOutcome, RestoreImages}; use alkane_flash::stock_firmware; +use alkane_flash::zynq_nand; use alkane_flash::transport::{Remote, RootMethod, SshOptions, SshTransport}; use std::collections::{BTreeMap, BTreeSet}; use std::fs; @@ -1039,8 +1040,10 @@ fn latest_backup(dir: &Path) -> Option { /// Boards this toolkit can install alkane onto, with the miner each is the /// control board for. The install/restore gate is the .afw's board matching one /// of these; `compat` lists them so an operator knows what is supported. -const SUPPORTED: &[(&str, &str)] = - &[("zynq-7010", "Antminer S17 (Xilinx Zynq-7010 control board)")]; +const SUPPORTED: &[(&str, &str)] = &[ + ("zynq-7010", "Antminer S17 (Xilinx Zynq-7010 control board)"), + ("a113d", "Antminer BHB42XXX / S19k Pro (Amlogic A113D/AXG control board)"), +]; fn is_supported(board: &str) -> bool { SUPPORTED.iter().any(|(b, _)| *b == board) @@ -1112,14 +1115,44 @@ fn run_restore_stock(args: &[String]) -> Result<(), Box> &["dry-run"], )?; let host = opts.value("host").ok_or("--host is required")?.to_owned(); - let firmware = opts.value("stock-firmware").ok_or( - "--stock-firmware is required \ - (an OTA update .tar.gz or an SD recovery .zip for this board)", - )?; // Restore reaches the alkane board over SSH as root; the board credential is // supplied via --password-file / ALKANE_BOARD_PASSWORD(_FILE). let password = read_board_password(&opts)?; + // A113D restores with NO stock firmware file: it is a one-byte boot-flag flip + // in-band from the running alkane OS (the genuine stock in the untouched boot + // partition is booted via storeboot). Try that first when no firmware is + // given; if the board is not an alkane A113D, require --stock-firmware. + let firmware = match opts.value("stock-firmware") { + Some(f) => f, + None => { + if opts.flag("dry-run") { + println!("DRY RUN: would restore {host} to stock by flipping the A113D boot flag"); + println!("(no stock firmware needed; the untouched stock boot partition is booted)."); + println!("Re-run with --confirm FLASH."); + return Ok(()); + } + if opts.value("confirm") != Some("FLASH") { + return Err("refusing to restore without --confirm FLASH".into()); + } + println!("restoring {host} to genuine stock (A113D flag flip, network-only)..."); + match stock::restore_aml_flag(&host, password.as_deref()) { + Ok(()) => { + println!("restore reported success (boot flag cleared; stock boots via storeboot)."); + println!("verify independently: the board should present genuine stock"); + println!("(cgminer API on :4028, lighttpd 401 on :80, dropbear 2018.x)."); + return Ok(()); + } + Err(alkane_flash::stock::StockError::NotApplicable) => { + return Err("this board is not an alkane A113D; pass --stock-firmware \ + to restore it" + .into()); + } + Err(e) => return Err(e.into()), + } + } + }; + // Parse the genuine vendor package for the stock kernel + rootfs. The kernel // device tree is not in distributable Bitmain firmware; the toolkit supplies // the correct per-board dtb, so any genuine package (OTA or SD) works here. @@ -1139,6 +1172,7 @@ fn run_restore_stock(args: &[String]) -> Result<(), Box> let images = RestoreImages { kernel: &fw.kernel, rootfs: &fw.rootfs, + dtb: fw.dtb.as_deref(), }; stock::restore_to_stock(&host, &images, password.as_deref())?; println!("restore-to-stock reported success (stock images written, BOOT.bin preserved)."); @@ -1147,9 +1181,176 @@ fn run_restore_stock(args: &[String]) -> Result<(), Box> Ok(()) } +/// Run a command as root on a stock board and print its output (drives the DSH +/// root-on-stock primitive; used to build and debug the flash operations). +fn run_root_run(args: &[String]) -> Result<(), Box> { + let opts = parse_args(args, ssh_values(), &[])?; + let host = opts.value("host").ok_or("--host is required")?.to_owned(); + let cmd = opts + .positionals + .join(" "); + if cmd.trim().is_empty() { + return Err("usage: alkane-cli afw root-run --host ".into()); + } + let password = read_board_password(&opts)?; + let out = stock::root_exec(&host, password.as_deref(), &cmd)?; + print!("{out}"); + Ok(()) +} + +/// Readable zynq NAND install-from-stock: wrap the afw's zImage/rootfs as the +/// legacy uImages the stock U-Boot boots, carve the on-board genuine-stock +/// backup, write the boot slots and reboot. Drives the DSH root-on-stock +/// primitive; board must be on stock (credential root/root). +fn run_nand_install(args: &[String]) -> Result<(), Box> { + let opts = parse_args(args, &[ssh_values(), &["confirm"]].concat(), &["allow-unsigned"])?; + let host = opts.value("host").ok_or("--host is required")?.to_owned(); + let afw_path = opts + .positionals + .first() + .ok_or("usage: alkane-cli afw nand-install --host --confirm FLASH")?; + let verified = load_afw(afw_path, &opts)?; + if !zynq::owns_board(&verified.manifest.board) { + return Err(format!("nand-install is zynq-7010 only, not {}", verified.manifest.board).into()); + } + if opts.value("confirm") != Some("FLASH") { + return Err("refusing to install without --confirm FLASH".into()); + } + let kernel = verified.image("kernel").ok_or("afw missing kernel image")?.1; + let dtb = verified.image("dtb").ok_or("afw missing dtb image")?.1; + let rootfs = verified.image("rootfs").ok_or("afw missing rootfs image")?.1; + let password = read_board_password(&opts)?; + println!("installing {} onto stock board {host} (readable NAND path)...", verified.manifest.board); + zynq_nand::install_from_stock(&host, kernel, dtb, rootfs, password.as_deref())?; + println!("install reported success (on-board stock backup carved; boot slots written; rebooting)."); + print!("{}", zynq_verify_hint(&host)); + Ok(()) +} + +/// Readable zynq restore-to-stock: write the vendor stock kernel/dtb/rootfs +/// back to the boot slots over SSH (board on alkane). Needs the alkane image +/// that exposes the boot partitions. +fn run_nand_restore_stock(args: &[String]) -> Result<(), Box> { + let opts = parse_args(args, &[ssh_values(), &["confirm", "stock-firmware"]].concat(), &["dry-run"])?; + let host = opts.value("host").ok_or("--host is required")?.to_owned(); + let firmware = opts.value("stock-firmware").ok_or("--stock-firmware is required")?; + let fw = stock_firmware::parse(Path::new(firmware))?; + println!("stock firmware: {}", fw.summary()); + if opts.value("confirm") != Some("FLASH") { + return Err("refusing to restore without --confirm FLASH".into()); + } + let password = read_board_password(&opts)?; + println!("restoring {host} to genuine stock (readable NAND path)..."); + zynq_nand::restore_to_stock(&host, &fw.kernel, &fw.rootfs, fw.dtb.as_deref(), password.as_deref())?; + println!("restore-to-stock reported success (stock kernel/dtb/rootfs written, BOOT.bin preserved)."); + Ok(()) +} + +/// Readable zynq on-board backup check: report whether a restorable genuine- +/// stock backup is present (board on alkane). Read-only. +fn run_nand_backup_check(args: &[String]) -> Result<(), Box> { + let opts = parse_args(args, ssh_values(), &[])?; + let host = opts.value("host").ok_or("--host is required")?.to_owned(); + let password = read_board_password(&opts)?; + if zynq_nand::onboard_backup_present(&host, password.as_deref())? { + println!("on-board stock backup: PRESENT (restorable with nand-restore-onboard)"); + } else { + println!("on-board stock backup: ABSENT"); + } + Ok(()) +} + +/// Readable zynq restore-from-on-board-backup: copy the saved stock images back +/// to the boot slots (board on alkane), no vendor file needed. +fn run_nand_restore_onboard(args: &[String]) -> Result<(), Box> { + let opts = parse_args(args, &[ssh_values(), &["confirm"]].concat(), &[])?; + let host = opts.value("host").ok_or("--host is required")?.to_owned(); + if opts.value("confirm") != Some("FLASH") { + return Err("refusing to restore without --confirm FLASH".into()); + } + let password = read_board_password(&opts)?; + println!("restoring {host} to stock from its on-board backup (readable NAND path)..."); + zynq_nand::restore_from_onboard(&host, password.as_deref())?; + println!("restore-from-onboard reported success (stock images written, rebooting)."); + Ok(()) +} + +/// Run a command as root on an alkane board over SSH and print its output +/// (the alkane-side analog of root-run; used to drive and debug the +/// alkane-side NAND operations: restore-to-stock and on-board backup/restore). +fn run_ssh_run(args: &[String]) -> Result<(), Box> { + let opts = parse_args(args, ssh_values(), &[])?; + let cmd = opts.positionals.join(" "); + if cmd.trim().is_empty() { + return Err("usage: alkane-cli afw ssh-run --host ".into()); + } + let (ssh, _secret) = ssh_options(&opts, "root")?; + let mut transport = SshTransport::connect(ssh, true)?; + let out = transport.root_command(&cmd, std::time::Duration::from_secs(120))?; + print!("{}", String::from_utf8_lossy(&out)); + Ok(()) +} + +/// Stream a local file to a stock board as root (drives the DSH root-on-stock +/// primitive; used to stage kernel/rootfs images for the flash operations). +fn run_root_put(args: &[String]) -> Result<(), Box> { + let opts = parse_args(args, &[ssh_values(), &["remote"]].concat(), &[])?; + let host = opts.value("host").ok_or("--host is required")?.to_owned(); + let remote = opts + .value("remote") + .ok_or("--remote is required")? + .to_owned(); + let local = opts + .positionals + .first() + .ok_or("usage: alkane-cli afw root-put --host --remote ")?; + let data = std::fs::read(local)?; + let password = read_board_password(&opts)?; + stock::root_put(&host, password.as_deref(), &data, &remote)?; + println!("put {} bytes -> {remote}", data.len()); + Ok(()) +} + +/// Report whether an alkane board holds a restorable on-board stock backup. +/// Read-only (no FLASH confirmation). +fn run_backup_check(args: &[String]) -> Result<(), Box> { + let opts = parse_args(args, ssh_values(), &[])?; + let host = opts.value("host").ok_or("--host is required")?.to_owned(); + let password = read_board_password(&opts)?; + let present = stock::onboard_stock_backup_present(&host, password.as_deref())?; + println!("on-board stock backup present: {present}"); + Ok(()) +} + +/// Restore an alkane board to genuine stock from its on-board backup (no vendor +/// firmware file). Destructive; gated by --confirm FLASH. +fn run_restore_onboard(args: &[String]) -> Result<(), Box> { + let opts = parse_args(args, &[ssh_values(), &["confirm"]].concat(), &["dry-run"])?; + let host = opts.value("host").ok_or("--host is required")?.to_owned(); + let password = read_board_password(&opts)?; + if opts.flag("dry-run") { + println!( + "DRY RUN: would restore {host} to stock from its on-board backup \ + (BOOT.bin preserved). Re-run with --confirm FLASH." + ); + return Ok(()); + } + if opts.value("confirm") != Some("FLASH") { + return Err("refusing to restore without --confirm FLASH".into()); + } + println!("restoring {host} to stock from its on-board backup (network-only)..."); + stock::restore_from_onboard_backup( + &host, + password.as_deref(), + std::time::Duration::from_secs(300), + )?; + println!("restore-from-onboard reported success. Verify independently the board answers as stock."); + Ok(()) +} + fn run_afw(args: &[String]) -> Result<(), Box> { let subcommand = args.first().ok_or( - "usage: alkane-cli afw ", + "usage: alkane-cli afw ", )?; let rest = &args[1..]; match subcommand.as_str() { @@ -1163,6 +1364,15 @@ fn run_afw(args: &[String]) -> Result<(), Box> { "verify-live" => run_verify_live(rest), "restore" => run_restore(rest), "restore-stock" => run_restore_stock(rest), + "backup-check" => run_backup_check(rest), + "restore-onboard" => run_restore_onboard(rest), + "root-run" => run_root_run(rest), + "root-put" => run_root_put(rest), + "ssh-run" => run_ssh_run(rest), + "nand-install" => run_nand_install(rest), + "nand-restore-stock" => run_nand_restore_stock(rest), + "nand-backup-check" => run_nand_backup_check(rest), + "nand-restore-onboard" => run_nand_restore_onboard(rest), other => Err(format!("unknown afw subcommand {other}").into()), } } diff --git a/crates/alkane-flash/src/aml_ubi.rs b/crates/alkane-flash/src/aml_ubi.rs new file mode 100644 index 00000000..87ee2163 --- /dev/null +++ b/crates/alkane-flash/src/aml_ubi.rs @@ -0,0 +1,656 @@ +// SPDX-License-Identifier: MIT +//! Readable Amlogic A113D (Amlogic AXG, Antminer BHB42XXX) install/restore over +//! the FLAG-BASED boot chain. This is the Claude-domain counterpart of +//! `zynq_nand`: it drives the DSH root-on-stock primitive (`stock::root_exec` / +//! `stock::root_put`) for the from-stock install, and the alkane SSH transport +//! for the in-band restore, with the stock-access method never read here. +//! +//! Mechanism (CONFIRMED live 2026-11-13, see alkane-sdk-construction +//! alkane-a113d-image-bringup): +//! +//! - The OS files `alkane/{vmlinux.bin,devicetree.dtb,uramdisk.image.gz}` are +//! staged into the nvdata UBI volume (UBIFS), exactly as the alkane boot chain +//! reads them (`ubifsload`). Zero raw writes to the brick-sensitive regions. +//! - A one-byte-magic FLAG lives in the `misc` partition (the Android BCB block, +//! abs NAND 0x1000000) at erase-block 1 (offset 0x20000, abs 0x1020000). Block +//! 0 (the BCB) is never touched. The flag is the four bytes "ALAN". +//! - Stock U-Boot's `bootcmd` is set (once, in-band via /dev/nand_env from stock) +//! to `run checkalk; run storeboot`, where `checkalk` RAW-reads the flag page +//! (`nand read`, NO UBI) and, only if the magic matches, runs `alkboot` (which +//! mounts the nvdata UBIFS and boots alkane). When the flag is absent the stock +//! path is a pure raw read + `storeboot`, which boots genuine stock STABLY (a +//! ubi/ubifs op in the stock boot path instead makes stock's firstboot +//! supervisor reboot-loop - that is why the flag read must be raw). +//! - INSTALL (stock -> alkane): stage the files, write the env, set flag=ALAN. +//! - RESTORE (alkane -> stock): erase the flag block in-band from the running +//! alkane OS (which exposes `misc` as an MTD). One raw NAND erase, `reboot -f`, +//! and stock boots via `storeboot`. Fully network-only; the alkane payload and +//! the env are left in place, so re-install is just re-writing the flag. +//! +//! itest note: this vendor U-Boot's `itest.l *` does NOT compare correctly, +//! but `itest.b *` does, so `checkalk` tests the four magic bytes with +//! nested `itest.b`. CONFIRMED live 2026-11-13. + +use crate::stock::StockError; +use crate::transport::{Remote, SshOptions, SshTransport}; +use crate::uimage::crc32; +use std::path::{Path, PathBuf}; +use std::time::Duration; + +pub const BOARD: &str = "a113d"; + +/// U-Boot env blob size on this board (CONFIRMED: `/dev/nand_env` is 64 KiB, a +/// standard U-Boot env = 4-byte little-endian CRC32 + NUL-separated key=value, +/// double-NUL terminated, 0x00-padded). +const ENV_SIZE: usize = 65536; + +/// Flag: four magic bytes "ALAN" at misc (abs 0x1000000) erase-block 1. +const FLAG_ABS_OFFSET: u64 = 0x1020000; // misc base 0x1000000 + block 1 (0x20000) +const FLAG_BLOCK_IN_MISC: u64 = 0x20000; // offset of the flag block within the misc MTD +const FLAG_MAGIC: [u8; 4] = *b"ALAN"; + +/// Boot load addresses (CONFIRMED live) and the alkane console bootargs. +const KRNADDR: &str = "0x1200000"; +const FDTADDR: &str = "0x8000000"; +const RDADDR: &str = "0x8100000"; +const ALK_BOOTARGS: &str = + "console=ttyAML0,115200 earlycon=meson,0xff803000 no_console_suspend"; + +/// The on-board basenames inside the nvdata UBI volume's `alkane/` directory. +const ALKANE_DIR: &str = "alkane"; + +// --------------------------------------------------------------------------- +// Shell abstraction: StockShell drives the DSH root primitive; AlkaneShell the +// alkane SSH transport. (Mirrors zynq_nand.) +// --------------------------------------------------------------------------- + +trait Shell { + fn exec(&mut self, cmd: &str) -> Result; + fn exec_long(&mut self, cmd: &str) -> Result; + fn put(&mut self, data: &[u8], remote_path: &str) -> Result<(), StockError>; +} + +struct StockShell { + host: String, + password: Option, +} + +impl Shell for StockShell { + fn exec(&mut self, cmd: &str) -> Result { + crate::stock::root_exec(&self.host, self.password.as_deref(), cmd) + } + fn exec_long(&mut self, cmd: &str) -> Result { + // root_exec already carries a generous timeout in the method. + crate::stock::root_exec(&self.host, self.password.as_deref(), cmd) + } + fn put(&mut self, data: &[u8], remote_path: &str) -> Result<(), StockError> { + crate::stock::root_put(&self.host, self.password.as_deref(), data, remote_path) + } +} + +struct AlkaneShell { + transport: SshTransport, + _secret: TempFile, +} + +impl AlkaneShell { + fn connect(host: &str, password: Option<&str>) -> Result { + // Password in a 0600 temp file; a throwaway empty known_hosts (the host + // key legitimately changes across stock<->alkane). Same stance as zynq. + let secret = TempFile::with(password.unwrap_or("alkane").as_bytes(), "pw")?; + let known = temp_path("kh"); + let _ = std::fs::File::create(&known); + let options = SshOptions { + host: host.to_owned(), + port: 22, + user: "root".to_owned(), + identity_file: None, + password_file: Some(secret.0.clone()), + known_hosts: Some(known), + root_method: crate::transport::RootMethod::Auto, + update_daemon_port: None, + }; + let transport = SshTransport::connect(options, true) + .map_err(|e| StockError::Network(e.to_string()))?; + Ok(AlkaneShell { + transport, + _secret: secret, + }) + } +} + +impl Shell for AlkaneShell { + fn exec(&mut self, cmd: &str) -> Result { + self.transport + .root_command(cmd, Duration::from_secs(120)) + .map(|o| String::from_utf8_lossy(&o).into_owned()) + .map_err(|e| StockError::Method(e.to_string())) + } + fn exec_long(&mut self, cmd: &str) -> Result { + self.transport + .root_command(cmd, Duration::from_secs(900)) + .map(|o| String::from_utf8_lossy(&o).into_owned()) + .map_err(|e| StockError::Method(e.to_string())) + } + fn put(&mut self, data: &[u8], remote_path: &str) -> Result<(), StockError> { + let tmp = TempFile::with(data, "put")?; + self.transport + .push(&tmp.0, remote_path, Duration::from_secs(900)) + .map_err(|e| StockError::Method(e.to_string())) + } +} + +static TEMP_SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + +fn temp_path(tag: &str) -> PathBuf { + let n = TEMP_SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + std::env::temp_dir().join(format!("alkane-aml-{}-{}-{}", std::process::id(), tag, n)) +} + +/// A 0600 temp file removed on drop. +struct TempFile(PathBuf); +impl TempFile { + fn with(contents: &[u8], tag: &str) -> Result { + let path = temp_path(tag); + write_private(&path, contents).map_err(|e| StockError::Io(e.to_string()))?; + Ok(TempFile(path)) + } +} +impl Drop for TempFile { + fn drop(&mut self) { + let _ = std::fs::remove_file(&self.0); + } +} + +#[cfg(unix)] +fn write_private(path: &Path, contents: &[u8]) -> std::io::Result<()> { + use std::io::Write as _; + use std::os::unix::fs::OpenOptionsExt; + let mut f = std::fs::OpenOptions::new() + .create(true) + .truncate(true) + .write(true) + .mode(0o600) + .open(path)?; + f.write_all(contents)?; + f.flush() +} + +#[cfg(not(unix))] +fn write_private(path: &Path, contents: &[u8]) -> std::io::Result<()> { + std::fs::write(path, contents) +} + +// --------------------------------------------------------------------------- +// base64 (busybox-safe: decode a possibly line-wrapped stream). +// --------------------------------------------------------------------------- + +fn b64_decode(s: &str) -> Option> { + const INV: u8 = 0xFF; + fn val(c: u8) -> u8 { + match c { + b'A'..=b'Z' => c - b'A', + b'a'..=b'z' => c - b'a' + 26, + b'0'..=b'9' => c - b'0' + 52, + b'+' => 62, + b'/' => 63, + _ => INV, + } + } + let mut out = Vec::new(); + let mut acc = 0u32; + let mut bits = 0u32; + for &c in s.as_bytes() { + if c == b'=' { + break; + } + let v = val(c); + if v == INV { + continue; // skip whitespace / newlines + } + acc = (acc << 6) | v as u32; + bits += 6; + if bits >= 8 { + bits -= 8; + out.push((acc >> bits) as u8); + } + } + Some(out) +} + +fn b64_encode(data: &[u8]) -> String { + const T: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + let mut out = String::with_capacity((data.len() + 2) / 3 * 4); + for chunk in data.chunks(3) { + let b = [ + chunk[0], + *chunk.get(1).unwrap_or(&0), + *chunk.get(2).unwrap_or(&0), + ]; + let n = ((b[0] as u32) << 16) | ((b[1] as u32) << 8) | b[2] as u32; + out.push(T[((n >> 18) & 63) as usize] as char); + out.push(T[((n >> 12) & 63) as usize] as char); + out.push(if chunk.len() > 1 { + T[((n >> 6) & 63) as usize] as char + } else { + '=' + }); + out.push(if chunk.len() > 2 { + T[(n & 63) as usize] as char + } else { + '=' + }); + } + out +} + +// --------------------------------------------------------------------------- +// U-Boot environment (standard format) read / parse / build / write. +// --------------------------------------------------------------------------- + +/// Read the 64 KiB U-Boot env blob from /dev/nand_env (stock only). +fn read_env(sh: &mut dyn Shell) -> Result, StockError> { + let out = sh.exec( + "echo B64START; dd if=/dev/nand_env bs=65536 count=1 2>/dev/null | base64; echo B64END", + )?; + let start = out + .find("B64START") + .ok_or_else(|| StockError::Method("env read: no marker".into()))?; + let end = out + .find("B64END") + .ok_or_else(|| StockError::Method("env read: no end marker".into()))?; + let b64 = &out[start + "B64START".len()..end]; + let blob = b64_decode(b64).ok_or_else(|| StockError::Method("env read: bad base64".into()))?; + if blob.len() != ENV_SIZE { + return Err(StockError::Method(format!( + "env read: {} bytes (expected {ENV_SIZE})", + blob.len() + ))); + } + let stored = u32::from_le_bytes([blob[0], blob[1], blob[2], blob[3]]); + if crc32(&blob[4..]) != stored { + return Err(StockError::Method("env read: CRC mismatch".into())); + } + Ok(blob) +} + +/// Parse the env body into ordered (key, value) pairs (up to the double-NUL). +fn parse_env(blob: &[u8]) -> Vec<(String, String)> { + let body = &blob[4..]; + let end = body + .windows(2) + .position(|w| w == [0, 0]) + .unwrap_or(body.len()); + let mut vars = Vec::new(); + for kv in body[..end].split(|&b| b == 0) { + if kv.is_empty() { + continue; + } + if let Some(eq) = kv.iter().position(|&b| b == b'=') { + let k = String::from_utf8_lossy(&kv[..eq]).into_owned(); + let v = String::from_utf8_lossy(&kv[eq + 1..]).into_owned(); + vars.push((k, v)); + } + } + vars +} + +/// Build a 64 KiB env blob from ordered (key,value) pairs: CRC32 + body + +/// double-NUL + 0x00 padding (what a clean `saveenv` produces). +fn build_env(vars: &[(String, String)]) -> Result, StockError> { + let mut body = Vec::with_capacity(ENV_SIZE); + for (k, v) in vars { + body.extend_from_slice(k.as_bytes()); + body.push(b'='); + body.extend_from_slice(v.as_bytes()); + body.push(0); + } + body.push(0); // terminating double-NUL (last var's NUL + this one) + if body.len() > ENV_SIZE - 4 { + return Err(StockError::Method("env too large".into())); + } + body.resize(ENV_SIZE - 4, 0); + let crc = crc32(&body); + let mut blob = Vec::with_capacity(ENV_SIZE); + blob.extend_from_slice(&crc.to_le_bytes()); + blob.extend_from_slice(&body); + Ok(blob) +} + +/// Set (or insert, preserving order) a variable. +fn set_var(vars: &mut Vec<(String, String)>, key: &str, value: &str) { + if let Some(slot) = vars.iter_mut().find(|(k, _)| k == key) { + slot.1 = value.to_owned(); + } else { + vars.push((key.to_owned(), value.to_owned())); + } +} + +/// Write the env blob to /dev/nand_env and read it back byte-exact BEFORE any +/// reboot (the env is only consumed at next boot, so a verified read-back cannot +/// brick). On a read-back mismatch the caller must restore the previous env. +fn write_env(sh: &mut dyn Shell, blob: &[u8]) -> Result<(), StockError> { + let b64 = b64_encode(blob); + // Stream the blob to a temp file, then dd it to /dev/nand_env in one write. + sh.put(b64.as_bytes(), "/tmp/.alkenv.b64")?; + let out = sh.exec( + "base64 -d /tmp/.alkenv.b64 > /tmp/.alkenv.bin 2>/dev/null; \ + dd if=/tmp/.alkenv.bin of=/dev/nand_env bs=65536 count=1 2>/dev/null; sync; \ + echo RB=$(dd if=/dev/nand_env bs=65536 count=1 2>/dev/null | md5sum | cut -d' ' -f1); \ + rm -f /tmp/.alkenv.b64 /tmp/.alkenv.bin", + )?; + let want = md5_hex(blob); + let got = out + .split("RB=") + .nth(1) + .map(|s| s.trim().to_owned()) + .unwrap_or_default(); + if got != want { + return Err(StockError::Method(format!( + "env write read-back mismatch: wrote {want}, read {got}" + ))); + } + Ok(()) +} + +fn md5_hex(data: &[u8]) -> String { + crate::md5::md5_hex(data) +} + +// --------------------------------------------------------------------------- +// MTD / flag helpers. +// --------------------------------------------------------------------------- + +/// Find the /dev/mtdN whose /proc/mtd label matches `name`. +fn find_mtd(sh: &mut dyn Shell, name: &str) -> Result { + let out = sh.exec("cat /proc/mtd")?; + for line in out.lines() { + if line.contains(&format!("\"{name}\"")) { + if let Some((dev, _)) = line.split_once(':') { + return Ok(format!("/dev/{}", dev.trim())); + } + } + } + Err(StockError::Method(format!("no '{name}' MTD on this board"))) +} + +/// Discover the nvdata UBI volume's name (never assumed: vendor histories leave +/// different names). Looks for an already-attached ubi volume on the nvdata MTD. +fn discover_nvdata_volume(sh: &mut dyn Shell) -> Result<(String, String), StockError> { + // Returns (mountpoint, volume_name). On stock the vendor mounts nvdata (e.g. + // at /tmp/miner); find the ubifs mount whose volume sits on the nvdata MTD. + let mounts = sh.exec("cat /proc/mounts")?; + for line in mounts.lines() { + // e.g. "/dev/ubi2_0 /tmp/miner ubifs rw,..." + let mut it = line.split_whitespace(); + let dev = it.next().unwrap_or(""); + let mnt = it.next().unwrap_or(""); + let fs = it.next().unwrap_or(""); + if fs == "ubifs" && dev.contains("ubi") { + // read the volume name from sysfs: /sys/class/ubi//name + let base = dev.trim_start_matches("/dev/"); + let name = sh + .exec(&format!("cat /sys/class/ubi/{base}/name 2>/dev/null"))? + .trim() + .to_owned(); + // Only accept the nvdata volume (skip the small config_data volume). + // nvdata is the large one; confirm by its mount not being /config. + if !name.is_empty() && mnt != "/config" { + return Ok((mnt.to_owned(), name)); + } + } + } + Err(StockError::Method( + "could not find the mounted nvdata UBI volume".into(), + )) +} + +/// Write the ALAN flag into misc block 1 (flag=alkane). `misc_dev` is the misc +/// MTD device on the running OS (stock: /dev/mtd2; alkane: whatever /proc/mtd +/// shows for "misc"). +fn set_flag_alkane(sh: &mut dyn Shell, misc_dev: &str) -> Result<(), StockError> { + // one page: magic + 0xFF pad + let mut page = FLAG_MAGIC.to_vec(); + page.resize(2048, 0xFF); + sh.put(&page, "/tmp/.alkflag")?; + let out = sh.exec(&format!( + "flash_erase {misc_dev} 0x{FLAG_BLOCK_IN_MISC:x} 1 >/dev/null 2>&1; \ + nandwrite -s 0x{FLAG_BLOCK_IN_MISC:x} -p {misc_dev} /tmp/.alkflag >/dev/null 2>&1; sync; \ + echo RB=$(dd if={misc_dev} bs=2048 skip={blk} count=1 2>/dev/null | md5sum | cut -d' ' -f1); \ + rm -f /tmp/.alkflag", + blk = FLAG_BLOCK_IN_MISC / 2048 + ))?; + let want = md5_hex(&page); + let got = out + .split("RB=") + .nth(1) + .map(|s| s.trim().to_owned()) + .unwrap_or_default(); + if got != want { + return Err(StockError::Method("flag write read-back mismatch".into())); + } + Ok(()) +} + +/// Erase the flag block (flag=stock). +fn clear_flag(sh: &mut dyn Shell, misc_dev: &str) -> Result<(), StockError> { + sh.exec(&format!( + "flash_erase {misc_dev} 0x{FLAG_BLOCK_IN_MISC:x} 1 >/dev/null 2>&1; sync; echo CLEARED" + ))?; + Ok(()) +} + +// --------------------------------------------------------------------------- +// The flag-based boot-chain env vars. +// --------------------------------------------------------------------------- + +/// checkalk raw-reads the flag page and tests the four magic bytes with nested +/// `itest.b` (this vendor U-Boot mis-compares `itest.l *`); only on a match +/// does it run alkboot. No ubi/ubifs here - that keeps the stock path raw. +fn checkalk_value() -> String { + format!( + "nand read 0x08000000 0x{FLAG_ABS_OFFSET:x} 0x800; \ + if itest.b *0x08000000 == 0x{a:02x}; then \ + if itest.b *0x08000001 == 0x{l:02x}; then \ + if itest.b *0x08000002 == 0x{a2:02x}; then \ + if itest.b *0x08000003 == 0x{n:02x}; then run alkboot; fi; fi; fi; fi", + a = FLAG_MAGIC[0], + l = FLAG_MAGIC[1], + a2 = FLAG_MAGIC[2], + n = FLAG_MAGIC[3], + ) +} + +/// alkboot mounts the nvdata UBIFS and boots alkane from `alkane/`. +fn alkboot_value(volume: &str) -> String { + format!( + "setenv bootargs ${{alkbootargs}}; ubi part nvdata; ubifsmount ubi0:{volume}; \ + ubifsload ${{krnaddr}} {ALKANE_DIR}/vmlinux.bin; \ + ubifsload ${{fdtaddr}} {ALKANE_DIR}/devicetree.dtb; \ + ubifsload ${{rdaddr}} {ALKANE_DIR}/uramdisk.image.gz; \ + booti ${{krnaddr}} ${{rdaddr}} ${{fdtaddr}}" + ) +} + +/// Install the flag-based boot env (preserving all existing stock vars). Leaves +/// bootcmd = "run checkalk; run storeboot". +fn install_boot_env(sh: &mut dyn Shell, volume: &str) -> Result<(), StockError> { + let blob = read_env(sh)?; + let mut vars = parse_env(&blob); + set_var(&mut vars, "krnaddr", KRNADDR); + set_var(&mut vars, "fdtaddr", FDTADDR); + set_var(&mut vars, "rdaddr", RDADDR); + set_var(&mut vars, "alkbootargs", ALK_BOOTARGS); + set_var(&mut vars, "alkboot", &alkboot_value(volume)); + set_var(&mut vars, "checkalk", &checkalk_value()); + set_var(&mut vars, "bootcmd", "run checkalk; run storeboot"); + let new_blob = build_env(&vars)?; + write_env(sh, &new_blob) +} + +fn reboot_stock(sh: &mut dyn Shell) { + let _ = sh.exec("sync; reboot"); +} + +fn reboot_alkane(sh: &mut dyn Shell) { + // plain `reboot` no-ops on the minimal init; `reboot -f` triggers PSCI reset. + let _ = sh.exec("sync; reboot -f"); +} + +// --------------------------------------------------------------------------- +// Public API (dispatched from stock.rs for board == a113d). +// --------------------------------------------------------------------------- + +/// Install alkane onto an A113D running genuine stock, network-only, over the +/// DSH root-on-stock primitive. Stages the OS files into the nvdata UBI volume, +/// installs the flag-based boot env, and sets flag=alkane; the next boot runs +/// alkane. Zero raw writes outside the flag block in `misc`. +pub fn install_from_stock( + host: &str, + kernel_image: &[u8], + dtb: &[u8], + uramdisk: &[u8], + password: Option<&str>, +) -> Result<(), StockError> { + let mut sh = StockShell { + host: host.to_owned(), + password: password.map(|s| s.to_owned()), + }; + + // Guard: this board must be A113D stock (has a 'misc' MTD and a mounted + // nvdata UBI). If not, defer to the compiled-in method. + let proc_mtd = sh.exec("cat /proc/mtd 2>/dev/null").unwrap_or_default(); + if !proc_mtd.contains("\"nvdata\"") || !proc_mtd.contains("\"misc\"") { + return Err(StockError::NotApplicable); + } + + let misc = find_mtd(&mut sh, "misc")?; + let (mount, volume) = discover_nvdata_volume(&mut sh)?; + + // Stage the three files into /alkane/ and read-back verify. + let dir = format!("{mount}/{ALKANE_DIR}"); + sh.exec(&format!("mkdir -p {dir}"))?; + // rootfs -> dtb -> kernel (kernel lands last). + stage_file(&mut sh, uramdisk, &format!("{dir}/uramdisk.image.gz"))?; + stage_file(&mut sh, dtb, &format!("{dir}/devicetree.dtb"))?; + stage_file(&mut sh, kernel_image, &format!("{dir}/vmlinux.bin"))?; + sh.exec("sync")?; + + // Install the flag-based boot env (read-back verified before reboot). + install_boot_env(&mut sh, &volume)?; + + // Set flag=alkane, then reboot into alkane. + set_flag_alkane(&mut sh, &misc)?; + reboot_stock(&mut sh); + Ok(()) +} + +/// Stage one file to a UBIFS path and prove its read-back md5 before continuing. +fn stage_file(sh: &mut dyn Shell, data: &[u8], dest: &str) -> Result<(), StockError> { + let tmp = "/tmp/.alkstage"; + sh.put(data, tmp)?; + let out = sh.exec_long(&format!( + "cp -f {tmp} {dest} && sync; echo RB=$(md5sum {dest} | cut -d' ' -f1); rm -f {tmp}" + ))?; + let want = md5_hex(data); + let got = out + .split("RB=") + .nth(1) + .map(|s| s.trim().to_owned()) + .unwrap_or_default(); + if got != want { + return Err(StockError::Method(format!( + "staged {dest} md5 mismatch: want {want}, got {got}" + ))); + } + Ok(()) +} + +/// Restore an A113D running alkane back to genuine stock, network-only, in-band +/// from the running alkane OS: erase the flag block (flag=stock) and reboot. +/// Stock boots via `storeboot` from the untouched `boot` MTD; the alkane payload +/// and env are left in place, so a re-install is just re-writing the flag. +pub fn restore_to_stock(host: &str, password: Option<&str>) -> Result<(), StockError> { + let mut sh = AlkaneShell::connect(host, password)?; + + // Guard: must be the alkane a113d image (exposes 'misc' and 'nvdata' MTDs, + // mainline 6.18.48). If 'misc' is absent this is not applicable. + let proc_mtd = sh.exec("cat /proc/mtd 2>/dev/null").unwrap_or_default(); + if !proc_mtd.contains("\"misc\"") { + return Err(StockError::NotApplicable); + } + let misc = find_mtd(&mut sh, "misc")?; + clear_flag(&mut sh, &misc)?; + reboot_alkane(&mut sh); + Ok(()) +} + +/// The on-board stock backup is structural on this board: `storeboot` always +/// boots genuine stock from the `boot` MTD (mtd4), which this install never +/// writes. So a complete backup is present whenever the board is an A113D. +pub fn onboard_backup_present(host: &str, password: Option<&str>) -> Result { + // Best-effort confirm over alkane that the flag chain is in place; if we + // cannot reach alkane, report not-applicable so the caller falls through. + let mut sh = AlkaneShell::connect(host, password)?; + let proc_mtd = sh.exec("cat /proc/mtd 2>/dev/null").unwrap_or_default(); + if proc_mtd.contains("\"misc\"") { + Ok(true) + } else { + Err(StockError::NotApplicable) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn env_roundtrips_with_crc() { + let vars = vec![ + ("bootcmd".to_owned(), "run checkalk; run storeboot".to_owned()), + ("bootdelay".to_owned(), "1".to_owned()), + ("checkalk".to_owned(), checkalk_value()), + ]; + let blob = build_env(&vars).unwrap(); + assert_eq!(blob.len(), ENV_SIZE); + let stored = u32::from_le_bytes([blob[0], blob[1], blob[2], blob[3]]); + assert_eq!(crc32(&blob[4..]), stored); + let parsed = parse_env(&blob); + assert_eq!(parsed.iter().find(|(k, _)| k == "bootcmd").unwrap().1, + "run checkalk; run storeboot"); + assert!(parsed.iter().any(|(k, _)| k == "checkalk")); + } + + #[test] + fn b64_roundtrip() { + for n in [0usize, 1, 2, 3, 64, 2048, 65536] { + let data: Vec = (0..n).map(|i| (i * 7 + 3) as u8).collect(); + let enc = b64_encode(&data); + let dec = b64_decode(&enc).unwrap(); + assert_eq!(dec, data, "n={n}"); + } + // wrapped base64 decodes the same + let data: Vec = (0..100).map(|i| i as u8).collect(); + let mut wrapped = b64_encode(&data); + wrapped.insert(20, '\n'); + wrapped.insert(50, '\n'); + assert_eq!(b64_decode(&wrapped).unwrap(), data); + } + + #[test] + fn checkalk_is_raw_and_byte_tested() { + let c = checkalk_value(); + assert!(c.starts_with("nand read 0x08000000")); + assert!(c.contains("itest.b *0x08000000 == 0x41")); + assert!(!c.contains("ubi")); // the stock path must never touch UBI + assert!(c.contains("run alkboot")); + } + + #[test] + fn alkboot_loads_from_alkane_dir() { + let a = alkboot_value("nvdata_log"); + assert!(a.contains("ubifsmount ubi0:nvdata_log")); + assert!(a.contains("alkane/vmlinux.bin")); + assert!(a.contains("booti ${krnaddr} ${rdaddr} ${fdtaddr}")); + } +} diff --git a/crates/alkane-flash/src/lib.rs b/crates/alkane-flash/src/lib.rs index 399618b5..a05d4760 100644 --- a/crates/alkane-flash/src/lib.rs +++ b/crates/alkane-flash/src/lib.rs @@ -11,12 +11,15 @@ // choices for this crate rather than defects. #![allow(clippy::type_complexity, clippy::too_many_arguments)] +pub mod aml_ubi; pub mod boards; pub mod install; pub mod md5; pub mod preflight; pub mod stock; pub mod stock_firmware; +pub mod uimage; +pub mod zynq_nand; // Network-only stock-crossing method bodies compiled into the toolkit; the // public interface lives in `stock`. See stock_method.rs. This module is // maintained as a self-contained unit; the style lints below are allowed here so diff --git a/crates/alkane-flash/src/stock.rs b/crates/alkane-flash/src/stock.rs index faf0a731..dcaa528d 100644 --- a/crates/alkane-flash/src/stock.rs +++ b/crates/alkane-flash/src/stock.rs @@ -34,6 +34,8 @@ pub enum StockError { Method(String), #[error("io: {0}")] Io(String), + #[error("not applicable to this board; use the compiled-in method")] + NotApplicable, } /// The genuine Bitmain stock kernel and rootfs to write back when restoring to @@ -46,6 +48,10 @@ pub enum StockError { pub struct RestoreImages<'a> { pub kernel: &'a [u8], pub rootfs: &'a [u8], + /// The genuine per-board device tree from the vendor package, when present + /// (SD recovery images ship one; OTA packages omit it). When `None`, the + /// zynq readable path takes the stock dtb from the on-board backup. + pub dtb: Option<&'a [u8]>, } /// Options for updating a board that already runs alkane, in place. @@ -215,12 +221,16 @@ pub fn method() -> &'static dyn StockMethod { } /// Report, over the network only, whether the board holds a complete on-board -/// stock backup that can be restored without a vendor firmware file. +/// stock backup that can be restored without a vendor firmware file. Zynq uses +/// the readable boot-slot path; other boards use the compiled-in method. pub fn onboard_stock_backup_present( host: &str, password: Option<&str>, ) -> Result { - method().onboard_stock_backup_present(host, password) + match crate::zynq_nand::onboard_backup_present(host, password) { + Err(StockError::NotApplicable) => method().onboard_stock_backup_present(host, password), + other => other, + } } /// Return an alkane board to genuine stock (network-only) using its on-board @@ -231,7 +241,12 @@ pub fn restore_from_onboard_backup( password: Option<&str>, timeout: std::time::Duration, ) -> Result<(), StockError> { - method().restore_from_onboard_backup(host, password, timeout) + match crate::zynq_nand::restore_from_onboard(host, password) { + Err(StockError::NotApplicable) => { + method().restore_from_onboard_backup(host, password, timeout) + } + other => other, + } } /// Install alkane onto a board on stock (network-only), via the compiled-in method. @@ -241,6 +256,38 @@ pub fn install_from_stock( afw: &VerifiedAfw, password: Option<&str>, ) -> Result<(), StockError> { + // Zynq-7010 uses the readable NAND path (uImage-wrap + flash_erase/nandwrite + // over the DSH root primitive, with an on-board stock backup carved first); + // other boards use the compiled-in method. + if afw.manifest.board == crate::boards::zynq::BOARD { + let img = |role: &str| { + afw.image(role) + .map(|(_, data)| data) + .ok_or_else(|| StockError::Method(format!("afw missing {role} image"))) + }; + return crate::zynq_nand::install_from_stock( + host, + img("kernel")?, + img("dtb")?, + img("rootfs")?, + password, + ); + } + // A113D (Amlogic AXG) uses the readable UBI-stage + flag-based boot chain. + if afw.manifest.board == crate::aml_ubi::BOARD { + let img = |role: &str| { + afw.image(role) + .map(|(_, data)| data) + .ok_or_else(|| StockError::Method(format!("afw missing {role} image"))) + }; + return crate::aml_ubi::install_from_stock( + host, + img("kernel")?, + img("dtb")?, + img("rootfs")?, + password, + ); + } method().install_from_stock(host, afw_path, afw, password) } @@ -251,7 +298,30 @@ pub fn restore_to_stock( images: &RestoreImages, password: Option<&str>, ) -> Result<(), StockError> { - method().restore_to_stock(host, images, password) + match crate::zynq_nand::restore_to_stock( + host, + images.kernel, + images.rootfs, + images.dtb, + password, + ) { + Err(StockError::NotApplicable) => { + // A113D restore is a one-byte flag flip in-band from alkane; it needs + // no stock images. Try it, then fall through to the compiled-in method. + match crate::aml_ubi::restore_to_stock(host, password) { + Err(StockError::NotApplicable) => method().restore_to_stock(host, images, password), + other => other, + } + } + other => other, + } +} + +/// Restore an alkane A113D to stock with no stock firmware file: a one-byte flag +/// flip in-band from the running alkane OS (network-only). Returns +/// `NotApplicable` if the board is not an alkane A113D. +pub fn restore_aml_flag(host: &str, password: Option<&str>) -> Result<(), StockError> { + crate::aml_ubi::restore_to_stock(host, password) } /// Run `cmd` as root on a board running stock (network-only), via the diff --git a/crates/alkane-flash/src/stock_method.rs b/crates/alkane-flash/src/stock_method.rs index 5d55ed95..ac14a2d1 100644 --- a/crates/alkane-flash/src/stock_method.rs +++ b/crates/alkane-flash/src/stock_method.rs @@ -715,6 +715,10 @@ fn text(data: &[u8]) -> String { // ---------------------------------------------------------------- SSH fn ssh_command(host: &str, password: Option<&str>, remote: &str) -> Command { + ssh_command_as(host, "root", password, remote) +} + +fn ssh_command_as(host: &str, user: &str, password: Option<&str>, remote: &str) -> Command { let mut command; if let Some(password) = password { command = Command::new("sshpass"); @@ -741,11 +745,39 @@ fn ssh_command(host: &str, password: Option<&str>, remote: &str) -> Command { if password.is_none() { command.args(["-o", "BatchMode=yes"]); } - command.arg(format!("root@{host}")); + command.arg(format!("{user}@{host}")); command.arg(remote); command } +fn ssh_exec_as( + host: &str, + user: &str, + password: Option<&str>, + remote: &str, + timeout: Duration, +) -> Result { + let result = run_command(ssh_command_as(host, user, password, remote), timeout, None)?; + if result.timed_out { + return Err(StockError::Network("target did not respond".into())); + } + Ok(result) +} + +/// True when the SSH failure is the login being refused rather than the target +/// being unreachable or a command failing after it ran. +fn is_login_refused(result: &CmdResult) -> bool { + if result.timed_out { + return false; + } + let lower = text(&result.stderr).to_lowercase(); + lower.contains("permission denied") + || lower.contains("authentication failed") + || lower.contains("no supported authentication") + || lower.contains("too many authentication failures") + || lower.contains("root login rejected") +} + fn classify_ssh(result: &CmdResult) -> StockError { let lower = text(&result.stderr).to_lowercase(); let auth = lower.contains("permission denied") @@ -2776,19 +2808,392 @@ fn root_put_via_web( Err(StockError::Method("command channel did not respond".into())) } +// ---------------------------------------------------------------- stock daemon channel +// +// On this board class the stock image has no privileged login at all: root's +// shell is disabled, the SSH daemon refuses root logins, and the only account +// that logs in is unprivileged with no sudo. The vendor keeps every privileged +// operation (firmware updates, reboots, config writes) behind a root-owned +// helper that its own web layer talks to over loopback; that helper accepts a +// command line from a local client and runs it through a shell as root. +// +// This route therefore needs no exploit of its own: it logs in with the stock +// account, stages a short script under /tmp, hands the script to the vendor +// helper through the helper's own installed client, and reads the result back. +// Only /tmp is written; the stock system, the boot chain and the NAND layout +// are never touched. The alternative route (the web upload) is left in place +// for boards where it does work. + +const STOCK_UNPRIV_USER_DEFAULT: &str = "miner"; +const STOCK_UNPRIV_PASSWORD_DEFAULT: &str = "miner"; +const STOCK_DAEMON_CLIENT: &str = "/usr/sbin/daemonc"; +const STOCK_CHANNEL_READY: &str = "__ALKANE_STOCK_CHANNEL_READY__"; +const STOCK_CHANNEL_ABSENT: &str = "__ALKANE_STOCK_CHANNEL_ABSENT__"; +const STOCK_RUN_MARK: &str = "@@AKRUN"; + +/// The stock account this board class allows over SSH. Overridable so an +/// operator whose board was provisioned differently does not need a new build. +fn stock_unpriv_user() -> String { + env::var("ALKANE_STOCK_LOGIN_USER") + .ok() + .map(|value| value.trim().to_string()) + .filter(|value| is_plain_user(value)) + .unwrap_or_else(|| STOCK_UNPRIV_USER_DEFAULT.to_string()) +} + +fn is_plain_user(value: &str) -> bool { + !value.is_empty() + && value.len() <= 32 + && value + .chars() + .all(|c| c.is_ascii_alphanumeric() || matches!(c, '_' | '-' | '.')) +} + +/// Passwords to try for the unprivileged stock account, in order: the one the +/// caller supplied, then any from the environment, then the documented vendor +/// default for that account on this board class. +fn stock_unpriv_passwords(password: Option<&str>) -> Vec { + let mut candidates = Vec::new(); + let mut push = |value: &str| { + if !value.is_empty() && !candidates.iter().any(|known| known == value) { + candidates.push(value.to_string()); + } + }; + if let Some(password) = password { + push(password); + } + if let Ok(value) = env::var("ALKANE_STOCK_LOGIN_PASSWORD") { + push(&value); + } + if let Some(value) = resolve_password(None) { + push(&value); + } + push(STOCK_UNPRIV_PASSWORD_DEFAULT); + candidates +} + +enum ChannelProbe { + Ready { uid: String }, + Absent, + Denied, + Failed(StockError), +} + +/// Stage `script` at `remote_script` and report whether the vendor helper is +/// present on this board and the login was accepted. +fn probe_stock_channel( + host: &str, + user: &str, + password: &str, + script: &str, + remote_script: &str, +) -> Result { + let remote = format!( + "if [ ! -x {client} ]; then echo {absent}; exit 9; fi; \ + cat > {path} && chmod 0644 {path} || exit 8; \ + id -u; echo {ready}", + client = shell_quote(STOCK_DAEMON_CLIENT), + absent = STOCK_CHANNEL_ABSENT, + path = shell_quote(remote_script), + ready = STOCK_CHANNEL_READY, + ); + let result = run_command( + ssh_command_as(host, user, Some(password), &remote), + Duration::from_secs(60), + Some(script.as_bytes().to_vec()), + )?; + let stdout = text(&result.stdout); + if result.ok() && stdout.contains(STOCK_CHANNEL_READY) { + let uid = stdout + .lines() + .find(|line| line.trim().parse::().is_ok()) + .map(|line| line.trim().to_string()) + .ok_or_else(|| StockError::Method("command channel did not respond".into()))?; + return Ok(ChannelProbe::Ready { uid }); + } + if stdout.contains(STOCK_CHANNEL_ABSENT) { + return Ok(ChannelProbe::Absent); + } + if is_login_refused(&result) { + return Ok(ChannelProbe::Denied); + } + if result.timed_out { + return Err(StockError::Network("target did not respond".into())); + } + Ok(ChannelProbe::Failed(command_failure(&result))) +} + +/// Run `script` as root through the stock daemon channel and return its +/// combined output. `Ok(NotApplicable)` means this is not a board with that +/// channel, so the caller should use another route. +fn stock_channel_run( + host: &str, + password: Option<&str>, + script: &str, +) -> Result { + let user = stock_unpriv_user(); + let token = random_token(); + let remote_script = format!("/tmp/.ak-cmd-{token}"); + let remote_out = format!("/tmp/.ak-out-{token}"); + let remote_missing = format!("/tmp/.ak-none-{token}"); + let mut denied = false; + + for candidate in stock_unpriv_passwords(password) { + match probe_stock_channel(host, &user, &candidate, script, &remote_script)? { + ChannelProbe::Ready { uid } => { + return stock_channel_execute( + host, + &user, + &candidate, + &uid, + &token, + &remote_script, + &remote_out, + &remote_missing, + ) + } + ChannelProbe::Absent => return Err(StockError::NotApplicable), + ChannelProbe::Denied => { + denied = true; + continue; + } + ChannelProbe::Failed(error) => return Err(error), + } + } + + if denied { + Err(StockError::Auth("target rejected the credential".into())) + } else { + Err(StockError::NotApplicable) + } +} + +/// Hand the staged script to the vendor helper. The helper is given a path +/// that does not exist first, so the vendor's own handler runs and exits +/// before anything of ours does; the script then runs as root, its output is +/// written to a private file that is handed back to the stock account, and +/// every staged file is removed again by the root side. +fn stock_channel_execute( + host: &str, + user: &str, + password: &str, + uid: &str, + token: &str, + remote_script: &str, + remote_out: &str, + remote_missing: &str, +) -> Result { + let mark = format!("{STOCK_RUN_MARK}{token}="); + let inject = format!( + "{missing}; sh {script} > {out} 2>&1; \ + echo \"{mark}$?\" >> {out}; \ + chmod 0644 {out} && chown {uid} {out}; \ + rm -f {script}", + missing = shell_quote(remote_missing), + script = shell_quote(remote_script), + out = shell_quote(remote_out), + mark = mark, + uid = shell_quote(uid), + ); + let remote = format!( + "{} {}", + shell_quote(STOCK_DAEMON_CLIENT), + shell_quote(&inject) + ); + let run = ssh_exec_as( + host, + user, + Some(password), + &remote, + Duration::from_secs(3600), + ); + + // Collect whatever the root side left, even when the call above failed or + // timed out, so the temporary files are removed either way. + let collect = format!( + "cat {out}; rm -f {out} {script}", + out = shell_quote(remote_out), + script = shell_quote(remote_script), + ); + let read = ssh_exec_as( + host, + user, + Some(password), + &collect, + Duration::from_secs(120), + ); + if let Ok(read) = &read { + if let Some((body, status)) = split_run_result(&text(&read.stdout), &mark) { + if status == 0 { + return Ok(body); + } + return Err(command_exit_error(status, body)); + } + } + if let Err(error) = run { + return Err(error); + } + if let Err(error) = read { + return Err(error); + } + Err(StockError::Method("command channel did not respond".into())) +} + +/// Split the collected file into the command output and the exit status the +/// root side appended after it. The status marker carries this call's token so +/// a command cannot forge it, and it is appended straight after the command's +/// last byte, so a command whose output has no trailing newline still parses. +fn split_run_result(output: &str, mark: &str) -> Option<(String, i32)> { + let index = output.rfind(mark)?; + let body = output[..index].to_string(); + let rest = &output[index + mark.len()..]; + let digits: String = rest.chars().take_while(|c| c.is_ascii_digit()).collect(); + let status = digits.parse::().ok()?; + Some((body, status)) +} + +fn stock_root_exec(host: &str, password: Option<&str>, cmd: &str) -> Result { + if cmd.trim().is_empty() { + return Err(StockError::Method("empty command".into())); + } + let script = format!("#!/bin/sh\n{cmd}\n"); + stock_channel_run(host, password, &script) +} + +fn stock_root_put( + host: &str, + password: Option<&str>, + data: &[u8], + remote_path: &str, +) -> Result<(), StockError> { + let user = stock_unpriv_user(); + let token = random_token(); + let staged = format!("/tmp/.ak-put-{token}"); + let scratch = format!("{remote_path}.ak-tmp-{token}"); + + let password = stage_stock_payload(host, &user, password, data, &staged)?; + + if let Err(error) = verify_stock_payload(host, &user, &password, data.len(), &staged) { + let _ = ssh_exec_as( + host, + &user, + Some(&password), + &format!("rm -f {}", shell_quote(&staged)), + Duration::from_secs(30), + ); + return Err(error); + } + + let script = format!( + "#!/bin/sh\n\ + src={src}\n\ + dst={dst}\n\ + tmp={tmp}\n\ + dir={dir}\n\ + mkdir -p \"$dir\" || {{ echo \"could not create the remote directory\"; exit 11; }}\n\ + cp \"$src\" \"$tmp\" || {{ rm -f \"$tmp\"; echo \"could not copy the staged file\"; exit 12; }}\n\ + chmod 0644 \"$tmp\" || {{ rm -f \"$tmp\"; echo \"could not set the file mode\"; exit 13; }}\n\ + mv -f \"$tmp\" \"$dst\" || {{ rm -f \"$tmp\"; echo \"could not move the file into place\"; exit 14; }}\n\ + n=$(wc -c < \"$dst\" 2>/dev/null)\n\ + [ \"$n\" = {size} ] || {{ echo \"the written file is $n bytes, not {size}\"; exit 15; }}\n\ + rm -f \"$src\"\n\ + exit 0\n", + src = shell_quote(&staged), + dst = shell_quote(remote_path), + tmp = shell_quote(&scratch), + dir = shell_quote(remote_parent(remote_path)), + size = shell_quote(&data.len().to_string()), + ); + + let result = stock_channel_run(host, Some(&password), &script); + if result.is_err() { + // The staged copy belongs to the stock account, so it can always be + // removed even when the root side never ran. + let _ = ssh_exec_as( + host, + &user, + Some(&password), + &format!("rm -f {} {}", shell_quote(&staged), shell_quote(&scratch)), + Duration::from_secs(30), + ); + } + result.map(|_| ()) +} + +/// Stream the payload to a temporary file owned by the stock account and +/// return the password that account accepted. +fn stage_stock_payload( + host: &str, + user: &str, + password: Option<&str>, + data: &[u8], + staged: &str, +) -> Result { + let dir = TempDir::new("stockput")?; + let payload = dir.join("payload"); + write_private(&payload, data)?; + + for candidate in stock_unpriv_passwords(password) { + let remote = format!( + "cat > {path} && chmod 0644 {path}", + path = shell_quote(staged) + ); + let input = fs::File::open(&payload) + .map_err(|e| StockError::Io(format!("could not read the payload: {e}")))?; + let result = run_command_stream( + ssh_command_as(host, user, Some(&candidate), &remote), + Duration::from_secs(1800), + input, + )?; + if result.ok() { + return Ok(candidate); + } + if result.timed_out { + return Err(StockError::Network("target transfer timed out".into())); + } + if is_login_refused(&result) { + continue; + } + return Err(command_failure(&result)); + } + Err(StockError::Auth("target rejected the credential".into())) +} + +fn verify_stock_payload( + host: &str, + user: &str, + password: &str, + size: usize, + staged: &str, +) -> Result<(), StockError> { + let remote = format!("wc -c < {path}", path = shell_quote(staged)); + let result = ssh_exec_as(host, user, Some(password), &remote, Duration::from_secs(60))?; + if !result.ok() { + return Err(command_failure(&result)); + } + let got = text(&result.stdout).trim().parse::().unwrap_or(0); + if got != size as u64 { + return Err(StockError::Method("target transfer was short".into())); + } + Ok(()) +} + fn root_exec_impl(host: &str, password: Option<&str>, cmd: &str) -> Result { validate_host(host)?; let resolved = resolve_password(password); let ssh_password = resolved.as_deref(); match ssh_root_ready(host, ssh_password) { Ok(()) => root_exec_via_ssh(host, ssh_password, cmd), - Err(ssh_error) => { - if is_stock_http(host) { - root_exec_via_web(host, password, cmd) - } else { - Err(ssh_error) + Err(ssh_error) => match stock_root_exec(host, password, cmd) { + Err(StockError::NotApplicable) | Err(StockError::Auth(_)) => { + if is_stock_http(host) { + root_exec_via_web(host, password, cmd) + } else { + Err(ssh_error) + } } - } + other => other, + }, } } @@ -2804,13 +3209,16 @@ fn root_put_impl( let ssh_password = resolved.as_deref(); match ssh_root_ready(host, ssh_password) { Ok(()) => root_put_via_ssh(host, ssh_password, data, remote_path), - Err(ssh_error) => { - if is_stock_http(host) { - root_put_via_web(host, password, data, remote_path) - } else { - Err(ssh_error) + Err(ssh_error) => match stock_root_put(host, password, data, remote_path) { + Err(StockError::NotApplicable) | Err(StockError::Auth(_)) => { + if is_stock_http(host) { + root_put_via_web(host, password, data, remote_path) + } else { + Err(ssh_error) + } } - } + other => other, + }, } } @@ -3391,6 +3799,47 @@ mod tests { } } + #[test] + fn run_result_splits_output_from_status() { + let marker = format!("{STOCK_RUN_MARK}abc123="); + assert_eq!( + split_run_result(&format!("uid=0(root)\n{marker}0\n"), &marker), + Some(("uid=0(root)\n".to_string(), 0)) + ); + // A command whose output does not end in a newline still parses. + assert_eq!( + split_run_result(&format!("no-newline{marker}3"), &marker), + Some(("no-newline".to_string(), 3)) + ); + // The last marker wins; earlier ones are ordinary output. + assert_eq!( + split_run_result(&format!("{marker}9\nreal{marker}0\n"), &marker), + Some((format!("{marker}9\nreal"), 0)) + ); + assert_eq!(split_run_result("nothing here\n", &marker), None); + assert_eq!(split_run_result(&format!("body{marker}"), &marker), None); + // A marker from another call is not accepted. + let other = format!("{STOCK_RUN_MARK}other="); + assert_eq!(split_run_result(&format!("out{other}0\n"), &marker), None); + } + + #[test] + fn stock_login_defaults_included_and_deduplicated() { + let candidates = stock_unpriv_passwords(Some("supplied")); + assert_eq!(candidates.first().map(String::as_str), Some("supplied")); + assert!(candidates + .iter() + .any(|value| value == STOCK_UNPRIV_PASSWORD_DEFAULT)); + let mut seen = candidates.clone(); + seen.sort(); + seen.dedup(); + assert_eq!(seen.len(), candidates.len()); + assert!(is_plain_user(STOCK_UNPRIV_USER_DEFAULT)); + assert!(!is_plain_user("bad user")); + assert!(!is_plain_user("bad;user")); + assert!(!is_plain_user("")); + } + #[test] fn remote_paths_are_split_and_validated() { assert_eq!(remote_parent("/tmp/a/b"), "/tmp/a"); diff --git a/crates/alkane-flash/src/uimage.rs b/crates/alkane-flash/src/uimage.rs new file mode 100644 index 00000000..63216f00 --- /dev/null +++ b/crates/alkane-flash/src/uimage.rs @@ -0,0 +1,152 @@ +// SPDX-License-Identifier: MIT +//! Legacy U-Boot image (`uImage`) header builder. +//! +//! The Zynq (Antminer S17/S19-class) stock U-Boot boots a legacy uImage: a +//! 64-byte big-endian header (magic `0x27051956`) in front of the payload. We +//! wrap the kernel (a raw ARM `zImage`) and the ramdisk (a gzipped cpio) in this +//! header so the board's own U-Boot boots them unchanged. The device tree is +//! written raw (no header). +//! +//! The header parameters below were read directly off a genuine stock S17 NAND +//! (kernel: type Kernel, uncompressed, load/entry `0x8000`; ramdisk: type +//! RAMDisk, gzip, load/entry `0`), so the images we write match exactly what the +//! stock boot chain already boots. + +/// Legacy uImage magic (big-endian). +pub const IH_MAGIC: u32 = 0x2705_1956; +/// Header length in bytes. +pub const HEADER_LEN: usize = 64; + +// ih_os +const IH_OS_LINUX: u8 = 5; +// ih_arch +const IH_ARCH_ARM: u8 = 2; +// ih_type +const IH_TYPE_KERNEL: u8 = 2; +const IH_TYPE_RAMDISK: u8 = 3; +// ih_comp +const IH_COMP_NONE: u8 = 0; +const IH_COMP_GZIP: u8 = 1; + +/// A CRC-32 (IEEE 802.3, the variant U-Boot uses) over `data`. +pub fn crc32(data: &[u8]) -> u32 { + let mut crc: u32 = 0xFFFF_FFFF; + for &byte in data { + crc ^= byte as u32; + for _ in 0..8 { + let mask = (crc & 1).wrapping_neg(); + crc = (crc >> 1) ^ (0xEDB8_8320 & mask); + } + } + !crc +} + +/// Which kind of uImage to build. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Kind { + /// ARM Linux kernel, uncompressed, load/entry 0x8000 (what the stock S17 + /// kernel uImage uses). + Kernel, + /// ARM Linux ramdisk, gzip, load/entry 0 (what the stock S17 ramdisk uImage + /// uses). + Ramdisk, +} + +impl Kind { + fn ih_type(self) -> u8 { + match self { + Kind::Kernel => IH_TYPE_KERNEL, + Kind::Ramdisk => IH_TYPE_RAMDISK, + } + } + fn ih_comp(self) -> u8 { + match self { + Kind::Kernel => IH_COMP_NONE, + Kind::Ramdisk => IH_COMP_GZIP, + } + } + fn load_entry(self) -> u32 { + match self { + Kind::Kernel => 0x8000, + Kind::Ramdisk => 0, + } + } +} + +/// Wrap `payload` in a legacy uImage header of the given `kind` and return the +/// full image (header followed by payload). `time` is the header timestamp; pass +/// a fixed value for a reproducible image. `name` is truncated to 31 bytes. +pub fn wrap(kind: Kind, payload: &[u8], time: u32, name: &str) -> Vec { + let mut hdr = [0u8; HEADER_LEN]; + hdr[0..4].copy_from_slice(&IH_MAGIC.to_be_bytes()); + // hdr[4..8] header CRC: filled in last, over the header with this field zero. + hdr[8..12].copy_from_slice(&time.to_be_bytes()); + hdr[12..16].copy_from_slice(&(payload.len() as u32).to_be_bytes()); + hdr[16..20].copy_from_slice(&kind.load_entry().to_be_bytes()); + hdr[20..24].copy_from_slice(&kind.load_entry().to_be_bytes()); + hdr[24..28].copy_from_slice(&crc32(payload).to_be_bytes()); + hdr[28] = IH_OS_LINUX; + hdr[29] = IH_ARCH_ARM; + hdr[30] = kind.ih_type(); + hdr[31] = kind.ih_comp(); + let name_bytes = name.as_bytes(); + let n = name_bytes.len().min(31); + hdr[32..32 + n].copy_from_slice(&name_bytes[..n]); + // Header CRC over the 64-byte header with the hcrc field (4..8) zeroed. + let hcrc = crc32(&hdr); + hdr[4..8].copy_from_slice(&hcrc.to_be_bytes()); + + let mut out = Vec::with_capacity(HEADER_LEN + payload.len()); + out.extend_from_slice(&hdr); + out.extend_from_slice(payload); + out +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn crc32_known_vector() { + // CRC-32/ISO-HDLC of "123456789" is 0xCBF43926. + assert_eq!(crc32(b"123456789"), 0xCBF4_3926); + assert_eq!(crc32(b""), 0); + } + + #[test] + fn header_shape_and_fields() { + let img = wrap(Kind::Kernel, b"payload-bytes", 0, "alkane"); + assert_eq!(img.len(), HEADER_LEN + 13); + assert_eq!(&img[0..4], &IH_MAGIC.to_be_bytes()); + assert_eq!(u32::from_be_bytes([img[12], img[13], img[14], img[15]]), 13); + // kernel: load/entry 0x8000, type kernel, comp none + assert_eq!(&img[16..20], &0x8000u32.to_be_bytes()); + assert_eq!(&img[20..24], &0x8000u32.to_be_bytes()); + assert_eq!(img[28], IH_OS_LINUX); + assert_eq!(img[29], IH_ARCH_ARM); + assert_eq!(img[30], IH_TYPE_KERNEL); + assert_eq!(img[31], IH_COMP_NONE); + assert_eq!(&img[64..], b"payload-bytes"); + } + + #[test] + fn ramdisk_fields() { + let img = wrap(Kind::Ramdisk, b"rd", 0, "rd"); + assert_eq!(&img[16..20], &0u32.to_be_bytes()); + assert_eq!(img[30], IH_TYPE_RAMDISK); + assert_eq!(img[31], IH_COMP_GZIP); + } + + #[test] + fn header_crc_validates() { + let img = wrap(Kind::Kernel, b"abc", 0x1234, "n"); + let mut hdr = [0u8; HEADER_LEN]; + hdr.copy_from_slice(&img[..HEADER_LEN]); + let stored = u32::from_be_bytes([hdr[4], hdr[5], hdr[6], hdr[7]]); + hdr[4..8].copy_from_slice(&[0, 0, 0, 0]); + assert_eq!(crc32(&hdr), stored); + // data CRC over payload + let dcrc = u32::from_be_bytes([img[24], img[25], img[26], img[27]]); + assert_eq!(crc32(b"abc"), dcrc); + } +} diff --git a/crates/alkane-flash/src/zynq_nand.rs b/crates/alkane-flash/src/zynq_nand.rs new file mode 100644 index 00000000..999c22b7 --- /dev/null +++ b/crates/alkane-flash/src/zynq_nand.rs @@ -0,0 +1,769 @@ +// SPDX-License-Identifier: MIT +//! Readable Zynq-7010 NAND install / restore / on-board-backup, driven entirely +//! over the network through two small root shells: +//! +//! * a board on **stock** is reached with the DSH root-on-stock primitives +//! (`crate::stock::root_exec` / `root_put`): this is the only compartmentalised +//! piece, and it is used only to get a root shell; +//! * a board on **alkane** is reached with ordinary SSH (`crate::transport`). +//! +//! Everything else -- what to write, where, in what form, and the read-back +//! verification -- lives here in plain, auditable Rust. The NAND writes +//! themselves are the same `flash_erase` + `nandwrite` MTD operations on both +//! sides; only the way we obtain the root shell differs. +//! +//! Absolute NAND map (Micron MT29F2G08, 256 MiB, 128 KiB erase, 2 KiB page), +//! confirmed on a genuine stock S17 and mirrored by the alkane board DT: +//! ```text +//! 0x00000000 BOOT.bin (FSBL + bitstream + stock U-Boot + env) NEVER written +//! 0x01a00000 device tree (raw fdt) +//! 0x02000000 kernel (legacy uImage) +//! 0x02800000 rootfs (legacy uImage ramdisk) +//! 0x04800000 stock `configs` (UBI) exposed read-only on alkane +//! 0x05000000 alkane-cfg (persisted MAC) +//! 0x06000000 on-board genuine-stock backup (stock `ramfs-bak` region) +//! 0x08000000 stock `reserve1` / nvdata (UBI) left untouched +//! ``` +//! On a board running alkane the boot slots are exposed as the named partitions +//! `boot-dtb` / `boot-kernel` / `boot-rootfs` / `stock-backup` (see the board +//! DT); on stock they fall inside `mtd0` / `mtd1` / `ramfs-bak`. Because we map +//! an absolute offset to whichever MTD partition contains it, the same code +//! writes the same physical NAND on both sides. + +use crate::md5::md5_hex; +use crate::stock::StockError; +use crate::transport::{Remote, SshOptions, SshTransport}; +use crate::uimage::{self, Kind}; +use std::io::Write as _; +use std::path::Path; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::time::Duration; + +/// NAND erase-block size (128 KiB). +const ERASE: u64 = 0x20000; +/// NAND page size (2 KiB); `nandwrite -p` pads the final page with 0xFF. +const PAGE: u64 = 0x800; + +/// Absolute boot-slot offsets (see the module map). +const OFF_DTB: u64 = 0x1a00000; +const OFF_KERNEL: u64 = 0x2000000; +const OFF_ROOTFS: u64 = 0x2800000; +const OFF_STOCK_BACKUP: u64 = 0x6000000; +/// BOOT.bin occupies 0x0..0x1a00000 and is never written. +const BOOTBIN_PRESERVE: u64 = 0x1a00000; + +/// Slot ceilings (so a too-large image is refused before any erase). +const SLOT_DTB: u64 = 0x600000; +const SLOT_KERNEL: u64 = 0x800000; +const SLOT_ROOTFS: u64 = 0x2000000; +const SLOT_STOCK_BACKUP: u64 = 0x2000000; + +/// Where the backup data lives inside the 32 MiB stock-backup region: the first +/// erase block holds the manifest, the images follow, each erase-block aligned. +const BK_MANIFEST: u64 = OFF_STOCK_BACKUP; // 0x6000000 +const BK_MAGIC: &[u8; 8] = b"ALKSTKB1"; + +fn round_up(value: u64, to: u64) -> u64 { + value.div_ceil(to) * to +} + +// --------------------------------------------------------------------------- +// Root shells +// --------------------------------------------------------------------------- + +/// A root shell on the target board: run a `/bin/sh` command as root and stream +/// a byte payload to a file as root. Both sides implement this; the NAND code +/// below is written once against it. +trait Shell { + fn exec(&mut self, cmd: &str) -> Result; + fn put(&mut self, data: &[u8], remote_path: &str) -> Result<(), StockError>; + /// Longer-running command (large nandwrite / nanddump). + fn exec_long(&mut self, cmd: &str) -> Result; +} + +/// Stock board: root obtained through the compartmentalised DSH primitive. +struct StockShell { + host: String, + password: Option, +} + +impl Shell for StockShell { + fn exec(&mut self, cmd: &str) -> Result { + crate::stock::root_exec(&self.host, self.password.as_deref(), cmd) + } + fn exec_long(&mut self, cmd: &str) -> Result { + crate::stock::root_exec(&self.host, self.password.as_deref(), cmd) + } + fn put(&mut self, data: &[u8], remote_path: &str) -> Result<(), StockError> { + crate::stock::root_put(&self.host, self.password.as_deref(), data, remote_path) + } +} + +/// Alkane board: root over ordinary SSH. A throwaway known-hosts file is used +/// so a board whose SSH host key legitimately changed across an install still +/// connects (accept-new), which is the norm on the bench. +struct AlkaneShell { + transport: SshTransport, + _secret: TempFile, +} + +static TEMP_SEQ: AtomicU64 = AtomicU64::new(0); + +fn temp_path(tag: &str) -> std::path::PathBuf { + let n = TEMP_SEQ.fetch_add(1, Ordering::Relaxed); + std::env::temp_dir().join(format!("alkane-{}-{}-{}", std::process::id(), tag, n)) +} + +/// A 0600 temp file removed on drop. +struct TempFile(std::path::PathBuf); +impl TempFile { + fn with(contents: &[u8], tag: &str) -> Result { + let path = temp_path(tag); + write_private(&path, contents).map_err(|e| StockError::Io(e.to_string()))?; + Ok(TempFile(path)) + } +} +impl Drop for TempFile { + fn drop(&mut self) { + let _ = std::fs::remove_file(&self.0); + } +} + +#[cfg(unix)] +fn write_private(path: &Path, contents: &[u8]) -> std::io::Result<()> { + use std::os::unix::fs::OpenOptionsExt; + let mut f = std::fs::OpenOptions::new() + .create(true) + .truncate(true) + .write(true) + .mode(0o600) + .open(path)?; + f.write_all(contents)?; + f.flush() +} + +impl AlkaneShell { + fn connect(host: &str, password: Option<&str>) -> Result { + let secret = TempFile::with(password.unwrap_or("alkane").as_bytes(), "pw")?; + let known = temp_path("kh"); + let _ = std::fs::File::create(&known); // empty -> accept-new always accepts + let options = SshOptions { + host: host.to_owned(), + port: 22, + user: "root".to_owned(), + identity_file: None, + password_file: Some(secret.0.clone()), + known_hosts: Some(known), + root_method: crate::transport::RootMethod::Auto, + update_daemon_port: None, + }; + let transport = SshTransport::connect(options, true) + .map_err(|e| StockError::Network(e.to_string()))?; + Ok(AlkaneShell { + transport, + _secret: secret, + }) + } +} + +impl Shell for AlkaneShell { + fn exec(&mut self, cmd: &str) -> Result { + self.transport + .root_command(cmd, Duration::from_secs(120)) + .map(|o| String::from_utf8_lossy(&o).into_owned()) + .map_err(|e| StockError::Method(e.to_string())) + } + fn exec_long(&mut self, cmd: &str) -> Result { + self.transport + .root_command(cmd, Duration::from_secs(900)) + .map(|o| String::from_utf8_lossy(&o).into_owned()) + .map_err(|e| StockError::Method(e.to_string())) + } + fn put(&mut self, data: &[u8], remote_path: &str) -> Result<(), StockError> { + let tmp = TempFile::with(data, "put")?; + self.transport + .push(&tmp.0, remote_path, Duration::from_secs(900)) + .map_err(|e| StockError::Method(e.to_string())) + } +} + +// --------------------------------------------------------------------------- +// MTD table: map an absolute NAND offset to (device, relative offset) +// --------------------------------------------------------------------------- + +#[derive(Clone, Debug)] +struct Mtd { + dev: String, // e.g. "mtd2" + base: u64, // absolute NAND offset of the partition start + size: u64, + #[allow(dead_code)] + name: String, +} + +/// Read the MTD partition table. Each partition's absolute base comes from +/// `/sys/class/mtd//offset` when present (alkane, where partitions are not +/// contiguous), falling back to the cumulative sum of sizes in `/proc/mtd` +/// order (stock, where they are contiguous from 0). +fn read_mtd_table(sh: &mut dyn Shell) -> Result, StockError> { + // name + size from /proc/mtd (always present); offset from sysfs if present. + let proc = sh.exec("cat /proc/mtd")?; + let mut out = Vec::new(); + let mut cursor = 0u64; + for line in proc.lines() { + let line = line.trim(); + if !line.starts_with("mtd") { + continue; + } + // "mtd0: 02800000 00020000 \"name\"" + let (dev, rest) = match line.split_once(':') { + Some(v) => v, + None => continue, + }; + let mut it = rest.split_whitespace(); + let size = it + .next() + .and_then(|h| u64::from_str_radix(h, 16).ok()) + .ok_or_else(|| StockError::Method(format!("bad /proc/mtd line: {line}")))?; + let _erase = it.next(); + let name = line + .split('"') + .nth(1) + .unwrap_or("") + .to_owned(); + let base = match sysfs_offset(sh, dev) { + Some(off) => off, + None => cursor, + }; + cursor = cursor.max(base) + size; + out.push(Mtd { + dev: dev.to_owned(), + base, + size, + name, + }); + } + if out.is_empty() { + return Err(StockError::Method("no MTD partitions found".into())); + } + Ok(out) +} + +fn sysfs_offset(sh: &mut dyn Shell, dev: &str) -> Option { + let out = sh + .exec(&format!("cat /sys/class/mtd/{dev}/offset 2>/dev/null")) + .ok()?; + out.trim().parse::().ok() +} + +/// Find the partition that contains `abs` and holding at least `len` bytes from +/// there; return (device, relative offset). +fn locate<'a>( + table: &'a [Mtd], + abs: u64, + len: u64, +) -> Result<(&'a str, u64), StockError> { + for m in table { + if abs >= m.base && abs < m.base + m.size { + let rel = abs - m.base; + if rel + len > m.size { + return Err(StockError::Method(format!( + "write of {len} B at abs 0x{abs:x} overruns {} (rel 0x{rel:x}, size 0x{:x})", + m.dev, m.size + ))); + } + return Ok((&m.dev, rel)); + } + } + Err(StockError::Method(format!( + "no MTD partition exposes absolute offset 0x{abs:x} (is the boot region mapped?)" + ))) +} + +// --------------------------------------------------------------------------- +// NAND primitives +// --------------------------------------------------------------------------- + +/// MD5 of `data` padded with 0xFF up to the next page boundary -- what a +/// `nandwrite -p` of `data` leaves on flash and what `nanddump -l ` +/// reads back. +fn padded_md5(data: &[u8]) -> String { + let rounded = round_up(data.len() as u64, PAGE) as usize; + let mut buf = data.to_vec(); + buf.resize(rounded, 0xFF); + md5_hex(&buf) +} + +/// Write `data` to absolute NAND offset `abs`, staging it in `/tmp/alk`, erasing +/// the covering erase blocks, writing with `nandwrite -p`, and verifying the +/// read-back against the padded MD5. `abs` must be erase-block aligned. +fn write_abs( + sh: &mut dyn Shell, + table: &[Mtd], + abs: u64, + data: &[u8], + label: &str, +) -> Result<(), StockError> { + if abs < BOOTBIN_PRESERVE { + return Err(StockError::Method(format!( + "refusing to write {label} at 0x{abs:x}: inside preserved BOOT.bin" + ))); + } + if abs % ERASE != 0 { + return Err(StockError::Method(format!( + "{label} offset 0x{abs:x} is not erase-block aligned" + ))); + } + let (dev, rel) = locate(table, abs, data.len() as u64)?; + let dev = dev.to_owned(); + let blocks = round_up(data.len() as u64, ERASE) / ERASE; + let remote = format!("/tmp/alk/{label}.img"); + sh.exec("mkdir -p /tmp/alk")?; + sh.put(data, &remote)?; + // Confirm the staged payload arrived intact before we erase anything. + let put_md5 = first_token(&sh.exec(&format!("md5sum {remote}"))?); + if put_md5 != md5_hex(data) { + return Err(StockError::Method(format!( + "{label}: staged copy md5 {put_md5} != {} (transfer corrupted)", + md5_hex(data) + ))); + } + sh.exec_long(&format!( + "flash_erase /dev/{dev} 0x{rel:x} {blocks} >/dev/null 2>&1 && \ + nandwrite -p -s 0x{rel:x} /dev/{dev} {remote} >/dev/null 2>&1 && echo WROTE" + )) + .and_then(|o| { + if o.contains("WROTE") { + Ok(()) + } else { + Err(StockError::Method(format!("{label}: erase/write failed: {o}"))) + } + })?; + let readlen = round_up(data.len() as u64, PAGE); + let back = first_token(&sh.exec_long(&format!( + "nanddump -s 0x{rel:x} -l {readlen} /dev/{dev} 2>/dev/null | md5sum" + ))?); + let want = padded_md5(data); + if back != want { + return Err(StockError::Method(format!( + "{label}: read-back md5 {back} != {want} at /dev/{dev} rel 0x{rel:x} \ + (write did not persist)" + ))); + } + sh.exec(&format!("rm -f {remote}"))?; + Ok(()) +} + +/// Copy `len` bytes already on NAND from absolute `src` to absolute `dst` +/// (used when carving the on-board stock backup). `dst` must be erase aligned. +fn copy_abs( + sh: &mut dyn Shell, + table: &[Mtd], + src: u64, + dst: u64, + len: u64, + label: &str, +) -> Result<(), StockError> { + let (sdev, srel) = locate(table, src, len)?; + let sdev = sdev.to_owned(); + let (ddev, drel) = locate(table, dst, len)?; + let ddev = ddev.to_owned(); + let blocks = round_up(len, ERASE) / ERASE; + let tmp = format!("/tmp/alk/{label}.bak"); + sh.exec("mkdir -p /tmp/alk")?; + let out = sh.exec_long(&format!( + "nanddump -s 0x{srel:x} -l {len} /dev/{sdev} -f {tmp} >/dev/null 2>&1 && \ + flash_erase /dev/{ddev} 0x{drel:x} {blocks} >/dev/null 2>&1 && \ + nandwrite -p -s 0x{drel:x} /dev/{ddev} {tmp} >/dev/null 2>&1 && \ + rm -f {tmp} && echo COPIED" + ))?; + if !out.contains("COPIED") { + return Err(StockError::Method(format!( + "{label}: backup copy failed: {out}" + ))); + } + Ok(()) +} + +/// Read `len` (even) bytes from NAND at (dev, rel) as raw bytes, via +/// `od -v -x`, which is the only `od` form the stock busybox understands (no +/// `-A`/`-t`). The leading octal address column and trailing byte-count line are +/// discarded by [`parse_od`]. +fn read_small(sh: &mut dyn Shell, dev: &str, rel: u64, len: u64) -> Result, StockError> { + let out = sh.exec(&format!( + "nanddump -s 0x{rel:x} -l {len} /dev/{dev} 2>/dev/null | od -v -x" + ))?; + Ok(parse_od(&out)) +} + +/// Read a big-endian u32 at byte `field_off` within the image whose header +/// starts at the (page-aligned) absolute NAND offset `region_abs`. `nanddump` +/// needs a page-aligned `-s`, so we read the first 64 bytes of the region and +/// slice the field in Rust (used to size the genuine stock images from their +/// uImage / fdt headers before backing up). +fn read_header_u32_be( + sh: &mut dyn Shell, + table: &[Mtd], + region_abs: u64, + field_off: usize, +) -> Result { + let (dev, rel) = locate(table, region_abs, 64)?; + let dev = dev.to_owned(); + let b = read_small(sh, &dev, rel, 64)?; + if b.len() < field_off + 4 { + return Err(StockError::Method(format!( + "short header read at 0x{region_abs:x} ({} bytes)", + b.len() + ))); + } + Ok(u32::from_be_bytes([ + b[field_off], + b[field_off + 1], + b[field_off + 2], + b[field_off + 3], + ])) +} + +fn first_token(s: &str) -> String { + s.split_whitespace().next().unwrap_or("").to_owned() +} + +// --------------------------------------------------------------------------- +// On-board stock backup manifest +// --------------------------------------------------------------------------- + +#[derive(Clone, Debug)] +struct BackupManifest { + kernel_abs: u64, + kernel_len: u64, + dtb_abs: u64, + dtb_len: u64, + rootfs_abs: u64, + rootfs_len: u64, +} + +impl BackupManifest { + fn encode(&self) -> Vec { + let mut v = Vec::with_capacity(64); + v.extend_from_slice(BK_MAGIC); + for n in [ + self.kernel_abs, + self.kernel_len, + self.dtb_abs, + self.dtb_len, + self.rootfs_abs, + self.rootfs_len, + ] { + v.extend_from_slice(&n.to_be_bytes()); + } + v + } + fn decode(b: &[u8]) -> Option { + if b.len() < 8 + 6 * 8 || &b[..8] != BK_MAGIC { + return None; + } + let g = |i: usize| { + let mut a = [0u8; 8]; + a.copy_from_slice(&b[8 + i * 8..8 + i * 8 + 8]); + u64::from_be_bytes(a) + }; + Some(BackupManifest { + kernel_abs: g(0), + kernel_len: g(1), + dtb_abs: g(2), + dtb_len: g(3), + rootfs_abs: g(4), + rootfs_len: g(5), + }) + } +} + +/// Carve the genuine stock kernel + dtb + ramdisk (still on NAND) into the +/// stock-backup region, with a manifest in its first block, so the board can be +/// returned to its own factory stock later with no vendor file. Called on the +/// stock side during a from-stock install, before the boot slots are overwritten. +fn carve_backup(sh: &mut dyn Shell, table: &[Mtd]) -> Result { + // Size the genuine images from their on-NAND headers (uImage data size at + // header offset 12; fdt totalsize at offset 4). + let kernel_len = 64 + read_header_u32_be(sh, table, OFF_KERNEL, 12)? as u64; + let dtb_len = read_header_u32_be(sh, table, OFF_DTB, 4)? as u64; + let rootfs_len = 64 + read_header_u32_be(sh, table, OFF_ROOTFS, 12)? as u64; + // Sanity: headers must look like a uImage/fdt, sizes within slots. + if kernel_len < 64 || kernel_len > SLOT_KERNEL || rootfs_len < 64 || rootfs_len > SLOT_ROOTFS { + return Err(StockError::Method(format!( + "stock image sizes implausible (kernel {kernel_len}, rootfs {rootfs_len}); \ + refusing to back up" + ))); + } + let k_dst = BK_MANIFEST + ERASE; // images follow the manifest block + let d_dst = k_dst + round_up(kernel_len, ERASE); + let r_dst = d_dst + round_up(dtb_len, ERASE); + if r_dst + round_up(rootfs_len, ERASE) > OFF_STOCK_BACKUP + SLOT_STOCK_BACKUP { + return Err(StockError::Method( + "stock backup does not fit in the 32 MiB backup region".into(), + )); + } + copy_abs(sh, table, OFF_KERNEL, k_dst, kernel_len, "stock-kernel")?; + copy_abs(sh, table, OFF_DTB, d_dst, dtb_len, "stock-dtb")?; + copy_abs(sh, table, OFF_ROOTFS, r_dst, rootfs_len, "stock-rootfs")?; + let manifest = BackupManifest { + kernel_abs: k_dst, + kernel_len, + dtb_abs: d_dst, + dtb_len, + rootfs_abs: r_dst, + rootfs_len, + }; + write_abs(sh, table, BK_MANIFEST, &manifest.encode(), "stock-backup-manifest")?; + Ok(manifest) +} + +/// Read and validate the on-board backup manifest, if present. +fn read_backup_manifest( + sh: &mut dyn Shell, + table: &[Mtd], +) -> Result, StockError> { + let (dev, rel) = match locate(table, BK_MANIFEST, 64) { + Ok(v) => v, + Err(_) => return Ok(None), // region not mapped -> treat as absent + }; + let dev = dev.to_owned(); + // Pull the 64-byte manifest off NAND via `od -v -x` (busybox-safe) and parse. + let bytes = read_small(sh, &dev, rel, 64)?; + Ok(BackupManifest::decode(&bytes)) +} + +/// Parse `od` hex output into bytes. Accepts both `-tx1` (byte hex) and `-x` +/// (little-endian 16-bit words). +fn parse_od(s: &str) -> Vec { + let toks: Vec<&str> = s.split_whitespace().collect(); + // Heuristic: 2-char tokens are bytes (-tx1); 4-char tokens are LE words (-x). + let mut out = Vec::new(); + for t in &toks { + match t.len() { + 2 => { + if let Ok(b) = u8::from_str_radix(t, 16) { + out.push(b); + } + } + 4 => { + if let Ok(w) = u16::from_str_radix(t, 16) { + out.push((w & 0xff) as u8); + out.push((w >> 8) as u8); + } + } + _ => {} + } + } + out +} + +// --------------------------------------------------------------------------- +// Operations +// --------------------------------------------------------------------------- + +/// What to write to the three boot slots (already in the exact on-NAND form: +/// kernel and rootfs as legacy uImages, dtb as a raw fdt). +struct BootImages { + kernel_uimage: Vec, + dtb: Vec, + rootfs_uimage: Vec, +} + +fn write_boot_slots( + sh: &mut dyn Shell, + table: &[Mtd], + img: &BootImages, +) -> Result<(), StockError> { + // rootfs, dtb, kernel order: an interrupted run never leaves a new rootfs + // under an old kernel. + if img.rootfs_uimage.len() as u64 > SLOT_ROOTFS { + return Err(StockError::Method("rootfs over slot ceiling".into())); + } + if img.dtb.len() as u64 > SLOT_DTB { + return Err(StockError::Method("dtb over slot ceiling".into())); + } + if img.kernel_uimage.len() as u64 > SLOT_KERNEL { + return Err(StockError::Method("kernel over slot ceiling".into())); + } + write_abs(sh, table, OFF_ROOTFS, &img.rootfs_uimage, "rootfs")?; + write_abs(sh, table, OFF_DTB, &img.dtb, "dtb")?; + write_abs(sh, table, OFF_KERNEL, &img.kernel_uimage, "kernel")?; + Ok(()) +} + +/// Whether the connected board is a Zynq, so the readable boot-slot path +/// applies. Other boards fall back to the compiled-in method. +fn shell_is_zynq(sh: &mut dyn Shell) -> bool { + sh.exec( + "(grep -qi zynq /proc/cpuinfo 2>/dev/null || \ + grep -qai zynq /proc/device-tree/compatible 2>/dev/null) && echo yes || true", + ) + .map(|o| o.contains("yes")) + .unwrap_or(false) +} + +fn reboot(sh: &mut dyn Shell) { + // Best-effort: the reboot drops the shell, so ignore the result. + let _ = sh.exec("sync; (sleep 1; reboot) >/dev/null 2>&1 &"); +} + +/// Install alkane onto a board currently on stock, over the network. The afw +/// ships a raw `zImage`, a raw fdt and a gzipped cpio rootfs; we wrap the kernel +/// and rootfs as the legacy uImages the preserved stock U-Boot boots, carve the +/// genuine stock backup first, then write the boot slots and reboot. +pub fn install_from_stock( + host: &str, + kernel_zimage: &[u8], + dtb: &[u8], + rootfs_cpio_gz: &[u8], + password: Option<&str>, +) -> Result<(), StockError> { + let mut sh = StockShell { + host: host.to_owned(), + password: password.map(str::to_owned), + }; + if first_token(&sh.exec("id -u")?) != "0" { + return Err(StockError::Auth("did not obtain root on the stock board".into())); + } + let table = read_mtd_table(&mut sh)?; + // Carve the genuine-stock backup from the live stock NAND before any write. + carve_backup(&mut sh, &table)?; + let img = BootImages { + kernel_uimage: uimage::wrap(Kind::Kernel, kernel_zimage, 0, "alkane-kernel"), + dtb: dtb.to_vec(), + rootfs_uimage: uimage::wrap(Kind::Ramdisk, rootfs_cpio_gz, 0, "alkane-rootfs"), + }; + write_boot_slots(&mut sh, &table, &img)?; + reboot(&mut sh); + Ok(()) +} + +/// Return an alkane board to genuine stock by writing the vendor images back to +/// the boot slots over SSH. `dtb` is the genuine per-board device tree (from the +/// vendor package); if `None`, the stock dtb saved in the on-board backup is +/// used. `kernel`/`rootfs` are the vendor legacy uImages, written as-is. +pub fn restore_to_stock( + host: &str, + kernel_uimage: &[u8], + rootfs_uimage: &[u8], + dtb: Option<&[u8]>, + password: Option<&str>, +) -> Result<(), StockError> { + let mut sh = AlkaneShell::connect(host, password)?; + if !shell_is_zynq(&mut sh) { + return Err(StockError::NotApplicable); + } + let table = read_mtd_table(&mut sh)?; + if rootfs_uimage.len() as u64 > SLOT_ROOTFS || kernel_uimage.len() as u64 > SLOT_KERNEL { + return Err(StockError::Method("vendor image over slot ceiling".into())); + } + // rootfs, dtb, kernel order (same safety ordering as install). + write_abs(&mut sh, &table, OFF_ROOTFS, rootfs_uimage, "rootfs")?; + match dtb { + Some(d) => { + if d.len() as u64 > SLOT_DTB { + return Err(StockError::Method("dtb over slot ceiling".into())); + } + write_abs(&mut sh, &table, OFF_DTB, d, "dtb")?; + } + None => { + // No vendor dtb (an OTA package omits it): restore the genuine + // per-board dtb from the on-board backup by copying within NAND. + let manifest = read_backup_manifest(&mut sh, &table)?.ok_or_else(|| { + StockError::Method( + "no stock dtb supplied and no on-board backup to take one from".into(), + ) + })?; + copy_abs(&mut sh, &table, manifest.dtb_abs, OFF_DTB, manifest.dtb_len, "dtb")?; + } + } + write_abs(&mut sh, &table, OFF_KERNEL, kernel_uimage, "kernel")?; + reboot(&mut sh); + Ok(()) +} + +/// Whether the board holds a complete, restorable on-board stock backup. +pub fn onboard_backup_present(host: &str, password: Option<&str>) -> Result { + let mut sh = AlkaneShell::connect(host, password)?; + if !shell_is_zynq(&mut sh) { + return Err(StockError::NotApplicable); + } + let table = read_mtd_table(&mut sh)?; + Ok(read_backup_manifest(&mut sh, &table)?.is_some()) +} + +/// Return an alkane board to stock using only the on-board backup (no vendor +/// file): copy the saved stock kernel, dtb and rootfs back to the boot slots. +pub fn restore_from_onboard(host: &str, password: Option<&str>) -> Result<(), StockError> { + let mut sh = AlkaneShell::connect(host, password)?; + if !shell_is_zynq(&mut sh) { + return Err(StockError::NotApplicable); + } + let table = read_mtd_table(&mut sh)?; + let manifest = read_backup_manifest(&mut sh, &table)? + .ok_or_else(|| StockError::Method("no complete on-board stock backup".into()))?; + // Copy within NAND: backup region -> boot slots. + copy_abs(&mut sh, &table, manifest.rootfs_abs, OFF_ROOTFS, manifest.rootfs_len, "rootfs")?; + copy_abs(&mut sh, &table, manifest.dtb_abs, OFF_DTB, manifest.dtb_len, "dtb")?; + copy_abs(&mut sh, &table, manifest.kernel_abs, OFF_KERNEL, manifest.kernel_len, "kernel")?; + reboot(&mut sh); + Ok(()) +} + + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn round_up_works() { + assert_eq!(round_up(1, PAGE), PAGE); + assert_eq!(round_up(PAGE, PAGE), PAGE); + assert_eq!(round_up(PAGE + 1, PAGE), 2 * PAGE); + assert_eq!(round_up(0, ERASE), 0); + } + + #[test] + fn padded_md5_matches_manual_pad() { + let data = b"hello"; + let mut padded = data.to_vec(); + padded.resize(PAGE as usize, 0xFF); + assert_eq!(padded_md5(data), md5_hex(&padded)); + } + + #[test] + fn manifest_roundtrips() { + let m = BackupManifest { + kernel_abs: 0x6020000, + kernel_len: 4006832, + dtb_abs: 0x6420000, + dtb_len: 7650, + rootfs_abs: 0x6440000, + rootfs_len: 26620582, + }; + let enc = m.encode(); + let dec = BackupManifest::decode(&enc).unwrap(); + assert_eq!(dec.kernel_abs, m.kernel_abs); + assert_eq!(dec.rootfs_len, m.rootfs_len); + assert!(BackupManifest::decode(b"nope").is_none()); + } + + #[test] + fn locate_maps_absolute_to_partition() { + let table = vec![ + Mtd { dev: "mtd0".into(), base: 0x0, size: 0x2800000, name: "x".into() }, + Mtd { dev: "mtd1".into(), base: 0x2800000, size: 0x2000000, name: "y".into() }, + ]; + assert_eq!(locate(&table, 0x2000000, 100).unwrap(), ("mtd0", 0x2000000)); + assert_eq!(locate(&table, 0x2800000, 100).unwrap(), ("mtd1", 0)); + assert!(locate(&table, 0x9000000, 1).is_err()); + } + + #[test] + fn parse_od_both_forms() { + // -tx1 byte form + assert_eq!(parse_od("41 42 43"), vec![0x41, 0x42, 0x43]); + // -x little-endian word form -> bytes + assert_eq!(parse_od("4241"), vec![0x41, 0x42]); + } +} diff --git a/crates/alkane-gui/src/stock_ops.rs b/crates/alkane-gui/src/stock_ops.rs index 81359dda..abb37cd7 100644 --- a/crates/alkane-gui/src/stock_ops.rs +++ b/crates/alkane-gui/src/stock_ops.rs @@ -274,6 +274,7 @@ fn restore_one(ip: &str, firmware: &Path, password: Option<&str>) -> (bool, Stri let images = RestoreImages { kernel: &fw.kernel, rootfs: &fw.rootfs, + dtb: fw.dtb.as_deref(), }; match stock::restore_to_stock(ip, &images, password) { Ok(()) => (