feat(integrity): diagnose restored PE and ELF table inconsistencies

This commit is contained in:
Momoko-Ayase committed 2026-11-05 22:06:18 +08:00
1 parent 1d64c732d9
commit 3fff15ed9a
9 files changed
+2810 -2

No files matched your search

+1
View File
@@ -2,6 +2,7 @@ mod artifact;
mod constructors;
mod error;
mod pipeline;
mod verify;
pub use error::Error;
pub use pipeline::{
@@ -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<String>,
}
/// 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,
})
}
+868
View File
@@ -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<u64> {
self.offset.checked_add(self.file_size)
}
fn memory_end(&self) -> Option<u64> {
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<u64> {
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<Segment>,
sections: Vec<SectionHeader>,
names: Vec<String>,
}
impl View<'_> {
fn segment_for(&self, address: u64, size: u64) -> Option<Segment> {
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<usize> {
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<String>) {
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<u64> {
let values: Vec<u64> = 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<Relocation> {
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:?}"
);
}
}
+246
View File
@@ -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<String>,
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<String>) -> 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<String>) {
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());
}
}
+1
View File
@@ -1,6 +1,7 @@
//! Platform-specific unpacking engines.
pub mod android;
mod findings;
mod panic_capture;
pub mod profile;
pub mod windows;
+477
View File
@@ -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<u32> {
let local = self.data.get(self.start.checked_add(offset as usize)?..)?;
rd_u32(local, 0)
}
fn u64(&self, offset: u32) -> Option<u64> {
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<Stream<'_>> = 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<u32> {
// 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::<usize>()
}
/// 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<u8>)]) -> Vec<u8> {
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<u8> {
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<u8> {
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"
);
}
}
File diff suppressed because it is too large. Load diff
@@ -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<clr::Metadata<'a>> {
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 {
+10 -2
View File
@@ -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());