Compare commits

..
Author SHA1 Message Date
Swastick Chowdhury bb1372cd70 loader: validate startup stack and TEB layout before mapping (#77)
Replace the saturating TEB address with checked arithmetic and reject a
stack below address zero, an overflowing TEB range, or a TEB overlapping
the stack before the image is parsed. Name the Win64 TEB field offsets
and add unit tests for layout validation and field placement.

Signed-off-by: Swastick Chowdhury <28708247+Swastickc@users.noreply.github.com>
2026-11-24 15:33:38 +05:30
3 changed files with 136 additions and 126 deletions

No files matched your search

-14
View File
@@ -94,9 +94,6 @@ 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;
/// Host memory budget for all mapped sections of one image. This is a loader policy
/// limit, not a property of the PE format.
const MAX_MAPPED_IMAGE_BYTES: u64 = 256 * 1024 * 1024;
fn read_u16(bytes: &[u8], at: usize) -> u16 {
u16::from_le_bytes([bytes[at], bytes[at + 1]])
@@ -276,17 +273,6 @@ impl ParsedPe {
}
pub(crate) fn load_at_base(&self, bytes: &[u8], base: u64) -> Result<LoadedImage, PeError> {
// Each section becomes a zero-filled host allocation, so bound the total before
// allocating anything. Sections may not overlap, so the sum is the mapped size.
let mapped: u64 = self
.sections
.iter()
.map(|sec| u64::from(sec.virtual_size.max(sec.raw_data_size)))
.sum();
if mapped > MAX_MAPPED_IMAGE_BYTES {
return Err(PeError::SectionMappingError(MemoryError::AllocationFailed));
}
let mut memory = GuestMemory::new();
for sec in &self.sections {
+136 -16
View File
@@ -11,6 +11,14 @@ use crate::{
const STACK_SIZE: usize = 64 * 1024;
const JIT_CAPACITY: usize = 1024 * 1024;
/// The TEB is placed this far above the TLS base and spans two 4 KiB pages.
const TEB_OFFSET: u64 = 0x10000;
const TEB_SIZE: usize = 0x2000;
// Win64 TEB fields (NT_TIB prefix plus the TLS slot) written by the harness.
const TEB_STACK_BASE: u64 = 0x08;
const TEB_STACK_LIMIT: u64 = 0x10;
const TEB_SELF: u64 = 0x30;
const TEB_TLS_POINTER: u64 = 0x58;
/// Guest addresses reserved by the fixture harness.
pub struct StartupLayout {
@@ -79,6 +87,8 @@ pub fn run_synthetic_startup_with_observer(
)
.into());
}
// Reject an impossible layout before parsing or mapping anything.
let (stack_base, teb_base) = layout_regions(&layout)?;
let pe = ParsedPe::parse(bytes)?;
observe(StartupEvent::Parsed {
sections: pe.sections.len(),
@@ -112,24 +122,9 @@ pub fn run_synthetic_startup_with_observer(
)?;
}
let stack_base = layout
.stack_top
.checked_sub(STACK_SIZE as u64)
.ok_or(MemoryError::Overflow)?;
memory.map_region(stack_base, STACK_SIZE, MemoryPermissions::READ_WRITE)?;
// Allocate and initialize Win64 TEB (Thread Environment Block)
// Layout in TEB:
// +0x08: StackBase (highest address)
// +0x10: StackLimit (lowest address)
// +0x30: Self pointer (TEB linear address)
// +0x58: ThreadLocalStoragePointer
let teb_base = layout.tls_base.saturating_add(0x10000);
memory.map_region(teb_base, 0x2000, MemoryPermissions::READ_WRITE)?;
memory.write_u64_bypass(teb_base + 0x08, layout.stack_top)?;
memory.write_u64_bypass(teb_base + 0x10, stack_base)?;
memory.write_u64_bypass(teb_base + 0x30, teb_base)?;
memory.write_u64_bypass(teb_base + 0x58, layout.tls_base)?;
map_teb(memory, teb_base, &layout, stack_base)?;
let mut engine = DbtEngine::new(JIT_CAPACITY)?;
engine.set_import_registry(imports);
@@ -171,3 +166,128 @@ pub fn run_synthetic_startup_with_observer(
dbt_metrics: engine.metrics,
})
}
/// Validate the harness layout and return `(stack_base, teb_base)`.
///
/// The stack occupies `[stack_top - STACK_SIZE, stack_top)` and the TEB
/// `[tls_base + TEB_OFFSET, + TEB_SIZE)`. Both ranges must fit in the address
/// space and must not overlap each other.
fn layout_regions(layout: &StartupLayout) -> Result<(u64, u64), MemoryError> {
let stack_base = layout
.stack_top
.checked_sub(STACK_SIZE as u64)
.ok_or(MemoryError::Overflow)?;
let teb_base = layout
.tls_base
.checked_add(TEB_OFFSET)
.ok_or(MemoryError::Overflow)?;
let teb_end = teb_base
.checked_add(TEB_SIZE as u64)
.ok_or(MemoryError::Overflow)?;
if teb_base < layout.stack_top && stack_base < teb_end {
return Err(MemoryError::OverlappingRegion {
base: teb_base,
size: TEB_SIZE as u64,
});
}
Ok((stack_base, teb_base))
}
/// Map the Win64 TEB and write the fields the harness provides.
fn map_teb(
memory: &mut crate::GuestMemory,
teb_base: u64,
layout: &StartupLayout,
stack_base: u64,
) -> Result<(), MemoryError> {
memory.map_region(teb_base, TEB_SIZE, MemoryPermissions::READ_WRITE)?;
memory.write_u64_bypass(teb_base + TEB_STACK_BASE, layout.stack_top)?;
memory.write_u64_bypass(teb_base + TEB_STACK_LIMIT, stack_base)?;
memory.write_u64_bypass(teb_base + TEB_SELF, teb_base)?;
memory.write_u64_bypass(teb_base + TEB_TLS_POINTER, layout.tls_base)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::GuestMemory;
fn layout(stack_top: u64, tls_base: u64) -> StartupLayout {
StartupLayout {
image_base: 0x1_4000_0000,
stack_top,
tls_base,
}
}
#[test]
fn valid_layout_places_stack_and_teb() {
let regions = layout_regions(&layout(0x2_0001_0000, 0x3_0000_0000));
assert_eq!(regions, Ok((0x2_0000_0000, 0x3_0001_0000)));
}
#[test]
fn stack_below_zero_is_rejected() {
assert_eq!(
layout_regions(&layout(0x8000, 0x3_0000_0000)),
Err(MemoryError::Overflow)
);
}
#[test]
fn teb_address_overflow_is_rejected_not_saturated() {
for tls_base in [u64::MAX, u64::MAX - 0xFFFF, u64::MAX - TEB_OFFSET - 0x1FFF] {
assert_eq!(
layout_regions(&layout(0x2_0001_0000, tls_base)),
Err(MemoryError::Overflow),
"tls_base {tls_base:#x}"
);
}
// The highest TEB that fits ends at u64::MAX: an end of 2^64 is not
// representable, and GuestMemory could not map that range either.
let top = u64::MAX - TEB_OFFSET - TEB_SIZE as u64;
assert!(layout_regions(&layout(0x2_0001_0000, top)).is_ok());
}
#[test]
fn teb_overlapping_stack_is_rejected() {
// TEB at 0x2_0000_8000..0x2_0000_A000 lies inside the stack 0x2_0000_0000..0x2_0001_0000.
let collide = layout(0x2_0001_0000, 0x1_FFFF_8000);
assert!(matches!(
layout_regions(&collide),
Err(MemoryError::OverlappingRegion { .. })
));
// Directly above the stack is fine.
assert!(layout_regions(&layout(0x2_0001_0000, 0x2_0000_0000)).is_ok());
}
#[test]
fn invalid_layout_fails_before_parsing() {
// Empty bytes would fail PE parsing; the layout error must come first.
let err = run_synthetic_startup(
&[],
layout(0x2_0001_0000, u64::MAX),
ImportRegistry::new(),
1,
)
.err()
.expect("startup must fail");
assert_eq!(
err.downcast_ref::<MemoryError>(),
Some(&MemoryError::Overflow)
);
}
#[test]
fn teb_fields_are_at_win64_offsets() {
let l = layout(0x2_0001_0000, 0x3_0000_0000);
let (stack_base, teb) = layout_regions(&l).unwrap();
let mut memory = GuestMemory::new();
map_teb(&mut memory, teb, &l, stack_base).unwrap();
assert_eq!(memory.read_u64(teb + 0x08), Ok(0x2_0001_0000));
assert_eq!(memory.read_u64(teb + 0x10), Ok(0x2_0000_0000));
assert_eq!(memory.read_u64(teb + 0x30), Ok(teb));
assert_eq!(memory.read_u64(teb + 0x58), Ok(0x3_0000_0000));
assert!(memory.read_u8(teb + TEB_SIZE as u64).is_err());
}
}
-96
View File
@@ -1,96 +0,0 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! PE image mapping budget tests (#80).
//!
//! A section's mapped size is max(VirtualSize, SizeOfRawData) and the loader
//! backs it with zero-filled host memory, so a small file can request a large
//! allocation. The loader's documented budget is 256 MiB per image.
use xenora_loader::{MemoryError, ParsedPe, PeError};
const BUDGET: u32 = 256 * 1024 * 1024;
/// An original synthetic image: one 0x200-byte code section at RVA 0x1000 followed by
/// uninitialized sections (no raw data) of the given virtual sizes, packed back to back.
fn build(bss_sizes: &[u32]) -> Vec<u8> {
let mut pe = vec![0u8; 0x400];
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(&(1 + bss_sizes.len() as u16).to_le_bytes());
pe[coff + 16..coff + 18].copy_from_slice(&112u16.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(&0x1000u32.to_le_bytes());
pe[opt + 24..opt + 32].copy_from_slice(&0x1_4000_0000u64.to_le_bytes());
let mut section = |i: usize, va: u32, vsize: u32, raw: u32, flags: u32| {
let h = opt + 112 + i * 40;
pe[h + 8..h + 12].copy_from_slice(&vsize.to_le_bytes());
pe[h + 12..h + 16].copy_from_slice(&va.to_le_bytes());
pe[h + 16..h + 20].copy_from_slice(&(if raw == 0 { 0 } else { 0x200u32 }).to_le_bytes());
pe[h + 20..h + 24].copy_from_slice(&raw.to_le_bytes());
pe[h + 36..h + 40].copy_from_slice(&flags.to_le_bytes());
};
section(0, 0x1000, 0x200, 0x200, 0x6000_0020);
let mut va = 0x2000u32;
for (i, &size) in bss_sizes.iter().enumerate() {
section(i + 1, va, size, 0, 0xC000_0080);
va += size;
}
pe
}
fn over_budget() -> PeError {
PeError::SectionMappingError(MemoryError::AllocationFailed)
}
#[test]
fn small_image_loads() {
let bytes = build(&[0x1000]);
let pe = ParsedPe::parse(&bytes).unwrap();
assert!(pe.load_into_memory(&bytes).is_ok());
}
#[test]
fn image_exactly_at_budget_loads() {
let bytes = build(&[BUDGET - 0x200]);
let pe = ParsedPe::parse(&bytes).unwrap();
assert!(pe.load_into_memory(&bytes).is_ok());
}
#[test]
fn one_byte_over_budget_is_rejected() {
let bytes = build(&[BUDGET - 0x1FF]);
let pe = ParsedPe::parse(&bytes).unwrap();
assert_eq!(pe.load_into_memory(&bytes).err(), Some(over_budget()));
}
#[test]
fn budget_counts_all_sections_together() {
// Three 128 MiB sections: each fits alone, the total (384 MiB) does not.
let bytes = build(&[128 << 20; 3]);
let pe = ParsedPe::parse(&bytes).unwrap();
assert_eq!(pe.load_into_memory(&bytes).err(), Some(over_budget()));
}
#[test]
fn near_4_gib_request_from_a_1_kib_file_is_rejected_before_allocation() {
let bytes = build(&[0xF000_0000]);
assert_eq!(bytes.len(), 0x400);
let pe = ParsedPe::parse(&bytes).expect("headers are valid; only the size is excessive");
assert_eq!(pe.load_into_memory(&bytes).err(), Some(over_budget()));
}
#[test]
fn repository_fixture_is_within_budget() {
let path = concat!(
env!("CARGO_MANIFEST_DIR"),
"/../../fixtures/pe/trusted-runner.exe"
);
let bytes = std::fs::read(path).unwrap();
let pe = ParsedPe::parse(&bytes).unwrap();
assert!(pe.load_into_memory(&bytes).is_ok());
}