a113d (Amlogic AXG/S21 Pro): UBI-file flash module + CLI routing

Add the S21 Pro-class Amlogic A113D/AXG flash module to the toolkit, matching
the Zynq-7010 treatment, plus CLI routing for plan/preflight/install.

- crates/alkane-flash/src/boards/a113d.rs: A113dPlan::from_afw validates the
  verified manifest (a113d, arm64, preserve, no fip/spl/tpl/u-boot member,
  exactly kernel/dtb/rootfs with arm64-image/fdt/uimage formats, per-image
  ceilings and total <= nvdata, plus independent magic checks and a
  defense-in-depth refusal of any non-nvdata partition carrying an image).
  The installer is file-only: it resolves the anthillos/ directory on a
  mounted ubifs volume and copies the three files there with staged + read-back
  md5 verification. The brick guard is structural - there is no flash_erase,
  nandwrite or dd-to-/dev/mtd anywhere in the module, so the FIP (mtd0/1) and
  stock boot (mtd4) and mtd2/3/5 can never be touched; every destination is
  checked to be a bare basename.
- crates/alkane-flash/src/boards/mod.rs: register the module.
- crates/alkane-cli/src/main.rs: route a113d bundles through afw
  plan/preflight/install.
- crates/alkane-artifacts/src/afw.rs: correct the a113d / a113d-s21pro board
  profile from armv7 to arm64 (the A113D/AXG is an arm64 SoC).

