verify / verify (pull_request) Skipped
source / check (pull_request) Successful in 4m17s
main's verify gate runs cargo fmt --check on the first-party crates; next's gate does not, so the afw/stock feature work reached next unformatted. Pure cargo fmt output. clippy -D warnings (workspace and GUI) and all tests pass. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01B1W6qKwKxq3oUPDKWicM6i
1117 lines
37 KiB
Rust
1117 lines
37 KiB
Rust
// 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;
|
|
pub const AM335X_HOLE_OFFSET: u64 = 0x780000;
|
|
pub const AM335X_HOLE_SIZE: u64 = 0x80000;
|
|
pub const AM335X_CHIP_SIZE: u64 = 0x8000000;
|
|
#[allow(clippy::type_complexity)]
|
|
const AM335X_MAP: &[(&str, u64, u64, bool, bool, i64, Option<&str>)] = &[
|
|
("mtd0", 0x0000000, 0x20000, true, true, 0, None),
|
|
("mtd1", 0x0020000, 0x20000, true, true, 0, None),
|
|
("mtd2", 0x0040000, 0x20000, true, true, 0, None),
|
|
("mtd3", 0x0060000, 0x20000, true, true, 0, None),
|
|
("mtd4", 0x0080000, 0x1C0000, true, true, 0, None),
|
|
("mtd5", 0x0240000, 0x20000, true, true, 0, None),
|
|
("mtd6", 0x0260000, 0x20000, false, true, 2, Some("dtb")),
|
|
("mtd7", 0x0280000, 0x500000, false, true, 3, Some("kernel")),
|
|
("mtd8", 0x0800000, 0x1400000, false, true, 1, Some("rootfs")),
|
|
("mtd9", 0x1C00000, 0x200000, true, false, 0, None),
|
|
("mtd10", 0x1E00000, 0x200000, true, false, 0, None),
|
|
("mtd11", 0x2000000, 0x6000000, true, false, 0, None),
|
|
];
|
|
const AM335X_CEILINGS: &[(&str, u64, &str)] = &[
|
|
("kernel", 0x500000, "mtd7"),
|
|
("dtb", 0x20000, "mtd6"),
|
|
("rootfs", 0x1400000, "mtd8"),
|
|
];
|
|
|
|
const IMAGE_ROLES: &[&str] = &["kernel", "dtb", "rootfs", "bootloader", "boot", "component"];
|
|
const IMAGE_FORMATS: &[&str] = &[
|
|
"fit",
|
|
"arm64-image",
|
|
"zimage",
|
|
"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<BoardProfile> {
|
|
let (arch, bootloader_policy) = match board {
|
|
"am335x" => ("arm", BootloaderPolicy::Preserve),
|
|
// Tier-3 from-stock AM335x: writes our non-RSA U-Boot into mtd4, so its
|
|
// policy is include (the flash module preserves the SPL mtd0-3).
|
|
"am335x-stock" => ("arm", BootloaderPolicy::Include),
|
|
"cv1835" => ("arm64", BootloaderPolicy::Preserve),
|
|
"zynq-7010" => ("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,
|
|
};
|
|
Some(BoardProfile {
|
|
arch,
|
|
bootloader_policy,
|
|
})
|
|
}
|
|
|
|
#[derive(Clone, Debug, Deserialize, Serialize)]
|
|
pub struct AfwSignature {
|
|
#[serde(rename = "type")]
|
|
pub kind: String,
|
|
pub member: Option<String>,
|
|
pub public_key_hex: Option<String>,
|
|
}
|
|
|
|
#[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<String>,
|
|
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<String>,
|
|
}
|
|
|
|
#[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<AfwPartition>,
|
|
pub images: Vec<AfwImage>,
|
|
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<String>,
|
|
}
|
|
|
|
#[derive(Clone, Debug, Eq, PartialEq)]
|
|
pub struct AfwMember {
|
|
pub name: String,
|
|
pub data: Vec<u8>,
|
|
}
|
|
|
|
#[derive(Debug)]
|
|
pub struct VerifiedAfw {
|
|
pub manifest: AfwManifest,
|
|
pub members: Vec<AfwMember>,
|
|
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<String>,
|
|
}
|
|
|
|
pub fn verify_afw(path: &Path, options: &VerifyOptions) -> Result<VerifiedAfw, AfwError> {
|
|
let bytes = fs::read(path)?;
|
|
verify_afw_bytes(&bytes, options)
|
|
}
|
|
|
|
pub fn verify_afw_bytes(bytes: &[u8], options: &VerifyOptions) -> Result<VerifiedAfw, AfwError> {
|
|
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()));
|
|
}
|
|
}
|
|
|
|
if manifest.board == "am335x" {
|
|
validate_am335x(manifest)?;
|
|
}
|
|
|
|
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 validate_am335x(manifest: &AfwManifest) -> Result<(), AfwError> {
|
|
for image in &manifest.images {
|
|
let lowered = format!("{} {}", image.name, image.file).to_lowercase();
|
|
if lowered.contains("spl") || lowered.contains("u-boot") || lowered.contains("uboot") {
|
|
return Err(AfwError::Manifest(format!(
|
|
"am335x bundle carries an spl/u-boot member: {}",
|
|
image.file
|
|
)));
|
|
}
|
|
}
|
|
let install: Vec<&AfwImage> = manifest
|
|
.images
|
|
.iter()
|
|
.filter(|image| image.install)
|
|
.collect();
|
|
if install.len() != 3 {
|
|
return Err(AfwError::Manifest(
|
|
"am335x must install exactly kernel, dtb and rootfs".to_owned(),
|
|
));
|
|
}
|
|
for (name, ceiling, partition) in AM335X_CEILINGS {
|
|
let Some(image) = manifest.images.iter().find(|image| image.name == *name) else {
|
|
return Err(AfwError::Manifest(format!("am335x is missing {name}")));
|
|
};
|
|
let expected_format = if *name == "dtb" { "fdt" } else { "uimage" };
|
|
if !image.install
|
|
|| image.format != expected_format
|
|
|| image.partition.as_deref() != Some(*partition)
|
|
{
|
|
return Err(AfwError::Manifest(format!(
|
|
"am335x {name} must be an installing {expected_format} for {partition}"
|
|
)));
|
|
}
|
|
if image.size > *ceiling {
|
|
return Err(AfwError::ImageTooLarge(image.name.clone()));
|
|
}
|
|
}
|
|
if manifest.partitions.len() != AM335X_MAP.len() {
|
|
return Err(AfwError::Manifest(
|
|
"am335x must plan all 12 mtd partitions".to_owned(),
|
|
));
|
|
}
|
|
for (name, offset, size, secure, boot_critical, write_order, image) in AM335X_MAP {
|
|
let Some(partition) = manifest.partitions.iter().find(|part| part.name == *name) else {
|
|
return Err(AfwError::Manifest(format!("am335x is missing {name}")));
|
|
};
|
|
if partition.offset != *offset
|
|
|| partition.size != *size
|
|
|| partition.secure != *secure
|
|
|| partition.boot_critical != *boot_critical
|
|
|| partition.write_order != *write_order
|
|
|| partition.image.as_deref() != *image
|
|
|| partition.device != format!("/dev/{name}")
|
|
{
|
|
return Err(AfwError::Manifest(format!(
|
|
"am335x {name} geometry is wrong"
|
|
)));
|
|
}
|
|
if partition.offset < AM335X_HOLE_OFFSET + AM335X_HOLE_SIZE
|
|
&& partition.offset + partition.size > AM335X_HOLE_OFFSET
|
|
{
|
|
return Err(AfwError::Manifest(format!(
|
|
"am335x {name} overlaps the 0x780000-0x800000 hole"
|
|
)));
|
|
}
|
|
if (name.starts_with("mtd0") || ["mtd1", "mtd2", "mtd3", "mtd4", "mtd5"].contains(name))
|
|
&& (partition.write_order != 0 || partition.image.is_some())
|
|
{
|
|
return Err(AfwError::Manifest(format!(
|
|
"am335x {name} is preserved and must not be written"
|
|
)));
|
|
}
|
|
}
|
|
let mtd7 = manifest
|
|
.partitions
|
|
.iter()
|
|
.find(|part| part.name == "mtd7")
|
|
.unwrap();
|
|
let mtd8 = manifest
|
|
.partitions
|
|
.iter()
|
|
.find(|part| part.name == "mtd8")
|
|
.unwrap();
|
|
if mtd7.offset + mtd7.size != AM335X_HOLE_OFFSET
|
|
|| mtd8.offset != AM335X_HOLE_OFFSET + AM335X_HOLE_SIZE
|
|
{
|
|
return Err(AfwError::Manifest(
|
|
"am335x mtd7 must end at the 0x780000 hole and mtd8 start at 0x800000".to_owned(),
|
|
));
|
|
}
|
|
let total: u64 = manifest.partitions.iter().map(|part| part.size).sum();
|
|
if total != AM335X_CHIP_SIZE - AM335X_HOLE_SIZE {
|
|
return Err(AfwError::Manifest(
|
|
"am335x partition sizes must sum to 0x7F80000".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",
|
|
"zimage" => "not an ARM zImage",
|
|
"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());
|
|
}
|
|
}
|
|
"zimage" => {
|
|
// ARM zImage magic 0x016f2818 (little-endian) at offset 0x24.
|
|
if data.len() < 0x28 || &data[0x24..0x28] != b"\x18\x28\x6f\x01" {
|
|
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<Vec<AfwMember>, 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::<u64>() != 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<u64, AfwError> {
|
|
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<u8> {
|
|
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<u8> {
|
|
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<u8> {
|
|
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)
|
|
));
|
|
}
|
|
}
|