diff --git a/senbei-engine/src/android/restore/mod.rs b/senbei-engine/src/android/restore/mod.rs index 0f27bd2..d894006 100644 --- a/senbei-engine/src/android/restore/mod.rs +++ b/senbei-engine/src/android/restore/mod.rs @@ -2,6 +2,7 @@ mod artifact; mod constructors; mod error; mod pipeline; +mod verify; pub use error::Error; pub use pipeline::{ diff --git a/senbei-engine/src/android/restore/pipeline.rs b/senbei-engine/src/android/restore/pipeline.rs index bc5ad3c..d8fc6f2 100644 --- a/senbei-engine/src/android/restore/pipeline.rs +++ b/senbei-engine/src/android/restore/pipeline.rs @@ -136,6 +136,11 @@ pub struct ValidationReport { pub dynamic_relocations: usize, pub pltgot_relocations: usize, pub has_louser: bool, + /// Cross-table findings that describe the output's structure without + /// rejecting it: a `PT_LOAD`/`DT_*`/relocation/hash/constructor invariant + /// a linker could not walk. Empty when every table is consistent. These are + /// diagnostics, not a runtime guarantee, and they never fail a restore. + pub diagnostics: Vec, } /// Machine-readable result of the restoration. @@ -2481,6 +2486,12 @@ fn validate_restored_binary( { return invalid("restored ELF table counts do not match materialization report"); } + // Cross-table diagnostics run last and only describe the output: they add + // no new way for restoration to fail. A finding here says a linker could + // not walk a table in these bytes, which is a weaker claim than the hard + // checks above and must not decide whether an image is accepted. + let mut diagnostics = Vec::new(); + super::verify::collect(data, &layout, &mut diagnostics); Ok(ValidationReport { format: "ELF64".to_owned(), machine: "AARCH64".to_owned(), @@ -2490,6 +2501,7 @@ fn validate_restored_binary( dynamic_relocations, pltgot_relocations, has_louser, + diagnostics, }) } diff --git a/senbei-engine/src/android/restore/verify.rs b/senbei-engine/src/android/restore/verify.rs new file mode 100644 index 0000000..33b5168 --- /dev/null +++ b/senbei-engine/src/android/restore/verify.rs @@ -0,0 +1,868 @@ +//! Bounded structural diagnostics for a restored AArch64 ELF. +//! +//! The restore pipeline already rejects a result whose tables do not match the +//! materialization report, whose required sections are absent, or whose +//! protector artefacts (the `SHT_LOUSER` private section, the protector entry +//! point) survive. This module adds the cross-table invariants that a dynamic +//! linker or a disassembler relies on, and that a partially applied fixup +//! container breaks first: +//! +//! * `PT_LOAD` mapping: alignment, file-vs-memory size, file backing, flag +//! agreement with the allocated sections it covers, and no overlaps; +//! * `DT_*` agreement: the tags that describe a table must point at that +//! table's own section, with that section's size; +//! * relocation records: an allowed type for its table, an in-image target, +//! and a symbol index inside the dynamic symbol table; +//! * the symbol hash table: bucket and chain counts that agree with +//! `.dynsym`, so a lookup cannot run off its own table; +//! * `.init_array` / `.fini_array`: whole-pointer sizes, tags that agree with +//! the sections, and a non-zero constructor value that lands in the image. +//! +//! These are *structure* checks. They say a linker could walk the tables; they +//! do not say the library initializes or resolves correctly. In particular the +//! bytes a constructor points at are never inspected, and an undefined symbol +//! is never required to have a local definition — that resolution belongs to +//! the dynamic linker and lives outside the file. +//! +//! Every read is bounds-checked and every loop is capped, so this never panics +//! on a crafted or truncated image. + +use crate::findings::Findings; +use senbei_elf::{ + ELF64_RELA_SIZE, ELF64_SYMBOL_SIZE, ElfLayout, SHT_NOBITS, SectionHeader, read_u32, read_u64, +}; + +/// AArch64 relocation kinds a restored image may carry in its dynamic tables. +const R_AARCH64_ABS64: u32 = 0x101; +const R_AARCH64_GLOB_DAT: u32 = 0x401; +const R_AARCH64_JUMP_SLOT: u32 = 0x402; +const R_AARCH64_RELATIVE: u32 = 0x403; + +const PT_LOAD: u32 = 1; +const PF_X: u32 = 1; +const PF_W: u32 = 2; +const PF_R: u32 = 4; +const SHF_WRITE: u64 = 1; +const SHF_ALLOC: u64 = 2; +const SHF_EXECINSTR: u64 = 4; + +const DT_PLTRELSZ: u64 = 2; +const DT_HASH: u64 = 4; +const DT_STRTAB: u64 = 5; +const DT_SYMTAB: u64 = 6; +const DT_RELA: u64 = 7; +const DT_RELASZ: u64 = 8; +const DT_STRSZ: u64 = 10; +const DT_JMPREL: u64 = 23; +const DT_INIT_ARRAY: u64 = 25; +const DT_FINI_ARRAY: u64 = 26; +const DT_INIT_ARRAYSZ: u64 = 27; +const DT_FINI_ARRAYSZ: u64 = 28; +const DT_GNU_HASH: u64 = 0x6FFF_FEF5; +const DT_VERSYM: u64 = 0x6FFF_FFF0; +const DT_RELACOUNT: u64 = 0x6FFF_FFF9; +const DT_VERNEED: u64 = 0x6FFF_FFFE; + +/// Maximum records walked in one relocation table. +const MAX_RELOCATIONS: u64 = 4_000_000; +/// Maximum dynamic table entries inspected. +const MAX_DYNAMIC_ENTRIES: u64 = 4_096; +/// Maximum constructor slots walked. +const MAX_ARRAY_SLOTS: u64 = 4_096; +/// Maximum GNU-hash buckets inspected. A real image's bucket count is a +/// power of two far below this; the cap only bounds a crafted header. +const MAX_HASH_BUCKETS: u32 = 1 << 20; + +/// One loadable segment, as the kernel would map it. +#[derive(Debug, Clone, Copy)] +struct Segment { + offset: u64, + virtual_address: u64, + file_size: u64, + memory_size: u64, + flags: u32, + alignment: u64, +} + +impl Segment { + fn file_end(&self) -> Option { + self.offset.checked_add(self.file_size) + } + + fn memory_end(&self) -> Option { + self.virtual_address.checked_add(self.memory_size) + } + + fn contains(&self, address: u64, size: u64) -> bool { + self.virtual_address <= address + && address + .checked_add(size) + .is_some_and(|end| end <= self.virtual_address.saturating_add(self.memory_size)) + } + + /// File offset for an address in this segment, if the bytes are backed. + fn file_offset(&self, address: u64, size: u64) -> Option { + let end = address.checked_add(size)?; + if address < self.virtual_address + || end > self.virtual_address.checked_add(self.file_size)? + { + return None; + } + self.offset + .checked_add(address.checked_sub(self.virtual_address)?) + } +} + +/// One restored image, in the terms the checks need. +struct View<'a> { + data: &'a [u8], + segments: Vec, + sections: Vec, + names: Vec, +} + +impl View<'_> { + fn segment_for(&self, address: u64, size: u64) -> Option { + self.segments + .iter() + .copied() + .find(|segment| segment.contains(address, size)) + } + + /// File offset backing `[address, address+size)`, when a segment covers it + /// and the file actually holds the bytes (not just `p_memsz` shadow). + fn offset_of(&self, address: u64, size: u64) -> Option { + let offset = self + .segments + .iter() + .find_map(|segment| segment.file_offset(address, size))?; + usize::try_from(offset).ok() + } + + /// The single section with this name; `None` when absent or duplicated. + /// Duplicates are reported by the caller's required-section lookup. + fn section(&self, name: &str) -> Option<&SectionHeader> { + let mut found = None; + for (index, section_name) in self.names.iter().enumerate() { + if section_name == name { + if found.is_some() { + return None; + } + found = self.sections.get(index); + } + } + found + } +} + +/// Collect every structural defect of a restored image. +/// +/// An empty `out` means the tables are internally consistent. It does not mean +/// the library loads: see the module docs. +/// +/// This never fails and never panics. It reports what it cannot parse as a +/// diagnostic instead of an error, so adding it to the pipeline cannot turn a +/// restore that previously succeeded into a failure. +pub(super) fn collect(data: &[u8], layout: &ElfLayout, out: &mut Vec) { + let mut segments = Vec::new(); + for index in 0..layout.program_header_count { + let Some(offset) = index + .checked_mul(layout.program_header_size) + .and_then(|delta| layout.program_header_offset.checked_add(delta)) + else { + out.push("ELF program header table offset overflows".to_owned()); + return; + }; + let kind = match read_u32(data, offset) { + Ok(kind) => kind, + Err(_) => { + out.push(format!( + "ELF program header {index} is not backed by the file" + )); + return; + } + }; + if kind != PT_LOAD { + continue; + } + let ( + Ok(flags), + Ok(file_offset), + Ok(address), + Ok(file_size), + Ok(memory_size), + Ok(alignment), + ) = ( + read_u32(data, offset + 4), + read_u64(data, offset + 8), + read_u64(data, offset + 0x10), + read_u64(data, offset + 0x20), + read_u64(data, offset + 0x28), + read_u64(data, offset + 0x30), + ) + else { + out.push(format!("PT_LOAD {index} is truncated")); + continue; + }; + segments.push(Segment { + offset: file_offset, + virtual_address: address, + file_size, + memory_size, + flags, + alignment, + }); + } + if segments.is_empty() { + out.push("restored ELF has no PT_LOAD segment".to_owned()); + return; + } + // Section names come from the ELF's own string table. A table that does not + // resolve is reported as a diagnostic and stops the name-dependent checks; + // it is not a restore error here. + let names = match layout.section_names(data) { + Ok(names) => names, + Err(error) => { + out.push(format!("section-name table is unreadable: {error}")); + return; + } + }; + let view = View { + data, + segments, + sections: layout.section_headers.clone(), + names, + }; + // One bounded sink per table group: a table whose every row is corrupt + // cannot flood the report or the allocator, and each group that overflowed + // still says so. The segment invariants are checked even when the dynamic + // table is absent or unreadable. + let mut findings = Findings::new(out); + check_segments(&view, &mut findings); + findings.finish(); + + let dynamic = dynamic_entries(&view); + if dynamic.is_empty() { + return; + } + for check in [ + check_dynamic as fn(&View<'_>, &[(u64, u64)], &mut Findings<'_>), + check_arrays, + ] { + let mut findings = Findings::new(out); + check(&view, &dynamic, &mut findings); + findings.finish(); + } + let mut findings = Findings::new(out); + check_relocations(&view, &mut findings); + findings.finish(); + let mut findings = Findings::new(out); + check_hashes(&view, &mut findings); + findings.finish(); +} + +fn check_segments(view: &View<'_>, out: &mut Findings<'_>) { + let file_len = view.data.len() as u64; + for (index, segment) in view.segments.iter().enumerate() { + if segment.alignment != 0 && !segment.alignment.is_power_of_two() { + out.push(format!( + "PT_LOAD {index} alignment 0x{:X} is not a power of two", + segment.alignment + )); + } + // The loader requires p_offset and p_vaddr to be congruent modulo the + // page alignment; otherwise the mapping cannot be established. + if segment.alignment > 1 + && segment.offset % segment.alignment != segment.virtual_address % segment.alignment + { + out.push(format!( + "PT_LOAD {index} file offset and virtual address are not congruent modulo 0x{:X}", + segment.alignment + )); + } + if segment.file_size > segment.memory_size { + out.push(format!( + "PT_LOAD {index} has p_filesz 0x{:X} greater than p_memsz 0x{:X}", + segment.file_size, segment.memory_size + )); + } + if segment.file_end().is_none_or(|end| end > file_len) { + out.push(format!( + "PT_LOAD {index} file range exceeds the file size 0x{file_len:X}" + )); + } + if segment.memory_end().is_none() { + out.push(format!("PT_LOAD {index} memory range overflows")); + } + if segment.flags & PF_R == 0 { + out.push(format!("PT_LOAD {index} is not readable")); + } + } + + // Sorted by address the mappings must not overlap: two segments covering + // one page is a link-time error, so an output that has it cannot describe + // the image it came from. + let mut sorted = view.segments.clone(); + sorted.sort_by_key(|segment| segment.virtual_address); + for pair in sorted.windows(2) { + let (previous, next) = (pair[0], pair[1]); + if let Some(end) = previous.memory_end() + && end > next.virtual_address + { + out.push(format!( + "PT_LOAD segments overlap: [0x{:X}..0x{end:X}) and [0x{:X}..)", + previous.virtual_address, next.virtual_address + )); + } + } + + // Every allocated section with file contents must be reachable through a + // segment that grants the section's own permissions — otherwise the + // dynamic linker's page protections disagree with what the fixups write. + for (index, section) in view.sections.iter().enumerate() { + if section.section_type == SHT_NOBITS + || section.section_type == 0 + || section.flags & SHF_ALLOC == 0 + || section.size == 0 + { + continue; + } + let Some(segment) = view.segment_for(section.address, section.size) else { + out.push(format!( + "allocated section {index} [0x{:X}..0x{:X}) is not covered by any PT_LOAD", + section.address, + section.address.saturating_add(section.size) + )); + continue; + }; + if segment.flags & PF_R == 0 { + out.push(format!( + "allocated section {index} lies in a non-readable PT_LOAD" + )); + } + if section.flags & SHF_WRITE != 0 && segment.flags & PF_W == 0 { + out.push(format!( + "writable section {index} lies in a read-only PT_LOAD" + )); + } + if section.flags & SHF_EXECINSTR != 0 && segment.flags & PF_X == 0 { + out.push(format!( + "executable section {index} lies in a non-executable PT_LOAD" + )); + } + if view.offset_of(section.address, section.size).is_none() { + out.push(format!( + "allocated section {index} has no file bytes behind its address range" + )); + } + } +} + +/// The dynamic table as `(tag, value)` pairs, up to the null entry. +fn dynamic_entries(view: &View<'_>) -> Vec<(u64, u64)> { + let Some(dynamic) = view.section(".dynamic") else { + return Vec::new(); + }; + let Some(start) = view.offset_of(dynamic.address, 0) else { + return Vec::new(); + }; + let count = (dynamic.size / 16).min(MAX_DYNAMIC_ENTRIES); + let mut entries = Vec::new(); + for index in 0..count { + let Some(offset) = index + .checked_mul(16) + .and_then(|delta| u64::try_from(start).ok()?.checked_add(delta)) + else { + break; + }; + let Ok(offset) = usize::try_from(offset) else { + break; + }; + let (Ok(tag), Ok(value)) = (read_u64(view.data, offset), read_u64(view.data, offset + 8)) + else { + break; + }; + if tag == 0 { + break; + } + entries.push((tag, value)); + } + entries +} + +fn single_tag( + entries: &[(u64, u64)], + tag: u64, + label: &str, + out: &mut Findings<'_>, +) -> Option { + let values: Vec = entries + .iter() + .filter_map(|&(entry_tag, value)| (entry_tag == tag).then_some(value)) + .collect(); + match values.as_slice() { + [] => None, + [value] => Some(*value), + _ => { + out.push(format!("{label} (tag 0x{tag:X}) appears more than once")); + Some(values[0]) + } + } +} + +fn check_dynamic(view: &View<'_>, entries: &[(u64, u64)], out: &mut Findings<'_>) { + for (tag, name, size_tag) in [ + (DT_SYMTAB, ".dynsym", None), + (DT_STRTAB, ".dynstr", Some(DT_STRSZ)), + (DT_RELA, ".rela.dyn", Some(DT_RELASZ)), + (DT_JMPREL, ".rela.plt", Some(DT_PLTRELSZ)), + (DT_VERSYM, ".gnu.version", None), + (DT_VERNEED, ".gnu.version_r", None), + (DT_GNU_HASH, ".gnu.hash", None), + (DT_HASH, ".hash", None), + ] { + let Some(value) = single_tag(entries, tag, name, out) else { + continue; + }; + // A tag naming a section this image does not have is only reported for + // the tags whose section is mandatory; the hash tags are optional, and + // the required-section lookup has already rejected a missing core + // table before this runs. + let Some(section) = view.section(name) else { + continue; + }; + if value != section.address { + out.push(format!( + "tag 0x{tag:X} points at 0x{value:X} but {name} starts at 0x{:X}", + section.address + )); + } + if let Some(size_tag) = size_tag + && let Some(size) = single_tag(entries, size_tag, name, out) + && size != section.size + { + out.push(format!( + "tag 0x{size_tag:X} declares 0x{size:X} bytes but {name} is 0x{:X} bytes", + section.size + )); + } + } + + // DT_RELACOUNT promises the first N records of .rela.dyn are + // R_AARCH64_RELATIVE, which lets the linker skip the whole prefix. + let Some(count) = single_tag(entries, DT_RELACOUNT, "DT_RELACOUNT", out) else { + return; + }; + let Some(rela_dyn) = view.section(".rela.dyn") else { + return; + }; + let total = rela_dyn.size / ELF64_RELA_SIZE as u64; + if count > total { + out.push(format!( + "DT_RELACOUNT {count} exceeds the {total} records in .rela.dyn" + )); + return; + } + for index in 0..count.min(MAX_RELOCATIONS) { + let Some(record) = read_relocation(view, *rela_dyn, index, ".rela.dyn", out) else { + return; + }; + if record.kind != R_AARCH64_RELATIVE { + out.push(format!( + "DT_RELACOUNT prefix record {index} has type 0x{:X}, not R_AARCH64_RELATIVE", + record.kind + )); + return; + } + } +} + +struct Relocation { + offset: u64, + kind: u32, + symbol: u32, +} + +fn read_relocation( + view: &View<'_>, + section: SectionHeader, + index: u64, + label: &str, + out: &mut Findings<'_>, +) -> Option { + let base = view.offset_of(section.address, section.size)?; + let offset = index + .checked_mul(ELF64_RELA_SIZE as u64) + .and_then(|delta| usize::try_from(delta).ok()) + .and_then(|delta| base.checked_add(delta))?; + let (Ok(target), Ok(info)) = (read_u64(view.data, offset), read_u64(view.data, offset + 8)) + else { + out.push(format!("{label} record {index} is not backed by the file")); + return None; + }; + Some(Relocation { + offset: target, + kind: info as u32, + symbol: u32::try_from(info >> 32).unwrap_or(u32::MAX), + }) +} + +fn check_relocations(view: &View<'_>, out: &mut Findings<'_>) { + let symbol_count = view + .section(".dynsym") + .map(|section| section.size / ELF64_SYMBOL_SIZE as u64) + .unwrap_or(0); + for (name, allowed) in [ + ( + ".rela.dyn", + &[R_AARCH64_RELATIVE, R_AARCH64_GLOB_DAT, R_AARCH64_ABS64][..], + ), + (".rela.plt", &[R_AARCH64_JUMP_SLOT, R_AARCH64_RELATIVE][..]), + ] { + let Some(section) = view.section(name) else { + continue; + }; + if section.entry_size != 0 && section.entry_size != ELF64_RELA_SIZE as u64 { + out.push(format!( + "{name} entry size is 0x{:X}, expected 0x{ELF64_RELA_SIZE:X}", + section.entry_size + )); + } + let count = section.size / ELF64_RELA_SIZE as u64; + for index in 0..count.min(MAX_RELOCATIONS) { + let Some(record) = read_relocation(view, *section, index, name, out) else { + return; + }; + if !allowed.contains(&record.kind) { + out.push(format!( + "{name} record {index} has type 0x{:X}, which this table cannot carry", + record.kind + )); + } + // The target is a virtual address a fixup writes to, so it must be + // inside a PT_LOAD. Whether the page is writable at that moment is + // the linker's business (RELRO relaxes it), so it is not checked. + if view.segment_for(record.offset, 8).is_none() { + out.push(format!( + "{name} record {index} targets 0x{:X}, which no PT_LOAD maps", + record.offset + )); + } + if record.kind == R_AARCH64_RELATIVE { + if record.symbol != 0 { + out.push(format!( + "{name} record {index} is R_AARCH64_RELATIVE but names symbol {}", + record.symbol + )); + } + } else if u64::from(record.symbol) >= symbol_count { + // A named relocation must index a real dynamic symbol. The + // symbol itself may stay undefined: the dynamic linker resolves + // it from another module, which is not this file's business. + out.push(format!( + "{name} record {index} references symbol {} outside the {symbol_count}-entry .dynsym", + record.symbol + )); + } + } + } +} + +fn check_hashes(view: &View<'_>, out: &mut Findings<'_>) { + let symbol_count = view + .section(".dynsym") + .map(|section| section.size / ELF64_SYMBOL_SIZE as u64) + .unwrap_or(0); + + if let Some(hash) = view.section(".hash") + && let Some(start) = view.offset_of(hash.address, hash.size) + { + { + let (Ok(buckets), Ok(chains)) = + (read_u32(view.data, start), read_u32(view.data, start + 4)) + else { + out.push(".hash header is truncated".to_owned()); + return; + }; + // The SysV layout is nbucket, nchain, buckets[], chains[]. nchain + // must equal the symbol count or a chain walk leaves the table. + if u64::from(chains) != symbol_count { + out.push(format!( + ".hash nchain {chains} does not match the {symbol_count}-entry .dynsym" + )); + } + let required = 8u64 + .saturating_add(u64::from(buckets).saturating_mul(4)) + .saturating_add(u64::from(chains).saturating_mul(4)); + if required > hash.size { + out.push(format!( + ".hash needs 0x{required:X} bytes for its buckets and chains but declares 0x{:X}", + hash.size + )); + } + } + } + + let Some(hash) = view.section(".gnu.hash") else { + return; + }; + let Some(start) = view.offset_of(hash.address, hash.size) else { + return; + }; + let (Ok(buckets), Ok(symoffset), Ok(bloom_size), Ok(bloom_shift)) = ( + read_u32(view.data, start), + read_u32(view.data, start + 4), + read_u32(view.data, start + 8), + read_u32(view.data, start + 12), + ) else { + out.push(".gnu.hash header is truncated".to_owned()); + return; + }; + if buckets == 0 || !buckets.is_power_of_two() { + out.push(format!( + ".gnu.hash bucket count {buckets} is not a power of two" + )); + } + if bloom_size == 0 || !bloom_size.is_power_of_two() { + out.push(format!( + ".gnu.hash bloom size {bloom_size} is not a power of two" + )); + } + if bloom_shift >= 64 { + out.push(format!( + ".gnu.hash bloom shift {bloom_shift} is not below the word size" + )); + } + let header = 16u64 + .saturating_add(u64::from(bloom_size).saturating_mul(8)) + .saturating_add(u64::from(buckets).saturating_mul(4)); + if header > hash.size { + out.push(format!( + ".gnu.hash needs 0x{header:X} bytes for its header and buckets but declares 0x{:X}", + hash.size + )); + return; + } + if u64::from(symoffset) > symbol_count { + out.push(format!( + ".gnu.hash symoffset {symoffset} exceeds the {symbol_count}-entry .dynsym" + )); + return; + } + // Chains follow the buckets, one per symbol from `symoffset` on. + let chains = symbol_count.saturating_sub(u64::from(symoffset)); + let required = header.saturating_add(chains.saturating_mul(4)); + if required > hash.size { + out.push(format!( + ".gnu.hash needs 0x{required:X} bytes for {chains} chain entries but declares 0x{:X}", + hash.size + )); + } + let bucket_at = start + .saturating_add(16) + .saturating_add((u64::from(bloom_size) * 8) as usize); + for index in 0..buckets.min(MAX_HASH_BUCKETS) { + let Some(at) = u64::from(index) + .checked_mul(4) + .and_then(|delta| u64::try_from(bucket_at).ok()?.checked_add(delta)) + .and_then(|at| usize::try_from(at).ok()) + else { + break; + }; + let Ok(bucket) = read_u32(view.data, at) else { + break; + }; + // A bucket pointing past the symbol table sends the lookup off the end. + if bucket != 0 && u64::from(bucket) >= symbol_count { + out.push(format!( + ".gnu.hash bucket {index} points at symbol {bucket}, outside the {symbol_count}-entry .dynsym" + )); + } + } +} + +/// Check `.init_array` / `.fini_array` framing and the constructor pointers. +/// +/// Only the pointer is validated, and only when it is non-zero: the bytes a +/// constructor points at are never examined, and a zero slot is a legitimate +/// remnant of a partially materialized image. +fn check_arrays(view: &View<'_>, entries: &[(u64, u64)], out: &mut Findings<'_>) { + for (name, address_tag, size_tag) in [ + (".init_array", DT_INIT_ARRAY, DT_INIT_ARRAYSZ), + (".fini_array", DT_FINI_ARRAY, DT_FINI_ARRAYSZ), + ] { + let section = view.section(name).copied(); + let tag_address = single_tag(entries, address_tag, name, out); + let tag_size = single_tag(entries, size_tag, name, out); + let Some(section) = section else { + if let Some(value) = tag_address { + out.push(format!( + "tag 0x{address_tag:X} points at 0x{value:X} but the image has no {name}" + )); + } + continue; + }; + if let Some(value) = tag_address + && section.address != value + { + out.push(format!( + "tag 0x{address_tag:X} points at 0x{value:X} but {name} starts at 0x{:X}", + section.address + )); + } + if section.size % 8 != 0 { + out.push(format!( + "{name} size 0x{:X} is not a whole number of pointers", + section.size + )); + } + if let Some(size) = tag_size + && section.size != 0 + && size != section.size + { + out.push(format!( + "tag 0x{size_tag:X} declares 0x{size:X} bytes but {name} is 0x{:X} bytes", + section.size + )); + } + let Some(start) = view.offset_of(section.address, section.size) else { + continue; + }; + let slots = (section.size / 8).min(MAX_ARRAY_SLOTS); + for slot in 0..slots { + let Some(at) = slot + .checked_mul(8) + .and_then(|delta| u64::try_from(start).ok()?.checked_add(delta)) + .and_then(|at| usize::try_from(at).ok()) + else { + break; + }; + let Ok(value) = read_u64(view.data, at) else { + break; + }; + if value == 0 { + continue; + } + if view.segment_for(value, 1).is_none() { + out.push(format!( + "{name} slot {slot} holds 0x{value:X}, which no PT_LOAD maps" + )); + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn segment_containment_is_half_open_and_overflow_safe() { + let segment = Segment { + offset: 0x1000, + virtual_address: 0x2000, + file_size: 0x100, + memory_size: 0x200, + flags: PF_R, + alignment: 0x1000, + }; + assert!(segment.contains(0x2000, 1)); + assert!(segment.contains(0x21FF, 1)); + assert!(!segment.contains(0x2200, 1), "end is exclusive"); + assert!(!segment.contains(0x1FFF, 1), "before the segment"); + assert!( + !segment.contains(0x21FF, 2), + "a range may not straddle the end" + ); + assert!(!segment.contains(u64::MAX, 2), "overflow is not contained"); + assert_eq!(segment.memory_end(), Some(0x2200)); + assert_eq!(segment.file_end(), Some(0x1100)); + } + + #[test] + fn segment_file_offset_only_covers_file_backed_bytes() { + let segment = Segment { + offset: 0x1000, + virtual_address: 0x2000, + file_size: 0x100, + memory_size: 0x200, + flags: PF_R, + alignment: 0x1000, + }; + assert_eq!(segment.file_offset(0x2000, 1), Some(0x1000)); + assert_eq!(segment.file_offset(0x20FF, 1), Some(0x10FF)); + // Beyond p_filesz but inside p_memsz: the zero-fill tail has no bytes. + assert_eq!(segment.file_offset(0x2100, 1), None); + assert_eq!(segment.file_offset(0x20FF, 2), None); + assert_eq!(segment.file_offset(0x1FFF, 1), None); + } + + #[test] + fn single_tag_detects_duplicates() { + let mut sink = Vec::new(); + let entries = [(DT_STRTAB, 0x100u64), (DT_STRTAB, 0x200), (DT_STRSZ, 0x40)]; + assert_eq!( + single_tag( + &entries, + DT_STRTAB, + "DT_STRTAB", + &mut Findings::new(&mut sink) + ), + Some(0x100) + ); + assert_eq!(sink.len(), 1); + assert!(sink[0].contains("more than once"), "{sink:?}"); + sink.clear(); + assert_eq!( + single_tag( + &entries, + DT_SYMTAB, + "DT_SYMTAB", + &mut Findings::new(&mut sink) + ), + None + ); + assert!(sink.is_empty()); + } + + #[test] + fn empty_image_reports_a_single_missing_segment() { + let layout = ElfLayout { + entrypoint: 0, + program_header_offset: 0, + program_header_size: 0x38, + program_header_count: 0, + program_headers: Vec::new(), + section_headers: Vec::new(), + section_name_index: 0, + private_section_index: usize::MAX, + }; + let data = [0_u8; 0x40]; + let mut out = Vec::new(); + collect(&data, &layout, &mut out); + assert_eq!(out.len(), 1, "{out:?}"); + assert!(out[0].contains("no PT_LOAD")); + } + + #[test] + fn truncated_program_header_table_is_reported_not_panicking() { + let layout = ElfLayout { + entrypoint: 0, + program_header_offset: 0x1000, + program_header_size: 0x38, + program_header_count: 1, + program_headers: Vec::new(), + section_headers: Vec::new(), + section_name_index: 0, + private_section_index: usize::MAX, + }; + let data = [0_u8; 0x40]; + let mut out = Vec::new(); + collect(&data, &layout, &mut out); + assert!( + out.iter() + .any(|message| message.contains("not backed by the file")), + "{out:?}" + ); + } +} diff --git a/senbei-engine/src/findings.rs b/senbei-engine/src/findings.rs new file mode 100644 index 0000000..010074f --- /dev/null +++ b/senbei-engine/src/findings.rs @@ -0,0 +1,246 @@ +//! A bounded sink for post-recovery structural diagnostics. +//! +//! Every walker in the integrity and ELF-verification passes visits a table +//! whose entry count comes from the output's own headers. The entry loops are +//! already capped, but a corrupt table can make *every* entry a defect — a +//! relocation block of 32 Ki entries of an undefined type, a thunk table whose +//! names are all ciphertext, a `.rela.dyn` whose symbols all fall out of range. +//! Formatting one message per row allocates a string per row, so a crafted +//! image could exhaust memory long before the entry cap is reached. +//! +//! [`Findings`] bounds that: a caller creating one per directory/table gets at +//! most [`MAX_PER_TABLE`] messages plus a single line saying how many were +//! withheld. Real images have a handful of findings at most, so the cap never +//! hides anything a reader would act on — and the "suppressed" line means a +//! truncated list is never mistaken for an exhaustive one. + +/// Maximum messages one table may contribute. +pub(crate) const MAX_PER_TABLE: usize = 16; + +/// A message sink that stops recording — and stops the caller's expensive +/// per-entry work — once it is full. +pub(crate) struct Findings<'a> { + out: &'a mut Vec, + budget: usize, + suppressed: usize, + /// A walker queried [`Findings::wants_more`] on a full sink, i.e. it + /// abandoned rows it never examined. Distinct from `suppressed`, which + /// counts messages that were formatted and dropped. + skipped: bool, + /// Drop everything and record nothing. Used by a walk that only needs a + /// count (e.g. comparing an IAT's length against its lookup table), so it + /// allocates nothing at all and never reports suppression. + silent: bool, +} + +impl<'a> Findings<'a> { + /// A recording sink with room for [`MAX_PER_TABLE`] messages. + pub(crate) fn new(out: &'a mut Vec) -> Self { + Self { + out, + budget: MAX_PER_TABLE, + suppressed: 0, + skipped: false, + silent: false, + } + } + + /// A discard-everything sink borrowing the same output as `self`, for a + /// sub-walk that only needs a count (the IAT-vs-lookup comparison). + pub(crate) fn silenced(&mut self) -> Findings<'_> { + Findings { + out: self.out, + budget: 0, + suppressed: 0, + skipped: false, + silent: true, + } + } + + pub(crate) fn push(&mut self, message: impl Into) { + if self.silent { + return; + } + if self.budget == 0 { + self.suppressed += 1; + return; + } + self.budget -= 1; + self.out.push(message.into()); + } + + /// True while a further per-entry finding would still be recorded. + /// + /// Walkers gate the per-entry work on this so that once the report is full + /// they stop classifying names / decoding entries instead of computing + /// strings that would be dropped. Asking a full sink is itself the signal + /// that rows were left unexamined: a walker that breaks out here never + /// reaches [`Findings::push`], so nothing would otherwise record that the + /// list is truncated. That is why this takes `&mut self` — the query marks + /// the truncation, so [`Findings::finish`] can still say so. + pub(crate) fn wants_more(&mut self) -> bool { + if self.silent { + return false; + } + if self.budget == 0 { + self.skipped = true; + return false; + } + true + } + + /// Close the sink. + /// + /// Emits an exact count only for messages that were actually formatted and + /// dropped. When a walker instead stopped early (its remaining rows were + /// never checked, so no count exists to report), emits a generic line — the + /// reader must not mistake a full list for an exhaustive one. + pub(crate) fn finish(self) { + if self.suppressed != 0 { + self.out.push(format!( + "{} further defect(s) in this table were suppressed", + self.suppressed + )); + } + if self.skipped { + self.out + .push("remaining entries in this table were not checked".to_owned()); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn sink_caps_messages_and_reports_the_remainder() { + let mut out = Vec::new(); + let mut findings = Findings::new(&mut out); + for index in 0..(MAX_PER_TABLE + 5) { + findings.push(format!("defect {index}")); + } + findings.finish(); + assert_eq!(out.len(), MAX_PER_TABLE + 1, "{out:?}"); + assert!(out[MAX_PER_TABLE].contains("5 further defect(s)")); + } + + #[test] + fn sink_without_overflow_adds_no_summary_line() { + let mut out = Vec::new(); + let mut findings = Findings::new(&mut out); + findings.push("only defect"); + findings.finish(); + assert_eq!(out, ["only defect"]); + } + + #[test] + fn full_sink_stops_requesting_per_entry_work() { + let mut out = Vec::new(); + let mut findings = Findings::new(&mut out); + assert!(findings.wants_more()); + for index in 0..MAX_PER_TABLE { + findings.push(format!("defect {index}")); + } + assert!( + !findings.wants_more(), + "a full sink must stop per-entry work" + ); + findings.finish(); + } + + #[test] + fn silent_sink_records_nothing_and_allocates_no_summary() { + let mut out = Vec::new(); + { + let mut parent = Findings::new(&mut out); + let mut findings = parent.silenced(); + assert!(!findings.wants_more()); + for index in 0..(MAX_PER_TABLE * 4) { + findings.push(format!("defect {index}")); + } + findings.finish(); + } + assert!(out.is_empty(), "{out:?}"); + } + + #[test] + fn early_exit_on_a_full_sink_still_marks_the_list_as_truncated() { + // A walker that stops at `wants_more()` never calls `push`, so there is + // no count to report — but the list is not exhaustive and `finish` must + // say so, otherwise 16 findings look like the whole story. + let mut out = Vec::new(); + let mut findings = Findings::new(&mut out); + for index in 0..MAX_PER_TABLE { + findings.push(format!("defect {index}")); + } + assert!(!findings.wants_more()); + findings.finish(); + assert_eq!(out.len(), MAX_PER_TABLE + 1, "{out:?}"); + assert_eq!( + out[MAX_PER_TABLE], "remaining entries in this table were not checked", + "a skipped tail gets a generic line, not an invented count" + ); + assert!( + !out[MAX_PER_TABLE].contains("0 further"), + "a skipped tail must not claim a suppression count" + ); + } + + #[test] + fn sink_below_cap_marks_no_truncation_when_polled() { + // Polling `wants_more` while there is budget must not by itself imply + // truncation. + let mut out = Vec::new(); + let mut findings = Findings::new(&mut out); + for _ in 0..MAX_PER_TABLE { + assert!(findings.wants_more()); + findings.push("defect"); + } + findings.finish(); + assert_eq!(out.len(), MAX_PER_TABLE, "{out:?}"); + assert!(out.iter().all(|line| line.starts_with("defect")), "{out:?}"); + } + + #[test] + fn dropped_messages_and_skipped_rows_report_both() { + // A walker that both formatted-too-many and then gave up gets the exact + // count for the dropped strings and the generic line for the unread + // rows, in that order. + let mut out = Vec::new(); + let mut findings = Findings::new(&mut out); + for index in 0..(MAX_PER_TABLE + 3) { + findings.push(format!("defect {index}")); + } + assert!(!findings.wants_more()); + findings.finish(); + assert_eq!(out.len(), MAX_PER_TABLE + 2, "{out:?}"); + assert!( + out[MAX_PER_TABLE].contains("3 further defect(s)"), + "{out:?}" + ); + assert_eq!( + out[MAX_PER_TABLE + 1], + "remaining entries in this table were not checked" + ); + } + + #[test] + fn silent_sink_polling_marks_no_truncation() { + let mut out = Vec::new(); + { + let mut parent = Findings::new(&mut out); + let mut findings = parent.silenced(); + assert!(!findings.wants_more()); + findings.finish(); + } + assert!(out.is_empty(), "{out:?}"); + } + + #[test] + fn zero_length_table_produces_nothing() { + let mut out = Vec::new(); + Findings::new(&mut out).finish(); + assert!(out.is_empty()); + } +} diff --git a/senbei-engine/src/lib.rs b/senbei-engine/src/lib.rs index 43cfd06..277b8b2 100644 --- a/senbei-engine/src/lib.rs +++ b/senbei-engine/src/lib.rs @@ -1,6 +1,7 @@ //! Platform-specific unpacking engines. pub mod android; +mod findings; mod panic_capture; pub mod profile; pub mod windows; diff --git a/senbei-engine/src/windows/integrity/clr.rs b/senbei-engine/src/windows/integrity/clr.rs new file mode 100644 index 0000000..e311004 --- /dev/null +++ b/senbei-engine/src/windows/integrity/clr.rs @@ -0,0 +1,477 @@ +//! Bounded structural diagnostics for the CLR (COR20) metadata of a managed PE. +//! +//! A managed assembly reaches the CLR, not the native loader, so the loader +//! checks in the parent module do not describe it. The CLR first reads the +//! COR20 header, then the BSJB root, then the stream headers, and only then +//! the `#~` table stream. Each of those steps has a size or alignment the file +//! itself must satisfy; a stream whose header claims a range past the metadata +//! blob is rejected with `BadImageFormatException` before any IL runs. +//! +//! These are *structure* checks, not a guarantee that the assembly will load: +//! the metadata is not semantically validated (no table-column walk, no heap +//! contents, no signature decoding). They only detect regions the CLR could +//! not even enumerate — the signature of a `.text` pass that scribbled over +//! metadata the protector had copied through verbatim. +//! +//! All reads are bounds-checked and every loop is capped. + +use super::rd_u32; +use crate::findings::Findings; + +/// BSJB root: 4-byte signature, u16 major/minor, u32 reserved, u32 version +/// length, then the NUL-padded version string. +const BSJB_FIXED: u32 = 16; +/// A stream header is an offset, a size, and a NUL-terminated name that the +/// ECMA-335 layout pads to a 4-byte boundary. +const STREAM_HEADER_MIN: u32 = 8; +/// Real assemblies carry five streams (`#~`, `#Strings`, `#US`, `#GUID`, +/// `#Blob`, plus `#-` in unoptimized builds). The cap only stops a corrupt +/// stream count from walking past the metadata blob. +const MAX_STREAMS: u32 = 64; +const MAX_STREAM_NAME: u32 = 32; +/// `#~` fixed header: reserved u32, major u8, minor u8, heap sizes u8, +/// reserved u8, valid u64, sorted u64 — then one u32 row count per set bit. +const TABLES_HEADER: u32 = 24; +const TABLES_HEADER_SIZE: u32 = 24; +/// The widest table index in ECMA-335 II.22 is `#~` bit 44 (GenericParamConstraint). +const MAX_TABLE_BIT: u32 = 44; +/// Heap-size flag bits in the `#~` header. +const HEAP_STRING: u8 = 0x01; +const HEAP_GUID: u8 = 0x02; +const HEAP_BLOB: u8 = 0x04; + +/// The metadata blob `[start, start+len)` inside the output file. +pub(super) struct Metadata<'a> { + pub(super) data: &'a [u8], + pub(super) start: usize, + pub(super) len: usize, +} + +impl Metadata<'_> { + fn bytes(&self) -> &[u8] { + self.data + .get(self.start..self.start.saturating_add(self.len)) + .unwrap_or(&[]) + } + + fn u32(&self, offset: u32) -> Option { + let local = self.data.get(self.start.checked_add(offset as usize)?..)?; + rd_u32(local, 0) + } + + fn u64(&self, offset: u32) -> Option { + let bytes = self + .bytes() + .get(offset as usize..(offset as usize).checked_add(8)?)?; + Some(u64::from_le_bytes(bytes.try_into().ok()?)) + } + + fn slice(&self, offset: u32, len: u32) -> Option<&[u8]> { + let start = offset as usize; + let end = start.checked_add(len as usize)?; + if end > self.len { + return None; + } + self.bytes().get(start..end) + } +} + +/// One declared metadata stream. +struct Stream<'a> { + name: &'a [u8], + offset: u32, + size: u32, +} + +/// Walk the BSJB header and every stream header, appending structural defects. +/// +/// `out` receives one message per defect; an empty `out` means the CLR would +/// be able to enumerate every stream. +pub(super) fn collect(metadata: &Metadata<'_>, out: &mut Findings<'_>) { + if metadata.slice(0, 4) != Some(b"BSJB") { + // The parent module reports a missing signature as fatal; nothing + // below can be parsed meaningfully. + return; + } + let version_length = match metadata.u32(12) { + Some(value) => value, + None => { + out.push("CLR metadata BSJB header is truncated".to_owned()); + return; + } + }; + // The version string is NUL-padded to a 4-byte boundary, followed by the + // flags and stream-count words. + let strings_at = BSJB_FIXED + .checked_add(version_length) + .and_then(|value| Some(value.checked_add(3)? & !3)); + let Some(flags_at) = strings_at else { + out.push("CLR metadata version length overflows".to_owned()); + return; + }; + // flags (u16) + stream count (u16) immediately follow the version string. + let Some(trailer) = metadata.slice(flags_at, 4) else { + out.push("CLR metadata version string runs past the metadata blob".to_owned()); + return; + }; + let stream_count = u16::from_le_bytes([trailer[2], trailer[3]]); + let Some(mut cursor) = flags_at.checked_add(4) else { + out.push("CLR metadata stream table offset overflows".to_owned()); + return; + }; + if u32::from(stream_count) > MAX_STREAMS { + out.push(format!( + "CLR metadata declares {stream_count} streams (more than {MAX_STREAMS})" + )); + return; + } + let mut streams: Vec> = Vec::with_capacity(stream_count as usize); + for index in 0..u32::from(stream_count) { + let Some(header) = metadata.slice(cursor, STREAM_HEADER_MIN) else { + out.push(format!( + "CLR metadata stream header {index} runs past the metadata blob" + )); + return; + }; + let offset = u32::from_le_bytes([header[0], header[1], header[2], header[3]]); + let size = u32::from_le_bytes([header[4], header[5], header[6], header[7]]); + let name_at = cursor.saturating_add(STREAM_HEADER_MIN); + let Some(name_len) = metadata + .slice(name_at, 1) + .and_then(|_| find_nul(metadata, name_at, MAX_STREAM_NAME)) + else { + out.push(format!( + "CLR metadata stream {index} name is unterminated within {MAX_STREAM_NAME} bytes" + )); + return; + }; + let name = metadata.slice(name_at, name_len).unwrap_or_default(); + if name.is_empty() || !name.iter().all(|&byte| (0x20..0x7F).contains(&byte)) { + out.push(format!( + "CLR metadata stream {index} name is empty or not printable ASCII" + )); + } + // Stream headers are 4-byte aligned; the name plus its NUL terminator + // is padded out to the next boundary. + let padded = name_len + .checked_add(1) + .and_then(|value| Some(value.checked_add(3)? & !3)) + .unwrap_or(name_len); + cursor = name_at.saturating_add(padded); + // The CLR rejects a stream whose declared range leaves the blob. + let end = offset.checked_add(size); + if end.is_none_or(|end| u64::from(end) > metadata.len as u64) { + out.push(format!( + "CLR metadata stream {} [0x{offset:X}..0x{:X}] extends past the metadata blob (0x{:X} bytes)", + escape(name), + offset.saturating_add(size), + metadata.len + )); + } + streams.push(Stream { name, offset, size }); + } + + // The CLR requires a tables stream and the heaps that stream's header + // flags claim to reference. + let tables = streams.iter().find(|stream| stream.name == b"#~"); + let unoptimized = streams.iter().find(|stream| stream.name == b"#-"); + let Some(tables) = tables.or(unoptimized) else { + out.push("CLR metadata has neither a '#~' nor a '#-' tables stream".to_owned()); + return; + }; + let heap = |name: &[u8]| streams.iter().any(|stream| stream.name == name); + if !heap(b"#Strings") { + out.push("CLR metadata has no '#Strings' heap".to_owned()); + } + if !heap(b"#GUID") { + out.push("CLR metadata has no '#GUID' heap".to_owned()); + } + if !heap(b"#Blob") { + out.push("CLR metadata has no '#Blob' heap".to_owned()); + } + collect_tables(metadata, tables, out); +} + +fn find_nul(metadata: &Metadata<'_>, offset: u32, limit: u32) -> Option { + // The window is clamped to the blob: a name near the end must not be + // reported as unterminated just because fewer than `limit` bytes remain. + let start = offset as usize; + let available = metadata.len.checked_sub(start)?; + let window = metadata.slice(offset, u32::try_from(available.min(limit as usize)).ok()?)?; + window + .iter() + .position(|&byte| byte == 0) + .and_then(|index| u32::try_from(index).ok()) +} + +fn escape(name: &[u8]) -> String { + name.iter() + .map(|&byte| { + if (0x20..0x7F).contains(&byte) { + char::from(byte) + } else { + '.' + } + }) + .collect() +} + +/// Validate the `#~` (or `#-`) tables stream header and its row-count array. +/// +/// The columns themselves are not decoded: doing so would require the full +/// ECMA-335 schema and buys little, because a corrupted schema almost always +/// breaks one of the framing invariants below first. +fn collect_tables(metadata: &Metadata<'_>, tables: &Stream<'_>, out: &mut Findings<'_>) { + let label = escape(tables.name); + let Some(header) = metadata.slice(tables.offset, TABLES_HEADER) else { + out.push(format!( + "CLR '{label}' stream is shorter than its {TABLES_HEADER}-byte header" + )); + return; + }; + if header[0..4] != [0, 0, 0, 0] { + out.push(format!("CLR '{label}' header reserved field is not zero")); + } + let major = header[4]; + if major != 2 { + out.push(format!( + "CLR '{label}' table schema major version is {major} (expected 2)" + )); + } + // The heap-size byte selects 2-byte vs 4-byte heap indices. Bit 0x40 is + // reserved for an extra-data stream that the shipped runtimes do not use, + // so only the three defined heap bits are checked here. The trailing + // reserved byte is deliberately not checked: real optimized assemblies in + // the wild carry values other than the ECMA-335 default of 1. + let heap_sizes = header[6]; + if heap_sizes & !(HEAP_STRING | HEAP_GUID | HEAP_BLOB) != 0 { + out.push(format!( + "CLR '{label}' header heap-size flags 0x{heap_sizes:02X} set undefined bits" + )); + } + let Some(valid) = metadata.u64(tables.offset.saturating_add(8)) else { + out.push(format!("CLR '{label}' header valid mask is truncated")); + return; + }; + // Sorted is a *hint*: writers are free to set it for tables they did not + // declare (and real assemblies do), so it is not checked against `valid`. + if valid == 0 { + out.push(format!("CLR '{label}' header declares no tables")); + } + let undefined = valid >> (MAX_TABLE_BIT + 1); + if undefined != 0 { + out.push(format!( + "CLR '{label}' valid mask sets undefined table bits (0x{undefined:X})" + )); + } + // One row count per set bit, in ascending table-bit order. A table may + // legitimately be present with zero rows, so the counts themselves are not + // inspected — only whether the stream is long enough to hold them. + let row_tables = valid.count_ones(); + let rows_bytes = row_tables.saturating_mul(4); + if metadata + .slice(tables.offset.saturating_add(TABLES_HEADER_SIZE), rows_bytes) + .is_none() + { + out.push(format!( + "CLR '{label}' row-count array ({row_tables} tables) runs past the metadata blob" + )); + } + // The tables stream itself must hold its header and row counts. + if tables.size < TABLES_HEADER_SIZE.saturating_add(rows_bytes) { + out.push(format!( + "CLR '{label}' stream size 0x{:X} cannot hold {row_tables} row count(s)", + tables.size + )); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Padded size of a NUL-terminated name, per the CLR's 4-byte alignment. + fn padded_name(name: &[u8]) -> usize { + (name.len() + 1 + 3) & !3 + } + + /// Header size of a BSJB blob carrying `streams` and this version string. + fn header_size(version: &str, streams: &[&[u8]]) -> usize { + 16 + padded_name(version.as_bytes()) + + 4 + + streams + .iter() + .map(|name| 8 + padded_name(name)) + .sum::() + } + + /// Build a BSJB blob. Stream bodies are appended by the caller at the + /// offsets returned by [`header_size`]; `bodies` places them here so the + /// stream table can name real ranges. + fn bsjb(version: &str, bodies: &[(&[u8], Vec)]) -> Vec { + let names: Vec<&[u8]> = bodies.iter().map(|(name, _)| *name).collect(); + let mut header = header_size(version, &names); + let mut offsets = Vec::with_capacity(bodies.len()); + for (_, body) in bodies { + offsets.push(header); + header += body.len(); + } + let mut blob = Vec::new(); + blob.extend_from_slice(b"BSJB"); + blob.extend_from_slice(&1_u16.to_le_bytes()); // major + blob.extend_from_slice(&1_u16.to_le_bytes()); // minor + blob.extend_from_slice(&0_u32.to_le_bytes()); // reserved + let version_bytes = version.as_bytes(); + let padded = padded_name(version_bytes); + blob.extend_from_slice(&(padded as u32).to_le_bytes()); + blob.extend_from_slice(version_bytes); + blob.resize(blob.len() + (padded - version_bytes.len()), 0); + blob.extend_from_slice(&0_u16.to_le_bytes()); // flags + blob.extend_from_slice(&(bodies.len() as u16).to_le_bytes()); + for ((name, body), offset) in bodies.iter().zip(&offsets) { + blob.extend_from_slice(&(*offset as u32).to_le_bytes()); + blob.extend_from_slice(&(body.len() as u32).to_le_bytes()); + let start = blob.len(); + blob.extend_from_slice(name); + blob.push(0); + blob.resize(start + padded_name(name), 0); + } + for (_, body) in bodies { + blob.extend_from_slice(body); + } + blob + } + + /// A `#~` stream body: reserved, major/minor/heaps/reserved, valid, + /// sorted, then one row count per set bit. + fn tables_body(valid: u64, rows: &[u32]) -> Vec { + let mut body = vec![0, 0, 0, 0, 2, 0, 0x05, 1]; + body.extend_from_slice(&valid.to_le_bytes()); + body.extend_from_slice(&0_u64.to_le_bytes()); + for row in rows { + body.extend_from_slice(&row.to_le_bytes()); + } + body + } + + /// A minimal well-formed blob: the four streams the CLR requires, with a + /// `#~` header describing one table with one row. + fn well_formed() -> Vec { + bsjb( + "v4.0.30319", + &[ + (b"#~", tables_body(1 << 0, &[1])), + (b"#Strings", vec![0; 4]), + (b"#GUID", vec![0; 16]), + (b"#Blob", vec![0; 4]), + ], + ) + } + + #[test] + fn well_formed_metadata_produces_no_findings() { + let blob = well_formed(); + let metadata = Metadata { + data: &blob, + start: 0, + len: blob.len(), + }; + let mut out = Vec::new(); + collect(&metadata, &mut Findings::new(&mut out)); + assert!(out.is_empty(), "{out:?}"); + } + + #[test] + fn stream_whose_declared_range_leaves_the_blob_is_reported() { + let mut blob = bsjb("v4.0.30319", &[(b"#~", tables_body(1 << 0, &[1]))]); + // Rewrite the first stream header's offset to a range past the blob. + let first_header = 16 + padded_name(b"v4.0.30319") + 4; + blob[first_header..first_header + 4].copy_from_slice(&0x1000_u32.to_le_bytes()); + let metadata = Metadata { + data: &blob, + start: 0, + len: blob.len(), + }; + let mut out = Vec::new(); + collect(&metadata, &mut Findings::new(&mut out)); + assert!( + out.iter() + .any(|message| message.contains("extends past the metadata blob")), + "{out:?}" + ); + } + + #[test] + fn missing_tables_stream_is_reported() { + let blob = bsjb("v4.0.30319", &[(b"#Strings", vec![0; 4])]); + let metadata = Metadata { + data: &blob, + start: 0, + len: blob.len(), + }; + let mut out = Vec::new(); + collect(&metadata, &mut Findings::new(&mut out)); + assert!( + out.iter().any(|message| message.contains("tables stream")), + "{out:?}" + ); + } + + #[test] + fn missing_heap_stream_is_reported() { + let blob = bsjb( + "v4.0.30319", + &[ + (b"#~", tables_body(1 << 0, &[1])), + (b"#Strings", vec![0; 4]), + ], + ); + let metadata = Metadata { + data: &blob, + start: 0, + len: blob.len(), + }; + let mut out = Vec::new(); + collect(&metadata, &mut Findings::new(&mut out)); + assert!( + out.iter().any(|message| message.contains("'#GUID' heap")), + "{out:?}" + ); + } + + #[test] + fn row_count_array_past_the_stream_is_reported() { + // 18 present tables need 72 row-count bytes; the body declares four. + let mut body = tables_body((1 << 18) - 1, &[1]); + body.truncate(0x2C); + let blob = bsjb("v4.0.30319", &[(b"#~", body)]); + let metadata = Metadata { + data: &blob, + start: 0, + len: blob.len(), + }; + let mut out = Vec::new(); + collect(&metadata, &mut Findings::new(&mut out)); + assert!( + out.iter() + .any(|message| message.contains("row-count array")), + "{out:?}" + ); + } + + #[test] + fn empty_metadata_is_reported_not_panicking() { + let empty: [u8; 0] = []; + let metadata = Metadata { + data: &empty, + start: 0, + len: 0, + }; + let mut out = Vec::new(); + collect(&metadata, &mut Findings::new(&mut out)); + assert!( + out.is_empty(), + "a missing BSJB signature is the parent module's finding, not this module's" + ); + } +} diff --git a/senbei-engine/src/windows/integrity/directories.rs b/senbei-engine/src/windows/integrity/directories.rs new file mode 100644 index 0000000..b450d36 --- /dev/null +++ b/senbei-engine/src/windows/integrity/directories.rs @@ -0,0 +1,1125 @@ +//! Bounded structural diagnostics for PE data directories. +//! +//! Every function here reports *file-structure* problems only: a directory +//! entry that does not resolve inside the image, a table that runs past the +//! end of the file, an entry whose target is outside every mapped section. +//! Such a table cannot be walked by the Windows loader or by a disassembler, +//! which is a defect the output bytes themselves prove. +//! +//! It is **not** a statement about runtime behaviour. A clean report says the +//! tables are internally consistent; it does not say the code they describe +//! will run. Conversely a diagnostics entry means "this region could not be +//! walked from the output", not "the other layout would have been right". +//! +//! Callers must treat these findings as [`IntegritySeverity::Warning`]: +//! +//! * callback bytes are never inspected — a callback address is just a value, +//! so the most that can be said structurally is "mapped, and executable"; +//! * import *symbols* need not resolve to a local definition; the loader binds +//! them from another module, so only the name RVA is checked; +//! * a delay-import document built with virtual addresses (legacy PE32) is +//! reported but not treated as corruption. +//! +//! All reads are bounds-checked and every loop has a hard cap, so this module +//! never panics on a crafted image. + +use super::Section; +use super::rd_u32; +use crate::findings::Findings; + +const IMAGE_SCN_MEM_EXECUTE: u32 = 0x2000_0000; +const IMAGE_ORDINAL_FLAG32: u32 = 0x8000_0000; +const IMAGE_ORDINAL_FLAG64: u64 = 0x8000_0000_0000_0000; + +/// Maximum import descriptors walked. Far beyond any real import table; the +/// cap only stops a corrupt, never-NUL table from walking on. +const MAX_IMPORT_DESCRIPTORS: u32 = 256; +/// Maximum thunks (IAT/INT entries) walked in one table. +const MAX_THUNKS: u32 = 65_536; +/// Maximum delay-load descriptors walked. +const MAX_DELAY_DESCRIPTORS: u32 = 256; +/// Maximum TLS callback slots walked. +const MAX_TLS_CALLBACKS: u32 = 1_024; +/// Maximum relocation blocks walked. +const MAX_RELOCATION_BLOCKS: u32 = 262_144; +/// Maximum exception directory entries inspected. +const MAX_EXCEPTION_ENTRIES: u32 = 1_000_000; +/// Maximum bound-import descriptors (plus their forwarder references). +const MAX_BOUND_ENTRIES: u32 = 256; +/// Longest import/export name accepted as "plausible". +const MAX_NAME: u32 = 512; +/// One unpacked PE image, resolved through its own headers. +/// +/// Both the memory-image outputs (raw pointer == virtual address) and the +/// compacted disk outputs are supported, because the mapping is computed from +/// whatever the output declares. +pub(super) struct Image<'a> { + pub(super) data: &'a [u8], + pub(super) headers: senbei_pe::Headers, + pub(super) sections: &'a [Section], + pub(super) is64: bool, + pub(super) image_base: u64, + pub(super) size_of_image: u32, +} + +impl Image<'_> { + /// File offset backing a complete virtual range, if any. Rejects a + /// section's zero-filled tail: a table that exists only in memory cannot + /// be walked from the output file. + /// + /// This mirrors [`senbei_pe::rva_range`] exactly — the header region is + /// used when the whole range is inside `SizeOfHeaders`, otherwise one + /// section must back every byte — but resolves against the sections this + /// image already holds. `rva_range` re-parses and allocates the whole + /// section table per call, which a 65 Ki-entry thunk walk would turn into + /// quadratic allocation over image size. + pub(super) fn file_range(&self, rva: u32, size: u32) -> Option> { + // `SizeOfHeaders` lives in the optional header; recomputing it costs + // one read and no allocation, so it is not cached on the struct. + let header_size = self + .headers + .pe_offset + .checked_add(24) + .and_then(|at| at.checked_add(60)) + .and_then(|at| u32::try_from(at).ok()) + .and_then(|at| rd_u32(self.data, at)) + .unwrap_or(0); + let offset = if rva < header_size && size <= header_size - rva { + rva + } else { + self.sections.iter().find_map(|section| { + let delta = rva.checked_sub(section.virtual_address)?; + // Only file-backed bytes count: `delta >= raw_size` is the + // zero-filled tail and has no offset in the output. + if delta >= section.raw_size || size > section.raw_size - delta { + return None; + } + section.raw_offset.checked_add(delta) + })? + }; + let start = usize::try_from(offset).ok()?; + let end = start.checked_add(usize::try_from(size).ok()?)?; + (end <= self.data.len()).then_some(start..end) + } + + /// File offset backing a complete virtual range, if any. + fn file_offset(&self, rva: u32, size: u32) -> Option { + self.file_range(rva, size).map(|range| range.start) + } + + /// True when `[rva, rva+size)` is inside the loader's virtual image: the + /// header region, or one section's virtual extent. The bytes need not be + /// backed by the file — a zero-filled tail is still mapped at runtime. + pub(super) fn mapped(&self, rva: u32, size: u32) -> bool { + let Some(end) = rva.checked_add(size) else { + return false; + }; + if end > self.size_of_image { + return false; + } + let first_section = self + .sections + .iter() + .map(|section| section.virtual_address) + .min() + .unwrap_or(u32::MAX); + if end <= first_section { + return true; + } + self.sections.iter().any(|section| { + let span = section.virtual_size.max(section.raw_size); + rva >= section.virtual_address + && end + <= section + .virtual_address + .wrapping_add(span) + .min(self.size_of_image) + }) + } + + /// True when the whole range lies in one executable section. + pub(super) fn executable(&self, rva: u32, size: u32) -> bool { + let Some(end) = rva.checked_add(size) else { + return false; + }; + self.sections.iter().any(|section| { + let span = section.virtual_size.max(section.raw_size); + (section.characteristics & IMAGE_SCN_MEM_EXECUTE) != 0 + && rva >= section.virtual_address + && end <= section.virtual_address.wrapping_add(span) + }) + } + + fn u16_at(&self, offset: usize) -> Option { + let end = offset.checked_add(2)?; + let bytes: [u8; 2] = self.data.get(offset..end)?.try_into().ok()?; + Some(u16::from_le_bytes(bytes)) + } + + fn u32_at(&self, offset: usize) -> Option { + let end = offset.checked_add(4)?; + let bytes: [u8; 4] = self.data.get(offset..end)?.try_into().ok()?; + Some(u32::from_le_bytes(bytes)) + } + + fn pointer_at(&self, offset: usize) -> Option { + if self.is64 { + let end = offset.checked_add(8)?; + let bytes: [u8; 8] = self.data.get(offset..end)?.try_into().ok()?; + Some(u64::from_le_bytes(bytes)) + } else { + self.u32_at(offset).map(u64::from) + } + } + + fn thunk_size(&self) -> u32 { + if self.is64 { 8 } else { 4 } + } + + /// Read one thunk entry at a file offset. + fn thunk_at(&self, offset: usize) -> Option { + self.pointer_at(offset) + } + + fn is_ordinal(&self, thunk: u64) -> bool { + if self.is64 { + thunk & IMAGE_ORDINAL_FLAG64 != 0 + } else { + thunk & u64::from(IMAGE_ORDINAL_FLAG32) != 0 + } + } + + /// Classify a named import's hint/name entry. + /// + /// `None` means the entry does not resolve to file bytes at all (a real + /// structural defect); `Some(false)` means it resolves but is not a + /// printable name — the "imports left encrypted" signal. + fn import_name(&self, entry_rva: u32) -> Option { + // A hint/name entry is a u16 ordinal followed by the name. + let start = self.file_offset(entry_rva, 2)?.checked_add(2)?; + self.classify_string(start) + } + + /// Classify a plain NUL-terminated string at `rva`: same three-way result + /// as [`Image::import_name`]. + fn printable_c_string(&self, rva: u32) -> Option { + let start = self.file_offset(rva, 1)?; + self.classify_string(start) + } + + fn classify_string(&self, start: usize) -> Option { + let limit = usize::try_from(MAX_NAME).unwrap_or(usize::MAX); + let window = self + .data + .get(start..start.checked_add(limit)?.min(self.data.len()))?; + let Some(nul) = window.iter().position(|&byte| byte == 0) else { + return Some(false); + }; + Some(nul != 0 && window[..nul].iter().all(|&b| (0x20..0x7F).contains(&b))) + } + + /// Walk one thunk array, checking its framing and (optionally) its names. + /// + /// `check_names` must be false for an array that may be *bound*: a bound + /// IAT holds already-resolved virtual addresses, not hint/name RVAs, so + /// classifying those as names would report every import as corrupt. + /// + /// Returns the number of entries walked, or `None` when the array's first + /// entry is not backed by the file. + fn walk_thunks( + &self, + table_rva: u32, + label: &str, + check_names: bool, + out: &mut Findings<'_>, + ) -> Option { + let start = self.file_offset(table_rva, self.thunk_size())?; + let stride = self.thunk_size() as usize; + let slots = self.data.len().saturating_sub(start) / stride; + let limit = slots.min(MAX_THUNKS as usize); + let mut count = 0_usize; + let mut terminated = false; + while count < limit { + let Some(thunk) = self.thunk_at(start + count * stride) else { + break; + }; + if thunk == 0 { + terminated = true; + break; + } + // Once the sink is full, stop doing per-entry work: the findings + // would be dropped anyway, and formatting them is the allocation + // cost this walk exists to avoid. + if check_names && out.wants_more() && !self.is_ordinal(thunk) { + // Hint/name RVA is the low 31 bits of a by-name thunk. + let name_rva = (thunk & 0x7FFF_FFFF) as u32; + match self.import_name(name_rva) { + None => out.push(format!( + "{label} entry {count} name RVA 0x{name_rva:X} does not map into any file-backed section" + )), + Some(false) => out.push(format!( + "{label} entry {count} name RVA 0x{name_rva:X} is not a printable string (imports left encrypted?)" + )), + Some(true) => {} + } + } + count += 1; + } + // A thunk array runs until its null terminator. Running out of slots + // means the table reaches the end of the file (truncated); reaching the + // cap means it is not terminated within any plausible table. + if !terminated { + out.push(if limit == MAX_THUNKS as usize { + format!("{label} has no terminating null within {MAX_THUNKS} entries") + } else { + format!("{label} runs to the end of the file without a terminating null") + }); + } + Some(count as u32) + } +} + +/// `(rva, size)` of a data directory. Missing header bytes read as `(0, 0)`, +/// which every consumer treats as "directory absent" — matching the loader. +fn directory(image: &Image<'_>, index: u32) -> (u32, u32) { + let base = image + .headers + .pe_offset + .wrapping_add(24) + .wrapping_add(if image.is64 { 112 } else { 96 }); + let Ok(base) = u32::try_from(base) else { + return (0, 0); + }; + let offset = base.saturating_add(index.saturating_mul(8)); + ( + rd_u32(image.data, offset).unwrap_or(0), + rd_u32(image.data, offset.saturating_add(4)).unwrap_or(0), + ) +} + +/// Collect every data-directory defect of a native image. +/// +/// Managed assemblies are excluded by the caller: their import table is a CLR +/// bootstrap stub the native loader does not resolve the same way. +pub(super) fn collect(image: &Image<'_>, out: &mut Vec) { + // One bounded sink per directory: a corrupt table cannot flood the report, + // and each directory that overflowed still says so. + for check in [ + collect_imports as fn(&Image<'_>, &mut Findings<'_>), + collect_delay_imports, + collect_bound_imports, + collect_iat, + collect_tls, + collect_relocations, + collect_exception, + collect_load_config, + ] { + let mut findings = Findings::new(out); + check(image, &mut findings); + findings.finish(); + } +} + +fn collect_imports(image: &Image<'_>, out: &mut Findings<'_>) { + let (rva, _) = directory(image, 1); + if rva == 0 { + return; + } + // The existing fatal check already reports an unmapped import directory; + // do not duplicate it here. + let Some(range) = image.file_range(rva, 20) else { + return; + }; + let stride = 20usize; + for index in 0..MAX_IMPORT_DESCRIPTORS { + let Some(offset) = (index as usize) + .checked_mul(stride) + .and_then(|delta| range.start.checked_add(delta)) + else { + return; + }; + // The table is walked until its all-zero terminator; running out of + // file inside it means the terminator is missing. + if offset + .checked_add(stride) + .is_none_or(|end| end > image.data.len()) + { + out.push(format!( + "import directory runs past the end of the file before descriptor {index}" + )); + return; + } + let original_first_thunk = image.u32_at(offset).unwrap_or(0); + let name_rva = image.u32_at(offset + 12).unwrap_or(0); + let first_thunk = image.u32_at(offset + 16).unwrap_or(0); + if name_rva == 0 { + return; + } + if image.file_range(name_rva, 1).is_none() { + // The fatal check already reports this per descriptor. + continue; + } + // A bound image may omit OriginalFirstThunk; the loader then walks the + // IAT itself. Either is a valid description of the imports. + let table = if original_first_thunk != 0 { + original_first_thunk + } else { + first_thunk + }; + if table == 0 { + out.push(format!( + "import descriptor {index} has neither OriginalFirstThunk nor FirstThunk" + )); + continue; + } + // Only a by-name lookup table carries hint/name RVAs. When the + // descriptor has no OriginalFirstThunk, `table` is the IAT and the + // image may be bound, so its entries are addresses, not names. + let Some(by_name) = image.walk_thunks( + table, + &format!("import descriptor {index} lookup table"), + original_first_thunk != 0, + out, + ) else { + out.push(format!( + "import descriptor {index} lookup table RVA 0x{table:X} does not map into any file-backed section" + )); + continue; + }; + // When both arrays exist the loader treats them as parallel: it copies + // the lookup table into the IAT, so a shorter IAT leaves imports + // unresolved. Only the counts are compared; the contents legitimately + // differ between an unbound and a bound image. The IAT is counted with + // name classification off: when the image is bound its entries are + // resolved addresses, not hint/name RVAs. + if original_first_thunk != 0 && first_thunk != 0 { + let mut ignored = out.silenced(); + if let Some(iat) = image.walk_thunks( + first_thunk, + &format!("import descriptor {index} IAT"), + false, + &mut ignored, + ) && iat != by_name + { + out.push(format!( + "import descriptor {index} IAT holds {iat} entries but its lookup table holds {by_name}" + )); + } + } + } + out.push(format!( + "import directory has more than {MAX_IMPORT_DESCRIPTORS} descriptors (missing null terminator)" + )); +} + +fn collect_delay_imports(image: &Image<'_>, out: &mut Findings<'_>) { + let (rva, _) = directory(image, 13); + if rva == 0 { + return; + } + let Some(range) = image.file_range(rva, 32) else { + out.push(format!( + "delay-import directory RVA 0x{rva:X} does not map into any file-backed section" + )); + return; + }; + let stride = 32usize; + for index in 0..MAX_DELAY_DESCRIPTORS { + let Some(offset) = (index as usize) + .checked_mul(stride) + .and_then(|delta| range.start.checked_add(delta)) + else { + return; + }; + if offset + .checked_add(stride) + .is_none_or(|end| end > image.data.len()) + { + return; + } + let attributes = image.u32_at(offset).unwrap_or(0); + let name_rva = image.u32_at(offset + 4).unwrap_or(0); + if attributes == 0 && name_rva == 0 { + return; + } + // Bit 0 says the descriptor's fields are RVAs. Old PE32 images link + // them as virtual addresses instead; that is legal, but the values + // cannot be resolved against this image without its load address. + if attributes & 1 == 0 { + out.push(format!( + "delay-import descriptor {index} stores virtual addresses rather than RVAs (legacy form; not validated)" + )); + continue; + } + if name_rva != 0 { + // The module name is a plain NUL-terminated string, not a + // hint/name entry. + match image.printable_c_string(name_rva) { + None => out.push(format!( + "delay-import descriptor {index} module name RVA 0x{name_rva:X} does not map into any section" + )), + Some(false) => out.push(format!( + "delay-import descriptor {index} module name RVA 0x{name_rva:X} is not a printable string (left encrypted?)" + )), + Some(true) => {} + } + } + let import_names = image.u32_at(offset + 16).unwrap_or(0); + let import_addresses = image.u32_at(offset + 12).unwrap_or(0); + let table = if import_names != 0 { + import_names + } else { + import_addresses + }; + if table == 0 { + out.push(format!( + "delay-import descriptor {index} has neither ImportNameTable nor ImportAddressTable" + )); + continue; + } + if image + .walk_thunks( + table, + &format!("delay-import descriptor {index} name table"), + true, + out, + ) + .is_none() + { + out.push(format!( + "delay-import descriptor {index} name table RVA 0x{table:X} does not map into any file-backed section" + )); + } + } + out.push(format!( + "delay-import directory has more than {MAX_DELAY_DESCRIPTORS} descriptors (missing null terminator)" + )); +} + +/// Bound imports (DD[11]): module names are offsets relative to the directory, +/// optionally followed by forwarder references. Unpackers commonly zero this +/// directory; when it survives, its names still has to resolve inside it. +fn collect_bound_imports(image: &Image<'_>, out: &mut Findings<'_>) { + let (rva, size) = directory(image, 11); + if rva == 0 || size < 8 { + return; + } + let Some(range) = image.file_range(rva, size) else { + out.push(format!( + "bound-import directory RVA 0x{rva:X} does not map into any file-backed section" + )); + return; + }; + let dir_end = range.end; + let mut offset = range.start; + for _ in 0..MAX_BOUND_ENTRIES { + if offset.checked_add(8).is_none_or(|end| end > dir_end) { + return; + } + let stamp = image.u32_at(offset).unwrap_or(0); + let flags = image.u32_at(offset + 4).unwrap_or(0); + let name_offset = (flags & 0xFFFF) as usize; + let forwarders = flags >> 16; + if stamp == 0 && flags == 0 { + return; + } + let Some(name_at) = range.start.checked_add(name_offset) else { + return; + }; + if name_at >= dir_end { + out.push(format!( + "bound-import module name offset 0x{name_offset:X} lies outside the directory" + )); + } else if image.u32_at(name_at).is_none() { + out.push(format!( + "bound-import module name at directory offset 0x{name_offset:X} is not backed by the file" + )); + } + // Each descriptor is followed by `forwarders` 8-byte references. + let advance = 8usize.saturating_add(forwarders as usize * 8); + offset = offset.saturating_add(advance); + } + out.push(format!( + "bound-import directory has more than {MAX_BOUND_ENTRIES} entries (missing null terminator)" + )); +} + +/// DD[12] is published by the loader as `IMAGE_DIRECTORY_ENTRY_IAT`, so it has +/// to resolve inside the image like any other directory. +fn collect_iat(image: &Image<'_>, out: &mut Findings<'_>) { + let (rva, size) = directory(image, 12); + if rva == 0 { + return; + } + if !image.mapped(rva, size.max(1)) { + out.push(format!( + "IAT directory RVA 0x{rva:X} (size 0x{size:X}) does not map into the image" + )); + } +} + +fn collect_tls(image: &Image<'_>, out: &mut Findings<'_>) { + let (rva, size) = directory(image, 9); + if rva == 0 { + return; + } + // IMAGE_TLS_DIRECTORY64 is 40 bytes, the 32-bit form 24. + let entry_size = if image.is64 { 40u32 } else { 24 }; + if size < entry_size { + out.push(format!( + "TLS directory size 0x{size:X} is smaller than the {entry_size}-byte header" + )); + } + let Some(start) = image.file_offset(rva, entry_size) else { + out.push(format!( + "TLS directory RVA 0x{rva:X} does not map into any file-backed section" + )); + return; + }; + // The TLS directory stores virtual addresses, not RVAs. + let mut callbacks = 0_u64; + for (name, offset) in [ + ("StartAddressOfRawData", 0usize), + ("EndAddressOfRawData", 8), + ("AddressOfIndex", 16), + ("AddressOfCallBacks", 24), + ] { + let Some(value) = image.pointer_at(start.saturating_add(offset)) else { + out.push(format!("TLS {name} field is truncated")); + continue; + }; + if value == 0 { + continue; + } + let Some(rva) = value.checked_sub(image.image_base) else { + out.push(format!( + "TLS {name} 0x{value:X} lies below the image base 0x{:X}", + image.image_base + )); + continue; + }; + let Ok(rva) = u32::try_from(rva) else { + continue; + }; + if !image.mapped(rva, 1) { + out.push(format!( + "TLS {name} 0x{value:X} (RVA 0x{rva:X}) does not map into the image" + )); + } + if name == "AddressOfCallBacks" { + callbacks = u64::from(rva); + } + } + if callbacks == 0 { + return; + } + let Ok(array_rva) = u32::try_from(callbacks) else { + return; + }; + // A null-terminated array of virtual addresses. Their values are data: + // "mapped and executable" is the strongest structural statement available. + let stride = image.thunk_size() as usize; + let Some(array_start) = image.file_offset(array_rva, image.thunk_size()) else { + out.push("TLS callback array does not map into any file-backed section".to_owned()); + return; + }; + let slots = image.data.len().saturating_sub(array_start) / stride; + for slot in 0..slots.min(MAX_TLS_CALLBACKS as usize) { + let Some(callback) = image.thunk_at(array_start + slot * stride) else { + break; + }; + if callback == 0 { + return; + } + // Once the sink is full the remaining slots cannot add anything; stop + // walking rather than formatting findings that would be dropped. + if !out.wants_more() { + return; + } + let Some(rva) = callback.checked_sub(image.image_base) else { + out.push(format!( + "TLS callback {slot} 0x{callback:X} lies below the image base 0x{:X}", + image.image_base + )); + continue; + }; + let Ok(rva) = u32::try_from(rva) else { + continue; + }; + if !image.mapped(rva, 1) { + out.push(format!( + "TLS callback {slot} 0x{callback:X} (RVA 0x{rva:X}) does not map into the image" + )); + } else if !image.executable(rva, 1) { + out.push(format!( + "TLS callback {slot} 0x{callback:X} (RVA 0x{rva:X}) is not in an executable section" + )); + } + } + out.push(format!( + "TLS callback array has no null terminator within {MAX_TLS_CALLBACKS} entries" + )); +} + +/// Walk the base relocation directory and check every block's own framing. +/// +/// Only the block header and the entry encoding are checked. The patched words +/// are not inspected: their post-relocation value depends on the load address. +fn collect_relocations(image: &Image<'_>, out: &mut Findings<'_>) { + let (rva, size) = directory(image, 5); + if rva == 0 { + return; + } + if size == 0 { + out.push("base relocation directory has a zero size".to_owned()); + return; + } + let Some(range) = image.file_range(rva, size) else { + out.push(format!( + "base relocation directory RVA 0x{rva:X} (size 0x{size:X}) does not map into any file-backed section" + )); + return; + }; + let mut offset = range.start; + let mut blocks = 0_u32; + while offset.checked_add(8).is_some_and(|end| end <= range.end) { + let page = image.u32_at(offset).unwrap_or(0); + let block_size = image.u32_at(offset + 4).unwrap_or(0); + // A block is 8 header bytes plus an even number of 2-byte entries. + if block_size < 8 + || !block_size.is_multiple_of(2) + || offset + .checked_add(block_size as usize) + .is_none_or(|end| end > range.end) + { + out.push(format!( + "relocation block {blocks} declares size 0x{block_size:X}, which does not fit the directory" + )); + return; + } + if !page.is_multiple_of(0x1000) { + out.push(format!( + "relocation block {blocks} page RVA 0x{page:X} is not 4 KiB aligned" + )); + } + if page >= image.size_of_image { + out.push(format!( + "relocation block {blocks} page RVA 0x{page:X} lies beyond SizeOfImage 0x{:X}", + image.size_of_image + )); + } + let entries = (block_size - 8) / 2; + for index in 0..entries { + let Some(entry) = image.u16_at(offset + 8 + index as usize * 2) else { + break; + }; + let kind = u32::from(entry >> 12); + // A block whose entries are all corrupt would otherwise produce one + // message per entry; stop once the directory's sink is full. + if !out.wants_more() { + break; + } + // Types above IMAGE_REL_BASED_DIR64 (10) are undefined for the + // AMD64/I386 loader; ABSOLUTE (0) is the NOP/padding type. + if kind > 10 { + out.push(format!( + "relocation block {blocks} entry {index} has unsupported type {kind}" + )); + } else if kind != 0 + && page.saturating_add(u32::from(entry & 0x0FFF)) >= image.size_of_image + { + out.push(format!( + "relocation block {blocks} entry {index} targets RVA 0x{:X} beyond SizeOfImage", + page.saturating_add(u32::from(entry & 0x0FFF)) + )); + } + } + offset += block_size as usize; + blocks += 1; + if blocks >= MAX_RELOCATION_BLOCKS { + out.push(format!( + "relocation directory has more than {MAX_RELOCATION_BLOCKS} blocks" + )); + return; + } + } + if offset != range.end { + out.push(format!( + "relocation directory has {} trailing byte(s) after the last block", + range.end.saturating_sub(offset) + )); + } +} + +/// Walk the exception (unwind) directory: every entry must describe a range +/// that lives inside the image. +fn collect_exception(image: &Image<'_>, out: &mut Findings<'_>) { + let (rva, size) = directory(image, 3); + if rva == 0 || size == 0 { + return; + } + // PE32+ uses RUNTIME_FUNCTION {begin, end, unwind} at 12 bytes; the x86 + // form has no unwind pointer and is 8 bytes. + let entry_size = if image.is64 { 12u32 } else { 8 }; + if size % entry_size != 0 { + out.push(format!( + "exception directory size 0x{size:X} is not a multiple of the {entry_size}-byte entry size" + )); + } + let usable = size - size % entry_size; + let Some(start) = image.file_offset(rva, usable) else { + out.push(format!( + "exception directory RVA 0x{rva:X} (size 0x{size:X}) does not map into any file-backed section" + )); + return; + }; + let count = (usable / entry_size).min(MAX_EXCEPTION_ENTRIES); + for index in 0..count { + if !out.wants_more() { + return; + } + let offset = start + index as usize * entry_size as usize; + let begin = image.u32_at(offset).unwrap_or(0); + let end = image.u32_at(offset + 4).unwrap_or(0); + if begin >= end { + out.push(format!( + "exception entry {index} has begin RVA 0x{begin:X} >= end RVA 0x{end:X}" + )); + continue; + } + if !image.mapped(begin, 1) { + out.push(format!( + "exception entry {index} begin RVA 0x{begin:X} does not map into the image" + )); + } + if !image.mapped(end - 1, 1) { + out.push(format!( + "exception entry {index} end RVA 0x{end:X} does not map into the image" + )); + } + if image.is64 { + let unwind = image.u32_at(offset + 8).unwrap_or(0); + // The low two bits are flags, not part of the RVA. + if unwind != 0 && !image.mapped(unwind & !3, 1) { + out.push(format!( + "exception entry {index} unwind info RVA 0x{unwind:X} does not map into the image" + )); + } + } + } +} + +/// Check the load-configuration directory's own pointers. +/// +/// The security cookie and the guard CF function table are the two fields the +/// loader reads during process start; both are virtual addresses. +fn collect_load_config(image: &Image<'_>, out: &mut Findings<'_>) { + let (rva, size) = directory(image, 10); + if rva == 0 || size == 0 { + return; + } + // The security cookie sits at +0x58 (PE32+) / +0x3C (PE32), the guard CF + // function table at +0x70 / +0x48. + let (cookie_offset, guard_offset, minimum) = if image.is64 { + (0x58usize, 0x70usize, 0x70u32) + } else { + (0x3C, 0x48, 0x40) + }; + if size < minimum { + out.push(format!( + "load-config directory size 0x{size:X} is smaller than the 0x{minimum:X} header the loader reads" + )); + } + let readable = minimum.min(size); + let Some(start) = image.file_offset(rva, readable) else { + out.push(format!( + "load-config directory RVA 0x{rva:X} does not map into any file-backed section" + )); + return; + }; + for (name, offset) in [ + ("security cookie", cookie_offset), + ("guard CF function table", guard_offset), + ] { + if (offset as u32).saturating_add(image.thunk_size()) > readable { + // Field lies beyond the declared size; nothing to check. + continue; + } + let Some(value) = image.pointer_at(start + offset) else { + continue; + }; + if value == 0 { + continue; + } + let Some(rva) = value.checked_sub(image.image_base) else { + out.push(format!( + "load-config {name} 0x{value:X} lies below the image base 0x{:X}", + image.image_base + )); + continue; + }; + let Ok(rva) = u32::try_from(rva) else { + continue; + }; + if !image.mapped(rva, 1) { + out.push(format!( + "load-config {name} 0x{value:X} (RVA 0x{rva:X}) does not map into the image" + )); + } + } +} + +#[cfg(test)] +mod tests { + // Synthetic-image coverage lives next to the module that builds those + // images (`super::tests`), so these unit tests stay about the helpers. + use super::*; + + /// Section table offset used by the synthetic images below. The fixtures + /// carry a real section table so the offset translation has something to + /// resolve against. + const SECTIONS_AT: usize = 0x100; + const HEADERS_SIZE: u32 = 0x400; + + fn headers() -> senbei_pe::Headers { + senbei_pe::Headers { + pe_offset: 0, + is_pe32_plus: true, + image_base: 0, + size_of_image: 0x2000, + entry_rva: 0x1000, + sections_offset: SECTIONS_AT, + sections: 1, + } + } + + fn text_section() -> Section { + Section { + virtual_address: 0x1000, + virtual_size: 0x1000, + raw_offset: 0x1000, + raw_size: 0x1000, + characteristics: 0x6000_0020, + } + } + + /// A file image whose one `.text` section is at RVA 0x1000 -> offset 0x1000. + fn image_data() -> Vec { + const SIZE: usize = 0x2000; + let mut data = vec![0_u8; SIZE]; + // SizeOfHeaders, at optional-header +60 for a PE32+ layout based at 0. + data[24 + 60..24 + 64].copy_from_slice(&HEADERS_SIZE.to_le_bytes()); + for (offset, value) in [ + (8usize, 0x1000u32), // VirtualSize + (12, 0x1000), // VirtualAddress + (16, 0x1000), // SizeOfRawData + (20, 0x1000), // PointerToRawData + (36, 0x6000_0020), // Characteristics: executable, readable + ] { + let at = SECTIONS_AT + offset; + data[at..at + 4].copy_from_slice(&value.to_le_bytes()); + } + data + } + + #[test] + fn thunk_width_and_ordinal_flag_follow_the_optional_header() { + let data = [0_u8; 8]; + let sections = [text_section()]; + let wide = Image { + data: &data, + headers: headers(), + sections: §ions, + is64: true, + image_base: 0, + size_of_image: 0x2000, + }; + let narrow = Image { + data: &data, + headers: headers(), + sections: §ions, + is64: false, + image_base: 0, + size_of_image: 0x2000, + }; + assert_eq!(wide.thunk_size(), 8); + assert_eq!(narrow.thunk_size(), 4); + assert!(narrow.is_ordinal(u64::from(0x8000_0000_u32))); + assert!(!narrow.is_ordinal(u64::from(0x7FFF_FFFF_u32))); + assert!(wide.is_ordinal(0x8000_0000_0000_0000)); + assert!(!wide.is_ordinal(0x0000_0000_FFFF_FFFF)); + } + + #[test] + fn mapped_rejects_ranges_outside_the_image() { + let sections = [text_section()]; + let data = image_data(); + let image = Image { + data: &data, + headers: headers(), + sections: §ions, + is64: true, + image_base: 0, + size_of_image: 0x2000, + }; + assert!(image.mapped(0, 0x100)); + assert!(image.mapped(0x1000, 0x1000)); + assert!( + !image.mapped(0x1FFF, 2), + "a range may not cross SizeOfImage" + ); + assert!( + !image.mapped(u32::MAX, 2), + "an overflowing range is unmapped" + ); + assert!( + !image.mapped(0xF00, 0x200), + "a range stays inside one section" + ); + assert!(image.executable(0x1000, 1)); + assert!(!image.executable(0x0800, 1), "headers are not executable"); + } + + #[test] + fn named_thunk_whose_target_is_unmapped_is_reported() { + // Slot 0 names RVA 0x9000 — outside every section, so the hint/name + // entry cannot be read at all. + let mut data = image_data(); + data[0x1000..0x1008].copy_from_slice(&0x9000_u64.to_le_bytes()); + let sections = [text_section()]; + let image = Image { + data: &data, + headers: headers(), + sections: §ions, + is64: true, + image_base: 0, + size_of_image: 0x2000, + }; + let mut out = Vec::new(); + assert_eq!( + image.walk_thunks(0x1000, "test table", true, &mut Findings::new(&mut out)), + Some(1) + ); + assert_eq!(out.len(), 1, "{out:?}"); + assert!(out[0].contains("does not map"), "{out:?}"); + } + + #[test] + fn thunk_whose_name_is_not_printable_is_reported_once() { + // Slot 0 names RVA 0x1010, whose hint/name bytes are zeroes: mapped, + // but not a name. That is the "left encrypted" signal. + let mut data = image_data(); + data[0x1000..0x1008].copy_from_slice(&0x1010_u64.to_le_bytes()); + let sections = [text_section()]; + let image = Image { + data: &data, + headers: headers(), + sections: §ions, + is64: true, + image_base: 0, + size_of_image: 0x2000, + }; + let mut out = Vec::new(); + assert_eq!( + image.walk_thunks(0x1000, "test table", true, &mut Findings::new(&mut out)), + Some(1) + ); + assert_eq!(out.len(), 1, "{out:?}"); + assert!(out[0].contains("not a printable string"), "{out:?}"); + } + + #[test] + fn thunk_table_running_to_the_file_end_is_reported() { + // Every slot names the same valid string and none is null, so the walk + // stops only because the file ended: a truncated table has to be said + // out loud rather than pass as terminated. + let mut data = image_data(); + // A valid hint/name entry in the header region (RVA 0x200: hint 0, + // then "f\0"), so every named entry resolves to a printable name. + data[0x200..0x204].copy_from_slice(&[0x00, 0x00, b'f', 0x00]); + for slot in 0..(data.len() - 0x1000) / 8 { + let at = 0x1000 + slot * 8; + data[at..at + 8].copy_from_slice(&0x200_u64.to_le_bytes()); + } + let sections = [text_section()]; + let image = Image { + data: &data, + headers: headers(), + sections: §ions, + is64: true, + image_base: 0, + size_of_image: 0x2000, + }; + let mut out = Vec::new(); + let walked = image.walk_thunks(0x1000, "test table", true, &mut Findings::new(&mut out)); + assert!(walked.is_some()); + assert!( + out.iter() + .any(|message| message.contains("without a terminating null")), + "{out:?}" + ); + assert!( + !out.iter() + .any(|message| message.contains("not a printable")), + "every named entry is valid here, got {out:?}" + ); + } + + #[test] + fn cached_file_mapping_matches_senbei_pe_rva_range() { + // The cached-sections mapping must agree with the format crate for the + // header region, a section interior, the zero-fill tail, and overflow. + let mut data = image_data(); + // Give `.text` a memory extent past its file bytes (the zero tail). + let at = SECTIONS_AT + 8; + data[at..at + 4].copy_from_slice(&0x1800u32.to_le_bytes()); // VirtualSize + let sections = [text_section()]; + let image = Image { + data: &data, + headers: headers(), + sections: §ions, + is64: true, + image_base: 0, + size_of_image: 0x2000, + }; + for (rva, size) in [ + (0x100u32, 0x100u32), // header region + (0x1000, 0x100), // section interior + (0x1F00, 0x100), // last file-backed bytes of `.text` + (0x1FF0, 0x20), // runs into the zero-filled tail + (0x2000, 1), // past `SizeOfRawData` + (0x0800, 0x100), // header region past `SizeOfHeaders` + (u32::MAX, 4), // offset overflow + (0x1000, 0), // zero length at a valid start + ] { + let want = senbei_pe::rva_range(&data, headers(), rva, size) + .ok() + .map(|range| range.start); + assert_eq!( + image.file_offset(rva, size), + want, + "mapping of RVA 0x{rva:X} + 0x{size:X} disagrees with senbei_pe" + ); + } + } + + #[test] + fn unbacked_thunk_table_returns_none() { + let data = image_data(); + let sections = [text_section()]; + let image = Image { + data: &data, + headers: headers(), + sections: §ions, + is64: true, + image_base: 0, + size_of_image: 0x2000, + }; + let mut out = Vec::new(); + assert_eq!( + image.walk_thunks(0x9000, "test table", true, &mut Findings::new(&mut out)), + None + ); + assert!(out.is_empty()); + } +} diff --git a/senbei-engine/src/windows/integrity.rs b/senbei-engine/src/windows/integrity/mod.rs similarity index 88% rename from senbei-engine/src/windows/integrity.rs rename to senbei-engine/src/windows/integrity/mod.rs index 7b0257c..6aa0d9b 100644 --- a/senbei-engine/src/windows/integrity.rs +++ b/senbei-engine/src/windows/integrity/mod.rs @@ -11,8 +11,16 @@ //! in a correctly unpacked image, so a clean report is not a guarantee of //! correctness, but a non-clean report is a reliable "this is broken" signal. //! +//! Everything in this module is a *structural* statement about the output +//! bytes. It never executes the image, never resolves an external symbol, and +//! never reads a callback's bytes — a clean report therefore means "the loader +//! would be able to walk these tables", not "this image runs". +//! //! All reads are bounds-checked; the check never panics on any input. +mod clr; +mod directories; + /// How serious one [`IntegrityReport`] defect is for choosing a DLL layout. /// /// This does not change what [`check`] puts in [`IntegrityReport::issues`]. @@ -473,9 +481,71 @@ pub fn check(out: &[u8]) -> IntegrityReport { } } + // --- Structural diagnostics -------------------------------------------- + // Everything below is advisory. These checks walk the directories the + // loader or the CLR reads in order, and they only report a table that + // cannot be walked from these bytes at all. They never decide whether a + // layout candidate is acceptable: an image whose directories are intact + // still need not run (see the module docs), and one that carries a + // protected-but-present directory must not be rejected for it. Reporting + // them as warnings keeps DLL layout selection and the golden outputs + // exactly where they were. + let mut diagnostics = Vec::new(); + let image = directories::Image { + data: out, + headers, + sections: &secs, + is64, + image_base: headers.image_base, + size_of_image, + }; + if is_managed { + if let Some(metadata) = clr_metadata(out, &image) { + // The metadata walk formats one message per malformed stream, so + // it gets a bounded sink like the directory walks. + let mut findings = crate::findings::Findings::new(&mut diagnostics); + clr::collect(&metadata, &mut findings); + findings.finish(); + } + } else { + directories::collect(&image, &mut diagnostics); + } + for message in diagnostics { + r.push(IntegritySeverity::Warning, message); + } + r } +/// Locate the BSJB metadata blob of a managed image for the CLR diagnostics. +/// +/// Returns `None` when the COR20 header or the blob itself does not resolve; +/// the fatal checks above already report that case, and there is nothing +/// further to enumerate. +fn clr_metadata<'a>(out: &'a [u8], image: &directories::Image<'_>) -> Option> { + let (clr_rva, _) = senbei_pe::data_directory(out, image.headers, 14).ok()?; + if clr_rva == 0 { + return None; + } + let cor = image.file_range(clr_rva, 0x10)?; + let md_rva = rd_u32(out, (cor.start as u32).saturating_add(8))?; + let md_size = rd_u32(out, (cor.start as u32).saturating_add(12))?; + if md_rva == 0 { + return None; + } + // The blob's first four bytes must be backed by the file; its declared + // size may legitimately exceed the file only if the CLR would refuse it, + // which is exactly what the diagnostics report. + let start = image.file_range(md_rva, 4)?.start; + let available = out.len().saturating_sub(start); + let len = usize::try_from(md_size).unwrap_or(available).min(available); + Some(clr::Metadata { + data: out, + start, + len, + }) +} + /// True if the NUL-terminated string starting at `off` looks like a DLL name: /// at least one byte, all printable ASCII up to the NUL, within a sane length. fn looks_like_dll_name(d: &[u8], off: u32) -> bool { diff --git a/senbei-engine/src/windows/mod.rs b/senbei-engine/src/windows/mod.rs index 6702c3d..a868d07 100644 --- a/senbei-engine/src/windows/mod.rs +++ b/senbei-engine/src/windows/mod.rs @@ -647,8 +647,16 @@ mod dll_layout_selection { data[pe + 24 + 108..pe + 24 + 112].copy_from_slice(&16u32.to_le_bytes()); let dd = pe + 24 + 112; if self.reloc && !self.managed { - data[dd + 5 * 8..dd + 5 * 8 + 4].copy_from_slice(&0x1800u32.to_le_bytes()); - data[dd + 5 * 8 + 4..dd + 5 * 8 + 8].copy_from_slice(&8u32.to_le_bytes()); + // A relocation directory has to be *backed by the file*: one + // block (page RVA 0x1000, 8-byte header + one HIGHLOW entry) + // at RVA 0x1020 -> file 0x220, inside the section's raw range. + data[dd + 5 * 8..dd + 5 * 8 + 4].copy_from_slice(&0x1020u32.to_le_bytes()); + data[dd + 5 * 8 + 4..dd + 5 * 8 + 8].copy_from_slice(&12u32.to_le_bytes()); + if data.len() >= 0x220 + 12 { + data[0x220..0x224].copy_from_slice(&0x1000u32.to_le_bytes()); + data[0x224..0x228].copy_from_slice(&12u32.to_le_bytes()); + data[0x228..0x22a].copy_from_slice(&0x3000u16.to_le_bytes()); + } } if self.import_name.is_some() || self.import_unmapped { data[dd + 8..dd + 12].copy_from_slice(&0x1100u32.to_le_bytes());