// SPDX-License-Identifier: MIT //! Verify local firmware artifacts before an install path consumes them. pub mod afw; pub mod fetch; use sha2::{Digest, Sha256}; use std::collections::HashSet; use std::fs::File; use std::io::{Read, Seek, SeekFrom}; use std::path::{Component, Path, PathBuf}; use thiserror::Error; const SEED: &str = include_str!("../data/manifest-seed.csv"); const HEADER: &str = "sha256,size_bytes,path,family,format,applicability"; #[derive(Clone, Debug, Eq, PartialEq)] pub struct ArtifactRecord { pub sha256: String, pub size_bytes: u64, pub path: PathBuf, pub family: String, pub format: String, pub applicability: String, } #[derive(Debug, Error)] pub enum VerifyError { #[error("artifact I/O: {0}")] Io(#[from] std::io::Error), #[error("manifest line {0} is invalid")] Manifest(usize), #[error("artifact size differs from manifest")] Size, #[error("artifact signature does not match its declared format")] Signature, #[error("artifact SHA-256 differs from manifest")] Digest, #[error("artifact format is not recognized")] UnsupportedFormat, } /// A verified, rewound descriptor. Consumers should read this descriptor /// directly instead of reopening the path after verification. pub struct VerifiedArtifact { file: File, record: ArtifactRecord, } impl VerifiedArtifact { pub fn record(&self) -> &ArtifactRecord { &self.record } pub fn reader(&mut self) -> &mut File { &mut self.file } /// Recheck the same descriptor immediately before a guarded write. pub fn revalidate(&mut self) -> Result<(), VerifyError> { verify_open_file(&mut self.file, &self.record) } } pub fn seed_manifest() -> Result, VerifyError> { parse_manifest(SEED) } pub fn parse_manifest(text: &str) -> Result, VerifyError> { let mut lines = text.lines(); if lines.next() != Some(HEADER) { return Err(VerifyError::Manifest(1)); } let mut paths = HashSet::new(); let mut records = Vec::new(); for (line_number, line) in lines.enumerate() { let line_number = line_number + 2; let parts: Vec<_> = line.splitn(6, ',').collect(); if parts.len() != 6 || parts.iter().any(|part| part.trim().is_empty()) { return Err(VerifyError::Manifest(line_number)); } let digest = parts[0]; let path = PathBuf::from(parts[2]); if digest.len() != 64 || !digest.bytes().all(|byte| byte.is_ascii_hexdigit()) || !path .components() .all(|part| matches!(part, Component::Normal(_))) || !paths.insert(path.clone()) { return Err(VerifyError::Manifest(line_number)); } let size_bytes = parts[1] .parse::() .map_err(|_| VerifyError::Manifest(line_number))?; if size_bytes == 0 { return Err(VerifyError::Manifest(line_number)); } records.push(ArtifactRecord { sha256: digest.to_ascii_lowercase(), size_bytes, path, family: parts[3].to_owned(), format: parts[4].to_owned(), applicability: parts[5].to_owned(), }); } if records.is_empty() { return Err(VerifyError::Manifest(1)); } Ok(records) } fn signature_matches(format: &str, first: &[u8]) -> Result { let prefix: &[u8] = match format { "IMAGEWTY-SD" | "update-zip" | "zip-installer" => b"PK\x03\x04", "ubifs" => b"\x31\x18\x10\x06", "swu" => b"070702", "wm-package-0x9a5ba57c" => b"\x7c\xa5\x5b\x9a", "bmu" => b"\x26\x01", "bin-AES-container" => b"\x3f\x0a\x64\xae", _ => return Err(VerifyError::UnsupportedFormat), }; Ok(first.starts_with(prefix)) } pub fn verify_file(path: &Path, record: &ArtifactRecord) -> Result { let mut file = File::open(path)?; verify_open_file(&mut file, record)?; Ok(VerifiedArtifact { file, record: record.clone(), }) } fn verify_open_file(file: &mut File, record: &ArtifactRecord) -> Result<(), VerifyError> { if file.metadata()?.len() != record.size_bytes { return Err(VerifyError::Size); } file.seek(SeekFrom::Start(0))?; let mut first = [0_u8; 16]; let length = file.read(&mut first)?; if !signature_matches(&record.format, &first[..length])? { return Err(VerifyError::Signature); } file.seek(SeekFrom::Start(0))?; let mut hasher = Sha256::new(); let mut buffer = [0_u8; 64 * 1024]; let mut read_bytes = 0_u64; loop { let length = file.read(&mut buffer)?; if length == 0 { break; } read_bytes += length as u64; hasher.update(&buffer[..length]); } if read_bytes != record.size_bytes { return Err(VerifyError::Size); } let digest = hasher.finalize(); let actual: String = digest.iter().map(|byte| format!("{byte:02x}")).collect(); if actual != record.sha256 { return Err(VerifyError::Digest); } file.seek(SeekFrom::Start(0))?; Ok(()) } #[cfg(test)] mod tests { use super::*; use std::io::Write; #[test] fn manifest_has_unique_safe_records() { let records = seed_manifest().unwrap(); assert_eq!(records.len(), 14); let traversal = format!("{HEADER}\n{},12,../escape,bin,bmu,all\n", "0".repeat(64)); assert!(matches!( parse_manifest(&traversal), Err(VerifyError::Manifest(2)) )); } #[test] fn checks_size_signature_and_digest_before_consumption() { let path = std::env::temp_dir().join(format!("alkane-artifact-test-{}", std::process::id())); let bytes = b"PK\x03\x04example"; let mut file = File::create(&path).unwrap(); file.write_all(bytes).unwrap(); drop(file); let mut record = ArtifactRecord { sha256: Sha256::digest(bytes) .iter() .map(|byte| format!("{byte:02x}")) .collect(), size_bytes: bytes.len() as u64, path: PathBuf::from("fixture.zip"), family: "test".to_owned(), format: "update-zip".to_owned(), applicability: "test".to_owned(), }; let mut verified = verify_file(&path, &record).unwrap(); verified.revalidate().unwrap(); let mut replay = Vec::new(); verified.reader().read_to_end(&mut replay).unwrap(); assert_eq!(replay, bytes); std::fs::write(&path, b"PK\x03\x04changed").unwrap(); assert!(matches!(verified.revalidate(), Err(VerifyError::Digest))); std::fs::write(&path, bytes).unwrap(); verified.revalidate().unwrap(); record.size_bytes += 1; assert!(matches!( verify_file(&path, &record), Err(VerifyError::Size) )); record.size_bytes -= 1; record.format = "ubifs".to_owned(); assert!(matches!( verify_file(&path, &record), Err(VerifyError::Signature) )); record.format = "update-zip".to_owned(); record.sha256 = "0".repeat(64); assert!(matches!( verify_file(&path, &record), Err(VerifyError::Digest) )); std::fs::remove_file(path).unwrap(); } #[test] #[ignore = "microbenchmark"] fn bench_verify_artifact() { let path = std::env::temp_dir().join(format!("alkane-artifact-bench-{}", std::process::id())); let mut bytes = vec![0x42_u8; 65_536]; bytes[..4].copy_from_slice(b"PK\x03\x04"); std::fs::write(&path, &bytes).unwrap(); let record = ArtifactRecord { sha256: Sha256::digest(&bytes) .iter() .map(|byte| format!("{byte:02x}")) .collect(), size_bytes: bytes.len() as u64, path: PathBuf::from("bench.zip"), family: "test".to_owned(), format: "update-zip".to_owned(), applicability: "test".to_owned(), }; let started = std::time::Instant::now(); for _ in 0..100 { std::hint::black_box(verify_file(&path, &record).unwrap()); } println!("bench_verify_artifact: {:?}", started.elapsed() / 100); std::fs::remove_file(path).unwrap(); } }