// SPDX-License-Identifier: MIT //! Headless alkane engine: artifact verification and the network-only `.afw` //! install path for CV1835. //! //! Credentials come only from an environment variable or a file path named on //! the command line. This program never prints a credential value. use alkane_artifacts::afw::{verify_afw, VerifiedAfw, VerifyOptions}; use alkane_artifacts::fetch::{self, ReleaseSource}; use alkane_artifacts::{seed_manifest, verify_file}; use alkane_core::platform; use alkane_flash::boards::a113d::{self, A113dInstallOptions, A113dOutcome, A113dPlan}; use alkane_flash::boards::am335x::{ self as am335x, Am335xPlan, AmInstallOptions, AmInstallOutcome, AmRestoreOptions, }; use alkane_flash::boards::cv1835::Cv1835Plan; use alkane_flash::boards::zynq::{self, ZynqPlan}; use alkane_flash::install::{ install, restore, verify_live, InstallOptions, InstallOutcome, RestoreOptions, }; 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; use std::path::{Path, PathBuf}; use std::time::{Duration, SystemTime, UNIX_EPOCH}; const DEFAULT_USER: &str = "miner"; const DEFAULT_TIMEOUT: u64 = 240; struct Opts { values: BTreeMap, flags: BTreeSet, positionals: Vec, } impl Opts { fn value(&self, name: &str) -> Option<&str> { self.values.get(name).map(String::as_str) } fn flag(&self, name: &str) -> bool { self.flags.contains(name) } } fn parse_args( args: &[String], values: &[&str], flags: &[&str], ) -> Result> { let mut opts = Opts { values: BTreeMap::new(), flags: BTreeSet::new(), positionals: Vec::new(), }; let mut index = 0; while index < args.len() { let arg = &args[index]; if let Some(rest) = arg.strip_prefix("--") { let (name, inline) = match rest.split_once('=') { Some((name, value)) => (name, Some(value.to_owned())), None => (rest, None), }; if values.contains(&name) { let value = match inline { Some(value) => value, None => { index += 1; args.get(index) .cloned() .ok_or_else(|| format!("--{name} needs a value"))? } }; opts.values.insert(name.to_owned(), value); } else if flags.contains(&name) { if inline.is_some() { return Err(format!("--{name} does not take a value").into()); } opts.flags.insert(name.to_owned()); } else { return Err(format!("unknown option --{name}").into()); } } else { opts.positionals.push(arg.clone()); } index += 1; } Ok(opts) } struct SecretFile { path: Option, temporary: bool, } impl Drop for SecretFile { fn drop(&mut self) { if self.temporary { if let Some(path) = &self.path { let _ = fs::remove_file(path); } } } } fn resolve_password(opts: &Opts) -> Result> { if let Some(path) = opts .value("password-file") .map(PathBuf::from) .or_else(|| std::env::var_os("ALKANE_BOARD_PASSWORD_FILE").map(PathBuf::from)) { if !path.is_file() { return Err(format!("password file not found: {}", path.display()).into()); } return Ok(SecretFile { path: Some(path), temporary: false, }); } if let Some(value) = std::env::var_os("ALKANE_BOARD_PASSWORD") { let nanos = SystemTime::now() .duration_since(UNIX_EPOCH) .unwrap_or_default() .as_nanos(); let path = std::env::temp_dir().join(format!("alkane-cli-pw-{}-{nanos}", std::process::id())); platform::write_private(&path, value.to_string_lossy().as_bytes())?; return Ok(SecretFile { path: Some(path), temporary: true, }); } Ok(SecretFile { path: None, temporary: false, }) } /// Resolve the board password into an in-memory string for the compiled-in /// stock method. The secret is never written to the environment or an argument; /// a temp file from `ALKANE_BOARD_PASSWORD` is read then dropped. Returns None /// when no credential was supplied. fn read_board_password(opts: &Opts) -> Result, Box> { let secret = resolve_password(opts)?; match &secret.path { Some(path) => { let raw = fs::read_to_string(path).map_err(|e| format!("reading board password: {e}"))?; Ok(Some(raw.trim_end_matches(['\n', '\r']).to_string())) } None => Ok(None), } } fn ssh_options( opts: &Opts, default_user: &str, ) -> Result<(SshOptions, SecretFile), Box> { let host = opts.value("host").ok_or("--host is required")?.to_owned(); let port = opts .value("port") .map(str::parse::) .transpose()? .unwrap_or(22); let user = opts.value("user").unwrap_or(default_user).to_owned(); let identity_file = opts .value("identity-file") .map(PathBuf::from) .or_else(|| std::env::var_os("ALKANE_BOARD_IDENTITY_FILE").map(PathBuf::from)); let known_hosts = opts.value("known-hosts").map(PathBuf::from); let root_method = opts .value("root-method") .map(|value| RootMethod::parse(value).ok_or_else(|| format!("unknown root method {value}"))) .transpose()? .unwrap_or(RootMethod::Auto); let update_daemon_port = opts .value("update-daemon-port") .map(str::parse::) .transpose()?; let secret = resolve_password(opts)?; let options = SshOptions { host, port, user, identity_file, password_file: secret.path.clone(), known_hosts, root_method, update_daemon_port, }; Ok((options, secret)) } fn load_afw(path: &str, opts: &Opts) -> Result> { let allow_unsigned = opts.flag("allow-unsigned"); let verified = verify_afw( Path::new(path), &VerifyOptions { allow_unsigned, expect_board: opts.value("expect-board").map(str::to_owned), }, )?; if verified.manifest.signature.kind == "unsigned" { eprintln!("WARNING: UNSIGNED .afw."); eprintln!( "SHA-256 proves integrity, not authenticity. Bench use only; site use needs Ed25519." ); for image in &verified.manifest.images { eprintln!( "payload sha256 {} {} {}", image.sha256, image.name, image.file ); } } Ok(verified) } fn print_afw(verified: &VerifiedAfw) { let manifest = &verified.manifest; println!("verified .afw"); println!(" archive sha256 {}", verified.archive_sha256); println!(" manifest sha256 {}", verified.manifest_sha256); println!( " board {} arch {} version {}", manifest.board, manifest.arch, manifest.version ); println!( " bootloader {} signature {} marker {} kernel {}", manifest.bootloader_policy.as_str(), manifest.signature.kind, manifest.marker, manifest.kernel_version ); println!( " revisions sdk {} os {} built {}", &manifest.sdk_revision[..12.min(manifest.sdk_revision.len())], &manifest.os_revision[..12.min(manifest.os_revision.len())], manifest.build_date ); for image in &manifest.images { println!( " image {} role {} format {} {} B sha256 {}{}", image.name, image.role, image.format, image.size, image.sha256, if image.install { format!(" -> {}", image.partition.as_deref().unwrap_or("unassigned")) } else { String::new() } ); } for partition in &manifest.partitions { println!( " partition {} {} {} B secure={} boot_critical={} write_order={}{}", partition.name, partition.device, partition.size, partition.secure, partition.boot_critical, partition.write_order, partition .image .as_deref() .map(|image| format!(" image={image}")) .unwrap_or_default() ); } } fn run_verify(args: &[String]) -> Result<(), Box> { let opts = parse_args( args, &["expect-board", "public-key"], &["allow-unsigned", "json", "quiet"], )?; let path = opts .positionals .first() .ok_or("usage: alkane-cli afw verify [--allow-unsigned]")?; if opts.value("public-key").is_some() { return Err( "this build cannot verify Ed25519 in Rust; use ci/check-afw.py --public-key".into(), ); } let verified = load_afw(path, &opts)?; if opts.flag("json") { println!( "{}", serde_json::json!({ "file": path, "archive_sha256": verified.archive_sha256, "manifest_sha256": verified.manifest_sha256, "manifest": verified.manifest, }) ); } else if !opts.flag("quiet") { print_afw(&verified); } Ok(()) } fn run_inspect(args: &[String]) -> Result<(), Box> { let opts = parse_args(args, &["expect-board"], &["allow-unsigned"])?; let path = opts .positionals .first() .ok_or("usage: alkane-cli afw inspect [--allow-unsigned]")?; let verified = load_afw(path, &opts)?; print_afw(&verified); println!("{}", serde_json::to_string_pretty(&verified.manifest)?); Ok(()) } fn ssh_values() -> &'static [&'static str] { &[ "host", "port", "user", "identity-file", "password-file", "known-hosts", "root-method", "update-daemon-port", ] } fn run_plan(args: &[String]) -> Result<(), Box> { let opts = parse_args(args, ssh_values(), &["allow-unsigned"])?; let path = opts .positionals .first() .ok_or("usage: alkane-cli afw plan --host ")?; let verified = load_afw(path, &opts)?; if am335x::owns_board(&verified.manifest.board) { let plan = Am335xPlan::from_afw(&verified)?; let (ssh, _secret) = ssh_options(&opts, DEFAULT_USER)?; let mut transport = SshTransport::connect(ssh, true)?; let kernel = String::from_utf8_lossy(&transport.user_command("uname -r", Duration::from_secs(15))?) .trim() .to_owned(); let uid = String::from_utf8_lossy(&transport.root_command("id -u", Duration::from_secs(15))?) .trim() .to_owned(); let mtd = String::from_utf8_lossy( &transport.user_command("cat /proc/mtd 2>/dev/null", Duration::from_secs(15))?, ) .into_owned(); println!("{}", plan.render()); println!("current kernel {kernel} uid {uid}"); println!("board mtd table:\n{mtd}"); println!( "root channel {} (transport {}, never serial)", transport.root_method(), transport.channel() ); println!("plan is read-only; no write performed"); return Ok(()); } if zynq::owns_board(&verified.manifest.board) { let plan = ZynqPlan::from_afw(&verified)?; println!("{}", plan.render()); println!("plan is read-only; no write performed (run preflight/install with --host)"); return Ok(()); } if a113d::owns_board(&verified.manifest.board) { let plan = A113dPlan::from_afw(&verified)?; println!("{}", plan.render()); println!("plan is read-only; no write performed (run preflight/install with --host)"); return Ok(()); } let plan = Cv1835Plan::from_afw(&verified)?; let (ssh, _secret) = ssh_options(&opts, DEFAULT_USER)?; let mut transport = SshTransport::connect(ssh, true)?; let kernel = String::from_utf8_lossy(&transport.user_command("uname -r", Duration::from_secs(15))?) .trim() .to_owned(); let uid = String::from_utf8_lossy(&transport.root_command("id -u", Duration::from_secs(15))?) .trim() .to_owned(); let p1_size = String::from_utf8_lossy(&transport.user_command( "cat /sys/class/block/mmcblk0p1/size 2>/dev/null || true", Duration::from_secs(15), )?) .trim() .to_owned(); println!("{}", plan.render()); println!( "current kernel {} uid {} p1 sectors {}", kernel, uid, p1_size ); println!( "root channel {} (transport {}, never serial)", transport.root_method(), transport.channel() ); if let Some(port) = transport.update_daemon_port() { println!("stock update-daemon port {port} (reached through an SSH local forward)"); } println!("plan is read-only; no write performed"); Ok(()) } fn run_preflight(args: &[String]) -> Result<(), Box> { let opts = parse_args( args, &[ssh_values(), &["held-backup", "expect-board"]].concat(), &["allow-unsigned", "check-golden", "allow-unknown-source"], )?; let path = opts .positionals .first() .ok_or("usage: alkane-cli afw preflight --host ")?; let verified = load_afw(path, &opts)?; // Zynq is reached through the compiled-in method (root SSH, boot regions // re-registered), not the generic user transport below. if zynq::owns_board(&verified.manifest.board) { let host = opts.value("host").ok_or("--host is required")?; let plan = ZynqPlan::from_afw(&verified)?; println!("{}", plan.render()); let password = read_board_password(&opts)?; let options = InPlaceOptions { dry_run: true, reboot: false, backup_dir: None, }; match stock::update_in_place(host, &verified, password.as_deref(), &options) { Ok(InPlaceOutcome::DryRun(report)) => print!("{report}"), Ok(InPlaceOutcome::Updated(_)) => { return Err("internal error: preflight reported a write".into()) } Err(e) => return Err(format!("preflight failed; do not write: {e}").into()), } println!("preflight is read-only; no write performed"); return Ok(()); } let (ssh, _secret) = ssh_options(&opts, DEFAULT_USER)?; let mut transport = SshTransport::connect(ssh, true)?; if am335x::owns_board(&verified.manifest.board) { let plan = Am335xPlan::from_afw(&verified)?; let report = am335x::preflight(&plan, &mut transport, opts.value("host").unwrap_or(""))?; print!("{}", report.render()); if !report.ok() { return Err("preflight failed; do not write".into()); } return Ok(()); } if a113d::owns_board(&verified.manifest.board) { let plan = A113dPlan::from_afw(&verified)?; let report = a113d::preflight(&plan, &mut transport, opts.value("host").unwrap_or(""))?; print!("{}", report.render()); if !report.ok() { return Err("preflight failed; do not write".into()); } return Ok(()); } let plan = Cv1835Plan::from_afw(&verified)?; let held_backup = opts.value("held-backup").map(PathBuf::from); let report = preflight( &plan, &mut transport, &PreflightOptions { host: opts.value("host").unwrap_or(""), held_backup: held_backup.as_deref(), check_golden: opts.flag("check-golden"), allow_unknown_source: opts.flag("allow-unknown-source"), }, )?; print!("{}", report.render()); if !report.ok() { return Err("preflight failed; do not write".into()); } Ok(()) } /// Update a Zynq board that already runs alkane, in place, through the /// compiled-in method: it re-registers the boot regions (not exposed to Linux on /// alkane), keeps a copy of every slot before any erase, writes the kernel and /// rootfs as the uImages the stock U-Boot boots, reads each back, and never /// writes BOOT.bin. A board on stock is refused (use --from-stock). fn install_zynq_in_place( verified: &VerifiedAfw, opts: &Opts, ) -> Result<(), Box> { let host = opts.value("host").ok_or("--host is required")?.to_owned(); let plan = ZynqPlan::from_afw(verified)?; println!("{}", plan.render()); let dry_run = opts.flag("dry-run"); if !dry_run && opts.value("confirm") != Some("FLASH") { return Err("refusing to write without --confirm FLASH (use --dry-run to inspect)".into()); } let backup_dir = opts .value("backup-dir") .map(PathBuf::from) .unwrap_or_else(|| platform::config_path("backups")); let password = read_board_password(opts)?; let options = InPlaceOptions { dry_run, reboot: !opts.flag("no-reboot"), backup_dir: Some(backup_dir), }; match stock::update_in_place(&host, verified, password.as_deref(), &options)? { InPlaceOutcome::DryRun(report) => { print!("{report}"); println!("DRY RUN: no board erase or write was performed."); println!( "Re-run with --confirm FLASH to write rootfs, dtb and kernel (BOOT.bin preserved)." ); } InPlaceOutcome::Updated(receipt) => { for held in &receipt.backups { println!( "held {} abs 0x{:x} ({} B) {} md5 {}", held.name, held.absolute, held.size, held.path.display(), held.md5 ); } println!("all read-backs matched before reboot; BOOT.bin never touched"); if receipt.rebooted { println!("board rebooted and answered as alkane again (SSH banner)"); print!("{}", zynq_verify_hint(&host)); } else { println!("reboot skipped (--no-reboot); the new images run after the next reboot"); } } } Ok(()) } /// Install onto a board currently on stock via the from-stock install method. fn install_from_stock_flow( verified: &VerifiedAfw, host: &str, afw: &Path, opts: &Opts, ) -> Result<(), Box> { if opts.flag("dry-run") { println!( "DRY RUN: would install {} onto stock board {host} via the from-stock install method ({})", verified.manifest.board, afw.display() ); return Ok(()); } if opts.value("confirm") != Some("FLASH") { return Err("refusing to install from stock without --confirm FLASH".into()); } // The install-from-stock method is compiled into the toolkit (network-only); // no external helper and no runtime AI dependency. A board credential, if // one is supplied, is passed in-process only. let password = read_board_password(opts)?; println!( "installing {} onto stock board {host} (network-only from-stock method)...", verified.manifest.board ); stock::install_from_stock(host, afw, verified, password.as_deref())?; println!("from-stock install reported success."); if zynq::owns_board(&verified.manifest.board) { print!("{}", zynq_verify_hint(host)); } else { println!("verify the board is now reachable as alkane:"); println!(" alkane-cli afw verify-live --host {host} --timeout 300"); } Ok(()) } /// How to confirm a Zynq board came up on alkane. fn zynq_verify_hint(host: &str) -> String { format!( "verify independently:\n\ \x20 alkane-cli afw verify-live --host {host} --password-file --timeout 300\n" ) } fn run_install(args: &[String]) -> Result<(), Box> { let opts = parse_args( args, &[ ssh_values(), &[ "held-backup", "backup-dir", "confirm", "expect-board", "board", ], ] .concat(), &[ "allow-unsigned", "allow-unknown-source", "check-golden", "dry-run", "no-reboot", "latest", "from-stock", ], )?; let path = resolve_afw_source(&opts)?; let verified = load_afw(&path.to_string_lossy(), &opts)?; if !is_supported(&verified.manifest.board) { return Err(format!( "{} is not a supported install target (see: alkane-cli afw compat)", verified.manifest.board ) .into()); } // A board on stock: the first install goes through the from-stock install // method; the tier-2 partition-write path below is for a board already on // alkane. if opts.flag("from-stock") { let host = opts.value("host").ok_or("--host is required")?.to_owned(); return install_from_stock_flow(&verified, &host, &path, &opts); } if zynq::owns_board(&verified.manifest.board) { return install_zynq_in_place(&verified, &opts); } let (ssh, _secret) = ssh_options(&opts, DEFAULT_USER)?; let mut transport = SshTransport::connect(ssh, true)?; let backup_dir = opts .value("backup-dir") .map(PathBuf::from) .unwrap_or_else(|| platform::config_path("backups")); if am335x::owns_board(&verified.manifest.board) { let plan = Am335xPlan::from_afw(&verified)?; let install_options = AmInstallOptions { dry_run: opts.flag("dry-run"), confirm: opts.value("confirm").map(str::to_owned), no_reboot: opts.flag("no-reboot"), backup_dir, }; println!("{}", plan.render()); match am335x::install( &plan, &mut transport, &install_options, opts.value("host").unwrap_or(""), )? { AmInstallOutcome::DryRun(report) => { print!("{}", report.render()); println!("DRY RUN: no board erase or write was performed."); let targets = plan .targets .iter() .map(|t| t.partition.name.as_str()) .collect::>() .join(", "); println!("Re-run with --confirm FLASH to write {targets}."); } AmInstallOutcome::Installed(receipt) => { for backup in &receipt.backups { println!( "held {} {} md5 {} sha256 {}", backup.partition, backup.path.display(), backup.md5, backup.sha256 ); } println!("all three mtd read-backs matched before reboot"); if receipt.rebooted { println!("reboot issued; an SSH drop here is the success signature"); println!( "next: alkane-cli afw verify-live --host {} --timeout 300", opts.value("host").unwrap_or("") ); } else { println!("reboot skipped (--no-reboot); verify-live will fail until the board reboots"); } } } return Ok(()); } if a113d::owns_board(&verified.manifest.board) { let plan = A113dPlan::from_afw(&verified)?; println!("{}", plan.render()); let install_options = A113dInstallOptions { dry_run: opts.flag("dry-run"), confirm: opts.value("confirm").map(str::to_owned), no_reboot: opts.flag("no-reboot"), backup_dir, }; match a113d::install( &plan, &mut transport, &install_options, opts.value("host").unwrap_or(""), )? { A113dOutcome::DryRun(report) => { print!("{}", report.render()); println!("DRY RUN: no file was written into the nvdata UBI."); let targets = plan .targets .iter() .map(|t| t.image_name.as_str()) .collect::>() .join(", "); println!("Re-run with --confirm FLASH to write {targets} into the alkane/ dir on nvdata (FIP + mtd0-5 are not MTD devices)."); } A113dOutcome::Installed(receipt) => { println!( "wrote OS files into the alkane/ dir on nvdata volume {}", receipt.volume ); for backup in &receipt.backups { match (&backup.path, &backup.md5) { (Some(path), Some(md5)) => { println!("held {} {} md5 {}", backup.image_name, path.display(), md5) } _ => println!("held {} (no prior file on board)", backup.image_name), } } println!( "all read-backs matched before reboot; no raw NAND write, FIP never touched" ); if receipt.rebooted { println!("reboot issued; an SSH drop here is the success signature"); } else { println!("reboot skipped (--no-reboot)"); } } } return Ok(()); } let plan = Cv1835Plan::from_afw(&verified)?; let install_options = InstallOptions { dry_run: opts.flag("dry-run"), confirm: opts.value("confirm").map(str::to_owned), no_reboot: opts.flag("no-reboot"), backup_dir, held_backup: opts.value("held-backup").map(PathBuf::from), allow_unknown_source: opts.flag("allow-unknown-source"), check_golden: opts.flag("check-golden"), }; println!("{}", plan.render()); match install( &verified, &plan, &mut transport, &install_options, opts.value("host").unwrap_or(""), )? { InstallOutcome::DryRun(report) => { print!("{}", report.render()); println!("DRY RUN: no board write was performed."); println!("Re-run with --confirm FLASH to write p1."); } InstallOutcome::Installed(receipt) => { println!("held stock p1 {}", receipt.backup_path.display()); println!("held p1 md5 {}", receipt.backup_md5); println!("held p1 sha256 {}", receipt.backup_sha256); println!("wrote p1 image md5 {}", receipt.image_md5); println!("whole-partition read-back matched before reboot"); if receipt.rebooted { println!("reboot issued; an SSH drop here is the success signature"); println!( "next: alkane-cli afw verify-live --host {} --timeout 300", opts.value("host").unwrap_or("") ); } else { println!( "reboot skipped (--no-reboot); verify-live will fail until the board reboots" ); } } } Ok(()) } fn run_verify_live(args: &[String]) -> Result<(), Box> { let opts = parse_args( args, &[ ssh_values(), &[ "marker", "kernel-version", "timeout", "expect-board", "board", ], ] .concat(), &["allow-unsigned"], )?; let requested_board = opts.value("board").map(str::to_owned); let (board, marker, kernel_version) = if let Some(path) = opts.positionals.first() { let verified = load_afw(path, &opts)?; let board = verified.manifest.board.clone(); if zynq::owns_board(&board) { let plan = ZynqPlan::from_afw(&verified)?; ( board, opts.value("marker").unwrap_or(&plan.marker).to_owned(), opts.value("kernel-version") .unwrap_or(&plan.kernel_version) .to_owned(), ) } else if board == "am335x" { let plan = Am335xPlan::from_afw(&verified)?; ( board, opts.value("marker").unwrap_or(&plan.marker).to_owned(), opts.value("kernel-version") .unwrap_or(&plan.kernel_version) .to_owned(), ) } else { let plan = Cv1835Plan::from_afw(&verified)?; ( board, opts.value("marker").unwrap_or(&plan.marker).to_owned(), opts.value("kernel-version") .unwrap_or(&plan.kernel_version) .to_owned(), ) } } else { let board = requested_board .clone() .unwrap_or_else(|| "cv1835".to_owned()); let (marker, kernel) = if board == "am335x" { ("Alkane".to_owned(), "6.18.48".to_owned()) } else if zynq::owns_board(&board) { ("Alkane".to_owned(), String::new()) } else { ("CVBOOT".to_owned(), String::new()) }; ( board, opts.value("marker").unwrap_or(&marker).to_owned(), opts.value("kernel-version").unwrap_or(&kernel).to_owned(), ) }; if let Some(expected) = &requested_board { if expected != &board { return Err(format!("bundle is for {board}, expected {expected}").into()); } } let host = opts.value("host").ok_or("--host is required")?.to_owned(); let timeout = opts .value("timeout") .map(str::parse::) .transpose()? .unwrap_or(DEFAULT_TIMEOUT); if zynq::owns_board(&board) { // Zynq is checked through the compiled-in method's root SSH (the host // key changes on every reflash, so it is not pinned) plus the web page. let password = read_board_password(&opts)?; let report = stock::verify_zynq_live( &host, password.as_deref(), &marker, &kernel_version, Duration::from_secs(timeout), )?; print!("{}", report.render()); if !report.ok() { return Err( "live verification failed: HTTP marker and SSH did not both confirm alkane".into(), ); } return Ok(()); } let (ssh, _secret) = ssh_options(&opts, DEFAULT_USER)?; if board == "am335x" { let report = am335x::verify_live( &host, &marker, &kernel_version, Duration::from_secs(timeout), &ssh, ); print!("{}", report.render()); if !report.ok() { return Err("live verification failed: SSH, HTTP marker, API or DHCP disagreed".into()); } return Ok(()); } let report = verify_live( &host, &marker, &kernel_version, Duration::from_secs(timeout), &ssh, ); print!("{}", report.render()); if !report.ok() { return Err("live verification failed after two channels disagreed".into()); } println!("also confirm the DHCP lease for the board before calling it proven"); Ok(()) } fn run_restore(args: &[String]) -> Result<(), Box> { let opts = parse_args( args, &[ ssh_values(), &[ "held-backup", "backup-dir", "confirm", "board", "held-kernel", "held-dtb", "held-uboot", ], ] .concat(), &["no-reboot"], )?; let (ssh, _secret) = ssh_options(&opts, DEFAULT_USER)?; let mut transport = SshTransport::connect(ssh, true)?; if let Some(profile) = opts.value("board").and_then(am335x::profile_for) { let dir = opts .value("backup-dir") .map(PathBuf::from) .unwrap_or_else(|| platform::config_path("backups")); // The held set is the profile's write targets: mtd8/mtd7/mtd6 on both // tiers, plus mtd4 (our U-Boot) on the tier-3 from-stock profile. let mut table: Vec<(&str, Option<&str>, &str)> = vec![ ("mtd8", opts.value("held-backup"), "mtd8-"), ("mtd7", opts.value("held-kernel"), "mtd7-"), ("mtd6", opts.value("held-dtb"), "mtd6-"), ]; if profile.targets.iter().any(|(part, ..)| *part == "mtd4") { table.push(("mtd4", opts.value("held-uboot"), "mtd4-")); } let mut backups: Vec<(String, PathBuf)> = Vec::new(); for (name, value, prefix) in table { let path = match value { Some(path) => PathBuf::from(path), None => latest_backup_for(&dir, prefix).ok_or_else(|| { format!( "no held {name} backup in {}; pass the matching --held-* option", dir.display() ) })?, }; backups.push((name.to_owned(), path)); } let preserve: Vec = profile.preserve.iter().map(|s| (*s).to_owned()).collect(); let receipt = am335x::restore( &backups, &mut transport, &AmRestoreOptions { confirm: opts.value("confirm").map(str::to_owned), no_reboot: opts.flag("no-reboot"), }, &preserve, )?; for (name, path) in &receipt.restored { println!("restored {name} from {}", path.display()); } println!("all mtd read-backs matched before reboot"); if receipt.rebooted { println!("reboot issued; the board should return to its held OS"); } return Ok(()); } let backup = if let Some(path) = opts.value("held-backup") { PathBuf::from(path) } else { let dir = opts .value("backup-dir") .map(PathBuf::from) .unwrap_or_else(|| platform::config_path("backups")); latest_backup(&dir).ok_or_else(|| { format!( "no held backup in {}; pass --held-backup ", dir.display() ) })? }; let receipt = restore( &backup, &mut transport, &RestoreOptions { confirm: opts.value("confirm").map(str::to_owned), no_reboot: opts.flag("no-reboot"), }, )?; println!("restored stock p1 from {}", receipt.backup_path.display()); println!("image md5 {}", receipt.image_md5); println!("whole-partition read-back matched before reboot"); if receipt.rebooted { println!("reboot issued; the board should return to its held stock OS"); } Ok(()) } fn latest_backup_for(dir: &Path, prefix: &str) -> Option { let mut entries: Vec = fs::read_dir(dir) .ok()? .filter_map(Result::ok) .map(|entry| entry.path()) .filter(|path| { path.extension() == Some(std::ffi::OsStr::new("img")) && path .file_name() .map(|name| name.to_string_lossy().starts_with(prefix)) .unwrap_or(false) }) .collect(); entries.sort(); entries.pop() } fn latest_backup(dir: &Path) -> Option { let mut entries: Vec = fs::read_dir(dir) .ok()? .filter_map(Result::ok) .map(|entry| entry.path()) .filter(|path| { path.extension() == Some(std::ffi::OsStr::new("img")) && path .file_name() .map(|name| name.to_string_lossy().starts_with("p1-")) .unwrap_or(false) }) .collect(); entries.sort(); entries.pop() } /// 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)"), ("a113d", "Antminer BHB42XXX / S19k Pro (Amlogic A113D/AXG control board)"), ]; fn is_supported(board: &str) -> bool { SUPPORTED.iter().any(|(b, _)| *b == board) } fn run_compat(_args: &[String]) -> Result<(), Box> { println!("alkane-os install is supported on:"); for (board, miner) in SUPPORTED { println!(" {board:<12} {miner}"); } println!( "\nInstall a local bundle: alkane-cli afw install --host --confirm FLASH" ); println!("Install the latest build: alkane-cli afw install --latest --board zynq-7010 --host --confirm FLASH"); println!("Remove (back to stock): alkane-cli afw restore-stock --host --confirm FLASH"); Ok(()) } fn download_dir() -> PathBuf { platform::config_path("downloads") } /// Fetch the latest alkane-os .afw for a board from Gitea into the cache. fn run_fetch_latest(args: &[String]) -> Result<(), Box> { let opts = parse_args(args, &["board", "output"], &[])?; let board = opts.value("board").unwrap_or("zynq-7010"); if !is_supported(board) { return Err(format!( "{board} is not a supported install target (see: alkane-cli afw compat)" ) .into()); } let dest = opts .value("output") .map(PathBuf::from) .unwrap_or_else(download_dir); let path = fetch::fetch_latest_afw(&ReleaseSource::alkane_os(), board, &dest)?; println!("fetched {}", path.display()); Ok(()) } /// Resolve the .afw either from `--latest` (fetch from Gitea) or a positional /// file path. fn resolve_afw_source(opts: &Opts) -> Result> { if opts.flag("latest") { let board = opts.value("board").unwrap_or("zynq-7010"); if !is_supported(board) { return Err(format!( "{board} is not a supported install target (see: alkane-cli afw compat)" ) .into()); } println!("fetching the latest {board} release from Gitea..."); let path = fetch::fetch_latest_afw(&ReleaseSource::alkane_os(), board, &download_dir())?; println!("using {}", path.display()); return Ok(path); } opts.positionals.first().map(PathBuf::from).ok_or_else(|| { "usage: alkane-cli afw install |--latest --host --confirm FLASH".into() }) } /// Return an alkane board to genuine Bitmain stock by writing the stock images /// from a genuine vendor firmware package back to NAND, over the network. fn run_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(); // 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. let fw = stock_firmware::parse(Path::new(firmware))?; println!("stock firmware: {}", fw.summary()); if opts.flag("dry-run") { println!("DRY RUN: would restore {host} to stock by writing the genuine stock kernel"); println!("and rootfs plus the per-board device tree back to NAND (BOOT.bin preserved)."); 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 from {firmware} (network-only)..."); 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)."); println!("verify independently: the board should no longer answer as alkane and should"); println!("present genuine stock (lighttpd 401 on :80, TCP 22 closed)."); 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 ", )?; let rest = &args[1..]; match subcommand.as_str() { "compat" => run_compat(rest), "fetch-latest" => run_fetch_latest(rest), "verify" => run_verify(rest), "inspect" => run_inspect(rest), "plan" => run_plan(rest), "preflight" => run_preflight(rest), "install" => run_install(rest), "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()), } } fn run() -> Result<(), Box> { let args: Vec = std::env::args().skip(1).collect(); let command = args.first().ok_or( "usage: alkane-cli verify-artifact | alkane-cli afw ...", )?; if command == "verify-artifact" { if args.len() != 3 { return Err("usage: alkane-cli verify-artifact ".into()); } let record = seed_manifest()? .into_iter() .find(|item| item.path == Path::new(&args[1])) .ok_or("artifact path is absent from the seed manifest")?; let verified = verify_file(Path::new(&args[2]), &record)?; println!( "verified {} {} {} bytes", verified.record().family, verified.record().format, verified.record().size_bytes ); return Ok(()); } if command == "afw" { return run_afw(&args[1..]); } if command == "-h" || command == "--help" || command == "help" { println!( "usage:\n alkane-cli verify-artifact \n \ alkane-cli afw compat\n \ alkane-cli afw fetch-latest [--board zynq-7010] [--output ]\n \ alkane-cli afw install --latest [--board zynq-7010] --host --confirm FLASH [--from-stock] [ssh options]\n \ alkane-cli afw restore-stock --host --confirm FLASH\n \ alkane-cli afw verify [--allow-unsigned] [--expect-board ]\n \ alkane-cli afw inspect [--allow-unsigned]\n \ alkane-cli afw plan --host [ssh options]\n \ alkane-cli afw preflight --host [ssh options] [--held-backup ]\n \ alkane-cli afw install --host --dry-run [ssh options]\n \ alkane-cli afw install --host --confirm FLASH [ssh options]\n \ alkane-cli afw verify-live [] --host [--board ] [--timeout ] [ssh options]\n \ alkane-cli afw restore --host --held-backup --confirm FLASH [ssh options]\n \ alkane-cli afw restore --board am335x --host --held-backup \\\n --held-kernel --held-dtb --confirm FLASH [ssh options]\n\ \nssh options: --user --port --identity-file --password-file --known-hosts \ --root-method auto|direct|update-daemon|rroot --update-daemon-port\n\ credentials: ALKANE_BOARD_PASSWORD or ALKANE_BOARD_PASSWORD_FILE; \ ALKANE_BOARD_IDENTITY_FILE" ); return Ok(()); } Err(format!("unknown command {command}").into()) } fn main() { if let Err(error) = run() { eprintln!("alkane-cli: {error}"); std::process::exit(1); } }