mirror of
https://github.com/Momoko-Ayase/Senbei.git
synced 2026-11-24 10:52:47 +08:00
fix(inspect): collect full static recovery research by default
Inspect the protected input and actual recovered image, with bounded structural evidence, source identities and scoped recovery traces. Keep ordinary unpack lightweight and retain no research output files or logs. Preserve Android extraction, restoration and metadata evidence, distinguish incomplete analyses from rejected candidates, and render detailed text and JSON reports with explicit address provenance.
This commit is contained in:
1 parent
05a4337a5e
commit
1ee4344c1e
22 files changed
+7776
-758
No files matched your search
@@ -16,8 +16,10 @@ pub use profile::{
|
||||
pub use threading::{thread_cap, with_thread_cap};
|
||||
|
||||
pub use windows::{
|
||||
Detected, IntegrityFinding, IntegrityReport, IntegritySeverity, Kind, UnpackError,
|
||||
check_integrity, detect, inspect_profile, unpack_auto, unpack_auto_profiled,
|
||||
unpack_auto_profiled_v, unpack_auto_v, unpack_dll, unpack_dll_v, unpack_exe,
|
||||
unpack_exe_profiled, unpack_exe_profiled_v, unpack_exe_v,
|
||||
AddressSpace, Detected, InspectionLimits, IntegrityFinding, IntegrityReport, IntegritySeverity,
|
||||
Kind, ResearchEvent, ResearchStage, ResearchTrace, TraceAddress, TraceValue, UnpackError,
|
||||
WindowsInspection, check_integrity, detect, inspect_profile, inspect_research,
|
||||
inspect_research_with_limits, unpack_auto, unpack_auto_profiled, unpack_auto_profiled_v,
|
||||
unpack_auto_v, unpack_dll, unpack_dll_v, unpack_exe, unpack_exe_profiled,
|
||||
unpack_exe_profiled_v, unpack_exe_v, with_research_trace, with_research_trace_limited,
|
||||
};
|
||||
File diff suppressed because it is too large.
Load diff
@@ -4,6 +4,7 @@ use senbei_crypto::primitives::*;
|
||||
|
||||
use super::super::error::*;
|
||||
use super::super::layout::{self, *};
|
||||
use super::super::research::{self, AddressSpace, ResearchStage};
|
||||
|
||||
mod pe32;
|
||||
|
||||
@@ -89,19 +90,14 @@ impl<'a> Unpacker<'a> {
|
||||
// (file_data, decompressed, info, decrypt_size); left on Unpacker.
|
||||
// The DLL port will need a different driver state anyway.
|
||||
fn decrypt_data2(&mut self) {
|
||||
let base_src = self.info[4].wrapping_add(4096);
|
||||
let mut k = self.info[0].wrapping_add(!self.decrypt_size);
|
||||
let words = self.decrypt_size >> 2;
|
||||
for i in 0..words {
|
||||
let off = i.wrapping_mul(4);
|
||||
let cell = get_u32(self.file_data, base_src.wrapping_add(off));
|
||||
write_u32(
|
||||
&mut self.decompressed,
|
||||
self.info[3].wrapping_add(off),
|
||||
k ^ cell,
|
||||
);
|
||||
k = i.wrapping_mul(i) ^ (k.wrapping_add(cell).wrapping_add(i));
|
||||
}
|
||||
primitives::decode_payload_prefix(
|
||||
self.file_data,
|
||||
self.info[4].wrapping_add(4096),
|
||||
&mut self.decompressed,
|
||||
self.info[3],
|
||||
self.info[0],
|
||||
self.decrypt_size,
|
||||
);
|
||||
}
|
||||
|
||||
fn load_payload(&mut self) -> Option<u32> {
|
||||
@@ -357,6 +353,14 @@ impl<'a> Unpacker<'a> {
|
||||
};
|
||||
|
||||
u.decrypt_data();
|
||||
research::emit_u32s(ResearchStage::Header, "info_words", u.info.to_vec());
|
||||
research::emit_u32_at(
|
||||
ResearchStage::Header,
|
||||
"magic",
|
||||
u.info[1],
|
||||
AddressSpace::FileOffset,
|
||||
0x1004,
|
||||
);
|
||||
if verbose {
|
||||
println!("[1/9] Decrypting file header...");
|
||||
println!(" info[0] key = 0x{:08X}", u.info[0]);
|
||||
@@ -390,10 +394,34 @@ impl<'a> Unpacker<'a> {
|
||||
});
|
||||
}
|
||||
u.decompressed = vec![0u8; size_of_image as usize];
|
||||
research::emit_u32_at(
|
||||
ResearchStage::Payload,
|
||||
"size_of_image",
|
||||
size_of_image,
|
||||
AddressSpace::FileOffset,
|
||||
pe_off.wrapping_add(80) as u64,
|
||||
);
|
||||
research::emit_range(
|
||||
ResearchStage::Payload,
|
||||
"declared_payload",
|
||||
AddressSpace::FileOffset,
|
||||
u.info[4] as u64 + 0x1000,
|
||||
u.info[5] as u64,
|
||||
);
|
||||
if verbose {
|
||||
println!("[2/9] Decrypting payload...");
|
||||
}
|
||||
let pe32_table = u.load_payload();
|
||||
research::emit_u32(ResearchStage::Payload, "prefix_length", u.decrypt_size);
|
||||
if let Some(table) = pe32_table {
|
||||
research::emit_u32_at(
|
||||
ResearchStage::Pe32Shell,
|
||||
"shell_table",
|
||||
table,
|
||||
AddressSpace::WorkingImageRva,
|
||||
table as u64,
|
||||
);
|
||||
}
|
||||
|
||||
// PE32 (32-bit) images use an entirely different config layout and
|
||||
// final-output transform than PE32+ (64-bit). Dispatch here, after the
|
||||
@@ -463,6 +491,18 @@ impl<'a> Unpacker<'a> {
|
||||
.into_iter()
|
||||
.find(|&extra| descriptor_is_valid(extra))
|
||||
.ok_or(UnpackError::Stage1DescriptorNotFound { anchor })?;
|
||||
research::emit_u32_at(
|
||||
ResearchStage::ExeStage1,
|
||||
"anchor",
|
||||
anchor,
|
||||
AddressSpace::WorkingImageRva,
|
||||
anchor as u64,
|
||||
);
|
||||
research::emit_u32(
|
||||
ResearchStage::ExeStage1,
|
||||
"anchor_layout_extra",
|
||||
anchor_extra,
|
||||
);
|
||||
|
||||
if verbose {
|
||||
println!(" anchor = 0x{anchor:08X}");
|
||||
@@ -502,6 +542,18 @@ impl<'a> Unpacker<'a> {
|
||||
u.decrypt_data3(tgt, xor_acc ^ chk1 ^ v, 21);
|
||||
let stage1 = get_u32(&u.decompressed, tgt);
|
||||
let stage1_len = get_u32(&u.decompressed, tgt.wrapping_add(4));
|
||||
research::emit_range(
|
||||
ResearchStage::ExeStage1,
|
||||
"stage1",
|
||||
AddressSpace::WorkingImageRva,
|
||||
stage1 as u64,
|
||||
stage1_len as u64,
|
||||
);
|
||||
research::emit_u32s(
|
||||
ResearchStage::ExeStage1,
|
||||
"stage1_descriptor",
|
||||
stage1_descriptor.to_vec(),
|
||||
);
|
||||
if verbose {
|
||||
println!("[3/9] Locating config layout...");
|
||||
println!(" stage1 = 0x{:08X}", stage1);
|
||||
@@ -587,6 +639,19 @@ impl<'a> Unpacker<'a> {
|
||||
let stage1b = stage1.wrapping_add(stage2_off);
|
||||
u.decrypt_data3(stage1b, key2, 19);
|
||||
let stage2 = get_u32(&u.decompressed, stage1b);
|
||||
research::emit_u32(ResearchStage::ExeStage2, "stage2_offset", stage2_off);
|
||||
research::emit_u32_at(
|
||||
ResearchStage::ExeStage2,
|
||||
"stage2",
|
||||
stage2,
|
||||
AddressSpace::WorkingImageRva,
|
||||
stage2 as u64,
|
||||
);
|
||||
research::emit_u32(
|
||||
ResearchStage::ExeStage2,
|
||||
"checksum_table_offset",
|
||||
chk_src_start,
|
||||
);
|
||||
if verbose {
|
||||
println!("[4/9] Decrypting stage2...");
|
||||
println!(" stage2 = 0x{:08X}", stage2);
|
||||
@@ -680,6 +745,11 @@ impl<'a> Unpacker<'a> {
|
||||
}
|
||||
walk2 = walk2.wrapping_add(32);
|
||||
}
|
||||
research::emit_u32s(
|
||||
ResearchStage::ExeStage2,
|
||||
"key_offsets",
|
||||
u.key_offsets.to_vec(),
|
||||
);
|
||||
if verbose {
|
||||
println!(
|
||||
" key offsets = [0x{:08X}, 0x{:08X}, 0x{:08X}, 0x{:08X}]",
|
||||
@@ -718,6 +788,14 @@ impl<'a> Unpacker<'a> {
|
||||
println!(" stage3 accum seed = 0x{accum_seed:08X}");
|
||||
}
|
||||
let stage3_key = xor_acc ^ chk2 ^ accum;
|
||||
research::emit_range(
|
||||
ResearchStage::ExeStage3,
|
||||
"stage3_descriptor",
|
||||
AddressSpace::WorkingImageRva,
|
||||
stage3_field as u64,
|
||||
stage3_dlen as u64,
|
||||
);
|
||||
research::emit_u32(ResearchStage::ExeStage3, "stage3_accum_seed", accum_seed);
|
||||
let stage3_source_end = (stage3_field as usize)
|
||||
.checked_add(stage3_slen as usize)
|
||||
.filter(|&end| end <= u.decompressed.len())
|
||||
@@ -774,6 +852,11 @@ impl<'a> Unpacker<'a> {
|
||||
}
|
||||
}
|
||||
if let Some(rounds) = selected {
|
||||
research::emit_u32(
|
||||
ResearchStage::ExeStage3,
|
||||
"selected_accumulator_rounds",
|
||||
rounds,
|
||||
);
|
||||
if verbose {
|
||||
println!(" selected stage3 accumulator rounds = {rounds}");
|
||||
}
|
||||
@@ -858,6 +941,20 @@ impl<'a> Unpacker<'a> {
|
||||
(crdp_end.wrapping_add(15)) & !15u32
|
||||
});
|
||||
u.decrypt_data6(data_offset);
|
||||
research::emit_u32_at(
|
||||
ResearchStage::ExeStage4,
|
||||
"bytecode",
|
||||
data_offset,
|
||||
AddressSpace::WorkingImageRva,
|
||||
data_offset as u64,
|
||||
);
|
||||
research::emit_range(
|
||||
ResearchStage::ExeStage4,
|
||||
"stage4_descriptor",
|
||||
AddressSpace::WorkingImageRva,
|
||||
stage4_field as u64,
|
||||
stage4_dlen as u64,
|
||||
);
|
||||
let chk5 = u.calculate_checksum(stage1.wrapping_add(chk_src_start.wrapping_add(8)));
|
||||
// accum2 sits 4 bytes past the function-end `48 EB 01 B9` + any CC padding
|
||||
// (i.e., the 4 bytes immediately after the last instance of that pattern).
|
||||
@@ -937,6 +1034,18 @@ impl<'a> Unpacker<'a> {
|
||||
reason: first_failure.expect("at least one Stage5 candidate was tried"),
|
||||
});
|
||||
};
|
||||
research::emit_u32(
|
||||
ResearchStage::ExeStage5,
|
||||
"selected_accumulator_rounds",
|
||||
selected_rounds,
|
||||
);
|
||||
research::emit_range(
|
||||
ResearchStage::ExeStage5,
|
||||
"stage5_descriptor",
|
||||
AddressSpace::WorkingImageRva,
|
||||
stage5_field as u64,
|
||||
stage5_dlen as u64,
|
||||
);
|
||||
if verbose {
|
||||
println!(" selected stage5 accumulator rounds = {selected_rounds}");
|
||||
}
|
||||
@@ -985,6 +1094,14 @@ impl<'a> Unpacker<'a> {
|
||||
// rather than the walk5 encrypted-pointer table. `new_layout` selects
|
||||
// that path.
|
||||
let new_layout = kind_pos_opt.is_none();
|
||||
research::emit_bool(ResearchStage::ExeStage5, "new_layout", new_layout);
|
||||
research::emit_u32_at(
|
||||
ResearchStage::ExeStage5,
|
||||
"stage5_marker",
|
||||
s5_marker,
|
||||
AddressSpace::WorkingImageRva,
|
||||
s5_marker as u64,
|
||||
);
|
||||
let kind_pos = kind_pos_opt.unwrap_or_else(|| s5_marker.wrapping_add(88));
|
||||
let walk4_slot = kind_pos.wrapping_sub(0x20);
|
||||
let walk3_slot = kind_pos.wrapping_sub(0x18);
|
||||
@@ -1021,6 +1138,20 @@ impl<'a> Unpacker<'a> {
|
||||
.ok_or(UnpackError::Stage5MarkerNotFound)?;
|
||||
walk4_slot = slots.compressed_info_ptr;
|
||||
bc2_off = slots.file_lfsr;
|
||||
research::emit_u32_at(
|
||||
ResearchStage::ExeStage5,
|
||||
"compressed_info_ptr",
|
||||
walk4_slot,
|
||||
AddressSpace::WorkingImageRva,
|
||||
walk4_slot as u64,
|
||||
);
|
||||
research::emit_u32_at(
|
||||
ResearchStage::ExeStage5,
|
||||
"file_lfsr",
|
||||
bc2_off,
|
||||
AddressSpace::WorkingImageRva,
|
||||
bc2_off as u64,
|
||||
);
|
||||
}
|
||||
let at5 = walk3_slot;
|
||||
let mut walk3 = get_u32(&u.decompressed, at5);
|
||||
@@ -1089,8 +1220,16 @@ impl<'a> Unpacker<'a> {
|
||||
// block (fileDecryptorAddress = fileChecksumAddresses + 0x58). Walk
|
||||
// 16-byte entries until the size dword (offset +4) is zero, decrypting
|
||||
// each.
|
||||
let file_cs = get_u32(&u.decompressed, bc2_off.wrapping_sub(0x58));
|
||||
research::emit_u32_at(
|
||||
ResearchStage::ExeStage5,
|
||||
"file_checksums",
|
||||
file_cs,
|
||||
AddressSpace::WorkingImageRva,
|
||||
file_cs as u64,
|
||||
);
|
||||
{
|
||||
let mut fcs = get_u32(&u.decompressed, bc2_off.wrapping_sub(0x58));
|
||||
let mut fcs = file_cs;
|
||||
while get_u32(&u.decompressed, fcs.wrapping_add(4)) != 0 {
|
||||
u.decrypt_data5(fcs, 16);
|
||||
fcs = fcs.wrapping_add(16);
|
||||
@@ -1149,6 +1288,51 @@ impl<'a> Unpacker<'a> {
|
||||
break;
|
||||
}
|
||||
}
|
||||
{
|
||||
let compressed = blocks
|
||||
.iter()
|
||||
.filter(|block| block.len != block.plain_len)
|
||||
.count();
|
||||
let compressed_bytes: u64 = blocks
|
||||
.iter()
|
||||
.filter(|block| block.len != block.plain_len)
|
||||
.map(|block| u64::from(block.len))
|
||||
.sum();
|
||||
let output_bytes: u64 = blocks
|
||||
.iter()
|
||||
.map(|block| u64::from(block.len.max(block.plain_len)))
|
||||
.sum();
|
||||
research::emit_u32(
|
||||
ResearchStage::Sections,
|
||||
"block_count",
|
||||
u32::try_from(blocks.len()).unwrap_or(u32::MAX),
|
||||
);
|
||||
research::emit_u32(
|
||||
ResearchStage::Sections,
|
||||
"compressed_block_count",
|
||||
u32::try_from(compressed).unwrap_or(u32::MAX),
|
||||
);
|
||||
research::emit_u64(
|
||||
ResearchStage::Sections,
|
||||
"compressed_bytes",
|
||||
compressed_bytes,
|
||||
);
|
||||
research::emit_u64(ResearchStage::Sections, "output_bytes", output_bytes);
|
||||
research::emit_u32_at(
|
||||
ResearchStage::Sections,
|
||||
"aes_schedule",
|
||||
u.key_offsets[2],
|
||||
AddressSpace::WorkingImageRva,
|
||||
u.key_offsets[2] as u64,
|
||||
);
|
||||
research::emit_u32_at(
|
||||
ResearchStage::Sections,
|
||||
"huffman_table",
|
||||
u.key_offsets[0],
|
||||
AddressSpace::WorkingImageRva,
|
||||
u.key_offsets[0] as u64,
|
||||
);
|
||||
}
|
||||
// Pass 2: each block writes only its own [dst, dst+max(len,plain_len))
|
||||
// span and reads only immutable input + the (snapshotted) key tables,
|
||||
// so blocks with disjoint dst spans are independent. `parallel_for`
|
||||
@@ -1397,9 +1581,18 @@ impl<'a> Unpacker<'a> {
|
||||
Some(s) => s,
|
||||
None => layout::select_dd8_shift(&u.decompressed, text_va, text_size, u.info[3]),
|
||||
};
|
||||
// The chosen selector value itself: the page-XOR shift, with 99
|
||||
// meaning the selector chose to skip dd8 entirely.
|
||||
research::emit_u32(ResearchStage::Sections, "text_dd8_shift", dd8_shift);
|
||||
if dd8_shift != 99 {
|
||||
let mut page = text_va >> 12;
|
||||
let end_page = text_va.wrapping_add(text_size) >> 12;
|
||||
research::emit_u32(ResearchStage::Sections, "dd8_first_page", page);
|
||||
research::emit_u32(
|
||||
ResearchStage::Sections,
|
||||
"dd8_page_count",
|
||||
end_page.saturating_sub(page),
|
||||
);
|
||||
while page < end_page {
|
||||
u.decrypt_data8(page << 12, 4096, page << dd8_shift);
|
||||
page = page.wrapping_add(1);
|
||||
@@ -1430,6 +1623,7 @@ impl<'a> Unpacker<'a> {
|
||||
.unwrap_or(64)
|
||||
};
|
||||
let dd_off = ep_off.wrapping_add(16);
|
||||
research::emit_u32(ResearchStage::ExeStage5, "ep_layout_offset", ep_off);
|
||||
// The metadata block (EP + data directories) is read transiently: decrypt
|
||||
// it, copy EP and dirs into the PE header, then RESTORE the original
|
||||
// encrypted bytes. The packer leaves this region encrypted in its output,
|
||||
@@ -1524,9 +1718,16 @@ impl<'a> Unpacker<'a> {
|
||||
layout::select_dd8_shift(&u.decompressed, text_va, text_size, u.info[3])
|
||||
}
|
||||
};
|
||||
research::emit_u32(ResearchStage::Sections, "text_dd8_shift", shift);
|
||||
if shift != 99 {
|
||||
let mut page = text_va >> 12;
|
||||
let end_page = text_va.wrapping_add(text_size) >> 12;
|
||||
research::emit_u32(ResearchStage::Sections, "dd8_first_page", page);
|
||||
research::emit_u32(
|
||||
ResearchStage::Sections,
|
||||
"dd8_page_count",
|
||||
end_page.saturating_sub(page),
|
||||
);
|
||||
while page < end_page {
|
||||
u.decrypt_data8(page << 12, 4096, page << shift);
|
||||
page = page.wrapping_add(1);
|
||||
@@ -1538,6 +1739,13 @@ impl<'a> Unpacker<'a> {
|
||||
// by-name import's hint/name, and recover the IAT (DD[12]).
|
||||
let import_rva = get_u32(&u.decompressed, pe_off2.wrapping_add(0x90));
|
||||
let import_size = get_u32(&u.decompressed, pe_off2.wrapping_add(0x94));
|
||||
research::emit_range(
|
||||
ResearchStage::Imports,
|
||||
"import_directory",
|
||||
AddressSpace::WorkingImageRva,
|
||||
import_rva as u64,
|
||||
import_size as u64,
|
||||
);
|
||||
if import_rva != 0 {
|
||||
u.process_imports_idt(import_rva, import_size, pe_off2);
|
||||
}
|
||||
@@ -1651,13 +1859,31 @@ impl<'a> Unpacker<'a> {
|
||||
// handled by `job::restore_tls_from_stub`.
|
||||
let tls_dd_off = pe_off2.wrapping_add(136 + 9 * 8);
|
||||
let tls_rva = get_u32(&u.decompressed, tls_dd_off);
|
||||
research::emit_u32_at(
|
||||
ResearchStage::Tls,
|
||||
"directory_rva",
|
||||
tls_rva,
|
||||
AddressSpace::WorkingImageRva,
|
||||
tls_rva as u64,
|
||||
);
|
||||
if tls_rva != 0 && (tls_rva as usize + 40) <= u.decompressed.len() {
|
||||
let tls_all_zero = u.decompressed[tls_rva as usize..tls_rva as usize + 40]
|
||||
.iter()
|
||||
.all(|&b| b == 0);
|
||||
if tls_all_zero {
|
||||
let image_base = get_u64(&u.decompressed, pe_off2.wrapping_add(48));
|
||||
if new_layout || !u.restore_pe64_tls_from_stub(pe_off, tls_rva, image_base) {
|
||||
let restored =
|
||||
!new_layout && u.restore_pe64_tls_from_stub(pe_off, tls_rva, image_base);
|
||||
research::emit_text(
|
||||
ResearchStage::Tls,
|
||||
"directory_action",
|
||||
if restored {
|
||||
"restored_from_stub"
|
||||
} else {
|
||||
"cleared"
|
||||
},
|
||||
);
|
||||
if !restored {
|
||||
write_u32(&mut u.decompressed, tls_dd_off, 0);
|
||||
write_u32(&mut u.decompressed, tls_dd_off.wrapping_add(4), 0);
|
||||
}
|
||||
@@ -1713,6 +1939,12 @@ impl<'a> Unpacker<'a> {
|
||||
);
|
||||
}
|
||||
|
||||
research::emit_u64(
|
||||
ResearchStage::Output,
|
||||
"output_len",
|
||||
u.decompressed.len() as u64,
|
||||
);
|
||||
research::emit_u32(ResearchStage::Finalize, "kind", if is_dll { 1 } else { 0 });
|
||||
Ok(u.decompressed)
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,17 @@
|
||||
use super::super::super::layout;
|
||||
use super::super::super::research::{self, AddressSpace, ResearchStage};
|
||||
use super::*;
|
||||
|
||||
/// Name of the dd8 formula the PE32 selector actually chose. `None` is the
|
||||
/// selector's skip verdict, not "did not run".
|
||||
fn dd8_selection_label(selection: Option<bool>) -> &'static str {
|
||||
match selection {
|
||||
Some(true) => "0x8000*(page+1)",
|
||||
Some(false) => "page+1",
|
||||
None => "skip",
|
||||
}
|
||||
}
|
||||
|
||||
fn stage_key_rounds(data: &[u8], table: u32, slots: usize) -> Result<u32, UnpackError> {
|
||||
let offset = table as usize;
|
||||
let size = slots.saturating_mul(16);
|
||||
@@ -189,6 +200,14 @@ impl<'a> Unpacker<'a> {
|
||||
// ---- Validated shell table ----
|
||||
let compact = get_u32(&self.decompressed, tbl.wrapping_add(0x78)) == info[6];
|
||||
let stage_field = if compact { 0x88 } else { 0x98 };
|
||||
research::emit_bool(ResearchStage::Pe32Shell, "compact_layout", compact);
|
||||
research::emit_u32_at(
|
||||
ResearchStage::Pe32Shell,
|
||||
"table",
|
||||
tbl,
|
||||
AddressSpace::WorkingImageRva,
|
||||
tbl as u64,
|
||||
);
|
||||
if verbose {
|
||||
println!("[3/9] Locating config layout (PE32)...");
|
||||
println!(" tbl = 0x{:X}, compact = {}", tbl, compact);
|
||||
@@ -201,6 +220,19 @@ impl<'a> Unpacker<'a> {
|
||||
let ss_shift = ss_size.wrapping_sub(if compact { 0xAEC } else { 0xBC0 });
|
||||
let third_pair_off = (if compact { 0xAB4u32 } else { 0xB8C }).wrapping_add(ss_shift);
|
||||
let header_checksum = self.decrypt_pe32_second_stage(tbl, pe_off)?;
|
||||
research::emit_range(
|
||||
ResearchStage::Pe32Stages,
|
||||
"second_stage",
|
||||
AddressSpace::WorkingImageRva,
|
||||
ss as u64,
|
||||
ss_size as u64,
|
||||
);
|
||||
research::emit_u32(ResearchStage::Pe32Stages, "second_stage_shift", ss_shift);
|
||||
research::emit_u32(
|
||||
ResearchStage::Pe32Stages,
|
||||
"header_checksum",
|
||||
header_checksum,
|
||||
);
|
||||
if verbose {
|
||||
println!(
|
||||
" ss = 0x{:08X}, size = 0x{:X}, shift = 0x{:X}",
|
||||
@@ -257,6 +289,20 @@ impl<'a> Unpacker<'a> {
|
||||
}
|
||||
}
|
||||
let info_table = info_table.ok_or(UnpackError::Pe32ThirdStageFailed)?;
|
||||
research::emit_u32_at(
|
||||
ResearchStage::Pe32Stages,
|
||||
"third_stage",
|
||||
ts,
|
||||
AddressSpace::WorkingImageRva,
|
||||
ts as u64,
|
||||
);
|
||||
research::emit_u32_at(
|
||||
ResearchStage::Pe32Stages,
|
||||
"info_table",
|
||||
info_table,
|
||||
AddressSpace::WorkingImageRva,
|
||||
info_table as u64,
|
||||
);
|
||||
if verbose {
|
||||
println!("[4/9] Decrypting stages (PE32)...");
|
||||
println!(
|
||||
@@ -306,6 +352,11 @@ impl<'a> Unpacker<'a> {
|
||||
ka = ka.wrapping_add(32);
|
||||
}
|
||||
|
||||
research::emit_u32s(
|
||||
ResearchStage::Pe32Stages,
|
||||
"key_offsets",
|
||||
self.key_offsets.to_vec(),
|
||||
);
|
||||
// ---- Checksum addresses ----
|
||||
let second_stage_cs_addr = tbl.wrapping_add(stage_field + 0x18);
|
||||
let forth_stage_cs_addr = ss.wrapping_add(cs_base_off);
|
||||
@@ -403,6 +454,13 @@ impl<'a> Unpacker<'a> {
|
||||
})
|
||||
.ok_or(UnpackError::Pe32CustomDecryptorNotFound)?;
|
||||
let custom_dec_addr = seven_start_actual.wrapping_add(custom_dec_off);
|
||||
research::emit_u32_at(
|
||||
ResearchStage::Pe32Stages,
|
||||
"custom_decryptor",
|
||||
custom_dec_addr,
|
||||
AddressSpace::WorkingImageRva,
|
||||
custom_dec_addr as u64,
|
||||
);
|
||||
self.decrypt_data6(custom_dec_addr);
|
||||
let custom_ops = generate(&self.decompressed, custom_dec_addr).ok_or(
|
||||
UnpackError::BytecodeGenerationFailed(BytecodeStage::Pe32CustomDecryptor),
|
||||
@@ -503,6 +561,11 @@ impl<'a> Unpacker<'a> {
|
||||
if !eighth_ok {
|
||||
return Err(UnpackError::Pe32EighthKeyNotFound);
|
||||
}
|
||||
research::emit_u32(
|
||||
ResearchStage::Pe32Stages,
|
||||
"eighth_key_rounds",
|
||||
eighth_key_rounds,
|
||||
);
|
||||
let eighth_start = get_u32(&self.decompressed, eighth_addr);
|
||||
if verbose {
|
||||
println!(
|
||||
@@ -704,7 +767,28 @@ impl<'a> Unpacker<'a> {
|
||||
}
|
||||
chosen.ok_or(UnpackError::Pe32FileLfsrNotFound)?
|
||||
};
|
||||
research::emit_u32_at(
|
||||
ResearchStage::Pe32Stages,
|
||||
"cluster_base",
|
||||
eighth_start.wrapping_add(off_import_table.wrapping_sub(0x18)),
|
||||
AddressSpace::WorkingImageRva,
|
||||
eighth_start.wrapping_add(off_import_table.wrapping_sub(0x18)) as u64,
|
||||
);
|
||||
research::emit_u32_at(
|
||||
ResearchStage::Pe32Stages,
|
||||
"file_checksums",
|
||||
get_u32(&self.decompressed, eighth_start.wrapping_add(off_file_cs)),
|
||||
AddressSpace::WorkingImageRva,
|
||||
eighth_start.wrapping_add(off_file_cs) as u64,
|
||||
);
|
||||
let file_dec_addr = eighth_start.wrapping_add(lfsr_off);
|
||||
research::emit_u32_at(
|
||||
ResearchStage::Pe32Stages,
|
||||
"file_lfsr",
|
||||
file_dec_addr,
|
||||
AddressSpace::WorkingImageRva,
|
||||
file_dec_addr as u64,
|
||||
);
|
||||
self.decrypt_data6(file_dec_addr);
|
||||
let file_ops = generate(&self.decompressed, file_dec_addr).ok_or(
|
||||
UnpackError::BytecodeGenerationFailed(BytecodeStage::Pe32FileDecryptor),
|
||||
@@ -765,6 +849,48 @@ impl<'a> Unpacker<'a> {
|
||||
dsz: d_sz2,
|
||||
});
|
||||
}
|
||||
{
|
||||
let compressed = blocks.iter().filter(|block| block.ssz != block.dsz).count();
|
||||
let compressed_bytes: u64 = blocks
|
||||
.iter()
|
||||
.filter(|block| block.ssz != block.dsz)
|
||||
.map(|block| u64::from(block.ssz))
|
||||
.sum();
|
||||
let output_bytes: u64 = blocks
|
||||
.iter()
|
||||
.map(|block| u64::from(block.ssz.max(block.dsz)))
|
||||
.sum();
|
||||
research::emit_u32(
|
||||
ResearchStage::Sections,
|
||||
"block_count",
|
||||
u32::try_from(blocks.len()).unwrap_or(u32::MAX),
|
||||
);
|
||||
research::emit_u32(
|
||||
ResearchStage::Sections,
|
||||
"compressed_block_count",
|
||||
u32::try_from(compressed).unwrap_or(u32::MAX),
|
||||
);
|
||||
research::emit_u64(
|
||||
ResearchStage::Sections,
|
||||
"compressed_bytes",
|
||||
compressed_bytes,
|
||||
);
|
||||
research::emit_u64(ResearchStage::Sections, "output_bytes", output_bytes);
|
||||
research::emit_u32_at(
|
||||
ResearchStage::Sections,
|
||||
"aes_schedule",
|
||||
self.key_offsets[2],
|
||||
AddressSpace::WorkingImageRva,
|
||||
self.key_offsets[2] as u64,
|
||||
);
|
||||
research::emit_u32_at(
|
||||
ResearchStage::Sections,
|
||||
"huffman_table",
|
||||
self.key_offsets[0],
|
||||
AddressSpace::WorkingImageRva,
|
||||
self.key_offsets[0] as u64,
|
||||
);
|
||||
}
|
||||
// Pass 2: independent per-block work over disjoint dst spans (see
|
||||
// `parallel_for` for how the spans are carved safely).
|
||||
{
|
||||
@@ -889,15 +1015,40 @@ impl<'a> Unpacker<'a> {
|
||||
// encrypted (native DLLs leave it plaintext); applying dd8 there would
|
||||
// scramble valid code, so skip it entirely in that case.
|
||||
if text_size > 0 && text_off > 0 {
|
||||
if let Some(big) =
|
||||
layout::select_dd8_formula_pe32(&self.decompressed, text_off, text_size)
|
||||
{
|
||||
let selection =
|
||||
layout::select_dd8_formula_pe32(&self.decompressed, text_off, text_size);
|
||||
// The selector's own verdict: the chosen formula, or that it chose
|
||||
// to skip dd8. Not a "did anything run" flag.
|
||||
research::emit_text(
|
||||
ResearchStage::Sections,
|
||||
"text_dd8_selection",
|
||||
dd8_selection_label(selection),
|
||||
);
|
||||
if let Some(big) = selection {
|
||||
if verbose {
|
||||
println!(
|
||||
"[7/9] Decrypting .text (PE32 dd8, formula={})...",
|
||||
if big { "0x8000*(page+1)" } else { "page+1" }
|
||||
);
|
||||
}
|
||||
research::emit_text(
|
||||
ResearchStage::Sections,
|
||||
"dd8_formula",
|
||||
if big { "0x8000*(page+1)" } else { "page+1" },
|
||||
);
|
||||
// Reproducible parameters of the selected formula: the page
|
||||
// multiplier, the first page index, and the page count.
|
||||
research::emit_u32(
|
||||
ResearchStage::Sections,
|
||||
"dd8_formula_multiplier",
|
||||
if big { 0x8000 } else { 1 },
|
||||
);
|
||||
research::emit_u32(ResearchStage::Sections, "dd8_first_page", text_off >> 12);
|
||||
research::emit_u32(
|
||||
ResearchStage::Sections,
|
||||
"dd8_page_count",
|
||||
text_size / 0x1000,
|
||||
);
|
||||
let num_pages = text_size / 0x1000;
|
||||
for page in 0..num_pages {
|
||||
let pk = if big {
|
||||
@@ -958,6 +1109,13 @@ impl<'a> Unpacker<'a> {
|
||||
// ---- TLS directory reconstruction (PE32: index 9 = pe+0xC0) ----
|
||||
let tls_dir_rva = get_u32(&self.decompressed, exe_pe.wrapping_add(0xC0));
|
||||
let tls_dir_sz = get_u32(&self.decompressed, exe_pe.wrapping_add(0xC4));
|
||||
research::emit_u32_at(
|
||||
ResearchStage::Tls,
|
||||
"directory_rva",
|
||||
tls_dir_rva,
|
||||
AddressSpace::WorkingImageRva,
|
||||
tls_dir_rva as u64,
|
||||
);
|
||||
if tls_dir_rva > 0
|
||||
&& tls_dir_sz >= 24
|
||||
&& (tls_dir_rva as usize + 24) <= self.decompressed.len()
|
||||
@@ -972,7 +1130,17 @@ impl<'a> Unpacker<'a> {
|
||||
// the image loadable, but drops the initialized TLS template,
|
||||
// `_tls_index` and the TLS callback array, so any module that
|
||||
// actually uses `thread_local` faults once it runs.
|
||||
if !self.restore_pe32_tls_from_stub(pe_off, tls_dir_rva, image_base) {
|
||||
let tls_restored = self.restore_pe32_tls_from_stub(pe_off, tls_dir_rva, image_base);
|
||||
research::emit_text(
|
||||
ResearchStage::Tls,
|
||||
"directory_action",
|
||||
if tls_restored {
|
||||
"restored_from_stub"
|
||||
} else {
|
||||
"synthesized_or_cleared"
|
||||
},
|
||||
);
|
||||
if !tls_restored {
|
||||
let mut tls_sec_va: u32 = 0;
|
||||
let mut data_sec_va: u32 = 0;
|
||||
let mut data_sec_sz: u32 = 0;
|
||||
@@ -1093,6 +1261,13 @@ impl<'a> Unpacker<'a> {
|
||||
let import_table_addr = eighth_start.wrapping_add(off_import_table);
|
||||
let mut import_table_ptr = get_u32(&self.decompressed, import_table_addr);
|
||||
let mut idt_size = get_u32(&self.decompressed, import_table_addr.wrapping_add(4));
|
||||
research::emit_range(
|
||||
ResearchStage::Imports,
|
||||
"eighth_stage_import_table",
|
||||
AddressSpace::WorkingImageRva,
|
||||
import_table_ptr as u64,
|
||||
idt_size as u64,
|
||||
);
|
||||
|
||||
let metadata_import_rva = get_u32(&metadata_dirs, 8);
|
||||
let metadata_import_size = get_u32(&metadata_dirs, 12);
|
||||
@@ -1197,8 +1372,16 @@ impl<'a> Unpacker<'a> {
|
||||
if !is_dll && !layout::pe32_imports_already_match_idata_layout(&mut out, pe_off) {
|
||||
layout::move_pe32_imports_to_kmiat(&mut out, pe_off);
|
||||
}
|
||||
research::emit_range(
|
||||
ResearchStage::Imports,
|
||||
"selected_import_table",
|
||||
AddressSpace::WorkingImageRva,
|
||||
import_table_ptr as u64,
|
||||
idt_size as u64,
|
||||
);
|
||||
let compact = layout::compact_memory_image_to_pe(&out, pe_off)
|
||||
.ok_or(UnpackError::Pe32OutputLayoutInvalid)?;
|
||||
research::emit_u64(ResearchStage::Output, "output_len", compact.len() as u64);
|
||||
Ok(compact)
|
||||
}
|
||||
}
|
||||
@@ -1257,6 +1440,13 @@ mod tests {
|
||||
check_metadata(false, true);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dd8_selection_label_reports_the_chosen_formula_or_skip() {
|
||||
assert_eq!(dd8_selection_label(Some(true)), "0x8000*(page+1)");
|
||||
assert_eq!(dd8_selection_label(Some(false)), "page+1");
|
||||
assert_eq!(dd8_selection_label(None), "skip");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stage_key_rounds_follow_active_descriptor_prefix() {
|
||||
for (sizes, expected) in [
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -7,8 +7,8 @@ mod image;
|
||||
pub(super) use dd8::{select_dd8_formula_pe32, select_dd8_shift};
|
||||
pub(super) use discovery::{
|
||||
discover_eighth_slots, find_bytecode_offset, find_lfsr_block, find_str_pos,
|
||||
find_tbl_pe32_candidates, find_v_after_pad, find_v4_offset, get_string_to_null, section_name,
|
||||
trial_decrypt5_u32,
|
||||
find_tbl_pe32_candidates, find_tbl_pe32_candidates_counted, find_v_after_pad, find_v4_offset,
|
||||
get_string_to_null, section_name, trial_decrypt5_u32,
|
||||
};
|
||||
pub(super) use image::{
|
||||
compact_memory_image_to_pe, move_pe32_imports_to_kmiat, pe32_imports_already_match_idata_layout,
|
||||
|
||||
@@ -217,18 +217,52 @@ pub fn section_name(data: &[u8], offset: u32) -> String {
|
||||
/// Return structurally plausible candidates; the pipeline must trial-decrypt
|
||||
/// their second stages before selecting a table.
|
||||
pub fn find_tbl_pe32_candidates(data: &[u8], info: &[u32; 8]) -> Vec<u32> {
|
||||
find_tbl_pe32_candidates_window(data, info, 0, data.len() as u64)
|
||||
}
|
||||
|
||||
/// [`find_tbl_pe32_candidates`] for a buffer that starts at working-image RVA
|
||||
/// `base` rather than at RVA 0 (a decoded payload prefix scratch).
|
||||
///
|
||||
/// `info[3]` and `info[6]` stay absolute; only the buffer origin changes, so a
|
||||
/// stage RVA is converted with `stage - base` before the in-buffer bounds
|
||||
/// check. `window_len` is the number of bytes from `base` to the end of the
|
||||
/// declared image, which may exceed `data.len()` for a bounded prefix scratch.
|
||||
/// All byte reads still require `data` to contain them; `window_len` only
|
||||
/// relaxes the plausibility checks for structures (the shell region and the
|
||||
/// stage range) that lie beyond the probe. With `base == 0` and
|
||||
/// `window_len == data.len()` this is exactly the original locator.
|
||||
pub fn find_tbl_pe32_candidates_window(
|
||||
data: &[u8],
|
||||
info: &[u32; 8],
|
||||
base: u32,
|
||||
window_len: u64,
|
||||
) -> Vec<u32> {
|
||||
find_tbl_pe32_candidates_counted(data, info, base, window_len).0
|
||||
}
|
||||
|
||||
/// [`find_tbl_pe32_candidates_window`] that also returns the number of
|
||||
/// 4-byte positions the scan examined. Research inspection reports that count
|
||||
/// as scan effort; it is never a candidate count.
|
||||
pub fn find_tbl_pe32_candidates_counted(
|
||||
data: &[u8],
|
||||
info: &[u32; 8],
|
||||
base: u32,
|
||||
window_len: u64,
|
||||
) -> (Vec<u32>, u32) {
|
||||
let mut tables = Vec::new();
|
||||
let shell = info[6] as usize;
|
||||
let mut positions_scanned = 0u32;
|
||||
let shell = info[6].wrapping_sub(base) as usize;
|
||||
let hi = shell.saturating_add(0x3000).min(data.len());
|
||||
for off in (shell..hi.saturating_sub(8)).step_by(4) {
|
||||
positions_scanned = positions_scanned.saturating_add(1);
|
||||
if get_u32(data, off as u32) != info[6] {
|
||||
continue;
|
||||
}
|
||||
let shell_size = get_u32(data, off as u32 + 4) as usize;
|
||||
if !(0x1001..0x100000).contains(&shell_size)
|
||||
|| shell
|
||||
.checked_add(shell_size)
|
||||
.is_none_or(|end| end > data.len())
|
||||
|| (shell as u64)
|
||||
.checked_add(shell_size as u64)
|
||||
.is_none_or(|end| end > window_len)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
@@ -241,25 +275,26 @@ pub fn find_tbl_pe32_candidates(data: &[u8], info: &[u32; 8]) -> Vec<u32> {
|
||||
};
|
||||
let header = get_u32(table, header_field) as usize;
|
||||
let header_size = get_u32(table, header_field + 4) as usize;
|
||||
let stage = get_u32(table, shell_field as u32 + 0x10) as usize;
|
||||
let stage = get_u32(table, shell_field as u32 + 0x10);
|
||||
let stage_size = get_u32(table, shell_field as u32 + 0x14) as usize;
|
||||
let stage_rel = stage.wrapping_sub(base) as u64;
|
||||
if header > 0
|
||||
&& header_size > 0
|
||||
&& header
|
||||
.checked_add(header_size)
|
||||
.is_some_and(|end| end <= 0x1000)
|
||||
&& stage >= info[3] as usize
|
||||
&& stage >= info[3]
|
||||
&& stage_size >= 4
|
||||
&& stage
|
||||
.checked_add(stage_size)
|
||||
.is_some_and(|end| end <= data.len())
|
||||
&& stage_rel
|
||||
.checked_add(stage_size as u64)
|
||||
.is_some_and(|end| end <= window_len)
|
||||
&& !tables.contains(&(candidate as u32))
|
||||
{
|
||||
tables.push(candidate as u32);
|
||||
}
|
||||
}
|
||||
}
|
||||
tables
|
||||
(tables, positions_scanned)
|
||||
}
|
||||
|
||||
/// Locate an LFSR-encrypted bytecode block (decrypt_data6 form) in a region.
|
||||
@@ -484,6 +519,25 @@ mod tests {
|
||||
(data, info, table)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn counted_locator_matches_the_original_and_reports_real_scan_work() {
|
||||
for compact in [false, true] {
|
||||
let (data, info, table) = pe32_table_fixture(compact);
|
||||
let plain = find_tbl_pe32_candidates(&data, &info);
|
||||
let (counted, positions) =
|
||||
find_tbl_pe32_candidates_counted(&data, &info, 0, data.len() as u64);
|
||||
assert_eq!(counted, plain, "compact={compact}");
|
||||
assert_eq!(plain, vec![table]);
|
||||
// The scan runs from info[6] to info[6]+0x3000 in 4-byte steps (or
|
||||
// to the end of the buffer), independent of the candidate count.
|
||||
let shell = info[6] as usize;
|
||||
let hi = (shell + 0x3000).min(data.len());
|
||||
let expected = hi.saturating_sub(8).saturating_sub(shell).div_ceil(4) as u32;
|
||||
assert_eq!(positions, expected);
|
||||
assert!(positions > 1);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pe32_table_supports_compact_header_descriptors() {
|
||||
for compact in [false, true] {
|
||||
|
||||
@@ -3,9 +3,11 @@
|
||||
pub mod dll;
|
||||
mod error;
|
||||
pub mod exe;
|
||||
mod inspect;
|
||||
pub mod integrity;
|
||||
mod layout;
|
||||
pub(crate) mod parallel;
|
||||
pub mod research;
|
||||
|
||||
use senbei_crypto::primitives;
|
||||
use serde::Serialize;
|
||||
@@ -15,6 +17,7 @@ use crate::profile::{
|
||||
ProtectionProfile, RecognitionStatus, RecoveryStatus, TargetFormat,
|
||||
};
|
||||
use integrity::IntegritySeverity as ProfileSeverity;
|
||||
use research::emit_text;
|
||||
|
||||
pub(crate) use crate::panic_capture::{PanicCapture, current_panic_capture, with_panic_capture};
|
||||
|
||||
@@ -22,9 +25,21 @@ pub use crate::thread_cap;
|
||||
pub use dll::{unpack_dll, unpack_dll_v};
|
||||
pub use error::*;
|
||||
pub use exe::{unpack as unpack_exe, unpack_v as unpack_exe_v};
|
||||
pub use inspect::{
|
||||
CandidateField, CandidateStatus, DeclaredPayload, DirectoryInspection, DirectoryMapping,
|
||||
DiscoveryReport, FileRegion, FileRegionKind, FlagField, HeaderWord, HeaderWordSemantic,
|
||||
InspectionIssue, InspectionLimits, InspectionSeverity, InspectionWork, NamedFlag, PayloadCheck,
|
||||
PeInspection, PrefixProbe, ProbeOutcome, ProtectionInspection, SectionAnomaly,
|
||||
SectionAnomalyKind, SectionBacking, SectionInspection, SectionPermissions, ShellCandidate,
|
||||
ShellCandidateKind, WindowsInspection,
|
||||
};
|
||||
pub use integrity::{
|
||||
IntegrityFinding, IntegrityReport, IntegritySeverity, check as check_integrity,
|
||||
};
|
||||
pub use research::{
|
||||
AddressSpace, ResearchEvent, ResearchStage, ResearchTrace, TraceAddress, TraceValue,
|
||||
with_research_trace, with_research_trace_limited,
|
||||
};
|
||||
|
||||
/// Maximum plausible PE `SizeOfImage` we are willing to allocate a zero buffer
|
||||
/// for. Guards against a corrupt/crafted header requesting a multi-gigabyte
|
||||
@@ -219,6 +234,25 @@ pub fn inspect_profile(input: &[u8]) -> ProtectionProfile {
|
||||
inspect_detected(input, detected)
|
||||
}
|
||||
|
||||
/// Rich, read-only research inspection of a Windows input.
|
||||
///
|
||||
/// Reports the PE container, the decoded protection header, the declared
|
||||
/// payload with in-bounds results, and a bounded scratch-only probe for real
|
||||
/// shell structures. It never allocates `SizeOfImage`, runs a recovery stage,
|
||||
/// or executes the input; facts that only later stages expose are reported as
|
||||
/// unavailable by the probe. Malformed input still returns a partial result.
|
||||
#[must_use]
|
||||
pub fn inspect_research(input: &[u8]) -> WindowsInspection {
|
||||
inspect_research_with_limits(input, &InspectionLimits::default())
|
||||
}
|
||||
|
||||
/// [`inspect_research`] with explicit work limits (scratch budget, candidate
|
||||
/// cap, issue cap). Tests and fuzzing use this to prove the bounds.
|
||||
#[must_use]
|
||||
pub fn inspect_research_with_limits(input: &[u8], limits: &InspectionLimits) -> WindowsInspection {
|
||||
inspect::inspect(input, limits)
|
||||
}
|
||||
|
||||
fn inspect_detected(input: &[u8], detected: Option<Detected>) -> ProtectionProfile {
|
||||
let mut profile = ProtectionProfile::new(ObservedTarget::windows(
|
||||
pe_target_format(input),
|
||||
@@ -326,6 +360,7 @@ fn run_exe_attempt(
|
||||
input: &[u8],
|
||||
verbose: bool,
|
||||
) -> Result<Vec<u8>, UnpackError> {
|
||||
emit_text(ResearchStage::Header, "route", "exe_style");
|
||||
match exe::unpack_v(input, verbose) {
|
||||
Ok(out) => {
|
||||
let report = integrity::check(&out);
|
||||
@@ -339,9 +374,11 @@ fn run_exe_attempt(
|
||||
profile.selected = Some(LayoutKind::ExeStyle);
|
||||
profile.recovery = RecoveryStatus::Succeeded;
|
||||
profile.record_static_validation(&report);
|
||||
emit_text(ResearchStage::Finalize, "candidate_outcome", "accepted");
|
||||
Ok(out)
|
||||
}
|
||||
Err(error) => {
|
||||
emit_text(ResearchStage::Finalize, "candidate_outcome", "failed");
|
||||
profile.record_attempt(
|
||||
LayoutKind::ExeStyle,
|
||||
AttemptOutcome::Failed,
|
||||
@@ -369,19 +406,25 @@ where
|
||||
D: FnOnce() -> Result<Vec<u8>, UnpackError>,
|
||||
E: FnOnce() -> Result<Vec<u8>, UnpackError>,
|
||||
{
|
||||
emit_text(ResearchStage::Header, "route", "dll");
|
||||
match accept_dll_layout(dll_layout()) {
|
||||
Ok((output, report)) => {
|
||||
emit_text(ResearchStage::Finalize, "candidate_outcome", "accepted");
|
||||
record_accepted(profile, LayoutKind::Dll, report);
|
||||
Ok(output)
|
||||
}
|
||||
Err(dll) => {
|
||||
emit_text(ResearchStage::Finalize, "candidate_outcome", "rejected");
|
||||
record_rejected(profile, LayoutKind::Dll, &dll);
|
||||
emit_text(ResearchStage::Header, "route", "exe_style");
|
||||
match accept_dll_layout(exe_layout()) {
|
||||
Ok((output, report)) => {
|
||||
emit_text(ResearchStage::Finalize, "candidate_outcome", "accepted");
|
||||
record_accepted(profile, LayoutKind::ExeStyle, report);
|
||||
Ok(output)
|
||||
}
|
||||
Err(exe) => {
|
||||
emit_text(ResearchStage::Finalize, "candidate_outcome", "rejected");
|
||||
record_rejected(profile, LayoutKind::ExeStyle, &exe);
|
||||
profile.recovery = RecoveryStatus::Failed;
|
||||
let error = UnpackError::PipelineFallbackFailed {
|
||||
@@ -1025,6 +1068,79 @@ mod dll_layout_selection {
|
||||
data
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn research_trace_records_route_and_outcome_for_profiled_routing() {
|
||||
let dll_image = valid_native_dll();
|
||||
let exe_image = valid_native_dll();
|
||||
let (trace, result) = with_research_trace(|| {
|
||||
let mut profile = ProtectionProfile::new(ObservedTarget::windows(
|
||||
Some(TargetFormat::Pe32Plus),
|
||||
Some(Kind::NativeDll),
|
||||
));
|
||||
profile.recognition = RecognitionStatus::Recognized;
|
||||
profile.candidates = planned_routes(Kind::NativeDll);
|
||||
let result = select_dll_layout_profiled(
|
||||
&mut profile,
|
||||
|| Ok(dll_image.clone()),
|
||||
|| Ok(exe_image.clone()),
|
||||
);
|
||||
(profile, result)
|
||||
});
|
||||
let (profile, result) = result;
|
||||
assert!(result.is_ok());
|
||||
assert_eq!(profile.selected, Some(LayoutKind::Dll));
|
||||
let routes: Vec<&str> = trace
|
||||
.events
|
||||
.iter()
|
||||
.filter(|event| event.name == "route")
|
||||
.map(|event| match &event.value {
|
||||
TraceValue::Text(text) => text.as_str(),
|
||||
other => panic!("route must be text, got {other:?}"),
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(routes, ["dll"]);
|
||||
let outcomes: Vec<&str> = trace
|
||||
.events
|
||||
.iter()
|
||||
.filter(|event| event.name == "candidate_outcome")
|
||||
.map(|event| match &event.value {
|
||||
TraceValue::Text(text) => text.as_str(),
|
||||
other => panic!("outcome must be text, got {other:?}"),
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(outcomes, ["accepted"]);
|
||||
assert!(
|
||||
trace
|
||||
.events
|
||||
.iter()
|
||||
.all(|event| event.stage == ResearchStage::Header
|
||||
|| event.stage == ResearchStage::Finalize)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn research_trace_is_absent_after_a_panicking_scope() {
|
||||
let (trace, ()) = with_research_trace(|| {
|
||||
let caught = crate::catch_unwind_quiet(|| {
|
||||
with_research_trace(|| panic!("scoped panic"));
|
||||
});
|
||||
assert!(caught.is_err());
|
||||
// The inner scope's sink is gone; the outer one is active again, so
|
||||
// this event belongs to the outer trace.
|
||||
assert!(crate::windows::research::trace_enabled());
|
||||
emit_text(ResearchStage::Finalize, "outer", "still traced");
|
||||
});
|
||||
assert_eq!(
|
||||
trace
|
||||
.events
|
||||
.iter()
|
||||
.map(|event| event.name)
|
||||
.collect::<Vec<_>>(),
|
||||
["outer"]
|
||||
);
|
||||
assert!(!crate::windows::research::trace_enabled());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inspect_profile_reports_recognition_without_running_a_route() {
|
||||
let profile = inspect_profile(&detected_dll_input());
|
||||
|
||||
@@ -0,0 +1,527 @@
|
||||
//! Scoped, bounded recovery trace for research inspection.
|
||||
//!
|
||||
//! A full static recovery is the only place that can report the values a
|
||||
//! protection header merely declares: the chosen layout, stage seeds, key
|
||||
//! offsets, decryptor tables, and per-section outcomes. [`with_research_trace`]
|
||||
//! installs a thread-local sink around an existing recovery call, so the
|
||||
//! pipelines can publish those values without changing their control flow or
|
||||
//! their output bytes.
|
||||
//!
|
||||
//! The sink is deliberately small:
|
||||
//!
|
||||
//! * It belongs to the calling thread for the duration of the closure. Events
|
||||
//! emitted by worker threads are not collected (workers do not mutate shared
|
||||
//! pipeline state, and collecting there would need synchronization).
|
||||
//! * It is bounded. Once the event limit is reached, further events are
|
||||
//! dropped and counted; the trace records that it is truncated rather than
|
||||
//! pretending the tail is absent.
|
||||
//! * Emitting is a no-op when no sink is installed, so pipeline code can call
|
||||
//! the helpers unconditionally.
|
||||
//!
|
||||
//! Events carry an [`AddressSpace`] whenever an offset is reported. A working
|
||||
//! image RVA, a decrypted payload offset, and a protected-file offset are not
|
||||
//! interchangeable; naming the space keeps research output from silently
|
||||
//! mixing them.
|
||||
|
||||
use std::cell::RefCell;
|
||||
|
||||
use serde::Serialize;
|
||||
|
||||
/// Event budget for one trace. A normal recovery emits a few dozen events;
|
||||
/// the limit only exists so a corrupt or adversarial input cannot make the
|
||||
/// research path allocate without bound.
|
||||
pub(crate) const DEFAULT_MAX_EVENTS: usize = 4096;
|
||||
|
||||
/// Which address space an offset belongs to. Every offset is an absolute
|
||||
/// position in its own space; none is an offset relative to another.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum AddressSpace {
|
||||
/// Absolute byte position in the protected input file the caller supplied.
|
||||
/// Use this for every input-file position, including the protection
|
||||
/// header/key-table cells at `0x1000..0x1020`.
|
||||
FileOffset,
|
||||
/// Absolute byte position inside the protected header/key-table region,
|
||||
/// measured from the start of the input file (not the region). Retained
|
||||
/// for producers that want to distinguish that region; it is not limited
|
||||
/// to the first 4 KiB and it is never a region-relative offset.
|
||||
ProtectedHeaderOffset,
|
||||
/// Offset relative to the decrypted payload base (`info[3]`). Converting
|
||||
/// to a working-image RVA is `info[3] + DecodedPayloadOffset`; the value
|
||||
/// alone is not an RVA.
|
||||
DecodedPayloadOffset,
|
||||
/// RVA of the working image (same numbering as a mapped PE).
|
||||
WorkingImageRva,
|
||||
}
|
||||
|
||||
/// Recovery stage that produced an event.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum ResearchStage {
|
||||
Header,
|
||||
Payload,
|
||||
Pe32Shell,
|
||||
Pe32Stages,
|
||||
ExeStage1,
|
||||
ExeStage2,
|
||||
ExeStage3,
|
||||
ExeStage4,
|
||||
ExeStage5,
|
||||
Sections,
|
||||
Imports,
|
||||
Tls,
|
||||
Output,
|
||||
DllStages,
|
||||
Finalize,
|
||||
}
|
||||
|
||||
/// Event payload. Scalars cover every observed field; `Range` is the common
|
||||
/// `(start, length)` descriptor shape; `U32s` is a short word list (key
|
||||
/// offsets, descriptor tuples) whose length is bounded by the caller.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum TraceValue {
|
||||
U32(u32),
|
||||
U64(u64),
|
||||
Bool(bool),
|
||||
Text(String),
|
||||
U32s(Vec<u32>),
|
||||
Range { start: u64, length: u64 },
|
||||
}
|
||||
|
||||
/// Address attached to an event, with the space that makes it unambiguous.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
|
||||
pub struct TraceAddress {
|
||||
pub space: AddressSpace,
|
||||
pub offset: u64,
|
||||
}
|
||||
|
||||
/// One traced recovery fact.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
|
||||
pub struct ResearchEvent {
|
||||
pub stage: ResearchStage,
|
||||
pub name: &'static str,
|
||||
pub value: TraceValue,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub address: Option<TraceAddress>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub note: Option<&'static str>,
|
||||
}
|
||||
|
||||
/// Bounded collection of events from one scoped recovery.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
|
||||
pub struct ResearchTrace {
|
||||
pub events: Vec<ResearchEvent>,
|
||||
/// True when at least one event did not fit the limit.
|
||||
pub truncated: bool,
|
||||
/// Number of events dropped after the limit was reached.
|
||||
pub dropped: u64,
|
||||
pub limit: usize,
|
||||
}
|
||||
|
||||
impl ResearchTrace {
|
||||
fn empty() -> Self {
|
||||
Self {
|
||||
events: Vec::new(),
|
||||
truncated: false,
|
||||
dropped: 0,
|
||||
limit: DEFAULT_MAX_EVENTS,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct TraceSink {
|
||||
events: Vec<ResearchEvent>,
|
||||
dropped: u64,
|
||||
limit: usize,
|
||||
}
|
||||
|
||||
impl TraceSink {
|
||||
fn new(limit: usize) -> Self {
|
||||
Self {
|
||||
events: Vec::new(),
|
||||
dropped: 0,
|
||||
limit,
|
||||
}
|
||||
}
|
||||
|
||||
fn push(&mut self, event: ResearchEvent) {
|
||||
if self.events.len() < self.limit {
|
||||
self.events.push(event);
|
||||
} else {
|
||||
self.dropped = self.dropped.saturating_add(1);
|
||||
}
|
||||
}
|
||||
|
||||
fn finish(self) -> ResearchTrace {
|
||||
ResearchTrace {
|
||||
events: self.events,
|
||||
truncated: self.dropped > 0,
|
||||
dropped: self.dropped,
|
||||
limit: self.limit,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
static SINK: RefCell<Option<TraceSink>> = const { RefCell::new(None) };
|
||||
}
|
||||
|
||||
/// Install a trace sink for the duration of `f`, returning the trace and the
|
||||
/// closure result. Nested calls are scoped: the inner call collects only its
|
||||
/// own events, and the outer sink resumes untouched afterward.
|
||||
///
|
||||
/// If `f` panics, the outer sink state is still restored by the guard; events
|
||||
/// collected by the panicking scope are discarded.
|
||||
pub fn with_research_trace<R>(f: impl FnOnce() -> R) -> (ResearchTrace, R) {
|
||||
with_research_trace_limited(DEFAULT_MAX_EVENTS, f)
|
||||
}
|
||||
|
||||
/// [`with_research_trace`] with an explicit event budget. A zero budget
|
||||
/// records no events but still reports `limit`/`dropped`, so callers can tell
|
||||
/// "not collected" from "nothing discovered".
|
||||
pub fn with_research_trace_limited<R>(
|
||||
max_events: usize,
|
||||
f: impl FnOnce() -> R,
|
||||
) -> (ResearchTrace, R) {
|
||||
let guard = SinkGuard::install(max_events);
|
||||
let result = f();
|
||||
let trace = guard.finish();
|
||||
(trace, result)
|
||||
}
|
||||
|
||||
struct SinkGuard {
|
||||
previous: Option<TraceSink>,
|
||||
}
|
||||
|
||||
impl SinkGuard {
|
||||
fn install(max_events: usize) -> Self {
|
||||
let previous = SINK.with(|cell| cell.borrow_mut().take());
|
||||
SINK.with(|cell| *cell.borrow_mut() = Some(TraceSink::new(max_events)));
|
||||
Self { previous }
|
||||
}
|
||||
|
||||
/// Take the collected events. Restoration of the previous sink is left to
|
||||
/// `Drop`, which runs exactly once whether `f` returned or unwound.
|
||||
fn finish(self) -> ResearchTrace {
|
||||
let sink = SINK.with(|cell| cell.borrow_mut().take());
|
||||
sink.map_or_else(ResearchTrace::empty, TraceSink::finish)
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for SinkGuard {
|
||||
fn drop(&mut self) {
|
||||
// Always replace, including with `None`: an outermost scope that
|
||||
// unwinds must not leave its sink installed for the rest of the
|
||||
// thread's life. On the normal path `finish` has already taken the
|
||||
// current sink, so this only restores the enclosing one.
|
||||
SINK.with(|cell| *cell.borrow_mut() = self.previous.take());
|
||||
}
|
||||
}
|
||||
|
||||
/// True when a trace is active on this thread. Use it to skip building values
|
||||
/// that only the trace consumes (snapshots, `Vec`s of derived fields).
|
||||
pub(crate) fn trace_enabled() -> bool {
|
||||
SINK.with(|cell| cell.borrow().is_some())
|
||||
}
|
||||
|
||||
fn push(event: ResearchEvent) {
|
||||
SINK.with(|cell| {
|
||||
if let Some(sink) = cell.borrow_mut().as_mut() {
|
||||
sink.push(event);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// Record an event without an address.
|
||||
pub(crate) fn emit(stage: ResearchStage, name: &'static str, value: TraceValue) {
|
||||
push(ResearchEvent {
|
||||
stage,
|
||||
name,
|
||||
value,
|
||||
address: None,
|
||||
note: None,
|
||||
});
|
||||
}
|
||||
|
||||
/// Record an event whose value is an offset in `space`.
|
||||
pub(crate) fn emit_at(
|
||||
stage: ResearchStage,
|
||||
name: &'static str,
|
||||
value: TraceValue,
|
||||
space: AddressSpace,
|
||||
offset: u64,
|
||||
) {
|
||||
push(ResearchEvent {
|
||||
stage,
|
||||
name,
|
||||
value,
|
||||
address: Some(TraceAddress { space, offset }),
|
||||
note: None,
|
||||
});
|
||||
}
|
||||
|
||||
/// Record an event with a short fixed explanation.
|
||||
pub(crate) fn emit_note(
|
||||
stage: ResearchStage,
|
||||
name: &'static str,
|
||||
value: TraceValue,
|
||||
note: &'static str,
|
||||
) {
|
||||
push(ResearchEvent {
|
||||
stage,
|
||||
name,
|
||||
value,
|
||||
address: None,
|
||||
note: Some(note),
|
||||
});
|
||||
}
|
||||
|
||||
/// Record a short text fact (candidate verdict, layout choice). Not for key
|
||||
/// material or byte dumps.
|
||||
pub(crate) fn emit_text(stage: ResearchStage, name: &'static str, text: impl Into<String>) {
|
||||
emit(stage, name, TraceValue::Text(text.into()));
|
||||
}
|
||||
|
||||
pub(crate) fn emit_u32(stage: ResearchStage, name: &'static str, value: u32) {
|
||||
emit(stage, name, TraceValue::U32(value));
|
||||
}
|
||||
|
||||
pub(crate) fn emit_u32_at(
|
||||
stage: ResearchStage,
|
||||
name: &'static str,
|
||||
value: u32,
|
||||
space: AddressSpace,
|
||||
offset: u64,
|
||||
) {
|
||||
emit_at(stage, name, TraceValue::U32(value), space, offset);
|
||||
}
|
||||
|
||||
pub(crate) fn emit_u64(stage: ResearchStage, name: &'static str, value: u64) {
|
||||
emit(stage, name, TraceValue::U64(value));
|
||||
}
|
||||
|
||||
pub(crate) fn emit_bool(stage: ResearchStage, name: &'static str, value: bool) {
|
||||
emit(stage, name, TraceValue::Bool(value));
|
||||
}
|
||||
|
||||
pub(crate) fn emit_u32s(stage: ResearchStage, name: &'static str, values: Vec<u32>) {
|
||||
emit(stage, name, TraceValue::U32s(values));
|
||||
}
|
||||
|
||||
/// Record a `[start, start + length)` range in `space`.
|
||||
pub(crate) fn emit_range(
|
||||
stage: ResearchStage,
|
||||
name: &'static str,
|
||||
space: AddressSpace,
|
||||
start: u64,
|
||||
length: u64,
|
||||
) {
|
||||
push(ResearchEvent {
|
||||
stage,
|
||||
name,
|
||||
value: TraceValue::Range { start, length },
|
||||
address: Some(TraceAddress {
|
||||
space,
|
||||
offset: start,
|
||||
}),
|
||||
note: None,
|
||||
});
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// An outermost scope that unwinds must not leave its sink installed.
|
||||
#[test]
|
||||
fn outermost_unwind_clears_the_sink() {
|
||||
let caught = crate::catch_unwind_quiet(|| {
|
||||
let _ = with_research_trace(|| {
|
||||
emit_u32(ResearchStage::Header, "before_panic", 1);
|
||||
panic!("escaped scope");
|
||||
});
|
||||
});
|
||||
assert!(caught.is_err());
|
||||
assert!(!trace_enabled(), "an unwound scope must not keep a sink");
|
||||
|
||||
// A later ordinary trace still works and collects only its own event.
|
||||
let (trace, ()) = with_research_trace(|| {
|
||||
emit_u32(ResearchStage::Header, "after", 2);
|
||||
});
|
||||
assert_eq!(
|
||||
trace
|
||||
.events
|
||||
.iter()
|
||||
.map(|event| event.name)
|
||||
.collect::<Vec<_>>(),
|
||||
["after"]
|
||||
);
|
||||
assert!(!trace_enabled());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_sink_means_no_collection() {
|
||||
assert!(!trace_enabled());
|
||||
emit_u32(ResearchStage::Header, "ignored", 1);
|
||||
let (trace, value) = with_research_trace(|| 7u32);
|
||||
assert_eq!(value, 7);
|
||||
assert!(trace.events.is_empty());
|
||||
assert!(!trace.truncated);
|
||||
assert!(!trace_enabled());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn events_keep_stage_value_and_provenance() {
|
||||
let (trace, ()) = with_research_trace(|| {
|
||||
assert!(trace_enabled());
|
||||
emit_at(
|
||||
ResearchStage::Payload,
|
||||
"payload_source",
|
||||
TraceValue::U32(0x4E0),
|
||||
AddressSpace::FileOffset,
|
||||
0x14E0,
|
||||
);
|
||||
emit_range(
|
||||
ResearchStage::Sections,
|
||||
"block",
|
||||
AddressSpace::WorkingImageRva,
|
||||
0x1000,
|
||||
0x200,
|
||||
);
|
||||
emit_note(
|
||||
ResearchStage::Output,
|
||||
"layout",
|
||||
TraceValue::Text("compact".into()),
|
||||
"selected",
|
||||
);
|
||||
emit_u32s(ResearchStage::ExeStage2, "key_offsets", vec![1, 2, 3, 4]);
|
||||
emit_bool(ResearchStage::Finalize, "new_layout", true);
|
||||
emit_u64(ResearchStage::Finalize, "output_len", 0x2000);
|
||||
});
|
||||
assert_eq!(trace.events.len(), 6);
|
||||
assert_eq!(trace.events[0].stage, ResearchStage::Payload);
|
||||
assert_eq!(trace.events[0].name, "payload_source");
|
||||
assert_eq!(trace.events[0].value, TraceValue::U32(0x4E0));
|
||||
assert_eq!(
|
||||
trace.events[0].address,
|
||||
Some(TraceAddress {
|
||||
space: AddressSpace::FileOffset,
|
||||
offset: 0x14E0
|
||||
})
|
||||
);
|
||||
assert_eq!(
|
||||
trace.events[1].address,
|
||||
Some(TraceAddress {
|
||||
space: AddressSpace::WorkingImageRva,
|
||||
offset: 0x1000
|
||||
})
|
||||
);
|
||||
assert_eq!(
|
||||
trace.events[1].value,
|
||||
TraceValue::Range {
|
||||
start: 0x1000,
|
||||
length: 0x200
|
||||
}
|
||||
);
|
||||
assert_eq!(trace.events[2].note, Some("selected"));
|
||||
assert_eq!(trace.events[3].value, TraceValue::U32s(vec![1, 2, 3, 4]));
|
||||
assert_eq!(trace.events[4].value, TraceValue::Bool(true));
|
||||
assert_eq!(trace.events[5].value, TraceValue::U64(0x2000));
|
||||
assert!(!trace.truncated);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nested_traces_are_scoped_and_the_outer_sink_resumes() {
|
||||
let (outer, inner) = with_research_trace(|| {
|
||||
emit_u32(ResearchStage::Header, "outer_before", 1);
|
||||
let inner = with_research_trace(|| {
|
||||
emit_u32(ResearchStage::Header, "inner", 2);
|
||||
});
|
||||
assert!(trace_enabled(), "outer sink must be restored");
|
||||
emit_u32(ResearchStage::Header, "outer_after", 3);
|
||||
inner
|
||||
});
|
||||
assert_eq!(
|
||||
inner
|
||||
.0
|
||||
.events
|
||||
.iter()
|
||||
.map(|event| event.name)
|
||||
.collect::<Vec<_>>(),
|
||||
["inner"]
|
||||
);
|
||||
assert_eq!(
|
||||
outer
|
||||
.events
|
||||
.iter()
|
||||
.map(|event| event.name)
|
||||
.collect::<Vec<_>>(),
|
||||
["outer_before", "outer_after"]
|
||||
);
|
||||
assert!(!trace_enabled());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn full_sink_drops_and_reports_truncation() {
|
||||
let (trace, ()) = with_research_trace(|| {
|
||||
for index in 0..=DEFAULT_MAX_EVENTS {
|
||||
emit_u32(
|
||||
ResearchStage::Header,
|
||||
"event",
|
||||
u32::try_from(index).expect("fits"),
|
||||
);
|
||||
}
|
||||
});
|
||||
assert_eq!(trace.events.len(), DEFAULT_MAX_EVENTS);
|
||||
assert_eq!(trace.limit, DEFAULT_MAX_EVENTS);
|
||||
assert_eq!(trace.dropped, 1);
|
||||
assert!(trace.truncated);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn explicit_budget_limits_and_reports_drops() {
|
||||
let (trace, ()) = with_research_trace_limited(2, || {
|
||||
emit_u32(ResearchStage::Header, "a", 1);
|
||||
emit_u32(ResearchStage::Header, "b", 2);
|
||||
emit_u32(ResearchStage::Header, "c", 3);
|
||||
});
|
||||
assert_eq!(trace.limit, 2);
|
||||
assert_eq!(trace.events.len(), 2);
|
||||
assert_eq!(trace.dropped, 1);
|
||||
assert!(trace.truncated);
|
||||
|
||||
let (trace, ()) = with_research_trace_limited(0, || {
|
||||
emit_u32(ResearchStage::Header, "a", 1);
|
||||
});
|
||||
assert_eq!(trace.limit, 0);
|
||||
assert!(trace.events.is_empty());
|
||||
assert_eq!(trace.dropped, 1);
|
||||
assert!(trace.truncated);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn serialized_trace_uses_snake_case_and_omits_empty_provenance() {
|
||||
let (trace, ()) = with_research_trace(|| {
|
||||
emit_u32_at(
|
||||
ResearchStage::ExeStage5,
|
||||
"file_lfsr",
|
||||
0x1234,
|
||||
AddressSpace::WorkingImageRva,
|
||||
0x1234,
|
||||
);
|
||||
emit_u32(ResearchStage::Finalize, "output_len", 0x2000);
|
||||
});
|
||||
let value = serde_json::to_value(&trace).expect("trace serializes");
|
||||
assert_eq!(value["limit"], DEFAULT_MAX_EVENTS);
|
||||
assert_eq!(value["events"][0]["stage"], "exe_stage5");
|
||||
assert_eq!(
|
||||
value["events"][0]["value"],
|
||||
serde_json::json!({"u32": 0x1234})
|
||||
);
|
||||
assert_eq!(value["events"][0]["address"]["space"], "working_image_rva");
|
||||
assert_eq!(value["events"][0]["address"]["offset"], 0x1234);
|
||||
assert!(value["events"][1].get("address").is_none());
|
||||
assert!(value["events"][1].get("note").is_none());
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user