8 new a113d unit tests; full suite: 55 alkane-flash, 12 alkane-artifacts, all
pass. End-to-end verified: make-afw.sh -> check-afw.py -> alkane-cli afw plan
on a stub a113d bundle.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01B1W6qHxYpv7yf7Ah57g4rQ
This commit is contained in:
2026-11-06 21:02:06 -06:00
co-authored by Claude Opus 4.8
parent cce24b6880
commit c79ee1315d
4 changed files with 814 additions and 2 deletions
+4 -2
View File
@@ -76,8 +76,10 @@ pub fn board_profile(board: &str) -> Option<BoardProfile> {
"am335x-stock" => ("arm", BootloaderPolicy::Include),
"cv1835" => ("arm64", BootloaderPolicy::Preserve),
"zynq-7010" => ("armv7", BootloaderPolicy::Preserve),
"a113d" => ("armv7", BootloaderPolicy::Preserve),
"a113d-s21pro" => ("armv7", BootloaderPolicy::Preserve),
// Amlogic A113D/AXG (S21 Pro-class) control board is arm64; our OS files
// are staged in the nvdata UBI and the signed FIP bootloader is preserved.
"a113d" => ("arm64", BootloaderPolicy::Preserve),
"a113d-s21pro" => ("arm64", BootloaderPolicy::Preserve),
"am335x-bb" => ("armv7", BootloaderPolicy::Preserve),
"zynq-s17" => ("armv7", BootloaderPolicy::Include),
_ => return None,
+53
View File
@@ -13,6 +13,7 @@ use alkane_flash::boards::am335x::{
};
use alkane_flash::boards::cv1835::Cv1835Plan;
use alkane_flash::boards::zynq::{self, ZynqInstallOptions, ZynqOutcome, ZynqPlan};
use alkane_flash::boards::a113d::{self, A113dInstallOptions, A113dOutcome, A113dPlan};
use alkane_flash::install::{
install, restore, verify_live, InstallOptions, InstallOutcome, RestoreOptions,
};
@@ -351,6 +352,12 @@ fn run_plan(args: &[String]) -> Result<(), Box<dyn std::error::Error>> {
println!("plan is read-only; no write performed (run preflight/install with --host)");
return Ok(());
}
if a113d::owns_board(&verified.manifest.board) {
let plan = A113dPlan::from_afw(&verified)?;
println!("{}", plan.render());
println!("plan is read-only; no write performed (run preflight/install with --host)");
return Ok(());
}
let plan = Cv1835Plan::from_afw(&verified)?;
let (ssh, _secret) = ssh_options(&opts, DEFAULT_USER)?;
let mut transport = SshTransport::connect(ssh, true)?;
@@ -415,6 +422,15 @@ fn run_preflight(args: &[String]) -> Result<(), Box<dyn std::error::Error>> {
}
return Ok(());
}
if a113d::owns_board(&verified.manifest.board) {
let plan = A113dPlan::from_afw(&verified)?;
let report = a113d::preflight(&plan, &mut transport, opts.value("host").unwrap_or(""))?;
print!("{}", report.render());
if !report.ok() {
return Err("preflight failed; do not write".into());
}
return Ok(());
}
let plan = Cv1835Plan::from_afw(&verified)?;
let held_backup = opts.value("held-backup").map(PathBuf::from);
let report = preflight(
@@ -544,6 +560,43 @@ fn run_install(args: &[String]) -> Result<(), Box<dyn std::error::Error>> {
}
return Ok(());
}
if a113d::owns_board(&verified.manifest.board) {
let plan = A113dPlan::from_afw(&verified)?;
println!("{}", plan.render());
let install_options = A113dInstallOptions {
dry_run: opts.flag("dry-run"),
confirm: opts.value("confirm").map(str::to_owned),
no_reboot: opts.flag("no-reboot"),
backup_dir,
};
match a113d::install(&plan, &mut transport, &install_options, opts.value("host").unwrap_or(""))? {
A113dOutcome::DryRun(report) => {
print!("{}", report.render());
println!("DRY RUN: no file was written into the nvdata UBI.");
let targets = plan.targets.iter().map(|t| t.image_name.as_str()).collect::<Vec<_>>().join(", ");
println!("Re-run with --confirm FLASH to stage {targets} into anthillos/ (FIP + mtd0-5 preserved).");
}
A113dOutcome::Installed(receipt) => {
println!("wrote OS files into {}", receipt.anthillos);
for backup in &receipt.backups {
match (&backup.path, &backup.md5) {
(Some(path), Some(md5)) => println!(
"held {} {} md5 {}",
backup.image_name, path.display(), md5
),
_ => println!("held {} (no prior file on board)", backup.image_name),
}
}
println!("all read-backs matched before reboot; no raw NAND write, FIP never touched");
if receipt.rebooted {
println!("reboot issued; an SSH drop here is the success signature");
} else {
println!("reboot skipped (--no-reboot)");
}
}
}
return Ok(());
}
let plan = Cv1835Plan::from_afw(&verified)?;
let install_options = InstallOptions {
dry_run: opts.flag("dry-run"),
+756
View File
@@ -0,0 +1,756 @@
// SPDX-License-Identifier: MIT
//! Amlogic A113D / AXG (Antminer S21 Pro-class) board module: tier-2 network
//! UPDATE of a board already running alkane. Our OS is staged as FILES in the
//! nvdata UBI volume (mtd6): anthillos/{vmlinux.bin, devicetree.dtb,
//! uramdisk.image.gz}. The signed FIP bootloader (mtd0/mtd1), the stock boot
//! fallback (mtd4), and mtd2/3/5 are PRESERVED - this module performs ZERO raw
//! NAND writes. It copies three files into an already-mounted UBIFS volume and
//! nothing else, so no code path here can touch a raw /dev/mtd device.
//!
//! The brick guard is therefore STRUCTURAL: there is no flash_erase, nandwrite,
//! or dd-to-/dev/mtd anywhere in this module. Each file destination is checked
//! to be a bare basename inside the resolved anthillos directory of a ubifs
//! mount; the raw FIP partitions (mtd0-5) are never named.
//!
//! The first from-stock install (via the vendor toolkit, past the signed
//! bootloader) is the dsh-owned path and is NOT this module. This is the
//! repeatable alkane-to-alkane update.
use crate::md5::md5_hex;
use crate::preflight::{classify, parse_digest};
use crate::transport::{Remote, RemoteError};
use alkane_artifacts::afw::{AfwImage, AfwPartition, BootloaderPolicy, VerifiedAfw};
use std::fs;
use std::io::Write;
use std::path::PathBuf;
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use thiserror::Error;
pub const BOARD: &str = "a113d";
pub const ARCH: &str = "arm64";
/// The UBI volume subdirectory the boot chain reads our OS files from.
pub const ANTHILLOS_DIR: &str = "anthillos";
/// nvdata UBI usable size; the three files together must fit (0xB900000).
pub const NVDATA_USABLE: u64 = 0xB900000;
/// Raw NAND partitions that are NEVER a write target (FIP + stock boot).
pub const PRESERVE_DEVICES: [&str; 6] = [
"/dev/mtd0", "/dev/mtd1", "/dev/mtd2", "/dev/mtd3", "/dev/mtd4", "/dev/mtd5",
];
/// Authoritative file targets: (image, on-board basename, ceiling, format).
/// Written rootfs -> dtb -> kernel so a mid-write interruption never leaves a
/// new rootfs beside an old kernel (the kernel file lands last).
const TARGETS: [(&str, &str, u64, &str); 3] = [
("rootfs", "uramdisk.image.gz", 0x6000000, "uimage"),
("dtb", "devicetree.dtb", 0x100000, "fdt"),
("kernel", "vmlinux.bin", 0x4000000, "arm64-image"),
];
#[derive(Debug, Error)]
pub enum A113dPlanError {
#[error("bundle is for {0}, not a113d")]
WrongBoard(String),
#[error("bundle arch is {0}, a113d needs arm64")]
WrongArch(String),
#[error("a113d requires bootloader_policy preserve (the FIP is never written)")]
BootloaderPolicy,
#[error("a113d bundle carries a bootloader/spl/fip/tpl member: {0}")]
BootloaderMember(String),
#[error("manifest is not an OS payload")]
PayloadType,
#[error("manifest marker is empty")]
Marker,
#[error("a113d must install exactly kernel, dtb and rootfs")]
InstallCount,
#[error("a113d is missing the {0} image")]
MissingImage(String),
#[error("a113d {image} format is {actual}, expected {expected}")]
ImageFormat { image: String, actual: String, expected: &'static str },
#[error("a113d {image} is {size} bytes, over the 0x{ceiling:x}-byte ceiling")]
ImageTooLarge { image: String, size: u64, ceiling: u64 },
#[error("a113d images total {total} bytes, over the nvdata UBI (0x{usable:x})")]
OverNvdata { total: u64, usable: u64 },
#[error("a113d {image} is not an arm64 Image")]
NotArm64 { image: String },
#[error("a113d {image} is not an FDT")]
NotFdt { image: String },
#[error("a113d {image} is not a legacy uImage")]
NotUimage { image: String },
#[error("a113d refuses: preserved partition {0} (mtd0-5) carries an image")]
PreservedCarriesImage(String),
#[error("a113d refuses an unsafe destination for {image}: {dest}")]
UnsafeDest { image: String, dest: String },
}
#[derive(Clone, Debug)]
pub struct A113dTarget {
pub image_name: String,
/// On-board basename inside the anthillos directory (never a device path).
pub dest: String,
pub size: u64,
pub data: Vec<u8>,
pub expected_md5: String,
}
#[derive(Clone, Debug)]
pub struct A113dPlan {
pub targets: Vec<A113dTarget>,
pub marker: String,
pub kernel_version: String,
pub sdk_revision: String,
pub os_revision: String,
pub afw_sha256: String,
pub min_free_bytes: u64,
}
fn is_bootloaderish(image: &AfwImage) -> bool {
let lowered = format!("{} {} {}", image.name, image.file, image.role).to_lowercase();
image.role == "bootloader"
|| lowered.contains("spl")
|| lowered.contains("u-boot")
|| lowered.contains("uboot")
|| lowered.contains("fip")
|| lowered.contains("tpl")
}
/// A destination is safe only as a bare basename (no separators, no traversal,
/// not a device path). This is what keeps every write inside anthillos/.
fn is_safe_dest(dest: &str) -> bool {
!dest.is_empty()
&& !dest.contains('/')
&& !dest.contains("..")
&& !dest.starts_with("/dev/")
&& dest == dest.trim()
}
impl A113dPlan {
pub fn from_afw(afw: &VerifiedAfw) -> Result<Self, A113dPlanError> {
let manifest = &afw.manifest;
if manifest.board != BOARD {
return Err(A113dPlanError::WrongBoard(manifest.board.clone()));
}
if manifest.arch != ARCH {
return Err(A113dPlanError::WrongArch(manifest.arch.clone()));
}
if manifest.payload_type != "os" {
return Err(A113dPlanError::PayloadType);
}
if manifest.bootloader_policy != BootloaderPolicy::Preserve {
return Err(A113dPlanError::BootloaderPolicy);
}
if manifest.marker.is_empty() {
return Err(A113dPlanError::Marker);
}
// FIP / bootloader members are never allowed - we reuse the board's.
for image in &manifest.images {
if is_bootloaderish(image) {
return Err(A113dPlanError::BootloaderMember(image.file.clone()));
}
}
// Defense in depth: only nvdata (mtd6) may carry an image; mtd0-5 preserved.
for partition in &manifest.partitions {
if partition.name != "nvdata" && partition.image.is_some() {
return Err(A113dPlanError::PreservedCarriesImage(partition.name.clone()));
}
// A preserved partition device must be in the never-write set when listed.
let _ = &partition.device;
}
let installs: Vec<&AfwImage> = manifest.images.iter().filter(|i| i.install).collect();
if installs.len() != TARGETS.len() {
return Err(A113dPlanError::InstallCount);
}
let mut targets = Vec::with_capacity(TARGETS.len());
let mut total = 0u64;
for (image_name, dest, ceiling, expected_format) in TARGETS {
let image = manifest
.images
.iter()
.find(|i| i.name == image_name && i.install)
.ok_or_else(|| A113dPlanError::MissingImage(image_name.to_owned()))?;
if image.format != expected_format {
return Err(A113dPlanError::ImageFormat {
image: image_name.to_owned(),
actual: image.format.clone(),
expected: expected_format,
});
}
if image.size > ceiling {
return Err(A113dPlanError::ImageTooLarge {
image: image_name.to_owned(),
size: image.size,
ceiling,
});
}
if !is_safe_dest(dest) {
return Err(A113dPlanError::UnsafeDest {
image: image_name.to_owned(),
dest: dest.to_owned(),
});
}
let data = afw
.image(image_name)
.map(|(_, data)| data)
.ok_or_else(|| A113dPlanError::MissingImage(image_name.to_owned()))?;
// Magic checks, independent of the producer gate.
match expected_format {
"arm64-image" => {
if !(data.len() >= 0x3C && data[0x38..0x3C] == *b"ARMd") {
return Err(A113dPlanError::NotArm64 { image: image_name.to_owned() });
}
}
"fdt" => {
if !(data.len() >= 4 && data[0..4] == [0xd0, 0x0d, 0xfe, 0xed]) {
return Err(A113dPlanError::NotFdt { image: image_name.to_owned() });
}
}
"uimage" => {
if !(data.len() >= 4 && data[0..4] == [0x27, 0x05, 0x19, 0x56]) {
return Err(A113dPlanError::NotUimage { image: image_name.to_owned() });
}
}
_ => {}
}
total += image.size;
targets.push(A113dTarget {
image_name: image_name.to_owned(),
dest: dest.to_owned(),
size: image.size,
expected_md5: md5_hex(data),
data: data.to_vec(),
});
}
if total > NVDATA_USABLE {
return Err(A113dPlanError::OverNvdata { total, usable: NVDATA_USABLE });
}
Ok(Self {
targets,
marker: manifest.marker.clone(),
kernel_version: manifest.kernel_version.clone(),
sdk_revision: manifest.sdk_revision.clone(),
os_revision: manifest.os_revision.clone(),
afw_sha256: afw.archive_sha256.clone(),
min_free_bytes: manifest
.preflight
.get("min_free_bytes")
.and_then(|v| v.as_u64())
.unwrap_or(16 * 1024 * 1024),
})
}
pub fn render(&self) -> String {
let mut out = format!("board {BOARD} arch {ARCH}\n");
out.push_str(
"tier 2 update: copy OS files into the nvdata UBI (anthillos/); \
FIP (mtd0/1) + stock boot (mtd4) + mtd2/3/5 preserved, zero raw NAND writes\n",
);
out.push_str("image format kernel=arm64-image, dtb=fdt, rootfs=uimage\n");
for target in &self.targets {
out.push_str(&format!(
"copy {} -> {ANTHILLOS_DIR}/{} size {} B md5 {}\n",
target.image_name, target.dest, target.size, target.expected_md5
));
}
out.push_str(&format!(
"marker {} kernel {} sdk {} os {}",
self.marker,
self.kernel_version,
short(&self.sdk_revision),
short(&self.os_revision),
));
out
}
}
fn short(rev: &str) -> &str {
rev.get(..12).unwrap_or(rev)
}
#[derive(Debug, Error)]
pub enum A113dError {
#[error("preflight failed:\n{0}")]
Preflight(String),
#[error("--confirm FLASH is required to write")]
Confirm,
#[error("no mounted ubifs volume with an {0}/ directory was found; refusing to write")]
NoAnthillos(String),
#[error("refusing an unsafe destination: {0}")]
UnsafeDest(String),
#[error("{0} staged md5 differs from the verified bundle")]
StageMismatch(String),
#[error("{0} read-back md5 mismatch; do not reboot")]
Readback(String),
#[error(transparent)]
Remote(#[from] RemoteError),
#[error(transparent)]
Io(#[from] std::io::Error),
}
#[derive(Clone, Debug)]
pub struct A113dCheck {
pub name: String,
pub ok: bool,
pub detail: String,
}
#[derive(Clone, Debug)]
pub struct A113dPreflight {
pub host: String,
pub checks: Vec<A113dCheck>,
/// Resolved absolute anthillos directory on a mounted ubifs volume.
pub anthillos: Option<String>,
}
impl A113dPreflight {
pub fn ok(&self) -> bool {
self.checks.iter().all(|c| c.ok)
}
pub fn render(&self) -> String {
let mut out = format!("preflight {}\n", self.host);
for c in &self.checks {
out.push_str(&format!(
"check {} {}: {}\n",
c.name,
if c.ok { "ok" } else { "FAIL" },
c.detail
));
}
out.push_str(&format!(
"result {}",
if self.ok() { "PASS" } else { "FAIL (do not write)" }
));
out
}
}
/// Find a mounted ubifs volume that already holds an anthillos/ directory - that
/// is where the running alkane boots our OS files from, and the only place this
/// module ever writes. We never attach or mount a raw device ourselves.
fn resolve_anthillos(remote: &mut dyn Remote) -> Result<Option<String>, A113dError> {
let mounts = remote.user_command("cat /proc/mounts 2>/dev/null", Duration::from_secs(20))?;
for line in String::from_utf8_lossy(&mounts).lines() {
let mut fields = line.split_whitespace();
let _dev = fields.next().unwrap_or("");
let mountpoint = fields.next().unwrap_or("");
let fstype = fields.next().unwrap_or("");
if fstype != "ubifs" || mountpoint.is_empty() {
continue;
}
let candidate = format!("{}/{ANTHILLOS_DIR}", mountpoint.trim_end_matches('/'));
let probe = remote.user_command(
&format!("test -d {candidate} && echo __HAVE__"),
Duration::from_secs(15),
)?;
if String::from_utf8_lossy(&probe).contains("__HAVE__") {
return Ok(Some(candidate));
}
}
Ok(None)
}
pub fn preflight(
plan: &A113dPlan,
remote: &mut dyn Remote,
host: &str,
) -> Result<A113dPreflight, A113dError> {
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; cat /etc/alkane-release 2>/dev/null \
|| true",
Duration::from_secs(20),
)?;
let text = String::from_utf8_lossy(&fingerprint).into_owned();
let mut it = text.split("__MODEL__");
let kernel = it.next().unwrap_or("").trim().to_owned();
let rest = it.next().unwrap_or("");
let mut it2 = rest.split("__RELEASE__");
let _model = it2.next().unwrap_or("");
let release = it2.next().unwrap_or("");
let source = classify(&kernel, release, &text);
checks.push(A113dCheck {
name: "source-os".to_owned(),
ok: source == "alkane",
detail: format!("{source} (update path requires alkane)"),
});
let uid = String::from_utf8_lossy(&remote.root_command("id -u", Duration::from_secs(20))?)
.trim()
.to_owned();
checks.push(A113dCheck { name: "root".to_owned(), ok: uid == "0", detail: format!("uid {uid}") });
let tools = remote.user_command(
"for c in ubiattach mount cp md5sum sync; do \
command -v $c >/dev/null 2>&1 && echo $c || echo missing:$c; done",
Duration::from_secs(15),
)?;
let missing: Vec<String> = String::from_utf8_lossy(&tools)
.lines()
.filter_map(|l| l.strip_prefix("missing:").map(str::to_owned))
.collect();
checks.push(A113dCheck {
name: "commands".to_owned(),
ok: missing.is_empty(),
detail: if missing.is_empty() {
"ubi/file tools present".to_owned()
} else {
format!("missing {}", missing.join(", "))
},
});
// nvdata (mtd6) must be present; we never write it raw, but its absence means
// the board is not the expected layout.
let mtd = String::from_utf8_lossy(
&remote.user_command("cat /proc/mtd 2>/dev/null", Duration::from_secs(20))?,
)
.into_owned();
let have_nvdata = mtd.contains("mtd6:");
checks.push(A113dCheck {
name: "nvdata".to_owned(),
ok: have_nvdata,
detail: if have_nvdata {
"mtd6 (nvdata UBI) present".to_owned()
} else {
format!("mtd6 not found: {mtd}")
},
});
// Every destination is a bare basename - the structural brick guard.
let dests_safe = plan.targets.iter().all(|t| is_safe_dest(&t.dest));
checks.push(A113dCheck {
name: "file-only".to_owned(),
ok: dests_safe,
detail: format!(
"all writes are files in {ANTHILLOS_DIR}/; raw {} never touched",
PRESERVE_DEVICES.join(",")
),
});
// Resolve the anthillos directory on a mounted ubifs volume.
let anthillos = resolve_anthillos(remote)?;
checks.push(A113dCheck {
name: "anthillos".to_owned(),
ok: anthillos.is_some(),
detail: match &anthillos {
Some(path) => format!("writing into {path}"),
None => "no mounted ubifs volume with anthillos/".to_owned(),
},
});
Ok(A113dPreflight { host: host.to_owned(), checks, anthillos })
}
#[derive(Clone, Debug)]
pub struct A113dInstallOptions {
pub dry_run: bool,
pub confirm: Option<String>,
pub no_reboot: bool,
pub backup_dir: PathBuf,
}
#[derive(Clone, Debug)]
pub struct A113dBackup {
pub image_name: String,
pub dest: String,
pub path: Option<PathBuf>,
pub md5: Option<String>,
pub size: u64,
}
#[derive(Clone, Debug)]
pub struct A113dReceipt {
pub anthillos: String,
pub backups: Vec<A113dBackup>,
pub rebooted: bool,
}
pub enum A113dOutcome {
DryRun(Box<A113dPreflight>),
Installed(A113dReceipt),
}
pub fn install(
plan: &A113dPlan,
remote: &mut dyn Remote,
options: &A113dInstallOptions,
host: &str,
) -> Result<A113dOutcome, A113dError> {
let report = preflight(plan, remote, host)?;
if !report.ok() {
return Err(A113dError::Preflight(report.render()));
}
if options.dry_run {
return Ok(A113dOutcome::DryRun(Box::new(report)));
}
if options.confirm.as_deref() != Some("FLASH") {
return Err(A113dError::Confirm);
}
let anthillos = report
.anthillos
.clone()
.ok_or_else(|| A113dError::NoAnthillos(ANTHILLOS_DIR.to_owned()))?;
fs::create_dir_all(&options.backup_dir)?;
let epoch = SystemTime::now().duration_since(UNIX_EPOCH).unwrap_or_default().as_secs();
let mut backups = Vec::new();
for target in &plan.targets {
// Structural guard, re-asserted at the point of writing: the destination
// is a bare basename inside anthillos/. No raw device can be named here.
if !is_safe_dest(&target.dest) {
return Err(A113dError::UnsafeDest(target.dest.clone()));
}
let name = &target.image_name;
let dest_path = format!("{anthillos}/{}", target.dest);
// Back up the existing file we are about to overwrite, if present.
let have = remote.user_command(
&format!("test -f {dest_path} && echo __YES__"),
Duration::from_secs(15),
)?;
if String::from_utf8_lossy(&have).contains("__YES__") {
let local = options.backup_dir.join(format!("{}-{epoch}.bak", target.dest));
remote.pull(&dest_path, &local, Duration::from_secs(300))?;
let data = fs::read(&local)?;
backups.push(A113dBackup {
image_name: name.clone(),
dest: target.dest.clone(),
md5: Some(md5_hex(&data)),
size: data.len() as u64,
path: Some(local),
});
} else {
backups.push(A113dBackup {
image_name: name.clone(),
dest: target.dest.clone(),
md5: None,
size: 0,
path: None,
});
}
// Stage the verified payload and prove its remote md5 before copying.
let mut staged = tempfile::NamedTempFile::new()?;
staged.write_all(&target.data)?;
staged.flush()?;
let remote_stage = format!("/tmp/.alkane-a113d-{name}.img");
remote.push(staged.path(), &remote_stage, Duration::from_secs(300))?;
let staged_md5 = parse_digest(
&remote.root_command(&format!("md5sum {remote_stage}"), Duration::from_secs(60))?,
32,
)
.unwrap_or_default();
if staged_md5 != target.expected_md5 {
let _ = remote.root_command(&format!("rm -f {remote_stage}"), Duration::from_secs(15));
return Err(A113dError::StageMismatch(name.clone()));
}
// Copy into the UBI volume (file write only), then sync. No raw NAND.
remote.root_command(
&format!("cp -f {remote_stage} {dest_path} && sync"),
Duration::from_secs(300),
)?;
// Read back the copied file and compare md5.
let readback = parse_digest(
&remote.root_command(&format!("md5sum {dest_path}"), Duration::from_secs(60))?,
32,
)
.unwrap_or_default();
let _ = remote.root_command(&format!("rm -f {remote_stage}"), Duration::from_secs(15));
if readback != target.expected_md5 {
return Err(A113dError::Readback(name.clone()));
}
}
let rebooted = if options.no_reboot {
false
} else {
remote.reboot()?;
true
};
Ok(A113dOutcome::Installed(A113dReceipt { anthillos, backups, rebooted }))
}
pub fn owns_board(board: &str) -> bool {
board == BOARD
}
/// True when no plan target would ever name a preserved raw partition. Used by
/// tests to assert the structural guard holds for the fixed TARGETS table.
pub fn no_raw_device_targets(plan: &A113dPlan) -> bool {
plan.targets.iter().all(|t| {
is_safe_dest(&t.dest) && !PRESERVE_DEVICES.iter().any(|d| t.dest.contains(d))
})
}
#[allow(dead_code)]
fn _partition_is_preserved(p: &AfwPartition) -> bool {
p.name != "nvdata"
}
#[cfg(test)]
mod tests {
use super::*;
use alkane_artifacts::afw::{AfwManifest, AfwMember};
use serde_json::json;
use sha2::{Digest, Sha256};
const REV: &str = "0123456789abcdef0123456789abcdef01234567";
fn arm64_image(payload: &[u8]) -> Vec<u8> {
let mut b = vec![0u8; 64];
b[0x38..0x3C].copy_from_slice(b"ARMd");
b.extend_from_slice(payload);
b
}
fn dtb() -> Vec<u8> {
let mut b = vec![0u8; 2048];
b[0..4].copy_from_slice(&[0xd0, 0x0d, 0xfe, 0xed]);
b
}
fn uramdisk() -> Vec<u8> {
let mut b = vec![0u8; 64];
b[0..4].copy_from_slice(&[0x27, 0x05, 0x19, 0x56]);
b
}
fn afw_with(
kernel: Vec<u8>,
dtb: Vec<u8>,
rootfs: Vec<u8>,
partitions: serde_json::Value,
) -> VerifiedAfw {
let image = |name: &str, file: &str, role: &str, fmt: &str, data: &[u8]| {
let sha: String = Sha256::digest(data).iter().map(|b| format!("{b:02x}")).collect();
json!({"name": name, "file": file, "role": role, "format": fmt,
"size": data.len(), "sha256": sha, "partition": "nvdata", "install": true})
};
let value = json!({
"schema": 2, "format": "afw", "board": "a113d", "arch": "arm64",
"version": "0.1.0", "build_date": "2026-11-06T00:00:00Z",
"sdk_revision": REV, "os_revision": REV, "payload_type": "os",
"bootloader_policy": "preserve",
"signature": {"type": "unsigned", "member": null, "public_key_hex": null},
"partitions": partitions,
"images": [
image("kernel", "payload/vmlinux.bin", "kernel", "arm64-image", &kernel),
image("dtb", "payload/devicetree.dtb", "dtb", "fdt", &dtb),
image("rootfs", "payload/uramdisk.image.gz", "rootfs", "uimage", &rootfs),
],
"boot_switch": {}, "preflight": {"min_free_bytes": 16777216},
"recovery": {}, "marker": "Alkane", "kernel_version": "6.18.48"
});
let manifest: AfwManifest = serde_json::from_value(value).unwrap();
VerifiedAfw {
manifest,
members: vec![
AfwMember { name: "payload/vmlinux.bin".to_owned(), data: kernel },
AfwMember { name: "payload/devicetree.dtb".to_owned(), data: dtb },
AfwMember { name: "payload/uramdisk.image.gz".to_owned(), data: rootfs },
],
manifest_sha256: "0".repeat(64),
archive_sha256: "0".repeat(64),
}
}
fn preserved_partitions() -> serde_json::Value {
json!([
{"name":"bootloader","device":"/dev/mtd0","offset":0,"size":2097152,
"secure":true,"boot_critical":true,"write_order":0,"image":null},
{"name":"nvdata","device":"/dev/mtd6","offset":74448896,"size":193986560,
"secure":false,"boot_critical":true,"write_order":1,"image":"kernel"}
])
}
fn good() -> VerifiedAfw {
afw_with(arm64_image(b"k"), dtb(), uramdisk(), preserved_partitions())
}
#[test]
fn accepts_a_good_plan_as_file_copies() {
let plan = A113dPlan::from_afw(&good()).unwrap();
assert_eq!(plan.targets.len(), 3);
// write order rootfs, dtb, kernel (kernel file lands last)
assert_eq!(plan.targets[0].image_name, "rootfs");
assert_eq!(plan.targets[2].image_name, "kernel");
// Every destination is a bare basename - no raw device anywhere.
assert!(no_raw_device_targets(&plan));
for t in &plan.targets {
assert!(!t.dest.contains('/'), "{} has a path, not a basename", t.image_name);
}
assert!(plan.render().contains("anthillos/"));
assert!(plan.render().contains("zero raw NAND writes"));
}
#[test]
fn refuses_a_non_arm64_kernel() {
let r = A113dPlan::from_afw(&afw_with(vec![0u8; 64], dtb(), uramdisk(), preserved_partitions()));
assert!(matches!(r, Err(A113dPlanError::NotArm64 { .. })));
}
#[test]
fn refuses_an_oversize_kernel() {
let big = arm64_image(&vec![0u8; 0x4000000]);
let r = A113dPlan::from_afw(&afw_with(big, dtb(), uramdisk(), preserved_partitions()));
assert!(matches!(r, Err(A113dPlanError::ImageTooLarge { .. })));
}
#[test]
fn refuses_a_fip_member() {
let mut v = good();
v.manifest.images[0].role = "bootloader".to_owned();
assert!(matches!(A113dPlan::from_afw(&v), Err(A113dPlanError::BootloaderMember(_))));
let mut v = good();
v.manifest.images[1].file = "payload/fip.bin".to_owned();
assert!(matches!(A113dPlan::from_afw(&v), Err(A113dPlanError::BootloaderMember(_))));
}
#[test]
fn refuses_a_preserved_partition_carrying_an_image() {
let partitions = json!([
{"name":"bootloader","device":"/dev/mtd0","offset":0,"size":2097152,
"secure":true,"boot_critical":true,"write_order":0,"image":"kernel"},
{"name":"nvdata","device":"/dev/mtd6","offset":74448896,"size":193986560,
"secure":false,"boot_critical":true,"write_order":1,"image":"kernel"}
]);
let v = afw_with(arm64_image(b"k"), dtb(), uramdisk(), partitions);
assert!(matches!(
A113dPlan::from_afw(&v),
Err(A113dPlanError::PreservedCarriesImage(_))
));
}
#[test]
fn wrong_board_and_arch_are_refused() {
let mut v = good();
v.manifest.board = "zynq-7010".to_owned();
assert!(matches!(A113dPlan::from_afw(&v), Err(A113dPlanError::WrongBoard(_))));
let mut v = good();
v.manifest.arch = "armv7".to_owned();
assert!(matches!(A113dPlan::from_afw(&v), Err(A113dPlanError::WrongArch(_))));
}
#[test]
fn every_target_is_a_basename_never_a_device() {
for (image, dest, _ceiling, _fmt) in TARGETS {
assert!(is_safe_dest(dest), "{image} dest {dest} is not a safe basename");
for dev in PRESERVE_DEVICES {
assert!(!dest.contains(dev), "{image} dest names a preserved device");
}
}
}
#[test]
fn unsafe_dest_is_rejected_by_guard() {
assert!(!is_safe_dest("/dev/mtd0"));
assert!(!is_safe_dest("../escape"));
assert!(!is_safe_dest("sub/dir/file"));
assert!(is_safe_dest("vmlinux.bin"));
}
}
+1
View File
@@ -2,6 +2,7 @@
//! Board modules. Each module validates the verified manifest for its family
//! and exposes the exact write plan the installer follows.
pub mod a113d;
pub mod am335x;
pub mod cv1835;
pub mod zynq;