diff --git a/crates/loader/src/probe.rs b/crates/loader/src/probe.rs index 9e5c8b7..f14c763 100644 --- a/crates/loader/src/probe.rs +++ b/crates/loader/src/probe.rs @@ -791,17 +791,42 @@ pub fn probe_pe_bytes(bytes: &[u8], config: &ProbeConfig) -> Result Option { for sec in §ions { let max_span = std::cmp::max(sec.virtual_size, sec.raw_data_size); if rva >= sec.virtual_address && rva < sec.virtual_address.saturating_add(max_span) { let off_in_sec = (rva - sec.virtual_address) as usize; - return Some(sec.raw_data_ptr as usize + off_in_sec); + let off = sec.raw_data_ptr as usize + off_in_sec; + if off >= bytes.len() { + return None; + } + return Some(off); } } None }; + // Read a NUL-terminated string that starts at `start`. + // + // Returns `None` when the string starts outside the buffer or is not + // terminated, so a truncated file yields an unreadable name instead of a + // slice that panics. + let read_c_string = |start: usize| -> Option { + if start >= bytes.len() { + return None; + } + let mut end = start; + while end < bytes.len() && bytes[end] != 0 { + end += 1; + } + Some(String::from_utf8_lossy(&bytes[start..end]).into_owned()) + }; + // 1. Relocations Census let mut relocations = RelocationCensus { total_entries: 0, @@ -895,14 +920,11 @@ pub fn probe_pe_bytes(bytes: &[u8], config: &ProbeConfig) -> Result name, + // The name is outside the file or is not NUL-terminated + // within it, which a truncated file can cause. + None => "UNKNOWN.dll".to_string(), }; let category = ProbeReport::categorize_dll(&dll_name); @@ -925,15 +947,13 @@ pub fn probe_pe_bytes(bytes: &[u8], config: &ProbeConfig) -> Result name, + None => "UNKNOWN_SYM".to_string(), } }; diff --git a/crates/loader/tests/probe_truncation.rs b/crates/loader/tests/probe_truncation.rs new file mode 100644 index 0000000..9ff771b --- /dev/null +++ b/crates/loader/tests/probe_truncation.rs @@ -0,0 +1,18 @@ +use xenora_loader::probe::{ProbeConfig, probe_pe_bytes}; + +/// The static probe must never panic on a truncated PE. +/// +/// The fixture is truncated across its whole length, which covers the range +/// where the import directory and the import names overlap the end of the +/// file, and every other range where a name or thunk read computed from the +/// section header can run past the buffer. +#[test] +fn probe_never_panics_on_truncated_input() { + let pe = include_bytes!("../../../fixtures/pe/trusted-runner.exe"); + for len in 1..=pe.len() { + let truncated = &pe[..len]; + // The probe may reject the file or report it with unreadable + // imports, but it must not panic. + let _ = probe_pe_bytes(truncated, &ProbeConfig::default()); + } +}