From 4123d1235b1a53c603566a0f185b3879f1b1e54d Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Mon, 16 Nov 2026 11:43:48 +0100 Subject: [PATCH 1/2] Add craft-pe: PE/COFF headers from Craft Anything Moves the header half of Craft Anything's crates/formats/src/pe.rs into a pure-Rust crate: PeHeaders/PeSection, headers, has_pe_header, subsystem_name, rich_header, the data-directory names and the RVA mapping helpers. The import, export, resource and program-model code stays in the app for now. Part of #778. Co-authored-by: Afloat Co-authored-by: BFlat Co-authored-by: Brandon Thomas --- Cargo.lock | 9 + Cargo.toml | 1 + README.md | 1 + crates/pe/Cargo.toml | 22 ++ crates/pe/src/bytes.rs | 37 +++ crates/pe/src/lib.rs | 265 ++++++++++++++++++ crates/pe/src/tests.rs | 263 +++++++++++++++++ crates/pe/tests/pe_optional_header_framing.rs | 62 ++++ 8 files changed, 660 insertions(+) create mode 100644 crates/pe/Cargo.toml create mode 100644 crates/pe/src/bytes.rs create mode 100644 crates/pe/src/lib.rs create mode 100644 crates/pe/src/tests.rs create mode 100644 crates/pe/tests/pe_optional_header_framing.rs diff --git a/Cargo.lock b/Cargo.lock index 480e000e5..5dfb703f4 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2391,6 +2391,15 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "craft-pe" +version = "0.1.0" +dependencies = [ + "serde", + "serde_json", + "thiserror 2.0.21", +] + [[package]] name = "craft-penpot" version = "0.1.0" diff --git a/Cargo.toml b/Cargo.toml index bd08fa725..941503050 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -174,6 +174,7 @@ craft-xcf = { path = "crates/xcf" } craft-xml = { path = "crates/xml" } craft-zip = { path = "crates/zip" } craft-y4m = { path = "crates/y4m" } +craft-pe = { path = "crates/pe" } craft-epub = { path = "crates/epub" } craft-ews = { path = "crates/ews" } craft-video = { path = "crates/video" } diff --git a/README.md b/README.md index 8150dfea9..3596ee7fe 100644 --- a/README.md +++ b/README.md @@ -386,6 +386,7 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit text-format crates read into and write from. WordCraft's model without its editing code. - [`craft-xlsx`](crates/xlsx/README.md): Excel workbooks (`.xlsx`, `.xlsm`, SpreadsheetML, transitional and strict) and binary workbooks (`.xlsb`) on `craft-opc`: the workbook part, shared strings, the styles tables and worksheet rows streamed one at a time, with limits on the package, the XML and the binary records. - [`craft-ora`](crates/ora/README.md): OpenRaster documents (`.ora`): the ZIP archive and the `stack.xml` layer tree as written, read with bounded sizes and written. From PhotoCraft. +- [`craft-pe`](crates/pe/src/lib.rs): PE/COFF headers (`.exe`, `.dll`, `.sys`, `.efi`) from untrusted bytes, from Craft Anything: the COFF header, PE32/PE32+ optional header with its data directories bounded by the header's real size, the section table, RVA-to-file mapping and the decoded Rich header. - [`craft-y4m`](crates/y4m/src/lib.rs): YUV4MPEG2 (`.y4m`) reader, from FilmCraft: the stream header, colour space layouts at 8 to 16 bits, a frame index built from the `FRAME` lines without loading the file, and plane access. Bounded on hostile input. diff --git a/crates/pe/Cargo.toml b/crates/pe/Cargo.toml new file mode 100644 index 000000000..513c39055 --- /dev/null +++ b/crates/pe/Cargo.toml @@ -0,0 +1,22 @@ +[package] +name = "craft-pe" +description = "PE/COFF headers from hostile bytes, from Craft Anything: the DOS stub pointer, COFF header, PE32/PE32+ optional header, data directories, section table, RVA-to-file mapping and the Rich header. Pure Rust, no I/O." +version.workspace = true +edition.workspace = true +license.workspace = true +rust-version.workspace = true +repository.workspace = true + +[lints] +workspace = true + +[dependencies] +thiserror = { workspace = true } +# `serde`: `Serialize` on `PeSection`, for apps that report section tables as JSON. +serde = { workspace = true, optional = true } + +[features] +serde = ["dep:serde"] + +[dev-dependencies] +serde_json = { workspace = true } diff --git a/crates/pe/src/bytes.rs b/crates/pe/src/bytes.rs new file mode 100644 index 000000000..971f36133 --- /dev/null +++ b/crates/pe/src/bytes.rs @@ -0,0 +1,37 @@ +//! Checked little-endian reads over untrusted bytes. Every read returns `None` when out of range. + +#[derive(Debug, Clone, Copy)] +pub(crate) struct Reader<'a> { + data: &'a [u8], +} + +impl<'a> Reader<'a> { + pub(crate) fn new(data: &'a [u8]) -> Self { + Reader { data } + } + + pub(crate) fn slice(&self, off: usize, len: usize) -> Option<&'a [u8]> { + let end = off.checked_add(len)?; + self.data.get(off..end) + } + + pub(crate) fn u8(&self, off: usize) -> Option { + self.data.get(off).copied() + } + + fn arr(&self, off: usize) -> Option<[u8; N]> { + self.slice(off, N)?.try_into().ok() + } + + pub(crate) fn u16_le(&self, off: usize) -> Option { + self.arr(off).map(u16::from_le_bytes) + } + + pub(crate) fn u32_le(&self, off: usize) -> Option { + self.arr(off).map(u32::from_le_bytes) + } + + pub(crate) fn u64_le(&self, off: usize) -> Option { + self.arr(off).map(u64::from_le_bytes) + } +} diff --git a/crates/pe/src/lib.rs b/crates/pe/src/lib.rs new file mode 100644 index 000000000..f2294359b --- /dev/null +++ b/crates/pe/src/lib.rs @@ -0,0 +1,265 @@ +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] +#![forbid(unsafe_code)] + +//! PE/COFF headers (`.exe`, `.dll`, `.sys`, `.efi`…) from untrusted bytes. +//! +//! [`headers`] reads the DOS stub pointer, the COFF header, the PE32 or PE32+ optional header, +//! its data directories and the section table; [`PeHeaders::rva_to_offset`] maps addresses +//! through it. [`rich_header`] decodes the linker's Rich header. Nothing here panics on hostile +//! input: required fields that are missing are errors, optional ones read as zero, the +//! directory count is bounded by the complete entries in the optional header, and at most +//! [`MAX_SECTIONS`] sections are read. +//! +//! From Craft Anything (`crates/formats/src/pe.rs`), where the import, export, resource and +//! program-model code built on these headers stays. With the `serde` feature, [`PeSection`] is +//! `Serialize`. + +mod bytes; + +use crate::bytes::Reader; + +/// Sections read from the section table; the rest are ignored (the loader allows 96). +pub const MAX_SECTIONS: usize = 96; + +/// The names of the sixteen optional-header data directories, by index. +pub const DATA_DIRECTORY_NAMES: [&str; 16] = [ + "export", + "import", + "resource", + "exception", + "security", + "basereloc", + "debug", + "architecture", + "globalptr", + "tls", + "load_config", + "bound_import", + "iat", + "delay_import", + "clr_runtime", + "reserved", +]; + +/// Why [`headers`] gave up. +#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] +pub enum PeError { + /// A required header ends before the file does. + #[error("the file ends early ({0})")] + Truncated(&'static str), + /// A signature or magic number is wrong. + #[error("the file is malformed ({0})")] + Malformed(String), +} + +/// One section table entry. +#[derive(Debug, Clone, PartialEq, Eq)] +#[cfg_attr(feature = "serde", derive(serde::Serialize))] +pub struct PeSection { + /// The 8-byte name up to its first NUL, decoded lossily. + pub name: String, + pub virtual_size: u32, + pub rva: u32, + pub raw_size: u32, + pub raw_offset: u32, + pub characteristics: u32, +} + +/// The COFF and optional header fields and the section table. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct PeHeaders { + /// File offset of the `PE\0\0` signature (`e_lfanew`). + pub pe_offset: usize, + pub machine: u16, + pub timestamp: u32, + pub characteristics: u16, + pub pe32_plus: bool, + pub image_base: u64, + pub entry_rva: u32, + pub size_of_headers: u32, + pub subsystem: u16, + pub dll_characteristics: u16, + /// Major and minor linker version. + pub linker: (u8, u8), + /// `(rva, size)` for each data directory present, at most 16. + pub data_dirs: Vec<(u32, u32)>, + pub sections: Vec, +} + +impl PeHeaders { + /// RVA → file offset through the section table (headers map 1:1). + pub fn rva_to_offset(&self, rva: u32) -> Option { + for s in &self.sections { + let size = s.virtual_size.max(s.raw_size); + if rva >= s.rva && rva - s.rva < size { + let delta = rva - s.rva; + if delta >= s.raw_size { + return None; + } + return usize::try_from(s.raw_offset.checked_add(delta)?).ok(); + } + } + if rva < self.size_of_headers { usize::try_from(rva).ok() } else { None } + } + + /// The virtual address of `rva` in the loaded image, or `None` when it overflows (or, for + /// PE32, leaves the 32-bit address space). + pub fn image_va(&self, rva: u64) -> Option { + let rva = u32::try_from(rva).ok()?; + let address = self.image_base.checked_add(u64::from(rva))?; + (self.pe32_plus || address <= u64::from(u32::MAX)).then_some(address) + } + + /// Bytes remaining in the selected RVA mapping before file offsets stop being contiguous. + pub fn rva_file_len(&self, rva: u32) -> Option { + let base = self.rva_to_offset(rva)?; + let next_section_distance = |count: usize| { + self.sections + .iter() + .take(count) + .filter(|s| s.virtual_size.max(s.raw_size) > 0) + .filter_map(|s| s.rva.checked_sub(rva)) + .filter(|&distance| distance > 0) + .min() + .unwrap_or(u32::MAX) + }; + match self.sections.iter().enumerate().find(|(_, s)| rva.checked_sub(s.rva).is_some_and(|delta| delta < s.virtual_size.max(s.raw_size))) { + Some((index, s)) => { + rva.checked_sub(s.rva).and_then(|delta| s.raw_size.checked_sub(delta)).map(|len| len.min(next_section_distance(index))) + } + None => self.size_of_headers.checked_sub(rva).map(|len| len.min(next_section_distance(self.sections.len()))), + } + .map(u64::from) + .and_then(|len| { + let address_end = u64::from(u32::MAX) + 1; + let remaining_rvas = address_end.checked_sub(u64::from(rva))?; + let remaining_offsets = address_end.checked_sub(u64::try_from(base).ok()?)?; + usize::try_from(len.min(remaining_rvas).min(remaining_offsets)).ok() + }) + } + + /// Data directory `i` (see [`DATA_DIRECTORY_NAMES`]) when present and non-empty. + pub fn dir(&self, i: usize) -> Option<(u32, u32)> { + self.data_dirs.get(i).copied().filter(|(rva, size)| *rva != 0 && *size != 0) + } +} + +/// True when bytes start with MZ and point at a `PE\0\0` signature. +pub fn has_pe_header(data: &[u8]) -> bool { + let r = Reader::new(data); + r.u32_le(0x3c).and_then(|o| r.slice(o as usize, 4)) == Some(b"PE\0\0") +} + +/// Parse the DOS stub pointer, COFF header, optional header and section table. +pub fn headers(data: &[u8]) -> Result { + let r = Reader::new(data); + if !data.starts_with(b"MZ") { + return Err(PeError::Malformed("no MZ signature".into())); + } + let pe = r.u32_le(0x3c).ok_or(PeError::Truncated("DOS header"))? as usize; + if r.slice(pe, 4) != Some(b"PE\0\0") { + return Err(PeError::Malformed("no PE signature".into())); + } + let coff = pe + 4; + let t = |o: Option| o.ok_or(PeError::Truncated("COFF header")); + let machine = t(r.u16_le(coff))?; + let nsections = usize::from(t(r.u16_le(coff + 2))?); + let timestamp = r.u32_le(coff + 4).unwrap_or(0); + let opt_size = usize::from(t(r.u16_le(coff + 16))?); + let characteristics = t(r.u16_le(coff + 18))?; + let opt = coff + 20; + let optional = Reader::new(r.slice(opt, opt_size).ok_or(PeError::Truncated("optional header"))?); + let magic = optional.u16_le(0).ok_or(PeError::Truncated("optional header"))?; + let pe32_plus = match magic { + 0x20b => true, + 0x10b => false, + m => return Err(PeError::Malformed(format!("optional header magic {m:#x}"))), + }; + let (dd, count_off) = if pe32_plus { (112, 108) } else { (96, 92) }; + if opt_size < dd { + return Err(PeError::Truncated("fixed optional header fields")); + } + let image_base = if pe32_plus { optional.u64_le(24) } else { optional.u32_le(28).map(u64::from) }.unwrap_or(0); + let count = (optional.u32_le(count_off).unwrap_or(0) as usize).min(16).min((opt_size - dd) / 8); + let data_dirs = (0..count).map(|i| (optional.u32_le(dd + i * 8).unwrap_or(0), optional.u32_le(dd + i * 8 + 4).unwrap_or(0))).collect(); + let sh = opt + opt_size; + let mut sections = Vec::new(); + for i in 0..nsections.min(MAX_SECTIONS) { + let o = sh + i * 40; + let Some(name) = r.slice(o, 8) else { break }; + let name = String::from_utf8_lossy(name.split(|&c| c == 0).next().unwrap_or(&[])).into_owned(); + sections.push(PeSection { + name, + virtual_size: r.u32_le(o + 8).unwrap_or(0), + rva: r.u32_le(o + 12).unwrap_or(0), + raw_size: r.u32_le(o + 16).unwrap_or(0), + raw_offset: r.u32_le(o + 20).unwrap_or(0), + characteristics: r.u32_le(o + 36).unwrap_or(0), + }); + } + Ok(PeHeaders { + pe_offset: pe, + machine, + timestamp, + characteristics, + pe32_plus, + image_base, + entry_rva: optional.u32_le(16).unwrap_or(0), + size_of_headers: optional.u32_le(60).unwrap_or(0), + subsystem: optional.u16_le(68).unwrap_or(0), + dll_characteristics: optional.u16_le(70).unwrap_or(0), + linker: (optional.u8(2).unwrap_or(0), optional.u8(3).unwrap_or(0)), + data_dirs, + sections, + }) +} + +/// The optional header's subsystem as a short name (`windows-gui`, `efi-application`…), or +/// `unknown`. +pub fn subsystem_name(s: u16) -> &'static str { + match s { + 1 => "native", + 2 => "windows-gui", + 3 => "windows-console", + 7 => "posix-console", + 9 => "windows-ce", + 10 => "efi-application", + 11 => "efi-boot-driver", + 12 => "efi-runtime-driver", + 14 => "xbox", + 16 => "windows-boot", + _ => "unknown", + } +} + +/// Decoded Rich header entries between the DOS stub and `pe_offset`: (product id, build, count). +/// At most 256 entries. +pub fn rich_header(data: &[u8], pe_offset: usize) -> Option> { + let r = Reader::new(data); + let region = data.get(0x40..pe_offset.min(data.len()))?; + let rich = region.windows(4).position(|w| w == b"Rich")? + 0x40; + let key = r.u32_le(rich + 4)?; + // Walk back to "DanS". + let mut pos = rich; + let mut start = None; + while pos >= 0x44 { + pos -= 4; + if r.u32_le(pos)? ^ key == 0x536e_6144 { + start = Some(pos); + break; + } + } + let start = start?; + let mut out = Vec::new(); + let mut o = start + 16; + while o + 8 <= rich && out.len() < 256 { + let id = r.u32_le(o)? ^ key; + let count = r.u32_le(o + 4)? ^ key; + out.push(((id >> 16) as u16, (id & 0xffff) as u16, count)); + o += 8; + } + Some(out) +} + +#[cfg(test)] +mod tests; diff --git a/crates/pe/src/tests.rs b/crates/pe/src/tests.rs new file mode 100644 index 000000000..237d8fa30 --- /dev/null +++ b/crates/pe/src/tests.rs @@ -0,0 +1,263 @@ +//! Header, mapping and Rich header tests. `header_rvas_stop_before_file_padding` is from Craft +//! Anything's `pe.rs`; the image builder here is a small stand-in for its testkit's `pe64`. + +use super::*; + +const PE_OFFSET: usize = 0xc0; +const OPT: usize = PE_OFFSET + 24; +const OPT_SIZE: usize = 112 + 16 * 8; +const SECTIONS: usize = OPT + OPT_SIZE; +const BASE: u64 = 0x1_4000_0000; + +fn put(data: &mut [u8], at: usize, bytes: &[u8]) { + data[at..at + bytes.len()].copy_from_slice(bytes); +} + +/// A PE32+ console image with `.text` at RVA 0x1000 (file 0x400) and `.rdata` at RVA 0x2000 +/// (file 0x600), an import directory, and a Rich header with two entries. +fn pe64() -> Vec { + let mut d = vec![0u8; 0x800]; + put(&mut d, 0, b"MZ"); + put(&mut d, 0x3c, &(PE_OFFSET as u32).to_le_bytes()); + rich(&mut d, 0x5a5a_1234, &[(0x0104, 30_729, 7), (0x00ff, 40_000, 1)]); + put(&mut d, PE_OFFSET, b"PE\0\0"); + let coff = PE_OFFSET + 4; + put(&mut d, coff, &0x8664u16.to_le_bytes()); + put(&mut d, coff + 2, &2u16.to_le_bytes()); + put(&mut d, coff + 4, &0x6000_0000u32.to_le_bytes()); + put(&mut d, coff + 16, &(OPT_SIZE as u16).to_le_bytes()); + put(&mut d, coff + 18, &0x22u16.to_le_bytes()); + put(&mut d, OPT, &0x20bu16.to_le_bytes()); + d[OPT + 2] = 14; + d[OPT + 3] = 36; + put(&mut d, OPT + 16, &0x1010u32.to_le_bytes()); + put(&mut d, OPT + 24, &BASE.to_le_bytes()); + put(&mut d, OPT + 60, &0x400u32.to_le_bytes()); + put(&mut d, OPT + 68, &3u16.to_le_bytes()); + put(&mut d, OPT + 70, &0x8160u16.to_le_bytes()); + put(&mut d, OPT + 108, &16u32.to_le_bytes()); + put(&mut d, OPT + 112 + 8, &0x2000u32.to_le_bytes()); + put(&mut d, OPT + 112 + 12, &0x28u32.to_le_bytes()); + for (i, (name, rva, raw)) in [(&b".text"[..], 0x1000u32, 0x400u32), (&b".rdata"[..], 0x2000, 0x600)].into_iter().enumerate() { + let o = SECTIONS + i * 40; + put(&mut d, o, name); + put(&mut d, o + 8, &0x180u32.to_le_bytes()); + put(&mut d, o + 12, &rva.to_le_bytes()); + put(&mut d, o + 16, &0x200u32.to_le_bytes()); + put(&mut d, o + 20, &raw.to_le_bytes()); + put(&mut d, o + 36, &0x6000_0020u32.to_le_bytes()); + } + d +} + +/// Write a Rich header (`DanS`, three zero pads, entries, `Rich`, key) at 0x80, XOR-masked. +fn rich(d: &mut [u8], key: u32, entries: &[(u16, u16, u32)]) { + let mut o = 0x80; + for word in [0x536e_6144u32, 0, 0, 0] { + put(d, o, &(word ^ key).to_le_bytes()); + o += 4; + } + for &(product, build, count) in entries { + put(d, o, &(((u32::from(product)) << 16 | u32::from(build)) ^ key).to_le_bytes()); + put(d, o + 4, &(count ^ key).to_le_bytes()); + o += 8; + } + put(d, o, b"Rich"); + put(d, o + 4, &key.to_le_bytes()); +} + +/// Every truncation and a spread of single-byte corruptions. +fn mutations(sample: &[u8]) -> Vec> { + let mut out: Vec> = (0..sample.len()).step_by(7).map(|len| sample[..len].to_vec()).collect(); + for i in (0..sample.len()).step_by(3) { + for v in [0x00, 0x7f, 0xff] { + let mut m = sample.to_vec(); + m[i] = v; + out.push(m); + } + } + out +} + +#[test] +fn reads_coff_optional_header_and_sections() { + let d = pe64(); + assert!(has_pe_header(&d)); + let h = headers(&d).unwrap(); + assert_eq!(h.pe_offset, PE_OFFSET); + assert_eq!(h.machine, 0x8664); + assert_eq!(h.timestamp, 0x6000_0000); + assert_eq!(h.characteristics, 0x22); + assert!(h.pe32_plus); + assert_eq!(h.image_base, BASE); + assert_eq!(h.entry_rva, 0x1010); + assert_eq!(h.size_of_headers, 0x400); + assert_eq!(subsystem_name(h.subsystem), "windows-console"); + assert_eq!(h.dll_characteristics, 0x8160); + assert_eq!(h.linker, (14, 36)); + assert_eq!(h.data_dirs.len(), 16); + assert_eq!(h.dir(1), Some((0x2000, 0x28))); + assert_eq!(DATA_DIRECTORY_NAMES[1], "import"); + assert_eq!(h.dir(0), None); + assert_eq!(h.dir(16), None); + let names: Vec<&str> = h.sections.iter().map(|s| s.name.as_str()).collect(); + assert_eq!(names, [".text", ".rdata"]); + assert_eq!(h.sections[1].characteristics, 0x6000_0020); +} + +#[test] +fn pe32_reads_a_32_bit_image_base() { + let mut d = pe64(); + put(&mut d, OPT, &0x10bu16.to_le_bytes()); + put(&mut d, OPT + 28, &0x0040_0000u32.to_le_bytes()); + put(&mut d, OPT + 92, &2u32.to_le_bytes()); + let h = headers(&d).unwrap(); + assert!(!h.pe32_plus); + assert_eq!(h.image_base, 0x0040_0000); + assert_eq!(h.data_dirs.len(), 2); + assert_eq!(h.image_va(0x1000), Some(0x0040_1000)); + let mut high = h.clone(); + high.image_base = 0xffff_f000; + assert_eq!(high.image_va(0x1000), None, "a PE32 address cannot leave 32 bits"); +} + +#[test] +fn bad_signatures_and_short_headers_are_errors() { + let d = pe64(); + assert_eq!(headers(b"ZM"), Err(PeError::Malformed("no MZ signature".into()))); + assert_eq!(headers(b"MZ"), Err(PeError::Truncated("DOS header"))); + let mut no_pe = d.clone(); + no_pe[PE_OFFSET] = b'X'; + assert!(!has_pe_header(&no_pe)); + assert_eq!(headers(&no_pe), Err(PeError::Malformed("no PE signature".into()))); + assert_eq!(headers(&d[..PE_OFFSET + 6]), Err(PeError::Truncated("COFF header"))); + assert_eq!(headers(&d[..OPT + 10]), Err(PeError::Truncated("optional header"))); + let mut magic = d.clone(); + put(&mut magic, OPT, &0x107u16.to_le_bytes()); + assert_eq!(headers(&magic), Err(PeError::Malformed("optional header magic 0x107".into()))); + assert_eq!(headers(&magic).unwrap_err().to_string(), "the file is malformed (optional header magic 0x107)"); + assert_eq!(PeError::Truncated("COFF header").to_string(), "the file ends early (COFF header)"); + let mut empty_optional = d.clone(); + put(&mut empty_optional, PE_OFFSET + 20, &0u16.to_le_bytes()); + assert_eq!(headers(&empty_optional), Err(PeError::Truncated("optional header"))); +} + +#[test] +fn a_section_table_cut_short_keeps_the_complete_entries() { + let d = pe64(); + let h = headers(&d[..SECTIONS + 40 + 7]).unwrap(); + assert_eq!(h.sections.len(), 1); + let mut many = d.clone(); + put(&mut many, PE_OFFSET + 6, &u16::MAX.to_le_bytes()); + many.resize(SECTIONS + 40 * 200, 0); + assert_eq!(headers(&many).unwrap().sections.len(), MAX_SECTIONS); +} + +#[test] +fn header_rvas_stop_before_file_padding() { + let mut pe = pe64(); + let first = headers(&pe).unwrap().sections[0].raw_offset; + let opt = Reader::new(&pe).u32_le(0x3c).unwrap() as usize + 24; + let size_headers = 0x200_u32; + pe[opt + 60..opt + 64].copy_from_slice(&size_headers.to_le_bytes()); + let coff = opt - 20; + let section = opt + usize::from(Reader::new(&pe).u16_le(coff + 16).unwrap()); + pe[section + 20..section + 24].copy_from_slice(&(first + 0x400).to_le_bytes()); + let h = headers(&pe).unwrap(); + assert_eq!(h.rva_to_offset(size_headers - 1), Some(0x1ff)); + assert_eq!(h.rva_to_offset(size_headers), None); + assert_eq!(h.rva_to_offset(h.sections[0].rva), Some((first + 0x400) as usize)); +} + +#[test] +fn rvas_map_through_sections_and_stop_at_raw_data() { + let h = headers(&pe64()).unwrap(); + assert_eq!(h.rva_to_offset(0x10), Some(0x10)); + assert_eq!(h.rva_to_offset(0x1010), Some(0x410)); + assert_eq!(h.rva_to_offset(0x2000), Some(0x600)); + assert_eq!(h.rva_to_offset(0x1000 + 0x200), None, "past the raw data in the virtual tail"); + assert_eq!(h.rva_to_offset(0x9000), None); + assert_eq!(h.rva_file_len(0x1010), Some(0x1f0)); + assert_eq!(h.rva_file_len(0x2100), Some(0x100)); + assert_eq!(h.rva_file_len(0x10), Some(0x3f0)); + assert_eq!(h.rva_file_len(0x9000), None); + assert_eq!(h.image_va(0x1010), Some(BASE + 0x1010)); + assert_eq!(h.image_va(u64::from(u32::MAX) + 1), None); +} + +#[test] +fn contiguous_file_length_stops_at_the_next_section() { + let mut h = headers(&pe64()).unwrap(); + // `.text` claims raw bytes that run into `.rdata`'s RVA range. + h.sections[0].raw_size = 0x2000; + h.sections[0].virtual_size = 0x2000; + assert_eq!(h.rva_file_len(0x1800), Some(0x1800)); + // Headers end where the first section begins. + h.size_of_headers = 0x1800; + assert_eq!(h.rva_file_len(0x0f00), Some(0x100)); +} + +#[test] +fn rich_header_entries_are_unmasked() { + let d = pe64(); + assert_eq!(rich_header(&d, PE_OFFSET), Some(vec![(0x0104, 30_729, 7), (0x00ff, 40_000, 1)])); + assert_eq!(rich_header(&d, 0x80), None, "Rich lies past the stub"); + let mut no_dans = d.clone(); + no_dans[0x80] ^= 1; + assert_eq!(rich_header(&no_dans, PE_OFFSET), None); + assert_eq!(rich_header(&d[..0x30], PE_OFFSET), None); +} + +#[test] +fn rich_header_is_capped_at_256_entries() { + let mut d = vec![0u8; 0x80 + 16 + 300 * 8 + 8 + 16]; + let entries: Vec<(u16, u16, u32)> = (0..300).map(|i| (1, i, 1)).collect(); + rich(&mut d, 7, &entries); + assert_eq!(rich_header(&d, d.len()).map(|e| e.len()), Some(256)); +} + +#[test] +fn subsystem_names() { + let names: Vec<&str> = [1, 2, 3, 7, 9, 10, 11, 12, 14, 16, 99].into_iter().map(subsystem_name).collect(); + assert_eq!( + names, + [ + "native", + "windows-gui", + "windows-console", + "posix-console", + "windows-ce", + "efi-application", + "efi-boot-driver", + "efi-runtime-driver", + "xbox", + "windows-boot", + "unknown" + ] + ); +} + +#[cfg(feature = "serde")] +#[test] +fn sections_serialize() { + let h = headers(&pe64()).unwrap(); + let value = serde_json::to_value(&h.sections[0]).unwrap(); + assert_eq!(value["name"], ".text"); + assert_eq!(value["rva"], 0x1000); +} + +#[test] +fn damaged_headers_never_panic() { + for m in mutations(&pe64()) { + let _ = has_pe_header(&m); + if let Ok(h) = headers(&m) { + for rva in [0, 0x10, 0x1010, 0x2000, 0x2100, u32::MAX] { + let _ = h.rva_to_offset(rva); + let _ = h.rva_file_len(rva); + let _ = h.image_va(u64::from(rva)); + } + let _ = rich_header(&m, h.pe_offset); + } + let _ = rich_header(&m, usize::MAX); + } +} diff --git a/crates/pe/tests/pe_optional_header_framing.rs b/crates/pe/tests/pe_optional_header_framing.rs new file mode 100644 index 000000000..2cdaa8593 --- /dev/null +++ b/crates/pe/tests/pe_optional_header_framing.rs @@ -0,0 +1,62 @@ +// From Craft Anything crates/formats/tests/pe_optional_header_framing.rs. +use craft_pe as pe; + +fn image(plus: bool, optional_size: usize, declared_dirs: u32) -> Vec { + let opt = 0x98; + let fixed = if plus { 112 } else { 96 }; + let mut data = vec![0; opt + optional_size.max(fixed) + 64]; + data[..2].copy_from_slice(b"MZ"); + data[0x3c..0x40].copy_from_slice(&0x80u32.to_le_bytes()); + data[0x80..0x84].copy_from_slice(b"PE\0\0"); + data[0x94..0x96].copy_from_slice(&(optional_size as u16).to_le_bytes()); + data[opt..opt + 2].copy_from_slice(&(if plus { 0x20bu16 } else { 0x10b }).to_le_bytes()); + data[opt + 68..opt + 70].copy_from_slice(&3u16.to_le_bytes()); + data[opt + fixed - 4..opt + fixed].copy_from_slice(&declared_dirs.to_le_bytes()); + data +} + +#[test] +fn required_optional_header_fields_cannot_be_borrowed_from_the_section_table() { + for plus in [false, true] { + for size in [0, 2, 70, if plus { 111 } else { 95 }] { + assert!(pe::headers(&image(plus, size, 16)).is_err(), "plus={plus}, size={size}"); + } + } +} + +#[test] +fn directory_count_is_bounded_by_complete_entries_in_the_optional_header() { + for plus in [false, true] { + let fixed = if plus { 112 } else { 96 }; + for available in [0, 7, 8, 15] { + let mut data = image(plus, fixed + available, 16); + data[0x98 + fixed..0x98 + fixed + 16].fill(0x55); + let parsed = pe::headers(&data).unwrap(); + assert_eq!(parsed.data_dirs.len(), available / 8, "plus={plus}, available={available}"); + if available >= 8 { + assert_eq!(parsed.data_dirs[0], (0x5555_5555, 0x5555_5555), "plus={plus}, available={available}"); + } + } + } +} + +#[test] +fn zero_or_one_directory_and_unused_optional_bytes_are_valid() { + for plus in [false, true] { + let fixed = if plus { 112 } else { 96 }; + for dirs in [0u32, 1] { + for padding in [0, 12] { + let size = fixed + dirs as usize * 8 + padding; + let mut data = image(plus, size, dirs); + data[0x86..0x88].copy_from_slice(&1u16.to_le_bytes()); + let section = 0x98 + size; + data[section..section + 5].copy_from_slice(b".test"); + let parsed = pe::headers(&data).unwrap(); + assert_eq!(parsed.pe32_plus, plus); + assert_eq!(parsed.subsystem, 3); + assert_eq!(parsed.data_dirs.len(), dirs as usize); + assert_eq!(parsed.sections[0].name, ".test"); + } + } + } +} From a8d29a877960fef3c3a19f9d56b02b54f6f3e3cf Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Mon, 16 Nov 2026 11:44:25 +0100 Subject: [PATCH 2/2] craft-pe: give the header reader its own field helper --- crates/pe/src/bytes.rs | 28 +++++++++++++--------------- 1 file changed, 13 insertions(+), 15 deletions(-) diff --git a/crates/pe/src/bytes.rs b/crates/pe/src/bytes.rs index 971f36133..63aaeed12 100644 --- a/crates/pe/src/bytes.rs +++ b/crates/pe/src/bytes.rs @@ -1,37 +1,35 @@ -//! Checked little-endian reads over untrusted bytes. Every read returns `None` when out of range. +//! Bounds-checked little-endian field reads for the header parser: out of range is `None`. #[derive(Debug, Clone, Copy)] -pub(crate) struct Reader<'a> { - data: &'a [u8], -} +pub(crate) struct Reader<'a>(&'a [u8]); impl<'a> Reader<'a> { pub(crate) fn new(data: &'a [u8]) -> Self { - Reader { data } + Self(data) } + /// `len` bytes at `off`. pub(crate) fn slice(&self, off: usize, len: usize) -> Option<&'a [u8]> { - let end = off.checked_add(len)?; - self.data.get(off..end) + self.0.get(off..off.checked_add(len)?) + } + + fn field(&self, off: usize) -> Option<[u8; N]> { + self.0.get(off..)?.first_chunk::().copied() } pub(crate) fn u8(&self, off: usize) -> Option { - self.data.get(off).copied() - } - - fn arr(&self, off: usize) -> Option<[u8; N]> { - self.slice(off, N)?.try_into().ok() + self.field::<1>(off).map(|[b]| b) } pub(crate) fn u16_le(&self, off: usize) -> Option { - self.arr(off).map(u16::from_le_bytes) + Some(u16::from_le_bytes(self.field(off)?)) } pub(crate) fn u32_le(&self, off: usize) -> Option { - self.arr(off).map(u32::from_le_bytes) + Some(u32::from_le_bytes(self.field(off)?)) } pub(crate) fn u64_le(&self, off: usize) -> Option { - self.arr(off).map(u64::from_le_bytes) + Some(u64::from_le_bytes(self.field(off)?)) } }