diff --git a/crates/xcl/src/loader.rs b/crates/xcl/src/loader.rs index 52c49afe78..3e0f7368b8 100644 --- a/crates/xcl/src/loader.rs +++ b/crates/xcl/src/loader.rs @@ -94,13 +94,17 @@ fn map_image_ex(path: &Path, is_main: bool) -> Result, String> let hdr = (pe.size_of_headers as usize).min(file.len()).min(size); std::ptr::copy_nonoverlapping(file.as_ptr(), base as *mut u8, hdr); for s in &pe.sections { - let raw = (s.raw_size as usize).min(s.mapped_size() as usize); + let mapped = s.mapped_size() as usize; + if s.va as usize + mapped > size { + return fail(format!("{name}: section {} outside the image", s.name)); + } + let raw = (s.raw_size as usize).min(mapped); if raw == 0 { continue; } let src = s.raw_ptr as usize; - if src + raw > file.len() || s.va as usize + raw > size { - return fail(format!("{name}: section {} outside the file/image", s.name)); + if src + raw > file.len() { + return fail(format!("{name}: section {} outside the file", s.name)); } std::ptr::copy_nonoverlapping(file.as_ptr().add(src), (base + s.va as usize) as *mut u8, raw); } @@ -113,19 +117,29 @@ fn map_image_ex(path: &Path, is_main: bool) -> Result, String> Err(e) => return fail(format!("{name}: relocations: {e}")), }; for r in relocs { - let p = base + r.rva as usize; - unsafe { - match r.kind { - pe::IMAGE_REL_BASED_DIR64 => { + let rva = r.rva as usize; + match r.kind { + pe::IMAGE_REL_BASED_DIR64 => { + if rva + 8 > size { + return fail(format!("{name}: relocation @ {:#x} outside image", r.rva)); + } + let p = base + rva; + unsafe { let v = (p as *mut u64).read_unaligned(); (p as *mut u64).write_unaligned((v as i64 + delta) as u64); } - pe::IMAGE_REL_BASED_HIGHLOW => { + } + pe::IMAGE_REL_BASED_HIGHLOW => { + if rva + 4 > size { + return fail(format!("{name}: relocation @ {:#x} outside image", r.rva)); + } + let p = base + rva; + unsafe { let v = (p as *mut u32).read_unaligned(); (p as *mut u32).write_unaligned((v as i64 + delta) as u32); } - k => crate::xlog_warn!("{name}: unsupported relocation type {k} @ {:#x}", r.rva), } + k => crate::xlog_warn!("{name}: unsupported relocation type {k} @ {:#x}", r.rva), } } } @@ -174,12 +188,22 @@ fn map_image_ex(path: &Path, is_main: bool) -> Result, String> } for dll in &all { for e in &dll.entries { + let iat = e.iat_rva as usize; + if iat + 8 > size { + modules::unregister_mapped(base); + return fail(format!("{name}: import IAT slot @ {:#x} outside image", e.iat_rva)); + } let addr = resolver::resolve_import(&dll.dll, &e.what, &name, dll.delay); - unsafe { ((base + e.iat_rva as usize) as *mut u64).write_unaligned(addr as u64) }; + unsafe { ((base + iat) as *mut u64).write_unaligned(addr as u64) }; } if dll.delay && dll.module_handle_rva != 0 { + let hmod = dll.module_handle_rva as usize; + if hmod + 8 > size { + modules::unregister_mapped(base); + return fail(format!("{name}: delay-load module handle @ {:#x} outside image", dll.module_handle_rva)); + } let h = resolver::load_library(&dll.dll).unwrap_or(1); - unsafe { ((base + dll.module_handle_rva as usize) as *mut u64).write_unaligned(h as u64) }; + unsafe { ((base + hmod) as *mut u64).write_unaligned(h as u64) }; } } @@ -209,10 +233,11 @@ fn map_image_ex(path: &Path, is_main: bool) -> Result, String> VirtualProtect(base as *const c_void, pe.size_of_headers as usize, PAGE_READONLY, &mut old); for s in &pe.sections { let len = ((s.mapped_size() as usize) + 0xFFF) & !0xFFF; - if len == 0 { + if len == 0 || s.va as usize >= size { continue; } - VirtualProtect((base + s.va as usize) as *const c_void, len, section_protection(s.characteristics), &mut old); + let protect_len = len.min(size.saturating_sub(s.va as usize)); + VirtualProtect((base + s.va as usize) as *const c_void, protect_len, section_protection(s.characteristics), &mut old); } windows_sys::Win32::System::Diagnostics::Debug::FlushInstructionCache( windows_sys::Win32::System::Threading::GetCurrentProcess(), diff --git a/crates/xcl/src/pe.rs b/crates/xcl/src/pe.rs index 8ff1915691..1b82cfd0ae 100644 --- a/crates/xcl/src/pe.rs +++ b/crates/xcl/src/pe.rs @@ -325,7 +325,7 @@ impl<'a> Pe<'a> { pub fn rva_to_offset(&self, rva: u32) -> Option { match self.layout { Layout::Mapped => { - if (rva as usize) < self.data.len() { + if (self.size_of_image == 0 || rva < self.size_of_image) && (rva as usize) < self.data.len() { Some(rva as usize) } else { None @@ -352,7 +352,17 @@ impl<'a> Pe<'a> { fn rva_tail(&self, rva: u32) -> Option<&'a [u8]> { match self.layout { - Layout::Mapped => self.data.get(rva as usize..), + Layout::Mapped => { + if self.size_of_image != 0 && rva >= self.size_of_image { + return None; + } + let len = if self.size_of_image != 0 { + (self.size_of_image - rva) as usize + } else { + self.data.len().saturating_sub(rva as usize) + }; + self.data.get(rva as usize..).and_then(|s| s.get(..len.min(s.len()))) + } Layout::File => { if rva < self.size_of_headers { let off = rva as usize; @@ -408,8 +418,15 @@ impl<'a> Pe<'a> { fn thunks(&self, int_rva: u32, iat_rva: u32) -> Result, PeError> { let mut out = Vec::new(); let names_rva = if int_rva != 0 { int_rva } else { iat_rva }; + if names_rva == 0 { + return Ok(out); + } for i in 0..65536u32 { - let slot = names_rva.checked_add(i * 8).ok_or(PeError::BadRva(names_rva))?; + let offset = i.checked_mul(8).ok_or(PeError::BadRva(names_rva))?; + let slot = names_rva.checked_add(offset).ok_or(PeError::BadRva(names_rva))?; + if self.size_of_image != 0 && slot.saturating_add(8) > self.size_of_image { + return Err(PeError::BadRva(slot)); + } let v = self.u64_at(slot).ok_or(PeError::BadRva(slot))?; if v == 0 { break; @@ -419,10 +436,16 @@ impl<'a> Pe<'a> { } else { let hn = (v & 0x7FFF_FFFF) as u32; let hint = self.u16_at(hn).ok_or(PeError::BadRva(hn))?; - let name = self.cstr_at(hn.wrapping_add(2)).ok_or(PeError::BadRva(hn))?; + let name_rva = hn.checked_add(2).ok_or(PeError::BadRva(hn))?; + let name = self.cstr_at(name_rva).ok_or(PeError::BadRva(hn))?; ImportName::Name { hint, name } }; - out.push(ImportEntry { iat_rva: iat_rva.checked_add(i * 8).ok_or(PeError::BadRva(iat_rva))?, what }); + let iat_offset = i.checked_mul(8).ok_or(PeError::BadRva(iat_rva))?; + let entry_iat_rva = iat_rva.checked_add(iat_offset).ok_or(PeError::BadRva(iat_rva))?; + if self.size_of_image != 0 && entry_iat_rva.saturating_add(8) > self.size_of_image { + return Err(PeError::BadRva(entry_iat_rva)); + } + out.push(ImportEntry { iat_rva: entry_iat_rva, what }); } Ok(out) } @@ -433,8 +456,15 @@ impl<'a> Pe<'a> { if d.rva == 0 || d.size == 0 { return Ok(out); } + if d.size < 20 || d.rva.checked_add(d.size).is_none() { + return Err(PeError::BadRva(d.rva)); + } for i in 0..4096u32 { - let o = d.rva.checked_add(i * 20).ok_or(PeError::BadRva(d.rva))?; + let pos = i.checked_mul(20).ok_or(PeError::BadRva(d.rva))?; + if 20 > d.size - pos { + return Err(PeError::BadRva(d.rva.checked_add(pos).unwrap_or(d.rva))); + } + let o = d.rva.checked_add(pos).ok_or(PeError::BadRva(d.rva))?; let g = |offset: u32| { let rva = o.checked_add(offset).ok_or(PeError::BadRva(o))?; self.u32_at(rva).ok_or(PeError::BadRva(rva)) @@ -458,8 +488,15 @@ impl<'a> Pe<'a> { if d.rva == 0 || d.size == 0 { return Ok(out); } + if d.size < 32 || d.rva.checked_add(d.size).is_none() { + return Err(PeError::BadRva(d.rva)); + } for i in 0..4096u32 { - let o = d.rva.checked_add(i * 32).ok_or(PeError::BadRva(d.rva))?; + let pos = i.checked_mul(32).ok_or(PeError::BadRva(d.rva))?; + if 32 > d.size - pos { + return Err(PeError::BadRva(d.rva.checked_add(pos).unwrap_or(d.rva))); + } + let o = d.rva.checked_add(pos).ok_or(PeError::BadRva(d.rva))?; let g = |offset: u32| { let rva = o.checked_add(offset).ok_or(PeError::BadRva(o))?; self.u32_at(rva).ok_or(PeError::BadRva(rva)) @@ -493,6 +530,9 @@ impl<'a> Pe<'a> { if d.rva == 0 || d.size == 0 { return Ok(out); } + if d.size < 8 || d.rva.checked_add(d.size).is_none() { + return Err(PeError::BadRva(d.rva)); + } // the block sizes come from the file: a block past the directory's end (or one whose // offsets overflow) is a malformed image, not a panic or a 2^31-entry loop let mut pos = 0u32; @@ -516,7 +556,11 @@ impl<'a> Pe<'a> { if kind == IMAGE_REL_BASED_ABSOLUTE { continue; } - out.push(Reloc { rva: page.checked_add((e & 0x0FFF) as u32).ok_or(PeError::BadRva(at))?, kind }); + let reloc_rva = page.checked_add((e & 0x0FFF) as u32).ok_or(PeError::BadRva(at))?; + if self.size_of_image != 0 && reloc_rva >= self.size_of_image { + return Err(PeError::BadRva(reloc_rva)); + } + out.push(Reloc { rva: reloc_rva, kind }); } pos += block; } @@ -562,6 +606,25 @@ impl<'a> Pe<'a> { let afunc = g(28)?; let anames = g(32)?; let aords = g(36)?; + let check_table = |rva: u32, size: u32| -> Result<(), PeError> { + if rva >= d.rva && rva < d.rva.saturating_add(d.size) { + let pos = rva - d.rva; + if size > d.size - pos { + return Err(PeError::BadRva(rva)); + } + } + if self.size_of_image != 0 && rva.saturating_add(size) > self.size_of_image { + return Err(PeError::BadRva(rva)); + } + Ok(()) + }; + let func_table_size = nfunc.checked_mul(4).ok_or(PeError::BadRva(afunc))?; + check_table(afunc, func_table_size)?; + let name_table_size = nnames.checked_mul(4).ok_or(PeError::BadRva(anames))?; + check_table(anames, name_table_size)?; + let ord_table_size = nnames.checked_mul(2).ok_or(PeError::BadRva(aords))?; + check_table(aords, ord_table_size)?; + let mut functions = Vec::with_capacity(nfunc as usize); for i in 0..nfunc { let rva = i.checked_mul(4).and_then(|o| afunc.checked_add(o)).ok_or(PeError::BadRva(afunc))?; @@ -800,4 +863,76 @@ mod tests { assert!(tls.end_raw >= tls.start_raw); assert!(pe.va_to_rva(tls.address_of_index).is_some()); } + + #[test] + fn truncated_directories_are_rejected() { + // Import directory with size smaller than one descriptor (20 bytes) + let data = directory_at_rva(DIR_IMPORT, 0x1000, &[0; 10]); + let pe = Pe::parse(&data, Layout::File).unwrap(); + assert!(matches!(pe.imports(), Err(PeError::BadRva(_)))); + + // Delay-import directory with size smaller than one descriptor (32 bytes) + let data = directory_at_rva(DIR_DELAY_IMPORT, 0x1000, &[0; 16]); + let pe = Pe::parse(&data, Layout::File).unwrap(); + assert!(matches!(pe.delay_imports(), Err(PeError::BadRva(_)))); + + // Relocation directory with size smaller than one block header (8 bytes) + let data = directory_at_rva(DIR_BASERELOC, 0x1000, &[0; 4]); + let pe = Pe::parse(&data, Layout::File).unwrap(); + assert!(matches!(pe.relocations(), Err(PeError::BadRva(_)))); + + // Export directory with size smaller than export directory structure (40 bytes) + let data = directory_at_rva(DIR_EXPORT, 0x1000, &[0; 30]); + let pe = Pe::parse(&data, Layout::File).unwrap(); + assert!(matches!(pe.exports(), Err(PeError::BadRva(_)))); + } + + #[test] + fn import_directory_without_null_terminator_exceeding_size_is_error() { + // Non-null import descriptor of 20 bytes, followed by only 10 bytes (not enough for 20-byte null descriptor) + let mut payload = vec![0u8; 30]; + payload[0..4].copy_from_slice(&0x1000u32.to_le_bytes()); // int_rva + payload[12..16].copy_from_slice(&0x1000u32.to_le_bytes()); // name_rva + payload[16..20].copy_from_slice(&0x1000u32.to_le_bytes()); // iat_rva + let data = directory_at_rva(DIR_IMPORT, 0x1000, &payload); + let pe = Pe::parse(&data, Layout::File).unwrap(); + assert!(matches!(pe.imports(), Err(PeError::BadRva(_)))); + } + + #[test] + fn delay_import_without_null_terminator_exceeding_size_is_error() { + let mut payload = vec![0u8; 40]; + payload[4..8].copy_from_slice(&0x1000u32.to_le_bytes()); // name_rva + payload[12..16].copy_from_slice(&0x1000u32.to_le_bytes()); // iat_rva + let data = directory_at_rva(DIR_DELAY_IMPORT, 0x1000, &payload); + let pe = Pe::parse(&data, Layout::File).unwrap(); + assert!(matches!(pe.delay_imports(), Err(PeError::BadRva(_)))); + } + + #[test] + fn export_tables_exceeding_directory_bounds_is_error() { + // Export directory claiming 100 functions (400 bytes), but directory size is only 48 bytes + let mut payload = vec![0u8; 48]; + payload[20..24].copy_from_slice(&100u32.to_le_bytes()); // nfunc = 100 + payload[28..32].copy_from_slice(&0x1028u32.to_le_bytes()); // afunc at offset 40 in directory + let data = directory_at_rva(DIR_EXPORT, 0x1000, &payload); + let pe = Pe::parse(&data, Layout::File).unwrap(); + assert!(matches!(pe.exports(), Err(PeError::BadRva(_)))); + } + + #[test] + fn thunks_with_out_of_bounds_iat_slot_is_error() { + // Import descriptor with IAT pointing past size_of_image (0x2000) + let mut payload = vec![0u8; 48]; + payload[0..4].copy_from_slice(&0x1028u32.to_le_bytes()); // int_rva -> points to non-zero thunk + payload[12..16].copy_from_slice(&0x1020u32.to_le_bytes()); // name_rva + payload[16..20].copy_from_slice(&0x7FFF_0000u32.to_le_bytes()); // iat_rva outside image + // thunk entry at 0x1028: ordinal 1 + payload[40..48].copy_from_slice(&(1u64 | (1u64 << 63)).to_le_bytes()); + let mut data = directory_at_rva(DIR_IMPORT, 0x1000, &payload); + // set size_of_image in optional header (opt = 0x58, size_of_image at opt + 56) + data[0x58 + 56..0x58 + 60].copy_from_slice(&0x2000u32.to_le_bytes()); + let pe = Pe::parse(&data, Layout::File).unwrap(); + assert!(matches!(pe.imports(), Err(PeError::BadRva(_)))); + } }