diff --git a/AGENTS.md b/AGENTS.md index 74297c9..12d71e3 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -66,6 +66,15 @@ applied after analysis and before `pdg`; they are user-authored r2 commands Report script failures with the script path and line, and do not treat r2ghidra's install hint as pseudocode. +## ESP-IDF partition inspection + +`fat_analyze::esp_partition` discovers and validates plaintext ESP-IDF partition +tables; `fat_core::esp_partition` owns the shared evidence. `identify` and +`inspect headers` use the same scan and terminal renderer. Table and entry file +offsets are separate from partition flash addresses: never infer the dump's flash +base from the default table location or manufacture payload regions from it. +Legacy tables may lack MD5; a valid MD5 is table integrity, not authenticity. + ## BMC inspection `fat_analyze::fit` interprets FIT metadata using the shared validated FDT reader in `firmware_formats`; `fat_core::fit` owns its serializable evidence. Image signatures, configuration signatures, and control-FDT key requirements remain distinct. A completely interpreted blob is required before emitting absence-based findings; signature metadata is not cryptographic verification or enforcement. diff --git a/CHANGELOG.md b/CHANGELOG.md index 2e1404a..5beed4f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,12 @@ ## [Unreleased] +### Added + +- Native ESP-IDF partition-table discovery in `identify`, `inspect headers`, and + `inspect layout`, including custom table locations, optional MD5 validation, + legacy tables, and separate file offsets and flash addresses. + ## [2.1.0] See the [release notes](release-notes/v2.1.0.md) for installation and upgrade instructions. diff --git a/crates/fat_analyze/src/bootloader.rs b/crates/fat_analyze/src/bootloader.rs index eee32db..f500828 100644 --- a/crates/fat_analyze/src/bootloader.rs +++ b/crates/fat_analyze/src/bootloader.rs @@ -73,6 +73,7 @@ pub fn analyze_firmware_bytes(bytes: &[u8]) -> std::io::Result BootloaderSnapshot { + snapshot + .esp_partitions + .tables + .sort_by_key(|table| table.file_offset); + snapshot.esp_partitions.tables.dedup(); + snapshot + .esp_partitions + .diagnostics + .sort_by_key(|diagnostic| diagnostic.file_offset); + snapshot.esp_partitions.diagnostics.dedup(); snapshot.fit.blobs.sort_by_key(|blob| blob.offset); snapshot.fit.blobs.dedup(); snapshot.fit.control_keys.sort_by_key(|key| key.offset); diff --git a/crates/fat_analyze/src/esp_partition.rs b/crates/fat_analyze/src/esp_partition.rs new file mode 100644 index 0000000..a6348ac --- /dev/null +++ b/crates/fat_analyze/src/esp_partition.rs @@ -0,0 +1,227 @@ +//! Native ESP-IDF table discovery, independent of chip architecture and flash base. +//! +//! Format reference: Espressif ESP-IDF components/partition_table/gen_esp32part.py +//! https://docs.espressif.com/projects/esp-idf/en/stable/esp32/api-guides/partition-tables.html +use std::collections::BTreeSet; + +use fat_core::esp_partition::{ + EspPartition, EspPartitionChecksum, EspPartitionDiagnostic, EspPartitionScan, EspPartitionTable, +}; +use md5::{Digest, Md5}; +use memchr::memmem; + +const ENTRY_SIZE: usize = 32; +const MAX_TABLE_SIZE: usize = 0xc00; +const MAGIC: &[u8] = &[0xaa, 0x50]; + +pub fn scan(bytes: &[u8]) -> EspPartitionScan { + let mut report = EspPartitionScan::default(); + let mut accepted_end = 0; + let mut rejected_ends = [0; ENTRY_SIZE]; + for start in memmem::find_iter(bytes, MAGIC) { + if start < accepted_end { + continue; + } + let phase = start % ENTRY_SIZE; + let (end, framed, result) = parse_at(bytes, start); + match result { + // A valid MD5 independently establishes the beginning of a table, + // even when an earlier incidental signature covered this position. + Ok(table) if table.checksum.is_some() || start >= rejected_ends[phase] => { + accepted_end = end; + report.tables.push(table); + } + Ok(_) => {} // Do not promote a legacy suffix of a rejected table. + Err(reason) => { + if start >= rejected_ends[phase] { + report.diagnostics.push(EspPartitionDiagnostic { + file_offset: start as u64, + reason, + }); + } + if framed { + rejected_ends[phase] = rejected_ends[phase].max(end); + } + } + } + } + report +} + +fn parse_at(bytes: &[u8], start: usize) -> (usize, bool, Result) { + let mut partitions = Vec::new(); + let mut checksum = None; + let mut error = None; + let mut cursor = start; + for _ in 0..MAX_TABLE_SIZE / ENTRY_SIZE { + let Some(record) = bytes.get(cursor..).and_then(|tail| tail.get(..ENTRY_SIZE)) else { + return ( + bytes.len(), + !partitions.is_empty(), + Err("truncated table or missing end marker".into()), + ); + }; + let record_offset = cursor; + cursor += ENTRY_SIZE; + if record == [0xff; ENTRY_SIZE] { + let framed = !partitions.is_empty(); + let result = if let Some(error) = error { + Err(error) + } else { + validate_partitions(&partitions).map(|()| EspPartitionTable { + file_offset: start as u64, + size: (cursor - start) as u64, + checksum, + partitions, + }) + }; + return (cursor, framed, result); + } + if record[..2] == [0xeb, 0xeb] { + if checksum.is_some() || partitions.is_empty() || record[2..16] != [0xff; 14] { + error + .get_or_insert_with(|| "invalid MD5 record placement or reserved bytes".into()); + } + let digest = Md5::digest(&bytes[start..record_offset]); + if record[16..] != digest[..] { + error.get_or_insert_with(|| "MD5 checksum mismatch".into()); + } + checksum = Some(EspPartitionChecksum { + stored_hex: hex(&record[16..]), + computed_hex: hex(&digest), + }); + } else if &record[..2] == MAGIC { + if checksum.is_some() { + error.get_or_insert_with(|| "partition entry follows MD5 record".into()); + } + match parse_entry(record, record_offset) { + Ok(partition) => partitions.push(partition), + Err(reason) => { + error.get_or_insert(reason); + } + } + } else { + let reason = format!("invalid record magic at file offset 0x{record_offset:x}"); + if partitions.is_empty() { + return (cursor, false, Err(reason)); + } + // Once entries establish framing, retain the rejected continuation + // through its terminator. A damaged middle record must not turn the + // following legacy entries into a new, apparently valid table. + error.get_or_insert(reason); + } + } + ( + cursor, + !partitions.is_empty(), + Err("table exceeds 0xc00 bytes or is missing its end marker".into()), + ) +} + +fn parse_entry(bytes: &[u8], file_offset: usize) -> Result { + let label_bytes = bytes[12..28] + .split(|byte| *byte == 0) + .next() + .unwrap_or_default(); + let label = std::str::from_utf8(label_bytes).map_err(|_| "invalid UTF-8 partition label")?; + if label.is_empty() || label.chars().any(char::is_control) { + return Err("empty partition label or control character in label".into()); + } + let partition_type = bytes[2]; + if partition_type == 0xff { + return Err("partition type 0xff is reserved for erased entries".into()); + } + let subtype = bytes[3]; + let flash_offset = u64::from(read_u32(bytes, 4)); + let size = u64::from(read_u32(bytes, 8)); + let alignment = if partition_type == 0 { 0x10000 } else { 0x1000 }; + if !flash_offset.is_multiple_of(alignment) { + return Err(format!("partition {label:?} has an unaligned flash offset")); + } + if size == 0 || flash_offset + size > 1_u64 << 32 { + return Err(format!( + "partition {label:?} has an invalid size or exceeds 32-bit flash addressing" + )); + } + if partition_type == 0 && !size.is_multiple_of(0x1000) { + return Err(format!( + "app partition {label:?} size is not aligned to 0x1000" + )); + } + Ok(EspPartition { + entry_file_offset: file_offset as u64, + label: label.to_string(), + partition_type, + subtype, + type_name: match partition_type { + 0 => Some("app".into()), + 1 => Some("data".into()), + 2 => Some("bootloader".into()), + 3 => Some("partition_table".into()), + _ => None, + }, + subtype_name: subtype_name(partition_type, subtype), + flash_offset, + size, + flags: read_u32(bytes, 28), + }) +} + +fn validate_partitions(partitions: &[EspPartition]) -> Result<(), String> { + if partitions.is_empty() { + return Err("table contains no partitions".into()); + } + let mut labels = BTreeSet::new(); + for partition in partitions { + if !labels.insert(&partition.label) { + return Err(format!("duplicate partition label {:?}", partition.label)); + } + } + let mut ordered = partitions.iter().collect::>(); + ordered.sort_by_key(|partition| partition.flash_offset); + for pair in ordered.windows(2) { + if pair[0].flash_offset + pair[0].size > pair[1].flash_offset { + return Err(format!( + "overlapping partitions {:?} and {:?}", + pair[0].label, pair[1].label + )); + } + } + Ok(()) +} + +fn subtype_name(kind: u8, subtype: u8) -> Option { + let name = match (kind, subtype) { + (0, 0) => "factory", + (0, 0x10..=0x1f) => return Some(format!("ota_{}", subtype - 0x10)), + (0, 0x20) => "test", + (1, 0) => "ota", + (1, 1) => "phy", + (1, 2) => "nvs", + (1, 3) => "coredump", + (1, 4) => "nvs_keys", + (1, 5) => "efuse", + (1, 6) => "undefined", + (1, 0x80) => "esphttpd", + (1, 0x81) => "fat", + (1, 0x82) => "spiffs", + (1, 0x83) => "littlefs", + (2 | 3, 0) => "primary", + (2 | 3, 1) => "ota", + (2, 2) => "recovery", + _ => return None, + }; + Some(name.into()) +} + +fn read_u32(bytes: &[u8], offset: usize) -> u32 { + u32::from_le_bytes( + bytes[offset..offset + 4] + .try_into() + .expect("bounded entry field"), + ) +} + +fn hex(bytes: &[u8]) -> String { + bytes.iter().map(|byte| format!("{byte:02x}")).collect() +} diff --git a/crates/fat_analyze/src/lib.rs b/crates/fat_analyze/src/lib.rs index 3e9a804..f699dbd 100644 --- a/crates/fat_analyze/src/lib.rs +++ b/crates/fat_analyze/src/lib.rs @@ -8,6 +8,7 @@ pub mod cert_diff; pub mod credential; pub mod edge_ai; pub mod engine; +pub mod esp_partition; pub mod firmware_formats; pub mod fit; pub mod image_measurements; diff --git a/crates/fat_analyze/tests/esp_partition_tables.rs b/crates/fat_analyze/tests/esp_partition_tables.rs new file mode 100644 index 0000000..7a71569 --- /dev/null +++ b/crates/fat_analyze/tests/esp_partition_tables.rs @@ -0,0 +1,263 @@ +use fat_analyze::bootloader::{analyze_firmware_bytes, analyze_layout_bytes, merge_snapshots}; +use md5::{Digest, Md5}; +use serde_json::Value; + +fn entry(label: &str, kind: u8, subtype: u8, offset: u32, size: u32, flags: u32) -> Vec { + let mut bytes = vec![0; 32]; + bytes[..2].copy_from_slice(&[0xaa, 0x50]); + bytes[2] = kind; + bytes[3] = subtype; + bytes[4..8].copy_from_slice(&offset.to_le_bytes()); + bytes[8..12].copy_from_slice(&size.to_le_bytes()); + bytes[12..12 + label.len()].copy_from_slice(label.as_bytes()); + bytes[28..32].copy_from_slice(&flags.to_le_bytes()); + bytes +} + +fn table(checksum: bool) -> Vec { + let mut bytes = entry("settings", 1, 2, 0x9000, 0x6000, 0); + bytes.extend(entry("radio", 1, 1, 0xf000, 0x1000, 0)); + bytes.extend(entry("slot_a", 0, 0x10, 0x10000, 0x100000, 0)); + finish(bytes, checksum) +} + +fn finish(mut bytes: Vec, checksum: bool) -> Vec { + if checksum { + let digest = Md5::digest(&bytes); + bytes.extend([0xeb, 0xeb]); + bytes.extend([0xff; 14]); + bytes.extend(digest); + } + bytes.extend([0xff; 32]); + bytes +} + +fn scan(bytes: &[u8]) -> Value { + let snapshot = analyze_firmware_bytes(bytes).unwrap(); + let json = serde_json::to_value(snapshot).unwrap(); + assert!( + json["esp_partitions"].is_object(), + "ESP-IDF scan missing: {json}" + ); + json["esp_partitions"].clone() +} + +#[test] +fn discovers_relocated_table_without_assuming_flash_base() { + let mut bytes = vec![0x77; 0x5123]; + bytes.extend(table(true)); + let report = scan(&bytes); + assert_eq!(report["tables"].as_array().unwrap().len(), 1); + let table = &report["tables"][0]; + assert_eq!(table["file_offset"], 0x5123); + assert_eq!(table["size"], 160); + assert_eq!( + table["checksum"]["stored_hex"], + table["checksum"]["computed_hex"] + ); + assert_eq!(table["partitions"][0]["label"], "settings"); + assert_eq!(table["partitions"][0]["entry_file_offset"], 0x5123); + assert_eq!(table["partitions"][0]["flash_offset"], 0x9000); + assert_eq!(table["partitions"][0]["size"], 0x6000); + assert!(table["partitions"][0].get("file_offset").is_none()); + assert_eq!(table["partitions"][2]["subtype_name"], "ota_0"); +} + +#[test] +fn standalone_legacy_table_preserves_custom_codes_flags_and_full_label() { + let bytes = finish( + entry("abcdefghijklmnop", 0x40, 0xa5, 0x2000, 0x1000, 0x80000003), + false, + ); + let report = scan(&bytes); + let table = &report["tables"][0]; + assert_eq!(table["file_offset"], 0); + assert!(table["checksum"].is_null()); + let partition = &table["partitions"][0]; + assert_eq!(partition["label"], "abcdefghijklmnop"); + assert_eq!(partition["partition_type"], 0x40); + assert_eq!(partition["subtype"], 0xa5); + assert_eq!(partition["flags"], 0x80000003_u32); + assert!(partition["type_name"].is_null()); + assert!(partition["subtype_name"].is_null()); +} + +#[test] +fn rejects_corrupt_checksum_without_accepting_a_table_suffix() { + let mut bytes = table(true); + bytes[112] ^= 1; + let report = scan(&bytes); + assert!(report["tables"].as_array().unwrap().is_empty()); + assert!(report["diagnostics"][0]["reason"] + .as_str() + .unwrap() + .contains("MD5")); +} + +#[test] +fn rejects_invalid_entries_without_accepting_valid_suffixes() { + for range in [8..12, 40..44] { + let mut bytes = table(false); + bytes[range].fill(0); + let report = scan(&bytes); + assert!(report["tables"].as_array().unwrap().is_empty(), "{report}"); + } +} + +#[test] +fn rejects_truncated_records_and_missing_terminator() { + let bytes = table(true); + for length in [1, 12, 31, 32, 63, 96, 120, 128, 159] { + assert!(scan(&bytes[..length])["tables"] + .as_array() + .unwrap() + .is_empty()); + } +} + +#[test] +fn rejects_overlaps_duplicate_names_and_invalid_alignment() { + for second in [ + entry("overlap", 1, 2, 0xa000, 0x6000, 0), + entry("settings", 1, 2, 0x20000, 0x6000, 0), + entry("unaligned", 1, 2, 0x20001, 0x6000, 0), + entry("app", 0, 0, 0x21000, 0x10000, 0), + entry("overflow", 1, 0x80, 0xfffff000, 0x2000, 0), + ] { + let mut bytes = entry("settings", 1, 2, 0x9000, 0x6000, 0); + bytes.extend(second); + assert!(scan(&finish(bytes, false))["tables"] + .as_array() + .unwrap() + .is_empty()); + } +} + +#[test] +fn rejects_invalid_utf8_and_empty_labels() { + for label in [[0xff; 16], [0; 16]] { + let mut bytes = table(false); + bytes[12..28].copy_from_slice(&label); + assert!(scan(&bytes)["tables"].as_array().unwrap().is_empty()); + } +} + +#[test] +fn retains_multiple_distinct_tables_and_deduplicates_merged_scans() { + let mut bytes = table(true); + bytes.resize(0x4000, 0xff); + bytes.extend(table(false)); + let report = scan(&bytes); + assert_eq!(report["tables"].as_array().unwrap().len(), 2); + assert_eq!(report["tables"][1]["file_offset"], 0x4000); + let snapshot = analyze_firmware_bytes(&bytes).unwrap(); + let merged = serde_json::to_value(merge_snapshots(snapshot.clone(), snapshot)).unwrap(); + assert_eq!( + merged["esp_partitions"]["tables"].as_array().unwrap().len(), + 2 + ); +} + +#[test] +fn accepts_bootloader_and_partition_table_entries_at_low_flash_addresses() { + let mut bytes = entry("boot", 2, 0, 0, 0x8000, 0); + bytes.extend(entry("table", 3, 0, 0x8000, 0x1000, 0)); + let report = scan(&finish(bytes, true)); + assert_eq!( + report["tables"][0]["partitions"][0]["type_name"], + "bootloader" + ); + assert_eq!( + report["tables"][0]["partitions"][1]["type_name"], + "partition_table" + ); +} + +#[test] +fn enforces_maximum_table_length() { + let mut entries = Vec::new(); + for n in 0..95 { + entries.extend(entry(&format!("p{n}"), 0x40, 0, n * 0x1000, 0x1000, 0)); + } + assert_eq!( + scan(&finish(entries.clone(), false))["tables"][0]["partitions"] + .as_array() + .unwrap() + .len(), + 95 + ); + entries.extend(entry("too_many", 0x40, 0, 0x100000, 0x1000, 0)); + assert!(scan(&finish(entries, false))["tables"] + .as_array() + .unwrap() + .is_empty()); +} + +#[test] +fn unrelated_data_and_magic_alone_are_not_tables() { + for bytes in [vec![0xff; 4096], vec![0; 4096], vec![0xaa, 0x50, 0, 0]] { + assert!(scan(&bytes)["tables"].as_array().unwrap().is_empty()); + } +} + +#[test] +fn layout_maps_only_table_bytes_not_unresolved_flash_payloads() { + let mut bytes = vec![0x77; 0x123]; + bytes.extend(table(true)); + let layout = analyze_layout_bytes(&bytes).unwrap(); + let region = layout + .regions + .iter() + .find(|region| region.format == "esp-idf-partition-table") + .expect("partition table region"); + assert_eq!(region.kind.as_str(), "partition-table"); + assert_eq!(region.offset, 0x123); + assert_eq!(region.size, Some(160)); + assert!(region.span_is_exact); + assert!(!layout.regions.iter().any(|region| region.offset == 0x9000)); +} + +#[test] +fn older_snapshots_remain_readable() { + let snapshot = analyze_firmware_bytes(&[]).unwrap(); + let mut json = serde_json::to_value(snapshot).unwrap(); + json.as_object_mut().unwrap().remove("esp_partitions"); + let restored: fat_core::bootloader::BootloaderSnapshot = serde_json::from_value(json).unwrap(); + assert!(restored.esp_partitions.tables.is_empty()); +} + +#[test] +fn corrupt_middle_magic_does_not_promote_a_legacy_suffix() { + let mut bytes = table(false); + bytes[32] = 0; + let report = scan(&bytes); + assert!(report["tables"].as_array().unwrap().is_empty(), "{report}"); +} + +#[test] +fn incidental_magic_does_not_hide_an_independently_valid_table() { + for prefix in [ + vec![0xaa, 0x50, b'a', b'b', b'c'], + [vec![0xaa, 0x50], vec![b'x'; 30]].concat(), + ] { + let mut bytes = prefix.clone(); + bytes.extend(table(true)); + let report = scan(&bytes); + assert_eq!(report["tables"].as_array().unwrap().len(), 1, "{report}"); + assert_eq!(report["tables"][0]["file_offset"], prefix.len()); + } +} + +#[test] +fn rejected_framing_does_not_hide_a_legacy_table_on_another_alignment() { + let mut bytes = entry("damaged", 1, 2, 0x9000, 0x6000, 0); + bytes.extend([0x77; 5]); + bytes.extend(finish( + entry("independent", 1, 2, 0x20000, 0x6000, 0), + false, + )); + bytes.resize(256, 0xff); + let report = scan(&bytes); + assert_eq!(report["tables"].as_array().unwrap().len(), 1, "{report}"); + assert_eq!(report["tables"][0]["file_offset"], 37); +} diff --git a/crates/fat_cli/src/esp_partition_report.rs b/crates/fat_cli/src/esp_partition_report.rs new file mode 100644 index 0000000..801e275 --- /dev/null +++ b/crates/fat_cli/src/esp_partition_report.rs @@ -0,0 +1,43 @@ +use fat_core::esp_partition::EspPartitionTable; + +use crate::report::Report; + +pub fn append_tables(view: &mut Report, tables: &[EspPartitionTable]) { + for table in tables { + view.section("ESP-IDF partitions"); + view.kv("Table file offset", format!("0x{:08x}", table.file_offset)); + view.kv( + "MD5", + if table.checksum.is_some() { + "valid" + } else { + "not present" + }, + ); + let rows = table + .partitions + .iter() + .map(|partition| { + vec![ + partition.label.clone(), + partition + .type_name + .clone() + .unwrap_or_else(|| format!("0x{:02x}", partition.partition_type)), + partition + .subtype_name + .clone() + .unwrap_or_else(|| format!("0x{:02x}", partition.subtype)), + format!("0x{:08x}", partition.flash_offset), + format!("0x{:08x}", partition.size), + format!("0x{:08x}", partition.flags), + ] + }) + .collect::>(); + view.table( + &["Name", "Type", "Subtype", "Flash offset", "Size", "Flags"], + &rows, + ); + view.text("Flash offsets are device addresses; mapping them into this file requires its flash base."); + } +} diff --git a/crates/fat_cli/src/helptext.rs b/crates/fat_cli/src/helptext.rs index a3b07f2..193f74e 100644 --- a/crates/fat_cli/src/helptext.rs +++ b/crates/fat_cli/src/helptext.rs @@ -2634,7 +2634,9 @@ const INSPECT_HEADERS_AFTER: &str = r#"Syntax: fat inspect headers [] [--file ] [--json] What it does: - Inspects known firmware container headers from a project or standalone file. + Inspects known firmware container headers and ESP-IDF partition tables from a + project or standalone file. ESP-IDF tables are discovered without assuming a + fixed location; partition flash addresses are distinct from input-file offsets. When the input is an ELF binary or shared object, it falls back to ELF header metadata instead of firmware-container parsing. "#; diff --git a/crates/fat_cli/src/identify_cmd.rs b/crates/fat_cli/src/identify_cmd.rs index 267f6d0..ffd4e2e 100644 --- a/crates/fat_cli/src/identify_cmd.rs +++ b/crates/fat_cli/src/identify_cmd.rs @@ -47,6 +47,7 @@ pub struct StructureSummary { pub image_headers: Vec, pub compression_members: Vec, pub filesystem_headers: Vec, + pub esp_partitions: fat_core::esp_partition::EspPartitionScan, #[serde(skip_serializing_if = "Option::is_none")] pub partitioning: Option, #[serde(default, skip_serializing_if = "Vec::is_empty")] @@ -292,11 +293,12 @@ fn collect_raw_blob_report(path: &Path, path_kind: String) -> DynResult DynResult DynResult { compression_members: snapshot.compression_members, filesystem_headers: snapshot.filesystem_headers, fit: snapshot.fit, + esp_partitions: snapshot.esp_partitions, }); } @@ -541,6 +553,7 @@ fn load_project_report(project_dir: &Path) -> DynResult { compression_members: Vec::new(), filesystem_headers: Vec::new(), fit: Default::default(), + esp_partitions: Default::default(), }) } @@ -559,6 +572,7 @@ fn load_file_report(firmware_path: &Path) -> DynResult { compression_members: snapshot.compression_members, filesystem_headers: snapshot.filesystem_headers, fit: snapshot.fit, + esp_partitions: snapshot.esp_partitions, }) } diff --git a/crates/fat_cli/src/main.rs b/crates/fat_cli/src/main.rs index e4db60c..4053715 100644 --- a/crates/fat_cli/src/main.rs +++ b/crates/fat_cli/src/main.rs @@ -64,6 +64,7 @@ mod emulate_config; mod emulate_gc; mod emulate_list; mod envelope_cmd; +mod esp_partition_report; mod experiment_cmd; mod extract_payload_cmd; mod fat_graph_cmd; diff --git a/crates/fat_cli/tests/esp_partition_cli.rs b/crates/fat_cli/tests/esp_partition_cli.rs new file mode 100644 index 0000000..e886219 --- /dev/null +++ b/crates/fat_cli/tests/esp_partition_cli.rs @@ -0,0 +1,129 @@ +use serde_json::Value; +use std::process::Command; +use tempfile::tempdir; + +fn fixture() -> Vec { + let mut bytes = vec![0x77; 0x123]; + let mut entry = [0; 32]; + entry[..4].copy_from_slice(&[0xaa, 0x50, 1, 2]); + entry[4..8].copy_from_slice(&0x9000_u32.to_le_bytes()); + entry[8..12].copy_from_slice(&0x6000_u32.to_le_bytes()); + entry[12..15].copy_from_slice(b"nvs"); + entry[28..32].copy_from_slice(&0x80000003_u32.to_le_bytes()); + bytes.extend(entry); + bytes.extend([0xff; 32]); + bytes +} + +#[test] +fn identify_and_headers_share_native_partition_evidence() { + let dir = tempdir().unwrap(); + let path = dir.path().join("firmware.bin"); + std::fs::write(&path, fixture()).unwrap(); + let mut reports = Vec::new(); + for command in [vec!["identify"], vec!["inspect", "headers"]] { + let output = Command::new(env!("CARGO_BIN_EXE_fat")) + .args(&command) + .arg("--file") + .arg(&path) + .arg("--json") + .output() + .unwrap(); + assert!(output.status.success(), "{output:?}"); + let json: Value = serde_json::from_slice(&output.stdout).unwrap(); + let scan = if command[0] == "identify" { + assert_eq!(json["likely_class"], "esp-idf-partitioned-image"); + &json["structure"]["esp_partitions"] + } else { + &json["esp_partitions"] + }; + assert_eq!(scan["tables"][0]["file_offset"], 0x123); + assert_eq!(scan["tables"][0]["partitions"][0]["flash_offset"], 0x9000); + reports.push(scan.clone()); + for columns in ["48", "120"] { + let output = Command::new(env!("CARGO_BIN_EXE_fat")) + .args(&command) + .arg("--file") + .arg(&path) + .env("NO_COLOR", "1") + .env("COLUMNS", columns) + .output() + .unwrap(); + assert!(output.status.success(), "{output:?}"); + let text = String::from_utf8_lossy(&output.stdout); + for value in [ + "ESP-IDF", + "0x00000123", + "0x00009000", + "0x00006000", + "nvs", + "0x80000003", + ] { + assert!(text.contains(value), "missing {value} in {text}"); + } + } + } + assert_eq!(reports[0], reports[1]); +} + +#[test] +fn rejected_table_is_diagnostic_not_identification() { + let dir = tempdir().unwrap(); + let path = dir.path().join("bad-table.bin"); + let mut bytes = fixture(); + bytes[0x123 + 8..0x123 + 12].fill(0); + std::fs::write(&path, bytes).unwrap(); + let output = Command::new(env!("CARGO_BIN_EXE_fat")) + .args(["inspect", "headers", "--file"]) + .arg(&path) + .arg("--json") + .output() + .unwrap(); + assert!(output.status.success(), "{output:?}"); + let report: Value = serde_json::from_slice(&output.stdout).unwrap(); + assert_eq!(report["esp_partitions"]["tables"], serde_json::json!([])); + assert!(!report["esp_partitions"]["diagnostics"] + .as_array() + .unwrap() + .is_empty()); +} + +#[test] +fn embedded_table_does_not_override_an_outer_uimage() { + let dir = tempdir().unwrap(); + let path = dir.path().join("linux-uimage.bin"); + let payload = fixture(); + let mut header = vec![0; 64]; + header[..4].copy_from_slice(&0x27051956_u32.to_be_bytes()); + header[12..16].copy_from_slice(&(payload.len() as u32).to_be_bytes()); + header[24..28].copy_from_slice(&crc32(&payload).to_be_bytes()); + header[28..32].copy_from_slice(&[5, 5, 2, 0]); // Linux, MIPS, kernel, uncompressed + let crc = crc32(&header); + header[4..8].copy_from_slice(&crc.to_be_bytes()); + header.extend(payload); + std::fs::write(&path, header).unwrap(); + let output = Command::new(env!("CARGO_BIN_EXE_fat")) + .args(["identify", "--file"]) + .arg(&path) + .arg("--json") + .output() + .unwrap(); + assert!(output.status.success(), "{output:?}"); + let report: Value = serde_json::from_slice(&output.stdout).unwrap(); + assert_eq!(report["likely_class"], "structured-firmware-container"); + assert_eq!( + report["structure"]["esp_partitions"]["tables"][0]["file_offset"], + 0x123 + 64 + ); +} + +fn crc32(bytes: &[u8]) -> u32 { + let mut crc = !0_u32; + for byte in bytes { + crc ^= u32::from(*byte); + for _ in 0..8 { + crc = (crc >> 1) ^ (0xedb88320_u32 & 0_u32.wrapping_sub(crc & 1)); + } + } + !crc +} diff --git a/crates/fat_core/src/bootloader.rs b/crates/fat_core/src/bootloader.rs index be68b6c..d86d7c6 100644 --- a/crates/fat_core/src/bootloader.rs +++ b/crates/fat_core/src/bootloader.rs @@ -29,6 +29,8 @@ pub struct BootloaderSnapshot { pub embedded_signatures: Vec, #[serde(default)] pub fit: crate::fit::FitScanReport, + #[serde(default)] + pub esp_partitions: crate::esp_partition::EspPartitionScan, pub findings: Vec, } diff --git a/crates/fat_core/src/esp_partition.rs b/crates/fat_core/src/esp_partition.rs new file mode 100644 index 0000000..03b38a0 --- /dev/null +++ b/crates/fat_core/src/esp_partition.rs @@ -0,0 +1,42 @@ +//! ESP-IDF partition metadata. Flash addresses do not imply input-file mappings. +use serde::{Deserialize, Serialize}; + +#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)] +pub struct EspPartitionScan { + pub tables: Vec, + pub diagnostics: Vec, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct EspPartitionTable { + pub file_offset: u64, + /// Bytes through the end marker, not an assumed 4 KiB flash-sector extent. + pub size: u64, + pub checksum: Option, + pub partitions: Vec, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct EspPartitionChecksum { + pub stored_hex: String, + pub computed_hex: String, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct EspPartition { + pub entry_file_offset: u64, + pub label: String, + pub partition_type: u8, + pub subtype: u8, + pub type_name: Option, + pub subtype_name: Option, + pub flash_offset: u64, + pub size: u64, + pub flags: u32, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct EspPartitionDiagnostic { + pub file_offset: u64, + pub reason: String, +} diff --git a/crates/fat_core/src/inspection.rs b/crates/fat_core/src/inspection.rs index 6d36872..0490394 100644 --- a/crates/fat_core/src/inspection.rs +++ b/crates/fat_core/src/inspection.rs @@ -14,6 +14,8 @@ pub struct InspectionReport { pub filesystem_headers: Vec, #[serde(default)] pub fit: crate::fit::FitScanReport, + #[serde(default)] + pub esp_partitions: crate::esp_partition::EspPartitionScan, } #[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)] diff --git a/crates/fat_core/src/layout.rs b/crates/fat_core/src/layout.rs index 550b0ea..421c7b9 100644 --- a/crates/fat_core/src/layout.rs +++ b/crates/fat_core/src/layout.rs @@ -74,6 +74,8 @@ pub struct LayoutRegionPartition { #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] pub enum LayoutRegionKind { + #[serde(rename = "partition-table")] + PartitionTable, #[serde(rename = "container")] Container, #[serde(rename = "boot-image")] @@ -89,6 +91,7 @@ pub enum LayoutRegionKind { impl LayoutRegionKind { pub fn as_str(self) -> &'static str { match self { + LayoutRegionKind::PartitionTable => "partition-table", LayoutRegionKind::Container => "container", LayoutRegionKind::BootImage => "boot-image", LayoutRegionKind::Compression => "compression", diff --git a/crates/fat_core/src/lib.rs b/crates/fat_core/src/lib.rs index 14aea32..971aa7b 100644 --- a/crates/fat_core/src/lib.rs +++ b/crates/fat_core/src/lib.rs @@ -11,6 +11,7 @@ pub mod decompile; pub mod diagnostics; pub mod diff; pub mod discovery; +pub mod esp_partition; pub mod experiment; pub mod experiment_selector; pub mod external_campaign; diff --git a/docs/commands.md b/docs/commands.md index c62e0d5..c753618 100644 --- a/docs/commands.md +++ b/docs/commands.md @@ -33,6 +33,32 @@ For firmware with case-distinct names, create the project on a case-sensitive vo `fat inspect bmc --file flash.mtd --details` expands the text report. Use `--json` or `--sarif` for structured output and `--fail-on-warning` to emit the report before returning a failing status for warning/error findings. Both `--env-offset` and `--env-size` are required for an explicit environment region. See [BMC inspection](bmc-inspection.md) for search bounds and the distinction between signature metadata and boot enforcement. +### ESP-IDF partition tables + +`identify` and `inspect headers` discover plaintext ESP-IDF partition tables in +flash dumps, merged images, and standalone table binaries. No ESP-IDF installation +or Python script is needed: + +```bash +fat identify firmware.bin +fat inspect headers --file firmware.bin +fat inspect headers --file firmware.bin --json +fat inspect layout --file firmware.bin +``` + +The scan finds tables at arbitrary file offsets, validates entry framing, +alignment, ranges, unique labels, non-overlap and MD5 when present, and accepts +legacy tables without MD5. Reports retain numeric types, subtypes and all flag +bits, including unrecognized values. JSON includes rejected-candidate diagnostics. +`inspect layout` locates the table bytes themselves. + +**Partition offsets are flash addresses.** They are not automatically offsets in +the input file: a cropped dump or standalone table may have a different origin. +FAT does not infer the flash base, claim that referenced payloads are present, or +decode NVS values. Encrypted tables need decrypted input; application-only images +may contain no table. The format follows [Espressif's partition-table +documentation](https://docs.espressif.com/projects/esp-idf/en/stable/esp32/api-guides/partition-tables.html). + ## Filesystem evidence | Command | Purpose |