diff --git a/Cargo.lock b/Cargo.lock index ddeebdbe..9136c72e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -40,6 +40,8 @@ name = "alkane-artifacts" version = "0.1.0" dependencies = [ "alkane-core", + "serde", + "serde_json", "sha2", "thiserror", ] @@ -50,6 +52,8 @@ version = "0.1.0" dependencies = [ "alkane-artifacts", "alkane-core", + "alkane-flash", + "serde_json", ] [[package]] @@ -74,6 +78,7 @@ version = "0.1.0" dependencies = [ "alkane-artifacts", "alkane-core", + "serde_json", "sha2", "tempfile", "thiserror", diff --git a/Cargo.toml b/Cargo.toml index db260694..5d3bf09e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -19,6 +19,7 @@ license = "MIT" thiserror = "2" serde = { version = "1", features = ["derive"] } sha2 = "0.10" +serde_json = "1" # Release binary: small, self-contained, and fast enough for a fleet GUI whose # hot path is network I/O, not CPU (round 18 #12). opt-level "s" + fat LTO + diff --git a/README.md b/README.md index e0a00dc7..def1b8f9 100644 --- a/README.md +++ b/README.md @@ -47,6 +47,30 @@ and Intel, macOS 11 or later; see [docs/macos.md](docs/macos.md). Discovery is read-only. Control and restore actions change miners. Check the selected devices before applying them. +## Headless .afw install (CV1835) + +`alkane-cli` is the headless engine; the GUI uses the same engine. A verified +`.afw` is a full OS bundle for exactly one board. The CV1835 installer writes +only `/dev/mmcblk0p1` over SSH, holds the current p1 first, reads the whole +partition back, and reboots only after the read-back matches. + +```sh +alkane-cli afw verify BUNDLE.afw --allow-unsigned +alkane-cli afw plan BUNDLE.afw --host 10.255.1.167 +alkane-cli afw preflight BUNDLE.afw --host 10.255.1.167 +alkane-cli afw install BUNDLE.afw --host 10.255.1.167 --dry-run +alkane-cli afw install BUNDLE.afw --host 10.255.1.167 --confirm FLASH +alkane-cli afw verify-live BUNDLE.afw --host 10.255.1.167 +alkane-cli afw restore --host 10.255.1.167 --held-backup p1.img --confirm FLASH +``` + +On stock Bitmain CV1835 the SSH login is the unprivileged `miner` account; the +toolkit obtains root through the stock update-daemon loopback channel, not a +serial console. Credentials come only from `ALKANE_BOARD_PASSWORD` or +`ALKANE_BOARD_PASSWORD_FILE`, or from `--password-file` / `--identity-file`. +No credential value is printed. `--allow-unsigned` is bench-only; site use +needs an Ed25519-signed bundle. + ## Development ```sh diff --git a/crates/alkane-artifacts/Cargo.toml b/crates/alkane-artifacts/Cargo.toml index 6b9d5412..1e86c14a 100644 --- a/crates/alkane-artifacts/Cargo.toml +++ b/crates/alkane-artifacts/Cargo.toml @@ -6,5 +6,7 @@ license.workspace = true [dependencies] alkane-core = { path = "../alkane-core" } +serde.workspace = true +serde_json.workspace = true sha2.workspace = true thiserror.workspace = true diff --git a/crates/alkane-artifacts/src/afw.rs b/crates/alkane-artifacts/src/afw.rs new file mode 100644 index 00000000..96314ab8 --- /dev/null +++ b/crates/alkane-artifacts/src/afw.rs @@ -0,0 +1,969 @@ +// SPDX-License-Identifier: MIT +//! Parse and verify an `.afw` full-OS install bundle. +//! +//! An `.afw` is a strict POSIX ustar with `manifest.json` first, an optional +//! `manifest.json.sig` second, then payload members in manifest order. This +//! module reads the tar itself, rejects unsafe or unexpected members, parses +//! the manifest, checks the board/arch and bootloader policy, and verifies +//! every payload size and SHA-256 before returning a [`VerifiedAfw`]. + +use serde::{Deserialize, Serialize}; +use sha2::{Digest, Sha256}; +use std::collections::HashSet; +use std::fs; +use std::path::Path; +use thiserror::Error; + +pub const BLOCK: usize = 512; +pub const MAX_ARCHIVE: usize = 512 * 1024 * 1024; +pub const MAX_MANIFEST: usize = 64 * 1024; +pub const CV1835_P1_SIZE: u64 = 16 * 1024 * 1024; + +const IMAGE_ROLES: &[&str] = &["kernel", "dtb", "rootfs", "bootloader", "boot", "component"]; +const IMAGE_FORMATS: &[&str] = &["fit", "arm64-image", "fdt", "cpio-gzip", "uimage", "raw"]; + +#[derive(Clone, Copy, Debug, Deserialize, Serialize, Eq, PartialEq)] +#[serde(rename_all = "lowercase")] +pub enum BootloaderPolicy { + Include, + Preserve, +} + +impl BootloaderPolicy { + pub fn as_str(self) -> &'static str { + match self { + Self::Include => "include", + Self::Preserve => "preserve", + } + } +} + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub struct BoardProfile { + pub arch: &'static str, + pub bootloader_policy: BootloaderPolicy, +} + +/// Board families named by the Antminer release plan. A bundle for a board not +/// in this table is refused rather than treated as generic. +pub fn board_profile(board: &str) -> Option { + let (arch, bootloader_policy) = match board { + "cv1835" => ("arm64", BootloaderPolicy::Preserve), + "zynq-7010" => ("armv7", BootloaderPolicy::Preserve), + "a113d" => ("armv7", BootloaderPolicy::Preserve), + "a113d-s21pro" => ("armv7", BootloaderPolicy::Preserve), + "am335x-bb" => ("armv7", BootloaderPolicy::Include), + "zynq-s17" => ("armv7", BootloaderPolicy::Include), + _ => return None, + }; + Some(BoardProfile { + arch, + bootloader_policy, + }) +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct AfwSignature { + #[serde(rename = "type")] + pub kind: String, + pub member: Option, + pub public_key_hex: Option, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct AfwImage { + pub name: String, + pub file: String, + pub role: String, + pub format: String, + pub size: u64, + pub sha256: String, + pub partition: Option, + pub install: bool, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct AfwPartition { + pub name: String, + pub device: String, + pub offset: u64, + pub size: u64, + pub secure: bool, + pub boot_critical: bool, + pub write_order: i64, + pub image: Option, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct AfwManifest { + pub schema: u32, + pub format: String, + pub board: String, + pub arch: String, + pub version: String, + pub build_date: String, + pub sdk_revision: String, + pub os_revision: String, + pub payload_type: String, + pub bootloader_policy: BootloaderPolicy, + pub signature: AfwSignature, + pub partitions: Vec, + pub images: Vec, + pub boot_switch: serde_json::Value, + pub preflight: serde_json::Value, + pub recovery: serde_json::Value, + pub marker: String, + pub kernel_version: String, + #[serde(default)] + pub notes: Option, +} + +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct AfwMember { + pub name: String, + pub data: Vec, +} + +#[derive(Debug)] +pub struct VerifiedAfw { + pub manifest: AfwManifest, + pub members: Vec, + pub manifest_sha256: String, + pub archive_sha256: String, +} + +impl VerifiedAfw { + pub fn payload(&self, name: &str) -> Option<&[u8]> { + self.members + .iter() + .find(|member| member.name == name) + .map(|member| member.data.as_slice()) + } + + pub fn image(&self, name: &str) -> Option<(&AfwImage, &[u8])> { + let image = self + .manifest + .images + .iter() + .find(|image| image.name == name)?; + let data = self.payload(&image.file)?; + Some((image, data)) + } + + pub fn install_image(&self) -> Option<(&AfwImage, &[u8])> { + let image = self.manifest.images.iter().find(|image| image.install)?; + let data = self.payload(&image.file)?; + Some((image, data)) + } + + pub fn partition(&self, name: &str) -> Option<&AfwPartition> { + self.manifest + .partitions + .iter() + .find(|part| part.name == name) + } + + pub fn payload_sha256(&self, name: &str) -> Option<&str> { + self.manifest + .images + .iter() + .find(|image| image.name == name) + .map(|image| image.sha256.as_str()) + } + + pub fn install_partition(&self) -> Option<&AfwPartition> { + let image = self.manifest.images.iter().find(|image| image.install)?; + self.partition(image.partition.as_deref()?) + } +} + +#[derive(Debug, Error)] +pub enum AfwError { + #[error("afw I/O: {0}")] + Io(#[from] std::io::Error), + #[error("archive is {0} bytes, outside the accepted range")] + ArchiveSize(usize), + #[error("tar: {0}")] + Tar(String), + #[error("unsafe member name: {0}")] + UnsafeName(String), + #[error("member {0} is not a regular file")] + NotRegular(String), + #[error("duplicate member {0}")] + Duplicate(String), + #[error("manifest.json must be the first member")] + ManifestFirst, + #[error("manifest.json is over the 64 KiB cap")] + ManifestTooLarge, + #[error("manifest JSON: {0}")] + ManifestJson(#[from] serde_json::Error), + #[error("unsupported schema {0}")] + Schema(u32), + #[error("manifest format is not afw")] + Format, + #[error("payload_type must be os")] + PayloadType, + #[error("unknown board family {0}")] + UnknownBoard(String), + #[error("board {board} must use arch {expected}")] + ArchMismatch { + board: String, + expected: &'static str, + }, + #[error("board {board} requires bootloader_policy {expected}")] + PolicyMismatch { + board: String, + expected: &'static str, + }, + #[error("manifest is invalid: {0}")] + Manifest(String), + #[error("payload member set or order is wrong")] + MemberOrder, + #[error("payload {0} size mismatch")] + Size(String), + #[error("payload {0} sha256 mismatch")] + Digest(String), + #[error("payload {0} format mismatch: {1}")] + ImageFormat(String, &'static str), + #[error("image {0} exceeds its partition")] + ImageTooLarge(String), + #[error("bundle is unsigned; pass --allow-unsigned for bench-only use")] + Unsigned, + #[error("Ed25519 signature verification is not implemented in this build")] + SignatureUnsupported, + #[error("bundle is for {actual}, expected {expected}")] + BoardMismatch { actual: String, expected: String }, +} + +#[derive(Clone, Debug, Default)] +pub struct VerifyOptions { + pub allow_unsigned: bool, + pub expect_board: Option, +} + +pub fn verify_afw(path: &Path, options: &VerifyOptions) -> Result { + let bytes = fs::read(path)?; + verify_afw_bytes(&bytes, options) +} + +pub fn verify_afw_bytes(bytes: &[u8], options: &VerifyOptions) -> Result { + if bytes.len() > MAX_ARCHIVE { + return Err(AfwError::ArchiveSize(bytes.len())); + } + let archive_sha256 = hex(&Sha256::digest(bytes)); + let raw = parse_tar(bytes)?; + if raw.first().map(|member| member.name.as_str()) != Some("manifest.json") { + return Err(AfwError::ManifestFirst); + } + if raw[0].data.len() > MAX_MANIFEST { + return Err(AfwError::ManifestTooLarge); + } + let manifest_bytes = raw[0].data.as_slice(); + let manifest: AfwManifest = serde_json::from_slice(manifest_bytes)?; + validate_manifest(&manifest, options)?; + + if manifest.signature.kind == "ed25519" { + let member = raw.get(1).ok_or(AfwError::SignatureUnsupported)?; + if member.name != "manifest.json.sig" || member.data.len() != 64 { + return Err(AfwError::SignatureUnsupported); + } + return Err(AfwError::SignatureUnsupported); + } + + let mut body = &raw[1..]; + if manifest.signature.member.is_some() { + body = &raw[2..]; + } + let expected: Vec<&str> = manifest + .images + .iter() + .map(|image| image.file.as_str()) + .collect(); + let actual: Vec<&str> = body.iter().map(|member| member.name.as_str()).collect(); + if expected != actual { + return Err(AfwError::MemberOrder); + } + + let mut members = Vec::with_capacity(body.len()); + for (member, image) in body.iter().zip(manifest.images.iter()) { + if member.data.len() as u64 != image.size { + return Err(AfwError::Size(member.name.clone())); + } + let digest = hex(&Sha256::digest(&member.data)); + if digest != image.sha256 { + return Err(AfwError::Digest(member.name.clone())); + } + check_image_format(&manifest, image, &member.data)?; + members.push(member.clone()); + } + + Ok(VerifiedAfw { + manifest, + members, + manifest_sha256: hex(&Sha256::digest(manifest_bytes)), + archive_sha256, + }) +} + +fn hex(bytes: &[u8]) -> String { + bytes.iter().map(|byte| format!("{byte:02x}")).collect() +} + +fn is_hex(value: &str, length: usize) -> bool { + value.len() == length + && value + .bytes() + .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte)) +} + +fn safe_name(name: &str) -> bool { + !name.is_empty() + && name.len() <= 255 + && !name.starts_with('/') + && !name.starts_with("./") + && !name.contains('\\') + && !name.contains('\0') + && !name.bytes().any(|byte| byte < 0x20) + && name + .split('/') + .all(|part| !part.is_empty() && part != "." && part != "..") +} + +fn validate_manifest(manifest: &AfwManifest, options: &VerifyOptions) -> Result<(), AfwError> { + if manifest.schema != 2 { + return Err(AfwError::Schema(manifest.schema)); + } + if manifest.format != "afw" { + return Err(AfwError::Format); + } + if manifest.payload_type != "os" { + return Err(AfwError::PayloadType); + } + let profile = board_profile(&manifest.board) + .ok_or_else(|| AfwError::UnknownBoard(manifest.board.clone()))?; + if manifest.arch != profile.arch { + return Err(AfwError::ArchMismatch { + board: manifest.board.clone(), + expected: profile.arch, + }); + } + if manifest.bootloader_policy != profile.bootloader_policy { + return Err(AfwError::PolicyMismatch { + board: manifest.board.clone(), + expected: profile.bootloader_policy.as_str(), + }); + } + if let Some(expected) = &options.expect_board { + if &manifest.board != expected { + return Err(AfwError::BoardMismatch { + actual: manifest.board.clone(), + expected: expected.clone(), + }); + } + } + if !is_hex(&manifest.sdk_revision, 40) || !is_hex(&manifest.os_revision, 40) { + return Err(AfwError::Manifest( + "sdk_revision and os_revision must be 40 lowercase hex characters".to_owned(), + )); + } + if manifest.version.is_empty() + || manifest.build_date.is_empty() + || manifest.marker.is_empty() + || manifest.kernel_version.is_empty() + { + return Err(AfwError::Manifest("identity fields are empty".to_owned())); + } + if manifest.images.is_empty() || manifest.partitions.is_empty() { + return Err(AfwError::Manifest( + "images and partitions must not be empty".to_owned(), + )); + } + + let mut image_names = HashSet::new(); + let mut partition_names = HashSet::new(); + for image in &manifest.images { + if !image_names.insert(image.name.as_str()) { + return Err(AfwError::Manifest(format!( + "duplicate image {}", + image.name + ))); + } + if !IMAGE_ROLES.contains(&image.role.as_str()) { + return Err(AfwError::Manifest(format!( + "image {} has an unknown role", + image.name + ))); + } + if !IMAGE_FORMATS.contains(&image.format.as_str()) { + return Err(AfwError::Manifest(format!( + "image {} has an unknown format", + image.name + ))); + } + if image.size == 0 || !is_hex(&image.sha256, 64) { + return Err(AfwError::Manifest(format!( + "image {} has no size or sha256", + image.name + ))); + } + if !safe_name(&image.file) || !image.file.starts_with("payload/") { + return Err(AfwError::UnsafeName(image.file.clone())); + } + if image.install && image.partition.is_none() { + return Err(AfwError::Manifest(format!( + "installable image {} has no partition", + image.name + ))); + } + } + for partition in &manifest.partitions { + if !partition_names.insert(partition.name.as_str()) { + return Err(AfwError::Manifest(format!( + "duplicate partition {}", + partition.name + ))); + } + if !partition.device.starts_with("/dev/") + || partition.size == 0 + || partition.write_order < 0 + { + return Err(AfwError::Manifest(format!( + "partition {} has invalid geometry", + partition.name + ))); + } + if partition.device.contains("boot0") + && (!partition.secure || partition.write_order != 0 || partition.image.is_some()) + { + return Err(AfwError::Manifest( + "boot0 must be secure, unwritten and image-free".to_owned(), + )); + } + if let Some(image) = &partition.image { + if !image_names.contains(image.as_str()) { + return Err(AfwError::Manifest(format!( + "partition {} names missing image {}", + partition.name, image + ))); + } + } + } + + let install: Vec<&AfwImage> = manifest + .images + .iter() + .filter(|image| image.install) + .collect(); + if install.is_empty() { + return Err(AfwError::Manifest( + "bundle has no installable image".to_owned(), + )); + } + for image in &manifest.images { + if let Some(partition_name) = &image.partition { + let partition = manifest + .partitions + .iter() + .find(|part| &part.name == partition_name) + .ok_or_else(|| { + AfwError::Manifest(format!( + "image {} targets unknown partition {}", + image.name, partition_name + )) + })?; + if partition.secure { + return Err(AfwError::Manifest(format!( + "image {} targets a secure partition", + image.name + ))); + } + if image.size > partition.size { + return Err(AfwError::ImageTooLarge(image.name.clone())); + } + } + } + + if manifest.board == "cv1835" { + if install.len() != 1 || install[0].name != "p1" { + return Err(AfwError::Manifest( + "cv1835 must install exactly p1".to_owned(), + )); + } + let p1 = install[0]; + if p1.format != "fit" || p1.size != CV1835_P1_SIZE { + return Err(AfwError::Manifest( + "cv1835 p1 must be the 16 MiB padded FIT".to_owned(), + )); + } + let partition = manifest + .partitions + .iter() + .find(|part| part.name == "p1") + .ok_or_else(|| AfwError::Manifest("cv1835 must plan p1".to_owned()))?; + if partition.device != "/dev/mmcblk0p1" + || partition.size != CV1835_P1_SIZE + || partition.secure + || partition.write_order != 1 + { + return Err(AfwError::Manifest("cv1835 p1 geometry is wrong".to_owned())); + } + } + + let has_bootloader = manifest + .images + .iter() + .any(|image| image.role == "bootloader"); + match manifest.bootloader_policy { + BootloaderPolicy::Preserve if has_bootloader => { + return Err(AfwError::Manifest( + "bootloader_policy is preserve but a bootloader image is present".to_owned(), + )); + } + BootloaderPolicy::Include if !has_bootloader => { + return Err(AfwError::Manifest( + "bootloader_policy is include but no bootloader image is present".to_owned(), + )); + } + _ => {} + } + + match manifest.signature.kind.as_str() { + "unsigned" => { + if !options.allow_unsigned { + return Err(AfwError::Unsigned); + } + if manifest.signature.member.is_some() { + return Err(AfwError::Manifest( + "unsigned manifest names a signature member".to_owned(), + )); + } + } + "ed25519" => { + if manifest.signature.member.as_deref() != Some("manifest.json.sig") { + return Err(AfwError::Manifest( + "ed25519 signature member must be manifest.json.sig".to_owned(), + )); + } + if manifest + .signature + .public_key_hex + .as_deref() + .map(|key| !is_hex(key, 64)) + .unwrap_or(true) + { + return Err(AfwError::Manifest( + "ed25519 manifest needs a 64-hex public key".to_owned(), + )); + } + } + _ => { + return Err(AfwError::Manifest("unknown signature type".to_owned())); + } + } + + Ok(()) +} + +fn check_image_format( + manifest: &AfwManifest, + image: &AfwImage, + data: &[u8], +) -> Result<(), AfwError> { + let fail = || { + AfwError::ImageFormat( + image.name.clone(), + match image.format.as_str() { + "fit" => "not a FIT or missing the board config", + "arm64-image" => "not an arm64 Image", + "fdt" => "not an FDT", + "cpio-gzip" => "not gzip-compressed", + "uimage" => "not a legacy uImage", + _ => "unknown format", + }, + ) + }; + match image.format.as_str() { + "fit" => { + if !data.starts_with(b"\xd0\x0d\xfe\xed") { + return Err(fail()); + } + if manifest.board == "cv1835" && !contains(data, b"config@cv1835_miner_emmc") { + return Err(fail()); + } + if contains(data, b"signature@") { + return Err(AfwError::ImageFormat( + image.name.clone(), + "FIT carries signature@ nodes", + )); + } + } + "fdt" => { + if !data.starts_with(b"\xd0\x0d\xfe\xed") { + return Err(fail()); + } + } + "arm64-image" => { + if data.len() < 64 || &data[0x38..0x3C] != b"ARMd" { + return Err(fail()); + } + } + "cpio-gzip" => { + if !data.starts_with(b"\x1f\x8b") { + return Err(fail()); + } + } + "uimage" => { + if !data.starts_with(b"\x27\x05\x19\x56") { + return Err(fail()); + } + } + "raw" => {} + _ => return Err(fail()), + } + Ok(()) +} + +fn contains(haystack: &[u8], needle: &[u8]) -> bool { + haystack + .windows(needle.len()) + .any(|window| window == needle) +} + +fn parse_tar(bytes: &[u8]) -> Result, AfwError> { + if bytes.is_empty() || !bytes.len().is_multiple_of(BLOCK) { + return Err(AfwError::Tar( + "archive length is not a multiple of 512 (truncated tar)".to_owned(), + )); + } + let mut members = Vec::new(); + let mut names = HashSet::new(); + let mut offset = 0; + let mut zero_blocks = 0; + while offset < bytes.len() { + let block = &bytes[offset..offset + BLOCK]; + offset += BLOCK; + if block == [0_u8; BLOCK] { + zero_blocks += 1; + if zero_blocks == 2 { + break; + } + continue; + } + if zero_blocks > 0 { + return Err(AfwError::Tar( + "non-zero data between end-of-archive blocks".to_owned(), + )); + } + if &block[257..262] != b"ustar" { + return Err(AfwError::Tar("header is not POSIX ustar".to_owned())); + } + let stored = octal(&block[148..156], "tar checksum")?; + let mut header = block.to_vec(); + header[148..156].fill(b' '); + if header.iter().map(|byte| *byte as u64).sum::() != stored { + return Err(AfwError::Tar("header checksum mismatch".to_owned())); + } + let mut name = field(&block[0..100]); + let prefix = field(&block[345..500]); + if !prefix.is_empty() { + name = format!("{prefix}/{name}"); + } + if !safe_name(&name) { + return Err(AfwError::UnsafeName(name)); + } + if block[156] != 0 && block[156] != b'0' { + return Err(AfwError::NotRegular(name)); + } + let size = octal(&block[124..136], "member size")?; + if size > MAX_ARCHIVE as u64 { + return Err(AfwError::ArchiveSize(size as usize)); + } + let padded = (size as usize).div_ceil(BLOCK) * BLOCK; + if offset + padded > bytes.len() { + return Err(AfwError::Tar(format!( + "member {name} runs past the end of the archive (truncated tar)" + ))); + } + if !names.insert(name.clone()) { + return Err(AfwError::Duplicate(name)); + } + members.push(AfwMember { + name, + data: bytes[offset..offset + size as usize].to_vec(), + }); + offset += padded; + if members.len() > 64 { + return Err(AfwError::Tar("too many members".to_owned())); + } + } + if zero_blocks < 2 { + return Err(AfwError::Tar( + "archive has no two-block end marker (truncated tar)".to_owned(), + )); + } + if bytes[offset..].iter().any(|byte| *byte != 0) { + return Err(AfwError::Tar( + "non-zero trailing bytes after the end marker".to_owned(), + )); + } + if members.is_empty() { + return Err(AfwError::Tar("archive has no members".to_owned())); + } + Ok(members) +} + +fn field(bytes: &[u8]) -> String { + let end = bytes + .iter() + .position(|byte| *byte == 0) + .unwrap_or(bytes.len()); + String::from_utf8_lossy(&bytes[..end]).into_owned() +} + +fn octal(bytes: &[u8], what: &str) -> Result { + let text = field(bytes); + let text = text.trim(); + if text.is_empty() { + return Ok(0); + } + if text.bytes().any(|byte| byte >= 0x80) { + return Err(AfwError::Tar(format!("{what} uses a base-256 tar number"))); + } + u64::from_str_radix(text, 8).map_err(|_| AfwError::Tar(format!("{what} is not octal"))) +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + const P1: usize = CV1835_P1_SIZE as usize; + const REV: &str = "0000000000000000000000000000000000000000"; + + fn header(name: &str, size: usize) -> [u8; BLOCK] { + assert!(name.len() <= 100); + let mut block = [0_u8; BLOCK]; + block[..name.len()].copy_from_slice(name.as_bytes()); + block[100..108].copy_from_slice(b"0000644\0"); + block[108..116].copy_from_slice(b"0000000\0"); + block[116..124].copy_from_slice(b"0000000\0"); + let size_field = format!("{size:011o}\0"); + block[124..136].copy_from_slice(size_field.as_bytes()); + block[136..148].copy_from_slice(b"00000000000\0"); + block[148..156].fill(b' '); + block[156] = b'0'; + block[257..263].copy_from_slice(b"ustar\0"); + block[263..265].copy_from_slice(b"00"); + let checksum: u64 = block.iter().map(|byte| *byte as u64).sum(); + let checksum_field = format!("{checksum:06o}\0 "); + block[148..156].copy_from_slice(checksum_field.as_bytes()); + block + } + + fn tar(members: &[(&str, &[u8])]) -> Vec { + let mut out = Vec::new(); + for (name, data) in members { + out.extend_from_slice(&header(name, data.len())); + out.extend_from_slice(data); + let padding = (BLOCK - data.len() % BLOCK) % BLOCK; + out.extend(std::iter::repeat_n(0_u8, padding)); + } + out.extend(std::iter::repeat_n(0_u8, BLOCK * 2)); + out + } + + fn p1_image(size: usize) -> Vec { + let mut fit = vec![0_u8; size]; + fit[..4].copy_from_slice(b"\xd0\x0d\xfe\xed"); + let marker = b"config@cv1835_miner_emmc"; + fit[0x100..0x100 + marker.len()].copy_from_slice(marker); + fit + } + + fn manifest(p1: &[u8]) -> serde_json::Value { + json!({ + "schema": 2, + "format": "afw", + "board": "cv1835", + "arch": "arm64", + "version": "0.1.0", + "build_date": "2026-11-04T00:00:00Z", + "sdk_revision": REV, + "os_revision": REV, + "payload_type": "os", + "bootloader_policy": "preserve", + "signature": {"type": "unsigned", "member": null, "public_key_hex": null}, + "partitions": [ + {"name": "p1", "device": "/dev/mmcblk0p1", "offset": 0, + "size": CV1835_P1_SIZE, "secure": false, "boot_critical": true, + "write_order": 1, "image": "p1"}, + {"name": "boot0", "device": "/dev/mmcblk0boot0", "offset": 0, + "size": 4194304, "secure": true, "boot_critical": true, + "write_order": 0, "image": null} + ], + "images": [ + {"name": "p1", "file": "payload/p1.fit", "role": "boot", + "format": "fit", "size": p1.len(), "sha256": hex(&Sha256::digest(p1)), + "partition": "p1", "install": true} + ], + "boot_switch": {"method": "partition-overwrite"}, + "preflight": {"required_commands": ["dd"]}, + "recovery": {"network": "afw restore"}, + "marker": "CVBOOT", + "kernel_version": "6.18.48" + }) + } + + fn bundle(p1: &[u8]) -> Vec { + let manifest = serde_json::to_vec(&manifest(p1)).unwrap(); + tar(&[("manifest.json", &manifest), ("payload/p1.fit", p1)]) + } + + fn options() -> VerifyOptions { + VerifyOptions { + allow_unsigned: true, + expect_board: None, + } + } + + #[test] + fn accepts_a_good_bundle() { + let p1 = p1_image(P1); + let verified = verify_afw_bytes(&bundle(&p1), &options()).unwrap(); + assert_eq!(verified.manifest.board, "cv1835"); + let (image, data) = verified.install_image().unwrap(); + assert_eq!(image.name, "p1"); + assert_eq!(data.len(), P1); + assert_eq!( + verified.install_partition().unwrap().device, + "/dev/mmcblk0p1" + ); + } + + #[test] + fn refuses_unsigned_without_the_flag() { + let p1 = p1_image(P1); + let mut opts = options(); + opts.allow_unsigned = false; + assert!(matches!( + verify_afw_bytes(&bundle(&p1), &opts), + Err(AfwError::Unsigned) + )); + } + + #[test] + fn refuses_a_one_byte_payload_change() { + let p1 = p1_image(P1); + let mut data = bundle(&p1); + let last = data.len() - BLOCK * 2 - 1; + data[last] ^= 0x01; + assert!(matches!( + verify_afw_bytes(&data, &options()), + Err(AfwError::Digest(_)) + )); + } + + #[test] + fn refuses_a_wrong_board_expectation() { + let p1 = p1_image(P1); + let mut opts = options(); + opts.expect_board = Some("zynq-7010".to_owned()); + assert!(matches!( + verify_afw_bytes(&bundle(&p1), &opts), + Err(AfwError::BoardMismatch { .. }) + )); + } + + #[test] + fn refuses_a_truncated_tar() { + let p1 = p1_image(P1); + let data = bundle(&p1); + assert!(matches!( + verify_afw_bytes(&data[..100], &options()), + Err(AfwError::Tar(_)) + )); + } + + #[test] + fn refuses_a_traversal_member() { + let p1 = p1_image(P1); + let manifest = serde_json::to_vec(&manifest(&p1)).unwrap(); + let data = tar(&[ + ("manifest.json", &manifest), + ("payload/../escape", p1.as_slice()), + ]); + assert!(matches!( + verify_afw_bytes(&data, &options()), + Err(AfwError::UnsafeName(_)) + )); + } + + #[test] + fn refuses_an_oversize_fit() { + let mut p1 = p1_image(P1); + p1.push(0); + let manifest = serde_json::to_vec(&manifest(&p1)).unwrap(); + let data = tar(&[("manifest.json", &manifest), ("payload/p1.fit", &p1)]); + assert!(matches!( + verify_afw_bytes(&data, &options()), + Err(AfwError::ImageTooLarge(_)) | Err(AfwError::Manifest(_)) + )); + } + + #[test] + fn refuses_a_bootloader_under_preserve() { + let p1 = p1_image(P1); + let mut value = manifest(&p1); + value["images"].as_array_mut().unwrap().push(json!({ + "name": "u-boot", "file": "payload/u-boot.img", "role": "bootloader", + "format": "uimage", "size": 4, "sha256": "0".repeat(64), + "partition": null, "install": false + })); + let mut body = serde_json::to_vec(&value).unwrap(); + body.extend_from_slice(&[0; 0]); + let u_boot = b"\x27\x05\x19\x56"; + let data = tar(&[ + ("manifest.json", &body), + ("payload/p1.fit", &p1), + ("payload/u-boot.img", u_boot), + ]); + assert!(matches!( + verify_afw_bytes(&data, &options()), + Err(AfwError::Manifest(_)) + )); + } + + #[test] + fn refuses_a_hash_mismatch() { + let p1 = p1_image(P1); + let mut value = manifest(&p1); + value["images"][0]["sha256"] = json!("1".repeat(64)); + let manifest = serde_json::to_vec(&value).unwrap(); + let data = tar(&[("manifest.json", &manifest), ("payload/p1.fit", &p1)]); + assert!(matches!( + verify_afw_bytes(&data, &options()), + Err(AfwError::Digest(_)) + )); + } + + #[test] + fn refuses_a_signed_bundle_it_cannot_verify() { + let p1 = p1_image(P1); + let mut value = manifest(&p1); + value["signature"] = json!({ + "type": "ed25519", + "member": "manifest.json.sig", + "public_key_hex": "0".repeat(64) + }); + let manifest = serde_json::to_vec(&value).unwrap(); + let data = tar(&[ + ("manifest.json", &manifest), + ("manifest.json.sig", &[0_u8; 64]), + ("payload/p1.fit", &p1), + ]); + assert!(matches!( + verify_afw_bytes(&data, &options()), + Err(AfwError::SignatureUnsupported) + )); + } +} diff --git a/crates/alkane-artifacts/src/lib.rs b/crates/alkane-artifacts/src/lib.rs index 12a60ba2..1833d76e 100644 --- a/crates/alkane-artifacts/src/lib.rs +++ b/crates/alkane-artifacts/src/lib.rs @@ -1,6 +1,8 @@ // SPDX-License-Identifier: MIT //! Verify local firmware artifacts before an install path consumes them. +pub mod afw; + use sha2::{Digest, Sha256}; use std::collections::HashSet; use std::fs::File; diff --git a/crates/alkane-cli/Cargo.toml b/crates/alkane-cli/Cargo.toml index 64a6fc75..76c1f7c1 100644 --- a/crates/alkane-cli/Cargo.toml +++ b/crates/alkane-cli/Cargo.toml @@ -7,3 +7,5 @@ license.workspace = true [dependencies] alkane-core = { path = "../alkane-core" } alkane-artifacts = { path = "../alkane-artifacts" } +alkane-flash = { path = "../alkane-flash" } +serde_json.workspace = true diff --git a/crates/alkane-cli/src/main.rs b/crates/alkane-cli/src/main.rs index 039c54bf..fa3f3d65 100644 --- a/crates/alkane-cli/src/main.rs +++ b/crates/alkane-cli/src/main.rs @@ -1,31 +1,624 @@ // SPDX-License-Identifier: MIT -//! Headless entry point for read-only artifact verification. +//! 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::{seed_manifest, verify_file}; -use std::path::Path; +use alkane_core::platform; +use alkane_flash::boards::cv1835::Cv1835Plan; +use alkane_flash::install::{ + install, restore, verify_live, InstallOptions, InstallOutcome, RestoreOptions, +}; +use alkane_flash::preflight::{preflight, PreflightOptions}; +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, + }) +} + +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)?; + 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)?; + let plan = Cv1835Plan::from_afw(&verified)?; + let (ssh, _secret) = ssh_options(&opts, DEFAULT_USER)?; + let mut transport = SshTransport::connect(ssh, true)?; + 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(()) +} + +fn run_install(args: &[String]) -> Result<(), Box> { + let opts = parse_args( + args, + &[ + ssh_values(), + &["held-backup", "backup-dir", "confirm", "expect-board"], + ] + .concat(), + &[ + "allow-unsigned", + "allow-unknown-source", + "check-golden", + "dry-run", + "no-reboot", + ], + )?; + let path = opts + .positionals + .first() + .ok_or("usage: alkane-cli afw install --host --dry-run|--confirm FLASH")?; + let verified = load_afw(path, &opts)?; + let plan = Cv1835Plan::from_afw(&verified)?; + 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")); + 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"], + ] + .concat(), + &["allow-unsigned"], + )?; + let (marker, kernel_version) = if let Some(path) = opts.positionals.first() { + let verified = load_afw(path, &opts)?; + let plan = Cv1835Plan::from_afw(&verified)?; + ( + opts.value("marker").unwrap_or(&plan.marker).to_owned(), + opts.value("kernel-version") + .unwrap_or(&plan.kernel_version) + .to_owned(), + ) + } else { + ( + opts.value("marker").unwrap_or("CVBOOT").to_owned(), + opts.value("kernel-version").unwrap_or("").to_owned(), + ) + }; + let host = opts.value("host").ok_or("--host is required")?.to_owned(); + let (ssh, _secret) = ssh_options(&opts, DEFAULT_USER)?; + let timeout = opts + .value("timeout") + .map(str::parse::) + .transpose()? + .unwrap_or(DEFAULT_TIMEOUT); + 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"]].concat(), + &["no-reboot"], + )?; + let (ssh, _secret) = ssh_options(&opts, DEFAULT_USER)?; + let mut transport = SshTransport::connect(ssh, true)?; + 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(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() +} + +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() { + "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), + other => Err(format!("unknown afw subcommand {other}").into()), + } +} fn run() -> Result<(), Box> { - let args: Vec<_> = std::env::args().collect(); - if args.len() != 4 || args[1] != "verify-artifact" { - return Err("usage: alkane-cli verify-artifact ".into()); + 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(()); } - let record = seed_manifest()? - .into_iter() - .find(|item| item.path == Path::new(&args[2])) - .ok_or("artifact path is absent from the seed manifest")?; - let verified = verify_file(Path::new(&args[3]), &record)?; - println!( - "verified {} {} {} bytes", - verified.record().family, - verified.record().format, - verified.record().size_bytes - ); - 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 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 [--timeout ] [ssh options]\n \ + alkane-cli afw restore --host --held-backup --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!("artifact verification failed: {error}"); + eprintln!("alkane-cli: {error}"); std::process::exit(1); } } diff --git a/crates/alkane-flash/Cargo.toml b/crates/alkane-flash/Cargo.toml index 98dce3c6..48d37808 100644 --- a/crates/alkane-flash/Cargo.toml +++ b/crates/alkane-flash/Cargo.toml @@ -7,6 +7,7 @@ license.workspace = true [dependencies] alkane-core = { path = "../alkane-core" } alkane-artifacts = { path = "../alkane-artifacts" } +serde_json.workspace = true sha2.workspace = true thiserror.workspace = true tempfile = "3" diff --git a/crates/alkane-flash/src/boards/cv1835.rs b/crates/alkane-flash/src/boards/cv1835.rs new file mode 100644 index 00000000..26b58112 --- /dev/null +++ b/crates/alkane-flash/src/boards/cv1835.rs @@ -0,0 +1,406 @@ +// SPDX-License-Identifier: MIT +//! CV1835 board module: the only write is the 16 MiB p1 FIT. +//! +//! The vendor boot0, BL2, BL31 and U-Boot chain is preserved. The board plan is +//! read from the verified `.afw` manifest, not guessed at runtime. + +use crate::md5::md5_hex; +use alkane_artifacts::afw::{ + AfwImage, AfwManifest, AfwPartition, BootloaderPolicy, VerifiedAfw, CV1835_P1_SIZE, +}; +use thiserror::Error; + +pub const BOARD: &str = "cv1835"; +pub const ARCH: &str = "arm64"; +pub const P1_DEVICE: &str = "/dev/mmcblk0p1"; +pub const MARKER: &str = "CVBOOT"; +pub const UPDATE_DAEMON_PORT: u16 = 12887; +pub const GOLDEN_LBA_BYTES: u64 = 0x300000 * 512; + +#[derive(Debug, Error)] +pub enum CvPlanError { + #[error("bundle is for {0}, not cv1835")] + WrongBoard(String), + #[error("bundle arch is {0}, cv1835 needs arm64")] + WrongArch(String), + #[error("cv1835 requires bootloader_policy preserve")] + BootloaderPolicy, + #[error("cv1835 bundle carries a bootloader member")] + BootloaderMember, + #[error("cv1835 bundle must install exactly p1")] + MissingP1, + #[error("cv1835 p1 is {0} bytes, not the 16 MiB padded FIT")] + P1Size(u64), + #[error("cv1835 p1 partition is not /dev/mmcblk0p1")] + P1Device, + #[error("cv1835 p1 partition must be 16 MiB, non-secure and written once")] + P1Geometry, + #[error("cv1835 p1 is not a bootable FIT: {0}")] + Fit(String), + #[error("manifest marker is empty")] + Marker, + #[error("manifest kernel_version is empty")] + KernelVersion, + #[error("manifest is not an OS payload")] + PayloadType, + #[error("manifest preflight is missing {0}")] + Preflight(String), +} + +#[derive(Clone, Debug)] +pub struct Cv1835Plan { + pub image: AfwImage, + pub data: Vec, + pub partition: AfwPartition, + pub expected_md5: String, + pub expected_sha256: String, + pub marker: String, + pub kernel_version: String, + pub sdk_revision: String, + pub os_revision: String, + pub source_os: Vec, + pub required_commands: Vec, + pub min_free_bytes: u64, + pub golden_lba_bytes: u64, +} + +impl Cv1835Plan { + pub fn from_afw(afw: &VerifiedAfw) -> Result { + let manifest = &afw.manifest; + if manifest.board != BOARD { + return Err(CvPlanError::WrongBoard(manifest.board.clone())); + } + if manifest.arch != ARCH { + return Err(CvPlanError::WrongArch(manifest.arch.clone())); + } + if manifest.payload_type != "os" { + return Err(CvPlanError::PayloadType); + } + if manifest.bootloader_policy != BootloaderPolicy::Preserve { + return Err(CvPlanError::BootloaderPolicy); + } + if manifest + .images + .iter() + .any(|image| image.role == "bootloader") + { + return Err(CvPlanError::BootloaderMember); + } + if manifest.marker.is_empty() { + return Err(CvPlanError::Marker); + } + if manifest.kernel_version.is_empty() { + return Err(CvPlanError::KernelVersion); + } + + let install: Vec<&AfwImage> = manifest + .images + .iter() + .filter(|image| image.install) + .collect(); + if install.len() != 1 || install[0].name != "p1" { + return Err(CvPlanError::MissingP1); + } + let image = install[0].clone(); + if image.format != "fit" { + return Err(CvPlanError::Fit("format is not fit".to_owned())); + } + if image.size != CV1835_P1_SIZE { + return Err(CvPlanError::P1Size(image.size)); + } + let (_, data) = afw.install_image().ok_or(CvPlanError::MissingP1)?; + if !data.starts_with(b"\xd0\x0d\xfe\xed") { + return Err(CvPlanError::Fit("missing FDT/FIT magic".to_owned())); + } + if !contains(data, b"config@cv1835_miner_emmc") { + return Err(CvPlanError::Fit( + "missing config@cv1835_miner_emmc".to_owned(), + )); + } + if contains(data, b"signature@") { + return Err(CvPlanError::Fit("carries signature@ nodes".to_owned())); + } + + let partition = manifest + .partitions + .iter() + .find(|part| part.name == "p1") + .ok_or(CvPlanError::P1Device)? + .clone(); + if partition.device != P1_DEVICE { + return Err(CvPlanError::P1Device); + } + if partition.size != CV1835_P1_SIZE + || partition.secure + || !partition.boot_critical + || partition.write_order != 1 + { + return Err(CvPlanError::P1Geometry); + } + if manifest + .partitions + .iter() + .any(|part| part.write_order > 0 && part.name != "p1") + { + return Err(CvPlanError::MissingP1); + } + + let source_os = json_strings(&manifest.preflight, "source_os"); + let required_commands = json_strings(&manifest.preflight, "required_commands"); + let min_free_bytes = manifest + .preflight + .get("min_free_bytes") + .and_then(|value| value.as_u64()) + .unwrap_or(32 * 1024 * 1024); + let golden_lba_bytes = manifest + .recovery + .get("golden_lba_bytes") + .and_then(|value| value.as_u64()) + .unwrap_or(GOLDEN_LBA_BYTES); + + Ok(Self { + expected_md5: md5_hex(data), + expected_sha256: image.sha256.clone(), + image, + data: data.to_vec(), + partition, + marker: manifest.marker.clone(), + kernel_version: manifest.kernel_version.clone(), + sdk_revision: manifest.sdk_revision.clone(), + os_revision: manifest.os_revision.clone(), + source_os, + required_commands, + min_free_bytes, + golden_lba_bytes, + }) + } + + pub fn render(&self) -> String { + format!( + "board cv1835 arch arm64\n\ + partition {} {} {} B secure=false boot_critical=true write_order={}\n\ + image {} {} {} B sha256 {}\n\ + image md5 {}\n\ + bootloader preserve (vendor boot0/BL2/BL31/U-Boot kept)\n\ + boot switch partition-overwrite (p1 is the switch)\n\ + marker {} kernel {} sdk {} os {}", + self.partition.name, + self.partition.device, + self.partition.size, + self.partition.write_order, + self.image.name, + self.image.file, + self.image.size, + self.image.sha256, + self.expected_md5, + self.marker, + self.kernel_version, + short_revision(&self.sdk_revision), + short_revision(&self.os_revision), + ) + } +} + +fn short_revision(revision: &str) -> &str { + revision.get(..12).unwrap_or(revision) +} + +fn contains(haystack: &[u8], needle: &[u8]) -> bool { + haystack + .windows(needle.len()) + .any(|window| window == needle) +} + +fn json_strings(value: &serde_json::Value, key: &str) -> Vec { + value + .get(key) + .and_then(|item| item.as_array()) + .map(|items| { + items + .iter() + .filter_map(|item| item.as_str().map(str::to_owned)) + .collect() + }) + .unwrap_or_default() +} + +pub fn manifest_from_json(value: serde_json::Value) -> Result { + serde_json::from_value(value) +} + +#[cfg(test)] +mod tests { + use super::*; + use alkane_artifacts::afw::AfwMember; + use serde_json::json; + use sha2::{Digest, Sha256}; + + const P1: usize = CV1835_P1_SIZE as usize; + const REV: &str = "0000000000000000000000000000000000000000"; + + fn sha_hex(data: &[u8]) -> String { + Sha256::digest(data) + .iter() + .map(|byte| format!("{byte:02x}")) + .collect() + } + + fn p1_image() -> Vec { + let mut fit = vec![0_u8; P1]; + fit[..4].copy_from_slice(b"\xd0\x0d\xfe\xed"); + let marker = b"config@cv1835_miner_emmc"; + fit[0x100..0x100 + marker.len()].copy_from_slice(marker); + fit + } + + fn manifest_value(p1: &[u8]) -> serde_json::Value { + json!({ + "schema": 2, + "format": "afw", + "board": "cv1835", + "arch": "arm64", + "version": "0.1.0", + "build_date": "2026-11-04T00:00:00Z", + "sdk_revision": REV, + "os_revision": REV, + "payload_type": "os", + "bootloader_policy": "preserve", + "signature": {"type": "unsigned", "member": null, "public_key_hex": null}, + "partitions": [ + {"name": "p1", "device": "/dev/mmcblk0p1", "offset": 0, + "size": CV1835_P1_SIZE, "secure": false, "boot_critical": true, + "write_order": 1, "image": "p1"}, + {"name": "boot0", "device": "/dev/mmcblk0boot0", "offset": 0, + "size": 4194304, "secure": true, "boot_critical": true, + "write_order": 0, "image": null} + ], + "images": [ + {"name": "p1", "file": "payload/p1.fit", "role": "boot", + "format": "fit", "size": p1.len(), + "sha256": sha_hex(p1), + "partition": "p1", "install": true} + ], + "boot_switch": {"method": "partition-overwrite"}, + "preflight": {"required_commands": ["dd", "md5sum", "sync"], + "source_os": ["stock-bitmain", "vnish", "braiins", "ouros", "alkane"], + "min_free_bytes": 33554432}, + "recovery": {"network": "afw restore", "golden_lba_bytes": GOLDEN_LBA_BYTES}, + "marker": "CVBOOT", + "kernel_version": "6.18.48" + }) + } + + fn afw(p1: &[u8]) -> VerifiedAfw { + let manifest = manifest_from_json(manifest_value(p1)).unwrap(); + VerifiedAfw { + manifest, + members: vec![AfwMember { + name: "payload/p1.fit".to_owned(), + data: p1.to_vec(), + }], + manifest_sha256: "0".repeat(64), + archive_sha256: "0".repeat(64), + } + } + + #[test] + fn accepts_the_cv_plan() { + let data = p1_image(); + let plan = Cv1835Plan::from_afw(&afw(&data)).unwrap(); + assert_eq!(plan.partition.device, "/dev/mmcblk0p1"); + assert_eq!(plan.image.size, CV1835_P1_SIZE); + assert_eq!(plan.marker, "CVBOOT"); + assert!(plan + .render() + .contains("partition p1 /dev/mmcblk0p1 16777216")); + } + + #[test] + fn refuses_a_bundle_for_another_board() { + let data = p1_image(); + let mut verified = afw(&data); + verified.manifest.board = "zynq-7010".to_owned(); + assert!(matches!( + Cv1835Plan::from_afw(&verified), + Err(CvPlanError::WrongBoard(_)) + )); + } + + #[test] + fn refuses_include_bootloader_policy() { + let data = p1_image(); + let mut verified = afw(&data); + verified.manifest.bootloader_policy = BootloaderPolicy::Include; + assert!(matches!( + Cv1835Plan::from_afw(&verified), + Err(CvPlanError::BootloaderPolicy) + )); + } + + #[test] + fn refuses_a_bootloader_member() { + let data = p1_image(); + let mut verified = afw(&data); + verified.manifest.images.push(AfwImage { + name: "u-boot".to_owned(), + file: "payload/u-boot.img".to_owned(), + role: "bootloader".to_owned(), + format: "uimage".to_owned(), + size: 4, + sha256: "0".repeat(64), + partition: None, + install: false, + }); + assert!(matches!( + Cv1835Plan::from_afw(&verified), + Err(CvPlanError::BootloaderMember) + )); + } + + #[test] + fn refuses_a_short_p1() { + let data = vec![0_u8; 1024]; + let verified = afw(&data); + assert!(matches!( + Cv1835Plan::from_afw(&verified), + Err(CvPlanError::P1Size(1024)) + )); + } + + #[test] + fn refuses_a_secure_p1() { + let data = p1_image(); + let mut verified = afw(&data); + verified.manifest.partitions[0].secure = true; + assert!(matches!( + Cv1835Plan::from_afw(&verified), + Err(CvPlanError::P1Geometry) + )); + } + + #[test] + fn refuses_a_wrong_device() { + let data = p1_image(); + let mut verified = afw(&data); + verified.manifest.partitions[0].device = "/dev/mmcblk0p3".to_owned(); + assert!(matches!( + Cv1835Plan::from_afw(&verified), + Err(CvPlanError::P1Device) + )); + } + + #[test] + fn refuses_a_fit_without_the_board_config() { + let mut data = p1_image(); + for byte in data.iter_mut() { + if *byte == b'c' { + *byte = b'x'; + } + } + let verified = afw(&data); + assert!(matches!( + Cv1835Plan::from_afw(&verified), + Err(CvPlanError::Fit(_)) + )); + } +} diff --git a/crates/alkane-flash/src/boards/mod.rs b/crates/alkane-flash/src/boards/mod.rs new file mode 100644 index 00000000..37d9db02 --- /dev/null +++ b/crates/alkane-flash/src/boards/mod.rs @@ -0,0 +1,5 @@ +// SPDX-License-Identifier: MIT +//! Board modules. Each module validates the verified manifest for its family +//! and exposes the exact write plan the installer follows. + +pub mod cv1835; diff --git a/crates/alkane-flash/src/install.rs b/crates/alkane-flash/src/install.rs new file mode 100644 index 00000000..bae9c9eb --- /dev/null +++ b/crates/alkane-flash/src/install.rs @@ -0,0 +1,920 @@ +// SPDX-License-Identifier: MIT +//! CV1835 install, restore and live verification over the network. +//! +//! Order of operations for an install: verify the bundle, preflight the board, +//! hold the current p1 over SSH, stage the new p1, write it once, read the whole +//! partition back, and only then reboot. Any doubt before the first write stops +//! the sequence. A read-back mismatch stops before reboot and prints the exact +//! restore command. + +use crate::boards::cv1835::{Cv1835Plan, CvPlanError}; +use crate::md5::md5_hex; +use crate::preflight::{preflight, PreflightError, PreflightOptions, PreflightReport}; +use crate::transport::{Remote, RemoteError, SshOptions, SshTransport}; +use alkane_artifacts::afw::{AfwError, VerifiedAfw}; +use sha2::{Digest, Sha256}; +use std::fs; +use std::io::{Read, Write}; +use std::net::{TcpStream, ToSocketAddrs}; +use std::path::{Path, PathBuf}; +use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; +use thiserror::Error; + +const REMOTE_BACKUP: &str = "/tmp/.alkane-p1-backup.img"; +const REMOTE_STAGE: &str = "/tmp/.alkane-p1-stage.img"; + +#[derive(Debug, Error)] +pub enum InstallError { + #[error("preflight failed; do not write\n{0}")] + Preflight(String), + #[error("install and restore need --confirm FLASH")] + Confirm, + #[error("verified .afw: {0}")] + Afw(#[from] AfwError), + #[error("cv1835 plan: {0}")] + Plan(#[from] CvPlanError), + #[error("preflight: {0}")] + PreflightError(#[from] PreflightError), + #[error("remote: {0}")] + Remote(#[from] RemoteError), + #[error("I/O: {0}")] + Io(#[from] std::io::Error), + #[error("backup {0} is not the 16 MiB p1 size")] + BackupSize(PathBuf), + #[error("backup md5 does not match the live p1; refusing to continue")] + BackupMismatch, + #[error("staged image md5 does not match the verified bundle; nothing written")] + StageMismatch, + #[error("p1 read-back md5 mismatch; do not reboot. Restore with: {0}")] + Readback(String), + #[error("restore read-back md5 mismatch; the board may still hold the new image")] + RestoreReadback, +} + +#[derive(Clone, Debug)] +pub struct InstallOptions { + pub dry_run: bool, + pub confirm: Option, + pub no_reboot: bool, + pub backup_dir: PathBuf, + pub held_backup: Option, + pub allow_unknown_source: bool, + pub check_golden: bool, +} + +impl Default for InstallOptions { + fn default() -> Self { + Self { + dry_run: false, + confirm: None, + no_reboot: false, + backup_dir: default_backup_dir(), + held_backup: None, + allow_unknown_source: false, + check_golden: false, + } + } +} + +#[derive(Clone, Debug)] +pub struct InstallReceipt { + pub backup_path: PathBuf, + pub backup_md5: String, + pub backup_sha256: String, + pub image_md5: String, + pub rebooted: bool, +} + +#[derive(Clone, Debug)] +pub enum InstallOutcome { + DryRun(Box), + Installed(InstallReceipt), +} + +pub fn install( + _afw: &VerifiedAfw, + plan: &Cv1835Plan, + remote: &mut dyn Remote, + options: &InstallOptions, + host: &str, +) -> Result { + let report = preflight( + plan, + remote, + &PreflightOptions { + host, + held_backup: options.held_backup.as_deref(), + check_golden: options.check_golden, + allow_unknown_source: options.allow_unknown_source, + }, + )?; + if !report.ok() { + return Err(InstallError::Preflight(report.render())); + } + if options.dry_run { + return Ok(InstallOutcome::DryRun(Box::new(report))); + } + if options.confirm.as_deref() != Some("FLASH") { + return Err(InstallError::Confirm); + } + + fs::create_dir_all(&options.backup_dir)?; + let epoch = SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap_or_default() + .as_secs(); + let backup_path = options.backup_dir.join(format!("p1-{epoch}.img")); + let device = &plan.partition.device; + + // Hold the current p1 as root, then pull it over the unprivileged SSH + // session. The daemon channel is blind, so this two-step path is required. + let remote_backup = REMOTE_BACKUP; + remote.root_command( + &format!("dd if={device} of={remote_backup} bs=1M 2>&1; chmod 644 {remote_backup}"), + Duration::from_secs(180), + )?; + remote.pull(remote_backup, &backup_path, Duration::from_secs(240))?; + let _ = remote.root_command(&format!("rm -f {remote_backup}"), Duration::from_secs(15)); + let backup_data = fs::read(&backup_path)?; + if backup_data.len() as u64 != plan.partition.size { + return Err(InstallError::BackupSize(backup_path)); + } + let backup_md5 = md5_hex(&backup_data); + if report.live_md5 != "unreadable" && backup_md5 != report.live_md5 { + return Err(InstallError::BackupMismatch); + } + let backup_sha256: String = Sha256::digest(&backup_data) + .iter() + .map(|byte| format!("{byte:02x}")) + .collect(); + write_sidecars( + &backup_path, + &backup_md5, + &backup_sha256, + &plan.partition, + &plan.expected_sha256, + epoch, + )?; + + stage_and_write(plan, remote, &backup_path)?; + + let rebooted = if options.no_reboot { + false + } else { + remote.reboot()?; + true + }; + Ok(InstallOutcome::Installed(InstallReceipt { + backup_path, + backup_md5, + backup_sha256, + image_md5: plan.expected_md5.clone(), + rebooted, + })) +} + +fn stage_and_write( + plan: &Cv1835Plan, + remote: &mut dyn Remote, + backup_path: &Path, +) -> Result<(), InstallError> { + let mut staged = + tempfile::NamedTempFile::new_in(backup_path.parent().unwrap_or_else(|| Path::new(".")))?; + staged.write_all(&plan.data)?; + staged.flush()?; + remote.push(staged.path(), REMOTE_STAGE, Duration::from_secs(240))?; + let staged_md5 = + remote.root_command(&format!("md5sum {REMOTE_STAGE}"), Duration::from_secs(60))?; + let staged_md5 = String::from_utf8_lossy(&staged_md5) + .split_whitespace() + .next() + .unwrap_or("") + .to_ascii_lowercase(); + if staged_md5 != plan.expected_md5 { + let _ = remote.root_command(&format!("rm -f {REMOTE_STAGE}"), Duration::from_secs(15)); + return Err(InstallError::StageMismatch); + } + + remote.root_command( + &format!( + "dd if={REMOTE_STAGE} of={} bs=1M conv=fsync 2>&1; sync", + plan.partition.device + ), + Duration::from_secs(240), + )?; + let readback = remote.root_command( + &format!("md5sum {}", plan.partition.device), + Duration::from_secs(90), + )?; + let readback = String::from_utf8_lossy(&readback) + .split_whitespace() + .next() + .unwrap_or("") + .to_ascii_lowercase(); + let _ = remote.root_command(&format!("rm -f {REMOTE_STAGE}"), Duration::from_secs(15)); + if readback != plan.expected_md5 { + return Err(InstallError::Readback(restore_command( + &plan.partition.device, + backup_path, + ))); + } + Ok(()) +} + +#[derive(Clone, Debug)] +pub struct RestoreOptions { + pub confirm: Option, + pub no_reboot: bool, +} + +#[derive(Clone, Debug)] +pub struct RestoreReceipt { + pub backup_path: PathBuf, + pub image_md5: String, + pub rebooted: bool, +} + +pub fn restore( + backup: &Path, + remote: &mut dyn Remote, + options: &RestoreOptions, +) -> Result { + if options.confirm.as_deref() != Some("FLASH") { + return Err(InstallError::Confirm); + } + let data = fs::read(backup)?; + if data.len() != 16 * 1024 * 1024 { + return Err(InstallError::BackupSize(backup.to_path_buf())); + } + let md5 = md5_hex(&data); + let sha256: String = Sha256::digest(&data) + .iter() + .map(|byte| format!("{byte:02x}")) + .collect(); + if let Some(sidecar) = read_sidecar(backup) { + if sidecar != sha256 { + return Err(InstallError::BackupMismatch); + } + } + + let root_uid = String::from_utf8_lossy(&remote.root_command("id -u", Duration::from_secs(20))?) + .trim() + .to_owned(); + if root_uid != "0" { + return Err(InstallError::Preflight(format!( + "root channel returned uid {root_uid}" + ))); + } + let size = remote.user_command( + "cat /sys/class/block/mmcblk0p1/size 2>/dev/null || true", + Duration::from_secs(15), + )?; + let sectors: u64 = String::from_utf8_lossy(&size).trim().parse().unwrap_or(0); + if sectors.saturating_mul(512) != 16 * 1024 * 1024 { + return Err(InstallError::Preflight( + "the board does not expose a 16 MiB /dev/mmcblk0p1".to_owned(), + )); + } + + let staged = tempfile::NamedTempFile::new()?; + fs::write(staged.path(), &data)?; + remote.push(staged.path(), REMOTE_STAGE, Duration::from_secs(240))?; + let staged_md5 = + remote.root_command(&format!("md5sum {REMOTE_STAGE}"), Duration::from_secs(60))?; + let staged_md5 = String::from_utf8_lossy(&staged_md5) + .split_whitespace() + .next() + .unwrap_or("") + .to_ascii_lowercase(); + if staged_md5 != md5 { + let _ = remote.root_command(&format!("rm -f {REMOTE_STAGE}"), Duration::from_secs(15)); + return Err(InstallError::StageMismatch); + } + remote.root_command( + &format!("dd if={REMOTE_STAGE} of=/dev/mmcblk0p1 bs=1M conv=fsync 2>&1; sync"), + Duration::from_secs(240), + )?; + let readback = remote.root_command("md5sum /dev/mmcblk0p1", Duration::from_secs(90))?; + let readback = String::from_utf8_lossy(&readback) + .split_whitespace() + .next() + .unwrap_or("") + .to_ascii_lowercase(); + let _ = remote.root_command(&format!("rm -f {REMOTE_STAGE}"), Duration::from_secs(15)); + if readback != md5 { + return Err(InstallError::RestoreReadback); + } + let rebooted = if options.no_reboot { + false + } else { + remote.reboot()?; + true + }; + Ok(RestoreReceipt { + backup_path: backup.to_path_buf(), + image_md5: md5, + rebooted, + }) +} + +fn restore_command(device: &str, backup: &Path) -> String { + format!( + "alkane-cli afw restore --host --held-backup {} --confirm FLASH (the held copy of {device} is at {})", + backup.display(), + backup.display() + ) +} + +fn default_backup_dir() -> PathBuf { + alkane_core::platform::config_path("backups") +} + +fn write_sidecars( + path: &Path, + md5: &str, + sha256: &str, + partition: &alkane_artifacts::afw::AfwPartition, + image_sha256: &str, + epoch: u64, +) -> Result<(), InstallError> { + let file_name = path + .file_name() + .map(|name| name.to_string_lossy().into_owned()) + .unwrap_or_else(|| "p1.img".to_owned()); + fs::write( + path.with_extension("img.sha256"), + format!("{sha256} {file_name}\n"), + )?; + let metadata = serde_json::json!({ + "board": "cv1835", + "partition": partition.name, + "device": partition.device, + "size": partition.size, + "md5": md5, + "sha256": sha256, + "afw_sha256": image_sha256, + "created_unix": epoch, + }); + fs::write( + path.with_extension("img.json"), + serde_json::to_vec_pretty(&metadata).unwrap_or_default(), + )?; + Ok(()) +} + +fn read_sidecar(path: &Path) -> Option { + let text = fs::read_to_string(path.with_extension("img.sha256")).ok()?; + text.split_whitespace().next().map(str::to_owned) +} + +#[derive(Clone, Debug)] +pub struct LiveReport { + pub attempts: u32, + pub http: String, + pub http_ok: bool, + pub ssh: String, + pub ssh_ok: bool, + pub api: String, + pub api_ok: bool, +} + +impl LiveReport { + pub fn ok(&self) -> bool { + self.http_ok && self.ssh_ok && self.api_ok + } + + pub fn render(&self) -> String { + format!( + "verify-live attempts {}\n http {}: {}\n ssh {}: {}\n api {}: {}\nresult {}", + self.attempts, + if self.http_ok { "ok" } else { "FAIL" }, + self.http, + if self.ssh_ok { "ok" } else { "FAIL" }, + self.ssh, + if self.api_ok { "ok" } else { "FAIL" }, + self.api, + if self.ok() { "PASS" } else { "FAIL" } + ) + } +} + +pub fn verify_live( + host: &str, + marker: &str, + kernel_version: &str, + timeout: Duration, + ssh_options: &SshOptions, +) -> LiveReport { + let deadline = Instant::now() + timeout; + let mut attempts = 0; + loop { + attempts += 1; + let (http, http_ok) = match http_get(host, "/", Duration::from_secs(5)) { + Ok(body) => { + let ok = body.contains(marker); + ( + if ok { + format!("marker {marker} present") + } else { + format!("marker {marker} absent ({} bytes)", body.len()) + }, + ok, + ) + } + Err(error) => (error, false), + }; + let (ssh, ssh_ok) = match SshTransport::connect(ssh_options.clone(), false) { + Ok(mut session) => match session.user_command("uname -r", Duration::from_secs(15)) { + Ok(output) => { + let kernel = String::from_utf8_lossy(&output).trim().to_owned(); + let ok = !kernel.is_empty() + && (kernel_version.is_empty() || kernel.contains(kernel_version)); + ( + format!( + "kernel {kernel}{}", + if ok { + "" + } else { + " (expected the installed kernel)" + } + ), + ok, + ) + } + Err(error) => (format!("{error}"), false), + }, + Err(error) => (format!("{error}"), false), + }; + let (api, api_ok) = match api_version(host, Duration::from_secs(5)) { + Ok(body) => { + let ok = body.contains("\"STATUS\"") + || body.contains("\"VERSION\"") + || body.to_lowercase().contains("version"); + (format!("{} bytes", body.len()), ok) + } + Err(error) => (error, false), + }; + if http_ok && ssh_ok && api_ok { + return LiveReport { + attempts, + http, + http_ok, + ssh, + ssh_ok, + api, + api_ok, + }; + } + if Instant::now() >= deadline { + return LiveReport { + attempts, + http, + http_ok, + ssh, + ssh_ok, + api, + api_ok, + }; + } + std::thread::sleep(Duration::from_secs(5)); + } +} + +fn http_get(host: &str, path: &str, timeout: Duration) -> Result { + let address = (host, 80_u16) + .to_socket_addrs() + .map_err(|error| format!("resolve: {error}"))? + .next() + .ok_or_else(|| "no address".to_owned())?; + let mut stream = TcpStream::connect_timeout(&address, timeout) + .map_err(|error| format!("connect: {error}"))?; + stream + .set_read_timeout(Some(timeout)) + .map_err(|error| error.to_string())?; + let request = format!("GET {path} HTTP/1.0\r\nHost: {host}\r\nConnection: close\r\n\r\n"); + stream + .write_all(request.as_bytes()) + .map_err(|error| error.to_string())?; + let mut data = Vec::new(); + let mut buffer = [0_u8; 8192]; + loop { + match stream.read(&mut buffer) { + Ok(0) => break, + Ok(read) => { + data.extend_from_slice(&buffer[..read]); + if data.len() > 512 * 1024 { + break; + } + } + Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => break, + Err(error) if error.kind() == std::io::ErrorKind::TimedOut => break, + Err(error) => return Err(error.to_string()), + } + } + let text = String::from_utf8_lossy(&data).into_owned(); + let status_ok = text + .lines() + .next() + .map(|line| line.contains(" 200 ") || line.ends_with(" 200")) + .unwrap_or(false); + if status_ok { + Ok(text) + } else { + Err(text.lines().next().unwrap_or("no HTTP response").to_owned()) + } +} + +fn api_version(host: &str, timeout: Duration) -> Result { + let address = (host, 4028_u16) + .to_socket_addrs() + .map_err(|error| format!("resolve: {error}"))? + .next() + .ok_or_else(|| "no address".to_owned())?; + let mut stream = TcpStream::connect_timeout(&address, timeout) + .map_err(|error| format!("connect: {error}"))?; + stream + .set_read_timeout(Some(timeout)) + .map_err(|error| error.to_string())?; + stream + .write_all(b"{\"command\":\"version\"}\n") + .map_err(|error| error.to_string())?; + let mut data = Vec::new(); + let mut buffer = [0_u8; 4096]; + loop { + match stream.read(&mut buffer) { + Ok(0) => break, + Ok(read) => { + data.extend_from_slice(&buffer[..read]); + if data.len() > 64 * 1024 { + break; + } + } + Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => break, + Err(error) if error.kind() == std::io::ErrorKind::TimedOut => break, + Err(error) => return Err(error.to_string()), + } + } + let text = String::from_utf8_lossy(&data).trim().to_owned(); + if text.is_empty() { + Err("no API response".to_owned()) + } else { + Ok(text) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn derives_backup_sidecar_names() { + let path = Path::new("/tmp/p1-1.img"); + assert_eq!( + path.with_extension("img.sha256"), + Path::new("/tmp/p1-1.img.sha256") + ); + assert_eq!( + path.with_extension("img.json"), + Path::new("/tmp/p1-1.img.json") + ); + } + + #[test] + fn restore_command_names_the_held_copy() { + let command = restore_command("/dev/mmcblk0p1", Path::new("/tmp/p1.img")); + assert!(command.contains("afw restore")); + assert!(command.contains("/tmp/p1.img")); + } +} + +#[cfg(test)] +mod network_tests { + use super::*; + use alkane_artifacts::afw::{AfwImage, AfwManifest, AfwMember, AfwPartition, BootloaderPolicy}; + use serde_json::json; + use std::collections::HashMap; + + const P1: usize = 16 * 1024 * 1024; + const REV: &str = "0000000000000000000000000000000000000000"; + + struct MockRemote { + partition: Vec, + files: HashMap>, + commands: Vec, + rebooted: bool, + readback_corrupt: bool, + } + + impl MockRemote { + fn new(partition: Vec) -> Self { + Self { + partition, + files: HashMap::new(), + commands: Vec::new(), + rebooted: false, + readback_corrupt: false, + } + } + + fn md5(&self, data: &[u8]) -> String { + md5_hex(data) + } + } + + impl Remote for MockRemote { + fn channel(&self) -> &str { + "mock" + } + + fn root_method(&self) -> &'static str { + "direct" + } + + fn user_command( + &mut self, + command: &str, + _timeout: Duration, + ) -> Result, RemoteError> { + self.commands.push(command.to_owned()); + let text = if command.contains("uname -r") { + "6.18.48\n__MODEL__\nAlkane CV1835\n__RELEASE__\nalkane\n".to_owned() + } else if command.contains("test -b") { + "block".to_owned() + } else if command.contains("/sys/class/block/mmcblk0p1/size") { + "32768".to_owned() + } else if command.contains("for c in dd") { + "dd\nmd5sum\nsync\n".to_owned() + } else if command.contains("df -k") { + "Filesystem 1K-blocks Used Available Use% Mounted on\n/dev/root 100000 1 90000 1% /tmp\n".to_owned() + } else if command.contains("mmcblk0boot0") { + "yes".to_owned() + } else { + String::new() + }; + Ok(text.into_bytes()) + } + + fn root_command( + &mut self, + command: &str, + _timeout: Duration, + ) -> Result, RemoteError> { + self.commands.push(command.to_owned()); + if command.starts_with("id -u") || command == "id" { + return Ok(b"0\n".to_vec()); + } + if let Some(rest) = command.strip_prefix("md5sum /dev/mmcblk0p1") { + let _ = rest; + let mut data = self.partition.clone(); + if self.readback_corrupt && self.files.contains_key(REMOTE_STAGE) { + if let Some(last) = data.last_mut() { + *last ^= 0xff; + } + self.readback_corrupt = false; + } + return Ok(format!("{} /dev/mmcblk0p1\n", self.md5(&data)).into_bytes()); + } + if let Some(rest) = command.strip_prefix("md5sum ") { + let path = rest.split_whitespace().next().unwrap_or(""); + let data = self.files.get(path).cloned().unwrap_or_default(); + return Ok(format!("{} {path}\n", self.md5(&data)).into_bytes()); + } + if let Some(rest) = command.strip_prefix("dd if=") { + let mut parts = rest.splitn(2, " of="); + let source = parts.next().unwrap_or(""); + let target = parts + .next() + .unwrap_or("") + .split_whitespace() + .next() + .unwrap_or(""); + if source == "/dev/mmcblk0p1" { + self.files.insert(target.to_owned(), self.partition.clone()); + } else if target == "/dev/mmcblk0p1" { + if let Some(data) = self.files.get(source).cloned() { + self.partition = data; + } + } + return Ok(Vec::new()); + } + if command.starts_with("rm -f ") { + let path = command.trim_start_matches("rm -f ").trim(); + self.files.remove(path); + return Ok(Vec::new()); + } + Ok(Vec::new()) + } + + fn push( + &mut self, + local: &Path, + remote: &str, + _timeout: Duration, + ) -> Result<(), RemoteError> { + self.files.insert(remote.to_owned(), fs::read(local)?); + Ok(()) + } + + fn pull( + &mut self, + remote: &str, + local: &Path, + _timeout: Duration, + ) -> Result<(), RemoteError> { + let data = self + .files + .get(remote) + .cloned() + .ok_or_else(|| RemoteError::Daemon("missing file".to_owned()))?; + fs::write(local, data)?; + Ok(()) + } + + fn reboot(&mut self) -> Result<(), RemoteError> { + self.rebooted = true; + Ok(()) + } + } + + fn p1_image() -> Vec { + let mut fit = vec![0_u8; P1]; + fit[..4].copy_from_slice(b"\xd0\x0d\xfe\xed"); + let marker = b"config@cv1835_miner_emmc"; + fit[0x100..0x100 + marker.len()].copy_from_slice(marker); + fit + } + + fn verified(data: &[u8]) -> VerifiedAfw { + let manifest = AfwManifest { + schema: 2, + format: "afw".to_owned(), + board: "cv1835".to_owned(), + arch: "arm64".to_owned(), + version: "0.1.0".to_owned(), + build_date: "2026-11-04T00:00:00Z".to_owned(), + sdk_revision: REV.to_owned(), + os_revision: REV.to_owned(), + payload_type: "os".to_owned(), + bootloader_policy: BootloaderPolicy::Preserve, + signature: alkane_artifacts::afw::AfwSignature { + kind: "unsigned".to_owned(), + member: None, + public_key_hex: None, + }, + partitions: vec![ + AfwPartition { + name: "p1".to_owned(), + device: "/dev/mmcblk0p1".to_owned(), + offset: 0, + size: P1 as u64, + secure: false, + boot_critical: true, + write_order: 1, + image: Some("p1".to_owned()), + }, + AfwPartition { + name: "boot0".to_owned(), + device: "/dev/mmcblk0boot0".to_owned(), + offset: 0, + size: 4 * 1024 * 1024, + secure: true, + boot_critical: true, + write_order: 0, + image: None, + }, + ], + images: vec![AfwImage { + name: "p1".to_owned(), + file: "payload/p1.fit".to_owned(), + role: "boot".to_owned(), + format: "fit".to_owned(), + size: P1 as u64, + sha256: Sha256::digest(data) + .iter() + .map(|byte| format!("{byte:02x}")) + .collect(), + partition: Some("p1".to_owned()), + install: true, + }], + boot_switch: json!({"method": "partition-overwrite"}), + preflight: json!({"required_commands": ["dd", "md5sum", "sync"], + "source_os": ["stock-bitmain", "vnish", "braiins", "ouros", "alkane"], + "min_free_bytes": 33554432}), + recovery: json!({"network": "afw restore", "golden_lba_bytes": 0x300000u64 * 512}), + marker: "Alkane".to_owned(), + kernel_version: "6.18.48".to_owned(), + notes: None, + }; + VerifiedAfw { + manifest, + members: vec![AfwMember { + name: "payload/p1.fit".to_owned(), + data: data.to_vec(), + }], + manifest_sha256: "0".repeat(64), + archive_sha256: "0".repeat(64), + } + } + + #[test] + fn installs_p1_holds_a_backup_and_verifies_before_reboot() { + let original = vec![0x11_u8; P1]; + let new = p1_image(); + let afw = verified(&new); + let plan = Cv1835Plan::from_afw(&afw).unwrap(); + let mut remote = MockRemote::new(original.clone()); + let temp = tempfile::tempdir().unwrap(); + let options = InstallOptions { + dry_run: false, + confirm: Some("FLASH".to_owned()), + no_reboot: true, + backup_dir: temp.path().to_path_buf(), + held_backup: None, + allow_unknown_source: true, + check_golden: false, + }; + let outcome = install(&afw, &plan, &mut remote, &options, "10.255.1.1").unwrap(); + let InstallOutcome::Installed(receipt) = outcome else { + panic!("expected an install"); + }; + assert_eq!(remote.partition, new); + assert_eq!(receipt.backup_md5, md5_hex(&original)); + assert!(receipt.backup_path.is_file()); + assert!(!remote.rebooted); + assert!(remote + .commands + .iter() + .any(|command| command.starts_with("dd if=/tmp/.alkane-p1-stage.img"))); + } + + #[test] + fn dry_run_never_writes_the_partition() { + let original = vec![0x22_u8; P1]; + let new = p1_image(); + let afw = verified(&new); + let plan = Cv1835Plan::from_afw(&afw).unwrap(); + let mut remote = MockRemote::new(original.clone()); + let temp = tempfile::tempdir().unwrap(); + let options = InstallOptions { + dry_run: true, + confirm: None, + no_reboot: false, + backup_dir: temp.path().to_path_buf(), + held_backup: None, + allow_unknown_source: true, + check_golden: false, + }; + let outcome = install(&afw, &plan, &mut remote, &options, "10.255.1.1").unwrap(); + assert!(matches!(outcome, InstallOutcome::DryRun(_))); + assert_eq!(remote.partition, original); + assert!(!remote + .commands + .iter() + .any(|command| command.starts_with("dd if=/tmp/.alkane-p1-stage.img"))); + } + + #[test] + fn a_readback_mismatch_stops_before_reboot() { + let original = vec![0x33_u8; P1]; + let new = p1_image(); + let afw = verified(&new); + let plan = Cv1835Plan::from_afw(&afw).unwrap(); + let mut remote = MockRemote::new(original); + remote.readback_corrupt = true; + let temp = tempfile::tempdir().unwrap(); + let options = InstallOptions { + dry_run: false, + confirm: Some("FLASH".to_owned()), + no_reboot: false, + backup_dir: temp.path().to_path_buf(), + held_backup: None, + allow_unknown_source: true, + check_golden: false, + }; + let result = install(&afw, &plan, &mut remote, &options, "10.255.1.1"); + assert!(matches!(result, Err(InstallError::Readback(_)))); + assert!(!remote.rebooted); + } + + #[test] + fn confirm_is_required_before_any_device_write() { + let original = vec![0x44_u8; P1]; + let new = p1_image(); + let afw = verified(&new); + let plan = Cv1835Plan::from_afw(&afw).unwrap(); + let mut remote = MockRemote::new(original.clone()); + let temp = tempfile::tempdir().unwrap(); + let options = InstallOptions { + dry_run: false, + confirm: None, + no_reboot: false, + backup_dir: temp.path().to_path_buf(), + held_backup: None, + allow_unknown_source: true, + check_golden: false, + }; + let result = install(&afw, &plan, &mut remote, &options, "10.255.1.1"); + assert!(matches!(result, Err(InstallError::Confirm))); + assert_eq!(remote.partition, original); + } +} diff --git a/crates/alkane-flash/src/lib.rs b/crates/alkane-flash/src/lib.rs index b9a9cb98..b8c6e6fa 100644 --- a/crates/alkane-flash/src/lib.rs +++ b/crates/alkane-flash/src/lib.rs @@ -1,6 +1,16 @@ // SPDX-License-Identifier: MIT -//! Guarded write sequence for a verified artifact and an SDK partition plan. -//! Board transport adapters must supply serial, recovery and readback evidence. +//! Guarded writes plus the network-only CV1835 installer. +//! +//! The original guarded-write helpers remain for boards that need an attached +//! recovery channel. CV1835 uses the network modules below: a verified `.afw`, +//! a board plan, an SSH transport with a stock-root stage, a read-only +//! preflight, a whole-partition read-back and a network restore. + +pub mod boards; +pub mod install; +pub mod md5; +pub mod preflight; +pub mod transport; use alkane_artifacts::VerifiedArtifact; use sha2::{Digest, Sha256}; diff --git a/crates/alkane-flash/src/md5.rs b/crates/alkane-flash/src/md5.rs new file mode 100644 index 00000000..ce6815ad --- /dev/null +++ b/crates/alkane-flash/src/md5.rs @@ -0,0 +1,116 @@ +// SPDX-License-Identifier: MIT +//! MD5 for the CV1835 whole-partition read-back. +//! +//! The stock busybox on this board ships `md5sum` but not `sha256sum`, and the +//! proven installer gates the write on a whole-partition md5. This module is a +//! small RFC 1321 implementation so the host can compare the same digest +//! without shelling out to a tool that may not exist. + +const S: [u32; 64] = [ + 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, + 14, 20, 5, 9, 14, 20, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 6, 10, 15, + 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, +]; + +const K: [u32; 64] = [ + 0xd76aa478, 0xe8c7b756, 0x242070db, 0xc1bdceee, 0xf57c0faf, 0x4787c62a, 0xa8304613, 0xfd469501, + 0x698098d8, 0x8b44f7af, 0xffff5bb1, 0x895cd7be, 0x6b901122, 0xfd987193, 0xa679438e, 0x49b40821, + 0xf61e2562, 0xc040b340, 0x265e5a51, 0xe9b6c7aa, 0xd62f105d, 0x02441453, 0xd8a1e681, 0xe7d3fbc8, + 0x21e1cde6, 0xc33707d6, 0xf4d50d87, 0x455a14ed, 0xa9e3e905, 0xfcefa3f8, 0x676f02d9, 0x8d2a4c8a, + 0xfffa3942, 0x8771f681, 0x6d9d6122, 0xfde5380c, 0xa4beea44, 0x4bdecfa9, 0xf6bb4b60, 0xbebfbc70, + 0x289b7ec6, 0xeaa127fa, 0xd4ef3085, 0x04881d05, 0xd9d4d039, 0xe6db99e5, 0x1fa27cf8, 0xc4ac5665, + 0xf4292244, 0x432aff97, 0xab9423a7, 0xfc93a039, 0x655b59c3, 0x8f0ccc92, 0xffeff47d, 0x85845dd1, + 0x6fa87e4f, 0xfe2ce6e0, 0xa3014314, 0x4e0811a1, 0xf7537e82, 0xbd3af235, 0x2ad7d2bb, 0xeb86d391, +]; + +pub fn md5(data: &[u8]) -> [u8; 16] { + let mut state = [0x67452301_u32, 0xefcdab89, 0x98badcfe, 0x10325476]; + let bit_length = (data.len() as u64).wrapping_mul(8); + let mut message = data.to_vec(); + message.push(0x80); + while message.len() % 64 != 56 { + message.push(0); + } + message.extend_from_slice(&bit_length.to_le_bytes()); + + for chunk in message.chunks_exact(64) { + let mut words = [0_u32; 16]; + for (index, word) in words.iter_mut().enumerate() { + let start = index * 4; + *word = u32::from_le_bytes([ + chunk[start], + chunk[start + 1], + chunk[start + 2], + chunk[start + 3], + ]); + } + let [mut a, mut b, mut c, mut d] = state; + for index in 0..64 { + let (f, g) = match index { + 0..=15 => ((b & c) | (!b & d), index), + 16..=31 => ((d & b) | (!d & c), (5 * index + 1) % 16), + 32..=47 => (b ^ c ^ d, (3 * index + 5) % 16), + _ => (c ^ (b | !d), (7 * index) % 16), + }; + let rotated = a + .wrapping_add(f) + .wrapping_add(K[index]) + .wrapping_add(words[g]) + .rotate_left(S[index]); + a = d; + d = c; + c = b; + b = b.wrapping_add(rotated); + } + state[0] = state[0].wrapping_add(a); + state[1] = state[1].wrapping_add(b); + state[2] = state[2].wrapping_add(c); + state[3] = state[3].wrapping_add(d); + } + + let mut digest = [0_u8; 16]; + for (index, word) in state.iter().enumerate() { + digest[index * 4..index * 4 + 4].copy_from_slice(&word.to_le_bytes()); + } + digest +} + +pub fn md5_hex(data: &[u8]) -> String { + md5(data).iter().map(|byte| format!("{byte:02x}")).collect() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn rfc1321_vectors() { + assert_eq!(md5_hex(b""), "d41d8cd98f00b204e9800998ecf8427e"); + assert_eq!(md5_hex(b"a"), "0cc175b9c0f1b6a831c399e269772661"); + assert_eq!(md5_hex(b"abc"), "900150983cd24fb0d6963f7d28e17f72"); + assert_eq!( + md5_hex(b"message digest"), + "f96b697d7cb7938d525a2f31aaf161d0" + ); + assert_eq!( + md5_hex(b"abcdefghijklmnopqrstuvwxyz"), + "c3fcd3d76192e4007dfb496cca67e13b" + ); + assert_eq!( + md5_hex(b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"), + "d174ab98d277d9f5a5611c2c9f419d9f" + ); + assert_eq!( + md5_hex( + b"12345678901234567890123456789012345678901234567890123456789012345678901234567890" + ), + "57edf4a22be3c955ac49da2e2107b67a" + ); + } + + #[test] + fn handles_a_block_boundary() { + let data = vec![0x42_u8; 64]; + assert_eq!(md5_hex(&data), "8e558437ffca99de04c18a63b55a4fad"); + } +} diff --git a/crates/alkane-flash/src/preflight.rs b/crates/alkane-flash/src/preflight.rs new file mode 100644 index 00000000..f9be22c5 --- /dev/null +++ b/crates/alkane-flash/src/preflight.rs @@ -0,0 +1,413 @@ +// SPDX-License-Identifier: MIT +//! Read-only CV1835 preflight: source-OS fingerprint, root channel, partition +//! identity, held/golden backup hashes, free space and secure-region refusal. +//! +//! Every check runs over the network. A failure is reported, never repaired. + +use crate::boards::cv1835::{Cv1835Plan, CvPlanError}; +use crate::md5::md5_hex; +use crate::transport::{Remote, RemoteError}; +use sha2::{Digest, Sha256}; +use std::fs; +use std::path::{Path, PathBuf}; +use std::time::Duration; +use thiserror::Error; + +const P1_NAME: &str = "mmcblk0p1"; + +#[derive(Debug, Error)] +pub enum PreflightError { + #[error("preflight transport: {0}")] + Remote(#[from] RemoteError), + #[error("preflight I/O: {0}")] + Io(#[from] std::io::Error), + #[error("preflight plan: {0}")] + Plan(#[from] CvPlanError), + #[error("held backup {path} is {size} bytes, not 16 MiB")] + BackupSize { path: PathBuf, size: u64 }, + #[error("held backup {0} has no readable md5")] + BackupUnreadable(PathBuf), +} + +#[derive(Clone, Debug)] +pub struct Check { + pub name: &'static str, + pub ok: bool, + pub detail: String, +} + +#[derive(Clone, Debug)] +pub struct BackupCheck { + pub path: PathBuf, + pub md5: String, + pub sha256: String, + pub matches_live: bool, +} + +#[derive(Clone, Debug)] +pub struct PreflightReport { + pub host: String, + pub source_os: String, + pub kernel: String, + pub model: String, + pub root_method: String, + pub root_uid: String, + pub partition_device: String, + pub partition_size: u64, + pub live_md5: String, + pub held_backup: Option, + pub golden_md5: Option, + pub free_bytes: u64, + pub boot0_present: bool, + pub checks: Vec, +} + +impl PreflightReport { + pub fn ok(&self) -> bool { + self.checks.iter().all(|check| check.ok) + } + + pub fn failures(&self) -> Vec<&Check> { + self.checks.iter().filter(|check| !check.ok).collect() + } + + pub fn render(&self) -> String { + let mut out = String::new(); + out.push_str(&format!("preflight {}\n", self.host)); + out.push_str(&format!( + "source-os {} (kernel {})\n", + self.source_os, self.kernel + )); + if !self.model.is_empty() { + out.push_str(&format!("model {}\n", self.model)); + } + out.push_str(&format!( + "root {} (uid {})\n", + self.root_method, self.root_uid + )); + out.push_str(&format!( + "partition {} {} B\n", + self.partition_device, self.partition_size + )); + out.push_str(&format!("live p1 md5 {}\n", self.live_md5)); + match &self.held_backup { + Some(backup) => out.push_str(&format!( + "held backup {} md5 {} ({})\n", + backup.path.display(), + backup.md5, + if backup.matches_live { + "matches live p1" + } else { + "differs from live p1" + } + )), + None => out.push_str("held backup none (install will create one before writing)\n"), + } + if let Some(golden) = &self.golden_md5 { + out.push_str(&format!("golden raw p1 md5 {golden}\n")); + } + out.push_str(&format!( + "free tmp {} MiB\n", + self.free_bytes / (1024 * 1024) + )); + out.push_str(&format!( + "boot0 {} (never written)\n", + if self.boot0_present { + "present" + } else { + "not present" + } + )); + for check in &self.checks { + out.push_str(&format!( + "check {} {}: {}\n", + check.name, + if check.ok { "ok" } else { "FAIL" }, + check.detail + )); + } + out.push_str(if self.ok() { + "result PASS\n" + } else { + "result FAIL (do not write)\n" + }); + out + } +} + +pub struct PreflightOptions<'a> { + pub host: &'a str, + pub held_backup: Option<&'a Path>, + pub check_golden: bool, + pub allow_unknown_source: bool, +} + +pub fn preflight( + plan: &Cv1835Plan, + remote: &mut dyn Remote, + options: &PreflightOptions<'_>, +) -> Result { + let mut checks = Vec::new(); + let fingerprint = remote.user_command( + "uname -r; echo __MODEL__; cat /proc/device-tree/model 2>/dev/null; echo; \ + echo __RELEASE__; cat /etc/os-release 2>/dev/null; \ + ls /etc/bos_version /etc/fw-info /etc/alkane-release /etc/ouros-release 2>/dev/null; \ + test -x /nvdata/rroot && echo rroot; \ + test -x /usr/sbin/update-daemon && echo update-daemon", + Duration::from_secs(20), + )?; + let text = String::from_utf8_lossy(&fingerprint).into_owned(); + let mut sections = text.split("__MODEL__"); + let kernel = sections.next().unwrap_or("").trim().to_owned(); + let rest = sections.next().unwrap_or(""); + let mut sections = rest.split("__RELEASE__"); + let model = sections.next().unwrap_or("").trim().to_owned(); + let release = sections.next().unwrap_or(""); + let source_os = classify(&kernel, release, &text); + let source_ok = plan.source_os.is_empty() + || plan.source_os.iter().any(|item| item == &source_os) + || options.allow_unknown_source; + checks.push(Check { + name: "source-os", + ok: source_ok, + detail: format!( + "{source_os} (allowed: {})", + if plan.source_os.is_empty() { + "any".to_owned() + } else { + plan.source_os.join(", ") + } + ), + }); + + let root_uid = String::from_utf8_lossy(&remote.root_command("id -u", Duration::from_secs(20))?) + .trim() + .to_owned(); + checks.push(Check { + name: "root", + ok: root_uid == "0", + detail: format!("uid {root_uid}"), + }); + + let partition_device = plan.partition.device.clone(); + let block = String::from_utf8_lossy(&remote.user_command( + &format!("test -b {partition_device} && echo block || echo missing"), + Duration::from_secs(15), + )?) + .trim() + .to_owned(); + let size_out = remote.user_command( + &format!("cat /sys/class/block/{P1_NAME}/size 2>/dev/null || true"), + Duration::from_secs(15), + )?; + let sectors: u64 = String::from_utf8_lossy(&size_out) + .trim() + .parse() + .unwrap_or(0); + let partition_size = sectors.saturating_mul(512); + checks.push(Check { + name: "partition", + ok: block == "block" && partition_size == plan.partition.size, + detail: format!( + "{partition_device} {partition_size} B (plan {} B)", + plan.partition.size + ), + }); + + let live = remote.root_command( + &format!("md5sum {partition_device}"), + Duration::from_secs(60), + )?; + let live_md5 = parse_digest(&live, 32).unwrap_or_else(|| "unreadable".to_owned()); + checks.push(Check { + name: "live-p1-md5", + ok: live_md5.len() == 32, + detail: live_md5.clone(), + }); + + let commands = remote.user_command( + "for c in dd md5sum sync; do command -v $c >/dev/null 2>&1 && echo $c || echo missing:$c; done", + Duration::from_secs(15), + )?; + let commands_text = String::from_utf8_lossy(&commands).into_owned(); + let missing: Vec<&str> = commands_text + .lines() + .filter_map(|line| line.strip_prefix("missing:")) + .collect(); + checks.push(Check { + name: "commands", + ok: missing.is_empty(), + detail: if missing.is_empty() { + "dd, md5sum, sync present".to_owned() + } else { + format!("missing {}", missing.join(", ")) + }, + }); + + let free_bytes = free_bytes(remote)?; + checks.push(Check { + name: "free-space", + ok: free_bytes >= plan.min_free_bytes, + detail: format!( + "{} MiB at /tmp (plan {} MiB)", + free_bytes / (1024 * 1024), + plan.min_free_bytes / (1024 * 1024) + ), + }); + + let boot0 = String::from_utf8_lossy(&remote.user_command( + "test -e /dev/mmcblk0boot0 && echo yes || echo no", + Duration::from_secs(15), + )?) + .trim() + .to_owned(); + let boot0_present = boot0 == "yes"; + checks.push(Check { + name: "secure-regions", + ok: !plan.partition.device.contains("boot0"), + detail: format!( + "boot0 {}; the write plan targets only {}", + if boot0_present { "present" } else { "absent" }, + plan.partition.device + ), + }); + + let mut held_backup = None; + if let Some(path) = options.held_backup { + let size = fs::metadata(path)?.len(); + if size != plan.partition.size { + return Err(PreflightError::BackupSize { + path: path.to_path_buf(), + size, + }); + } + let data = fs::read(path)?; + let md5 = md5_hex(&data); + let sha256: String = Sha256::digest(&data) + .iter() + .map(|byte| format!("{byte:02x}")) + .collect(); + let matches_live = md5 == live_md5; + checks.push(Check { + name: "held-backup", + ok: true, + detail: format!( + "{} md5 {md5} ({})", + path.display(), + if matches_live { + "matches live p1" + } else { + "differs from live p1; restore will still write it" + } + ), + }); + held_backup = Some(BackupCheck { + path: path.to_path_buf(), + md5, + sha256, + matches_live, + }); + } + + let mut golden_md5 = None; + if options.check_golden { + let out = remote.root_command( + &format!( + "dd if=/dev/mmcblk0 skip={} count=32768 bs=512 2>/dev/null | md5sum", + plan.golden_lba_bytes / 512 + ), + Duration::from_secs(90), + )?; + if let Some(digest) = parse_digest(&out, 32) { + golden_md5 = Some(digest); + } + } + + Ok(PreflightReport { + host: options.host.to_owned(), + source_os, + kernel, + model, + root_method: remote.root_method().to_owned(), + root_uid, + partition_device, + partition_size, + live_md5, + held_backup, + golden_md5, + free_bytes, + boot0_present, + checks, + }) +} + +fn classify(kernel: &str, release: &str, all: &str) -> String { + if all.contains("/etc/bos_version") || release.contains("Braiins") { + return "braiins".to_owned(); + } + if all.contains("/etc/alkane-release") || kernel.starts_with("6.18") { + return "alkane".to_owned(); + } + if all.contains("/etc/ouros-release") || kernel.contains("6.6.147") { + return "ouros".to_owned(); + } + if all.contains("/etc/fw-info") || release.contains("Vnish") || release.contains("AnthillOS") { + return "vnish".to_owned(); + } + if kernel.contains("4.9.38") || all.contains("update-daemon") || all.contains("rroot") { + return "stock-bitmain".to_owned(); + } + "unknown".to_owned() +} + +pub fn parse_digest(output: &[u8], length: usize) -> Option { + let text = String::from_utf8_lossy(output); + text.split_whitespace() + .map(|token| token.trim().to_ascii_lowercase()) + .find(|token| token.len() == length && token.bytes().all(|byte| byte.is_ascii_hexdigit())) +} + +fn free_bytes(remote: &mut dyn Remote) -> Result { + let out = remote.user_command("df -k /tmp 2>/dev/null || df -k /", Duration::from_secs(15))?; + let text = String::from_utf8_lossy(&out); + for line in text.lines().rev() { + let fields: Vec<&str> = line.split_whitespace().collect(); + if fields.len() >= 4 { + if let Ok(kib) = fields[3].parse::() { + return Ok(kib.saturating_mul(1024)); + } + } + } + Ok(0) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn classifies_the_source_os() { + assert_eq!( + classify("4.9.38-tag-", "", "update-daemon\n"), + "stock-bitmain" + ); + assert_eq!( + classify("4.9.38-tag-", "/etc/fw-info\n", "/etc/fw-info\n"), + "vnish" + ); + assert_eq!(classify("6.6.147", "/etc/ouros-release\n", ""), "ouros"); + assert_eq!(classify("6.18.48", "", ""), "alkane"); + assert_eq!(classify("4.9.38", "", "/etc/bos_version\n"), "braiins"); + assert_eq!(classify("5.10.0", "", ""), "unknown"); + } + + #[test] + fn parses_md5_from_md5sum_output() { + let output = b"3f43804f10ce256200bfc71e7fbdd9ee /dev/mmcblk0p1\n"; + assert_eq!( + parse_digest(output, 32).as_deref(), + Some("3f43804f10ce256200bfc71e7fbdd9ee") + ); + assert_eq!(parse_digest(b"not a digest\n", 32), None); + } +} diff --git a/crates/alkane-flash/src/transport.rs b/crates/alkane-flash/src/transport.rs new file mode 100644 index 00000000..d761f144 --- /dev/null +++ b/crates/alkane-flash/src/transport.rs @@ -0,0 +1,699 @@ +// SPDX-License-Identifier: MIT +//! Network transport for the CV1835 installer. +//! +//! Two root channels are implemented, both over the network: +//! +//! * `direct`: the SSH login is already uid 0 (Braiins OS, ourOS/alkane with a +//! root key, or an operator-supplied root login). +//! * `update-daemon`: stock Bitmain (and Vnish, which runs on the stock +//! kernel) exposes an SSH login as `miner` (uid 1001). `/usr/sbin/update-daemon` +//! listens on 127.0.0.1:12887 and pipes its socket into `system()` as root. +//! We reach it through an SSH local forward, exactly as documented in the RE +//! notes (`cv-kvm-host` / `cvbuild/cvroot.py`, +//! `alkane-sdk-wiki/40-boot-os-and-build/cross-install-matrix.md`). The +//! channel is blind, so root output is redirected to a world-readable file +//! and read back over the unprivileged SSH session. +//! * `rroot`: an existing `/nvdata/rroot` setuid helper on CV stock/Vnish, +//! documented in `60-reverse-engineering-methods/rroot-setuid-escalation.md`. +//! It is a fallback because the helper is not durable across a p7 reformat. +//! +//! Credentials are never read here: a password is used only through +//! `sshpass -f `, and that path comes from the operator (environment +//! variable materialized by the CLI, or a file named on the command line). + +use std::fs; +use std::io::{Read, Write}; +use std::net::{SocketAddr, TcpStream}; +use std::path::{Path, PathBuf}; +use std::process::{Child, Command, ExitStatus, Stdio}; +use std::thread; +use std::time::{Duration, Instant}; +use thiserror::Error; + +const MAX_CAPTURE: usize = 64 * 1024 * 1024; + +#[derive(Debug, Error)] +pub enum RemoteError { + #[error("remote I/O: {0}")] + Io(#[from] std::io::Error), + #[error("cannot start {0}")] + MissingTool(&'static str), + #[error("invalid target: {0}")] + InvalidTarget(String), + #[error("SSH transport: {0}")] + Ssh(String), + #[error("SSH command timed out after {0:?}")] + Timeout(Duration), + #[error("remote command failed ({status}): {stderr}")] + Command { status: String, stderr: String }, + #[error("root access was not obtained: {0}")] + NotRoot(String), + #[error("no network root channel is available on this board")] + NoRootMethod, + #[error("update-daemon: {0}")] + Daemon(String), + #[error("remote output is over the {0}-byte cap")] + OutputTooLarge(usize), +} + +impl RemoteError { + fn sanitize(text: &str) -> String { + let text = text.trim(); + let mut shortened: String = text.chars().take(300).collect(); + if shortened.len() < text.len() { + shortened.push_str("..."); + } + shortened + } +} + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum RootMethod { + Auto, + Direct, + UpdateDaemon, + Rroot, +} + +impl RootMethod { + pub fn parse(value: &str) -> Option { + match value { + "auto" => Some(Self::Auto), + "direct" => Some(Self::Direct), + "update-daemon" => Some(Self::UpdateDaemon), + "rroot" => Some(Self::Rroot), + _ => None, + } + } +} + +#[derive(Clone, Debug)] +pub struct SshOptions { + pub host: String, + pub port: u16, + pub user: String, + pub identity_file: Option, + pub password_file: Option, + pub known_hosts: Option, + pub root_method: RootMethod, + pub update_daemon_port: Option, +} + +impl Default for SshOptions { + fn default() -> Self { + Self { + host: String::new(), + port: 22, + user: "miner".to_owned(), + identity_file: None, + password_file: None, + known_hosts: None, + root_method: RootMethod::Auto, + update_daemon_port: None, + } + } +} + +impl SshOptions { + fn validate(&self) -> Result<(), RemoteError> { + if self.host.is_empty() + || self.host.len() > 253 + || self.host.starts_with('-') + || !self.host.bytes().all(|byte| { + byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'-' | b':' | b'_') + }) + { + return Err(RemoteError::InvalidTarget("host".to_owned())); + } + if self.user.is_empty() + || !self + .user + .bytes() + .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'-' | b'.')) + { + return Err(RemoteError::InvalidTarget("user".to_owned())); + } + if self.port == 0 { + return Err(RemoteError::InvalidTarget("port".to_owned())); + } + if let Some(path) = &self.password_file { + if !path.is_file() { + return Err(RemoteError::InvalidTarget(format!( + "password file not found: {}", + path.display() + ))); + } + } + Ok(()) + } +} + +enum Strategy { + Direct, + Rroot, + UpdateDaemon { + local_port: u16, + remote_port: u16, + tunnel: Child, + }, +} + +impl Drop for Strategy { + fn drop(&mut self) { + if let Self::UpdateDaemon { tunnel, .. } = self { + let _ = tunnel.kill(); + let _ = tunnel.wait(); + } + } +} + +pub struct SshTransport { + options: SshOptions, + known_hosts: PathBuf, + strategy: Strategy, + counter: u64, +} + +impl SshTransport { + /// Open a session and (when `require_root`) prove a uid-0 channel. + pub fn connect(options: SshOptions, require_root: bool) -> Result { + options.validate()?; + let known_hosts = options + .known_hosts + .clone() + .unwrap_or_else(|| alkane_core::platform::config_path("known_hosts")); + if let Some(parent) = known_hosts.parent() { + fs::create_dir_all(parent)?; + } + if !known_hosts.exists() { + fs::write(&known_hosts, b"")?; + } + if options.password_file.is_some() { + Command::new("sshpass") + .arg("-V") + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .status() + .map_err(|_| RemoteError::MissingTool("sshpass"))?; + } + let mut transport = Self { + options, + known_hosts, + strategy: Strategy::Direct, + counter: 0, + }; + let identity = transport.user_command("uname -r", Duration::from_secs(15))?; + let _ = identity; + if !require_root { + return Ok(transport); + } + + let uid = + String::from_utf8_lossy(&transport.user_command("id -u", Duration::from_secs(15))?) + .trim() + .to_owned(); + let direct = uid == "0"; + let method = match transport.options.root_method { + RootMethod::Auto if direct => RootMethod::Direct, + RootMethod::Auto => { + if transport.has_update_daemon()? { + RootMethod::UpdateDaemon + } else if transport.has_rroot()? { + RootMethod::Rroot + } else { + return Err(RemoteError::NoRootMethod); + } + } + other => other, + }; + match method { + RootMethod::Direct => { + if !direct { + return Err(RemoteError::NotRoot( + "the SSH login is not uid 0; use --root-method auto, update-daemon or rroot" + .to_owned(), + )); + } + transport.strategy = Strategy::Direct; + } + RootMethod::Rroot => { + if !transport.has_rroot()? { + return Err(RemoteError::NotRoot( + "/nvdata/rroot is not present or not executable".to_owned(), + )); + } + transport.strategy = Strategy::Rroot; + } + RootMethod::UpdateDaemon => { + if !transport.has_update_daemon()? { + return Err(RemoteError::NotRoot( + "/usr/sbin/update-daemon is not present".to_owned(), + )); + } + let remote_port = transport + .options + .update_daemon_port + .unwrap_or(transport.detect_update_daemon_port()?); + let (local_port, tunnel) = transport.start_tunnel(remote_port)?; + transport.strategy = Strategy::UpdateDaemon { + local_port, + remote_port, + tunnel, + }; + } + RootMethod::Auto => unreachable!(), + } + + let root_output = transport.root_command("id", Duration::from_secs(20))?; + let root = String::from_utf8_lossy(&root_output); + if !root.contains("uid=0") { + return Err(RemoteError::NotRoot( + "the selected channel did not return uid=0".to_owned(), + )); + } + Ok(transport) + } + + pub fn channel(&self) -> String { + format!("ssh:{}@{}", self.options.user, self.options.host) + } + + pub fn root_method(&self) -> &'static str { + match &self.strategy { + Strategy::Direct => "direct", + Strategy::Rroot => "rroot", + Strategy::UpdateDaemon { .. } => "update-daemon", + } + } + + pub fn update_daemon_port(&self) -> Option { + match &self.strategy { + Strategy::UpdateDaemon { remote_port, .. } => Some(*remote_port), + _ => None, + } + } + + fn ssh_base(&self) -> Command { + let mut command = if let Some(password) = &self.options.password_file { + let mut command = Command::new("sshpass"); + command.arg("-f").arg(password).arg("ssh"); + command + } else { + Command::new("ssh") + }; + command + .arg("-F") + .arg("none") + .arg("-o") + .arg(if self.options.password_file.is_some() { + "BatchMode=no" + } else { + "BatchMode=yes" + }) + .arg("-o") + .arg("StrictHostKeyChecking=accept-new") + .arg("-o") + .arg(format!("UserKnownHostsFile={}", self.known_hosts.display())) + .arg("-o") + .arg("GlobalKnownHostsFile=/dev/null") + .arg("-o") + .arg("ConnectTimeout=10") + .arg("-o") + .arg("ServerAliveInterval=5") + .arg("-o") + .arg("ServerAliveCountMax=3") + .arg("-o") + .arg("RequestTTY=no") + .arg("-o") + .arg("LogLevel=ERROR") + .arg("-o") + .arg("NumberOfPasswordPrompts=1") + .arg("-o") + .arg("PreferredAuthentications=publickey,password,keyboard-interactive"); + if let Some(identity) = &self.options.identity_file { + command + .arg("-i") + .arg(identity) + .arg("-o") + .arg("IdentitiesOnly=yes"); + } + command + } + + fn ssh_command(&self, command: &str) -> Command { + let mut child = self.ssh_base(); + child + .arg("-p") + .arg(self.options.port.to_string()) + .arg(format!("{}@{}", self.options.user, self.options.host)) + .arg(command); + child + } + + fn run_user(&self, command: &str, timeout: Duration) -> Result, RemoteError> { + let (stdout, stderr, status) = run_bounded(self.ssh_command(command), timeout)?; + if !status.success() { + return Err(RemoteError::Command { + status: status.to_string(), + stderr: RemoteError::sanitize(&String::from_utf8_lossy(&stderr)), + }); + } + Ok(stdout) + } + + fn has_rroot(&self) -> Result { + let out = self.run_user( + "test -x /nvdata/rroot && echo yes || echo no", + Duration::from_secs(15), + )?; + Ok(String::from_utf8_lossy(&out).contains("yes")) + } + + fn has_update_daemon(&self) -> Result { + let out = self.run_user( + "test -x /usr/sbin/update-daemon && echo yes || echo no", + Duration::from_secs(15), + )?; + Ok(String::from_utf8_lossy(&out).contains("yes")) + } + + fn detect_update_daemon_port(&self) -> Result { + let out = self.run_user( + "cat /proc/net/tcp /proc/net/tcp6 2>/dev/null || true", + Duration::from_secs(15), + )?; + let text = String::from_utf8_lossy(&out); + for line in text.lines() { + let fields: Vec<&str> = line.split_whitespace().collect(); + if fields.len() < 4 || fields[3] != "0A" { + continue; + } + let local = fields[1]; + let port = local.rsplit(':').next().unwrap_or(""); + let port = u16::from_str_radix(port, 16).unwrap_or(0); + if port == 12887 || port == 22026 { + return Ok(port); + } + } + // The CV1835 stock build listens on 12887. The fallback keeps the + // explicit --update-daemon-port option available for other builds. + Ok(12887) + } + + fn start_tunnel(&self, remote_port: u16) -> Result<(u16, Child), RemoteError> { + let listener = std::net::TcpListener::bind(("127.0.0.1", 0))?; + let local_port = listener.local_addr()?.port(); + drop(listener); + let mut command = self.ssh_base(); + command + .arg("-N") + .arg("-o") + .arg("ExitOnForwardFailure=yes") + .arg("-L") + .arg(format!("127.0.0.1:{local_port}:127.0.0.1:{remote_port}")) + .arg("-p") + .arg(self.options.port.to_string()) + .arg(format!("{}@{}", self.options.user, self.options.host)) + .stdin(Stdio::null()) + .stdout(Stdio::null()) + .stderr(Stdio::null()); + let mut tunnel = command.spawn()?; + let deadline = Instant::now() + Duration::from_secs(20); + loop { + if TcpStream::connect_timeout( + &SocketAddr::from(([127, 0, 0, 1], local_port)), + Duration::from_millis(500), + ) + .is_ok() + { + return Ok((local_port, tunnel)); + } + if let Some(status) = tunnel.try_wait()? { + return Err(RemoteError::Daemon(format!( + "SSH forward exited before it was ready ({status})" + ))); + } + if Instant::now() >= deadline { + let _ = tunnel.kill(); + return Err(RemoteError::Daemon( + "SSH forward did not become ready".to_owned(), + )); + } + thread::sleep(Duration::from_millis(250)); + } + } + + fn daemon_send(&self, command: &str) -> Result<(), RemoteError> { + let Strategy::UpdateDaemon { local_port, .. } = &self.strategy else { + return Err(RemoteError::Daemon("not using update-daemon".to_owned())); + }; + let local_port = *local_port; + if command.contains('\n') || command.contains('\r') { + return Err(RemoteError::Daemon("command contains a newline".to_owned())); + } + let mut stream = TcpStream::connect_timeout( + &SocketAddr::from(([127, 0, 0, 1], local_port)), + Duration::from_secs(10), + )?; + stream.set_write_timeout(Some(Duration::from_secs(10)))?; + stream.write_all(format!(";{command};").as_bytes())?; + stream.flush()?; + let _ = stream.set_read_timeout(Some(Duration::from_millis(500))); + let mut sink = [0_u8; 256]; + let _ = stream.read(&mut sink); + Ok(()) + } + + fn daemon_capture(&mut self, command: &str, timeout: Duration) -> Result, RemoteError> { + let path = format!("/tmp/.alkane-root-{}-{}", std::process::id(), self.counter); + self.counter += 1; + let wrapped = format!("{{ {command} ; }} > {path} 2>&1; chmod 644 {path}"); + self.daemon_send(&wrapped)?; + let deadline = Instant::now() + timeout; + loop { + let probe = format!("test -f {path} && echo ready || true"); + let out = self.run_user(&probe, Duration::from_secs(15))?; + if String::from_utf8_lossy(&out).contains("ready") { + break; + } + if Instant::now() >= deadline { + return Err(RemoteError::Daemon(format!( + "root command produced no output file within {timeout:?}" + ))); + } + thread::sleep(Duration::from_millis(200)); + } + let output = self.run_user(&format!("cat {path}"), Duration::from_secs(60))?; + let _ = self.run_user(&format!("rm -f {path}"), Duration::from_secs(15)); + Ok(output) + } + + fn daemon_reboot(&mut self) -> Result<(), RemoteError> { + self.daemon_send("sync; echo b > /proc/sysrq-trigger") + } +} + +impl Remote for SshTransport { + fn channel(&self) -> &str { + "ssh" + } + + fn root_method(&self) -> &'static str { + SshTransport::root_method(self) + } + + fn user_command(&mut self, command: &str, timeout: Duration) -> Result, RemoteError> { + self.run_user(command, timeout) + } + + fn root_command(&mut self, command: &str, timeout: Duration) -> Result, RemoteError> { + match self.root_method() { + "direct" => self.run_user(command, timeout), + "rroot" => { + let wrapped = format!("/nvdata/rroot -c {}", shell_quote(command)); + self.run_user(&wrapped, timeout) + } + "update-daemon" => self.daemon_capture(command, timeout), + _ => Err(RemoteError::NoRootMethod), + } + } + + fn push(&mut self, local: &Path, remote: &str, timeout: Duration) -> Result<(), RemoteError> { + let remote = safe_remote_path(remote)?; + let mut command = self.ssh_command(&format!("cat > {remote}")); + command + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()); + let mut child = command.spawn()?; + let mut stdin = child.stdin.take().expect("piped stdin"); + let path = local.to_path_buf(); + let writer = thread::spawn(move || -> std::io::Result<()> { + let mut source = fs::File::open(path)?; + let mut buffer = [0_u8; 64 * 1024]; + loop { + let read = source.read(&mut buffer)?; + if read == 0 { + break; + } + stdin.write_all(&buffer[..read])?; + } + stdin.flush() + }); + let (stdout, stderr) = read_pipes(&mut child); + let status = wait_timeout(&mut child, timeout)?; + let _ = writer.join(); + let _ = stdout.join(); + let stderr = stderr.join().unwrap_or_default(); + if !status.success() { + return Err(RemoteError::Command { + status: status.to_string(), + stderr: RemoteError::sanitize(&String::from_utf8_lossy(&stderr)), + }); + } + Ok(()) + } + + fn pull(&mut self, remote: &str, local: &Path, timeout: Duration) -> Result<(), RemoteError> { + let remote = safe_remote_path(remote)?; + let data = self.run_user(&format!("cat {remote}"), timeout)?; + if data.len() > MAX_CAPTURE { + return Err(RemoteError::OutputTooLarge(MAX_CAPTURE)); + } + fs::write(local, data)?; + Ok(()) + } + + fn reboot(&mut self) -> Result<(), RemoteError> { + match self.root_method() { + "update-daemon" => self.daemon_reboot(), + _ => { + // A successful sysrq reset drops the SSH connection mid-command. + let _ = self.run_user( + "sync; echo b > /proc/sysrq-trigger", + Duration::from_secs(15), + ); + Ok(()) + } + } + } +} + +pub trait Remote { + fn channel(&self) -> &str; + fn root_method(&self) -> &'static str { + "network" + } + fn user_command(&mut self, command: &str, timeout: Duration) -> Result, RemoteError>; + fn root_command(&mut self, command: &str, timeout: Duration) -> Result, RemoteError>; + fn push(&mut self, local: &Path, remote: &str, timeout: Duration) -> Result<(), RemoteError>; + fn pull(&mut self, remote: &str, local: &Path, timeout: Duration) -> Result<(), RemoteError>; + fn reboot(&mut self) -> Result<(), RemoteError>; +} + +pub fn shell_quote(text: &str) -> String { + format!("'{}'", text.replace('\'', "'\\''")) +} + +pub fn safe_remote_path(path: &str) -> Result<&str, RemoteError> { + if !path.starts_with('/') + || path.len() > 200 + || path.contains("..") + || !path + .bytes() + .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'/' | b'.' | b'_' | b'-')) + { + return Err(RemoteError::InvalidTarget(format!( + "unsafe remote path: {path}" + ))); + } + Ok(path) +} + +fn read_pipes(child: &mut Child) -> (thread::JoinHandle>, thread::JoinHandle>) { + let mut stdout = child.stdout.take().expect("piped stdout"); + let mut stderr = child.stderr.take().expect("piped stderr"); + let out = thread::spawn(move || { + let mut data = Vec::new(); + let _ = stdout.read_to_end(&mut data); + data + }); + let err = thread::spawn(move || { + let mut data = Vec::new(); + let _ = stderr.read_to_end(&mut data); + data + }); + (out, err) +} + +fn wait_timeout(child: &mut Child, timeout: Duration) -> Result { + let deadline = Instant::now() + timeout; + loop { + if let Some(status) = child.try_wait()? { + return Ok(status); + } + if Instant::now() >= deadline { + let _ = child.kill(); + let _ = child.wait(); + return Err(RemoteError::Timeout(timeout)); + } + thread::sleep(Duration::from_millis(20)); + } +} + +fn run_bounded( + mut command: Command, + timeout: Duration, +) -> Result<(Vec, Vec, ExitStatus), RemoteError> { + command + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()); + let mut child = command.spawn()?; + let (stdout, stderr) = read_pipes(&mut child); + let status = wait_timeout(&mut child, timeout)?; + let stdout = stdout.join().unwrap_or_default(); + let stderr = stderr.join().unwrap_or_default(); + if stdout.len() > MAX_CAPTURE { + return Err(RemoteError::OutputTooLarge(MAX_CAPTURE)); + } + Ok((stdout, stderr, status)) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn quotes_shell_arguments_for_rroot() { + assert_eq!(shell_quote("id"), "'id'"); + assert_eq!(shell_quote("echo 'x'"), "'echo '\\''x'\\'''"); + } + + #[test] + fn rejects_option_injection_and_unsafe_paths() { + let mut options = SshOptions { + host: "-oProxyCommand=bad".to_owned(), + user: "root".to_owned(), + ..SshOptions::default() + }; + assert!(options.validate().is_err()); + options.host = "10.255.1.167".to_owned(); + options.user = "root;id".to_owned(); + assert!(options.validate().is_err()); + assert!(safe_remote_path("/tmp/ok.img").is_ok()); + assert!(safe_remote_path("relative").is_err()); + assert!(safe_remote_path("/tmp/../etc/passwd").is_err()); + assert!(safe_remote_path("/tmp/a;b").is_err()); + } + + #[test] + fn parses_root_methods() { + assert_eq!(RootMethod::parse("auto"), Some(RootMethod::Auto)); + assert_eq!( + RootMethod::parse("update-daemon"), + Some(RootMethod::UpdateDaemon) + ); + assert_eq!(RootMethod::parse("serial"), None); + } +}