From 315f91d82e44dc4ba9a5dc6e59c634ccf5dffa37 Mon Sep 17 00:00:00 2001 From: Daniel Schaefer Date: Fri, 20 Nov 2026 09:31:31 +0800 Subject: [PATCH 01/31] input_deck: Don't panic on unknown EC values The EC sends 0xFF as board ID if it fails to read the ADC (BOARD_VERSION_UNKNOWN). Any value we don't know would panic, which in the UEFI app embedded in the BIOS stops the boot. Map unknown values to a new Unknown(u8) variant instead. An unknown module has size 0 and an unknown touchpad is treated as not present, so the deck is not considered fully populated. Co-Authored-By: Claude Opus 5.5 --- framework_lib/src/chromium_ec/input_deck.rs | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/framework_lib/src/chromium_ec/input_deck.rs b/framework_lib/src/chromium_ec/input_deck.rs index 68920688..8bd1bcf8 100644 --- a/framework_lib/src/chromium_ec/input_deck.rs +++ b/framework_lib/src/chromium_ec/input_deck.rs @@ -49,6 +49,9 @@ pub enum InputModuleType { Touchpad, Reserved15, Disconnected, + /// Value the EC reported that we don't know. + /// The EC reports 0xFF if it failed to read the board ID. + Unknown(u8), } impl From for InputModuleType { fn from(item: u8) -> Self { @@ -69,7 +72,7 @@ impl From for InputModuleType { 13 => Self::Touchpad, 14 => Self::Reserved15, 15 => Self::Disconnected, - _ => panic!("Invalid module type"), + x => Self::Unknown(x), } } } @@ -95,6 +98,7 @@ impl InputModuleType { Self::Touchpad => 0, Self::Reserved15 => 0, Self::Disconnected => 0, + Self::Unknown(_) => 0, } } } @@ -115,6 +119,8 @@ pub enum InputDeckState { ForceOn, /// Manual override: Input deck will follow power sequence, no present check NoDetection, + /// Value the EC reported that we don't know + Unknown(u8), } impl From for InputDeckState { fn from(item: u8) -> Self { @@ -126,7 +132,7 @@ impl From for InputDeckState { 4 => InputDeckState::ForceOff, 5 => InputDeckState::ForceOn, 6 => InputDeckState::NoDetection, - _ => panic!("Invalid value"), + x => InputDeckState::Unknown(x), } } } @@ -181,7 +187,7 @@ impl From for InputDeckStatus { let tp_id = InputModuleType::from(item.board_id[InputDeckMux::Touchpad as usize]); let tp_present = !matches!( tp_id, - InputModuleType::Short | InputModuleType::Disconnected + InputModuleType::Short | InputModuleType::Disconnected | InputModuleType::Unknown(_) ); InputDeckStatus { From 04f3da6158bd0429b6699db45607a04d35789af3 Mon Sep 17 00:00:00 2001 From: Daniel Schaefer Date: Fri, 20 Nov 2026 09:31:58 +0800 Subject: [PATCH 02/31] power: Don't panic when reading the EC memory map fails read_memory() returns None if the platform isn't detected as Framework or the driver fails, but many callers unwrapped it. power_info() and get_accel_data() are also used by the UEFI app embedded in the BIOS, where a panic stops the boot. - read_u32/read_string return Option, add read_u8, and power_info() returns None if any read fails - get_accel_data() reads the whole block at once and returns zeros and an unreliable lid angle if that fails - AccelData::from doesn't index past short data - print_sensors() doesn't index past the sensor locations the EC reported - get_fan_num() returns an error instead of panicking Co-Authored-By: Claude Opus 5.5 --- framework_lib/src/power.rs | 114 +++++++++++++++++++++---------------- 1 file changed, 65 insertions(+), 49 deletions(-) diff --git a/framework_lib/src/power.rs b/framework_lib/src/power.rs index cbb0382b..9c22c433 100644 --- a/framework_lib/src/power.rs +++ b/framework_lib/src/power.rs @@ -186,6 +186,10 @@ pub struct AccelData { } impl From> for AccelData { fn from(t: Vec) -> Self { + let Some(t) = t.get(..6) else { + error!("Accelerometer data too short: {} bytes", t.len()); + return Self { x: 0, y: 0, z: 0 }; + }; Self { x: i16::from_le_bytes([t[0], t[1]]), y: i16::from_le_bytes([t[2], t[3]]), @@ -225,13 +229,17 @@ impl fmt::Display for LidAngle { } } -fn read_string(ec: &CrosEc, address: u16) -> String { - let bytes = ec.read_memory(address, EC_MEMMAP_TEXT_MAX).unwrap(); - String::from_utf8_lossy(bytes.as_slice()).replace(['\0'], "") +fn read_string(ec: &CrosEc, address: u16) -> Option { + let bytes = ec.read_memory(address, EC_MEMMAP_TEXT_MAX)?; + Some(String::from_utf8_lossy(bytes.as_slice()).replace(['\0'], "")) +} + +fn read_u8(ec: &CrosEc, address: u16) -> Option { + ec.read_memory(address, 1)?.first().copied() } -fn read_u32(ec: &CrosEc, address: u16) -> u32 { - let bytes = ec.read_memory(address, 4).unwrap(); +fn read_u32(ec: &CrosEc, address: u16) -> Option { + let bytes = ec.read_memory(address, 4)?; if bytes.len() != 4 { debug_assert!( bytes.len() == 4, @@ -239,9 +247,9 @@ fn read_u32(ec: &CrosEc, address: u16) -> u32 { bytes.len() ); error!("Unexpected length returned: {:?} instead of 4", bytes.len()); - return 0; + return None; } - u32::from_ne_bytes(bytes[0..4].try_into().unwrap()) + Some(u32::from_ne_bytes(bytes[0..4].try_into().unwrap())) } pub fn print_memmap_version_info(ec: &CrosEc) { @@ -433,13 +441,20 @@ pub fn get_accel_data(ec: &CrosEc) -> (AccelData, AccelData, LidAngle) { // bit 4 = busy // bit 7 = present // #define EC_MEMMAP_ACC_STATUS_SAMPLE_ID_MASK 0x0f - let _acc_status = ec.read_memory(EC_MEMMAP_ACC_STATUS, 0x01).unwrap()[0]; // While busy, keep reading - let lid_angle = ec.read_memory(EC_MEMMAP_ACC_DATA, 0x02).unwrap(); - let lid_angle = u16::from_le_bytes([lid_angle[0], lid_angle[1]]); - let accel_1 = ec.read_memory(EC_MEMMAP_ACC_DATA + 2, 0x06).unwrap(); - let accel_2 = ec.read_memory(EC_MEMMAP_ACC_DATA + 8, 0x06).unwrap(); + // 0x92-0x93: Lid angle, 0x94-0x99: 1st accel, 0x9a-0x9f: 2nd accel + let Some(data) = ec + .read_memory(EC_MEMMAP_ACC_DATA, 14) + .filter(|d| d.len() == 14) + else { + error!("Failed to read accelerometer data"); + let zero = AccelData { x: 0, y: 0, z: 0 }; + return (zero.clone(), zero, LidAngle::Unreliable); + }; + let lid_angle = u16::from_le_bytes([data[0], data[1]]); + let accel_1 = data[2..8].to_vec(); + let accel_2 = data[8..14].to_vec(); // TODO: Make sure we got a new sample // println!(" Status Bit: {} 0x{:X}", acc_status, acc_status); @@ -494,13 +509,13 @@ pub fn print_sensors(ec: &CrosEc) { // bit 4 = busy // bit 7 = present // #define EC_MEMMAP_ACC_STATUS_SAMPLE_ID_MASK 0x0f - let acc_status = ec.read_memory(EC_MEMMAP_ACC_STATUS, 0x01).unwrap()[0]; + let Some(acc_status) = read_u8(ec, EC_MEMMAP_ACC_STATUS) else { + println!("Accelerometers: Failed to read"); + return; + }; // While busy, keep reading - let lid_angle = ec.read_memory(EC_MEMMAP_ACC_DATA, 0x02).unwrap(); - let lid_angle = u16::from_le_bytes([lid_angle[0], lid_angle[1]]); - let accel_1 = ec.read_memory(EC_MEMMAP_ACC_DATA + 2, 0x06).unwrap(); - let accel_2 = ec.read_memory(EC_MEMMAP_ACC_DATA + 8, 0x06).unwrap(); + let (accel_1, accel_2, lid_angle) = get_accel_data(ec); let present = (acc_status & 0x80) > 0; if present { @@ -509,21 +524,19 @@ pub fn print_sensors(ec: &CrosEc) { debug!(" Present: {}", present); debug!(" Busy: {}", (acc_status & 0x8) > 0); print!(" Lid Angle: "); - if lid_angle == LID_ANGLE_UNRELIABLE { - println!("Unreliable"); - } else { - println!("{} Deg", lid_angle); + match lid_angle { + LidAngle::Angle(deg) => println!("{} Deg", deg), + LidAngle::Unreliable => println!("Unreliable"), } - println!( - " {:<12} {}", - format!("{:?} Sensor:", accel_locations[0]), - AccelData::from(accel_1) - ); - println!( - " {:<12} {}", - format!("{:?} Sensor:", accel_locations[1]), - AccelData::from(accel_2) - ); + // The EC might not report the location of every sensor + let location = |i: usize| { + accel_locations + .get(i) + .map(|l| format!("{:?} Sensor:", l)) + .unwrap_or_else(|| format!("Sensor {}:", i + 1)) + }; + println!(" {:<12} {}", location(0), accel_1); + println!(" {:<12} {}", location(1), accel_2); } } @@ -696,7 +709,10 @@ pub fn print_thermal(ec: &CrosEc) { } pub fn get_fan_num(ec: &CrosEc) -> EcResult { - let fans = ec.read_memory(EC_MEMMAP_FAN, 0x08).unwrap(); + let fans = ec + .read_memory(EC_MEMMAP_FAN, 2 * EC_FAN_SPEED_ENTRIES as u16) + .filter(|f| f.len() == 2 * EC_FAN_SPEED_ENTRIES) + .ok_or_else(|| EcError::DeviceError("Failed to read fan speeds".to_string()))?; let mut count = 0; for i in 0..EC_FAN_SPEED_ENTRIES { @@ -711,24 +727,24 @@ pub fn get_fan_num(ec: &CrosEc) -> EcResult { // TODO: Use Result pub fn power_info(ec: &CrosEc) -> Option { - let battery_flag = ec.read_memory(EC_MEMMAP_BATT_FLAG, 1)?[0]; + let battery_flag = read_u8(ec, EC_MEMMAP_BATT_FLAG)?; debug!("AC/Battery flag: {:#X}", battery_flag); - let battery_lfcc = read_u32(ec, EC_MEMMAP_BATT_LFCC); - let battery_cap = read_u32(ec, EC_MEMMAP_BATT_CAP); - - let present_voltage = read_u32(ec, EC_MEMMAP_BATT_VOLT); - let present_rate = read_u32(ec, EC_MEMMAP_BATT_RATE); - let _remaining_capacity = read_u32(ec, EC_MEMMAP_BATT_CAP); // TODO: Why didn't I use this? - let battery_count = ec.read_memory(EC_MEMMAP_BATT_COUNT, 1).unwrap()[0]; // 8 bit - let current_battery_index = ec.read_memory(EC_MEMMAP_BATT_INDEX, 1).unwrap()[0]; // 8 bit - let design_capacity = read_u32(ec, EC_MEMMAP_BATT_DCAP); - let design_voltage = read_u32(ec, EC_MEMMAP_BATT_DVLT); - let cycle_count = read_u32(ec, EC_MEMMAP_BATT_CCNT); - - let manufacturer = read_string(ec, EC_MEMMAP_BATT_MFGR); - let model_number = read_string(ec, EC_MEMMAP_BATT_MODEL); - let serial_number = read_string(ec, EC_MEMMAP_BATT_SERIAL); - let battery_type = read_string(ec, EC_MEMMAP_BATT_TYPE); + let battery_lfcc = read_u32(ec, EC_MEMMAP_BATT_LFCC)?; + let battery_cap = read_u32(ec, EC_MEMMAP_BATT_CAP)?; + + let present_voltage = read_u32(ec, EC_MEMMAP_BATT_VOLT)?; + let present_rate = read_u32(ec, EC_MEMMAP_BATT_RATE)?; + let _remaining_capacity = read_u32(ec, EC_MEMMAP_BATT_CAP)?; // TODO: Why didn't I use this? + let battery_count = read_u8(ec, EC_MEMMAP_BATT_COUNT)?; + let current_battery_index = read_u8(ec, EC_MEMMAP_BATT_INDEX)?; + let design_capacity = read_u32(ec, EC_MEMMAP_BATT_DCAP)?; + let design_voltage = read_u32(ec, EC_MEMMAP_BATT_DVLT)?; + let cycle_count = read_u32(ec, EC_MEMMAP_BATT_CCNT)?; + + let manufacturer = read_string(ec, EC_MEMMAP_BATT_MFGR)?; + let model_number = read_string(ec, EC_MEMMAP_BATT_MODEL)?; + let serial_number = read_string(ec, EC_MEMMAP_BATT_SERIAL)?; + let battery_type = read_string(ec, EC_MEMMAP_BATT_TYPE)?; Some(PowerInfo { ac_present: 0 != (battery_flag & EC_BATT_FLAG_AC_PRESENT), From 20e2cab7b3e6f056b7c4db3dde2ed554ca6f130f Mon Sep 17 00:00:00 2001 From: Daniel Schaefer Date: Fri, 20 Nov 2026 10:16:44 +0800 Subject: [PATCH 03/31] Add fuzzing of EC memory map and host command responses With cfg(fuzzing), set by cargo-fuzz, CrosEc uses a mock driver that returns fuzzer-provided data for memory map reads and host commands, so the parsing code can be fuzzed without hardware. Two targets: - ec_memmap: battery, power, thermal, sensors, switches - ec_host_cmd: PD info, EC info and platform specific host commands The fuzz crate is its own workspace, so regular builds don't need nightly. Normal builds are unaffected, all changes are behind cfg(fuzzing). See fuzz/README.md Co-Authored-By: Claude Opus 5.5 --- framework_lib/Cargo.toml | 4 + framework_lib/src/chromium_ec/command.rs | 2 + framework_lib/src/chromium_ec/fuzz_driver.rs | 134 +++++++++++++++++++ framework_lib/src/chromium_ec/mod.rs | 10 ++ framework_lib/src/os_specific.rs | 7 + framework_lib/src/smbios.rs | 6 + fuzz/.gitignore | 4 + fuzz/Cargo.toml | 38 ++++++ fuzz/README.md | 33 +++++ fuzz/fuzz_targets/ec_host_cmd.rs | 54 ++++++++ fuzz/fuzz_targets/ec_memmap.rs | 23 ++++ 11 files changed, 315 insertions(+) create mode 100644 framework_lib/src/chromium_ec/fuzz_driver.rs create mode 100644 fuzz/.gitignore create mode 100644 fuzz/Cargo.toml create mode 100644 fuzz/README.md create mode 100644 fuzz/fuzz_targets/ec_host_cmd.rs create mode 100644 fuzz/fuzz_targets/ec_memmap.rs diff --git a/framework_lib/Cargo.toml b/framework_lib/Cargo.toml index ddd7ecba..5e1c70eb 100644 --- a/framework_lib/Cargo.toml +++ b/framework_lib/Cargo.toml @@ -93,3 +93,7 @@ features = [ "Win32_UI_Shell_PropertiesSystem" ] + +[lints.rust] +# Set by cargo-fuzz, see fuzz/ +unexpected_cfgs = { level = "warn", check-cfg = ['cfg(fuzzing)'] } diff --git a/framework_lib/src/chromium_ec/command.rs b/framework_lib/src/chromium_ec/command.rs index c75f5796..b1cf5c52 100644 --- a/framework_lib/src/chromium_ec/command.rs +++ b/framework_lib/src/chromium_ec/command.rs @@ -202,6 +202,8 @@ pub trait EcRequestRaw { where Self: Sized, { + #[cfg(fuzzing)] + super::fuzz_driver::set_expected_size(Some(std::mem::size_of::())); let response = self.send_command_vec_extra(ec, extra_data)?; if response.len() != core::mem::size_of::() { return Err(EcError::DeviceError(format!( diff --git a/framework_lib/src/chromium_ec/fuzz_driver.rs b/framework_lib/src/chromium_ec/fuzz_driver.rs new file mode 100644 index 00000000..37836558 --- /dev/null +++ b/framework_lib/src/chromium_ec/fuzz_driver.rs @@ -0,0 +1,134 @@ +//! Mock EC driver for fuzzing, only compiled with `--cfg fuzzing` (cargo-fuzz sets it) +//! +//! Instead of talking to hardware, EC responses come from a fuzzer-provided input: +//! +//! - The memory map is a static image, so repeated reads of the same offset agree, +//! like they would on real hardware. +//! - Host command responses are taken sequentially from a tape. Once the tape runs +//! out, every command fails, so retry/polling loops terminate. + +use std::cell::{Cell, RefCell}; + +use super::{EcError, EcResponseStatus, EcResult, EC_MEMMAP_SIZE}; +use num_traits::FromPrimitive; + +/// Maximum response payload of the LPC protocol v3 (256 byte packet - 8 byte header) +const MAX_RESPONSE: usize = 0x100 - 8; + +#[derive(Default)] +struct State { + memmap: Vec, + tape: Vec, + pos: usize, +} + +thread_local! { + static STATE: RefCell = RefCell::new(State::default()); + /// Size of the struct that the caller (`send_command_extra`) expects as response. + /// The driver can't otherwise know it and would almost always fail that size check. + static EXPECTED_SIZE: Cell> = const { Cell::new(None) }; +} + +/// Install fuzzer input. `memmap` is zero-padded to the full memmap size. +pub fn set_input(memmap: &[u8], tape: &[u8]) { + STATE.with(|s| { + let mut s = s.borrow_mut(); + s.memmap = memmap.to_vec(); + s.memmap.resize(EC_MEMMAP_SIZE as usize, 0); + s.tape = tape.to_vec(); + s.pos = 0; + }); + EXPECTED_SIZE.with(|e| e.set(None)); +} + +pub(crate) fn set_expected_size(size: Option) { + EXPECTED_SIZE.with(|e| e.set(size)); +} + +pub(crate) fn read_memory(offset: u16, length: u16) -> EcResult> { + STATE.with(|s| { + let s = s.borrow(); + let start = offset as usize; + let end = start + length as usize; + s.memmap + .get(start..end) + .map(|x| x.to_vec()) + .ok_or_else(|| EcError::DeviceError("memmap read out of range".to_string())) + }) +} + +pub(crate) fn send_command(_command: u16, _command_version: u8, _data: &[u8]) -> EcResult> { + let expected = EXPECTED_SIZE.with(|e| e.take()); + STATE.with(|s| { + let mut s = s.borrow_mut(); + let Some(&ctrl) = s.tape.get(s.pos) else { + return Err(EcError::DeviceError("fuzz tape exhausted".to_string())); + }; + s.pos += 1; + + // Control byte: + // 0x00..=0xBF success, response of expected size (or ctrl-defined length) + // 0xC0..=0xDF success, length from next byte (to hit size mismatch paths) + // 0xE0..=0xFF EC returned an error status + let len = match ctrl { + 0xE0..=0xFF => { + let code = (ctrl - 0xE0) as u32; + return Err(match ::from_u32(code) { + Some(status) => EcError::Response(status), + None => EcError::UnknownResponseCode(code), + }); + } + 0xC0..=0xDF => { + let Some(&l) = s.tape.get(s.pos) else { + return Err(EcError::DeviceError("fuzz tape exhausted".to_string())); + }; + s.pos += 1; + l as usize + } + _ => expected.unwrap_or(ctrl as usize), + } + .min(MAX_RESPONSE); + + // Pad with zeros if the tape runs out mid-response + let start = s.pos.min(s.tape.len()); + let end = (s.pos + len).min(s.tape.len()); + let mut resp = s.tape[start..end].to_vec(); + resp.resize(len, 0); + s.pos += len; + Ok(resp) + }) +} + +const PLATFORMS: &[crate::util::Platform] = { + use crate::util::Platform::*; + &[ + Framework12IntelGen13, + Framework12IntelCore3, + IntelGen11, + IntelGen12, + IntelGen13, + IntelCoreUltra1, + IntelCoreUltra3, + Framework13Amd7080, + Framework13AmdAi300, + Framework16Amd7080, + Framework16AmdAi300, + FrameworkDesktopAmdAiMax300, + FrameworkDesktopAmdAiMax400, + UnknownSystem, + ] +}; + +/// Split a fuzzer input into platform selector, memmap image and command tape and install it +/// +/// Layout: `[platform: u8][memmap: EC_MEMMAP_SIZE bytes][tape: rest]` +pub fn setup(data: &[u8]) -> Option { + let (&platform, rest) = data.split_first()?; + let platform = PLATFORMS[platform as usize % PLATFORMS.len()]; + crate::smbios::fuzz_set_platform(Some(platform)); + + let split = rest.len().min(EC_MEMMAP_SIZE as usize); + let (memmap, tape) = rest.split_at(split); + set_input(memmap, tape); + Some(super::CrosEc::new()) +} diff --git a/framework_lib/src/chromium_ec/mod.rs b/framework_lib/src/chromium_ec/mod.rs index 1f6e8ba2..010a0718 100644 --- a/framework_lib/src/chromium_ec/mod.rs +++ b/framework_lib/src/chromium_ec/mod.rs @@ -25,6 +25,8 @@ pub mod command; pub mod commands; #[cfg(target_os = "linux")] mod cros_ec; +#[cfg(fuzzing)] +pub mod fuzz_driver; pub mod i2c_passthrough; pub mod input_deck; pub mod panic; @@ -2221,7 +2223,11 @@ impl CrosEcDriver for CrosEc { return None; } + #[cfg(fuzzing)] + return print_err(fuzz_driver::read_memory(offset, length)); + // TODO: Change this function to return EcResult instead and print the error only in UI code + #[allow(unreachable_code)] print_err(match self.driver { #[cfg(all(not(windows), target_arch = "x86_64"))] Some(CrosEcDriverType::Portio) => portio::read_memory(offset, length), @@ -2253,6 +2259,10 @@ impl CrosEcDriver for CrosEc { ))); } + #[cfg(fuzzing)] + return fuzz_driver::send_command(command, command_version, data); + + #[allow(unreachable_code)] match self.driver { #[cfg(all(not(windows), target_arch = "x86_64"))] Some(CrosEcDriverType::Portio) => portio::send_command(command, command_version, data), diff --git a/framework_lib/src/os_specific.rs b/framework_lib/src/os_specific.rs index 3566e4c8..f9575b1c 100644 --- a/framework_lib/src/os_specific.rs +++ b/framework_lib/src/os_specific.rs @@ -40,7 +40,14 @@ pub fn get_os_version() -> String { /// Sleep a number of microseconds pub fn sleep(micros: u64) { let duration = Duration::from_micros(micros); + // Don't slow down the fuzzer, there's no hardware to wait for + #[cfg(fuzzing)] + { + let _ = duration; + return; + } #[cfg(not(feature = "uefi"))] + #[allow(unreachable_code)] { thread::sleep(duration); } diff --git a/framework_lib/src/smbios.rs b/framework_lib/src/smbios.rs index 43feff6b..3465024f 100644 --- a/framework_lib/src/smbios.rs +++ b/framework_lib/src/smbios.rs @@ -19,6 +19,12 @@ use std::io::{Read, Seek, SeekFrom}; /// Current platform. Won't ever change during the program's runtime static CACHED_PLATFORM: Mutex>> = Mutex::new(None); +/// Force the detected platform, so fuzz targets don't depend on the host's SMBIOS +#[cfg(fuzzing)] +pub fn fuzz_set_platform(platform: Option) { + *CACHED_PLATFORM.lock().unwrap() = Some(platform); +} + // TODO: Should cache SMBIOS and values gotten from it // SMBIOS is fixed after boot. Oh, so maybe not cache when we're running in UEFI diff --git a/fuzz/.gitignore b/fuzz/.gitignore new file mode 100644 index 00000000..1a45eee7 --- /dev/null +++ b/fuzz/.gitignore @@ -0,0 +1,4 @@ +target +corpus +artifacts +coverage diff --git a/fuzz/Cargo.toml b/fuzz/Cargo.toml new file mode 100644 index 00000000..2ef2049f --- /dev/null +++ b/fuzz/Cargo.toml @@ -0,0 +1,38 @@ +[package] +name = "framework_lib-fuzz" +version = "0.0.0" +publish = false +edition = "2021" + +[package.metadata] +cargo-fuzz = true + +[dependencies] +libfuzzer-sys = "0.4" + +[dependencies.framework_lib] +path = "../framework_lib" +# No hidapi/rusb, nothing to fuzz there and avoids needing the system libraries +default-features = false + +# Keep out of the main workspace, so normal builds don't need nightly/libfuzzer +[workspace] +members = ["."] + +[profile.release] +debug = 1 +overflow-checks = true + +[[bin]] +name = "ec_memmap" +path = "fuzz_targets/ec_memmap.rs" +test = false +doc = false +bench = false + +[[bin]] +name = "ec_host_cmd" +path = "fuzz_targets/ec_host_cmd.rs" +test = false +doc = false +bench = false diff --git a/fuzz/README.md b/fuzz/README.md new file mode 100644 index 00000000..dc9807ca --- /dev/null +++ b/fuzz/README.md @@ -0,0 +1,33 @@ +# Fuzzing + +Fuzz the parsing of EC responses (memory map and host commands) without hardware. +With `--cfg fuzzing` (set by cargo-fuzz), `CrosEc` uses a mock driver +(`framework_lib/src/chromium_ec/fuzz_driver.rs`) that returns fuzzer-provided data. + +Input layout: `[platform: u8][memmap: 255 bytes][host command responses...]` + +Each host command response starts with a control byte: + +- `0x00..=0xBF`: Success, response of the size the caller expects +- `0xC0..=0xDF`: Success, length from the next byte +- `0xE0..=0xFF`: EC error status + +Once the input is exhausted, all host commands fail. + +## Running + +Requires nightly and `cargo install cargo-fuzz`. + +```sh +cd fuzz +cargo +nightly fuzz run ec_memmap -- -close_fd_mask=1 -timeout=5 +cargo +nightly fuzz run ec_host_cmd -- -close_fd_mask=1 -timeout=5 + +# Keep going after crashes and collect all of them +cargo +nightly fuzz run ec_host_cmd -- -fork=4 -ignore_crashes=1 -close_fd_mask=1 + +# Reproduce a crash +cargo +nightly fuzz run ec_memmap artifacts/ec_memmap/crash-... +``` + +`-close_fd_mask=1` silences stdout, the library prints a lot. diff --git a/fuzz/fuzz_targets/ec_host_cmd.rs b/fuzz/fuzz_targets/ec_host_cmd.rs new file mode 100644 index 00000000..23933bd3 --- /dev/null +++ b/fuzz/fuzz_targets/ec_host_cmd.rs @@ -0,0 +1,54 @@ +//! Fuzz handling of EC host command responses +#![no_main] + +use framework_lib::chromium_ec::fuzz_driver; +use framework_lib::{ccgx, parade_retimer, power}; +use libfuzzer_sys::fuzz_target; + +fuzz_target!(|data: &[u8]| { + let Some(ec) = fuzz_driver::setup(data) else { + return; + }; + + // PD / power + power::get_and_print_pd_info(&ec); + power::get_and_print_cypd_pd_info(&ec); + let _ = power::read_pd_version(&ec); + let _ = power::is_charging(&ec); + let _ = power::get_cutoff_status(&ec); + let _ = power::get_thermal_thresholds(&ec); + power::print_thermal_thresholds(&ec); + let _ = ccgx::get_pd_controller_versions(&ec); + let _ = parade_retimer::get_version(&ec); + + // EC info + let _ = ec.version_info(); + let _ = ec.get_protocol_info(); + let _ = ec.get_features(); + let _ = ec.get_sysinfo(); + let _ = ec.get_uptime_info(); + let _ = ec.get_ap_throttle_status(); + let _ = ec.get_panic_info(); + let _ = ec.get_s0ix_counter(); + let _ = ec.get_ec_hib_delay(); + if let Some(info) = power::power_info(&ec) { + let _ = ec.get_charge_state(&info); + } + let _ = ec.console_read(); + let _ = ec.motionsense_sensor_list(); + + // Platform features + let _ = ec.get_privacy_info(); + let _ = ec.get_charge_limit(); + let _ = ec.get_fp_led_level(); + let _ = ec.get_intrusion_status(); + let _ = ec.get_input_deck_status(); + let _ = ec.print_fw12_inputdeck_status(); + let _ = ec.print_fw13_inputdeck_status(); + let _ = ec.print_fw16_inputdeck_status(); + let _ = ec.get_keyboard_backlight(); + let _ = ec.check_bay_status(); + let _ = ec.get_gpu_serial(); + let _ = ec.read_gpu_desc_header(); + let _ = ec.get_all_gpios(); +}); diff --git a/fuzz/fuzz_targets/ec_memmap.rs b/fuzz/fuzz_targets/ec_memmap.rs new file mode 100644 index 00000000..dcda252a --- /dev/null +++ b/fuzz/fuzz_targets/ec_memmap.rs @@ -0,0 +1,23 @@ +//! Fuzz parsing of the EC memory map (battery, thermal, sensors, switches, ...) +#![no_main] + +use framework_lib::chromium_ec::fuzz_driver; +use framework_lib::power; +use libfuzzer_sys::fuzz_target; + +fuzz_target!(|data: &[u8]| { + let Some(ec) = fuzz_driver::setup(data) else { + return; + }; + + let _ = ec.check_mem_magic(); + let _ = power::power_info(&ec); + power::get_and_print_power_info(&ec); + power::print_memmap_version_info(&ec); + let _ = power::get_thermal(&ec); + power::print_thermal(&ec); + let _ = power::get_fan_num(&ec); + power::print_switches(&ec); + let _ = power::get_accel_data(&ec); + power::print_sensors(&ec); +}); From 674f3c2b5127f339aeaeba587bcd8d8a98234a80 Mon Sep 17 00:00:00 2001 From: Daniel Schaefer Date: Fri, 20 Nov 2026 11:42:15 +0800 Subject: [PATCH 04/31] ccgx: Don't panic on truncated PD binaries read_256_bytes returns only 0x80 bytes when the row is at the end of the file (needed for CCG3, where the metadata is in the last row). But the metadata parsers and read_version index past that at 0xC0 and 0xE0, so a truncated or malformed binary panics. Found by fuzzing. Co-Authored-By: Claude Opus 5.5 --- framework_lib/src/ccgx/binary.rs | 29 ++++++++++++++++++++++++++++- framework_lib/src/ccgx/mod.rs | 6 +++--- 2 files changed, 31 insertions(+), 4 deletions(-) diff --git a/framework_lib/src/ccgx/binary.rs b/framework_lib/src/ccgx/binary.rs index 799e9b34..9c2f6de2 100644 --- a/framework_lib/src/ccgx/binary.rs +++ b/framework_lib/src/ccgx/binary.rs @@ -152,7 +152,8 @@ fn read_version( read_metadata(file_buffer, flash_row_size, metadata_offset, ccgx)?; let data = read_256_bytes(file_buffer, fw_row_start, flash_row_size)?; trace!("First row of firmware: {:X?}", data); - let data = &data[FW_VERSION_OFFSET..]; + // Row might be too short, if the firmware starts in the last row of the file + let data = data.get(FW_VERSION_OFFSET..)?; let (version_info, _) = VersionInfo::read_from_prefix(data).ok()?; @@ -778,4 +779,30 @@ mod tests { } }); } + + #[test] + // Metadata row is the last 0x80 bytes of the file, too short for the metadata + fn truncated_metadata_row() { + let mut pd_bin_path = PathBuf::from(env!("CARGO_MANIFEST_DIR")); + pd_bin_path.push("test_bins/adl-pd-0.1.33.bin"); + let data = fs::read(pd_bin_path).unwrap(); + + // FW1 metadata is in row 0x1FE at 0xFF00 + let data = &data[..0xFF80]; + assert_eq!(read_versions(data, SiliconFamily::Ccg6Adl), None); + assert_eq!(read_versions(data, SiliconFamily::Ccg6), None); + } + + #[test] + // Metadata points to a firmware in the last row, too short for the version + fn truncated_firmware_row() { + let mut data = vec![0; 0x10000]; + // CCG6 FW1 metadata at row 0x1FE, offset 0xC0 + let metadata = 0x1FE * SMALL_ROW + 0xC0; + // Firmware starts in the row after boot_last_row, the last row of the file + data[metadata + 0x05..metadata + 0x07].copy_from_slice(&0x1FEu16.to_le_bytes()); + data[metadata + 0x16..metadata + 0x18].copy_from_slice(&0x4359u16.to_le_bytes()); + + assert_eq!(read_versions(&data, SiliconFamily::Ccg6), None); + } } diff --git a/framework_lib/src/ccgx/mod.rs b/framework_lib/src/ccgx/mod.rs index 44d106fd..c020d2a4 100644 --- a/framework_lib/src/ccgx/mod.rs +++ b/framework_lib/src/ccgx/mod.rs @@ -273,7 +273,7 @@ pub fn get_pd_controller_versions(ec: &CrosEc) -> EcResult { } fn parse_metadata_ccg3(buffer: &[u8]) -> Option<(u32, u32)> { - let buffer = &buffer[CCG3_METADATA_OFFSET..]; + let buffer = buffer.get(CCG3_METADATA_OFFSET..)?; let (metadata, _) = CyAcdMetadata::read_from_prefix(buffer).ok()?; trace!("Metadata: {:X?}", metadata); if metadata.metadata_valid.get() == METADATA_MAGIC { @@ -288,7 +288,7 @@ fn parse_metadata_ccg3(buffer: &[u8]) -> Option<(u32, u32)> { //fn parse_metadata(buffer: &[u8; 256]) -> Option<(u32, u32)> { fn parse_metadata_cyacd(buffer: &[u8]) -> Option<(u32, u32)> { - let buffer = &buffer[METADATA_OFFSET..]; + let buffer = buffer.get(METADATA_OFFSET..)?; let (metadata, _) = CyAcdMetadata::read_from_prefix(buffer).ok()?; trace!("Metadata: {:X?}", metadata); if metadata.metadata_valid.get() == METADATA_MAGIC { @@ -302,7 +302,7 @@ fn parse_metadata_cyacd(buffer: &[u8]) -> Option<(u32, u32)> { } fn parse_metadata_cyacd2(buffer: &[u8]) -> Option<(u32, u32)> { - let buffer = &buffer[CCG8_METADATA_OFFSET..]; + let buffer = buffer.get(CCG8_METADATA_OFFSET..)?; let (metadata, _) = CyAcd2Metadata::read_from_prefix(buffer).ok()?; trace!("Metadata: {:X?}", metadata); if metadata.metadata_valid.get() == CCG8_METADATA_MAGIC { From ada76790a99d1b46a10ddf039dad8613ae26105d Mon Sep 17 00:00:00 2001 From: Daniel Schaefer Date: Fri, 20 Nov 2026 11:42:15 +0800 Subject: [PATCH 05/31] fuzz: Add EC and CCGX firmware binary targets Input is the firmware file itself, seeded from test_bins. See README. Co-Authored-By: Claude Opus 5.5 --- fuzz/Cargo.toml | 14 ++++++++++++++ fuzz/README.md | 24 +++++++++++++++++++++++- fuzz/fuzz_targets/ccgx_binary.rs | 26 ++++++++++++++++++++++++++ fuzz/fuzz_targets/ec_binary.rs | 18 ++++++++++++++++++ 4 files changed, 81 insertions(+), 1 deletion(-) create mode 100644 fuzz/fuzz_targets/ccgx_binary.rs create mode 100644 fuzz/fuzz_targets/ec_binary.rs diff --git a/fuzz/Cargo.toml b/fuzz/Cargo.toml index 2ef2049f..67e2359a 100644 --- a/fuzz/Cargo.toml +++ b/fuzz/Cargo.toml @@ -36,3 +36,17 @@ path = "fuzz_targets/ec_host_cmd.rs" test = false doc = false bench = false + +[[bin]] +name = "ec_binary" +path = "fuzz_targets/ec_binary.rs" +test = false +doc = false +bench = false + +[[bin]] +name = "ccgx_binary" +path = "fuzz_targets/ccgx_binary.rs" +test = false +doc = false +bench = false diff --git a/fuzz/README.md b/fuzz/README.md index dc9807ca..f8818d06 100644 --- a/fuzz/README.md +++ b/fuzz/README.md @@ -1,6 +1,7 @@ # Fuzzing -Fuzz the parsing of EC responses (memory map and host commands) without hardware. +Fuzz the parsing of EC responses (memory map and host commands) without hardware, +and the parsing of firmware binaries. With `--cfg fuzzing` (set by cargo-fuzz), `CrosEc` uses a mock driver (`framework_lib/src/chromium_ec/fuzz_driver.rs`) that returns fuzzer-provided data. @@ -31,3 +32,24 @@ cargo +nightly fuzz run ec_memmap artifacts/ec_memmap/crash-... ``` `-close_fd_mask=1` silences stdout, the library prints a lot. + +## Firmware binary parsing + +These targets take the firmware file itself as input, so crash artifacts can be +reproduced with the real tool (`framework_tool --ec-bin`/`--pd-bin`). + +- `ec_binary`: EC firmware binaries +- `ccgx_binary`: CCGX PD firmware binaries, tried with every silicon family + +The interesting data is at offsets far beyond libFuzzer's default max input +length, so seed the corpus with real binaries and raise `-max_len`: + +```sh +cd fuzz +mkdir -p corpus/ec_binary corpus/ccgx_binary +cp ../framework_lib/test_bins/*-ec-*.bin corpus/ec_binary/ +cp ../framework_lib/test_bins/*pd*.bin ../framework_lib/test_bins/dahlia-*.bin corpus/ccgx_binary/ + +cargo +nightly fuzz run ec_binary -- -close_fd_mask=1 -max_len=524288 +cargo +nightly fuzz run ccgx_binary -- -close_fd_mask=1 -max_len=262144 +``` diff --git a/fuzz/fuzz_targets/ccgx_binary.rs b/fuzz/fuzz_targets/ccgx_binary.rs new file mode 100644 index 00000000..81017e44 --- /dev/null +++ b/fuzz/fuzz_targets/ccgx_binary.rs @@ -0,0 +1,26 @@ +//! Fuzz parsing of CCGX PD firmware binaries (--pd-bin) +#![no_main] + +use framework_lib::ccgx::binary; +use framework_lib::ccgx::SiliconFamily; +use libfuzzer_sys::fuzz_target; + +fuzz_target!(|data: &[u8]| { + let families = [ + SiliconFamily::Ccg3, + SiliconFamily::Ccg5, + SiliconFamily::Ccg6Adl, + SiliconFamily::Ccg6, + SiliconFamily::Ccg8D, + SiliconFamily::Ccg8S, + SiliconFamily::Ccg6Cfp, + SiliconFamily::Ccg8Cfp, + ]; + // Unlike the commandline, try all families, not just until the first match + for family in families { + if let Some(versions) = binary::read_versions(data, family) { + binary::print_fw(&versions.backup_fw); + binary::print_fw(&versions.main_fw); + } + } +}); diff --git a/fuzz/fuzz_targets/ec_binary.rs b/fuzz/fuzz_targets/ec_binary.rs new file mode 100644 index 00000000..70a4bf12 --- /dev/null +++ b/fuzz/fuzz_targets/ec_binary.rs @@ -0,0 +1,18 @@ +//! Fuzz parsing of EC firmware binaries (--ec-bin) +#![no_main] + +use framework_lib::ec_binary; +use libfuzzer_sys::fuzz_target; + +fuzz_target!(|data: &[u8]| { + for ro in [true, false] { + if let Some(ver) = ec_binary::read_ec_version(data, ro) { + ec_binary::print_ec_version(&ver, ro); + } + } + + // Version string parsing, also used on the version reported by the EC + if let Ok(s) = std::str::from_utf8(&data[..data.len().min(64)]) { + let _ = ec_binary::parse_ec_version_str(s); + } +}); From 625b7611439e701f0d2d42eabf4850d31836a937 Mon Sep 17 00:00:00 2001 From: Daniel Schaefer Date: Fri, 20 Nov 2026 11:54:23 +0800 Subject: [PATCH 06/31] capsule: Don't panic on truncated capsule headers Reading the capsule header or the Windows UX header out of a file that's too short panicked. Return None instead. And don't underflow when calculating the image size of a UX capsule with a bogus size. Found by fuzzing. Co-Authored-By: Claude Opus 5.5 --- framework_lib/src/capsule.rs | 37 +++++++++++++++++++--------- framework_lib/src/commandline/mod.rs | 12 ++++++--- 2 files changed, 34 insertions(+), 15 deletions(-) diff --git a/framework_lib/src/capsule.rs b/framework_lib/src/capsule.rs index 2b59ada6..8f5ad097 100644 --- a/framework_lib/src/capsule.rs +++ b/framework_lib/src/capsule.rs @@ -112,8 +112,9 @@ fn print_capsule_flags(flags: u32) { } } -fn read_capsule_header(data: &[u8]) -> EfiCapsuleHeader { - EfiCapsuleHeader { +fn read_capsule_header(data: &[u8]) -> Option { + let data = data.get(..core::mem::size_of::())?; + Some(EfiCapsuleHeader { capsule_guid: CGuid::from(GUID::build_from_components( u32::from_le_bytes(data[0..4].try_into().unwrap()), u16::from_le_bytes(data[4..6].try_into().unwrap()), @@ -123,11 +124,11 @@ fn read_capsule_header(data: &[u8]) -> EfiCapsuleHeader { header_size: u32::from_le_bytes(data[16..20].try_into().unwrap()), flags: u32::from_le_bytes(data[20..24].try_into().unwrap()), capsule_image_size: u32::from_le_bytes(data[24..28].try_into().unwrap()), - } + }) } pub fn parse_capsule_header(data: &[u8]) -> Option { - let header = read_capsule_header(data); + let header = read_capsule_header(data)?; if header.is_valid(data) { Some(header) } else { @@ -152,10 +153,11 @@ pub fn print_capsule_header(header: &EfiCapsuleHeader) { ); } -pub fn parse_ux_header(data: &[u8]) -> DisplayCapsule { - let capsule_header = read_capsule_header(data); - let p = &data[core::mem::size_of::()..]; - DisplayCapsule { +pub fn parse_ux_header(data: &[u8]) -> Option { + let capsule_header = read_capsule_header(data)?; + let p = + data.get(core::mem::size_of::()..core::mem::size_of::())?; + Some(DisplayCapsule { capsule_header, image_payload: DisplayPayload { version: p[0], @@ -166,7 +168,7 @@ pub fn parse_ux_header(data: &[u8]) -> DisplayCapsule { offset_x: u32::from_le_bytes(p[8..12].try_into().unwrap()), offset_y: u32::from_le_bytes(p[12..16].try_into().unwrap()), }, - } + }) } pub fn print_ux_header(header: &DisplayCapsule) { let header_len = core::mem::size_of::(); @@ -186,7 +188,7 @@ pub fn print_ux_header(header: &DisplayCapsule) { println!(" Mode: {:>20}", { ux_header.mode }); println!(" Offset X: {:>20}", { ux_header.offset_x }); println!(" Offset Y: {:>20}", { ux_header.offset_y }); - let image_size = header.capsule_header.capsule_image_size as usize - header_len; + let image_size = (header.capsule_header.capsule_image_size as usize).saturating_sub(header_len); println!(" Calculcated Size: {:>14} B", image_size); println!(" Calculcated Size: {:>14} KB", image_size / 1024); } @@ -235,7 +237,7 @@ mod tests { assert_eq!(cap, expected_header); assert_eq!(cap.capsule_guid, CGuid::from(esrt::WINUX_GUID)); - let ux_header = parse_ux_header(&data); + let ux_header = parse_ux_header(&data).unwrap(); assert_eq!( ux_header, DisplayCapsule { @@ -252,4 +254,17 @@ mod tests { } ); } + + #[test] + fn truncated_capsule() { + let mut capsule_path = PathBuf::from(env!("CARGO_MANIFEST_DIR")); + capsule_path.push("test_bins/winux.bin"); + let data = fs::read(capsule_path).unwrap(); + + // Shorter than the capsule header + assert_eq!(parse_capsule_header(&data[..27]), None); + assert_eq!(parse_ux_header(&data[..27]), None); + // Has capsule header, but shorter than the UX header + assert_eq!(parse_ux_header(&data[..43]), None); + } } diff --git a/framework_lib/src/commandline/mod.rs b/framework_lib/src/commandline/mod.rs index f23d5e9e..5f1da58e 100644 --- a/framework_lib/src/commandline/mod.rs +++ b/framework_lib/src/commandline/mod.rs @@ -2206,8 +2206,9 @@ pub fn run_with_args(args: &Cli, _allupdate: bool) -> i32 { println!(" Size: {:>20} KB", data.len() / 1024); if let Some(header) = analyze_capsule(&data) { if header.capsule_guid == CGuid::from(esrt::WINUX_GUID) { - let ux_header = capsule::parse_ux_header(&data); - if let Some(dump_path) = &args.dump { + if let (Some(ux_header), Some(dump_path)) = + (capsule::parse_ux_header(&data), &args.dump) + { // TODO: Better error handling, rather than just panicking capsule::dump_winux_image(&data, &ux_header, dump_path); } @@ -3092,8 +3093,11 @@ pub fn analyze_capsule(data: &[u8]) -> Option { } esrt::WINUX_GUID => { println!(" Type: Windows UX capsule"); - let ux_header = capsule::parse_ux_header(data); - capsule::print_ux_header(&ux_header); + if let Some(ux_header) = capsule::parse_ux_header(data) { + capsule::print_ux_header(&ux_header); + } else { + println!(" Windows UX header is truncated"); + } } _ => { println!(" Type: Unknown"); From fa341f2b9def0cea47f28d6913c18b70e56edc8f Mon Sep 17 00:00:00 2001 From: Daniel Schaefer Date: Fri, 20 Nov 2026 11:54:23 +0800 Subject: [PATCH 07/31] capsule_content: Don't panic on truncated BIOS capsules When a marker is found close to the end of the file, the data following it was sliced without bounds checks. Found by fuzzing. Co-Authored-By: Claude Opus 5.5 --- framework_lib/src/capsule_content.rs | 30 +++++++++++++++++++++------- 1 file changed, 23 insertions(+), 7 deletions(-) diff --git a/framework_lib/src/capsule_content.rs b/framework_lib/src/capsule_content.rs index e993f03f..04240804 100644 --- a/framework_lib/src/capsule_content.rs +++ b/framework_lib/src/capsule_content.rs @@ -16,7 +16,7 @@ pub fn find_retimer_version(data: &[u8]) -> Option { let needle = b"$_RETIMER_PARAM_"; let found = util::find_sequence(data, needle)?; let offset = found + 0x8 + needle.len(); - let bytes = &data[offset..offset + 2]; + let bytes = data.get(offset..offset + 2)?; Some(u16::from_le_bytes(bytes.try_into().ok()?)) } @@ -31,12 +31,12 @@ pub fn find_bios_version(data: &[u8]) -> Option { // One of: GFW30, HFW3T, HFW30, IFR30, KFM30, JFP30, LFK30, IFGA3, IFGP6, LFR20, LFSP0 let platform_offset = found + 0xA + needle.len() - 1; - let platform = core::str::from_utf8(&data[platform_offset..platform_offset + 5]) + let platform = core::str::from_utf8(data.get(platform_offset..platform_offset + 5)?) .map(|x| x.to_string()) .ok()?; let ver_offset = found + 0x10 + needle.len() - 1; - let version = core::str::from_utf8(&data[ver_offset..ver_offset + 5]) + let version = core::str::from_utf8(data.get(ver_offset..ver_offset + 5)?) .map(|x| x.to_string()) .ok()?; @@ -47,7 +47,7 @@ pub fn find_ec_in_bios_cap(data: &[u8]) -> Option<&[u8]> { let needle = b"$_IFLASH_EC_IMG_"; let found = util::find_sequence(data, needle)?; let ec_offset = found + 0x9 + needle.len() - 1; - Some(&data[ec_offset..ec_offset + EC_LEN]) + data.get(ec_offset..ec_offset + EC_LEN) } pub fn find_pd_in_bios_cap(data: &[u8]) -> Option<&[u8]> { @@ -58,12 +58,28 @@ pub fn find_pd_in_bios_cap(data: &[u8]) -> Option<&[u8]> { let ccg6_needle = &[0x00, 0x40, 0x00, 0x20, 0x11, 0x00]; let ccg8_needle = &[0x00, 0x80, 0x00, 0x20, 0xAD, 0x0C]; if let Some(found_pd1) = util::find_sequence(data, ccg5_needle) { - Some(&data[found_pd1..found_pd1 + CCG5_PD_LEN]) + data.get(found_pd1..found_pd1 + CCG5_PD_LEN) } else if let Some(found_pd1) = util::find_sequence(data, ccg6_needle) { - Some(&data[found_pd1..found_pd1 + CCG6_PD_LEN]) + data.get(found_pd1..found_pd1 + CCG6_PD_LEN) } else if let Some(found_pd1) = util::find_sequence(data, ccg8_needle) { - Some(&data[found_pd1..found_pd1 + CCG8_PD_LEN]) + data.get(found_pd1..found_pd1 + CCG8_PD_LEN) } else { None } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + // Needle found at the end of the file, without the data after it + fn truncated_content() { + assert!(find_retimer_version(b"$_RETIMER_PARAM_").is_none()); + assert!(find_bios_version(b"$BVDT").is_none()); + assert!(find_ec_in_bios_cap(b"$_IFLASH_EC_IMG_").is_none()); + assert!(find_pd_in_bios_cap(&[0x00, 0x20, 0x00, 0x20, 0x11, 0x00]).is_none()); + assert!(find_pd_in_bios_cap(&[0x00, 0x40, 0x00, 0x20, 0x11, 0x00]).is_none()); + assert!(find_pd_in_bios_cap(&[0x00, 0x80, 0x00, 0x20, 0xAD, 0x0C]).is_none()); + } +} From 67f7c8f2cad755ba9892afcf76447fb7d14936cb Mon Sep 17 00:00:00 2001 From: Daniel Schaefer Date: Fri, 20 Nov 2026 11:54:23 +0800 Subject: [PATCH 08/31] capsule: Fix --dump of Windows UX capsule image dropping 44 bytes The image was sliced as data[header_len..image_size], but image_size is already the size without the header, so the end was cut short by the header length. The dumped BMP was 44 bytes shorter than the size in its own header. Also don't panic if the capsule is smaller than claimed. Co-Authored-By: Claude Opus 5.5 --- framework_lib/src/capsule.rs | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/framework_lib/src/capsule.rs b/framework_lib/src/capsule.rs index 8f5ad097..6141a52e 100644 --- a/framework_lib/src/capsule.rs +++ b/framework_lib/src/capsule.rs @@ -196,9 +196,12 @@ pub fn print_ux_header(header: &DisplayCapsule) { /// Extract the image data from the display capsule to a file pub fn dump_winux_image(data: &[u8], header: &DisplayCapsule, filename: &str) { let header_len = core::mem::size_of::(); - let image_size = header.capsule_header.capsule_image_size as usize - header_len; + let image_size = (header.capsule_header.capsule_image_size as usize).saturating_sub(header_len); - let image = &data[header_len..image_size]; + let Some(image) = data.get(header_len..header_len + image_size) else { + println!("Capsule is too small for the image size in its header"); + return; + }; #[cfg(not(feature = "uefi"))] { From ceb4b9e06017728613e7cbe5994a903423f6fdad Mon Sep 17 00:00:00 2001 From: Daniel Schaefer Date: Fri, 20 Nov 2026 11:54:32 +0800 Subject: [PATCH 09/31] fuzz: Add UEFI and H2O capsule targets Co-Authored-By: Claude Opus 5.5 --- fuzz/Cargo.toml | 14 ++++++++++++++ fuzz/README.md | 6 ++++++ fuzz/fuzz_targets/capsule.rs | 15 +++++++++++++++ fuzz/fuzz_targets/h2o_capsule.rs | 26 ++++++++++++++++++++++++++ 4 files changed, 61 insertions(+) create mode 100644 fuzz/fuzz_targets/capsule.rs create mode 100644 fuzz/fuzz_targets/h2o_capsule.rs diff --git a/fuzz/Cargo.toml b/fuzz/Cargo.toml index 67e2359a..635bbdb3 100644 --- a/fuzz/Cargo.toml +++ b/fuzz/Cargo.toml @@ -50,3 +50,17 @@ path = "fuzz_targets/ccgx_binary.rs" test = false doc = false bench = false + +[[bin]] +name = "capsule" +path = "fuzz_targets/capsule.rs" +test = false +doc = false +bench = false + +[[bin]] +name = "h2o_capsule" +path = "fuzz_targets/h2o_capsule.rs" +test = false +doc = false +bench = false diff --git a/fuzz/README.md b/fuzz/README.md index f8818d06..fc6a2730 100644 --- a/fuzz/README.md +++ b/fuzz/README.md @@ -40,6 +40,8 @@ reproduced with the real tool (`framework_tool --ec-bin`/`--pd-bin`). - `ec_binary`: EC firmware binaries - `ccgx_binary`: CCGX PD firmware binaries, tried with every silicon family +- `capsule`: UEFI capsules, including the Windows UX capsule header (`--capsule`) +- `h2o_capsule`: Finding BIOS version, EC and PD firmware in Insyde BIOS capsules (`--h2o-capsule`) The interesting data is at offsets far beyond libFuzzer's default max input length, so seed the corpus with real binaries and raise `-max_len`: @@ -52,4 +54,8 @@ cp ../framework_lib/test_bins/*pd*.bin ../framework_lib/test_bins/dahlia-*.bin c cargo +nightly fuzz run ec_binary -- -close_fd_mask=1 -max_len=524288 cargo +nightly fuzz run ccgx_binary -- -close_fd_mask=1 -max_len=262144 + +mkdir -p corpus/capsule && cp ../framework_lib/test_bins/winux.bin corpus/capsule/ +cargo +nightly fuzz run capsule -- -close_fd_mask=1 -max_len=1048576 +cargo +nightly fuzz run h2o_capsule -- -close_fd_mask=1 -max_len=1048576 ``` diff --git a/fuzz/fuzz_targets/capsule.rs b/fuzz/fuzz_targets/capsule.rs new file mode 100644 index 00000000..6574ce09 --- /dev/null +++ b/fuzz/fuzz_targets/capsule.rs @@ -0,0 +1,15 @@ +//! Fuzz parsing of UEFI capsules (--capsule) +#![no_main] + +use framework_lib::capsule; +use framework_lib::commandline::analyze_capsule; +use framework_lib::esrt; +use libfuzzer_sys::fuzz_target; + +fuzz_target!(|data: &[u8]| { + if let Some(header) = analyze_capsule(data) { + if header.capsule_guid == esrt::WINUX_GUID.into() { + let _ = capsule::parse_ux_header(data); + } + } +}); diff --git a/fuzz/fuzz_targets/h2o_capsule.rs b/fuzz/fuzz_targets/h2o_capsule.rs new file mode 100644 index 00000000..22229cec --- /dev/null +++ b/fuzz/fuzz_targets/h2o_capsule.rs @@ -0,0 +1,26 @@ +//! Fuzz parsing of Insyde H2O BIOS capsule content (--h2o-capsule) +#![no_main] + +use framework_lib::capsule_content::*; +use framework_lib::ccgx::{binary, SiliconFamily}; +use framework_lib::commandline::analyze_ec_fw; +use libfuzzer_sys::fuzz_target; + +fuzz_target!(|data: &[u8]| { + let _ = find_bios_version(data); + let _ = find_retimer_version(data); + if let Some(ec_bin) = find_ec_in_bios_cap(data) { + analyze_ec_fw(ec_bin); + } + if let Some(pd_bin) = find_pd_in_bios_cap(data) { + for family in [ + SiliconFamily::Ccg5, + SiliconFamily::Ccg6Adl, + SiliconFamily::Ccg6, + SiliconFamily::Ccg8D, + SiliconFamily::Ccg8S, + ] { + let _ = binary::read_versions(pd_bin, family); + } + } +}); From b14a949709bec8ac8005259ba1ba61d55e721113 Mon Sep 17 00:00:00 2001 From: Daniel Schaefer Date: Fri, 20 Nov 2026 11:58:03 +0800 Subject: [PATCH 10/31] fuzz: Seed h2o_capsule target with EC and PD binaries Without seeds the fuzzer never produces an input large enough to contain the embedded EC and PD firmware, so it only covered the marker search. Generate minimal capsules from test_bins. Also try all PD silicon families and print the result, like the ccgx_binary target. Co-Authored-By: Claude Opus 5.5 --- fuzz/README.md | 2 ++ fuzz/fuzz_targets/h2o_capsule.rs | 9 ++++++++- fuzz/seed_h2o_capsule.py | 29 +++++++++++++++++++++++++++++ 3 files changed, 39 insertions(+), 1 deletion(-) create mode 100755 fuzz/seed_h2o_capsule.py diff --git a/fuzz/README.md b/fuzz/README.md index fc6a2730..c7376a04 100644 --- a/fuzz/README.md +++ b/fuzz/README.md @@ -57,5 +57,7 @@ cargo +nightly fuzz run ccgx_binary -- -close_fd_mask=1 -max_len=262144 mkdir -p corpus/capsule && cp ../framework_lib/test_bins/winux.bin corpus/capsule/ cargo +nightly fuzz run capsule -- -close_fd_mask=1 -max_len=1048576 +# BIOS capsules are too big to check in, generate minimal ones from test_bins +python3 seed_h2o_capsule.py cargo +nightly fuzz run h2o_capsule -- -close_fd_mask=1 -max_len=1048576 ``` diff --git a/fuzz/fuzz_targets/h2o_capsule.rs b/fuzz/fuzz_targets/h2o_capsule.rs index 22229cec..4d3cce75 100644 --- a/fuzz/fuzz_targets/h2o_capsule.rs +++ b/fuzz/fuzz_targets/h2o_capsule.rs @@ -13,14 +13,21 @@ fuzz_target!(|data: &[u8]| { analyze_ec_fw(ec_bin); } if let Some(pd_bin) = find_pd_in_bios_cap(data) { + // Unlike the commandline, try all families, not just until the first match for family in [ + SiliconFamily::Ccg3, SiliconFamily::Ccg5, SiliconFamily::Ccg6Adl, SiliconFamily::Ccg6, SiliconFamily::Ccg8D, SiliconFamily::Ccg8S, + SiliconFamily::Ccg6Cfp, + SiliconFamily::Ccg8Cfp, ] { - let _ = binary::read_versions(pd_bin, family); + if let Some(versions) = binary::read_versions(pd_bin, family) { + binary::print_fw(&versions.backup_fw); + binary::print_fw(&versions.main_fw); + } } } }); diff --git a/fuzz/seed_h2o_capsule.py b/fuzz/seed_h2o_capsule.py new file mode 100755 index 00000000..2d4ddc5f --- /dev/null +++ b/fuzz/seed_h2o_capsule.py @@ -0,0 +1,29 @@ +#!/usr/bin/env python3 +"""Generate seeds for the h2o_capsule fuzz target from test_bins + +Real BIOS capsules are too big to check in, so build minimal ones that +contain just the markers and the embedded EC and PD firmware. +""" +import itertools +import pathlib + +BINS = pathlib.Path(__file__).parent / "../framework_lib/test_bins" +OUT = pathlib.Path(__file__).parent / "corpus/h2o_capsule" + +# PD region sizes in the capsule, see capsule_content.rs +PD_LEN = {b"\x00\x20": 0x20000, b"\x00\x40": 0x20000, b"\x00\x80": 0x40000} + +OUT.mkdir(parents=True, exist_ok=True) +ecs = sorted(BINS.glob("*-ec-*.bin")) +pds = [p for p in sorted(BINS.glob("*-pd-*.bin")) if p.read_bytes()[:2] in PD_LEN] +for ec, pd in itertools.product(ecs, pds): + pd_data = pd.read_bytes() + pd_data = pd_data.ljust(PD_LEN[pd_data[:2]], b"\xff") + seed = ( + b"$BVDT" + b"\x00" * 9 + b"HFW30" + b"\x00" + b"03.05" + b"\x00" * 8 + + b"$_RETIMER_PARAM_" + b"\x00" * 8 + b"\x34\x12" + + b"$_IFLASH_EC_IMG_" + b"\x00" * 8 + ec.read_bytes() + + pd_data + ) + (OUT / f"{ec.stem}+{pd.stem}.bin").write_bytes(seed) + print(OUT / f"{ec.stem}+{pd.stem}.bin") From d9a93bf0766c9fec3acfcbdcf49e5ca3a3cdcdb1 Mon Sep 17 00:00:00 2001 From: Daniel Schaefer Date: Fri, 20 Nov 2026 12:01:48 +0800 Subject: [PATCH 11/31] chromium_ec: Don't loop forever if EC reports erase block size 0 erase_ec_flash() advances by the erase block size from EC_CMD_FLASH_INFO, so a 0 there made it loop forever. Return an error instead. With the previous commit this also re-locks the flash. Co-Authored-By: Claude Opus 5.5 --- framework_lib/src/chromium_ec/mod.rs | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/framework_lib/src/chromium_ec/mod.rs b/framework_lib/src/chromium_ec/mod.rs index 010a0718..f04b0597 100644 --- a/framework_lib/src/chromium_ec/mod.rs +++ b/framework_lib/src/chromium_ec/mod.rs @@ -1184,6 +1184,12 @@ impl CrosEc { ) -> EcResult<()> { // Erasing a big section takes too long sometimes and the linux kernel driver times out, so // split it up into chunks. + if chunk_size == 0 { + // Would never make progress + return Err(EcError::DeviceError( + "EC reported an erase block size of 0".to_string(), + )); + } let mut cur_offset = offset; while cur_offset < offset + size { From bdc294eaa668603a6a427c1fdca3ad06b9cc321f Mon Sep 17 00:00:00 2001 From: Daniel Schaefer Date: Fri, 20 Nov 2026 12:02:26 +0800 Subject: [PATCH 12/31] chromium_ec: Don't panic on short EC flash read response read_ec_flash_chunk() sliced the response to the requested size, which panicked if the driver returned fewer bytes. Return an error instead. Longer responses (as seen on Windows) are still accepted. Co-Authored-By: Claude Opus 5.5 --- framework_lib/src/chromium_ec/mod.rs | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/framework_lib/src/chromium_ec/mod.rs b/framework_lib/src/chromium_ec/mod.rs index f04b0597..a6f84cf8 100644 --- a/framework_lib/src/chromium_ec/mod.rs +++ b/framework_lib/src/chromium_ec/mod.rs @@ -1228,9 +1228,16 @@ impl CrosEc { //assert!(size <= 0x80); // TODO: I think this is EC_LPC_HOST_PACKET_SIZE - size_of::() let data = EcRequestFlashRead { offset, size }.send_command_vec(self)?; - // TODO: Windows asserts because it returns more data - //debug_assert!(data.len() == size as usize); // Make sure we get back what was requested - Ok(data[..size as usize].to_vec()) + // Windows returns more data than requested, so only check that we got at least that much + data.get(..size as usize) + .map(|x| x.to_vec()) + .ok_or_else(|| { + EcError::DeviceError(format!( + "Flash read returned {} bytes, expected {}", + data.len(), + size + )) + }) } pub fn read_ec_flash(&self, offset: u32, size: u32) -> EcResult> { From c9316efb6bc7f0281214b8e7142e0e372f7962e8 Mon Sep 17 00:00:00 2001 From: Daniel Schaefer Date: Fri, 20 Nov 2026 12:03:02 +0800 Subject: [PATCH 13/31] chromium_ec: Don't drop last partial chunk when writing/reading EC flash write_ec_flash() and read_ec_flash() computed the number of 0x80 byte chunks by rounding down, so a trailing partial chunk was silently not written or read, even though the loop body already handles a shorter last chunk. All regions are multiples of 0x80 today, so this did not trigger yet. Also print the real end address and read size in the progress output. Co-Authored-By: Claude Opus 5.5 --- framework_lib/src/chromium_ec/mod.rs | 11 ++++------- 1 file changed, 4 insertions(+), 7 deletions(-) diff --git a/framework_lib/src/chromium_ec/mod.rs b/framework_lib/src/chromium_ec/mod.rs index a6f84cf8..2eaa37a8 100644 --- a/framework_lib/src/chromium_ec/mod.rs +++ b/framework_lib/src/chromium_ec/mod.rs @@ -1129,11 +1129,11 @@ impl CrosEc { let chunk_size = 0x80; - let chunks = data.len() / chunk_size; + let chunks = data.len().div_ceil(chunk_size); println!( " Will write flash from 0x{:X} to 0x{:X} in {}*{}B chunks", addr, - data.len(), + addr as usize + data.len(), chunks, chunk_size ); @@ -1247,7 +1247,7 @@ impl CrosEc { let (chunk_size, chunks) = if size <= 0x80 { (size, 1) } else { - (0x80, size / 0x80) + (0x80, size.div_ceil(0x80)) }; for chunk_no in 0..chunks { #[cfg(feature = "uefi")] @@ -1266,10 +1266,7 @@ impl CrosEc { println!(); print!( "Reading chunk {:>4}/{:>4} ({:>6}/{:>6}): X", - chunk_no, - chunks, - offset, - cur_chunk_size * chunks + chunk_no, chunks, offset, size ); } else { print!("X"); From ac20e9f8a53bd89bf80bff5225a4ed750a39cfa1 Mon Sep 17 00:00:00 2001 From: Daniel Schaefer Date: Fri, 20 Nov 2026 12:20:17 +0800 Subject: [PATCH 14/31] fuzz_driver: Allow fuzz targets to install a command handler The tape can't model stateful behavior, like flash contents that are read back after writing. Let a fuzz target handle host commands itself, falling back to the tape if it returns None. Cleared by set_input(). Co-Authored-By: Claude Opus 5.5 --- framework_lib/src/chromium_ec/fuzz_driver.rs | 23 +++++++++++++++++++- 1 file changed, 22 insertions(+), 1 deletion(-) diff --git a/framework_lib/src/chromium_ec/fuzz_driver.rs b/framework_lib/src/chromium_ec/fuzz_driver.rs index 37836558..efc4cfeb 100644 --- a/framework_lib/src/chromium_ec/fuzz_driver.rs +++ b/framework_lib/src/chromium_ec/fuzz_driver.rs @@ -6,6 +6,8 @@ //! like they would on real hardware. //! - Host command responses are taken sequentially from a tape. Once the tape runs //! out, every command fails, so retry/polling loops terminate. +//! - Optionally a fuzz target can install a command handler, to model stateful +//! behavior (like flash contents) that a tape can't express. use std::cell::{Cell, RefCell}; @@ -22,8 +24,13 @@ struct State { pos: usize, } +/// Handles a host command `(command, command_version, request)` instead of the tape. +/// Returning `None` falls through to the tape. +pub type CommandHandler = Box Option>>>; + thread_local! { static STATE: RefCell = RefCell::new(State::default()); + static HANDLER: RefCell> = const { RefCell::new(None) }; /// Size of the struct that the caller (`send_command_extra`) expects as response. /// The driver can't otherwise know it and would almost always fail that size check. static EXPECTED_SIZE: Cell> = const { Cell::new(None) }; @@ -39,6 +46,12 @@ pub fn set_input(memmap: &[u8], tape: &[u8]) { s.pos = 0; }); EXPECTED_SIZE.with(|e| e.set(None)); + HANDLER.with(|h| *h.borrow_mut() = None); +} + +/// Install a command handler, see [`CommandHandler`]. Cleared by [`set_input`]. +pub fn set_command_handler(handler: CommandHandler) { + HANDLER.with(|h| *h.borrow_mut() = Some(handler)); } pub(crate) fn set_expected_size(size: Option) { @@ -57,8 +70,16 @@ pub(crate) fn read_memory(offset: u16, length: u16) -> EcResult> { }) } -pub(crate) fn send_command(_command: u16, _command_version: u8, _data: &[u8]) -> EcResult> { +pub(crate) fn send_command(command: u16, command_version: u8, data: &[u8]) -> EcResult> { let expected = EXPECTED_SIZE.with(|e| e.take()); + let handled = HANDLER.with(|h| { + h.borrow_mut() + .as_mut() + .and_then(|handler| handler(command, command_version, data)) + }); + if let Some(res) = handled { + return res; + } STATE.with(|s| { let mut s = s.borrow_mut(); let Some(&ctrl) = s.tape.get(s.pos) else { From d1cbfe2dfc1f253211d5702425bb34b7ef8bcc22 Mon Sep 17 00:00:00 2001 From: Daniel Schaefer Date: Fri, 20 Nov 2026 12:20:26 +0800 Subject: [PATCH 15/31] fuzz: Add EC reflash target Runs CrosEc::reflash against a model of the EC flash. The fuzzer input selects flash type, platforms, version struct placement, file length, the reported flash info and injected faults; the target builds a matching firmware file. It checks invariants on the commands sent to the EC, not just for panics: flash is only erased/written inside the reported flash size and selected regions, only with the file contents and after erasing, never in dry-run mode or with an invalid file, only between FirmwareStart and FirmwareDone, the flash is always locked again, and on success the flash contains the file. It immediately finds that full flashing doesn't check the flash size the EC reports and that erase_ec_flash() can overflow; fixed in the next commits. Co-Authored-By: Claude Opus 5.5 --- fuzz/Cargo.toml | 7 + fuzz/README.md | 20 ++ fuzz/fuzz_targets/ec_reflash.rs | 518 ++++++++++++++++++++++++++++++++ 3 files changed, 545 insertions(+) create mode 100644 fuzz/fuzz_targets/ec_reflash.rs diff --git a/fuzz/Cargo.toml b/fuzz/Cargo.toml index 635bbdb3..9876e543 100644 --- a/fuzz/Cargo.toml +++ b/fuzz/Cargo.toml @@ -64,3 +64,10 @@ path = "fuzz_targets/h2o_capsule.rs" test = false doc = false bench = false + +[[bin]] +name = "ec_reflash" +path = "fuzz_targets/ec_reflash.rs" +test = false +doc = false +bench = false diff --git a/fuzz/README.md b/fuzz/README.md index c7376a04..f263a61f 100644 --- a/fuzz/README.md +++ b/fuzz/README.md @@ -61,3 +61,23 @@ cargo +nightly fuzz run capsule -- -close_fd_mask=1 -max_len=1048576 python3 seed_h2o_capsule.py cargo +nightly fuzz run h2o_capsule -- -close_fd_mask=1 -max_len=1048576 ``` + +## EC flashing + +`ec_reflash` runs `CrosEc::reflash` (`--flash-ec` and friends) against a model of +the EC flash, installed with `fuzz_driver::set_command_handler`. The fuzzer input +doesn't contain the firmware file, it selects the flash type, platforms, placement of +the version structs, file length, what EC_CMD_FLASH_INFO reports and which commands +fail. The target builds a matching file from that. + +Besides crashes, it checks that flashing stays inside the reported flash size and +the selected regions, writes the file contents only to erased flash, doesn't touch +flash with an invalid file or in dry-run mode, always locks the flash again after +FirmwareStart, and leaves the file contents in flash when it reports success. +See the comment at the top of `fuzz_targets/ec_reflash.rs`. + +No seed corpus is needed, inputs are small: + +```sh +cargo +nightly fuzz run ec_reflash -- -close_fd_mask=1 -timeout=10 +``` diff --git a/fuzz/fuzz_targets/ec_reflash.rs b/fuzz/fuzz_targets/ec_reflash.rs new file mode 100644 index 00000000..2ba3cd89 --- /dev/null +++ b/fuzz/fuzz_targets/ec_reflash.rs @@ -0,0 +1,518 @@ +//! Fuzz EC firmware flashing (--flash-ec, --flash-ro-ec, --flash-rw-ec, --flash-full-ec) +//! +//! Unlike the other targets, the EC firmware file is not taken from the fuzzer input +//! directly. The interesting parts (version structs at fixed offsets ~256K into a +//! 512K file) would practically never be found. Instead the fuzzer input selects +//! the flash type, platforms, version struct placement, file length, what the EC +//! reports and where faults are injected. The harness builds a matching file and +//! runs `CrosEc::reflash` against a model of the EC flash. +//! +//! Besides crashes and hangs, it checks that reflashing: +//! - never erases or writes outside the flash size reported by the EC +//! - only erases and writes the regions of the selected flash type +//! - only writes erased flash, with the data from the file at the same offset +//! - doesn't touch flash at all, if the file is invalid, too short or for another platform +//! - doesn't touch flash at all in dry-run mode +//! - only touches flash between FirmwareStart and FirmwareDone +//! - always sends AccessSpiDone and FirmwareDone after FirmwareStart, even on errors +//! - leaves the file contents in flash, if it reports success +#![no_main] + +use std::cell::RefCell; +use std::rc::Rc; +use std::sync::LazyLock; + +use framework_lib::chromium_ec::command::EcCommands; +use framework_lib::chromium_ec::{fuzz_driver, EcError, EcFlashType, EcResponseStatus, EcResult}; +use libfuzzer_sys::fuzz_target; + +const FLASH_SIZE: usize = 0x80000; +const RW_BASE: usize = 0x40000; +const MEC_RO_SIZE: usize = 0x3A000; +const NPC_RO_SIZE: usize = 0x3F000; +const RW_SIZE: usize = 0x3F000; + +// Offsets of the version struct (struct image_data) in the EC binary +const RO_VER_LEGACY: usize = 0x2430; +const RW_VER_LEGACY: usize = 0x402f0; +const RO_VER_ZEPHYR: usize = 0x00180; +const RW_VER_ZEPHYR: usize = 0x40140; +const IMAGE_DATA_LEN: usize = 48; + +// MecFlashNotify +const ACCESS_SPI: u8 = 0x00; +const FIRMWARE_START: u8 = 0x01; +const FIRMWARE_DONE: u8 = 0x02; +const ACCESS_SPI_DONE: u8 = 0x03; + +/// Legacy MEC EC platforms first, then NPC/Zephyr +const PLATFORMS: &[&str] = &["hx20", "hx30", "azalea", "lotus", "marigold"]; + +/// Reads fuzzer input, returns 0 once it runs out +struct Input<'a>(&'a [u8]); +impl Input<'_> { + fn u8(&mut self) -> u8 { + let Some((&b, rest)) = self.0.split_first() else { + return 0; + }; + self.0 = rest; + b + } + fn u32(&mut self) -> u32 { + u32::from_le_bytes([self.u8(), self.u8(), self.u8(), self.u8()]) + } + /// Pick from interesting values most of the time, otherwise an arbitrary one + fn pick(&mut self, interesting: &[u32]) -> u32 { + let sel = self.u8() as usize; + match interesting.get(sel) { + Some(&v) => v, + None if sel < 0xC0 => interesting[sel % interesting.len()], + None => self.u32(), + } + } +} + +#[derive(Clone, Copy)] +enum VersionPlacement { + None, + Legacy, + Zephyr, +} + +/// Fields are only read for Debug output of failures +#[allow(dead_code)] +#[derive(Debug)] +enum Op { + Notify(u8), + Erase(usize, usize), + Write(usize, usize), + Read(usize, usize), + Other(u16), +} + +#[derive(Clone, Copy)] +enum Fault { + Error, + ShortReply, + LongReply, + Corrupt, +} + +struct Model { + flash: Vec, + /// Bytes erased and not written since + erased: Vec, + image: Rc>, + build_info: Vec, + flash_info: [u32; 6], + faults: Vec<(usize, Fault)>, + cmd_no: usize, + log: Vec, + violations: Vec, +} + +/// Physically larger than the default flash size, to notice anything beyond the reported size +const PHYS_SIZE: usize = 0x100000; +/// Different from the image pattern, so a skipped write is noticed +static INITIAL_FLASH: LazyLock> = + LazyLock::new(|| (0..PHYS_SIZE).map(|i| !image_pattern(i)).collect()); + +/// Position dependent, so a write to the wrong offset is noticed +fn image_pattern(i: usize) -> u8 { + (i as u8) ^ ((i >> 8) as u8).rotate_left(3) ^ ((i >> 16) as u8).rotate_left(5) +} + +fn le_u32(data: &[u8], offset: usize) -> Option { + Some(u32::from_le_bytes(data.get(offset..offset + 4)?.try_into().ok()?) as usize) +} + +impl Model { + fn reported_size(&self) -> usize { + (self.flash_info[0] as usize).min(self.flash.len()) + } + + /// Check range against reported flash size, the EC would reject it + fn check_range(&mut self, what: &str, offset: usize, size: usize) -> EcResult<()> { + let end = offset.checked_add(size); + if end.is_none_or(|end| end > self.reported_size()) { + self.violations.push(format!( + "{} 0x{:X}+0x{:X} beyond reported flash size 0x{:X}", + what, offset, size, self.flash_info[0] + )); + return Err(EcError::Response(EcResponseStatus::InvalidParameter)); + } + Ok(()) + } + + fn handle(&mut self, command: u16, data: &[u8]) -> EcResult> { + let fault = self + .faults + .iter() + .find(|(n, _)| *n == self.cmd_no) + .map(|(_, f)| *f); + self.cmd_no += 1; + // Log even if it fails, the command was sent and the EC might have acted on it + self.log.push(log_op(command, data)); + if let Some(Fault::Error) = fault { + return Err(EcError::Response(EcResponseStatus::Error)); + } + + let mut resp = self.execute(command, data)?; + match fault { + Some(Fault::ShortReply) => { + resp.pop(); + } + Some(Fault::LongReply) => resp.extend_from_slice(&[0xAA; 16]), + Some(Fault::Corrupt) => { + if let Some(b) = resp.first_mut() { + *b ^= 0x01; + } + } + _ => {} + } + Ok(resp) + } + + fn execute(&mut self, command: u16, data: &[u8]) -> EcResult> { + let invalid = EcError::Response(EcResponseStatus::InvalidParameter); + match command { + c if c == EcCommands::GetBuildInfo as u16 => Ok(self.build_info.clone()), + c if c == EcCommands::FlashInfo as u16 => Ok(self + .flash_info + .iter() + .flat_map(|x| x.to_le_bytes()) + .collect()), + c if c == EcCommands::FlashNotified as u16 => { + data.first().ok_or(invalid)?; + Ok(vec![]) + } + c if c == EcCommands::FlashErase as u16 => { + let (offset, size) = (le_u32(data, 0).unwrap(), le_u32(data, 4).unwrap()); + self.check_range("Erase", offset, size)?; + self.flash[offset..offset + size].fill(0xFF); + self.erased[offset..offset + size].fill(true); + Ok(vec![]) + } + c if c == EcCommands::FlashWrite as u16 => { + let (offset, size) = (le_u32(data, 0).unwrap(), le_u32(data, 4).unwrap()); + let payload = &data[8..]; + if payload.len() != size { + self.violations.push(format!( + "Write 0x{:X} claims 0x{:X} bytes, sends 0x{:X}", + offset, + size, + payload.len() + )); + return Err(invalid); + } + self.check_range("Write", offset, size)?; + if self.image.get(offset..offset + size) != Some(payload) { + self.violations.push(format!( + "Write 0x{:X}+0x{:X} doesn't match file", + offset, size + )); + } + if !self.erased[offset..offset + size].iter().all(|x| *x) { + self.violations.push(format!( + "Write 0x{:X}+0x{:X} to unerased flash", + offset, size + )); + } + self.flash[offset..offset + size].copy_from_slice(payload); + self.erased[offset..offset + size].fill(false); + Ok(vec![]) + } + c if c == EcCommands::FlashRead as u16 => { + let (offset, size) = (le_u32(data, 0).unwrap(), le_u32(data, 4).unwrap()); + self.check_range("Read", offset, size)?; + Ok(self.flash[offset..offset + size].to_vec()) + } + _ => Err(EcError::Response(EcResponseStatus::InvalidCommand)), + } + } +} + +fn log_op(command: u16, data: &[u8]) -> Op { + let range = || (le_u32(data, 0).unwrap(), le_u32(data, 4).unwrap()); + match command { + c if c == EcCommands::FlashNotified as u16 => match data.first() { + Some(&flags) => Op::Notify(flags), + None => Op::Other(c), + }, + c if c == EcCommands::FlashErase as u16 => { + let (offset, size) = range(); + Op::Erase(offset, size) + } + c if c == EcCommands::FlashWrite as u16 => { + let (offset, size) = range(); + Op::Write(offset, size) + } + c if c == EcCommands::FlashRead as u16 => { + let (offset, size) = range(); + Op::Read(offset, size) + } + c => Op::Other(c), + } +} + +fn plant_version(image: &mut [u8], offset: usize, version: &str) { + let Some(dst) = image.get_mut(offset..offset + IMAGE_DATA_LEN) else { + return; + }; + let mut v = [0u8; 32]; + v[..version.len()].copy_from_slice(version.as_bytes()); + dst[0..4].copy_from_slice(&0xce778899u32.to_le_bytes()); + dst[4..36].copy_from_slice(&v); + dst[36..40].copy_from_slice(&0x40000u32.to_le_bytes()); + dst[40..44].copy_from_slice(&0u32.to_le_bytes()); + dst[44..48].copy_from_slice(&0xceaabbddu32.to_le_bytes()); +} + +fn version_str(platform: &str) -> String { + format!("{}_v0.0.1-7a61a89", platform) +} + +fn ranges_overlap_outside(op: (usize, usize), allowed: &[(usize, usize)]) -> bool { + let (start, size) = op; + let end = start + size; + !allowed.iter().any(|&(a, len)| start >= a && end <= a + len) +} + +fuzz_target!(|data: &[u8]| { + let mut input = Input(data); + + let cfg = input.u8(); + // EcFlashType isn't Copy + let ft = || match cfg & 0x3 { + 0 => EcFlashType::Full, + 1 => EcFlashType::Both, + 2 => EcFlashType::Ro, + _ => EcFlashType::Rw, + }; + let dry_run = cfg & 0x4 != 0; + + let running = PLATFORMS[input.u8() as usize % PLATFORMS.len()]; + let file_platform = |input: &mut Input| { + let b = input.u8(); + if b < 0xC0 { + running + } else { + PLATFORMS[b as usize % PLATFORMS.len()] + } + }; + let ro_platform = file_platform(&mut input); + let rw_platform = file_platform(&mut input); + let placement = |b: u8| match b % 4 { + 0 => VersionPlacement::None, + 1 | 2 => VersionPlacement::Zephyr, + _ => VersionPlacement::Legacy, + }; + let b = input.u8(); + let (ro_place, rw_place) = (placement(b), placement(b >> 4)); + + let file_len = input.pick(&[ + FLASH_SIZE as u32, + FLASH_SIZE as u32 + 0x100, + (RW_BASE + RW_SIZE) as u32, + (RW_BASE + RW_SIZE - 1) as u32, + RW_BASE as u32, + NPC_RO_SIZE as u32, + MEC_RO_SIZE as u32, + (RW_VER_ZEPHYR + IMAGE_DATA_LEN) as u32, + (RW_VER_LEGACY + IMAGE_DATA_LEN) as u32, + ]) as usize + % (FLASH_SIZE + 0x101); + let flash_size = input.pick(&[ + FLASH_SIZE as u32, + (RW_BASE + RW_SIZE) as u32, + (RW_BASE + RW_SIZE - 1) as u32, + 0x100000, + 0, + ]); + let erase_block_size = input.pick(&[0x1000, 0x10000, 0x80, 0, 0x7F000, 0xFFFF_F000, 3]); + let write_block_size = input.u32(); + let protect_block_size = input.u32(); + let write_ideal_size = input.u32(); + let flags = input.u32(); + + // Up to two faults, at a command number and of a kind + let mut faults = vec![]; + for _ in 0..2 { + let kind = input.u8(); + let at = u16::from_le_bytes([input.u8(), input.u8()]) as usize; + let kind = match kind % 8 { + 0 => Fault::Error, + 1 => Fault::ShortReply, + 2 => Fault::LongReply, + 3 => Fault::Corrupt, + _ => continue, + }; + faults.push((at, kind)); + } + + let mut image: Vec = (0..file_len).map(image_pattern).collect(); + match ro_place { + VersionPlacement::None => {} + VersionPlacement::Legacy => { + plant_version(&mut image, RO_VER_LEGACY, &version_str(ro_platform)) + } + VersionPlacement::Zephyr => { + plant_version(&mut image, RO_VER_ZEPHYR, &version_str(ro_platform)) + } + } + match rw_place { + VersionPlacement::None => {} + VersionPlacement::Legacy => { + plant_version(&mut image, RW_VER_LEGACY, &version_str(rw_platform)) + } + VersionPlacement::Zephyr => { + plant_version(&mut image, RW_VER_ZEPHYR, &version_str(rw_platform)) + } + } + let image = Rc::new(image); + + let mut build_info = version_str(running).into_bytes(); + build_info.push(0); + + let model = Rc::new(RefCell::new(Model { + flash: INITIAL_FLASH.clone(), + erased: vec![false; PHYS_SIZE], + image: image.clone(), + build_info, + flash_info: [ + flash_size, + write_block_size, + erase_block_size, + protect_block_size, + write_ideal_size, + flags, + ], + faults, + cmd_no: 0, + log: vec![], + violations: vec![], + })); + + // Pick any Framework platform to pass the SMBIOS check, reflash doesn't care which. + // Empty memory map and tape, the command handler answers everything. + let ec = fuzz_driver::setup(&[0]).unwrap(); + let handler_model = model.clone(); + fuzz_driver::set_command_handler(Box::new(move |command, _version, data| { + Some(handler_model.borrow_mut().handle(command, data)) + })); + + let res = ec.reflash(&image, ft(), dry_run); + + let model = model.borrow(); + assert!( + model.violations.is_empty(), + "Violations: {:#?}", + model.violations + ); + + // Which regions are allowed to be touched and whether the file is good to flash at all + let has_mec = matches!(running, "hx20" | "hx30"); + let ro_size = if has_mec { MEC_RO_SIZE } else { NPC_RO_SIZE }; + let (needs_ro, needs_rw) = match ft() { + EcFlashType::Full | EcFlashType::Both => (true, true), + EcFlashType::Ro => (true, false), + EcFlashType::Rw => (false, true), + }; + let allowed: Vec<(usize, usize)> = match ft() { + EcFlashType::Full => vec![(0, FLASH_SIZE)], + EcFlashType::Both => vec![(0, ro_size), (RW_BASE, RW_SIZE)], + EcFlashType::Ro => vec![(0, ro_size)], + EcFlashType::Rw => vec![(RW_BASE, RW_SIZE)], + }; + let required_len = match ft() { + EcFlashType::Full => FLASH_SIZE, + EcFlashType::Both | EcFlashType::Rw => RW_BASE + RW_SIZE, + EcFlashType::Ro => ro_size, + }; + let version_ok = |place: VersionPlacement, platform: &str, legacy: usize, zephyr: usize| { + let offset = match place { + VersionPlacement::None => return false, + VersionPlacement::Legacy => legacy, + VersionPlacement::Zephyr => zephyr, + }; + platform == running && offset + IMAGE_DATA_LEN <= file_len + }; + let file_ok = file_len >= required_len + && (!needs_ro || version_ok(ro_place, ro_platform, RO_VER_LEGACY, RO_VER_ZEPHYR)) + && (!needs_rw || version_ok(rw_place, rw_platform, RW_VER_LEGACY, RW_VER_ZEPHYR)); + + let mut started = false; + let mut spi_done_after_start = false; + let mut done_after_start = false; + let mut modified = false; + for op in &model.log { + match *op { + Op::Notify(flags) => match flags { + FIRMWARE_START => { + started = true; + spi_done_after_start = false; + done_after_start = false; + } + FIRMWARE_DONE if started => done_after_start = true, + ACCESS_SPI_DONE if started => spi_done_after_start = true, + ACCESS_SPI | FIRMWARE_DONE | ACCESS_SPI_DONE => {} + other => panic!("Unexpected flash notify flags 0x{:X}", other), + }, + Op::Erase(offset, size) | Op::Write(offset, size) => { + modified = true; + assert!(!dry_run, "Flash modified in dry run: {:?}", op); + assert!(file_ok, "Flash modified with invalid file: {:?}", op); + assert!( + started && !done_after_start, + "Flash modified outside of FirmwareStart/Done: {:?}", + op + ); + assert!( + !ranges_overlap_outside((offset, size), &allowed), + "{:?} outside of allowed regions {:X?}", + op, + allowed + ); + } + Op::Read(..) | Op::Other(_) => {} + } + } + if started { + assert!( + spi_done_after_start && done_after_start, + "Flash not locked again after FirmwareStart, result: {:?}, log: {:?}", + res, + model + .log + .iter() + .filter(|op| matches!(op, Op::Notify(_))) + .collect::>() + ); + } + + if res.is_ok() { + assert!(file_ok, "Reflash succeeded with invalid file"); + } + if res.is_ok() && !dry_run { + assert!(modified); + for (start, len) in &allowed { + assert!( + model.flash[*start..start + len] == image[*start..start + len], + "Reported success, but flash 0x{:X}+0x{:X} doesn't match file", + start, + len + ); + } + } + // Nothing outside the allowed regions changed + let mut gap_start = 0; + for &(start, len) in allowed.iter().chain(&[(PHYS_SIZE, 0)]) { + assert!( + model.flash[gap_start..start] == INITIAL_FLASH[gap_start..start], + "Flash changed outside of allowed regions, between 0x{:X} and 0x{:X}", + gap_start, + start + ); + gap_start = start + len; + } +}); From d1907e9e05161cfe20b2ed4df2afc2a1dc5e4641 Mon Sep 17 00:00:00 2001 From: Daniel Schaefer Date: Fri, 20 Nov 2026 12:21:32 +0800 Subject: [PATCH 16/31] chromium_ec: Check full EC flash against the reported flash size reflash() only checked that RO+RW fit into the flash size reported by EC_CMD_FLASH_INFO. Full flashing erases and writes 0x80000 bytes, which is more than RO+RW, so with a reported size between 0x7F000 and 0x80000 it went past the end. Found by the ec_reflash fuzz target. Co-Authored-By: Claude Opus 5.5 --- framework_lib/src/chromium_ec/mod.rs | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/framework_lib/src/chromium_ec/mod.rs b/framework_lib/src/chromium_ec/mod.rs index 2eaa37a8..2c019cad 100644 --- a/framework_lib/src/chromium_ec/mod.rs +++ b/framework_lib/src/chromium_ec/mod.rs @@ -975,6 +975,12 @@ impl CrosEc { { info.flash_size } ))); } + if ft == EcFlashType::Full && FLASH_BASE + FLASH_SIZE > info.flash_size { + return Err(EcError::DeviceError(format!( + "Full image overruns end of flash 0x{:X}", + { info.flash_size } + ))); + } println!("Unlocking flash"); self.flash_notify(MecFlashNotify::AccessSpi)?; From a366290398fc3d05736ac675d3701aa8a4be8c33 Mon Sep 17 00:00:00 2001 From: Daniel Schaefer Date: Fri, 20 Nov 2026 12:22:13 +0800 Subject: [PATCH 17/31] chromium_ec: Don't overflow when erasing EC flash with huge block size erase_ec_flash() advanced by the erase block size reported by the EC, even for the last, smaller chunk. With a huge block size that overflowed, panicking with overflow checks, or wrapping around and erasing again below the start of the region otherwise. Advance by the size actually erased. Found by the ec_reflash fuzz target. Co-Authored-By: Claude Opus 5.5 --- framework_lib/src/chromium_ec/mod.rs | 13 +++++-------- 1 file changed, 5 insertions(+), 8 deletions(-) diff --git a/framework_lib/src/chromium_ec/mod.rs b/framework_lib/src/chromium_ec/mod.rs index 2c019cad..851328d5 100644 --- a/framework_lib/src/chromium_ec/mod.rs +++ b/framework_lib/src/chromium_ec/mod.rs @@ -1196,15 +1196,11 @@ impl CrosEc { "EC reported an erase block size of 0".to_string(), )); } + let end = offset + size; let mut cur_offset = offset; - while cur_offset < offset + size { - let rem_size = offset + size - cur_offset; - let cur_size = if rem_size < chunk_size { - rem_size - } else { - chunk_size - }; + while cur_offset < end { + let cur_size = core::cmp::min(end - cur_offset, chunk_size); debug!( "EcRequestFlashErase (0x{:05X}, 0x{:05X})", cur_offset, cur_size @@ -1216,7 +1212,8 @@ impl CrosEc { } .send_command(self)?; } - cur_offset += chunk_size; + // Not chunk_size, that can overflow if it's huge + cur_offset += cur_size; } Ok(()) } From 0a151fc4d9cc9e727a03a6efcea19564cd1e1997 Mon Sep 17 00:00:00 2001 From: Daniel Schaefer Date: Fri, 20 Nov 2026 12:37:28 +0800 Subject: [PATCH 18/31] fuzz: Add STM32 keyboard HEX file target Parses Intel HEX firmware files like --flash-stm32-kbd does, finds the version, and runs the write planning through a cfg(fuzzing) shim, which checks that the planned ranges cover the image exactly and stay within their pages. Includes a small seed file. Co-Authored-By: Claude Opus 5.5 --- framework_lib/src/stm32_kbd/flash.rs | 26 ++++++++++++++++++++++++++ fuzz/Cargo.toml | 7 +++++++ fuzz/README.md | 10 ++++++++++ fuzz/fuzz_targets/stm32_hex.rs | 22 ++++++++++++++++++++++ fuzz/seeds/stm32_hex.hex | 9 +++++++++ 5 files changed, 74 insertions(+) create mode 100644 fuzz/fuzz_targets/stm32_hex.rs create mode 100644 fuzz/seeds/stm32_hex.hex diff --git a/framework_lib/src/stm32_kbd/flash.rs b/framework_lib/src/stm32_kbd/flash.rs index b47c7a52..1f1f5c7d 100644 --- a/framework_lib/src/stm32_kbd/flash.rs +++ b/framework_lib/src/stm32_kbd/flash.rs @@ -286,6 +286,32 @@ impl<'a> Plan<'a> { } } +/// Run write planning without a keyboard, for fuzzing. Panics if the plan doesn't +/// cover the image exactly, with every range inside its page. +#[cfg(fuzzing)] +pub fn fuzz_plan(img: &HexImage, protect: bool) { + let plan = Plan::new(img, protect); + let mut image_bytes = 0; + let mut slot_ranges = 0; + for page in plan.first_page..=plan.last_page { + let lo = FLASH_BASE + page * PAGE_SIZE; + for r in plan.page_ranges(page) { + assert!(r.addr >= lo && r.addr + r.bytes.len() as u32 <= lo + PAGE_SIZE); + if r.is_slot { + slot_ranges += 1; + } else { + assert_eq!( + r.bytes, + &img.bytes[(r.addr - img.base) as usize..][..r.bytes.len()] + ); + image_bytes += r.bytes.len(); + } + } + } + assert_eq!(image_bytes, img.bytes.len()); + assert_eq!(slot_ranges, if protect { 1 } else { 0 }); +} + enum ChunkState { /// Holds the data Matches, diff --git a/fuzz/Cargo.toml b/fuzz/Cargo.toml index 9876e543..e96a01a6 100644 --- a/fuzz/Cargo.toml +++ b/fuzz/Cargo.toml @@ -71,3 +71,10 @@ path = "fuzz_targets/ec_reflash.rs" test = false doc = false bench = false + +[[bin]] +name = "stm32_hex" +path = "fuzz_targets/stm32_hex.rs" +test = false +doc = false +bench = false diff --git a/fuzz/README.md b/fuzz/README.md index f263a61f..c5db9fc8 100644 --- a/fuzz/README.md +++ b/fuzz/README.md @@ -81,3 +81,13 @@ No seed corpus is needed, inputs are small: ```sh cargo +nightly fuzz run ec_reflash -- -close_fd_mask=1 -timeout=10 ``` + +## STM32 keyboard firmware + +`stm32_hex` parses Intel HEX files (`--flash-stm32-kbd`) and plans the flash writes +for them, checking that the plan covers the image exactly. + +```sh +mkdir -p corpus/stm32_hex && cp seeds/stm32_hex.hex corpus/stm32_hex/ +cargo +nightly fuzz run stm32_hex -- -close_fd_mask=1 -max_len=8192 +``` diff --git a/fuzz/fuzz_targets/stm32_hex.rs b/fuzz/fuzz_targets/stm32_hex.rs new file mode 100644 index 00000000..ec597376 --- /dev/null +++ b/fuzz/fuzz_targets/stm32_hex.rs @@ -0,0 +1,22 @@ +//! Fuzz parsing of STM32 keyboard firmware HEX files (--flash-stm32-kbd) +//! and planning the flash writes for them +#![no_main] + +use framework_lib::stm32_kbd; +use libfuzzer_sys::fuzz_target; + +fuzz_target!(|data: &[u8]| { + let Ok(text) = std::str::from_utf8(data) else { + return; + }; + let Ok(img) = stm32_kbd::HexImage::parse(text) else { + return; + }; + let _ = img.end(); + if let Some(version) = img.find_version() { + let _ = stm32_kbd::format_version(version); + } + for protect in [false, true] { + stm32_kbd::fuzz_plan(&img, protect); + } +}); diff --git a/fuzz/seeds/stm32_hex.hex b/fuzz/seeds/stm32_hex.hex new file mode 100644 index 00000000..661fe860 --- /dev/null +++ b/fuzz/seeds/stm32_hex.hex @@ -0,0 +1,9 @@ +:020000040800F2 +:10010000000102030405060708090A0B0C0D0E0F77 +:10011000000102030405060708090A0B0C0D0E0F67 +:10012000000102030405060708090A0B0C0D0E0F57 +:10013000000102030405060708090A0B0C0D0E0F47 +:100140000100AC3238003412200020008000000092 +:100FF80000000000000000000000000000000000E9 +:0400000508000100EE +:00000001FF From ae830a25b126ddeb7604bf86c0ca5110ec2986c7 Mon Sep 17 00:00:00 2001 From: Daniel Schaefer Date: Wed, 25 Nov 2026 22:21:05 +0800 Subject: [PATCH 19/31] fuzz: Add GPU EEPROM target Reads and writes the Framework 16 expansion bay EEPROM through the library functions behind --flash-gpu-descriptor-file, --dump/--validate-gpu-descriptor-file, --expansion-bay and --flash-gpu-descriptor, against a model of the EEPROM behind EC_CMD_I2C_PASSTHRU. The model decodes the passthrough requests itself and has page-wrapping writes, a switchable expansion bay power GPIO on the dual interposer and injected faults. Checks that writes carry the file data at the offset they're written to, don't cross pages, don't happen in dry run, that forced power is turned off again, and that successful reads and writes return or leave the right data. Co-Authored-By: Claude Opus 5.5 --- fuzz/Cargo.toml | 7 + fuzz/README.md | 18 ++ fuzz/fuzz_targets/gpu_eeprom.rs | 513 ++++++++++++++++++++++++++++++++ 3 files changed, 538 insertions(+) create mode 100644 fuzz/fuzz_targets/gpu_eeprom.rs diff --git a/fuzz/Cargo.toml b/fuzz/Cargo.toml index e96a01a6..960cdd84 100644 --- a/fuzz/Cargo.toml +++ b/fuzz/Cargo.toml @@ -78,3 +78,10 @@ path = "fuzz_targets/stm32_hex.rs" test = false doc = false bench = false + +[[bin]] +name = "gpu_eeprom" +path = "fuzz_targets/gpu_eeprom.rs" +test = false +doc = false +bench = false diff --git a/fuzz/README.md b/fuzz/README.md index c5db9fc8..52ce2dd9 100644 --- a/fuzz/README.md +++ b/fuzz/README.md @@ -82,6 +82,24 @@ No seed corpus is needed, inputs are small: cargo +nightly fuzz run ec_reflash -- -close_fd_mask=1 -timeout=10 ``` +## GPU EEPROM + +`gpu_eeprom` reads and writes the Framework 16 expansion bay EEPROM +(`--flash-gpu-descriptor-file`, `--dump-gpu-descriptor-file`, +`--validate-gpu-descriptor-file`, `--expansion-bay`, `--flash-gpu-descriptor`) against +a model of the EEPROM behind EC_CMD_I2C_PASSTHRU. Like `ec_reflash`, the input selects +the operation, EEPROM size, descriptor header fields, file length, expansion bay board, +power state and faults, and the target builds the EEPROM image and file from that. + +Besides crashes, it checks that writes carry the file data at the right offset, don't +cross EEPROM pages, don't happen in dry-run mode, that expansion bay power is turned +off again if it was forced on, and that successful reads and writes leave or return +the right data. See the comment at the top of `fuzz_targets/gpu_eeprom.rs`. + +```sh +cargo +nightly fuzz run gpu_eeprom -- -close_fd_mask=1 -timeout=10 +``` + ## STM32 keyboard firmware `stm32_hex` parses Intel HEX files (`--flash-stm32-kbd`) and plans the flash writes diff --git a/fuzz/fuzz_targets/gpu_eeprom.rs b/fuzz/fuzz_targets/gpu_eeprom.rs new file mode 100644 index 00000000..8d834df5 --- /dev/null +++ b/fuzz/fuzz_targets/gpu_eeprom.rs @@ -0,0 +1,513 @@ +//! Fuzz reading and writing the Framework 16 expansion bay (GPU) EEPROM +//! (--flash-gpu-descriptor-file, --dump-gpu-descriptor-file, --validate-gpu-descriptor-file, +//! --expansion-bay, --flash-gpu-descriptor) +//! +//! The EEPROM is behind the EC, accessed with EC_CMD_I2C_PASSTHRU. Like `ec_reflash`, +//! the fuzzer input doesn't contain the EEPROM image or file directly. It selects +//! the operation, the EEPROM size, the descriptor header fields, file length, the +//! expansion bay board, power state and where faults are injected. The harness +//! builds a matching EEPROM image and file and runs the operation against a model +//! of the EEPROM. +//! +//! The model decodes the I2C passthrough requests itself, so the bytes on the wire +//! are checked, not just the round-trip through the library's helpers. +//! +//! Besides crashes and hangs, it checks that: +//! - a dry run doesn't write to the EEPROM or change GPIOs +//! - every write carries the data from the file at the offset it's written to +//! - no write crosses an EEPROM page boundary (it would wrap around within the page) +//! - expansion bay power is restored, if it was forced on +//! - after a successful write, the EEPROM contains the file +//! - successful reads return what's in the EEPROM, nothing more or less +#![no_main] + +use std::cell::RefCell; +use std::rc::Rc; + +use framework_lib::chromium_ec::command::EcCommands; +use framework_lib::chromium_ec::commands::{ + SetGpuSerialMagic, BOARD_VERSION_11, BOARD_VERSION_12, BOARD_VERSION_13, BOARD_VERSION_15, +}; +use framework_lib::chromium_ec::{fuzz_driver, EcError, EcResponseStatus, EcResult}; +use libfuzzer_sys::fuzz_target; + +const EEPROM_PORT: u8 = 5; +const EEPROM_ADDR: u16 = 0x50; +const PAGE_SIZE: usize = 32; +const HEADER_LEN: usize = 48; +const MAGIC: [u8; 4] = [0x32, 0xAC, 0x00, 0x00]; +const I2C_READ_FLAG: u16 = 1 << 15; +const POWER_GPIO: &str = "gpu_3v_5v_en"; + +/// Reads fuzzer input, returns 0 once it runs out +struct Input<'a>(&'a [u8]); +impl Input<'_> { + fn u8(&mut self) -> u8 { + let Some((&b, rest)) = self.0.split_first() else { + return 0; + }; + self.0 = rest; + b + } + fn u16(&mut self) -> u16 { + u16::from_le_bytes([self.u8(), self.u8()]) + } + fn u32(&mut self) -> u32 { + u32::from_le_bytes([self.u8(), self.u8(), self.u8(), self.u8()]) + } + /// Pick from interesting values most of the time, otherwise an arbitrary one + fn pick(&mut self, interesting: &[u32]) -> u32 { + let sel = self.u8() as usize; + match interesting.get(sel) { + Some(&v) => v, + None if sel < 0xC0 => interesting[sel % interesting.len()], + None => self.u32(), + } + } +} + +#[derive(Clone, Copy, Debug)] +enum Fault { + /// Host command fails, I2C transfer not executed + Error, + /// I2C NAK on the first message, nothing executed + Nak, + /// I2C timeout on the first message, nothing executed + Timeout, + /// Executed, but reply truncated to this many bytes + Truncate(usize), + /// Executed, but garbage appended to the reply + LongReply, + /// Executed, but reply reports a different number of messages + WrongMsgCount, + /// Executed, but read returns fewer bytes with success status + PartialRead, +} + +/// Fields are only read for Debug output of failures +#[allow(dead_code)] +#[derive(Debug)] +enum Op { + Write(usize, usize), + Read(usize, usize), + GpioSet(bool), + Other(u16), +} + +struct Model { + eeprom: Vec, + /// EEPROM only responds when powered (on the dual interposer power is switchable) + powered: bool, + dual_interposer: bool, + bay_status: [u8; 3], + gpu_serial: [u8; 22], + faults: Vec<(usize, Fault)>, + cmd_no: usize, + /// Faults that actually hit an I2C command + hit_faults: Vec, + log: Vec, + violations: Vec, + file: Rc>, + /// EEPROM's current address, set by a write, advanced by reads + addr_ptr: usize, +} + +fn le_u16(data: &[u8], offset: usize) -> Option { + Some(u16::from_le_bytes( + data.get(offset..offset + 2)?.try_into().ok()?, + )) +} + +impl Model { + fn handle(&mut self, command: u16, data: &[u8]) -> EcResult> { + match command { + c if c == EcCommands::I2cPassthrough as u16 => self.i2c(data), + c if c == EcCommands::ExpansionBayStatus as u16 => { + self.log.push(Op::Other(c)); + Ok(self.bay_status.to_vec()) + } + c if c == EcCommands::GpioGet as u16 => { + self.log.push(Op::Other(c)); + if !data.starts_with(POWER_GPIO.as_bytes()) { + return Err(EcError::Response(EcResponseStatus::InvalidParameter)); + } + Ok(vec![self.powered as u8]) + } + c if c == EcCommands::GpioSet as u16 => { + if !data.starts_with(POWER_GPIO.as_bytes()) || data.len() != 33 { + self.log.push(Op::Other(c)); + return Err(EcError::Response(EcResponseStatus::InvalidParameter)); + } + let value = data[32] != 0; + self.log.push(Op::GpioSet(value)); + if self.dual_interposer { + self.powered = value; + } + Ok(vec![]) + } + c if c == EcCommands::GetGpuSerial as u16 => { + self.log.push(Op::Other(c)); + Ok(self.gpu_serial.to_vec()) + } + c if c == EcCommands::ProgramGpuEeprom as u16 => { + self.log.push(Op::Other(c)); + Ok(vec![1]) + } + c => { + self.log.push(Op::Other(c)); + Err(EcError::Response(EcResponseStatus::InvalidCommand)) + } + } + } + + fn i2c(&mut self, data: &[u8]) -> EcResult> { + let invalid = || EcError::Response(EcResponseStatus::InvalidParameter); + let fault = self + .faults + .iter() + .find(|(n, _)| *n == self.cmd_no) + .map(|(_, f)| *f); + self.cmd_no += 1; + if let Some(f) = fault { + self.hit_faults.push(f); + } + + // Decode the request like the EC does + let (&port, rest) = data.split_first().ok_or_else(invalid)?; + let (&count, rest) = rest.split_first().ok_or_else(invalid)?; + let mut msgs = vec![]; + for i in 0..count as usize { + let addr_flags = le_u16(rest, i * 4).ok_or_else(invalid)?; + let len = le_u16(rest, i * 4 + 2).ok_or_else(invalid)? as usize; + msgs.push((addr_flags, len)); + } + let mut write_data = &rest[count as usize * 4..]; + let write_total: usize = msgs + .iter() + .filter(|(f, _)| f & I2C_READ_FLAG == 0) + .map(|(_, l)| l) + .sum(); + if write_total != write_data.len() { + self.violations.push(format!( + "I2C request has {} bytes of write data, messages say {}", + write_data.len(), + write_total + )); + return Err(invalid()); + } + + match fault { + Some(Fault::Error) => return Err(EcError::Response(EcResponseStatus::Error)), + Some(Fault::Nak) => return Ok(vec![1, 0]), + Some(Fault::Timeout) => return Ok(vec![2, 0]), + _ => {} + } + + let mut resp = vec![0u8, 0]; + for (i, &(addr_flags, len)) in msgs.iter().enumerate() { + let addr = addr_flags & !I2C_READ_FLAG; + if port != EEPROM_PORT || addr != EEPROM_ADDR || !self.powered { + // Not acknowledged, EC stops at the first failing message + resp[0] = 1; + resp[1] = i as u8; + return Ok(resp); + } + if addr_flags & I2C_READ_FLAG != 0 { + // Sequential read from the address pointer, wraps at the end of the EEPROM + let ptr = self.addr_ptr; + let mut len = len; + if let Some(Fault::PartialRead) = fault { + len /= 2; + } + self.log.push(Op::Read(ptr, len)); + for j in 0..len { + resp.push(self.eeprom[(ptr + j) % self.eeprom.len()]); + } + self.addr_ptr = (ptr + len) % self.eeprom.len(); + } else { + let (msg, rest) = write_data.split_at(len); + write_data = rest; + if msg.len() < 2 { + self.violations + .push(format!("I2C write of {} bytes, no address", msg.len())); + return Ok(vec![1, i as u8]); + } + // 16-bit address, MSB first + let ptr = u16::from_be_bytes([msg[0], msg[1]]) as usize; + let payload = &msg[2..]; + self.addr_ptr = ptr % self.eeprom.len(); + if !payload.is_empty() { + self.write(ptr, payload); + } + } + resp[1] = i as u8 + 1; + } + + match fault { + Some(Fault::Truncate(n)) => resp.truncate(n), + Some(Fault::LongReply) => resp.extend_from_slice(&[0xAA; 16]), + Some(Fault::WrongMsgCount) => resp[1] = resp[1].wrapping_add(1), + _ => {} + } + Ok(resp) + } + + fn write(&mut self, ptr: usize, payload: &[u8]) { + self.log.push(Op::Write(ptr, payload.len())); + if ptr / PAGE_SIZE != (ptr + payload.len() - 1) / PAGE_SIZE { + self.violations.push(format!( + "Write 0x{:X}+0x{:X} crosses EEPROM page boundary", + ptr, + payload.len() + )); + } + if self.file.get(ptr..ptr + payload.len()) != Some(payload) { + self.violations.push(format!( + "Write 0x{:X}+0x{:X} doesn't match file", + ptr, + payload.len() + )); + } + // Like a real EEPROM, wrap within the page + let page = ptr - ptr % PAGE_SIZE; + for (j, b) in payload.iter().enumerate() { + let a = page + (ptr % PAGE_SIZE + j) % PAGE_SIZE; + let len = self.eeprom.len(); + self.eeprom[a % len] = *b; + } + } +} + +/// Build a descriptor: header with the given fields, then position dependent data +fn descriptor(total_len: usize, length: u32, desc_len: u32, magic_ok: bool) -> Vec { + let mut d: Vec = (0..total_len) + .map(|i| (i as u8) ^ ((i >> 8) as u8).rotate_left(3) ^ 0x5A) + .collect(); + let mut hdr = [0u8; HEADER_LEN]; + hdr[0..4].copy_from_slice(if magic_ok { + &MAGIC + } else { + &[0x32, 0xAC, 0, 1] + }); + hdr[4..8].copy_from_slice(&length.to_le_bytes()); + hdr[36..40].copy_from_slice(&desc_len.to_le_bytes()); + let n = total_len.min(HEADER_LEN); + d[..n].copy_from_slice(&hdr[..n]); + d +} + +fuzz_target!(|data: &[u8]| { + let mut input = Input(data); + + let op = input.u8() % 6; + let dry_run = input.u8() & 1 != 0; + let eeprom_size = [0x1000, 0x2000, 0x8000, 0x10000][input.u8() as usize % 4]; + + let board = input.u8(); + let (b0, b1) = match board % 5 { + 0 => (BOARD_VERSION_12, BOARD_VERSION_12), + 1 => (BOARD_VERSION_13, BOARD_VERSION_15), + 2 => (BOARD_VERSION_11, BOARD_VERSION_15), + 3 => (BOARD_VERSION_15, BOARD_VERSION_15), + _ => (input.u8(), input.u8()), + }; + let dual_interposer = (b0, b1) == (BOARD_VERSION_12, BOARD_VERSION_12); + // Only the dual interposer can switch power, others are always powered + let initially_powered = !dual_interposer || board & 0x80 != 0; + + // Header in the EEPROM + let lengths = [ + HEADER_LEN as u32, + 0, + 1, + 31, + 32, + 33, + 0x100, + 0x1000 - HEADER_LEN as u32, + 0xFFFF - HEADER_LEN as u32, + 0x10000 - HEADER_LEN as u32, + 0x10000, + 0xFFFF_FFFF, + 0x8000_0000, + ]; + let ee_length = input.pick(&lengths); + let ee_desc_len = input.pick(&lengths); + let ee_magic_ok = input.u8() < 0xE0; + let mut eeprom = descriptor(eeprom_size, ee_length, ee_desc_len, ee_magic_ok); + // Distinguish EEPROM from file contents, except for the header + for b in eeprom.iter_mut().skip(HEADER_LEN) { + *b = !*b; + } + + // File to write or validate against + let file_len = input.pick(&[ + 0, + 1, + 4, + 31, + 32, + 33, + HEADER_LEN as u32, + 0x200, + 0x1000, + 0x2000 + 7, + 0xFFFF, + 0x10000, + 0x10000 + 32, + 0x10021, + ]) as usize + % 0x10100; + let file_length = input.pick(&lengths); + let file_desc_len = input.pick(&lengths); + let file = Rc::new(descriptor(file_len, file_length, file_desc_len, true)); + + let mut gpu_serial = [0u8; 22]; + gpu_serial[1] = input.u8() & 1; + for b in gpu_serial[2..].iter_mut() { + *b = input.u8(); + } + + // Up to two faults, at a passthrough command number and of a kind + let mut faults = vec![]; + for _ in 0..2 { + let kind = input.u8(); + let at = input.u16() as usize % 0x900; + let kind = match kind % 10 { + 0 => Fault::Error, + 1 => Fault::Nak, + 2 => Fault::Timeout, + 3 => Fault::Truncate(0), + 4 => Fault::Truncate(1), + 5 => Fault::LongReply, + 6 => Fault::WrongMsgCount, + 7 => Fault::PartialRead, + _ => continue, + }; + faults.push((at, kind)); + } + + let initial_eeprom = eeprom.clone(); + let model = Rc::new(RefCell::new(Model { + eeprom, + powered: initially_powered, + dual_interposer, + bay_status: [0x07, b0, b1], + gpu_serial, + faults, + cmd_no: 0, + hit_faults: vec![], + log: vec![], + violations: vec![], + file: file.clone(), + addr_ptr: 0, + })); + + // Framework 16, the EEPROM is only there + let ec = fuzz_driver::setup(&[9]).unwrap(); + let handler_model = model.clone(); + fuzz_driver::set_command_handler(Box::new(move |command, _version, data| { + Some(handler_model.borrow_mut().handle(command, data)) + })); + + // What a correct read from offset 0 returns: what's in the EEPROM, wrapping around + let expected = |len: usize| -> Vec { + (0..len) + .map(|i| initial_eeprom[i % initial_eeprom.len()]) + .collect() + }; + + match op { + 0 => { + let res = ec.set_gpu_descriptor(&file, dry_run); + let m = model.borrow(); + if dry_run { + assert!( + !m.log + .iter() + .any(|op| matches!(op, Op::Write(..) | Op::GpioSet(_))), + "Dry run modified EEPROM or GPIO: {:?}", + m.log + ); + } + assert_eq!( + m.powered, initially_powered, + "Expansion bay power not restored, result {:?}", + res + ); + if res.is_ok() && !dry_run { + // Can't hold more than it has room for + if file_len <= eeprom_size { + assert!( + m.eeprom[..file_len] == file[..], + "Write reported success, but EEPROM doesn't contain the file" + ); + } else { + // Reporting success here would be wrong, the EEPROM wraps around. + // But the tool doesn't know the EEPROM size, the write offsets + // and verification after writing take care of it. + } + drop(m); + // Like the commandline does after writing + let valid = ec.validate_gpu_descriptor(&file); + let m = model.borrow(); + if file_len > eeprom_size && m.hit_faults.is_empty() { + assert!( + !matches!(valid, Ok(true)), + "File larger than EEPROM validated successfully" + ); + } + } + } + 1 => { + let res = ec.read_gpu_descriptor(); + if let Ok(desc) = res { + let total = ee_length as u64 + ee_desc_len as u64; + assert!(ee_magic_ok, "Read descriptor with invalid magic"); + assert_eq!(desc.len() as u64, total, "Descriptor length wrong"); + assert!(desc == expected(desc.len()), "Descriptor content wrong"); + } + } + 2 => { + if let Ok(hdr) = ec.read_gpu_desc_header() { + assert_eq!({ hdr.length }, ee_length); + assert_eq!({ hdr.descriptor_length }, ee_desc_len); + } + } + 3 => { + let addr = input.u16(); + let len = input.pick(&[256, 48, 1, 0, 128, 129, 0xFFFF]) as u16; + if let Ok(chunk) = ec.read_ec_gpu_chunk(addr, len) { + assert_eq!(chunk.len(), len as usize); + let want: Vec = (0..len as usize) + .map(|i| initial_eeprom[(addr as usize + i) % initial_eeprom.len()]) + .collect(); + assert!(chunk == want, "Read chunk content wrong"); + } + } + 4 => { + let _ = ec.get_gpu_serial(); + let len = input.u8() as usize % 24; + let serial: String = (0..len).map(|_| (b'A' + input.u8() % 26) as char).collect(); + let _ = ec.set_gpu_serial(SetGpuSerialMagic::WriteGPUConfig as u8, serial); + } + _ => { + // Validate against the EEPROM contents, optionally with one byte changed + let len = (ee_length as u64 + ee_desc_len as u64).min(0x10000) as usize; + let mut reference = expected(len); + let flip = input.u16() as usize; + let flipped = input.u8() & 1 != 0 && !reference.is_empty(); + if flipped { + let i = flip % reference.len(); + reference[i] ^= 0x01; + } + if let Ok(valid) = ec.validate_gpu_descriptor(&reference) { + assert!(ee_magic_ok); + assert_eq!(valid, !flipped, "Validation result wrong"); + } + } + } + + let m = model.borrow(); + assert!(m.violations.is_empty(), "Violations: {:#?}", m.violations); +}); From b34f59f38e2b5695eefb789018ca8b9ef5340ce8 Mon Sep 17 00:00:00 2001 From: Daniel Schaefer Date: Wed, 25 Nov 2026 22:22:22 +0800 Subject: [PATCH 20/31] chromium_ec: Don't panic setting a GPU serial that isn't 18 characters set_gpu_serial() copied the serial into an 18 byte slice, which panics for any other length. Clap checks the length, but the UEFI commandline doesn't, so --flash-gpu-descriptor with a wrong serial crashed there. Return an error instead. Found by the gpu_eeprom fuzz target. Co-Authored-By: Claude Opus 5.5 --- framework_lib/src/chromium_ec/mod.rs | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/framework_lib/src/chromium_ec/mod.rs b/framework_lib/src/chromium_ec/mod.rs index 851328d5..bbec0007 100644 --- a/framework_lib/src/chromium_ec/mod.rs +++ b/framework_lib/src/chromium_ec/mod.rs @@ -1493,6 +1493,13 @@ impl CrosEc { /// `newserial` - a string that is 18 characters long pub fn set_gpu_serial(&self, magic: u8, newserial: String) -> EcResult { let mut array_tmp: [u8; 20] = [0; 20]; + // Clap checks the length, the UEFI commandline doesn't + if newserial.len() != 18 { + return Err(EcError::DeviceError(format!( + "GPU serial must be 18 characters, is {}", + newserial.len() + ))); + } array_tmp[..18].copy_from_slice(newserial.as_bytes()); let result = EcRequestSetGpuSerial { magic, From 5b0925def8956a3878b2a3f4e3eb84395983516d Mon Sep 17 00:00:00 2001 From: Daniel Schaefer Date: Wed, 25 Nov 2026 22:22:30 +0800 Subject: [PATCH 21/31] chromium_ec: Don't panic on a GPU serial that isn't UTF-8 get_gpu_serial() unwrapped the UTF-8 conversion of the serial the EC read from the expansion bay EEPROM, before even checking whether the EC considers it valid. A blank or corrupted EEPROM crashed --expansion-bay. Check validity first and convert lossily. Found by the gpu_eeprom fuzz target. Co-Authored-By: Claude Opus 5.5 --- framework_lib/src/chromium_ec/mod.rs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/framework_lib/src/chromium_ec/mod.rs b/framework_lib/src/chromium_ec/mod.rs index bbec0007..8ab14ae9 100644 --- a/framework_lib/src/chromium_ec/mod.rs +++ b/framework_lib/src/chromium_ec/mod.rs @@ -1478,12 +1478,13 @@ impl CrosEc { pub fn get_gpu_serial(&self) -> EcResult { let gpuserial: EcResponseGetGpuSerial = EcRequestGetGpuSerial { idx: 0 }.send_command(self)?; - let serial: String = String::from_utf8(gpuserial.serial.to_vec()).unwrap(); - if gpuserial.valid == 0 { return Err(EcError::DeviceError("No valid GPU serial".to_string())); } + // Comes from the EEPROM, which could contain anything + let serial = String::from_utf8_lossy(&gpuserial.serial).to_string(); + Ok(serial) } From 8974c09537694b4a7bba6add806e90c5f1b7e5a6 Mon Sep 17 00:00:00 2001 From: Daniel Schaefer Date: Wed, 25 Nov 2026 22:24:14 +0800 Subject: [PATCH 22/31] i2c_passthrough: Reject reads that return more data than requested i2c_read() passed on whatever the EC returned. read_ec_gpu_chunk() appends each chunk to the previous ones, so extra bytes ended up where the next chunk belongs and a dump or validation of the GPU EEPROM returned shifted data without an error. Found by the gpu_eeprom fuzz target. Co-Authored-By: Claude Opus 5.5 --- framework_lib/src/chromium_ec/i2c_passthrough.rs | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/framework_lib/src/chromium_ec/i2c_passthrough.rs b/framework_lib/src/chromium_ec/i2c_passthrough.rs index fa66cec8..b5cdd94a 100644 --- a/framework_lib/src/chromium_ec/i2c_passthrough.rs +++ b/framework_lib/src/chromium_ec/i2c_passthrough.rs @@ -142,6 +142,15 @@ fn i2c_read_impl( // The EC only returns as many bytes as it managed to read. // On NAK or timeout that's less than requested, possibly nothing at all. let res_data = &data[size_of::<_EcI2cPassthruResponse>()..]; + // Callers append the data to what they read before, extra bytes would end up + // where the next read's data belongs + if res_data.len() > usize::from(len) { + return Err(EcError::DeviceError(format!( + "I2C read returned {} bytes, more than requested {}", + res_data.len(), + len + ))); + } // The EC stops at the first message that fails, so it can have processed // any number of messages up to the requested count debug_assert!(res.messages as usize <= messages.len()); From 923243e1b837e4582ea43ea53def897637965e17 Mon Sep 17 00:00:00 2001 From: Daniel Schaefer Date: Wed, 25 Nov 2026 22:25:01 +0800 Subject: [PATCH 23/31] chromium_ec: Don't overflow on bad GPU descriptor lengths read_gpu_descriptor() added the header and descriptor lengths from the EEPROM, which overflows with overflow checks, and truncated the sum to u16, silently reading only part of the descriptor if it was larger. Return an error for lengths that don't fit into the 16-bit EEPROM address space. Found by the gpu_eeprom fuzz target. Co-Authored-By: Claude Opus 5.5 --- framework_lib/src/chromium_ec/mod.rs | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/framework_lib/src/chromium_ec/mod.rs b/framework_lib/src/chromium_ec/mod.rs index 8ab14ae9..7cd742f9 100644 --- a/framework_lib/src/chromium_ec/mod.rs +++ b/framework_lib/src/chromium_ec/mod.rs @@ -1667,7 +1667,18 @@ impl CrosEc { "Invalid descriptor hdr magic".to_string(), )); } - self.read_ec_gpu_chunk(0x00, (header.descriptor_length + header.length) as u16) + // Lengths come from the EEPROM, could be anything + let (length, descriptor_length) = (header.length, header.descriptor_length); + let total = length + .checked_add(descriptor_length) + .and_then(|total| u16::try_from(total).ok()) + .ok_or_else(|| { + EcError::DeviceError(format!( + "Invalid descriptor length: header {} + descriptor {} bytes", + length, descriptor_length + )) + })?; + self.read_ec_gpu_chunk(0x00, total) } pub fn read_gpu_desc_header(&self) -> EcResult { From d620d0bad70c812fad047f2a9ca08672b72bc024 Mon Sep 17 00:00:00 2001 From: Daniel Schaefer Date: Wed, 25 Nov 2026 22:25:59 +0800 Subject: [PATCH 24/31] i2c_passthrough: Don't panic on malformed EC responses i2c_read(), i2c_write() and i2c_write_block() read the 2 byte response header without checking the response is that long, reading out of bounds and then panicking on the slice. The write functions also asserted there's no data after the header. Check both and return an error, sharing the check i2c_transfer() already had. Found by the gpu_eeprom fuzz target. Co-Authored-By: Claude Opus 5.5 --- .../src/chromium_ec/i2c_passthrough.rs | 45 +++++++++++++------ 1 file changed, 31 insertions(+), 14 deletions(-) diff --git a/framework_lib/src/chromium_ec/i2c_passthrough.rs b/framework_lib/src/chromium_ec/i2c_passthrough.rs index b5cdd94a..e7139d70 100644 --- a/framework_lib/src/chromium_ec/i2c_passthrough.rs +++ b/framework_lib/src/chromium_ec/i2c_passthrough.rs @@ -61,6 +61,19 @@ impl EcI2cPassthruResponse { } } +/// Split the EC response into header and read data +fn parse_response(data: &[u8]) -> EcResult<(_EcI2cPassthruResponse, &[u8])> { + let header_len = size_of::<_EcI2cPassthruResponse>(); + if data.len() < header_len { + return Err(EcError::DeviceError(format!( + "I2C passthrough response too short: {} bytes", + data.len() + ))); + } + let res: _EcI2cPassthruResponse = unsafe { core::ptr::read(data.as_ptr() as *const _) }; + Ok((res, &data[header_len..])) +} + /// Indicate that it's a read, not a write const I2C_READ_FLAG: u16 = 1 << 15; @@ -138,10 +151,9 @@ fn i2c_read_impl( buffer[params_len + msgs_len..].copy_from_slice(addr_bytes); let data = ec.send_command(EcCommands::I2cPassthrough as u16, 0, &buffer)?; - let res: _EcI2cPassthruResponse = unsafe { core::ptr::read(data.as_ptr() as *const _) }; // The EC only returns as many bytes as it managed to read. // On NAK or timeout that's less than requested, possibly nothing at all. - let res_data = &data[size_of::<_EcI2cPassthruResponse>()..]; + let (res, res_data) = parse_response(&data)?; // Callers append the data to what they read before, extra bytes would end up // where the next read's data belongs if res_data.len() > usize::from(len) { @@ -217,8 +229,14 @@ pub fn i2c_write_block( buffer[params_len + msgs_len + addr_bytes.len()..].copy_from_slice(data); let data = ec.send_command(EcCommands::I2cPassthrough as u16, 0, &buffer)?; - let res: _EcI2cPassthruResponse = unsafe { core::ptr::read(data.as_ptr() as *const _) }; - assert_eq!(data.len(), size_of::<_EcI2cPassthruResponse>()); // No extra data other than the header + let (res, res_data) = parse_response(&data)?; + // No extra data other than the header + if !res_data.is_empty() { + return Err(EcError::DeviceError(format!( + "I2C write returned {} bytes of unexpected data", + res_data.len() + ))); + } // Only assert message count if the transfer was successful // On error (NAK/timeout), the EC may return 0 messages processed @@ -269,8 +287,14 @@ pub fn i2c_write( buffer[params_len + msgs_len + addr_bytes.len()..].copy_from_slice(data); let data = ec.send_command(EcCommands::I2cPassthrough as u16, 0, &buffer)?; - let res: _EcI2cPassthruResponse = unsafe { core::ptr::read(data.as_ptr() as *const _) }; - assert_eq!(data.len(), size_of::<_EcI2cPassthruResponse>()); // No extra data other than the header + let (res, res_data) = parse_response(&data)?; + // No extra data other than the header + if !res_data.is_empty() { + return Err(EcError::DeviceError(format!( + "I2C write returned {} bytes of unexpected data", + res_data.len() + ))); + } // Only assert message count if the transfer was successful // On error (NAK/timeout), the EC may return 0 messages processed @@ -355,14 +379,7 @@ pub fn i2c_transfer( buffer[params_len + msgs_len..].copy_from_slice(write); let data = ec.send_command(EcCommands::I2cPassthrough as u16, 0, &buffer)?; - if data.len() < header_len { - return Err(EcError::DeviceError(format!( - "I2C passthrough response too short: {} bytes", - data.len() - ))); - } - let res: _EcI2cPassthruResponse = unsafe { core::ptr::read(data.as_ptr() as *const _) }; - let res_data = &data[header_len..]; + let (res, res_data) = parse_response(&data)?; let i2c_status = res.i2c_status; trace!( " i2c_transfer response (status: 0x{:02X}, messages: {}, data: {:#04X?})", From a1231ed98c0eda434c904b41caf05eab6d913585 Mon Sep 17 00:00:00 2001 From: Daniel Schaefer Date: Wed, 25 Nov 2026 22:27:29 +0800 Subject: [PATCH 25/31] i2c_passthrough: Return an error on a wrong message count The I2C read and write functions debug_assert'ed the number of messages the EC reports to have run, panicking in debug builds if the EC response is off. Return an error instead, like i2c_transfer() already did: the EC can't have run more messages than requested and must have run all of them if it reports success. Found by the gpu_eeprom fuzz target. Co-Authored-By: Claude Opus 5.5 --- .../src/chromium_ec/i2c_passthrough.rs | 51 +++++++++---------- 1 file changed, 23 insertions(+), 28 deletions(-) diff --git a/framework_lib/src/chromium_ec/i2c_passthrough.rs b/framework_lib/src/chromium_ec/i2c_passthrough.rs index e7139d70..6fef5c59 100644 --- a/framework_lib/src/chromium_ec/i2c_passthrough.rs +++ b/framework_lib/src/chromium_ec/i2c_passthrough.rs @@ -74,6 +74,19 @@ fn parse_response(data: &[u8]) -> EcResult<(_EcI2cPassthruResponse, &[u8])> { Ok((res, &data[header_len..])) } +/// The EC stops at the first message that fails, so it can have processed any +/// number of messages up to the requested count. On success it must have run all. +fn check_message_count(res: &_EcI2cPassthruResponse, requested: usize) -> EcResult<()> { + let ran = res.messages as usize; + if ran > requested || (res.i2c_status == 0 && ran != requested) { + return Err(EcError::DeviceError(format!( + "EC ran {} of {} I2C messages", + ran, requested + ))); + } + Ok(()) +} + /// Indicate that it's a read, not a write const I2C_READ_FLAG: u16 = 1 << 15; @@ -163,9 +176,7 @@ fn i2c_read_impl( len ))); } - // The EC stops at the first message that fails, so it can have processed - // any number of messages up to the requested count - debug_assert!(res.messages as usize <= messages.len()); + check_message_count(&res, messages.len())?; let i2c_status = res.i2c_status; trace!( " i2c_read response (status: 0x{:02X}, len: {}, data: {:#04X?})", @@ -238,11 +249,7 @@ pub fn i2c_write_block( ))); } - // Only assert message count if the transfer was successful - // On error (NAK/timeout), the EC may return 0 messages processed - if res.i2c_status == 0 { - debug_assert_eq!(res.messages as usize, messages.len()); - } + check_message_count(&res, messages.len())?; Ok(EcI2cPassthruResponse { i2c_status: res.i2c_status, @@ -296,11 +303,7 @@ pub fn i2c_write( ))); } - // Only assert message count if the transfer was successful - // On error (NAK/timeout), the EC may return 0 messages processed - if res.i2c_status == 0 { - debug_assert_eq!(res.messages as usize, messages.len()); - } + check_message_count(&res, messages.len())?; Ok(EcI2cPassthruResponse { i2c_status: res.i2c_status, @@ -388,22 +391,14 @@ pub fn i2c_transfer( res_data ); + check_message_count(&res, messages.len())?; // On NAK or timeout the EC stops early, so only check a successful transfer - if i2c_status == 0 { - if res.messages as usize != messages.len() { - return Err(EcError::DeviceError(format!( - "EC ran {} of {} I2C messages", - res.messages, - messages.len() - ))); - } - if res_data.len() != read_len as usize { - return Err(EcError::DeviceError(format!( - "Short I2C read: wanted {} bytes, got {}", - read_len, - res_data.len() - ))); - } + if i2c_status == 0 && res_data.len() != read_len as usize { + return Err(EcError::DeviceError(format!( + "Short I2C read: wanted {} bytes, got {}", + read_len, + res_data.len() + ))); } Ok(EcI2cPassthruResponse { From e47d7afb8055077b6459b1e949ccecef5b57986c Mon Sep 17 00:00:00 2001 From: Daniel Schaefer Date: Wed, 25 Nov 2026 22:27:43 +0800 Subject: [PATCH 26/31] chromium_ec: Don't wrap around when writing a GPU descriptor over 64K set_gpu_descriptor() cast the write offset to u16, so with a file larger than 64KiB the chunks past that wrapped to offset 0 and overwrote the descriptor header. Reject such files before touching the EEPROM. Found by the gpu_eeprom fuzz target. Co-Authored-By: Claude Opus 5.5 --- framework_lib/src/chromium_ec/mod.rs | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/framework_lib/src/chromium_ec/mod.rs b/framework_lib/src/chromium_ec/mod.rs index 7cd742f9..f6acaaa1 100644 --- a/framework_lib/src/chromium_ec/mod.rs +++ b/framework_lib/src/chromium_ec/mod.rs @@ -1557,6 +1557,14 @@ impl CrosEc { "Writing GPU EEPROM {}", if dry_run { " (DRY RUN)" } else { "" } ); + // EEPROM has 16-bit addresses, anything beyond would wrap around and + // overwrite the start + if data.len() > 0x10000 { + return Err(EcError::DeviceError(format!( + "GPU descriptor too large: {} bytes, max 65536", + data.len() + ))); + } let mut force_power = false; let info = EcRequestExpansionBayStatus {}.send_command(self)?; From b1cb86770aea204a309d23a3d60fcb52047b8013 Mon Sep 17 00:00:00 2001 From: Daniel Schaefer Date: Wed, 25 Nov 2026 22:33:49 +0800 Subject: [PATCH 27/31] chromium_ec: Don't overflow reading past the end of the GPU EEPROM read_ec_gpu_chunk() computed each chunk's offset as a u16, which overflows if address plus length goes beyond 0xFFFF, panicking with overflow checks and wrapping around to offset 0 otherwise. Return an error for reads outside the 16-bit address space. Found by the gpu_eeprom fuzz target. Co-Authored-By: Claude Opus 5.5 --- framework_lib/src/chromium_ec/mod.rs | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/framework_lib/src/chromium_ec/mod.rs b/framework_lib/src/chromium_ec/mod.rs index f6acaaa1..d2c299a9 100644 --- a/framework_lib/src/chromium_ec/mod.rs +++ b/framework_lib/src/chromium_ec/mod.rs @@ -1516,6 +1516,14 @@ impl CrosEc { let eeprom_addr = 0x50; let mut data: Vec = Vec::with_capacity(len.into()); + // EEPROM has 16-bit addresses + if usize::from(addr) + usize::from(len) > 0x10000 { + return Err(EcError::DeviceError(format!( + "EEPROM read 0x{:X}+0x{:X} beyond 16-bit address space", + addr, len + ))); + } + while data.len() < len.into() { let remaining = len - data.len() as u16; let chunk_len = core::cmp::min(i2c_passthrough::MAX_I2C_CHUNK, remaining.into()); From 0c4986b17f8945b3b25f9f90728ff10402dd5bcd Mon Sep 17 00:00:00 2001 From: Daniel Schaefer Date: Wed, 25 Nov 2026 22:33:58 +0800 Subject: [PATCH 28/31] fuzz: gpu_eeprom: Show faults and commands when a read returns wrong data Co-Authored-By: Claude Opus 5.5 --- fuzz/fuzz_targets/gpu_eeprom.rs | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/fuzz/fuzz_targets/gpu_eeprom.rs b/fuzz/fuzz_targets/gpu_eeprom.rs index 8d834df5..a74a7122 100644 --- a/fuzz/fuzz_targets/gpu_eeprom.rs +++ b/fuzz/fuzz_targets/gpu_eeprom.rs @@ -482,7 +482,14 @@ fuzz_target!(|data: &[u8]| { let want: Vec = (0..len as usize) .map(|i| initial_eeprom[(addr as usize + i) % initial_eeprom.len()]) .collect(); - assert!(chunk == want, "Read chunk content wrong"); + assert!( + chunk == want, + "Read chunk content wrong {:?} {:?} addr={:X} len={:X}", + model.borrow().hit_faults, + model.borrow().log, + addr, + len + ); } } 4 => { From dc5247bfc2c72586a083bb757ab0822f4368d2a2 Mon Sep 17 00:00:00 2001 From: Daniel Schaefer Date: Wed, 25 Nov 2026 22:34:06 +0800 Subject: [PATCH 29/31] chromium_ec: Show the file size as total when writing the GPU EEPROM The progress output showed the current chunk size times the number of chunks, which is rounded up to a multiple of 32 bytes. Show the actual number of bytes to write. Co-Authored-By: Claude Opus 5.5 --- framework_lib/src/chromium_ec/mod.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/framework_lib/src/chromium_ec/mod.rs b/framework_lib/src/chromium_ec/mod.rs index d2c299a9..4611170b 100644 --- a/framework_lib/src/chromium_ec/mod.rs +++ b/framework_lib/src/chromium_ec/mod.rs @@ -1622,7 +1622,7 @@ impl CrosEc { chunk_no, chunks, offset, - cur_chunk_size * chunks + data.len() ); } else { print!("X"); From 0e39d9f6c7010f736921b5e55acc762594420584 Mon Sep 17 00:00:00 2001 From: Daniel Schaefer Date: Wed, 25 Nov 2026 22:34:23 +0800 Subject: [PATCH 30/31] commandline: Don't claim GPU descriptor was written in dry run --flash-gpu-descriptor-file with --dry-run printed that the descriptor was successfully written and then validated the EEPROM against the file, which fails unless it already contained it. Co-Authored-By: Claude Opus 5.5 --- framework_lib/src/commandline/mod.rs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/framework_lib/src/commandline/mod.rs b/framework_lib/src/commandline/mod.rs index 5f1da58e..563bc367 100644 --- a/framework_lib/src/commandline/mod.rs +++ b/framework_lib/src/commandline/mod.rs @@ -2331,6 +2331,9 @@ pub fn run_with_args(args: &Cli, _allupdate: bool) -> i32 { println!(" Size: {:>20} KB", data.len() / 1024); let res = ec.set_gpu_descriptor(&data, args.dry_run); match res { + Ok(()) if args.dry_run => { + println!("GPU Descriptor not written (dry run)"); + } Ok(()) => { println!("GPU Descriptor successfully written"); println!("Validating GPU Descriptor..."); From 266d8c48b395a27b0c5ee48b7bab95a070fcf86c Mon Sep 17 00:00:00 2001 From: Daniel Schaefer Date: Wed, 25 Nov 2026 22:44:16 +0800 Subject: [PATCH 31/31] fuzz: gpu_eeprom: Check that reads and writes succeed without faults All checks only looked at results that were Ok, so a change making everything fail would have passed. Without injected faults, writing a file that fits into the EEPROM and reading or validating a valid descriptor must succeed. Mostly generate files whose header lengths match the file length, so validating after writing can be checked too. Validating right after writing is only checked if the expansion bay was already powered: if set_gpu_descriptor() forced power on, it's off again and the model's EEPROM doesn't answer. Co-Authored-By: Claude Opus 5.5 --- fuzz/fuzz_targets/gpu_eeprom.rs | 43 ++++++++++++++++++++++++++++++--- 1 file changed, 39 insertions(+), 4 deletions(-) diff --git a/fuzz/fuzz_targets/gpu_eeprom.rs b/fuzz/fuzz_targets/gpu_eeprom.rs index a74a7122..286a22e0 100644 --- a/fuzz/fuzz_targets/gpu_eeprom.rs +++ b/fuzz/fuzz_targets/gpu_eeprom.rs @@ -358,8 +358,13 @@ fuzz_target!(|data: &[u8]| { 0x10021, ]) as usize % 0x10100; - let file_length = input.pick(&lengths); - let file_desc_len = input.pick(&lengths); + // Mostly a well-formed file, where the header lengths match the file length + let consistent = input.u8() < 0xC0 && file_len >= HEADER_LEN; + let (file_length, file_desc_len) = if consistent { + (HEADER_LEN as u32, (file_len - HEADER_LEN) as u32) + } else { + (input.pick(&lengths), input.pick(&lengths)) + }; let file = Rc::new(descriptor(file_len, file_length, file_desc_len, true)); let mut gpu_serial = [0u8; 22]; @@ -435,6 +440,9 @@ fuzz_target!(|data: &[u8]| { "Expansion bay power not restored, result {:?}", res ); + if !dry_run && m.hit_faults.is_empty() && file_len <= eeprom_size { + assert!(res.is_ok(), "Write failed without a fault: {:?}", res); + } if res.is_ok() && !dry_run { // Can't hold more than it has room for if file_len <= eeprom_size { @@ -457,12 +465,29 @@ fuzz_target!(|data: &[u8]| { "File larger than EEPROM validated successfully" ); } + let fits = consistent && file_len <= eeprom_size && file_len <= 0xFFFF; + // If power was forced on for writing, it's off again and reading fails + if fits && m.hit_faults.is_empty() && initially_powered { + assert!( + matches!(valid, Ok(true)), + "Validation after successful write failed: {:?}", + valid + ); + } } } 1 => { let res = ec.read_gpu_descriptor(); + let total = ee_length as u64 + ee_desc_len as u64; + if ee_magic_ok && total <= 0xFFFF && initially_powered { + let m = model.borrow(); + assert!( + res.is_ok() || !m.hit_faults.is_empty(), + "Read of valid descriptor failed without a fault: {:?}", + res + ); + } if let Ok(desc) = res { - let total = ee_length as u64 + ee_desc_len as u64; assert!(ee_magic_ok, "Read descriptor with invalid magic"); assert_eq!(desc.len() as u64, total, "Descriptor length wrong"); assert!(desc == expected(desc.len()), "Descriptor content wrong"); @@ -508,7 +533,17 @@ fuzz_target!(|data: &[u8]| { let i = flip % reference.len(); reference[i] ^= 0x01; } - if let Ok(valid) = ec.validate_gpu_descriptor(&reference) { + let res = ec.validate_gpu_descriptor(&reference); + let total = ee_length as u64 + ee_desc_len as u64; + if ee_magic_ok && total <= 0xFFFF && initially_powered { + let m = model.borrow(); + assert!( + res.is_ok() || !m.hit_faults.is_empty(), + "Validation of valid descriptor failed without a fault: {:?}", + res + ); + } + if let Ok(valid) = res { assert!(ee_magic_ok); assert_eq!(valid, !flipped, "Validation result wrong"); }