flash: restore the Zynq from its on-board stock backup

A from-stock install now leaves a complete genuine-stock backup on the
board (stock device tree, kernel and ramdisk) in the reserved NAND region
after the alkane MAC area, clear of the stock configs UBI and all alkane
boot slots.

Add network-only StockMethod calls to check for that backup and restore
the board to genuine stock from it, with public wrappers and interface
tests. BOOT.bin is preserved.

Verified: cargo build -p alkane-flash; cargo test -p alkane-flash
(74 passed, 1 ignored).
This commit is contained in:
DeepSeek Harness
2026-11-13 11:45:16 -06:00
parent 224b3b37e8
commit bccfaae2fa
2 changed files with 826 additions and 12 deletions
+130
View File
@@ -12,6 +12,11 @@
//! (`StockMethod`, `StockError`) plus the toolkit-side orchestration and
//! verification around the method. The method is plain Rust and must be
//! network-only.
//!
//! A from-stock install also leaves a complete genuine-stock backup on the
//! board: the stock device tree, kernel and ramdisk, in the reserved NAND
//! region after the alkane MAC area. The two on-board backup calls below check
//! and restore that copy over the network, with no vendor firmware file.
use alkane_artifacts::afw::VerifiedAfw;
use std::path::{Path, PathBuf};
@@ -157,6 +162,26 @@ pub trait StockMethod {
password: Option<&str>,
options: &InPlaceOptions,
) -> Result<InPlaceOutcome, StockError>;
/// Report, over the network only, whether the board holds a complete
/// on-board stock backup that can be restored without a vendor firmware
/// file. False means absent or incomplete; it is not an error.
fn onboard_stock_backup_present(
&self,
host: &str,
password: Option<&str>,
) -> Result<bool, StockError>;
/// Return an alkane board to genuine stock, over the network only, using
/// the on-board stock backup. The backup must be present and complete; call
/// `onboard_stock_backup_present` first. `timeout` bounds the wait for the
/// restored board to answer as stock after the reboot.
fn restore_from_onboard_backup(
&self,
host: &str,
password: Option<&str>,
timeout: std::time::Duration,
) -> Result<(), StockError>;
}
/// The compiled-in method implementation.
@@ -164,6 +189,26 @@ pub fn method() -> &'static dyn StockMethod {
crate::stock_method::method()
}
/// Report, over the network only, whether the board holds a complete on-board
/// stock backup that can be restored without a vendor firmware file.
pub fn onboard_stock_backup_present(
host: &str,
password: Option<&str>,
) -> Result<bool, StockError> {
method().onboard_stock_backup_present(host, password)
}
/// Return an alkane board to genuine stock (network-only) using its on-board
/// stock backup, via the compiled-in method. The backup must be present and
/// complete; check it first with [`onboard_stock_backup_present`].
pub fn restore_from_onboard_backup(
host: &str,
password: Option<&str>,
timeout: std::time::Duration,
) -> Result<(), StockError> {
method().restore_from_onboard_backup(host, password, timeout)
}
/// Install alkane onto a board on stock (network-only), via the compiled-in method.
pub fn install_from_stock(
host: &str,
@@ -215,8 +260,93 @@ mod tests {
// The interface is exercised against whatever `stock_method` provides. We
// only assert the toolkit wires a method object in; its behaviour is the
// method module's own tests.
#[test]
fn public_signatures_are_wired() {
let _: fn(&str, Option<&str>) -> Result<bool, StockError> = onboard_stock_backup_present;
let _: fn(&str, Option<&str>, std::time::Duration) -> Result<(), StockError> =
restore_from_onboard_backup;
}
struct FakeMethod {
present: bool,
}
impl StockMethod for FakeMethod {
fn install_from_stock(
&self,
_: &str,
_: &Path,
_: &VerifiedAfw,
_: Option<&str>,
) -> Result<(), StockError> {
Err(StockError::NotImplemented)
}
fn restore_to_stock(
&self,
_: &str,
_: &RestoreImages,
_: Option<&str>,
) -> Result<(), StockError> {
Err(StockError::NotImplemented)
}
fn update_in_place(
&self,
_: &str,
_: &VerifiedAfw,
_: Option<&str>,
_: &InPlaceOptions,
) -> Result<InPlaceOutcome, StockError> {
Err(StockError::NotImplemented)
}
fn onboard_stock_backup_present(
&self,
_: &str,
_: Option<&str>,
) -> Result<bool, StockError> {
Ok(self.present)
}
fn restore_from_onboard_backup(
&self,
_: &str,
_: Option<&str>,
_: std::time::Duration,
) -> Result<(), StockError> {
if self.present {
Ok(())
} else {
Err(StockError::Method(
"no complete on-board stock backup".into(),
))
}
}
}
#[test]
fn a_method_is_compiled_in() {
let _m: &dyn StockMethod = method();
}
#[test]
fn onboard_backup_methods_report_present_or_absent() {
let present = FakeMethod { present: true };
assert!(present
.onboard_stock_backup_present("192.0.2.10", Some("secret"))
.unwrap());
assert!(present
.restore_from_onboard_backup("192.0.2.10", Some("secret"), std::time::Duration::ZERO)
.is_ok());
let absent = FakeMethod { present: false };
assert!(!absent
.onboard_stock_backup_present("192.0.2.10", None)
.unwrap());
assert!(matches!(
absent.restore_from_onboard_backup("192.0.2.10", None, std::time::Duration::ZERO),
Err(StockError::Method(_))
));
}
}
+696 -12
View File
@@ -40,6 +40,14 @@ const DTB_SLOT: u64 = 0x20000;
const KERNEL_SLOT: u64 = 0x800000;
const ROOTFS_SLOT: u64 = 0x2000000;
// A complete genuine-stock backup kept on the board by a from-stock install.
// The area sits in the vendor `reserve` partition after the alkane MAC region,
// clear of the stock `configs` UBI, the alkane boot slots and BOOT.bin.
const STOCK_BACKUP_BASE: u64 = 0x5200000;
const STOCK_BACKUP_END: u64 = 0x6000000;
const STOCK_BACKUP_HEADER: u64 = 0x20000;
const STOCK_BACKUP_MAGIC: &str = "ALKANE-STOCK-BACKUP 1";
// ---------------------------------------------------------------- stock assets
//
// The stock payloads are not compiled into the toolkit. They are fetched over
@@ -1479,12 +1487,7 @@ fn map_covers_boot_regions(map: &[Mtd]) -> bool {
.all(|absolute| locate_mtd(map, *absolute).is_some())
}
fn get_mtd_map(host: &str, password: Option<&str>) -> Result<Vec<Mtd>, StockError> {
let map = read_mtd_map(host, password)?;
if map_covers_boot_regions(&map) {
return Ok(map);
}
fn apply_mtd_patch(host: &str, password: Option<&str>) -> Result<(), StockError> {
let mtd_patch = stock_asset(&ASSET_MTD_PATCH)?;
ssh_push(
host,
@@ -1510,6 +1513,15 @@ fn get_mtd_map(host: &str, password: Option<&str>) -> Result<Vec<Mtd>, StockErro
"target storage layout unsupported".into(),
));
}
Ok(())
}
fn get_mtd_map(host: &str, password: Option<&str>) -> Result<Vec<Mtd>, StockError> {
let map = read_mtd_map(host, password)?;
if map_covers_boot_regions(&map) {
return Ok(map);
}
apply_mtd_patch(host, password)?;
let map = read_mtd_map(host, password)?;
if !map_covers_boot_regions(&map) {
return Err(StockError::Method(
@@ -1519,6 +1531,28 @@ fn get_mtd_map(host: &str, password: Option<&str>) -> Result<Vec<Mtd>, StockErro
Ok(map)
}
/// Like `get_mtd_map`, but also requires `absolute` to be reachable. The
/// per-board storage helper re-registers the boot regions; on alkane that same
/// view includes the reserve area used for the on-board stock backup.
fn get_mtd_map_for_backup(
host: &str,
password: Option<&str>,
absolute: u64,
) -> Result<Vec<Mtd>, StockError> {
let map = read_mtd_map(host, password)?;
if map_covers_boot_regions(&map) && locate_mtd(&map, absolute).is_some() {
return Ok(map);
}
apply_mtd_patch(host, password)?;
let map = read_mtd_map(host, password)?;
if !map_covers_boot_regions(&map) || locate_mtd(&map, absolute).is_none() {
return Err(StockError::Method(
"target storage layout unsupported".into(),
));
}
Ok(map)
}
fn locate_mtd(map: &[Mtd], absolute: u64) -> Option<(&Mtd, u64)> {
for mtd in map {
if mtd.offset <= absolute && absolute < mtd.offset + mtd.size {
@@ -1640,7 +1674,134 @@ fn stock_web_targets(
// ---------------------------------------------------------------- scripts
fn flash_script(targets: &[FlashTarget], token: &str, web_cgi: Option<&str>) -> String {
// Runs as root inside the from-stock web helper, before any alkane image is
// written. It leaves the genuine stock boot chain in the reserve area and
// writes the manifest last. Any failure exits through `fail`, so the stock
// board is never touched unless the backup is complete.
const STOCK_BACKUP_WEB_SCRIPT: &str = r#"
ak_base=0x5200000
ak_end=0x6000000
ak_hdr=131072
ak_blk=131072
ak_src_dtb=0x1a00000
ak_src_kernel=0x2000000
ak_src_ramdisk=0x2800000
ak_num() {
printf '%d\n' "$(( $1 ))"
}
ak_mtd_for() {
ak_abs=$(ak_num "$1") || return 1
for ak_d in /sys/class/mtd/mtd[0-9]*; do
[ -e "$ak_d/offset" ] || continue
ak_off=$(cat "$ak_d/offset" 2>/dev/null) || continue
ak_siz=$(cat "$ak_d/size" 2>/dev/null) || continue
[ -n "$ak_off" ] && [ -n "$ak_siz" ] || continue
ak_off=$(ak_num "$ak_off") || continue
ak_siz=$(ak_num "$ak_siz") || continue
if [ "$ak_abs" -ge "$ak_off" ] && [ "$ak_abs" -lt "$((ak_off + ak_siz))" ]; then
ak_name=$(basename "$ak_d")
printf '%s %s %s\n' "/dev/$ak_name" "$((ak_abs - ak_off))" "$ak_off"
return 0
fi
done
return 1
}
ak_be32() {
set -- $(od -An -tx1 -j "$2" -N4 "$1" 2>/dev/null)
[ "$#" -eq 4 ] || return 1
printf '%d\n' "$(( (0x$1 << 24) | (0x$2 << 16) | (0x$3 << 8) | 0x$4 ))"
}
ak_uimage_len() {
ak_magic=$(dd if="$1" bs=1 count=4 2>/dev/null | od -An -tx1 | tr -d ' \n')
[ "$ak_magic" = "27051956" ] || return 1
ak_total=$((64 + $(ak_be32 "$1" 12))) || return 1
[ "$ak_total" -gt 64 ] || return 1
ak_bytes=$(( ((ak_total + ak_blk - 1) / ak_blk) * ak_blk ))
[ "$((ak_bytes <= $2))" -eq 1 ] || return 1
printf '%d\n' "$ak_bytes"
}
set -- $(ak_mtd_for "$ak_base")
[ "$#" -eq 3 ] || fail bk-map
ak_dev=$1
ak_bakrel=$2
ak_devoff=$3
set -- $(ak_mtd_for "$ak_src_dtb")
[ "$#" -eq 3 ] || fail bk-src-dtb
ak_srcrel=$2
[ "$((ak_srcrel % ak_blk))" -eq 0 ] || fail bk-align-dtb
dd if="$1" bs="$ak_blk" skip="$((ak_srcrel / ak_blk))" count=1 of=/tmp/.ak-bk-dtb 2>/dev/null || fail bk-read-dtb
[ "$(wc -c < /tmp/.ak-bk-dtb 2>/dev/null)" = "$ak_hdr" ] || fail bk-short-dtb
ak_dtb_md5=$(md5sum /tmp/.ak-bk-dtb | cut -d' ' -f1) || fail bk-md5-dtb
ak_dtb_size=$ak_hdr
set -- $(ak_mtd_for "$ak_src_kernel")
[ "$#" -eq 3 ] || fail bk-src-kernel
ak_srcrel=$2
[ "$((ak_srcrel % ak_blk))" -eq 0 ] || fail bk-align-kernel
dd if="$1" bs="$ak_blk" skip="$((ak_srcrel / ak_blk))" count=1 of=/tmp/.ak-bk-kernel-head 2>/dev/null || fail bk-read-kernel
ak_kernel_size=$(ak_uimage_len /tmp/.ak-bk-kernel-head 0x800000) || fail bk-kernel
dd if="$1" bs="$ak_blk" skip="$((ak_srcrel / ak_blk))" count="$((ak_kernel_size / ak_blk))" of=/tmp/.ak-bk-kernel 2>/dev/null || fail bk-read-kernel
[ "$(wc -c < /tmp/.ak-bk-kernel 2>/dev/null)" = "$ak_kernel_size" ] || fail bk-short-kernel
ak_kernel_md5=$(md5sum /tmp/.ak-bk-kernel | cut -d' ' -f1) || fail bk-md5-kernel
set -- $(ak_mtd_for "$ak_src_ramdisk")
[ "$#" -eq 3 ] || fail bk-src-ramdisk
ak_srcrel=$2
[ "$((ak_srcrel % ak_blk))" -eq 0 ] || fail bk-align-ramdisk
dd if="$1" bs="$ak_blk" skip="$((ak_srcrel / ak_blk))" count=1 of=/tmp/.ak-bk-ramdisk-head 2>/dev/null || fail bk-read-ramdisk
ak_ramdisk_size=$(ak_uimage_len /tmp/.ak-bk-ramdisk-head 0x2000000) || fail bk-ramdisk
dd if="$1" bs="$ak_blk" skip="$((ak_srcrel / ak_blk))" count="$((ak_ramdisk_size / ak_blk))" of=/tmp/.ak-bk-ramdisk 2>/dev/null || fail bk-read-ramdisk
[ "$(wc -c < /tmp/.ak-bk-ramdisk 2>/dev/null)" = "$ak_ramdisk_size" ] || fail bk-short-ramdisk
ak_ramdisk_md5=$(md5sum /tmp/.ak-bk-ramdisk | cut -d' ' -f1) || fail bk-md5-ramdisk
ak_dtb_bak=$((ak_base + ak_hdr))
ak_kernel_bak=$((ak_dtb_bak + ak_dtb_size))
ak_ramdisk_bak=$((ak_kernel_bak + ak_kernel_size))
ak_end_used=$((ak_ramdisk_bak + ak_ramdisk_size))
[ "$((ak_end_used <= ak_end))" -eq 1 ] || fail bk-space
set -- $(ak_mtd_for "$ak_dtb_bak")
[ "$#" -eq 3 ] && [ "$1" = "$ak_dev" ] || fail bk-split
set -- $(ak_mtd_for "$ak_kernel_bak")
[ "$#" -eq 3 ] && [ "$1" = "$ak_dev" ] || fail bk-split
set -- $(ak_mtd_for "$ak_ramdisk_bak")
[ "$#" -eq 3 ] && [ "$1" = "$ak_dev" ] || fail bk-split
ak_blocks=$(( (ak_end_used - ak_base) / ak_blk ))
flash_erase "$ak_dev" "$ak_bakrel" "$ak_blocks" >/dev/null 2>&1 || fail bk-erase
nandwrite -p -s "$((ak_dtb_bak - ak_devoff))" "$ak_dev" /tmp/.ak-bk-dtb >/dev/null 2>&1 || fail bk-write-dtb
nandwrite -p -s "$((ak_kernel_bak - ak_devoff))" "$ak_dev" /tmp/.ak-bk-kernel >/dev/null 2>&1 || fail bk-write-kernel
nandwrite -p -s "$((ak_ramdisk_bak - ak_devoff))" "$ak_dev" /tmp/.ak-bk-ramdisk >/dev/null 2>&1 || fail bk-write-ramdisk
ak_v=$(dd if="$ak_dev" bs="$ak_blk" skip="$(( (ak_dtb_bak - ak_devoff) / ak_blk ))" count="$((ak_dtb_size / ak_blk))" 2>/dev/null | md5sum | cut -d' ' -f1)
[ "$ak_v" = "$ak_dtb_md5" ] || fail bk-verify-dtb
ak_v=$(dd if="$ak_dev" bs="$ak_blk" skip="$(( (ak_kernel_bak - ak_devoff) / ak_blk ))" count="$((ak_kernel_size / ak_blk))" 2>/dev/null | md5sum | cut -d' ' -f1)
[ "$ak_v" = "$ak_kernel_md5" ] || fail bk-verify-kernel
ak_v=$(dd if="$ak_dev" bs="$ak_blk" skip="$(( (ak_ramdisk_bak - ak_devoff) / ak_blk ))" count="$((ak_ramdisk_size / ak_blk))" 2>/dev/null | md5sum | cut -d' ' -f1)
[ "$ak_v" = "$ak_ramdisk_md5" ] || fail bk-verify-ramdisk
{
printf '%s\n' "ALKANE-STOCK-BACKUP 1"
printf 'dtb 0x1a00000 0x%x 0x%x %s\n' "$ak_dtb_bak" "$ak_dtb_size" "$ak_dtb_md5"
printf 'kernel 0x2000000 0x%x 0x%x %s\n' "$ak_kernel_bak" "$ak_kernel_size" "$ak_kernel_md5"
printf 'ramdisk 0x2800000 0x%x 0x%x %s\n' "$ak_ramdisk_bak" "$ak_ramdisk_size" "$ak_ramdisk_md5"
printf '%s\n' "end"
} > /tmp/.ak-bk-header || fail bk-header
nandwrite -p -s "$ak_bakrel" "$ak_dev" /tmp/.ak-bk-header >/dev/null 2>&1 || fail bk-write-header
ak_v=$(dd if="$ak_dev" bs="$ak_blk" skip="$((ak_bakrel / ak_blk))" count=1 2>/dev/null | head -c 19)
[ "$ak_v" = "ALKANE-STOCK-BACKUP" ] || fail bk-verify-header
rm -f /tmp/.ak-bk-dtb /tmp/.ak-bk-kernel /tmp/.ak-bk-kernel-head \
/tmp/.ak-bk-ramdisk /tmp/.ak-bk-ramdisk-head /tmp/.ak-bk-header
"#;
fn flash_script(
targets: &[FlashTarget],
token: &str,
web_cgi: Option<&str>,
with_stock_backup: bool,
) -> String {
let mut script = String::new();
script.push_str("#!/bin/sh\n");
script.push_str("set -u\n");
@@ -1649,6 +1810,10 @@ fn flash_script(targets: &[FlashTarget], token: &str, web_cgi: Option<&str>) ->
}
script.push_str("fail(){ echo \"@@FAIL@@ $*\"; sync; exit 1; }\n");
if with_stock_backup {
script.push_str(STOCK_BACKUP_WEB_SCRIPT);
}
for target in targets {
let path = if web_cgi.is_some() {
format!("/tmp/.ak-{token}-{}", target.file)
@@ -1757,6 +1922,452 @@ fn build_web_body(
(body, boundary)
}
// ---------------------------------------------------------------- on-board stock backup
//
// A from-stock install copies the genuine stock device tree, kernel and ramdisk
// off their slots into the vendor `reserve` area before anything is overwritten.
// The copy is block-padded, carries a small text manifest with a digest for each
// member, and is written manifest-last so an interrupted install never leaves a
// backup that passes the presence check. Ownership/format stay inside this
// module; the public interface only reports complete/absent and restores.
#[derive(Clone, Debug)]
struct StockBackupEntry {
name: &'static str,
target_abs: u64,
backup_abs: u64,
size: u64,
md5: String,
}
#[derive(Clone, Debug)]
struct StockBackup {
entries: Vec<StockBackupEntry>,
}
fn parse_hex_u64(value: &str) -> Option<u64> {
let digits = value
.strip_prefix("0x")
.or_else(|| value.strip_prefix("0X"))?;
u64::from_str_radix(digits, 16).ok()
}
fn stock_entry_spec(name: &str) -> Option<(&'static str, u64, u64)> {
match name {
"dtb" => Some(("dtb", ABS_DTB, DTB_SLOT)),
"kernel" => Some(("kernel", ABS_KERNEL, KERNEL_SLOT)),
"ramdisk" => Some(("ramdisk", ABS_ROOTFS, ROOTFS_SLOT)),
_ => None,
}
}
fn parse_stock_backup(header: &[u8]) -> Option<StockBackup> {
let text = String::from_utf8_lossy(header);
let mut lines = text.lines();
let first = lines.next()?.trim_matches('\0').trim();
if first != STOCK_BACKUP_MAGIC {
return None;
}
let mut entries = Vec::new();
let mut ended = false;
for raw in lines {
let line = raw.trim_matches('\0').trim();
if line.is_empty() {
continue;
}
if line == "end" {
ended = true;
break;
}
let fields: Vec<&str> = line.split_whitespace().collect();
if fields.len() != 5 {
return None;
}
let (name, target_abs, slot) = stock_entry_spec(fields[0])?;
let declared_target = parse_hex_u64(fields[1])?;
let backup_abs = parse_hex_u64(fields[2])?;
let size = parse_hex_u64(fields[3])?;
let md5 = fields[4].to_ascii_lowercase();
if declared_target != target_abs
|| md5.len() != 32
|| !md5.chars().all(|c| c.is_ascii_hexdigit())
{
return None;
}
if size == 0 || size % BLK != 0 || size > slot || (name == "dtb" && size != DTB_SLOT) {
return None;
}
let backup_end = backup_abs.checked_add(size)?;
if backup_abs % BLK != 0
|| backup_abs < STOCK_BACKUP_BASE + STOCK_BACKUP_HEADER
|| backup_end > STOCK_BACKUP_END
{
return None;
}
if entries
.iter()
.any(|entry: &StockBackupEntry| entry.name == name)
{
return None;
}
entries.push(StockBackupEntry {
name,
target_abs,
backup_abs,
size,
md5,
});
}
if !ended || entries.len() != 3 {
return None;
}
let mut spans: Vec<(u64, u64)> = entries
.iter()
.map(|entry| (entry.backup_abs, entry.backup_abs + entry.size))
.collect();
spans.sort_unstable();
for pair in spans.windows(2) {
if pair[0].1 > pair[1].0 {
return None;
}
}
Some(StockBackup { entries })
}
fn render_stock_backup(entries: &[StockBackupEntry]) -> Vec<u8> {
let mut text = String::new();
text.push_str(STOCK_BACKUP_MAGIC);
text.push('\n');
for entry in entries {
text.push_str(&format!(
"{} 0x{:x} 0x{:x} 0x{:x} {}\n",
entry.name, entry.target_abs, entry.backup_abs, entry.size, entry.md5
));
}
text.push_str("end\n");
text.into_bytes()
}
fn read_mtd_span(
host: &str,
password: Option<&str>,
map: &[Mtd],
absolute: u64,
size: u64,
label: &str,
) -> Result<Vec<u8>, StockError> {
if size == 0 || size % BLK != 0 {
return Err(StockError::Method(
"target storage layout unsupported".into(),
));
}
let (mtd, rel) = locate_mtd(map, absolute)
.ok_or_else(|| StockError::Method("target storage layout unsupported".into()))?;
if rel.checked_add(size).map_or(true, |end| end > mtd.size) {
return Err(StockError::Method(
"target storage layout unsupported".into(),
));
}
let remote = format!(
"dd if={} bs={} skip={} count={} 2>/dev/null",
mtd.device,
BLK,
rel / BLK,
size / BLK
);
let result = ssh_exec(host, password, &remote, Duration::from_secs(600))?;
if !result.ok() {
return Err(StockError::Method(format!(
"could not read the on-board stock {label} backup"
)));
}
if result.stdout.len() as u64 != size {
return Err(StockError::Method(format!(
"the on-board stock {label} backup is short"
)));
}
Ok(result.stdout)
}
fn stock_uimage_span(
host: &str,
password: Option<&str>,
map: &[Mtd],
absolute: u64,
slot: u64,
label: &str,
) -> Result<Vec<u8>, StockError> {
let first = read_mtd_span(host, password, map, absolute, BLK, label)?;
if first.len() < 64 || first[..4] != [0x27, 0x05, 0x19, 0x56] {
return Err(StockError::Method(format!(
"the on-board stock {label} slot does not hold a stock image"
)));
}
let payload = u32::from_be_bytes([first[12], first[13], first[14], first[15]]) as u64;
let total = 64u64
.checked_add(payload)
.ok_or_else(|| StockError::Method(format!("the on-board stock {label} slot is invalid")))?;
let bytes = total.div_ceil(BLK) * BLK;
if total <= 64 || bytes > slot {
return Err(StockError::Method(format!(
"the on-board stock {label} slot does not hold a stock image"
)));
}
if bytes <= BLK {
return Ok(first[..bytes as usize].to_vec());
}
let rest = read_mtd_span(host, password, map, absolute + BLK, bytes - BLK, label)?;
let mut out = first;
out.extend_from_slice(&rest);
out.truncate(bytes as usize);
Ok(out)
}
fn read_validated_onboard_stock_backup(
host: &str,
password: Option<&str>,
map: &[Mtd],
) -> Result<Option<StockBackup>, StockError> {
let Some((mtd, rel)) = locate_mtd(map, STOCK_BACKUP_BASE) else {
return Ok(None);
};
if rel
.checked_add(STOCK_BACKUP_HEADER)
.map_or(true, |end| end > mtd.size)
{
return Ok(None);
}
let remote = format!(
"dd if={} bs={} skip={} count={} 2>/dev/null",
mtd.device,
BLK,
rel / BLK,
STOCK_BACKUP_HEADER / BLK
);
let header = ssh_exec(host, password, &remote, Duration::from_secs(120))?;
if !header.ok() || header.stdout.len() as u64 != STOCK_BACKUP_HEADER {
return Ok(None);
}
let Some(backup) = parse_stock_backup(&header.stdout) else {
return Ok(None);
};
for entry in &backup.entries {
let Some((entry_mtd, entry_rel)) = locate_mtd(map, entry.backup_abs) else {
return Ok(None);
};
if entry_rel
.checked_add(entry.size)
.map_or(true, |end| end > entry_mtd.size)
{
return Ok(None);
}
let remote = format!(
"dd if={} bs={} skip={} count={} 2>/dev/null | md5sum | cut -d' ' -f1",
entry_mtd.device,
BLK,
entry_rel / BLK,
entry.size / BLK
);
let result = ssh_exec(host, password, &remote, Duration::from_secs(300))?;
if !result.ok() {
return Ok(None);
}
if !text(&result.stdout).trim().eq_ignore_ascii_case(&entry.md5) {
return Ok(None);
}
}
Ok(Some(backup))
}
fn create_onboard_stock_backup(
host: &str,
password: Option<&str>,
map: &[Mtd],
) -> Result<(), StockError> {
let dtb = read_mtd_span(host, password, map, ABS_DTB, DTB_SLOT, "device tree")?;
if dtb.len() < 8 || dtb[..4] != [0xd0, 0x0d, 0xfe, 0xed] {
return Err(StockError::Method(
"the stock device tree slot is not usable for a backup".into(),
));
}
let kernel = stock_uimage_span(host, password, map, ABS_KERNEL, KERNEL_SLOT, "kernel")?;
let ramdisk = stock_uimage_span(host, password, map, ABS_ROOTFS, ROOTFS_SLOT, "ramdisk")?;
let mut prepared: Vec<(&'static str, u64, Vec<u8>)> = vec![
("dtb", ABS_DTB, dtb),
("kernel", ABS_KERNEL, kernel),
("ramdisk", ABS_ROOTFS, ramdisk),
];
let mut entries = Vec::with_capacity(prepared.len());
let mut next = STOCK_BACKUP_BASE + STOCK_BACKUP_HEADER;
for (name, target_abs, data) in &prepared {
let size = data.len() as u64;
if next
.checked_add(size)
.map_or(true, |end| end > STOCK_BACKUP_END)
{
return Err(StockError::Method(
"the on-board stock backup area is too small".into(),
));
}
entries.push(StockBackupEntry {
name,
target_abs: *target_abs,
backup_abs: next,
size,
md5: md5_hex(data),
});
next += size;
}
let header = render_stock_backup(&entries);
let mut write: Vec<(&'static str, &'static str, u64, u64, Cow<'static, [u8]>)> = Vec::new();
write.push((
"backup-header-clear",
"stock-backup-empty.bin",
STOCK_BACKUP_BASE,
STOCK_BACKUP_HEADER,
Cow::Owned(vec![0u8; STOCK_BACKUP_HEADER as usize]),
));
for (entry, (_, _, data)) in entries.iter().zip(prepared.drain(..)) {
write.push((
match entry.name {
"dtb" => "backup-dtb",
"kernel" => "backup-kernel",
_ => "backup-ramdisk",
},
match entry.name {
"dtb" => "stock-backup.dtb",
"kernel" => "stock-backup-kernel.uimg",
_ => "stock-backup-ramdisk.uimg",
},
entry.backup_abs,
entry.size,
Cow::Owned(data),
));
}
write.push((
"backup-header",
"stock-backup.txt",
STOCK_BACKUP_BASE,
STOCK_BACKUP_HEADER,
Cow::Owned(header),
));
let targets = targets_from_map(map, write)?;
flash_via_ssh(host, password, &targets)?;
match read_validated_onboard_stock_backup(host, password, map)? {
Some(_) => Ok(()),
None => Err(StockError::Method(
"the on-board stock backup did not verify after it was written".into(),
)),
}
}
fn restore_from_onboard_backup_impl(
host: &str,
password: Option<&str>,
timeout: Duration,
) -> Result<(), StockError> {
validate_host(host)?;
if !ssh_port_open(host) {
if is_stock_http(host) {
return Ok(());
}
return Err(StockError::Network("target unreachable".into()));
}
let resolved = resolve_password(password);
let password = resolved.as_deref();
ssh_probe(host, password)?;
let state = board_state(host, password)?;
if state == "stock" {
return Ok(());
}
let map = get_mtd_map_for_backup(host, password, STOCK_BACKUP_BASE)?;
let Some(backup) = read_validated_onboard_stock_backup(host, password, &map)? else {
return Err(StockError::Method(
"no complete on-board stock backup".into(),
));
};
let name = |wanted: &str| -> Result<&StockBackupEntry, StockError> {
backup
.entries
.iter()
.find(|entry| entry.name == wanted)
.ok_or_else(|| StockError::Method("no complete on-board stock backup".into()))
};
let dtb_entry = name("dtb")?;
let kernel_entry = name("kernel")?;
let ramdisk_entry = name("ramdisk")?;
let dtb = read_mtd_span(
host,
password,
&map,
dtb_entry.backup_abs,
dtb_entry.size,
"device tree",
)?;
let kernel = read_mtd_span(
host,
password,
&map,
kernel_entry.backup_abs,
kernel_entry.size,
"kernel",
)?;
let ramdisk = read_mtd_span(
host,
password,
&map,
ramdisk_entry.backup_abs,
ramdisk_entry.size,
"ramdisk",
)?;
let write = vec![
(
"ramdisk",
"stock-rootfs.uimg",
ABS_ROOTFS,
ROOTFS_SLOT,
Cow::Owned(ramdisk),
),
("dtb", "stock-dtb.bin", ABS_DTB, DTB_SLOT, Cow::Owned(dtb)),
(
"kernel",
"stock-kernel.uimg",
ABS_KERNEL,
KERNEL_SLOT,
Cow::Owned(kernel),
),
];
let targets = targets_from_map(&map, write)?;
flash_via_ssh(host, password, &targets)?;
reboot_target(host, password);
let _ = wait_stock(host, timeout);
Ok(())
}
fn onboard_stock_backup_present_impl(
host: &str,
password: Option<&str>,
) -> Result<bool, StockError> {
validate_host(host)?;
if !ssh_port_open(host) {
if is_stock_http(host) {
return Ok(false);
}
return Err(StockError::Network("target unreachable".into()));
}
let resolved = resolve_password(password);
let password = resolved.as_deref();
ssh_probe(host, password)?;
let map = get_mtd_map_for_backup(host, password, STOCK_BACKUP_BASE)?;
Ok(read_validated_onboard_stock_backup(host, password, &map)?.is_some())
}
// ---------------------------------------------------------------- install / restore
fn install_via_web(
@@ -1792,7 +2403,7 @@ fn install_via_web(
let targets = stock_web_targets(kernel, dtb, rootfs)?;
let token = random_token();
let cgi = format!("zz{token}.cgi");
let script = flash_script(&targets, &token, Some(&cgi));
let script = flash_script(&targets, &token, Some(&cgi), true);
let (body, boundary) = build_web_body(&targets, &token, &cgi, &script);
let body_path = dir.join("upload.body");
write_private(&body_path, &body)?;
@@ -1846,8 +2457,16 @@ fn install_via_ssh(
kernel: Vec<u8>,
dtb: Vec<u8>,
rootfs: Vec<u8>,
backup_stock: bool,
) -> Result<(), StockError> {
let map = get_mtd_map(host, password)?;
let map = if backup_stock {
get_mtd_map_for_backup(host, password, STOCK_BACKUP_BASE)?
} else {
get_mtd_map(host, password)?
};
if backup_stock {
create_onboard_stock_backup(host, password, &map)?;
}
let targets = alkane_targets(&map, kernel, dtb, rootfs)?;
flash_via_ssh(host, password, &targets)?;
reboot_target(host, password);
@@ -1877,7 +2496,7 @@ fn flash_via_ssh(
let timeout = Duration::from_secs(300);
ssh_push(host, password, &remote, target.data.as_ref(), timeout)?;
}
let script = flash_script(targets, "", None);
let script = flash_script(targets, "", None, false);
let remote_script = "/tmp/rs/go.sh";
ssh_push(
host,
@@ -2227,7 +2846,7 @@ impl StockMethod for Method {
let resolved = resolve_password(password);
let password = resolved.as_deref();
ssh_probe(host, password)?;
return install_via_ssh(host, password, kernel, dtb, rootfs);
return install_via_ssh(host, password, kernel, dtb, rootfs, false);
}
// A board on genuine stock is reached through its own web gate.
@@ -2236,7 +2855,8 @@ impl StockMethod for Method {
let resolved = resolve_password(password);
let password = resolved.as_deref();
ssh_probe(host, password)?;
return install_via_ssh(host, password, kernel, dtb, rootfs);
let stock = board_state(host, password)? == "stock";
return install_via_ssh(host, password, kernel, dtb, rootfs, stock);
}
return Err(StockError::Network("target unreachable".into()));
}
@@ -2311,6 +2931,23 @@ impl StockMethod for Method {
) -> Result<InPlaceOutcome, StockError> {
update_in_place_impl(host, afw, password, options)
}
fn onboard_stock_backup_present(
&self,
host: &str,
password: Option<&str>,
) -> Result<bool, StockError> {
onboard_stock_backup_present_impl(host, password)
}
fn restore_from_onboard_backup(
&self,
host: &str,
password: Option<&str>,
timeout: Duration,
) -> Result<(), StockError> {
restore_from_onboard_backup_impl(host, password, timeout)
}
}
static METHOD: Method = Method;
@@ -2599,4 +3236,51 @@ mod tests {
assert!(absolute >= BOOTBIN_PRESERVE);
}
}
#[test]
fn stock_backup_manifest_round_trips_and_rejects_incomplete() {
let base = STOCK_BACKUP_BASE + STOCK_BACKUP_HEADER;
let entries = vec![
StockBackupEntry {
name: "dtb",
target_abs: ABS_DTB,
backup_abs: base,
size: DTB_SLOT,
md5: "0".repeat(32),
},
StockBackupEntry {
name: "kernel",
target_abs: ABS_KERNEL,
backup_abs: base + DTB_SLOT,
size: BLK,
md5: "1".repeat(32),
},
StockBackupEntry {
name: "ramdisk",
target_abs: ABS_ROOTFS,
backup_abs: base + DTB_SLOT + BLK,
size: BLK,
md5: "2".repeat(32),
},
];
let header = render_stock_backup(&entries);
let mut padded = header.clone();
padded.resize(STOCK_BACKUP_HEADER as usize, 0xff);
let parsed = parse_stock_backup(&padded).expect("manifest parses");
assert_eq!(parsed.entries.len(), 3);
assert_eq!(parsed.entries[1].size, BLK);
let text = String::from_utf8(header).unwrap();
let missing = text.replace(
&format!(
"kernel 0x{:x} 0x{:x} 0x{:x} {}\n",
ABS_KERNEL,
base + DTB_SLOT,
BLK,
"1".repeat(32)
),
"",
);
assert!(parse_stock_backup(missing.as_bytes()).is_none());
}
}