From 999de9f2df6332a51e249679e5598ac4cde04897 Mon Sep 17 00:00:00 2001 From: Swastick Chowdhury <28708247+Swastickc@users.noreply.github.com> Date: Tue, 24 Nov 2026 15:02:00 +0530 Subject: [PATCH] loader: validate PE headers, section ranges and entry point (#79) Fix two parser panics found by the pe_parse fuzz target: a truncated PE32+ optional header and unchecked RVA range arithmetic. Also require the 112-byte fixed optional header, check section table and raw data bounds, reject overlapping sections and require the entry point to lie in an executable section. Adds pe_validation regression tests built from original synthetic images. Signed-off-by: Swastick Chowdhury <28708247+Swastickc@users.noreply.github.com> --- crates/loader/src/pe.rs | 142 ++++++++++------ crates/loader/tests/pe_validation.rs | 239 +++++++++++++++++++++++++++ 2 files changed, 330 insertions(+), 51 deletions(-) create mode 100644 crates/loader/tests/pe_validation.rs diff --git a/crates/loader/src/pe.rs b/crates/loader/src/pe.rs index fb1156c..22b0b68 100644 --- a/crates/loader/src/pe.rs +++ b/crates/loader/src/pe.rs @@ -91,6 +91,17 @@ pub const IMAGE_SCN_MEM_WRITE: u32 = 0x80000000; // Standard Constants pub const IMAGE_FILE_MACHINE_AMD64: u16 = 0x8664; pub const PE32_PLUS_MAGIC: u16 = 0x020B; +/// PE32+ optional header length up to and including NumberOfRvaAndSizes. +const PE32_PLUS_MIN_OPTIONAL_HEADER: usize = 112; +const SECTION_HEADER_SIZE: usize = 40; + +fn read_u16(bytes: &[u8], at: usize) -> u16 { + u16::from_le_bytes([bytes[at], bytes[at + 1]]) +} + +fn read_u32(bytes: &[u8], at: usize) -> u32 { + u32::from_le_bytes(bytes[at..at + 4].try_into().unwrap()) +} impl ParsedPe { /// Parse PE32+ headers from an in-memory byte slice. @@ -105,80 +116,82 @@ impl ParsedPe { } let e_lfanew = u32::from_le_bytes(bytes[0x3C..0x40].try_into().unwrap()) as usize; - if bytes.len() < e_lfanew + 24 { + let coff_offset = e_lfanew.checked_add(4).ok_or(PeError::TooSmall)?; + if bytes.len() < coff_offset.checked_add(20).ok_or(PeError::TooSmall)? { return Err(PeError::TooSmall); } // 2. PE Signature - if &bytes[e_lfanew..e_lfanew + 4] != b"PE\0\0" { + if &bytes[e_lfanew..coff_offset] != b"PE\0\0" { return Err(PeError::InvalidPeSignature); } // 3. COFF File Header - let coff_offset = e_lfanew + 4; - let machine = u16::from_le_bytes(bytes[coff_offset..coff_offset + 2].try_into().unwrap()); + let machine = read_u16(bytes, coff_offset); if machine != IMAGE_FILE_MACHINE_AMD64 { return Err(PeError::UnsupportedMachine(machine)); } + let number_of_sections = read_u16(bytes, coff_offset + 2); + let time_date_stamp = read_u32(bytes, coff_offset + 4); + let size_of_optional_header = usize::from(read_u16(bytes, coff_offset + 16)); - let number_of_sections = - u16::from_le_bytes(bytes[coff_offset + 2..coff_offset + 4].try_into().unwrap()); - let time_date_stamp = - u32::from_le_bytes(bytes[coff_offset + 4..coff_offset + 8].try_into().unwrap()); - let size_of_optional_header = u16::from_le_bytes( - bytes[coff_offset + 16..coff_offset + 18] - .try_into() - .unwrap(), - ) as usize; - - // 4. Optional Header (PE32+ is required) + // 4. Optional Header (PE32+ is required). The fixed PE32+ fields end at + // NumberOfRvaAndSizes (offset 108, 4 bytes); a shorter header is malformed. let opt_offset = coff_offset + 20; - if bytes.len() < opt_offset + size_of_optional_header { + let section_table_offset = opt_offset + size_of_optional_header; + if bytes.len() < opt_offset + 2 { return Err(PeError::TooSmall); } - - let magic = u16::from_le_bytes(bytes[opt_offset..opt_offset + 2].try_into().unwrap()); + let magic = read_u16(bytes, opt_offset); if magic != PE32_PLUS_MAGIC { return Err(PeError::InvalidMagic(magic)); } + if size_of_optional_header < PE32_PLUS_MIN_OPTIONAL_HEADER + || bytes.len() < section_table_offset + { + return Err(PeError::TooSmall); + } - let entry_point_rva = - u32::from_le_bytes(bytes[opt_offset + 16..opt_offset + 20].try_into().unwrap()); + let entry_point_rva = read_u32(bytes, opt_offset + 16); let image_base = u64::from_le_bytes(bytes[opt_offset + 24..opt_offset + 32].try_into().unwrap()); - let section_alignment = - u32::from_le_bytes(bytes[opt_offset + 32..opt_offset + 36].try_into().unwrap()); - let file_alignment = - u32::from_le_bytes(bytes[opt_offset + 36..opt_offset + 40].try_into().unwrap()); - let size_of_image = - u32::from_le_bytes(bytes[opt_offset + 56..opt_offset + 60].try_into().unwrap()); - let size_of_headers = - u32::from_le_bytes(bytes[opt_offset + 60..opt_offset + 64].try_into().unwrap()); + let section_alignment = read_u32(bytes, opt_offset + 32); + let file_alignment = read_u32(bytes, opt_offset + 36); + let size_of_image = read_u32(bytes, opt_offset + 56); + let size_of_headers = read_u32(bytes, opt_offset + 60); // 5. Section Headers - let mut sections = Vec::with_capacity(number_of_sections as usize); - let section_table_offset = opt_offset + size_of_optional_header; - let section_header_size = 40; - - if bytes.len() < section_table_offset + (number_of_sections as usize * section_header_size) - { + let table_end = usize::from(number_of_sections) + .checked_mul(SECTION_HEADER_SIZE) + .and_then(|len| section_table_offset.checked_add(len)) + .ok_or(PeError::InvalidSectionHeaders)?; + if bytes.len() < table_end { return Err(PeError::InvalidSectionHeaders); } - for i in 0..number_of_sections as usize { - let offset = section_table_offset + i * section_header_size; - let sec_bytes = &bytes[offset..offset + section_header_size]; - + let mut sections = Vec::with_capacity(usize::from(number_of_sections)); + for sec_bytes in bytes[section_table_offset..table_end].chunks_exact(SECTION_HEADER_SIZE) { // Section name (up to 8 bytes UTF-8 or null-padded ASCII) let name_raw = &sec_bytes[0..8]; let name_len = name_raw.iter().position(|&b| b == 0).unwrap_or(8); let name = String::from_utf8_lossy(&name_raw[..name_len]).into_owned(); - let virtual_size = u32::from_le_bytes(sec_bytes[8..12].try_into().unwrap()); - let virtual_address = u32::from_le_bytes(sec_bytes[12..16].try_into().unwrap()); - let raw_data_size = u32::from_le_bytes(sec_bytes[16..20].try_into().unwrap()); - let raw_data_ptr = u32::from_le_bytes(sec_bytes[20..24].try_into().unwrap()); - let characteristics = u32::from_le_bytes(sec_bytes[36..40].try_into().unwrap()); + let virtual_size = read_u32(sec_bytes, 8); + let virtual_address = read_u32(sec_bytes, 12); + let raw_data_size = read_u32(sec_bytes, 16); + let raw_data_ptr = read_u32(sec_bytes, 20); + let characteristics = read_u32(sec_bytes, 36); + + // The mapped range must fit in the 32-bit RVA space, and raw data must be in the file. + virtual_address + .checked_add(virtual_size.max(raw_data_size)) + .ok_or(PeError::InvalidSectionHeaders)?; + if raw_data_size > 0 { + let raw_end = u64::from(raw_data_ptr) + u64::from(raw_data_size); + if raw_end > bytes.len() as u64 { + return Err(PeError::InvalidSectionHeaders); + } + } let permissions = MemoryPermissions { read: (characteristics & IMAGE_SCN_MEM_READ) != 0, @@ -197,6 +210,32 @@ impl ParsedPe { }); } + // Mapped section ranges must not overlap. Zero-sized sections map nothing. + let mut ranges: Vec<(u32, u32)> = sections + .iter() + .map(|s| { + ( + s.virtual_address, + s.virtual_address + s.virtual_size.max(s.raw_data_size), + ) + }) + .filter(|(start, end)| start < end) + .collect(); + ranges.sort_unstable(); + if ranges.windows(2).any(|w| w[1].0 < w[0].1) { + return Err(PeError::InvalidSectionHeaders); + } + + // The entry point must lie inside an executable section. + let entry_ok = sections.iter().any(|s| { + s.permissions.execute + && entry_point_rva >= s.virtual_address + && entry_point_rva - s.virtual_address < s.virtual_size.max(s.raw_data_size) + }); + if !entry_ok { + return Err(PeError::InvalidEntryPoint); + } + Ok(ParsedPe { machine, number_of_sections, @@ -214,13 +253,12 @@ impl ParsedPe { /// Translate a Relative Virtual Address (RVA) to a raw file offset. pub fn rva_to_file_offset(&self, rva: u32) -> Option { for sec in &self.sections { - let start = sec.virtual_address; - let size = std::cmp::max(sec.virtual_size, sec.raw_data_size); - if rva >= start && rva < start + size { - let diff = (rva - start) as usize; - if diff < sec.raw_data_size as usize { - return Some(sec.raw_data_ptr as usize + diff); - } + // Sections are public and may not come from `parse`, so stay checked here. + let Some(diff) = rva.checked_sub(sec.virtual_address) else { + continue; + }; + if diff < sec.virtual_size.max(sec.raw_data_size) && diff < sec.raw_data_size { + return (sec.raw_data_ptr as usize).checked_add(diff as usize); } } None @@ -245,7 +283,9 @@ impl ParsedPe { let initial_data = if sec.raw_data_size > 0 && sec.raw_data_ptr > 0 { let start = sec.raw_data_ptr as usize; - let end = start + sec.raw_data_size as usize; + let end = start + .checked_add(sec.raw_data_size as usize) + .ok_or(PeError::InvalidSectionHeaders)?; bytes .get(start..end) .ok_or(PeError::InvalidSectionHeaders)? diff --git a/crates/loader/tests/pe_validation.rs b/crates/loader/tests/pe_validation.rs new file mode 100644 index 0000000..dc5c29e --- /dev/null +++ b/crates/loader/tests/pe_validation.rs @@ -0,0 +1,239 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +//! Malformed-input regression tests for the PE32+ parser (#79). +//! +//! Every image here is built byte by byte from the Microsoft PE/COFF +//! specification layout: DOS header with e_lfanew at 0x3C, "PE\0\0", the +//! 20-byte COFF header, the PE32+ optional header (112 fixed bytes before the +//! data directories) and 40-byte section headers. + +use xenora_loader::{ParsedPe, PeError, PeSection}; + +const RX: u32 = 0x6000_0020; // code | execute | read +const R: u32 = 0x4000_0040; // initialized data | read + +struct Sec { + va: u32, + vsize: u32, + raw_ptr: u32, + raw_size: u32, + flags: u32, +} + +/// A two-section image: .text at RVA 0x1000 (file 0x200) and .rdata at RVA 0x2000 (file 0x400). +fn valid_sections() -> Vec { + vec![ + Sec { + va: 0x1000, + vsize: 0x100, + raw_ptr: 0x200, + raw_size: 0x200, + flags: RX, + }, + Sec { + va: 0x2000, + vsize: 0x80, + raw_ptr: 0x400, + raw_size: 0x200, + flags: R, + }, + ] +} + +fn build(opt_size: u16, entry: u32, secs: &[Sec]) -> Vec { + let mut pe = vec![0u8; 0x600]; + pe[0..2].copy_from_slice(b"MZ"); + pe[0x3C..0x40].copy_from_slice(&0x40u32.to_le_bytes()); + pe[0x40..0x44].copy_from_slice(b"PE\0\0"); + let coff = 0x44; + pe[coff..coff + 2].copy_from_slice(&0x8664u16.to_le_bytes()); + pe[coff + 2..coff + 4].copy_from_slice(&(secs.len() as u16).to_le_bytes()); + pe[coff + 16..coff + 18].copy_from_slice(&opt_size.to_le_bytes()); + let opt = coff + 20; + pe[opt..opt + 2].copy_from_slice(&0x020Bu16.to_le_bytes()); + pe[opt + 16..opt + 20].copy_from_slice(&entry.to_le_bytes()); + pe[opt + 24..opt + 32].copy_from_slice(&0x1_4000_0000u64.to_le_bytes()); + pe[opt + 32..opt + 36].copy_from_slice(&0x1000u32.to_le_bytes()); + pe[opt + 36..opt + 40].copy_from_slice(&0x200u32.to_le_bytes()); + pe[opt + 56..opt + 60].copy_from_slice(&0x3000u32.to_le_bytes()); + pe[opt + 60..opt + 64].copy_from_slice(&0x200u32.to_le_bytes()); + let table = opt + usize::from(opt_size); + for (i, s) in secs.iter().enumerate() { + let h = table + i * 40; + pe[h..h + 5].copy_from_slice(b".sect"); + pe[h + 8..h + 12].copy_from_slice(&s.vsize.to_le_bytes()); + pe[h + 12..h + 16].copy_from_slice(&s.va.to_le_bytes()); + pe[h + 16..h + 20].copy_from_slice(&s.raw_size.to_le_bytes()); + pe[h + 20..h + 24].copy_from_slice(&s.raw_ptr.to_le_bytes()); + pe[h + 36..h + 40].copy_from_slice(&s.flags.to_le_bytes()); + } + pe +} + +#[test] +fn valid_image_parses_maps_and_translates() { + let bytes = build(112, 0x1010, &valid_sections()); + let pe = ParsedPe::parse(&bytes).expect("valid image"); + assert_eq!(pe.entry_point_rva, 0x1010); + assert_eq!(pe.sections.len(), 2); + assert_eq!(pe.rva_to_file_offset(0x1010), Some(0x210)); + assert_eq!(pe.rva_to_file_offset(0x2004), Some(0x404)); + assert_eq!(pe.rva_to_file_offset(0x3000), None); + let loaded = pe.load_into_memory(&bytes).expect("load"); + assert_eq!(loaded.entry_point, 0x1_4000_1010); +} + +#[test] +fn optional_header_with_data_directories_is_accepted() { + let bytes = build(240, 0x1000, &valid_sections()); + assert!(ParsedPe::parse(&bytes).is_ok()); +} + +#[test] +fn repository_fixtures_still_parse_and_load() { + let root = concat!(env!("CARGO_MANIFEST_DIR"), "/../.."); + for path in [ + "fixtures/pe/trusted-runner.exe", + "experiments/x1/fixtures/x2.exe", + "experiments/x1/fixtures/x3.exe", + "experiments/x1/fixtures/x4-17.exe", + "experiments/x1/fixtures/x4-93.exe", + "experiments/x1/fixtures/x5.exe", + "experiments/x1/fixtures/x6.exe", + ] { + let bytes = std::fs::read(format!("{root}/{path}")).expect(path); + let pe = ParsedPe::parse(&bytes).unwrap_or_else(|e| panic!("{path}: {e}")); + pe.load_into_memory(&bytes) + .unwrap_or_else(|e| panic!("{path}: {e}")); + } +} + +/// Reproducer from #79: 90 bytes, SizeOfOptionalHeader = 2, file ends after the magic. +#[test] +fn truncated_optional_header_is_rejected_not_panicking() { + let mut bytes = vec![0u8; 90]; + bytes[0..2].copy_from_slice(b"MZ"); + bytes[0x3C..0x40].copy_from_slice(&0x40u32.to_le_bytes()); + bytes[0x40..0x44].copy_from_slice(b"PE\0\0"); + bytes[0x44..0x46].copy_from_slice(&0x8664u16.to_le_bytes()); + bytes[0x54..0x56].copy_from_slice(&2u16.to_le_bytes()); + bytes[0x58..0x5A].copy_from_slice(&0x020Bu16.to_le_bytes()); + assert_eq!(ParsedPe::parse(&bytes).unwrap_err(), PeError::TooSmall); +} + +#[test] +fn optional_header_shorter_than_pe32_plus_fixed_fields_is_rejected() { + for opt_size in [24u16, 64, 111] { + let bytes = build(opt_size, 0x1000, &valid_sections()); + assert_eq!( + ParsedPe::parse(&bytes).unwrap_err(), + PeError::TooSmall, + "{opt_size}" + ); + } +} + +#[test] +fn e_lfanew_past_end_of_file_is_rejected() { + let mut bytes = build(112, 0x1000, &valid_sections()); + bytes[0x3C..0x40].copy_from_slice(&u32::MAX.to_le_bytes()); + assert_eq!(ParsedPe::parse(&bytes).unwrap_err(), PeError::TooSmall); +} + +#[test] +fn section_table_past_end_of_file_is_rejected() { + let mut bytes = build(112, 0x1000, &valid_sections()); + bytes[0x46..0x48].copy_from_slice(&u16::MAX.to_le_bytes()); + assert_eq!( + ParsedPe::parse(&bytes).unwrap_err(), + PeError::InvalidSectionHeaders + ); +} + +#[test] +fn section_range_overflowing_rva_space_is_rejected() { + let mut secs = valid_sections(); + secs[1].va = 0xFFFF_F000; + secs[1].vsize = 0x2000; + let bytes = build(112, 0x1000, &secs); + assert_eq!( + ParsedPe::parse(&bytes).unwrap_err(), + PeError::InvalidSectionHeaders + ); +} + +/// Reproducer from #79: lookup over a section whose end overflows u32 must not panic or wrap. +#[test] +fn rva_lookup_with_overflowing_section_returns_none() { + let bytes = build(112, 0x1000, &valid_sections()); + let mut pe = ParsedPe::parse(&bytes).unwrap(); + pe.sections.insert( + 0, + PeSection { + name: "wrap".into(), + virtual_address: 0xFFFF_FF00, + virtual_size: 0x200, + raw_data_ptr: 0x200, + raw_data_size: 0x200, + characteristics: R, + permissions: pe.sections[1].permissions, + }, + ); + // A wrapped end (0xFFFF_FF00 + 0x200 = 0x100) would wrongly capture RVA 0x80. + assert_eq!(pe.rva_to_file_offset(0x80), None); + assert_eq!(pe.rva_to_file_offset(0xFFFF_FF10), Some(0x210)); + assert_eq!(pe.rva_to_file_offset(0x1004), Some(0x204)); +} + +#[test] +fn overlapping_sections_are_rejected() { + let mut secs = valid_sections(); + secs[1].va = 0x1100; // .text maps 0x1000..0x1200 (raw size wins) + let bytes = build(112, 0x1000, &secs); + assert_eq!( + ParsedPe::parse(&bytes).unwrap_err(), + PeError::InvalidSectionHeaders + ); +} + +#[test] +fn adjacent_sections_are_accepted() { + let mut secs = valid_sections(); + secs[1].va = 0x1200; + let bytes = build(112, 0x1000, &secs); + assert!(ParsedPe::parse(&bytes).is_ok()); +} + +#[test] +fn truncated_section_data_is_rejected() { + let mut secs = valid_sections(); + secs[1].raw_size = 0x201; // file is 0x600 bytes; 0x400 + 0x201 runs one byte past the end + let bytes = build(112, 0x1000, &secs); + assert_eq!( + ParsedPe::parse(&bytes).unwrap_err(), + PeError::InvalidSectionHeaders + ); + + secs[1].raw_size = 0x200; + secs[1].raw_ptr = u32::MAX; + let bytes = build(112, 0x1000, &secs); + assert_eq!( + ParsedPe::parse(&bytes).unwrap_err(), + PeError::InvalidSectionHeaders + ); +} + +#[test] +fn entry_point_outside_executable_section_is_rejected() { + // Past the end of .text's mapped range, in non-executable .rdata, and outside every section. + for entry in [0x1200, 0x2000, 0x0, u32::MAX] { + let bytes = build(112, entry, &valid_sections()); + assert_eq!( + ParsedPe::parse(&bytes).unwrap_err(), + PeError::InvalidEntryPoint, + "entry {entry:#x}" + ); + } + // Last byte of .text is still inside it. + assert!(ParsedPe::parse(&build(112, 0x11FF, &valid_sections())).is_ok()); +}