diff --git a/fuzz/fuzz_targets/pe_parse.rs b/fuzz/fuzz_targets/pe_parse.rs index 4a33398..60902d6 100644 --- a/fuzz/fuzz_targets/pe_parse.rs +++ b/fuzz/fuzz_targets/pe_parse.rs @@ -2,8 +2,8 @@ //! PE header/RVA parser over arbitrary bytes. //! -//! Exercises `parse`, `sections`, `data_directory`, `rva_to_offset`, and -//! `rva_range`. Every failure is an `Err`; a panic is a bug. +//! Exercises format parsing/mapping and the bounded research inspector, +//! including partially parsed inputs. A returned issue is fine; a panic is a bug. use libfuzzer_sys::fuzz_target; @@ -11,6 +11,13 @@ const MAX_INPUT: usize = 256 * 1024; fuzz_target!(|data: &[u8]| { let data = &data[..data.len().min(MAX_INPUT)]; + let limits = senbei_engine::windows::InspectionLimits { + prefix_scratch_bytes: 64 * 1024, + max_candidates: 16, + max_issues: 16, + ..Default::default() + }; + let _ = senbei_engine::windows::inspect_research_with_limits(data, &limits); let Ok(headers) = senbei_pe::parse(data) else { return; }; diff --git a/fuzz/src/smoke.rs b/fuzz/src/smoke.rs index 0fe631b..28e6794 100644 --- a/fuzz/src/smoke.rs +++ b/fuzz/src/smoke.rs @@ -122,6 +122,13 @@ fn pe_calls(data: &[u8]) { let data = &data[..data.len().min(MAX_PE)]; let _ = senbei_engine::detect(data); let _ = senbei_engine::check_integrity(data); + let limits = senbei_engine::windows::InspectionLimits { + prefix_scratch_bytes: 64 * 1024, + max_candidates: 16, + max_issues: 16, + ..Default::default() + }; + let _ = senbei_engine::windows::inspect_research_with_limits(data, &limits); if let Ok(headers) = senbei_pe::parse(data) { let _ = senbei_pe::sections(data, headers); let _ = senbei_pe::characteristics(data, headers); diff --git a/senbei-cli/src/main.rs b/senbei-cli/src/main.rs index 54b1beb..672b0b6 100644 --- a/senbei-cli/src/main.rs +++ b/senbei-cli/src/main.rs @@ -143,16 +143,13 @@ impl Options { // rejected rather than guessed at. if command == Command::Inspect { if dry_run { - return Err("'inspect' never recovers; drop --dry-run".to_owned()); + return Err("'inspect' writes nothing; drop --dry-run".to_owned()); } if out.is_some() { return Err("'inspect' writes nothing; --out is not allowed".to_owned()); } - if strict_integrity { - return Err( - "'inspect' runs no static check; --strict-integrity is not allowed".to_owned(), - ); - } + // `--strict-integrity` is meaningful: inspection runs the real + // static check and reports its verdict. } if machine { // Machine output owns stdout; interleaved progress would corrupt it. @@ -205,12 +202,14 @@ fn execute(options: &mut Options) -> u8 { } } -/// Detection completes even when an input is not a target; only an input that -/// could not be read makes inspection fail. +/// Inspection reports what the input is and what happened when it was tried; +/// only an input that could not be read makes it fail. fn execute_inspect(options: &Options, path: &Path, scan_all: bool) -> u8 { match job::inspect_path(path, scan_all, &options.limits) { Ok(report) => { - let code = report_exit_code(&report, false); + // A recovery that ran and produced a suspect image is exactly what + // `--strict-integrity` asks about, so it applies here too. + let code = report_exit_code(&report, options.strict_integrity); if options.machine { println!("{}", report.to_json()); } else if options.quiet < 2 { @@ -395,10 +394,13 @@ fn print_help() { ); println!( " inspect PATH\n\ - \x20 detect only. Reports what each input is, whether it is\n\ - \x20 recognized, and which recovery routes would be tried.\n\ - \x20 Never recovers, never writes an output, never creates a log,\n\ - \x20 and never claims a route succeeded or a check passed." + \x20 run the real static recovery for research, and report\n\ + \x20 everything observed: recognition evidence, each route\n\ + \x20 tried and why it was rejected, the route selected, the\n\ + \x20 static check's verdict, and the engines' own structural\n\ + \x20 evidence (protected-header fields, seeds, module records,\n\ + \x20 restored-image facts). Nothing is kept: no output file,\n\ + \x20 no log, no temporary tree, and the input is never run." ); println!(" unpack PATH detection and recovery; writes outputs (the default)."); println!( @@ -423,7 +425,9 @@ fn print_help() { \x20 exit non-zero when any output fails the static integrity\n\ \x20 check (a suspect) or a file errors. Off by default: a\n\ \x20 suspect is still written and the process exits 0 unless\n\ - \x20 a file errors. Quiet levels are unchanged." + \x20 a file errors. Quiet levels are unchanged.\n\ + \x20 With 'inspect', the check applies to the image actually\n\ + \x20 recovered for research; no output file is retained." ); let defaults = ResourceLimits::default(); println!( @@ -638,16 +642,22 @@ mod command_line { } #[test] - fn inspect_rejects_recovery_only_flags() { + fn inspect_rejects_writing_flags() { assert!(parse(&["inspect", "--out", "o", "app.exe"]).is_err()); assert!(parse(&["inspect", "--dry-run", "app.exe"]).is_err()); - assert!(parse(&["inspect", "--strict-integrity", "app.exe"]).is_err()); assert_eq!( parse(&["inspect", "--json", "a"]).unwrap().command, Command::Inspect ); } + /// Inspection runs the real static check, so asking it to be strict about + /// that verdict is meaningful, not contradictory. + #[test] + fn inspect_accepts_strict_integrity() { + assert!(parse(&["inspect", "--strict-integrity", "app.exe"]).is_ok()); + } + #[test] fn a_subcommand_without_a_path_is_a_usage_error() { assert!(parse(&["inspect"]).is_err()); diff --git a/senbei-cli/tests/reporting.rs b/senbei-cli/tests/reporting.rs index 11163b2..c9035f6 100644 --- a/senbei-cli/tests/reporting.rs +++ b/senbei-cli/tests/reporting.rs @@ -175,8 +175,10 @@ fn inspect_writes_no_output_no_log_and_no_temporary() { ); } +/// Inspection reports the real attempt but keeps nothing: no output file is +/// advertised, and a non-target never gets a route selected for it. #[test] -fn inspect_never_claims_recovery_or_validation() { +fn inspect_keeps_nothing_and_claims_no_route_for_a_non_target() { let td = tempfile::tempdir().unwrap(); write_plain(td.path(), "plain.exe"); let output = run(&["inspect", td.path().to_str().unwrap(), "--json"]); @@ -184,16 +186,17 @@ fn inspect_never_claims_recovery_or_validation() { for input in value["inputs"].as_array().unwrap() { assert!( input["profile"]["selected"].is_null(), - "inspect must not select a route: {input}" + "a non-target selects no route: {input}" ); - assert_eq!(input["profile"]["recovery"], "not_attempted"); - assert_eq!(input["profile"]["static_validation"], "not_run"); + assert_eq!(input["profile"]["recognition"], "not_recognized"); + assert_eq!(input["status"], "skipped"); assert!( input["outputs"].as_array().unwrap().is_empty(), "inspect must not report outputs" ); assert!(input["recovered"].is_null()); } + assert_eq!(value["summary"]["errors"], 0); } #[test] @@ -276,6 +279,32 @@ fn dry_run_json_describes_an_attempt_that_really_ran() { assert_eq!(reported["status"], "error"); } +/// Only inspection keeps the research payloads; an ordinary unpack must not +/// serialize or clone them. +#[test] +fn unpack_and_dry_run_carry_no_research_payload() { + let td = tempfile::tempdir().unwrap(); + let input = write_metadata(td.path(), 31); + let out = td.path().join("out"); + let unpack = run(&[ + input.to_str().unwrap(), + "--out", + out.to_str().unwrap(), + "--json", + ]); + let dry_run = run(&["--dry-run", input.to_str().unwrap(), "--json"]); + + for output in [unpack, dry_run] { + let value = parse_json(&output); + for reported in value["inputs"].as_array().unwrap() { + assert!(reported["research"].is_null(), "{reported}"); + assert!(reported["android_research"].is_null(), "{reported}"); + assert!(reported["metadata_research"].is_null(), "{reported}"); + assert!(reported["source"].is_null(), "{reported}"); + } + } +} + #[test] fn dry_run_refuses_an_output_directory() { let output = run(&["--dry-run", "--out", "out", "plain.exe"]); @@ -337,15 +366,27 @@ fn inspect_help_is_documented() { } #[test] -fn inspect_rejects_recovery_only_flags() { - for flag in ["--out", "--strict-integrity"] { - let output = run(&["inspect", "--json", flag, "x"]); - assert_eq!(output.status.code(), Some(2), "{flag}"); - } +fn inspect_rejects_writing_flags() { + let output = run(&["inspect", "--json", "--out", "x"]); + assert_eq!( + output.status.code(), + Some(2), + "--out writes, inspect keeps nothing" + ); let output = run(&["inspect", "--dry-run", "x"]); assert_eq!(output.status.code(), Some(2)); } +/// Inspection runs the real static check, so `--strict-integrity` is a real +/// request about a real verdict rather than a contradiction. +#[test] +fn inspect_accepts_strict_integrity() { + let td = tempfile::tempdir().unwrap(); + let input = write_plain(td.path(), "plain.exe"); + let output = run(&["inspect", input.to_str().unwrap(), "--strict-integrity"]); + assert_ne!(output.status.code(), Some(2), "not a usage error"); +} + // --------------------------------------------------------------------------- // Containers and companions // --------------------------------------------------------------------------- @@ -459,13 +500,16 @@ fn inspect_reports_a_container_inventory_separately_from_its_entries() { assert_eq!(manifests[0]["package"], "com.example.app"); assert_eq!(manifests[0]["version"], "42"); assert_eq!(manifests[0]["named"], true); - // Only content-probe candidates are listed, and nothing was probed. + // Inventory is membership: the entries a restore would probe, listed apart + // from the entries that were actually probed (which have their own result). let candidates = input["container"]["candidate_entries"].as_array().unwrap(); assert_eq!(candidates.len(), 1); assert!(candidates[0].as_str().unwrap().ends_with("libil2cpp.so")); - assert!(input["entries"].as_array().unwrap().is_empty()); + let entries = input["entries"].as_array().unwrap(); + assert_eq!(entries.len(), 1, "the candidate was probed: {input}"); + assert_eq!(entries[0]["status"], "not_target"); assert!(input["outputs"].as_array().unwrap().is_empty()); - // Inventory is membership, not inspected protected content. + // The container itself has no single profile; its entries do the talking. assert!(input["profile"].is_null()); assert_eq!(input["status"], "skipped"); } @@ -514,6 +558,56 @@ fn inspect_reports_a_non_matching_companion_without_an_error() { assert!(input["outputs"].as_array().unwrap().is_empty()); } +/// Inspection runs the real static recovery, so the report carries the attempt +/// and the structural evidence behind it — while still keeping nothing. +#[test] +fn inspect_reports_the_attempt_and_its_structural_evidence() { + let td = tempfile::tempdir().unwrap(); + let input = td.path().join("app.exe"); + std::fs::write(&input, fake_protected_pe()).unwrap(); + let before = tree(td.path()); + + let output = run(&["inspect", input.to_str().unwrap(), "--json"]); + assert_eq!( + output.status.code(), + Some(0), + "a failing trial is a finding" + ); + let value = parse_json(&output); + let reported = &value["inputs"][0]; + + // Recognition is evidence about the input. + assert_eq!(reported["status"], "recognized"); + assert_eq!(reported["profile"]["recognition"], "recognized"); + // The input identity is the physical file, and it was inspected as-is. + assert!(reported["source"]["sha256"].is_string()); + assert_eq!(reported["source"]["size"], 0x2000); + assert_eq!(reported["research"]["input_view"], "original"); + // The header structure the inspector decoded is there, not just a verdict: + // the recognized magic and the decoded header words it came from. + let protection = &reported["research"]["input"]["protection"]; + assert_eq!(protection["magic_recognized"], true); + let words = protection["header_words"].as_array().unwrap(); + assert!(!words.is_empty(), "decoded header words are reported"); + assert!( + words.iter().any(|word| word["semantic"] == "magic"), + "each word names the field it decodes to: {protection}" + ); + // The recovery really ran: a candidate was attempted and no route survived + // this synthetic image, so nothing is selected. + assert_ne!(reported["profile"]["recovery"], "not_attempted"); + assert!(reported["profile"]["selected"].is_null()); + // Nothing was kept. + assert!(reported["outputs"].as_array().unwrap().is_empty()); + assert!(reported["recovered"].is_null()); + assert_eq!( + tree(td.path()), + before, + "inspection must not create, change, or remove anything" + ); + assert_eq!(value["summary"]["errors"], 0); +} + #[test] fn unpack_reports_the_companion_state_it_actually_used() { let td = tempfile::tempdir().unwrap(); @@ -551,3 +645,56 @@ fn a_relative_path_is_reported_verbatim() { let value = parse_json(&output); assert_eq!(value["inputs"][0]["path"], "plain.exe"); } + +/// A resource ceiling on a real target is an incomplete analysis: the document +/// says so and the process exits 1. It is never "recognized, therefore fine". +#[test] +fn inspect_of_an_over_limit_target_is_incomplete_and_exits_one() { + let td = tempfile::tempdir().unwrap(); + let apk = td.path().join("base.apk"); + // A protected-library candidate far larger than the 1 MiB entry ceiling. + let large = vec![0x7Fu8; 2 * 1024 * 1024]; + write_zip( + &apk, + &[ + ("AndroidManifest.xml", MANIFEST.as_bytes()), + ("lib/arm64-v8a/libil2cpp.so", &large), + ], + ); + + let output = run(&[ + "inspect", + apk.to_str().unwrap(), + "--json", + "--max-entry-mib", + "1", + ]); + assert_eq!( + output.status.code(), + Some(1), + "a truncated analysis is a failure: {output:?}" + ); + let value = parse_json(&output); + assert_eq!(value["summary"]["errors"], 1); + let input = &value["inputs"][0]; + assert_eq!(input["status"], "error"); + assert_eq!(input["analysis_incomplete"], true); + assert!( + !input["errors"].as_array().unwrap().is_empty(), + "the reason is on the report: {input}" + ); + assert!(input["outputs"].as_array().unwrap().is_empty()); +} + +/// An unsupported layout is a research finding, not an incomplete analysis. +#[test] +fn inspect_of_an_unsupported_target_stays_a_finding() { + let td = tempfile::tempdir().unwrap(); + let input = write_plain(td.path(), "plain.exe"); + let output = run(&["inspect", input.to_str().unwrap(), "--json"]); + assert_eq!(output.status.code(), Some(0), "{output:?}"); + let value = parse_json(&output); + assert_eq!(value["summary"]["errors"], 0); + let reported = &value["inputs"][0]; + assert_eq!(reported["analysis_incomplete"], false, "{reported}"); +} diff --git a/senbei-crypto/src/windows/primitives.rs b/senbei-crypto/src/windows/primitives.rs index 7cd2014..ac89bbc 100644 --- a/senbei-crypto/src/windows/primitives.rs +++ b/senbei-crypto/src/windows/primitives.rs @@ -899,6 +899,39 @@ pub fn decrypt_data1(file_data: &[u8], info: &mut [u32; 8]) { } } +/// Prefix decoder shared by the payload loader and research inspection. +/// +/// Decodes `size` bytes from `input` at `source` into `dst` at `dst_offset` +/// with the file-key recurrence used by the protected payload's first zone. +/// `dst` is not resized and must already cover +/// `dst_offset..dst_offset + size`; the caller owns every bound and every +/// allocation decision. Only complete words are decoded; an unaligned tail +/// is left untouched, matching the payload loader's original loop. +/// +/// Writing into a caller-supplied slice (rather than allocating a whole +/// `SizeOfImage` image) is what lets inspection decode a bounded prefix with +/// exactly the same arithmetic the recovery pipeline uses. +pub fn decode_payload_prefix( + input: &[u8], + source: u32, + dst: &mut [u8], + dst_offset: u32, + key0: u32, + size: u32, +) { + // Whole words only, matching the original `decrypt_size >> 2` loop: an + // unaligned size decodes its floor of words and leaves the tail alone. + // No debug assertion — a malformed header must not panic in any build. + let mut key = key0.wrapping_add(!size); + let words = size >> 2; + for i in 0..words { + let off = i.wrapping_mul(4); + let cell = get_u32(input, source.wrapping_add(off)); + write_u32(dst, dst_offset.wrapping_add(off), key ^ cell); + key = i.wrapping_mul(i) ^ (key.wrapping_add(cell).wrapping_add(i)); + } +} + /// decrypt_data6: LFSR XOR decryption of a bytecode block at `pos` in `d`. /// The block length is read from `d[pos + 95]`. pub fn decrypt_data6(d: &mut [u8], pos: u32) { @@ -1131,3 +1164,70 @@ mod tests { )); } } + +#[cfg(test)] +mod prefix_decoder_tests { + use super::*; + + /// The shared decoder must reproduce the original inline recurrence byte + /// for byte. This is the regression guard for factoring `decrypt_data2`. + #[test] + fn shared_prefix_decoder_matches_inline_recurrence() { + for (key0, size, dst_offset) in [ + (0u32, 64u32, 0u32), + (0x24F9_9AD4, 0x100, 0x1000), + (u32::MAX, 0x3FFC, 0xBF8000), + ] { + let words = (size / 4) as usize; + let input: Vec = (0..words * 4).map(|i| (i * 37 + 11) as u8).collect(); + let total = dst_offset as u64 + size as u64; + assert!(total <= 0x1000_0000); + let mut got = vec![0u8; total as usize]; + + let mut k = key0.wrapping_add(!size); + for i in 0..size / 4 { + let off = i.wrapping_mul(4); + let cell = get_u32(&input, off); + write_u32(&mut got, dst_offset.wrapping_add(off), k ^ cell); + k = i.wrapping_mul(i) ^ (k.wrapping_add(cell).wrapping_add(i)); + } + + let mut want = vec![0u8; total as usize]; + decode_payload_prefix(&input, 0, &mut want, dst_offset, key0, size); + assert_eq!( + got, want, + "key0={key0:#X} size={size:#X} dst={dst_offset:#X}" + ); + } + } + + #[test] + fn shared_prefix_decoder_can_write_a_bounded_prefix() { + let input: Vec = (0..0x40).map(|i| i as u8).collect(); + let mut dst = vec![0u8; 0x20]; + decode_payload_prefix(&input, 0, &mut dst, 0, 0x1234, 0x20); + assert!(dst.iter().any(|&b| b != 0)); + } + + /// An unaligned size must decode the same floor of words as the original + /// `decrypt_size >> 2` loop and leave the remainder untouched — in every + /// build, with no debug assertion. + #[test] + fn shared_prefix_decoder_floors_an_unaligned_size() { + for size in [0u32, 1, 2, 3, 5, 7, 0x11] { + let input: Vec = (0..0x40).map(|i| (i * 13 + 5) as u8).collect(); + let mut dst = vec![0xAAu8; 0x40]; + decode_payload_prefix(&input, 0, &mut dst, 0, 0xFEED_FACE, size); + + let mut want = vec![0xAAu8; 0x40]; + let mut key = 0xFEED_FACEu32.wrapping_add(!size); + for i in 0..size / 4 { + let off = i.wrapping_mul(4); + let cell = get_u32(&input, off); + write_u32(&mut want, off, key ^ cell); + key = i.wrapping_mul(i) ^ (key.wrapping_add(cell).wrapping_add(i)); + } + assert_eq!(dst, want, "size={size}"); + } + } +} diff --git a/senbei-engine/src/lib.rs b/senbei-engine/src/lib.rs index 5001400..0e1a167 100644 --- a/senbei-engine/src/lib.rs +++ b/senbei-engine/src/lib.rs @@ -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, }; diff --git a/senbei-engine/src/windows/dll/pipeline.rs b/senbei-engine/src/windows/dll/pipeline.rs index b14c4b0..3af217a 100644 --- a/senbei-engine/src/windows/dll/pipeline.rs +++ b/senbei-engine/src/windows/dll/pipeline.rs @@ -13,6 +13,7 @@ //! CalculateChecksumWithSizeXor -> primitives::calculate_checksum //! CalculateCrc32 -> crc32::compute (via above) +use super::super::research::{self, AddressSpace, ResearchStage, TraceValue}; use super::super::{ BufferOperation, BytecodeStage, DecompressionStage, DescriptorTable, SectionPipeline, UnpackError, @@ -20,6 +21,29 @@ use super::super::{ use senbei_crypto::bytecode::{Op, OpsLut, generate}; use senbei_crypto::primitives::{self, *}; +/// Per-code-block index for trace events. The four blocks share one research +/// stage, so an explicit index keeps their events orderable. +fn code_block_index(stage: DecompressionStage) -> u32 { + match stage { + DecompressionStage::DllCodeBlock1 => 1, + DecompressionStage::DllCodeBlock2 => 2, + DecompressionStage::DllCodeBlock3 => 3, + DecompressionStage::DllCodeBlock4 => 4, + _ => 0, + } +} + +/// Address/offset as an unsigned trace value. Every field fed here is a +/// computed working-image or file offset; the packer's values are 32-bit and +/// negative encodings are still reported as their 32-bit bit pattern. +fn trace_offset(value: i32) -> u64 { + u64::from(value as u32) +} + +/// Section-block samples are bounded: a large image can hold thousands of +/// blocks, and the sink limit must not be what stops the trace. +const TRACE_BLOCK_SAMPLE: usize = 16; + /// Read a signed 32-bit little-endian value. fn get_i32(d: &[u8], offset: i32) -> i32 { get_u32(d, offset as u32) as i32 @@ -78,6 +102,38 @@ fn decrypt_data4( let compressed_addr = get_i32(d, offset + 8); let decompressed_size = get_i32(d, offset + 12); + if research::trace_enabled() { + // One descriptor event per block; `block` makes the shared stage + // orderable without a stage variant per block. + research::emit_at( + ResearchStage::DllStages, + "code_block_descriptor", + TraceValue::U32s(vec![ + code_block_index(stage), + addr as u32, + size as u32, + compressed_addr as u32, + decompressed_size as u32, + ]), + AddressSpace::WorkingImageRva, + trace_offset(offset), + ); + research::emit_u32_at( + ResearchStage::DllStages, + "aes_key_schedule", + decomp_params[3] as u32, + AddressSpace::WorkingImageRva, + trace_offset(decomp_params[3]), + ); + research::emit_u32_at( + ResearchStage::DllStages, + "huffman_table", + decomp_params[1] as u32, + AddressSpace::WorkingImageRva, + trace_offset(decomp_params[1]), + ); + } + aes_decrypt(d, addr as u32, size as u32, decomp_params[3] as u32); // DecryptData1(offset, key, 19) == primitives::decrypt_data3 with shift 19 decrypt_data3(d, offset as u32, key as u32, 19); @@ -85,8 +141,20 @@ fn decrypt_data4( if let Some(ops) = transform && size > 0 { + if research::trace_enabled() { + research::emit_u32(ResearchStage::DllStages, "bytecode_ops", ops.len() as u32); + } OpsLut::new(ops).map_region(d, addr as usize, size as usize); } + if size > 0 { + research::emit_range( + ResearchStage::DllStages, + "block_decrypted", + AddressSpace::WorkingImageRva, + trace_offset(addr), + size as u64, + ); + } if size != decompressed_size && let Err(reason) = primitives::decompress_detailed( @@ -98,8 +166,23 @@ fn decrypt_data4( decompressed_size as u32, ) { + research::emit_note( + ResearchStage::DllStages, + "block_decompression", + TraceValue::Bool(false), + "block_decompression_failed", + ); return Err(UnpackError::StageDecompressionFailed { stage, reason }); } + if size != decompressed_size { + research::emit_range( + ResearchStage::DllStages, + "block_decompression", + AddressSpace::WorkingImageRva, + trace_offset(compressed_addr), + decompressed_size.max(0) as u64, + ); + } Ok(()) } @@ -163,6 +246,9 @@ fn section_header_blank(file_data: &[u8], off: i32) -> bool { /// `ProcessImportTable`. fn process_import_table(d: &mut [u8], mut import_table_offset: i32) { + let table_start = import_table_offset; + let mut descriptors: u32 = 0; + let mut thunks: u64 = 0; while get_i32(d, import_table_offset + 12) != 0 { let name_offset = get_i32(d, import_table_offset + 12); decrypt_data7(d, name_offset as u32, name_offset as u8); @@ -191,10 +277,22 @@ fn process_import_table(d: &mut [u8], mut import_table_offset: i32) { d[entry as usize] = 0; d[entry.wrapping_add(1) as usize] = 0; } + thunks += 1; thunk_addr += 8; } + descriptors += 1; import_table_offset += 20; } + // `table_start` is a working-image RVA; the pipeline reached this walk + // only after the import descriptor was validated by the caller. + research::emit_u32_at( + ResearchStage::Imports, + "import_descriptors", + descriptors, + AddressSpace::WorkingImageRva, + trace_offset(table_start), + ); + research::emit_u64(ResearchStage::Imports, "import_thunks", thunks); } /// `DecryptAndDecompressData`. @@ -215,11 +313,19 @@ fn decrypt_and_decompress_data( src_offset: i32, expected_crc: i32, } + let block_table_offset = section_data_offset; let mut blocks: Vec = Vec::new(); loop { // Guard: need 16 bytes at section_data_offset in `d` let off = section_data_offset as usize; if off.saturating_add(16) > d.len() { + research::emit_u32_at( + ResearchStage::Sections, + "block_table_out_of_bounds", + off as u32, + AddressSpace::WorkingImageRva, + trace_offset(section_data_offset), + ); return Err(UnpackError::DescriptorOutOfBounds { table: DescriptorTable::DllSectionBlocks, offset: off, @@ -236,6 +342,8 @@ fn decrypt_and_decompress_data( if size == 0 { break; } + // The descriptor table itself is working-image data; its records are + // emitted (bounded) below after the loop has the totals. blocks.push(Blk { dest_offset, size, @@ -243,6 +351,53 @@ fn decrypt_and_decompress_data( expected_crc, }); } + if research::trace_enabled() { + let mut raw_total: u64 = 0; + let mut out_total: u64 = 0; + let mut compressed = 0u32; + for (index, block) in blocks.iter().enumerate() { + raw_total += block.size.max(0) as u64; + out_total += block.expected_crc.max(0) as u64; + if block.size != block.expected_crc { + compressed += 1; + } + if index < TRACE_BLOCK_SAMPLE { + research::emit_u32( + ResearchStage::Sections, + "block_descriptor", + block.dest_offset as u32, + ); + research::emit_u32( + ResearchStage::Sections, + "block_src", + block.src_offset as u32, + ); + research::emit_u32(ResearchStage::Sections, "block_raw_len", block.size as u32); + research::emit_u32( + ResearchStage::Sections, + "block_out_len", + block.expected_crc as u32, + ); + } + } + research::emit_u32_at( + ResearchStage::Sections, + "block_count", + blocks.len() as u32, + AddressSpace::WorkingImageRva, + trace_offset(block_table_offset), + ); + research::emit_u32(ResearchStage::Sections, "compressed_blocks", compressed); + research::emit_u64(ResearchStage::Sections, "raw_total_len", raw_total); + research::emit_u64(ResearchStage::Sections, "output_total_len", out_total); + research::emit_u32_at( + ResearchStage::Sections, + "section_image_base", + section_image_base as u32, + AddressSpace::WorkingImageRva, + trace_offset(section_image_base), + ); + } // Pass 2: each block writes only [src_offset, src_offset+max(size,crc)) and // reads only immutable input + the (snapshotted) key tables, so blocks with // disjoint write spans are independent. `parallel_for` carves the spans @@ -252,10 +407,42 @@ fn decrypt_and_decompress_data( let lut = OpsLut::new(decrypt_func); let ko0 = decomp_params[0]; let ko2 = decomp_params[2]; - let ks_snap = primitives::aes_schedule_snapshot(d, ko2 as u32) - .ok_or(UnpackError::InvalidAesKeySchedule { offset: ko2 as u32 })?; - let tab_snap = primitives::huffman_table_snapshot(d, ko0 as u32) - .ok_or(UnpackError::InvalidHuffmanTable { offset: ko0 as u32 })?; + if research::trace_enabled() { + research::emit_u32_at( + ResearchStage::Sections, + "aes_key_schedule", + ko2 as u32, + AddressSpace::WorkingImageRva, + trace_offset(ko2), + ); + research::emit_u32_at( + ResearchStage::Sections, + "huffman_table", + ko0 as u32, + AddressSpace::WorkingImageRva, + trace_offset(ko0), + ); + } + let ks_snap = primitives::aes_schedule_snapshot(d, ko2 as u32).ok_or_else(|| { + research::emit_u32_at( + ResearchStage::Sections, + "aes_schedule_invalid", + ko2 as u32, + AddressSpace::WorkingImageRva, + trace_offset(ko2), + ); + UnpackError::InvalidAesKeySchedule { offset: ko2 as u32 } + })?; + let tab_snap = primitives::huffman_table_snapshot(d, ko0 as u32).ok_or_else(|| { + research::emit_u32_at( + ResearchStage::Sections, + "huffman_table_invalid", + ko0 as u32, + AddressSpace::WorkingImageRva, + trace_offset(ko0), + ); + UnpackError::InvalidHuffmanTable { offset: ko0 as u32 } + })?; let spans: Vec<(usize, usize)> = blocks .iter() .map(|b| { @@ -291,16 +478,45 @@ fn decrypt_and_decompress_data( } Ok(()) }; - super::super::parallel::parallel_for(d, &spans, 1, do_block)?; + // Workers cannot emit into the trace (the sink is thread-local), so + // the driver records the outcome after the fan-out returns. + if let Err(error) = super::super::parallel::parallel_for(d, &spans, 1, do_block) { + match &error { + UnpackError::SectionDecompressionFailed { block, .. } => { + research::emit_u32( + ResearchStage::Sections, + "block_decompression_failed", + *block as u32, + ); + } + _ => research::emit_note( + ResearchStage::Sections, + "block_pass_failed", + TraceValue::Bool(false), + "section block pass failed", + ), + } + return Err(error); + } } // Zero-fill loop. + let zero_fill_table = section_data_offset; + let mut zero_fill_records: u32 = 0; + let mut zero_fill_bytes: u64 = 0; loop { let off = section_data_offset as usize; // The entry block loop above correctly requires 16 bytes; this loop // decrypts 16 too, so guard 16 (an 8-byte guard would let // decrypt_data6_shift6 index past the end of a truncated descriptor). if off.saturating_add(16) > d.len() { + research::emit_u32_at( + ResearchStage::Sections, + "zero_fill_out_of_bounds", + off as u32, + AddressSpace::WorkingImageRva, + trace_offset(section_data_offset), + ); return Err(UnpackError::DescriptorOutOfBounds { table: DescriptorTable::DllZeroFill, offset: off, @@ -315,6 +531,8 @@ fn decrypt_and_decompress_data( if zero_size == 0 { break; } + zero_fill_records += 1; + zero_fill_bytes += zero_size.max(0) as u64; for i in 0..zero_size { let idx = (zero_offset + i) as usize; if idx >= d.len() { @@ -328,6 +546,16 @@ fn decrypt_and_decompress_data( d[idx] = 0; } } + if research::trace_enabled() { + research::emit_u32_at( + ResearchStage::Sections, + "zero_fill_count", + zero_fill_records, + AddressSpace::WorkingImageRva, + trace_offset(zero_fill_table), + ); + research::emit_u64(ResearchStage::Sections, "zero_fill_bytes", zero_fill_bytes); + } Ok(()) } @@ -359,6 +587,45 @@ fn unpack_dll_inner(input: &[u8], verbose: bool) -> Result, UnpackError> let original_file_data = input; let keys = initialize_keys(file_data); + if research::trace_enabled() { + research::emit_u32s( + ResearchStage::Header, + "header_keys", + keys.iter().map(|key| *key as u32).collect(), + ); + // keys[1] is the magic; keys[3] is the payload base, keys[6] the anchor. + research::emit_u32_at( + ResearchStage::Header, + "magic", + keys[1] as u32, + AddressSpace::ProtectedHeaderOffset, + 4100, + ); + // `keys[3]` is the destination base inside the working image; the + // payload's source bytes begin at `keys[4] + 4096` in the file. + research::emit_u32_at( + ResearchStage::Header, + "payload_base", + keys[3] as u32, + AddressSpace::WorkingImageRva, + trace_offset(keys[3]), + ); + research::emit_u32(ResearchStage::Header, "payload_len", keys[5] as u32); + research::emit_u32_at( + ResearchStage::Header, + "payload_src", + (keys[4] as u32).wrapping_add(4096), + AddressSpace::FileOffset, + trace_offset(keys[4]).wrapping_add(4096), + ); + research::emit_u32_at( + ResearchStage::Header, + "anchor", + keys[6] as u32, + AddressSpace::WorkingImageRva, + trace_offset(keys[6]), + ); + } if verbose { println!("[1/9] Initializing keys..."); println!(" keys[0] key = 0x{:08X}", keys[0] as u32); @@ -403,6 +670,41 @@ fn unpack_dll_inner(input: &[u8], verbose: bool) -> Result, UnpackError> } let mut out = vec![0u8; size_of_image as usize]; let base_offset = keys[6] - keys[3] + 0x2000; + if research::trace_enabled() { + research::emit_u32_at( + ResearchStage::Payload, + "pe_offset", + pe_offset as u32, + AddressSpace::FileOffset, + trace_offset(pe_offset), + ); + research::emit_u32( + ResearchStage::Payload, + "size_of_image", + size_of_image as u32, + ); + research::emit_u32_at( + ResearchStage::Payload, + "base_offset", + base_offset as u32, + AddressSpace::DecodedPayloadOffset, + trace_offset(base_offset), + ); + research::emit_u32_at( + ResearchStage::Payload, + "key_table_src", + (keys[4] as u32).wrapping_add(4096), + AddressSpace::FileOffset, + trace_offset(keys[4]).wrapping_add(4096), + ); + research::emit_range( + ResearchStage::Payload, + "key_table", + AddressSpace::WorkingImageRva, + trace_offset(keys[3]), + (base_offset >> 2) as u64 * 4, + ); + } if verbose { println!("[2/9] Decrypting key table..."); println!(" size_of_image = 0x{:08X}", size_of_image as u32); @@ -428,6 +730,20 @@ fn unpack_dll_inner(input: &[u8], verbose: bool) -> Result, UnpackError> let dst = (keys[3] + base_offset) as usize; let n = (keys[5] - base_offset) as usize; primitives::try_copy_from_slice(&mut out, dst, n, file_data, src)?; + research::emit_range( + ResearchStage::Payload, + "payload_copy", + AddressSpace::FileOffset, + src as u64, + n as u64, + ); + research::emit_range( + ResearchStage::Payload, + "payload_dest", + AddressSpace::WorkingImageRva, + dst as u64, + n as u64, + ); } write_i32(&mut out, keys[3], 4096); out[..4096].copy_from_slice(&file_data[..4096]); @@ -442,6 +758,21 @@ fn unpack_dll_inner(input: &[u8], verbose: bool) -> Result, UnpackError> write_i32(&mut out, pe_offset + 156, v156); write_i32(&mut out, pe_offset + 176, 0); write_i32(&mut out, pe_offset + 180, 0); + if research::trace_enabled() { + // The four header dwords restored from the anchor area. Their source + // is a working-image read, and the destination is an RVA too. + research::emit_u32s( + ResearchStage::Payload, + "header_fixups", + vec![ + v144 as u32, + v148 as u32, + v152 as u32, + v156 as u32, + (pe_offset + 144) as u32, + ], + ); + } let mut checksum_offset1 = keys[6] + 5776; let mut xor_accumulator: u32 = 0; @@ -461,6 +792,18 @@ fn unpack_dll_inner(input: &[u8], verbose: bool) -> Result, UnpackError> ); let decrypted_addr1 = get_i32(&out, decrypt_offset1); + if research::trace_enabled() { + research::emit_u32_at( + ResearchStage::DllStages, + "descriptor_key", + xor_accumulator ^ (checksum1 as u32) ^ enc_key, + AddressSpace::WorkingImageRva, + trace_offset(decrypt_offset1), + ); + research::emit_u32(ResearchStage::DllStages, "xor_accumulator", xor_accumulator); + research::emit_u32(ResearchStage::DllStages, "checksum1", checksum1 as u32); + research::emit_u32(ResearchStage::DllStages, "descriptor_shift", 21); + } if verbose { println!("[3/9] Decrypting primary descriptor..."); println!(" xor_accumulator = 0x{:08X}", xor_accumulator); @@ -471,6 +814,13 @@ fn unpack_dll_inner(input: &[u8], verbose: bool) -> Result, UnpackError> if decrypted_addr1 < keys[3] || primary_end.is_none_or(|end| end < 0 || end as usize > out.len()) { + research::emit_u32_at( + ResearchStage::DllStages, + "primary_descriptor_invalid", + decrypted_addr1 as u32, + AddressSpace::WorkingImageRva, + trace_offset(decrypted_addr1), + ); return Err(UnpackError::InvalidDllPrimaryDescriptor { address: decrypted_addr1 as u32, minimum: keys[3] as u32, @@ -479,6 +829,20 @@ fn unpack_dll_inner(input: &[u8], verbose: bool) -> Result, UnpackError> } let import_offset = get_i32(&out, decrypted_addr1 + 3444); let decrypted_addr2_size = get_i32(&out, decrypted_addr1 + 3632); + research::emit_range( + ResearchStage::DllStages, + "primary_descriptor", + AddressSpace::WorkingImageRva, + trace_offset(decrypted_addr1), + 3856, + ); + research::emit_u32_at( + ResearchStage::DllStages, + "import_offset", + import_offset as u32, + AddressSpace::WorkingImageRva, + trace_offset(decrypted_addr1 + 3444), + ); decrypt_data3( &mut out, (decrypted_addr1 + 3632) as u32, @@ -487,24 +851,51 @@ fn unpack_dll_inner(input: &[u8], verbose: bool) -> Result, UnpackError> ); let addr2 = decrypted_addr2_size; + research::emit_u32_at( + ResearchStage::DllStages, + "secondary_descriptor", + addr2 as u32, + AddressSpace::WorkingImageRva, + trace_offset(addr2), + ); let reloc_block_offset = addr2 + 9248; let reloc_type = get_i32(&out, reloc_block_offset); if (reloc_type & 0x0F) == 1 { + research::emit_u32(ResearchStage::DllStages, "reloc_shift", 5); decrypt_data3_shift5(&mut out, addr2 + 9252); } else if reloc_type == 2 { let p = get_i32(&out, addr2 + 9252); + research::emit_u32_at( + ResearchStage::DllStages, + "reloc_block", + p as u32, + AddressSpace::WorkingImageRva, + trace_offset(addr2 + 9252), + ); process_reloc_block(&mut out, p); + } else { + research::emit_u32(ResearchStage::DllStages, "reloc_type", reloc_type as u32); } let reloc_block_offset2 = reloc_block_offset + 16; let reloc_type2 = get_i32(&out, reloc_block_offset2); if (reloc_type2 & 0x0F) == 1 { + research::emit_u32(ResearchStage::DllStages, "reloc2_shift", 5); decrypt_data3_shift5(&mut out, reloc_block_offset2 + 4); } else if reloc_type2 == 2 { let p = get_i32(&out, reloc_block_offset2 + 4); + research::emit_u32_at( + ResearchStage::DllStages, + "reloc2_block", + p as u32, + AddressSpace::WorkingImageRva, + trace_offset(reloc_block_offset2 + 4), + ); process_reloc_block(&mut out, p); + } else { + research::emit_u32(ResearchStage::DllStages, "reloc2_type", reloc_type2 as u32); } let mut decomp_params = [0i32; 4]; @@ -517,6 +908,36 @@ fn unpack_dll_inner(input: &[u8], verbose: bool) -> Result, UnpackError> decomp_params[2] = get_i32(&out, param_base + 32); decrypt_data3_shift5(&mut out, param_base + 40); decomp_params[3] = get_i32(&out, param_base + 40); + if research::trace_enabled() { + research::emit_u32_at( + ResearchStage::DllStages, + "decomp_params", + param_base as u32, + AddressSpace::WorkingImageRva, + trace_offset(param_base), + ); + research::emit_u32s( + ResearchStage::DllStages, + "decomp_param_values", + decomp_params.iter().map(|value| *value as u32).collect(), + ); + // param[0] is the Huffman table, param[2] the AES key schedule; both + // are working-image offsets read through the same buffer. + research::emit_u32_at( + ResearchStage::DllStages, + "huffman_table", + decomp_params[0] as u32, + AddressSpace::WorkingImageRva, + trace_offset(decomp_params[0]), + ); + research::emit_u32_at( + ResearchStage::DllStages, + "aes_key_schedule", + decomp_params[2] as u32, + AddressSpace::WorkingImageRva, + trace_offset(decomp_params[2]), + ); + } if verbose { println!("[4/9] Processing relocations & decomp params..."); println!(" addr2 = 0x{:08X}", addr2 as u32); @@ -544,6 +965,10 @@ fn unpack_dll_inner(input: &[u8], verbose: bool) -> Result, UnpackError> table_val = table_val.wrapping_add(k); } + if research::trace_enabled() { + research::emit_u32(ResearchStage::DllStages, "checksum2", checksum2 as u32); + research::emit_u32(ResearchStage::DllStages, "table_key", table_val as u32); + } let addr3_offset = decrypted_addr1 + 3712; decrypt_data4( &mut out, @@ -597,6 +1022,29 @@ fn unpack_dll_inner(input: &[u8], verbose: bool) -> Result, UnpackError> let lfsr = addr4 + 3200; // Decompress == primitives::decrypt_data6 (LFSR keystream, len at +95). decrypt_data6(&mut out, lfsr as u32); + research::emit_u32_at( + ResearchStage::DllStages, + "file_lfsr", + lfsr as u32, + AddressSpace::WorkingImageRva, + trace_offset(lfsr), + ); + research::emit_u32_at( + ResearchStage::DllStages, + "addr3b", + addr3b as u32, + AddressSpace::WorkingImageRva, + trace_offset(addr3b), + ); + research::emit_u32_at( + ResearchStage::DllStages, + "addr4", + addr4 as u32, + AddressSpace::WorkingImageRva, + trace_offset(addr4), + ); + research::emit_u32(ResearchStage::DllStages, "crc_val", crc_val as u32); + research::emit_u32(ResearchStage::DllStages, "checksum3", checksum3 as u32); if verbose { println!("[6/9] Decrypting code blocks 2-3 (addr3b, addr4)..."); println!(" crc_val = 0x{:08X}", crc_val as u32); @@ -616,9 +1064,38 @@ fn unpack_dll_inner(input: &[u8], verbose: bool) -> Result, UnpackError> lfsr_seed_val = lfsr_seed_val.wrapping_add(k); } - let decrypt_func = generate(&out, lfsr as u32).ok_or(UnpackError::BytecodeGenerationFailed( - BytecodeStage::DllPrimaryDecryptor, - ))?; + research::emit_u32_at( + ResearchStage::DllStages, + "lfsr_seed", + lfsr_seed_val as u32, + AddressSpace::WorkingImageRva, + trace_offset(addr4 + 3160), + ); + research::emit_u32(ResearchStage::DllStages, "checksum4", checksum4 as u32); + let decrypt_func = generate(&out, lfsr as u32).ok_or_else(|| { + research::emit_u32_at( + ResearchStage::DllStages, + "bytecode_invalid", + lfsr as u32, + AddressSpace::WorkingImageRva, + trace_offset(lfsr), + ); + UnpackError::BytecodeGenerationFailed(BytecodeStage::DllPrimaryDecryptor) + })?; + if research::trace_enabled() { + research::emit_u32_at( + ResearchStage::DllStages, + "bytecode_primary", + lfsr as u32, + AddressSpace::WorkingImageRva, + trace_offset(lfsr), + ); + research::emit_u32( + ResearchStage::DllStages, + "bytecode_ops", + decrypt_func.len() as u32, + ); + } let addr5_offset = decrypted_addr1 + 3840; let addr5 = get_i32(&out, addr5_offset); @@ -638,21 +1115,78 @@ fn unpack_dll_inner(input: &[u8], verbose: bool) -> Result, UnpackError> let metadata_offset = addr5 + 12312; let mut metadata_addr = get_i32(&out, metadata_offset); + let metadata_table = metadata_addr; while get_i32(&out, metadata_addr + 4) != 0 { decrypt_data6_shift6(&mut out, metadata_addr, 16); metadata_addr += 16; } + if research::trace_enabled() { + research::emit_u32_at( + ResearchStage::DllStages, + "metadata_descriptor", + metadata_table as u32, + AddressSpace::WorkingImageRva, + trace_offset(metadata_table), + ); + research::emit_u64( + ResearchStage::DllStages, + "metadata_descriptor_bytes", + (metadata_addr - metadata_table).max(0) as u64, + ); + } let lfsr2 = metadata_offset + 88; decrypt_data6(&mut out, lfsr2 as u32); + research::emit_u32_at( + ResearchStage::DllStages, + "metadata_lfsr", + lfsr2 as u32, + AddressSpace::WorkingImageRva, + trace_offset(lfsr2), + ); - let decrypt_func2 = generate(&out, lfsr2 as u32).ok_or( - UnpackError::BytecodeGenerationFailed(BytecodeStage::DllSectionDecryptor), - )?; + let decrypt_func2 = generate(&out, lfsr2 as u32).ok_or_else(|| { + research::emit_u32_at( + ResearchStage::DllStages, + "bytecode_invalid", + lfsr2 as u32, + AddressSpace::WorkingImageRva, + trace_offset(lfsr2), + ); + UnpackError::BytecodeGenerationFailed(BytecodeStage::DllSectionDecryptor) + })?; + if research::trace_enabled() { + research::emit_u32_at( + ResearchStage::DllStages, + "bytecode_section", + lfsr2 as u32, + AddressSpace::WorkingImageRva, + trace_offset(lfsr2), + ); + research::emit_u32( + ResearchStage::DllStages, + "bytecode_section_ops", + decrypt_func2.len() as u32, + ); + } let section_image_base = 4095 - get_i32(original_file_data, 4224); let section_data_offset = get_i32(&out, addr5 + 11976); + research::emit_u32_at( + ResearchStage::Sections, + "descriptor_table", + section_data_offset as u32, + AddressSpace::WorkingImageRva, + trace_offset(section_data_offset), + ); + research::emit_u32_at( + ResearchStage::Sections, + "section_image_base", + section_image_base as u32, + AddressSpace::WorkingImageRva, + trace_offset(section_image_base), + ); if verbose { println!("[8/9] Decrypting & decompressing sections..."); println!( @@ -674,6 +1208,7 @@ fn unpack_dll_inner(input: &[u8], verbose: bool) -> Result, UnpackError> 96 }; let clr_dir_rva = get_i32(file_data, pe_offset + 24 + dd_base + 14 * 8); + research::emit_bool(ResearchStage::Sections, "managed_prefill", clr_dir_rva != 0); if clr_dir_rva != 0 { let sh_start = get_u16(file_data, (pe_offset + 20) as u32) as i32 + pe_offset + 24; for i in 0..section_count(file_data, pe_offset) { @@ -693,6 +1228,20 @@ fn unpack_dll_inner(input: &[u8], verbose: bool) -> Result, UnpackError> let dd = sec_va as usize; let n = copy_len as usize; out[dd..dd + n].copy_from_slice(&file_data[s..s + n]); + research::emit_range( + ResearchStage::Sections, + "managed_prefill_src", + AddressSpace::FileOffset, + s as u64, + n as u64, + ); + research::emit_range( + ResearchStage::Sections, + "managed_prefill_dst", + AddressSpace::WorkingImageRva, + dd as u64, + n as u64, + ); } break; } @@ -709,8 +1258,22 @@ fn unpack_dll_inner(input: &[u8], verbose: bool) -> Result, UnpackError> )?; let import_table_offset = get_i32(&out, addr5 + 12016); + research::emit_u32_at( + ResearchStage::Imports, + "import_table", + import_table_offset as u32, + AddressSpace::WorkingImageRva, + trace_offset(addr5 + 12016), + ); if import_table_offset != 0 { process_import_table(&mut out, import_table_offset); + } else { + research::emit_note( + ResearchStage::Imports, + "import_table", + TraceValue::Bool(false), + "no import table", + ); } out[..4096].copy_from_slice(&file_data[..4096]); @@ -722,6 +1285,36 @@ fn unpack_dll_inner(input: &[u8], verbose: bool) -> Result, UnpackError> let section_start = section_header_base + 24; let image_data_addr = get_i32(original_file_data, section_start - 128); let image_data_size = get_i32(original_file_data, section_start - 124); + if research::trace_enabled() { + research::emit_u32_at( + ResearchStage::Finalize, + "original_entry_field", + image_data_addr as u32, + AddressSpace::FileOffset, + trace_offset(section_start - 128), + ); + research::emit_u32_at( + ResearchStage::Finalize, + "image_data_addr", + image_data_addr as u32, + AddressSpace::WorkingImageRva, + trace_offset(image_data_addr), + ); + research::emit_u32_at( + ResearchStage::Finalize, + "image_data_size", + image_data_size as u32, + AddressSpace::FileOffset, + trace_offset(section_start - 124), + ); + research::emit_u32_at( + ResearchStage::Finalize, + "section_header_base", + section_header_base as u32, + AddressSpace::FileOffset, + trace_offset(section_header_base), + ); + } let mut entry_point_adjustment = 0i32; { @@ -750,6 +1343,27 @@ fn unpack_dll_inner(input: &[u8], verbose: bool) -> Result, UnpackError> let dd = image_data_addr as usize; let n = image_data_size as usize; out[dd..dd + n].copy_from_slice(&file_data[s..s + n]); + research::emit_range( + ResearchStage::Finalize, + "image_data_src", + AddressSpace::FileOffset, + s as u64, + n as u64, + ); + research::emit_range( + ResearchStage::Finalize, + "image_data_dst", + AddressSpace::WorkingImageRva, + dd as u64, + n as u64, + ); + research::emit_u32_at( + ResearchStage::Finalize, + "entry_point_adjustment", + entry_point_adjustment as u32, + AddressSpace::FileOffset, + trace_offset(entry_point_adjustment), + ); } // Managed-only CLR header recopy (Task 3.2). No-op for native. @@ -770,12 +1384,37 @@ fn unpack_dll_inner(input: &[u8], verbose: bool) -> Result, UnpackError> let dd = clr_rva as usize; let n = clr_size as usize; out[dd..dd + n].copy_from_slice(&file_data[s..s + n]); + research::emit_u32_at( + ResearchStage::Finalize, + "clr_header", + clr_rva as u32, + AddressSpace::WorkingImageRva, + trace_offset(clr_rva), + ); + research::emit_range( + ResearchStage::Finalize, + "clr_header_src", + AddressSpace::FileOffset, + s as u64, + n as u64, + ); break; } } + } else { + research::emit_bool(ResearchStage::Finalize, "clr_header", false); } + // The anchor page rewrites the last stage of the header; the source and + // destination below are both readings of the working image. decrypt_data6_shift6(&mut out, keys[3] + 16, 656); + research::emit_range( + ResearchStage::Finalize, + "anchor_header", + AddressSpace::WorkingImageRva, + trace_offset(keys[3] + 16), + 656, + ); let pe_offset2 = get_i32(&out, 60); let final_size_of_image = get_i32(&out, keys[3] + 32); write_i32(&mut out, pe_offset2 + 40, final_size_of_image); @@ -783,7 +1422,147 @@ fn unpack_dll_inner(input: &[u8], verbose: bool) -> Result, UnpackError> let s = (keys[3] + 48) as usize; let dd = (pe_offset2 + 136) as usize; out.copy_within(s..s + 128, dd); + research::emit_range( + ResearchStage::Finalize, + "data_directories", + AddressSpace::WorkingImageRva, + dd as u64, + 128, + ); + } + + if research::trace_enabled() { + research::emit_u32_at( + ResearchStage::Finalize, + "final_pe_offset", + pe_offset2 as u32, + AddressSpace::WorkingImageRva, + trace_offset(pe_offset2), + ); + research::emit_u32( + ResearchStage::Output, + "final_size_of_image", + final_size_of_image as u32, + ); + research::emit_u64(ResearchStage::Output, "output_len", out.len() as u64); + research::emit_u32_at( + ResearchStage::Output, + "output_base", + keys[3] as u32, + AddressSpace::WorkingImageRva, + trace_offset(keys[3]), + ); } Ok(out) } + +#[cfg(test)] +mod tests { + use super::*; + use crate::windows::MAGIC_KONN; + use crate::windows::research::{ResearchTrace, with_research_trace}; + + /// A protected-shaped header `unpack_dll_inner` accepts far enough to emit + /// the header key events, then rejects at the PE offset check. Detection + /// fields are the same shape the synthetic detection test uses. + fn protected_header_input() -> Vec { + let mut data = vec![0u8; 0x1200]; + let pe = 0x80i32; + data[60..64].copy_from_slice(&pe.to_le_bytes()); + data[pe as usize..pe as usize + 4].copy_from_slice(b"PE\0\0"); + // PE32+ optional header magic at pe + 24. + data[pe as usize + 24..pe as usize + 26].copy_from_slice(&0x20Bu16.to_le_bytes()); + // Header key derivation: keys[0] = word(4096); keys[1] = keys[0] ^ word(4100). + let key0 = 1u32; + data[4096..4100].copy_from_slice(&key0.to_le_bytes()); + data[4100..4104].copy_from_slice(&(key0 ^ MAGIC_KONN).to_le_bytes()); + data + } + + fn event_names(trace: &ResearchTrace) -> Vec<&'static str> { + trace.events.iter().map(|event| event.name).collect() + } + + #[test] + fn trace_disabled_emits_nothing_and_keeps_the_result() { + let input = protected_header_input(); + assert!(!research::trace_enabled()); + let result = unpack_dll(&input); + // The synthetic header cannot recover an image; the point is that the + // untraced path is unaffected and no sink was installed. + assert!(result.is_err()); + assert!(!research::trace_enabled()); + } + + #[test] + fn trace_records_header_facts_and_the_real_failure() { + let input = protected_header_input(); + let (trace, result) = with_research_trace(|| unpack_dll(&input)); + assert!(result.is_err(), "synthetic header must fail recovery"); + + let names = event_names(&trace); + assert!( + names.contains(&"header_keys"), + "header key table must be traced: {names:?}" + ); + assert!(names.contains(&"magic")); + assert!(names.contains(&"payload_base")); + + // Scalar header facts are real computed values, and the magic keeps + // the KONN encoding under the protected-header space. + let keys = trace + .events + .iter() + .find(|event| event.name == "header_keys") + .expect("header_keys event"); + // keys[0] is the raw first word and keys[1] carries the magic; later + // entries are chained, so only these two are fixed by this input. + match &keys.value { + TraceValue::U32s(values) => { + assert_eq!(values.len(), 8); + assert_eq!(values[0], 1); + assert_eq!(values[1], MAGIC_KONN); + } + other => panic!("header_keys must be a word list, got {other:?}"), + } + let magic = trace + .events + .iter() + .find(|event| event.name == "magic") + .expect("magic event"); + assert_eq!(magic.value, TraceValue::U32(MAGIC_KONN)); + assert_eq!( + magic.address, + Some(crate::windows::research::TraceAddress { + space: AddressSpace::ProtectedHeaderOffset, + offset: 4100, + }) + ); + + let anchor = trace + .events + .iter() + .find(|event| event.name == "anchor") + .expect("anchor event"); + assert_eq!( + anchor.address.as_ref().map(|address| address.space), + Some(AddressSpace::WorkingImageRva) + ); + let TraceValue::U32(anchor_rva) = &anchor.value else { + panic!("anchor must be an RVA"); + }; + assert_eq!( + anchor.address.as_ref().map(|address| address.offset), + Some(u64::from(*anchor_rva)) + ); + + // Nothing may claim a layout selection or a validated image: the + // synthetic input never reaches section recovery. + assert!( + !names.iter().any(|name| name.contains("selected")), + "no selection claim on a failed recovery: {names:?}" + ); + assert!(!names.contains(&"output_len")); + } +} diff --git a/senbei-engine/src/windows/exe/pipeline.rs b/senbei-engine/src/windows/exe/pipeline.rs index b903dd3..3efa1fb 100644 --- a/senbei-engine/src/windows/exe/pipeline.rs +++ b/senbei-engine/src/windows/exe/pipeline.rs @@ -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 { @@ -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) } diff --git a/senbei-engine/src/windows/exe/pipeline/pe32.rs b/senbei-engine/src/windows/exe/pipeline/pe32.rs index c071bef..1bc17a1 100644 --- a/senbei-engine/src/windows/exe/pipeline/pe32.rs +++ b/senbei-engine/src/windows/exe/pipeline/pe32.rs @@ -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) -> &'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 { 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 [ diff --git a/senbei-engine/src/windows/inspect.rs b/senbei-engine/src/windows/inspect.rs new file mode 100644 index 0000000..ba47ff3 --- /dev/null +++ b/senbei-engine/src/windows/inspect.rs @@ -0,0 +1,2599 @@ +//! Rich, read-only Windows research inspection. +//! +//! [`inspect_research`](super::inspect_research) answers a narrower question +//! than recovery: what does the input itself say? It parses the PE container +//! (headers, sections, directories, file regions), decodes the protected header +//! table when one is present, and — within a small, fixed scratch budget — +//! decodes the declared payload prefix to look for real shell structures. +//! +//! What it never does: allocate `SizeOfImage`, run a recovery stage, execute +//! the input, or report a protection build/version. A recovery is the only +//! place where later-stage facts become observable; this module reports only +//! what a bounded probe can see, and names the stage where a fact was not +//! available instead of guessing. +//! +//! Every offset is labelled with the address space it belongs to: +//! [`AddressSpace::FileOffset`] (protected input bytes), +//! [`AddressSpace::DecodedPayloadOffset`] (offset relative to the decoded +//! payload base `info[3]`), and [`AddressSpace::WorkingImageRva`] (RVA of the +//! image the pipeline builds). The scratch image this module decodes is exactly +//! such a working-image fragment, so payload offsets and RVAs coincide only +//! when the probe base is `info[3]`. + +use serde::Serialize; + +use senbei_crypto::primitives; +use senbei_pe::{Headers, Section}; + +use super::layout; +use super::research::AddressSpace; +use crate::profile::TargetFormat; +use crate::windows::{Kind, MAGIC_KONN}; + +/// Upper bound for the PE section and directory lists. A real image is far +/// below this; a corrupt header cannot make inspection allocate or scan +/// without bound. +const MAX_SECTIONS: u16 = 96; +/// Upper bound for the data directories walked from `NumberOfRvaAndSizes`. +const MAX_DIRECTORIES: u32 = 16; +/// Upper bound for reported file regions (gaps + overlay). +const MAX_REGIONS: usize = 64; +/// Upper bound for reported issues, so a malformed header cannot grow output +/// without bound. +pub const DEFAULT_MAX_ISSUES: usize = 64; +/// Default scratch budget for prefix decoding (2 MiB). +pub const DEFAULT_PREFIX_SCRATCH_BYTES: u64 = 2 * 1024 * 1024; +/// Default candidate cap for shell discovery. +pub const DEFAULT_MAX_CANDIDATES: usize = 32; +/// Work limits for [`inspect_research_with_limits`]. The defaults are what +/// [`inspect_research`] uses; tests and fuzzing can lower them to prove the +/// bounds. +/// +/// The trace budget is not here: the pure inspector never emits trace events. +/// Use [`with_research_trace_limited`](super::with_research_trace_limited) to +/// bound a recovery trace. +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct InspectionLimits { + pub prefix_scratch_bytes: u64, + pub max_candidates: usize, + pub max_issues: usize, +} + +impl Default for InspectionLimits { + fn default() -> Self { + Self { + prefix_scratch_bytes: DEFAULT_PREFIX_SCRATCH_BYTES, + max_candidates: DEFAULT_MAX_CANDIDATES, + max_issues: DEFAULT_MAX_ISSUES, + } + } +} + +/// Severity of an inspection issue. Inspection issues explain a partial or +/// unavailable finding; they are not recovery errors. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] +#[serde(rename_all = "snake_case")] +pub enum InspectionSeverity { + Info, + Warning, + /// The fact exists but needs a stage this bounded probe does not run. + Unavailable, +} + +/// One partial-finding explanation. +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct InspectionIssue { + pub severity: InspectionSeverity, + /// Short area tag: "pe", "protection", "payload", "probe", "discovery". + pub area: &'static str, + pub message: String, +} + +/// Work actually done by one inspection. +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct InspectionWork { + pub prefix_scratch_limit: u64, + pub prefix_bytes_decoded: u64, + pub candidates_considered: u32, + /// True when a limit (not the input) stopped a probe from going further. + pub budget_limited: bool, +} + +/// Complete result of one research inspection. Always returned, even for +/// garbage; malformed inputs keep whatever parsed and explain the rest in +/// [`issues`](Self::issues). +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct WindowsInspection { + pub input_len: u64, + #[serde(skip_serializing_if = "Option::is_none")] + pub pe: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub protection: Option, + pub issues: Vec, + pub work: InspectionWork, +} + +/// COFF header field a named flag came from. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] +#[serde(rename_all = "snake_case")] +pub enum FlagField { + CoffCharacteristics, + DllCharacteristics, +} + +/// A set bit with its documented name. These are *declarations* in the header, +/// not guarantees about runtime behaviour. +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct NamedFlag { + pub field: FlagField, + pub bit: u16, + pub name: &'static str, +} + +/// Section permission bits from `IMAGE_SCN_MEM_*` / `IMAGE_SCN_CNT_*`. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] +pub struct SectionPermissions { + pub read: bool, + pub write: bool, + pub execute: bool, + pub code: bool, + pub initialized_data: bool, + pub uninitialized_data: bool, +} + +/// How much of a section's declared raw range the file actually backs. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] +#[serde(rename_all = "snake_case")] +pub enum SectionBacking { + /// The full declared raw range is inside the input. + FileBacked, + /// Part of the raw range is inside the input. + RawTruncated { available: u64 }, + /// The section declares no file bytes (BSS-like). + VirtualOnly, +} + +/// One observed section-table anomaly. +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct SectionAnomaly { + pub kind: SectionAnomalyKind, + pub detail: String, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] +#[serde(rename_all = "snake_case")] +pub enum SectionAnomalyKind { + /// Raw range starts before the end of the PE headers. + RawOverlapsHeaders, + /// Raw range runs past the end of the file. + RawPastEof, + /// Virtual range overlaps another section's virtual range. + VirtualOverlap, + /// Raw range overlaps another section's raw range. + RawOverlap, + /// Virtual size is zero but raw size is not. + ZeroVirtualSize, + /// Entry point lies inside the section's virtual range. + EntryPointInside, +} + +/// One section-table entry as declared, plus what the file backs. +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct SectionInspection { + pub index: u16, + /// Section name, trailing NULs stripped. Not guaranteed ASCII. + pub name: String, + pub virtual_address: u32, + pub virtual_size: u32, + pub raw_offset: u32, + pub raw_size: u32, + /// `raw_offset + raw_size` as computed, even when it overflows 32 bits. + pub raw_end: u64, + pub raw_in_bounds: bool, + /// Original `IMAGE_SECTION_HEADER.Characteristics`. The permission booleans + /// are derived views; discardable/shared/cache bits exist only here. + pub characteristics: u32, + pub permissions: SectionPermissions, + pub backing: SectionBacking, + pub anomalies: Vec, +} + +/// How a declared data directory maps into the file. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] +#[serde(rename_all = "snake_case")] +pub enum DirectoryMapping { + /// Directory entry is (0, 0): not published. + Zero, + /// The range lies wholly in the PE headers. + HeaderBacked, + /// The range lies wholly in file bytes outside any section (the + /// certificate table is the only such directory). + FileBacked, + /// The range lies wholly in one section's file-backed bytes. + SectionBacked { section: u16 }, + /// Only `backed` bytes of `size` are file-backed. + PartiallyBacked { backed: u64 }, + /// Nothing maps into the input. + Unmapped, +} + +/// One declared data directory. +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct DirectoryInspection { + pub index: u16, + pub name: &'static str, + /// RVA, or file offset for the certificate directory (index 4). + pub address: u32, + pub address_space: AddressSpace, + pub size: u32, + /// File offset when the declared range is file-backed from its start. + #[serde(skip_serializing_if = "Option::is_none")] + pub file_offset: Option, + pub mapping: DirectoryMapping, + #[serde(skip_serializing_if = "Option::is_none")] + pub note: Option<&'static str>, +} + +/// A byte range of the file not covered by any section's declared raw range. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] +#[serde(rename_all = "snake_case")] +pub enum FileRegionKind { + /// Between the end of the PE headers and the first section's raw start. + HeadersToFirstSection, + /// Between two sections' raw ranges. + BetweenSections, + /// After the last section's raw range. + Overlay, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] +pub struct FileRegion { + pub offset: u64, + pub length: u64, + pub kind: FileRegionKind, +} + +/// Everything parsed from the PE headers of either the input or a restored +/// image. Fields are optional so a truncated header still reports what parsed. +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct PeInspection { + #[serde(skip_serializing_if = "Option::is_none")] + pub pe_offset: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub machine: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub format: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub kind: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub image_base: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub entry_point_rva: Option, + /// File offset backing the entry point, when a section maps it. + #[serde(skip_serializing_if = "Option::is_none")] + pub entry_point_file_offset: Option, + /// True when the entry point RVA maps to file bytes; false when it is in a + /// zero-filled tail or unmapped; absent when no entry point was parsed. + #[serde(skip_serializing_if = "Option::is_none")] + pub entry_point_available: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub size_of_image: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub size_of_headers: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub section_alignment: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub file_alignment: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub characteristics: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub dll_characteristics: Option, + pub named_flags: Vec, + pub sections: Vec, + pub directories: Vec, + pub unsectioned: Vec, + #[serde(skip_serializing_if = "Option::is_none")] + pub overlay: Option, + /// Header-level parse explanation when parsing stopped early. + #[serde(skip_serializing_if = "Option::is_none")] + pub parse_issue: Option, +} + +/// Decoded header word with the source file position it came from. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] +#[serde(rename_all = "snake_case")] +pub enum HeaderWordSemantic { + Key, + Magic, + PayloadSource, + DestinationRva, + TotalLength, + EndMarker, +} + +/// One of the eight protection header words. +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct HeaderWord { + pub index: u8, + /// Absolute byte offset in the protected input of the *raw* cell this word + /// was extracted from (`0x1000 + index * 4`). It identifies where the + /// scalar was read, not what the value means. + pub source_file_offset: u64, + pub raw_word: u32, + /// Decoded word (the key-table formula's output). + pub decoded_word: u32, + /// Semantic name only where the pipeline actually uses the word that way. + #[serde(skip_serializing_if = "Option::is_none")] + pub semantic: Option, +} + +/// One in-bounds check on the declared payload region. +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct PayloadCheck { + pub name: &'static str, + pub start: u64, + pub length: u64, + pub end: u64, + pub limit: u64, + pub in_bounds: bool, + pub overflow: bool, +} + +/// The payload the header declares. Values are the decoded header words, +/// expressed in the space the pipeline uses: `source_file_offset` is a file +/// offset, `destination_rva` and `size_of_image` are working-image RVAs. +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct DeclaredPayload { + /// `info[4] + 0x1000`, the first protected byte of the payload. + pub source_file_offset: u64, + pub destination_rva: u32, + /// `info[6] - info[3] + 0x2000`: the prefix the key-table cipher covers. + pub prefix_length: u64, + /// `info[5]`: declared total payload length. + pub total_length: u64, + /// Header-declared `SizeOfImage` of the protected file. + pub size_of_image: u64, + pub checks: Vec, +} + +/// Outcome of a bounded probe. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] +#[serde(rename_all = "snake_case")] +pub enum ProbeOutcome { + /// A required stage or input region was missing; no probe was possible. + Unavailable, + /// A work limit stopped the probe before it could decide. + BudgetLimited, + /// The probe ran but produced no structurally valid result. + Failed, + /// The probe produced a validated structural result. + Decoded, +} + +/// Bounded scratch-only decoding of the declared payload prefix. +/// +/// `requested_length`/`decoded_length` are the whole scratch span: the decoded +/// prefix plus the raw tail copied verbatim after it. `prefix_bytes` and +/// `tail_bytes` split that span, so a reader never has to infer how much was +/// actually cipher-decoded. +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct PrefixProbe { + pub status: ProbeOutcome, + /// `prefix_bytes + tail_bytes`: the scratch span the probe used. + pub requested_length: u64, + pub decoded_length: u64, + /// Bytes actually run through the prefix cipher + /// (`info[6] - info[3] + 0x2000`), or the intended prefix on an + /// `Unavailable`/`BudgetLimited` outcome. On those outcomes it is a + /// declaration, not work done: read `decoded_length` for what happened. + pub prefix_bytes: u64, + /// Raw payload tail available after the prefix, clamped to the input. + /// These bytes are copied only when the probe status is `Decoded`; on a + /// blocked or budget-limited probe this is a planned span, not work done. + pub tail_bytes: u64, + pub limit_bytes: u64, + /// First decoded words at the payload destination (working-image RVA). + pub first_words: Vec, + #[serde(skip_serializing_if = "Option::is_none")] + pub reason: Option<&'static str>, +} + +/// Kind of structure a shell candidate represents. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] +#[serde(rename_all = "snake_case")] +pub enum ShellCandidateKind { + /// PE32 compact/standard shell table (`find_tbl_pe32_candidates` shape). + Pe32ShellTable, + /// PE32+ anchor descriptor scan (anchor-relative stage1 descriptor). + Pe32PlusAnchor, +} + +/// How far a candidate was validated. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] +#[serde(rename_all = "snake_case")] +pub enum CandidateStatus { + /// A value was read from the input and reported; not structural. + Observed, + /// The shape matches, but the stage that would confirm it was not run. + StructuralCandidate, + /// A bounded trial produced a structurally valid result. + TrialValidated, + /// A bounded trial rejected the candidate. + Rejected, +} + +/// One named field of a shell candidate. `space` is present only when the +/// value is an offset; plain scalars (sizes, flags) carry `None` so a number +/// is never mislabelled as an address. +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct CandidateField { + pub name: &'static str, + pub value: u32, + #[serde(skip_serializing_if = "Option::is_none")] + pub space: Option, +} + +/// One discovered shell structure. +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct ShellCandidate { + pub kind: ShellCandidateKind, + pub status: CandidateStatus, + /// Offset in the decoded payload scratch (relative to the probe base). + #[serde(skip_serializing_if = "Option::is_none")] + pub payload_offset: Option, + /// Working-image RVA of the candidate, when the scratch is RVA-addressed. + #[serde(skip_serializing_if = "Option::is_none")] + pub image_rva: Option, + /// File offset in the protected input when the structure lives there. + #[serde(skip_serializing_if = "Option::is_none")] + pub source_file_offset: Option, + pub fields: Vec, + pub reason: &'static str, +} + +/// Result of bounded shell discovery. +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct DiscoveryReport { + pub status: ProbeOutcome, + pub candidates: Vec, + /// Word positions the structural scan examined. This is scan effort, not a + /// candidate count; use `candidates.len()` for how many structures were + /// reported. + pub positions_scanned: u32, + #[serde(skip_serializing_if = "Option::is_none")] + pub reason: Option<&'static str>, +} + +/// Protection-header facts and bounded probe results for one input. +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct ProtectionInspection { + /// Decoded `info[1]`. + pub magic: Option, + pub magic_recognized: bool, + pub header_words: Vec, + #[serde(skip_serializing_if = "Option::is_none")] + pub payload: Option, + pub probe: PrefixProbe, + pub discovery: DiscoveryReport, +} + +// --------------------------------------------------------------------------- +// Inspection entry points +// --------------------------------------------------------------------------- + +pub(super) fn inspect(input: &[u8], limits: &InspectionLimits) -> WindowsInspection { + let mut issues = IssueList::new(limits.max_issues); + let pe = inspect_pe(input, &mut issues); + let protection = inspect_protection(input, limits, &mut issues); + let (prefix_bytes_decoded, candidates_considered, budget_limited) = work_from(&protection); + WindowsInspection { + input_len: input.len() as u64, + pe, + protection, + issues: issues.into_vec(), + work: InspectionWork { + prefix_scratch_limit: limits.prefix_scratch_bytes, + prefix_bytes_decoded, + candidates_considered, + budget_limited, + }, + } +} + +fn work_from(protection: &Option) -> (u64, u32, bool) { + let Some(protection) = protection else { + return (0, 0, false); + }; + let budget_limited = protection.probe.status == ProbeOutcome::BudgetLimited + || protection.discovery.status == ProbeOutcome::BudgetLimited; + ( + // Actual cipher-decoded bytes, excluding the verbatim raw tail. A + // failed/budget-limited probe decoded nothing. + if protection.probe.status == ProbeOutcome::Decoded { + protection.probe.prefix_bytes + } else { + 0 + }, + u32::try_from(protection.discovery.candidates.len()).unwrap_or(u32::MAX), + budget_limited, + ) +} + +struct IssueList { + issues: Vec, + limit: usize, +} + +impl IssueList { + fn new(limit: usize) -> Self { + Self { + issues: Vec::new(), + limit, + } + } + + fn push( + &mut self, + severity: InspectionSeverity, + area: &'static str, + message: impl Into, + ) { + if self.issues.len() < self.limit { + self.issues.push(InspectionIssue { + severity, + area, + message: message.into(), + }); + } + } + + fn into_vec(self) -> Vec { + self.issues + } +} + +// --------------------------------------------------------------------------- +// PE header inspection +// --------------------------------------------------------------------------- + +const DIRECTORY_NAMES: [&str; 16] = [ + "export", + "import", + "resource", + "exception", + "certificate", + "base_relocation", + "debug", + "architecture", + "global_pointer", + "tls", + "load_config", + "bound_import", + "iat", + "delay_import", + "clr_runtime", + "reserved", +]; + +fn inspect_pe(input: &[u8], issues: &mut IssueList) -> Option { + let headers = match senbei_pe::parse(input) { + Ok(headers) => Some(headers), + Err(error) => { + issues.push( + InspectionSeverity::Warning, + "pe", + format!("PE headers did not parse: {error}"), + ); + None + } + }; + let headers = headers?; + let sections = senbei_pe::sections(input, headers).unwrap_or_default(); + let typed = TypedHeader::read(input, &headers); + let mut pe = PeInspection { + pe_offset: Some(headers.pe_offset as u64), + machine: typed.machine, + format: Some(if headers.is_pe32_plus { + TargetFormat::Pe32Plus + } else { + TargetFormat::Pe32 + }), + kind: typed.kind, + image_base: Some(headers.image_base), + entry_point_rva: Some(headers.entry_rva), + entry_point_file_offset: None, + entry_point_available: None, + size_of_image: Some(headers.size_of_image), + size_of_headers: typed.size_of_headers, + section_alignment: typed.section_alignment, + file_alignment: typed.file_alignment, + characteristics: typed.characteristics, + dll_characteristics: typed.dll_characteristics, + named_flags: typed.named_flags, + sections: Vec::new(), + directories: Vec::new(), + unsectioned: Vec::new(), + overlay: None, + parse_issue: None, + }; + + let entry = resolve_entry(input, &headers); + pe.entry_point_file_offset = entry.0; + pe.entry_point_available = Some(entry.1); + + let size_of_headers = typed.size_of_headers.unwrap_or(0); + let section_anomalies = + section_anomalies(§ions, headers.entry_rva, input.len(), size_of_headers); + for (index, section) in sections.iter().enumerate().take(MAX_SECTIONS as usize) { + pe.sections.push(inspect_section( + index as u16, + section, + section_name(input, &headers, index as u16), + input.len(), + §ion_anomalies[index], + )); + } + if sections.len() > MAX_SECTIONS as usize { + issues.push( + InspectionSeverity::Warning, + "pe", + format!( + "{} sections declared; only the first {} are reported", + sections.len(), + MAX_SECTIONS + ), + ); + } + + pe.directories = inspect_directories(input, &headers, §ions); + let (unsectioned, overlay) = file_regions(input.len(), §ions, &headers); + pe.unsectioned = unsectioned; + pe.overlay = overlay; + + if typed.machine.is_none() { + pe.parse_issue = Some("COFF machine field is outside the input".to_owned()); + } + Some(pe) +} + +/// `(file_offset, is_file_backed)` for the entry point, when one exists. +fn resolve_entry(input: &[u8], headers: &Headers) -> (Option, bool) { + if headers.entry_rva == 0 { + return (None, false); + } + let sections = senbei_pe::sections(input, *headers).unwrap_or_default(); + for section in §ions { + let delta = headers.entry_rva.wrapping_sub(section.virtual_address); + let span = section.virtual_size.max(section.raw_size); + if headers.entry_rva >= section.virtual_address && delta < span { + if delta < section.raw_size { + let offset = section.raw_offset as u64 + delta as u64; + if offset < input.len() as u64 { + return (Some(offset), true); + } + } + return (None, false); + } + } + if headers.entry_rva < headers.sections_offset as u32 { + let offset = headers.entry_rva as u64; + if offset < input.len() as u64 { + return (Some(offset), true); + } + } + (None, false) +} + +struct TypedHeader { + machine: Option, + kind: Option, + size_of_headers: Option, + section_alignment: Option, + file_alignment: Option, + characteristics: Option, + dll_characteristics: Option, + named_flags: Vec, +} + +impl TypedHeader { + fn read(input: &[u8], headers: &Headers) -> Self { + let pe = headers.pe_offset; + let machine = read_u16(input, pe + 4); + let characteristics = read_u16(input, pe + 22); + let optional = pe + 24; + // These four fields sit at the same optional-header offsets in PE32 + // and PE32+; only ImageBase and the directory base differ. + let size_of_headers = read_u32(input, optional + 60); + let section_alignment = read_u32(input, optional + 32); + let file_alignment = read_u32(input, optional + 36); + let dll_characteristics = read_u16(input, optional + 70); + let mut named_flags = Vec::new(); + if let Some(chars) = characteristics { + for (bit, name) in COFF_FLAGS { + if chars & bit != 0 { + named_flags.push(NamedFlag { + field: FlagField::CoffCharacteristics, + bit, + name, + }); + } + } + } + if let Some(chars) = dll_characteristics { + for (bit, name) in DLL_FLAGS { + if chars & bit != 0 { + named_flags.push(NamedFlag { + field: FlagField::DllCharacteristics, + bit, + name, + }); + } + } + } + let kind = match (characteristics, clr_directory_rva(input, headers)) { + (Some(chars), Some(clr)) => { + let is_dll = chars & 0x2000 != 0; + Some(match (is_dll, clr != 0) { + (false, false) => Kind::NativeExe, + (false, true) => Kind::ManagedExe, + (true, false) => Kind::NativeDll, + (true, true) => Kind::ManagedDll, + }) + } + _ => None, + }; + Self { + machine, + kind, + size_of_headers, + section_alignment, + file_alignment, + characteristics, + dll_characteristics, + named_flags, + } + } +} + +const COFF_FLAGS: [(u16, &str); 11] = [ + (0x0001, "relocations_stripped"), + (0x0002, "executable_image"), + (0x0004, "line_numbers_stripped"), + (0x0008, "local_symbols_stripped"), + (0x0010, "large_address_aware"), + (0x0020, "32bit_machine"), + (0x0100, "debug_stripped"), + (0x0200, "removable_run_from_swap"), + (0x1000, "system"), + (0x2000, "dll"), + (0x4000, "unmanaged_code_only"), +]; + +const DLL_FLAGS: [(u16, &str); 9] = [ + (0x0020, "high_entropy_va"), + (0x0040, "dynamic_base_aslr_declared"), + (0x0080, "force_integrity"), + (0x0100, "nx_compat_declared"), + (0x0200, "no_isolation"), + (0x0400, "no_seh"), + (0x0800, "no_bind"), + (0x1000, "app_container"), + (0x4000, "guard_cf_declared"), +]; + +fn clr_directory_rva(input: &[u8], headers: &Headers) -> Option { + senbei_pe::data_directory(input, *headers, 14) + .ok() + .map(|(rva, _)| rva) +} + +fn inspect_section( + index: u16, + section: &Section, + name: String, + input_len: usize, + anomalies: &[SectionAnomaly], +) -> SectionInspection { + let raw_end = section.raw_offset as u64 + section.raw_size as u64; + let raw_in_bounds = raw_end <= input_len as u64; + let available = (input_len as u64).saturating_sub(section.raw_offset as u64); + let backing = if section.raw_size == 0 { + SectionBacking::VirtualOnly + } else if raw_in_bounds { + SectionBacking::FileBacked + } else { + SectionBacking::RawTruncated { + available: available.min(section.raw_size as u64), + } + }; + SectionInspection { + index, + name, + virtual_address: section.virtual_address, + virtual_size: section.virtual_size, + raw_offset: section.raw_offset, + raw_size: section.raw_size, + raw_end, + raw_in_bounds, + characteristics: section.characteristics, + permissions: SectionPermissions { + read: section.characteristics & 0x4000_0000 != 0, + write: section.characteristics & 0x8000_0000 != 0, + execute: section.characteristics & 0x2000_0000 != 0, + code: section.characteristics & 0x0000_0020 != 0, + initialized_data: section.characteristics & 0x0000_0040 != 0, + uninitialized_data: section.characteristics & 0x0000_0080 != 0, + }, + backing, + anomalies: anomalies.to_vec(), + } +} + +/// Section names are exactly 8 bytes and may fill the field (no NUL). +fn section_name(input: &[u8], headers: &Headers, index: u16) -> String { + let Some(offset) = headers.sections_offset.checked_add(usize::from(index) * 40) else { + return String::new(); + }; + let Some(field) = input.get(offset..offset + 8) else { + return String::new(); + }; + let end = field.iter().position(|&b| b == 0).unwrap_or(8); + String::from_utf8_lossy(&field[..end]).into_owned() +} + +/// Anomalies for at most [`MAX_SECTIONS`] sections. The cap is applied before +/// any pairwise work, so a crafted header declaring 65535 overlapping sections +/// cannot drive quadratic time or per-section allocation. +fn section_anomalies( + sections: &[Section], + entry_rva: u32, + input_len: usize, + size_of_headers: u32, +) -> Vec> { + let sections = §ions[..sections.len().min(MAX_SECTIONS as usize)]; + let mut result = vec![Vec::new(); sections.len()]; + if sections.is_empty() { + return result; + } + for (index, section) in sections.iter().enumerate() { + let raw_end = section.raw_offset as u64 + section.raw_size as u64; + let virt_end = + section.virtual_address as u64 + section.virtual_size.max(section.raw_size) as u64; + let mut anomalies = Vec::new(); + if section.raw_size != 0 + && size_of_headers != 0 + && (section.raw_offset as u64) < u64::from(size_of_headers) + { + anomalies.push(SectionAnomaly { + kind: SectionAnomalyKind::RawOverlapsHeaders, + detail: format!( + "raw range starts at 0x{:X}, inside the declared headers (0x{size_of_headers:X})", + section.raw_offset + ), + }); + } + if raw_end > input_len as u64 && section.raw_size != 0 { + anomalies.push(SectionAnomaly { + kind: SectionAnomalyKind::RawPastEof, + detail: format!("raw range ends at 0x{raw_end:X}, input is 0x{input_len:X} bytes"), + }); + } + if section.virtual_size == 0 && section.raw_size != 0 { + anomalies.push(SectionAnomaly { + kind: SectionAnomalyKind::ZeroVirtualSize, + detail: "virtual size is zero while raw size is not".to_owned(), + }); + } + let entry_in = + entry_rva != 0 && entry_rva >= section.virtual_address && (entry_rva as u64) < virt_end; + if entry_in { + anomalies.push(SectionAnomaly { + kind: SectionAnomalyKind::EntryPointInside, + detail: format!("entry point 0x{entry_rva:X} lies in this section"), + }); + } + for other in §ions[index + 1..] { + let other_virt_end = + other.virtual_address as u64 + other.virtual_size.max(other.raw_size) as u64; + let virt_overlap = (section.virtual_address as u64) < other_virt_end + && (other.virtual_address as u64) < virt_end + && section.virtual_size != 0 + && other.virtual_size != 0; + if virt_overlap { + anomalies.push(SectionAnomaly { + kind: SectionAnomalyKind::VirtualOverlap, + detail: format!( + "virtual range overlaps section at RVA 0x{:X}", + other.virtual_address + ), + }); + } + let other_raw_end = other.raw_offset as u64 + other.raw_size as u64; + if section.raw_size != 0 + && other.raw_size != 0 + && (section.raw_offset as u64) < other_raw_end + && (other.raw_offset as u64) < raw_end + { + anomalies.push(SectionAnomaly { + kind: SectionAnomalyKind::RawOverlap, + detail: format!( + "raw range overlaps section at file offset 0x{:X}", + other.raw_offset + ), + }); + } + } + result[index] = anomalies; + } + result +} + +fn inspect_directories( + input: &[u8], + headers: &Headers, + sections: &[Section], +) -> Vec { + let count = directory_count(input, headers).min(MAX_DIRECTORIES).min(16); + let mut result = Vec::new(); + for index in 0..count { + let Ok((address, size)) = senbei_pe::data_directory(input, *headers, index as u16) else { + break; + }; + let name = DIRECTORY_NAMES[index as usize]; + let address_space = if index == 4 { + AddressSpace::FileOffset + } else { + AddressSpace::WorkingImageRva + }; + if address == 0 || size == 0 { + result.push(DirectoryInspection { + index: index as u16, + name, + address, + address_space, + size, + file_offset: None, + mapping: DirectoryMapping::Zero, + note: None, + }); + continue; + } + let (file_offset, mapping) = if index == 4 { + // The certificate table is a file offset, not an RVA, and it is + // not inside any section — report plain file backing rather than + // inventing a section index. + let end = address as u64 + size as u64; + if end <= input.len() as u64 { + (Some(address as u64), DirectoryMapping::FileBacked) + } else { + ( + Some(address as u64), + DirectoryMapping::PartiallyBacked { + backed: (input.len() as u64).saturating_sub(address as u64), + }, + ) + } + } else { + map_directory(input, headers, sections, address, size) + }; + let note = if index == 4 { + Some("certificate directory uses a file offset, not an RVA") + } else { + None + }; + result.push(DirectoryInspection { + index: index as u16, + name, + address, + address_space, + size, + file_offset, + mapping, + note, + }); + } + result +} + +fn directory_count(input: &[u8], headers: &Headers) -> u32 { + let optional = headers.pe_offset + 24; + let offset = if headers.is_pe32_plus { + optional + 108 + } else { + optional + 92 + }; + read_u32(input, offset).unwrap_or(0) +} + +fn map_directory( + input: &[u8], + headers: &Headers, + sections: &[Section], + rva: u32, + size: u32, +) -> (Option, DirectoryMapping) { + // Headers extend to the declared `SizeOfHeaders`, not merely to the end of + // the section table: a directory placed in the reserved header padding is + // header-backed too. + let size_of_headers = read_u32(input, headers.pe_offset + 24 + 60) + .filter(|&size| size != 0) + .unwrap_or(headers.sections_offset as u32); + if rva < size_of_headers { + let end = rva as u64 + size as u64; + if end <= input.len() as u64 { + return (Some(rva as u64), DirectoryMapping::HeaderBacked); + } + return ( + None, + DirectoryMapping::PartiallyBacked { + backed: (input.len() as u64).saturating_sub(rva as u64), + }, + ); + } + for (index, section) in sections.iter().enumerate() { + let delta = rva.wrapping_sub(section.virtual_address); + if rva < section.virtual_address { + continue; + } + let span = section.virtual_size.max(section.raw_size); + if delta >= span { + continue; + } + if delta < section.raw_size { + let offset = section.raw_offset as u64 + delta as u64; + let raw_left = (section.raw_size - delta) as u64; + if size as u64 <= raw_left && offset + size as u64 <= input.len() as u64 { + return ( + Some(offset), + DirectoryMapping::SectionBacked { + section: index as u16, + }, + ); + } + return ( + Some(offset), + DirectoryMapping::PartiallyBacked { + backed: raw_left.min((input.len() as u64).saturating_sub(offset)), + }, + ); + } + return (None, DirectoryMapping::Unmapped); + } + (None, DirectoryMapping::Unmapped) +} + +fn file_regions( + input_len: usize, + sections: &[Section], + headers: &Headers, +) -> (Vec, Option) { + let file_len = input_len as u64; + let section_table_end = headers.sections_offset as u64 + sections.len() as u64 * 40; + // A declared `SizeOfHeaders` is the reserve the loader zero-fills; the + // section table end is the conservative minimum. Use the smaller so a + // bogus SizeOfHeaders cannot hide a gap. + let header_end = section_table_end.min(file_len); + let mut raws: Vec<(u64, u64)> = sections + .iter() + .filter(|section| section.raw_size != 0 && (section.raw_offset as u64) < file_len) + .map(|section| { + ( + section.raw_offset as u64, + (section.raw_offset as u64 + section.raw_size as u64).min(file_len), + ) + }) + .collect(); + raws.sort_unstable(); + let first_start = raws.first().map_or(file_len, |(start, _)| *start); + let mut regions: Vec = Vec::new(); + let push = |offset: u64, end: u64, kind: FileRegionKind, regions: &mut Vec| { + if offset < end && regions.len() < MAX_REGIONS { + regions.push(FileRegion { + offset, + length: end - offset, + kind, + }); + } + }; + if header_end < first_start { + push( + header_end, + first_start, + FileRegionKind::HeadersToFirstSection, + &mut regions, + ); + } + let mut cursor = first_start; + for (start, end) in &raws { + if *start > cursor { + push( + cursor, + *start, + FileRegionKind::BetweenSections, + &mut regions, + ); + } + cursor = cursor.max(*end); + } + let overlay = (cursor < file_len).then(|| FileRegion { + offset: cursor, + length: file_len - cursor, + kind: FileRegionKind::Overlay, + }); + (regions, overlay) +} + +// --------------------------------------------------------------------------- +// Small bounded readers +// --------------------------------------------------------------------------- + +fn read_u16(input: &[u8], offset: usize) -> Option { + let bytes = input.get(offset..offset.checked_add(2)?)?; + Some(u16::from_le_bytes([bytes[0], bytes[1]])) +} + +fn read_u32(input: &[u8], offset: usize) -> Option { + let bytes = input.get(offset..offset.checked_add(4)?)?; + Some(u32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]])) +} + +// --------------------------------------------------------------------------- +// Protection header inspection +// --------------------------------------------------------------------------- + +/// The protected header table occupies `[0x1000, 0x1020)`. +const HEADER_TABLE_OFFSET: usize = 0x1000; +const HEADER_TABLE_LEN: usize = 32; + +fn inspect_protection( + input: &[u8], + limits: &InspectionLimits, + issues: &mut IssueList, +) -> Option { + let words = header_words(input)?; + let info: [u32; 8] = std::array::from_fn(|index| words[index].decoded); + let magic = Some(info[1]); + let magic_recognized = info[1] == MAGIC_KONN; + + let mut header_words_out: Vec = Vec::with_capacity(8); + for (index, word) in words.iter().enumerate() { + header_words_out.push(HeaderWord { + index: index as u8, + source_file_offset: (HEADER_TABLE_OFFSET + index * 4) as u64, + raw_word: word.raw, + decoded_word: word.decoded, + semantic: header_semantic(index), + }); + } + + if !magic_recognized { + issues.push( + InspectionSeverity::Info, + "protection", + format!( + "header table decoded but info[1] is 0x{:08X}, not the supported magic", + info[1] + ), + ); + } + + let payload = declared_payload(input, &info); + // A probe only makes sense for the protected layout this pipeline knows. + // An unrelated file can carry a coherent-looking word table by accident; + // reporting its raw/decoded words is fine, running the pipeline's + // discovery over it is not. + let (probe, scratch) = if magic_recognized { + decode_prefix_probe(input, &info, payload.as_ref(), limits, issues) + } else { + ( + PrefixProbe { + status: ProbeOutcome::Unavailable, + requested_length: 0, + decoded_length: 0, + prefix_bytes: 0, + tail_bytes: 0, + limit_bytes: limits.prefix_scratch_bytes, + first_words: Vec::new(), + reason: Some("header magic is not a supported protection header"), + }, + None, + ) + }; + let discovery = discover_shell(input, payload.as_ref(), &probe, scratch.as_deref(), limits); + + Some(ProtectionInspection { + magic, + magic_recognized, + header_words: header_words_out, + payload, + probe, + discovery, + }) +} + +struct Word { + raw: u32, + decoded: u32, +} + +/// Decode the eight header words with the same recurrence `decrypt_data1` +/// uses, pairing each decoded word with its raw source cell so the report +/// cannot show an inconsistent raw/decoded pair. +fn header_words(input: &[u8]) -> Option<[Word; 8]> { + if input.len() < HEADER_TABLE_OFFSET + HEADER_TABLE_LEN { + return None; + } + let mut info = [0u32; 8]; + primitives::decrypt_data1(input, &mut info); + Some(std::array::from_fn(|index| { + let raw = primitives::get_u32(input, (HEADER_TABLE_OFFSET + index * 4) as u32); + Word { + raw, + decoded: info[index], + } + })) +} + +fn header_semantic(index: usize) -> Option { + match index { + 0 => Some(HeaderWordSemantic::Key), + 1 => Some(HeaderWordSemantic::Magic), + 3 => Some(HeaderWordSemantic::DestinationRva), + 4 => Some(HeaderWordSemantic::PayloadSource), + 5 => Some(HeaderWordSemantic::TotalLength), + 6 => Some(HeaderWordSemantic::EndMarker), + // info[2] and info[7] are not used semantically by the pipeline. + _ => None, + } +} + +fn declared_payload(input: &[u8], info: &[u32; 8]) -> Option { + // Read SizeOfImage from the parsed PE, never from a raw e_lfanew: a + // crafted offset must not drive a read here. + let headers = senbei_pe::parse(input).ok()?; + let size_of_image = headers.size_of_image; + let destination = info[3]; + let total = info[5]; + let prefix_word = info[6].wrapping_sub(info[3]); + let prefix_length = prefix_word as u64 + 0x2000; + let source = info[4] as u64 + 0x1000; + let mut checks = Vec::new(); + checks.push(payload_check( + "declared_prefix", + destination as u64, + prefix_length, + size_of_image as u64, + )); + checks.push(payload_check( + "source_prefix", + source, + prefix_length, + input.len() as u64, + )); + checks.push(payload_check( + "declared_payload", + destination as u64, + total as u64, + size_of_image as u64, + )); + let raw_tail_start = source.saturating_add(prefix_length); + let remaining = u64::from(total).saturating_sub(prefix_length); + checks.push(payload_check( + "source_raw_tail", + raw_tail_start, + remaining, + input.len() as u64, + )); + Some(DeclaredPayload { + source_file_offset: source, + destination_rva: destination, + prefix_length, + total_length: total as u64, + size_of_image: size_of_image as u64, + checks, + }) +} + +fn payload_check(name: &'static str, start: u64, length: u64, limit: u64) -> PayloadCheck { + let overflow = start.checked_add(length).is_none(); + let end = start.saturating_add(length); + PayloadCheck { + name, + start, + length, + end, + limit, + in_bounds: !overflow && end <= limit, + overflow, + } +} + +// --------------------------------------------------------------------------- +// Bounded prefix probe +// --------------------------------------------------------------------------- + +/// Decode the declared payload prefix into scratch (never `SizeOfImage`) and +/// report the first words. Larger values (stage tables) need the rest of the +/// pipeline, so a successful decode here is reported as `Decoded`, not as +/// recovery. +/// Decode the declared payload prefix once into scratch (never `SizeOfImage`) +/// and report the first words. The scratch is returned privately so discovery +/// can reuse it instead of decoding a second time; it is never part of the +/// public report. +/// +/// The budget counts the whole allocation (prefix plus the raw tail actually +/// present in the input), and the required source end is the prefix end or the +/// real tail end, whichever the input can actually supply. +fn decode_prefix_probe( + input: &[u8], + info: &[u32; 8], + payload: Option<&DeclaredPayload>, + limits: &InspectionLimits, + issues: &mut IssueList, +) -> (PrefixProbe, Option>) { + let limit_bytes = limits.prefix_scratch_bytes; + let unavailable = |requested_length: u64, reason: &'static str| { + ( + PrefixProbe { + status: ProbeOutcome::Unavailable, + requested_length, + decoded_length: 0, + prefix_bytes: requested_length, + tail_bytes: 0, + limit_bytes, + first_words: Vec::new(), + reason: Some(reason), + }, + None, + ) + }; + let Some(payload) = payload else { + return unavailable(0, "declared payload words could not be read"); + }; + if !info_header_plausible(info) { + return unavailable(0, "header words are not a coherent payload descriptor"); + } + let prefix = payload.prefix_length; + let source = payload.source_file_offset; + let Some(prefix_end) = source.checked_add(prefix) else { + return unavailable(prefix, "payload descriptor overflows a file offset"); + }; + if prefix_end > input.len() as u64 { + return unavailable(prefix, "input does not contain the declared payload prefix"); + } + // Raw tail: whatever real payload bytes follow the prefix and are inside + // the input. A file that ends exactly at the prefix is valid. + let tail = payload + .total_length + .saturating_sub(prefix) + .min((input.len() as u64).saturating_sub(prefix_end)); + let allocation = prefix.saturating_add(tail); + if prefix > limit_bytes || allocation > limit_bytes { + issues.push( + InspectionSeverity::Info, + "probe", + format!( + "prefix probe needs 0x{allocation:X} bytes (prefix 0x{prefix:X}, tail 0x{tail:X}), above the 0x{limit_bytes:X} scratch cap" + ), + ); + return ( + PrefixProbe { + status: ProbeOutcome::BudgetLimited, + requested_length: allocation, + decoded_length: 0, + prefix_bytes: prefix, + tail_bytes: tail, + limit_bytes, + first_words: Vec::new(), + reason: Some("declared prefix plus tail exceeds the scratch budget"), + }, + None, + ); + } + if !prefix.is_multiple_of(4) { + return unavailable(prefix, "declared prefix length is not word-aligned"); + } + let Ok(prefix_len) = usize::try_from(prefix) else { + return unavailable(prefix, "declared prefix length is too large"); + }; + let Ok(tail_len) = usize::try_from(tail) else { + return unavailable(prefix, "declared raw tail is too large"); + }; + let Ok(source_u32) = u32::try_from(source) else { + return unavailable(prefix, "payload source is outside the 32-bit address space"); + }; + let mut scratch = vec![0u8; prefix_len + tail_len]; + primitives::decode_payload_prefix( + input, + source_u32, + &mut scratch, + 0, + info[0], + u32::try_from(prefix).expect("prefix was checked against a 2 MiB cap"), + ); + if tail_len > 0 { + let start = usize::try_from(prefix_end).expect("prefix end fits usize"); + scratch[prefix_len..prefix_len + tail_len].copy_from_slice(&input[start..start + tail_len]); + } + let first_words = (0..4.min(scratch.len() / 4)) + .map(|index| primitives::get_u32(&scratch, (index * 4) as u32)) + .collect(); + issues.push( + InspectionSeverity::Info, + "probe", + "prefix decoded in scratch; later stages still require a full recovery", + ); + ( + PrefixProbe { + status: ProbeOutcome::Decoded, + requested_length: allocation, + decoded_length: allocation, + prefix_bytes: prefix, + tail_bytes: tail, + limit_bytes, + first_words, + reason: Some("bounded prefix only; not a recovered image"), + }, + Some(scratch), + ) +} + +fn info_header_plausible(info: &[u32; 8]) -> bool { + let end = info[6]; + let base = info[3]; + let total = info[5]; + end > base + && total > end.wrapping_sub(base) + && total as u64 <= senbei_crypto::MAX_IMAGE_SIZE + && base != 0 +} + +// --------------------------------------------------------------------------- +// Bounded shell discovery +// --------------------------------------------------------------------------- + +fn discover_shell( + input: &[u8], + payload: Option<&DeclaredPayload>, + probe: &PrefixProbe, + scratch: Option<&[u8]>, + limits: &InspectionLimits, +) -> DiscoveryReport { + if probe.status != ProbeOutcome::Decoded { + return DiscoveryReport { + status: match probe.status { + ProbeOutcome::Unavailable => ProbeOutcome::Unavailable, + ProbeOutcome::BudgetLimited => ProbeOutcome::BudgetLimited, + _ => ProbeOutcome::Unavailable, + }, + candidates: Vec::new(), + positions_scanned: 0, + reason: Some("shell discovery needs a decoded payload prefix"), + }; + } + let (Some(info), Some(payload), Some(scratch)) = (header_info(input), payload, scratch) else { + return DiscoveryReport { + status: ProbeOutcome::Unavailable, + candidates: Vec::new(), + positions_scanned: 0, + reason: Some("protection header or decoded prefix is unavailable"), + }; + }; + // Use the PE format the parser accepted rather than re-reading e_lfanew; + // a crafted e_lfanew must not select a discovery path here. + let Some(pe) = senbei_pe::parse(input).ok() else { + return DiscoveryReport { + status: ProbeOutcome::Unavailable, + candidates: Vec::new(), + positions_scanned: 0, + reason: Some("PE headers did not parse"), + }; + }; + if pe.is_pe32_plus { + discover_pe32_plus_anchor(info, payload, scratch, limits) + } else { + discover_pe32_table(info, payload, scratch, limits) + } +} + +fn header_info(input: &[u8]) -> Option<[u32; 8]> { + if input.len() < HEADER_TABLE_OFFSET + HEADER_TABLE_LEN { + return None; + } + let mut info = [0u32; 8]; + primitives::decrypt_data1(input, &mut info); + Some(info) +} + +/// PE32 shell table discovery, run against the decoded scratch with +/// `info[3]` as the buffer origin. +/// +/// `find_tbl_pe32_candidates_at` takes the origin explicitly, so `info[3]` and +/// `info[6]` stay absolute and only the in-buffer bounds check shifts. A +/// candidate at scratch offset `candidate` is working-image RVA +/// `info[3] + candidate` and protected-file offset +/// `info[4] + 0x1000 + candidate`. +fn discover_pe32_table( + info: [u32; 8], + payload: &DeclaredPayload, + scratch: &[u8], + limits: &InspectionLimits, +) -> DiscoveryReport { + let base = info[3]; + // The declared working image may be larger than the decoded prefix. Pass + // its size so a candidate whose fields validate against the declared image + // is still reported; its stage bytes are then known to be undecoded. + let window_len = payload.size_of_image.saturating_sub(base as u64); + // The locator owns the scan loop, so it reports the real number of word + // positions examined; that count is scan effort, not a candidate count. + let (candidates, positions_scanned) = + layout::find_tbl_pe32_candidates_counted(scratch, &info, base, window_len); + let mut out = Vec::new(); + let mut budget_limited = false; + for candidate in candidates { + if out.len() >= limits.max_candidates { + budget_limited = true; + break; + } + let u = candidate as usize; + let Some(table) = scratch.get(u..u + 0xD0) else { + continue; + }; + let compact = primitives::get_u32(table, 0x78) == info[6]; + let (header_field, stage_field) = if compact { + (0x50u32, 0x88u32) + } else { + (0x58, 0x98) + }; + let header = primitives::get_u32(table, header_field); + let header_size = primitives::get_u32(table, header_field + 4); + let stage_descriptor = primitives::get_u32(table, stage_field); + let stage_descriptor_size = primitives::get_u32(table, stage_field + 4); + let checksum_start = primitives::get_u32(table, stage_field + 0x10); + let checksum_size = primitives::get_u32(table, stage_field + 0x14); + let mut fields = vec![ + CandidateField { + name: "compact_layout", + value: u32::from(compact), + space: None, + }, + CandidateField { + name: "header_start", + value: header, + space: Some(AddressSpace::WorkingImageRva), + }, + CandidateField { + name: "header_size", + value: header_size, + space: None, + }, + CandidateField { + name: "stage_descriptor_start", + value: stage_descriptor, + space: Some(AddressSpace::WorkingImageRva), + }, + CandidateField { + name: "stage_descriptor_size", + value: stage_descriptor_size, + space: None, + }, + CandidateField { + name: "checksum_start", + value: checksum_start, + space: Some(AddressSpace::WorkingImageRva), + }, + CandidateField { + name: "checksum_size", + value: checksum_size, + space: None, + }, + CandidateField { + name: "second_stage_key", + value: primitives::get_u32(table, 0x40), + space: None, + }, + ]; + // The descriptor stores an absolute working-image RVA; the scratch + // starts at `info[3]`, so subtract the base before the bounds check. + let stage_in_scratch = stage_descriptor + .checked_sub(info[3]) + .and_then(|relative| (relative as usize).checked_add(4)) + .is_some_and(|end| end <= scratch.len()); + if !stage_in_scratch { + fields.push(CandidateField { + name: "stage_beyond_prefix", + value: 1, + space: None, + }); + } + let source_offset = payload.source_file_offset.saturating_add(candidate as u64); + let status = if header > 0 + && header_size > 0 + && header + .checked_add(header_size) + .is_some_and(|end| end <= 0x1000) + && checksum_size >= 4 + { + CandidateStatus::StructuralCandidate + } else { + CandidateStatus::Rejected + }; + let reason = match (status, stage_in_scratch) { + (CandidateStatus::StructuralCandidate, true) => { + "shell table shape matches the declared image; second-stage decryption requires recovery" + } + (CandidateStatus::StructuralCandidate, false) => { + "shell table fields match the declared image; stage bytes are beyond the bounded prefix" + } + _ => "shell table shape does not satisfy the header/stage ranges", + }; + out.push(ShellCandidate { + kind: ShellCandidateKind::Pe32ShellTable, + status, + payload_offset: Some(candidate as u64), + image_rva: Some(base.wrapping_add(candidate)), + source_file_offset: Some(source_offset), + fields, + reason, + }); + } + let status = if budget_limited { + ProbeOutcome::BudgetLimited + } else if out.is_empty() { + ProbeOutcome::Failed + } else { + ProbeOutcome::Decoded + }; + let reason = match status { + ProbeOutcome::Decoded => "candidates reported without stage validation", + ProbeOutcome::Failed => "no shell table shape in the decoded payload window", + ProbeOutcome::BudgetLimited => "candidate list reached the configured cap", + ProbeOutcome::Unavailable => "shell discovery unavailable", + }; + DiscoveryReport { + status, + candidates: out, + positions_scanned, + reason: Some(reason), + } +} + +/// PE32+ anchor discovery: scan `info[6]+0x1000 .. info[6]+0x8000` for the +/// anchor field (dword == `info[3]`, followed by a near, 0x200-aligned value +/// below `info[6]`), and report the anchor-relative stage1 descriptor when it +/// validates. Uses the same rebased scratch as the PE32 probe. +fn discover_pe32_plus_anchor( + info: [u32; 8], + payload: &DeclaredPayload, + scratch: &[u8], + _limits: &InspectionLimits, +) -> DiscoveryReport { + let base = info[3]; + let rebased_info6 = info[6].wrapping_sub(base); + let mut probe = rebased_info6.wrapping_add(0x1000); + let probe_end = rebased_info6.wrapping_add(0x8000); + let mut anchor = None; + let mut positions_scanned = 0u32; + while probe + 12 <= probe_end && (probe as usize + 12) <= scratch.len() { + positions_scanned = positions_scanned.saturating_add(1); + if primitives::get_u32(scratch, probe) == base { + // The scratch starts at `info[3]`, but the layout stores absolute + // RVAs, so the nearby end marker is compared after adding the base + // back. `probe` itself is a scratch offset; the report adds the + // base when it names an image RVA. + let v8 = primitives::get_u32(scratch, probe + 8); + if v8 >= base { + let delta = info[6].wrapping_sub(v8); + if v8 < info[6] && delta <= 0x1000 && delta.is_multiple_of(0x200) { + anchor = Some(probe); + break; + } + } + } + probe = probe.wrapping_add(4); + } + let Some(anchor) = anchor else { + return DiscoveryReport { + status: ProbeOutcome::Failed, + candidates: Vec::new(), + positions_scanned, + reason: Some("no anchor field in the decoded payload window"), + }; + }; + let descriptor = [0u32, 8].into_iter().find_map(|extra| { + let pos = anchor.wrapping_add(120 + extra); + let end = (pos as usize).checked_add(8)?; + if end > scratch.len() { + return None; + } + let start = primitives::get_u32(scratch, pos); + let length = primitives::get_u32(scratch, pos + 4); + // Descriptor values are absolute RVAs; the scratch starts at `info[3]`, + // so the in-probe bounds check subtracts the base. + let start_rel = start.checked_sub(base)?; + let valid = length >= 16 + && (start_rel as usize) + .checked_add(length as usize) + .is_some_and(|end| end <= scratch.len()); + valid.then_some((extra, start, length)) + }); + let mut fields = vec![CandidateField { + name: "anchor_payload_offset", + value: anchor, + space: Some(AddressSpace::DecodedPayloadOffset), + }]; + if let Some((extra, start, length)) = descriptor { + fields.push(CandidateField { + name: "stage1_layout_extra", + value: extra, + space: None, + }); + fields.push(CandidateField { + name: "stage1_start", + value: start, + space: Some(AddressSpace::WorkingImageRva), + }); + fields.push(CandidateField { + name: "stage1_length", + value: length, + space: None, + }); + } + let status = if descriptor.is_some() { + CandidateStatus::StructuralCandidate + } else { + CandidateStatus::Observed + }; + let source_offset = payload.source_file_offset.saturating_add(anchor as u64); + DiscoveryReport { + status: ProbeOutcome::Decoded, + candidates: vec![ShellCandidate { + kind: ShellCandidateKind::Pe32PlusAnchor, + status, + payload_offset: Some(anchor as u64), + image_rva: Some(base.wrapping_add(anchor)), + source_file_offset: Some(source_offset), + fields, + reason: if descriptor.is_some() { + "anchor and stage1 descriptor validate; full stage decryption requires recovery" + } else { + "anchor field found; stage1 descriptor needs recovery to validate" + }, + }], + positions_scanned, + reason: Some("bounded anchor probe only"), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + const PE_OFF: usize = 0x80; + const OPT_SIZE: usize = 0xE0; + const SECTION_TABLE: usize = PE_OFF + 24 + OPT_SIZE; + const SIZE_OF_IMAGE: u32 = 0x40_4000; + + /// Minimal PE32 with `sections` entries, no protection table. Everything + /// after the header is caller-controlled. + fn pe32(file_len: usize, sections: &[(&str, u32, u32, u32, u32, u32)]) -> Vec { + let mut data = vec![0u8; file_len]; + let needed = SECTION_TABLE + sections.len() * 40; + if data.len() < needed { + data.resize(needed, 0); + } + data[..2].copy_from_slice(b"MZ"); + data[0x3C..0x40].copy_from_slice(&(PE_OFF as u32).to_le_bytes()); + data[PE_OFF..PE_OFF + 4].copy_from_slice(b"PE\0\0"); + data[PE_OFF + 4..PE_OFF + 6].copy_from_slice(&0x14C_u16.to_le_bytes()); + data[PE_OFF + 6..PE_OFF + 8].copy_from_slice(&(sections.len() as u16).to_le_bytes()); + data[PE_OFF + 20..PE_OFF + 22].copy_from_slice(&(OPT_SIZE as u16).to_le_bytes()); + data[PE_OFF + 22..PE_OFF + 24].copy_from_slice(&0x0102_u16.to_le_bytes()); + let opt = PE_OFF + 24; + data[opt..opt + 2].copy_from_slice(&0x10B_u16.to_le_bytes()); + data[opt + 16..opt + 20].copy_from_slice(&0x1000_u32.to_le_bytes()); + data[opt + 28..opt + 32].copy_from_slice(&0x400000_u32.to_le_bytes()); + data[opt + 32..opt + 36].copy_from_slice(&0x1000_u32.to_le_bytes()); + data[opt + 36..opt + 40].copy_from_slice(&0x200_u32.to_le_bytes()); + data[opt + 56..opt + 60].copy_from_slice(&SIZE_OF_IMAGE.to_le_bytes()); + data[opt + 60..opt + 64].copy_from_slice(&0x400_u32.to_le_bytes()); + data[opt + 70..opt + 72].copy_from_slice(&0_u16.to_le_bytes()); + data[opt + 92..opt + 96].copy_from_slice(&16_u32.to_le_bytes()); + for (index, (name, vsize, va, raw_size, raw_off, characteristics)) in + sections.iter().enumerate() + { + let at = SECTION_TABLE + index * 40; + let field = name.as_bytes(); + let take = field.len().min(8); + data[at..at + take].copy_from_slice(&field[..take]); + data[at + 8..at + 12].copy_from_slice(&vsize.to_le_bytes()); + data[at + 12..at + 16].copy_from_slice(&va.to_le_bytes()); + data[at + 16..at + 20].copy_from_slice(&raw_size.to_le_bytes()); + data[at + 20..at + 24].copy_from_slice(&raw_off.to_le_bytes()); + data[at + 36..at + 40].copy_from_slice(&characteristics.to_le_bytes()); + } + data + } + + fn sample_sections() -> [(&'static str, u32, u32, u32, u32, u32); 1] { + [(".text", 0x1000, 0x1000, 0x200, 0x400, 0x6000_0020)] + } + + #[test] + fn pe_reports_headers_sections_and_entry_backing() { + let data = pe32(0x800, &sample_sections()); + let out = inspect(&data, &InspectionLimits::default()); + let pe = out.pe.expect("PE must parse"); + assert_eq!(pe.machine, Some(0x14C)); + assert_eq!(pe.format, Some(TargetFormat::Pe32)); + assert_eq!(pe.kind, Some(Kind::NativeExe)); + assert_eq!(pe.image_base, Some(0x40_0000)); + assert_eq!(pe.entry_point_rva, Some(0x1000)); + assert_eq!(pe.entry_point_file_offset, Some(0x400)); + assert_eq!(pe.entry_point_available, Some(true)); + assert_eq!(pe.size_of_image, Some(SIZE_OF_IMAGE)); + assert_eq!(pe.size_of_headers, Some(0x400)); + assert_eq!(pe.section_alignment, Some(0x1000)); + assert_eq!(pe.file_alignment, Some(0x200)); + assert_eq!(pe.sections.len(), 1); + let text = &pe.sections[0]; + assert_eq!(text.name, ".text"); + assert_eq!(text.virtual_address, 0x1000); + assert_eq!(text.raw_offset, 0x400); + assert_eq!(text.raw_end, 0x600); + assert!(text.raw_in_bounds); + assert_eq!(text.backing, SectionBacking::FileBacked); + assert_eq!(text.characteristics, 0x6000_0020); + assert!(text.permissions.read && text.permissions.execute && text.permissions.code); + assert!(!text.permissions.write); + assert_eq!( + pe.named_flags + .iter() + .map(|flag| flag.name) + .collect::>(), + ["executable_image", "debug_stripped"] + ); + assert!( + pe.directories + .iter() + .all(|dir| dir.mapping == DirectoryMapping::Zero) + ); + } + + #[test] + fn directory_mappings_report_real_backing() { + let mut data = pe32(0x1000, &sample_sections()); + let opt = PE_OFF + 24; + let dd = opt + 96; + // Certificate table (index 4) is a file offset outside any section. + data[dd + 4 * 8..dd + 4 * 8 + 4].copy_from_slice(&0x900u32.to_le_bytes()); + data[dd + 4 * 8 + 4..dd + 4 * 8 + 8].copy_from_slice(&0x40u32.to_le_bytes()); + // Import (index 1) inside the declared header area but past the + // section table end (0x400 headers are declared). + data[dd + 8..dd + 12].copy_from_slice(&0x300u32.to_le_bytes()); + data[dd + 12..dd + 16].copy_from_slice(&0x20u32.to_le_bytes()); + let pe = inspect(&data, &InspectionLimits::default()).pe.unwrap(); + let cert = &pe.directories[4]; + assert_eq!(cert.address_space, AddressSpace::FileOffset); + assert_eq!(cert.mapping, DirectoryMapping::FileBacked); + assert_eq!(cert.file_offset, Some(0x900)); + let import = &pe.directories[1]; + assert_eq!(import.mapping, DirectoryMapping::HeaderBacked); + assert_eq!(import.file_offset, Some(0x300)); + } + + #[test] + fn raw_section_overlapping_headers_is_reported() { + // Declared headers end at 0x400; a section raw range starting at + // 0x300 overlaps them. + let sections = [(".data", 0x1000, 0x1000, 0x200, 0x300, 0xC000_0040)]; + let data = pe32(0x800, §ions); + let pe = inspect(&data, &InspectionLimits::default()).pe.unwrap(); + assert!( + pe.sections[0] + .anomalies + .iter() + .any(|anomaly| anomaly.kind == SectionAnomalyKind::RawOverlapsHeaders) + ); + } + + #[test] + fn raw_section_characteristics_survive_the_permission_view() { + // 0x0200_0040 = MEM_DISCARDABLE | CNT_INITIALIZED_DATA, neither of + // which the permission booleans represent. + let sections = [(".data", 0x1000, 0x1000, 0x200, 0x400, 0x0200_0040)]; + let data = pe32(0x800, §ions); + let pe = inspect(&data, &InspectionLimits::default()).pe.unwrap(); + assert_eq!(pe.sections[0].characteristics, 0x0200_0040); + assert!(pe.sections[0].permissions.initialized_data); + assert!(!pe.sections[0].permissions.execute); + } + + #[test] + fn named_dll_flags_are_declarations() { + let mut data = pe32(0x800, &sample_sections()); + let opt = PE_OFF + 24; + data[opt + 70..opt + 72].copy_from_slice(&0x0140_u16.to_le_bytes()); + let out = inspect(&data, &InspectionLimits::default()); + let pe = out.pe.unwrap(); + let flags: Vec<&str> = pe.named_flags.iter().map(|flag| flag.name).collect(); + assert!(flags.contains(&"dynamic_base_aslr_declared")); + assert!(flags.contains(&"nx_compat_declared")); + assert_eq!(pe.dll_characteristics, Some(0x0140)); + } + + #[test] + fn positions_scanned_is_real_scan_effort_not_a_candidate_count() { + // PE32: the locator scans a bounded 4-byte-stepped window, so the count + // is in the thousands even though only two candidates exist. + let data = protected(0x3000, 0x4000); + let protection = inspect(&data, &InspectionLimits::default()) + .protection + .unwrap(); + let positions = protection.discovery.positions_scanned; + assert!(positions > 8, "PE32 scan positions = {positions}"); + assert!( + positions as usize >= protection.discovery.candidates.len(), + "scan effort cannot be below the reported candidates" + ); + + // PE32+: the same field counts anchor-scan dwords. + let prefix = 0x3000usize; + let mut plain = vec![0u8; prefix]; + let anchor = 0x2100usize; + primitives::write_u32(&mut plain, anchor as u32, 0x20_0000); + primitives::write_u32(&mut plain, anchor as u32 + 8, 0x20_0C00); + primitives::write_u32(&mut plain, (anchor + 120) as u32, 0x20_2000); + primitives::write_u32(&mut plain, (anchor + 124) as u32, 0x40); + let data = protected_pe64(prefix, &plain); + let protection = inspect(&data, &InspectionLimits::default()) + .protection + .unwrap(); + // Scan starts at (info[6]-info[3])+0x1000 = 0x2000; the anchor at 0x2100 + // is the 65th word examined (0x100/4 + 1), and the loop stops there. + assert_eq!(protection.discovery.positions_scanned, 0x41); + assert_eq!(protection.discovery.candidates.len(), 1); + } + + #[test] + fn declared_section_count_is_capped_before_pairwise_work() { + // 65535 sections all claiming the same virtual and raw range: the + // uncapped pairwise sweep would do ~2.1e9 comparisons. The cap must + // apply before any pair processing. + let count = u16::MAX; + let mut data = pe32(0x400, &[]); + data[PE_OFF + 6..PE_OFF + 8].copy_from_slice(&count.to_le_bytes()); + let table = SECTION_TABLE; + let needed = table + count as usize * 40; + data.resize(needed, 0); + for index in 0..count as usize { + let at = table + index * 40; + data[at..at + 5].copy_from_slice(b".text"); + data[at + 8..at + 12].copy_from_slice(&0x1000u32.to_le_bytes()); + data[at + 12..at + 16].copy_from_slice(&0x1000u32.to_le_bytes()); + data[at + 16..at + 20].copy_from_slice(&0x1000u32.to_le_bytes()); + data[at + 20..at + 24].copy_from_slice(&0x400u32.to_le_bytes()); + data[at + 36..at + 40].copy_from_slice(&0x6000_0020u32.to_le_bytes()); + } + let out = inspect(&data, &InspectionLimits::default()); + let pe = out.pe.expect("headers parse"); + assert_eq!(pe.sections.len(), MAX_SECTIONS as usize); + assert!( + out.issues + .iter() + .any(|issue| issue.message.contains("sections declared")), + "truncation must be stated, not silent" + ); + } + + #[test] + fn section_anomalies_name_real_problems() { + let mut data = pe32(0x600, &sample_sections()); + // Entry point lies in the zero-filled tail (raw size is 0x200). + let opt = PE_OFF + 24; + data[opt + 16..opt + 20].copy_from_slice(&0x1200_u32.to_le_bytes()); + let out = inspect(&data, &InspectionLimits::default()); + let pe = out.pe.unwrap(); + let text = &pe.sections[0]; + assert_eq!(text.backing, SectionBacking::FileBacked); + assert_eq!(pe.entry_point_file_offset, None); + assert_eq!(pe.entry_point_available, Some(false)); + assert!( + text.anomalies + .iter() + .any(|anomaly| anomaly.kind == SectionAnomalyKind::EntryPointInside) + ); + } + + #[test] + fn raw_past_eof_is_reported_not_hidden() { + let sections = [(".text", 0x3000, 0x1000, 0x3000, 0x400, 0x6000_0020)]; + let data = pe32(0x600, §ions); + let pe = inspect(&data, &InspectionLimits::default()).pe.unwrap(); + let text = &pe.sections[0]; + assert!(!text.raw_in_bounds); + assert_eq!(text.raw_end, 0x3400); + assert_eq!( + text.backing, + SectionBacking::RawTruncated { available: 0x200 } + ); + assert!( + text.anomalies + .iter() + .any(|anomaly| anomaly.kind == SectionAnomalyKind::RawPastEof) + ); + } + + #[test] + fn unsectioned_ranges_cover_header_gap_gap_and_overlay() { + let sections = [ + (".text", 0x1000, 0x1000, 0x200, 0x400, 0x6000_0020), + (".data", 0x1000, 0x2000, 0x200, 0x700, 0xC000_0040), + ]; + let data = pe32(0xA00, §ions); + let pe = inspect(&data, &InspectionLimits::default()).pe.unwrap(); + let section_table_end = (SECTION_TABLE + 2 * 40) as u64; + assert_eq!(SECTION_TABLE, 0x178); + assert_eq!( + pe.unsectioned, + vec![ + FileRegion { + offset: section_table_end, + length: 0x400 - section_table_end, + kind: FileRegionKind::HeadersToFirstSection + }, + FileRegion { + offset: 0x600, + length: 0x100, + kind: FileRegionKind::BetweenSections + } + ] + ); + // .text raw is [0x400,0x600), .data raw is [0x700,0x900): a gap. + assert!(pe.unsectioned.iter().any(|region| { + region.kind == FileRegionKind::BetweenSections + && region.offset == 0x600 + && region.length == 0x100 + })); + assert_eq!( + pe.overlay, + Some(FileRegion { + offset: 0x900, + length: 0x100, + kind: FileRegionKind::Overlay + }) + ); + } + + #[test] + fn trailing_overlay_is_separate_from_interior_gaps() { + let sections = [(".text", 0x1000, 0x1000, 0x200, 0x400, 0x6000_0020)]; + let data = pe32(0xA00, §ions); + let pe = inspect(&data, &InspectionLimits::default()).pe.unwrap(); + assert_eq!( + pe.overlay, + Some(FileRegion { + offset: 0x600, + length: 0x400, + kind: FileRegionKind::Overlay + }) + ); + assert!(pe.unsectioned.iter().all(|region| region.offset != 0x600)); + } + + #[test] + fn truncated_section_table_keeps_partial_pe_findings() { + let mut data = pe32(0x800, &sample_sections()); + // Cut inside the section table: the optional header still parses, but + // the full 40-byte entry does not. + data.truncate(SECTION_TABLE + 8); + let out = inspect(&data, &InspectionLimits::default()); + assert!(out.pe.is_none()); + assert!(out.protection.is_none()); + assert!( + out.issues + .iter() + .any(|issue| issue.area == "pe" && issue.severity == InspectionSeverity::Warning) + ); + } + + #[test] + fn unrecognized_magic_reports_words_but_runs_no_probe() { + let mut data = protected(0x3000, 0x4000); + let mut info = [0u32; 8]; + primitives::decrypt_data1(&data, &mut info); + // Coherent payload descriptor, but the magic is not supported. + info[1] = 0x4E4E_4F4B ^ 0x0101_0101; + let mut key = info[0]; + primitives::write_u32(&mut data, 0x1000, key); + for i in 0..7u32 { + let cell = info[(i + 1) as usize] ^ key; + primitives::write_u32(&mut data, 0x1004 + i * 4, cell); + key = i.wrapping_mul(i) ^ (key.wrapping_add(cell).wrapping_sub(i)); + } + let protection = inspect(&data, &InspectionLimits::default()) + .protection + .expect("words still reported"); + assert!(!protection.magic_recognized); + assert_eq!(protection.header_words.len(), 8); + assert_eq!(protection.probe.status, ProbeOutcome::Unavailable); + assert!(protection.discovery.candidates.is_empty()); + assert_eq!(protection.discovery.status, ProbeOutcome::Unavailable); + } + + #[test] + fn malformed_large_pe_offset_with_coherent_header_does_not_panic() { + let mut data = protected(0x3000, 0x4000); + // e_lfanew far past the file while the protection table stays valid. + data[0x3C..0x40].copy_from_slice(&u32::MAX.to_le_bytes()); + let out = inspect(&data, &InspectionLimits::default()); + assert!(out.pe.is_none()); + let protection = out.protection.expect("header table is independent of PE"); + assert_eq!(protection.payload, None); + assert_eq!(protection.probe.status, ProbeOutcome::Unavailable); + assert_eq!(protection.discovery.status, ProbeOutcome::Unavailable); + + // A crafted PE offset that still points at bytes shaped like a PE must + // not drive discovery either. + let mut data = protected(0x3000, 0x4000); + let crafted = data.len() as u32 - 0x20; + data[0x3C..0x40].copy_from_slice(&crafted.to_le_bytes()); + data[crafted as usize..crafted as usize + 4].copy_from_slice(b"PE\0\0"); + let out = inspect(&data, &InspectionLimits::default()); + assert!(out.pe.is_none()); + assert_eq!( + out.protection.unwrap().probe.status, + ProbeOutcome::Unavailable + ); + } + + #[test] + fn payload_ending_exactly_at_eof_still_decodes() { + let prefix = 0x3000usize; + let source = 0x1100usize; + let file_len = source + prefix; + let mut data = pe32(file_len, &sample_sections()); + let info = [ + 0x1122_3344u32, + MAGIC_KONN, + 0x196C, + 0x20_0000, + 0x100, + prefix as u32, + 0x20_0000u32 + prefix as u32 - 0x2000, + 0xA0, + ]; + let mut key = info[0]; + primitives::write_u32(&mut data, 0x1000, key); + for i in 0..7u32 { + let cell = info[(i + 1) as usize] ^ key; + primitives::write_u32(&mut data, 0x1004 + i * 4, cell); + key = i.wrapping_mul(i) ^ (key.wrapping_add(cell).wrapping_sub(i)); + } + let protection = inspect(&data, &InspectionLimits::default()) + .protection + .unwrap(); + assert_eq!(protection.probe.status, ProbeOutcome::Decoded); + // The fixture declares total == prefix and ends at EOF, so there is no + // raw tail: the scratch span is the decoded prefix itself. + assert_eq!(protection.probe.prefix_bytes, prefix as u64); + assert_eq!(protection.probe.tail_bytes, 0); + assert_eq!(protection.probe.decoded_length, prefix as u64); + assert_eq!(protection.probe.requested_length, prefix as u64); + } + + #[test] + fn garbage_input_returns_an_explained_empty_result() { + for data in [&b""[..], b"MZ", &[0xAAu8; 64][..]] { + let out = inspect(data, &InspectionLimits::default()); + assert_eq!(out.input_len, data.len() as u64); + assert!(out.pe.is_none()); + assert!(out.protection.is_none()); + assert!(!out.issues.is_empty()); + assert_eq!(out.work.prefix_bytes_decoded, 0); + assert!(!out.work.budget_limited); + } + } + + /// PE32 fixture with a valid header table at 0x1000 and a payload the + /// header declares. `prefix_len` is the payload prefix and `total` the + /// declared payload length; the file is sized to hold both, plus a 0x1000 + /// raw tail. Payload bytes are synthetic (not a real loader key), so the + /// prefix decodes to deterministic bytes and no stage structure exists. + fn protected(prefix_len: usize, total: u32) -> Vec { + let source = 0x1100usize; + let file_len = source + prefix_len + 0x1000; + let mut data = pe32(file_len, &sample_sections()); + let info = [ + 0x1122_3344u32, + MAGIC_KONN, + 0x196C, + 0x20_0000, + 0x100, + total, + 0x20_0000u32 + (prefix_len as u32).wrapping_sub(0x2000), + 0xA0, + ]; + for (index, word) in info.into_iter().enumerate() { + primitives::write_u32(&mut data, (0x1000 + index * 4) as u32, word); + } + // Re-encode the header cells the same way `decrypt_data1` reads them. + let mut key = info[0]; + primitives::write_u32(&mut data, 0x1000, key); + for i in 0..7u32 { + let cell = info[(i + 1) as usize] ^ key; + primitives::write_u32(&mut data, 0x1004 + i * 4, cell); + key = i.wrapping_mul(i) ^ (key.wrapping_add(cell).wrapping_sub(i)); + } + // Source of the declared payload: info[4] + 0x1000 = 0x1100. + let source = 0x1100usize; + let fill = prefix_len.min(file_len.saturating_sub(source)); + for i in 0..fill { + data[source + i] = (i % 251) as u8; + } + data + } + + /// PE32+ fixture shaped like `protected`, with a caller-supplied plaintext + /// payload prefix so an anchor/descriptor can be planted. + fn protected_pe64(prefix_len: usize, plain: &[u8]) -> Vec { + let source = 0x1100usize; + let file_len = source + prefix_len + 0x1000; + let mut data = pe32(file_len, &sample_sections()); + let opt = PE_OFF + 24; + // PE32+ optional header: magic + ImageBase (u64) + SizeOfImage. + data[opt..opt + 2].copy_from_slice(&0x20B_u16.to_le_bytes()); + data[opt + 24..opt + 32].copy_from_slice(&0x1_4000_0000_u64.to_le_bytes()); + data[opt + 56..opt + 60].copy_from_slice(&SIZE_OF_IMAGE.to_le_bytes()); + data[opt + 108..opt + 112].copy_from_slice(&16_u32.to_le_bytes()); + let info = [ + 0x1122_3344u32, + MAGIC_KONN, + 0x196C, + 0x20_0000, + 0x100, + prefix_len as u32, + 0x20_0000u32 + (prefix_len as u32).wrapping_sub(0x2000), + 0xA0, + ]; + let mut key = info[0]; + primitives::write_u32(&mut data, 0x1000, key); + for i in 0..7u32 { + let cell = info[(i + 1) as usize] ^ key; + primitives::write_u32(&mut data, 0x1004 + i * 4, cell); + key = i.wrapping_mul(i) ^ (key.wrapping_add(cell).wrapping_sub(i)); + } + encode_prefix(&mut data, &info, plain); + data + } + + #[test] + fn pe32_plus_anchor_and_stage1_descriptor_are_reported() { + let prefix = 0x3000usize; + let mut plain = vec![0u8; prefix]; + // The anchor scan starts at info[6]-info[3]+0x1000 = 0x2000. + let anchor = 0x2100usize; + primitives::write_u32(&mut plain, anchor as u32, 0x20_0000); + // `anchor+8` must be an absolute RVA below info[6], with a 0x200-aligned + // distance to it, and must not itself look like an anchor. + primitives::write_u32(&mut plain, anchor as u32 + 8, 0x20_0C00); + // Stage1 descriptor at anchor+120: (start, length), in image. + primitives::write_u32(&mut plain, (anchor + 120) as u32, 0x20_2000); + primitives::write_u32(&mut plain, (anchor + 124) as u32, 0x40); + let data = protected_pe64(prefix, &plain); + let out = inspect(&data, &InspectionLimits::default()); + let pe = out.pe.expect("PE32+ parses"); + assert_eq!(pe.format, Some(TargetFormat::Pe32Plus)); + let protection = out.protection.unwrap(); + assert_eq!(protection.probe.status, ProbeOutcome::Decoded); + let candidate = protection + .discovery + .candidates + .iter() + .find(|candidate| candidate.kind == ShellCandidateKind::Pe32PlusAnchor) + .expect("anchor candidate"); + assert_eq!(candidate.payload_offset, Some(anchor as u64)); + assert_eq!(candidate.image_rva, Some(0x20_0000 + anchor as u32)); + assert_eq!(candidate.status, CandidateStatus::StructuralCandidate); + let field = |name: &str| { + candidate + .fields + .iter() + .find(|field| field.name == name) + .unwrap_or_else(|| panic!("missing {name}")) + }; + assert_eq!(field("stage1_start").value, 0x20_2000); + assert_eq!(field("stage1_length").value, 0x40); + assert_eq!( + field("stage1_start").space, + Some(AddressSpace::WorkingImageRva) + ); + } + + #[test] + fn header_words_decode_with_source_offsets_and_verified_semantics() { + let data = protected(0x3000, 0x4000); + let protection = inspect(&data, &InspectionLimits::default()) + .protection + .expect("table present"); + assert!(protection.magic_recognized); + assert_eq!(protection.magic, Some(MAGIC_KONN)); + assert_eq!(protection.header_words.len(), 8); + let words: Vec = protection + .header_words + .iter() + .map(|word| word.decoded_word) + .collect(); + assert_eq!( + words, + vec![ + 0x1122_3344, + MAGIC_KONN, + 0x196C, + 0x20_0000, + 0x100, + 0x4000, + 0x20_0000 + 0x1000, + 0xA0 + ] + ); + for (index, word) in protection.header_words.iter().enumerate() { + assert_eq!(word.index, index as u8); + assert_eq!(word.source_file_offset, (0x1000 + index * 4) as u64); + } + assert_eq!( + protection.header_words[1].semantic, + Some(HeaderWordSemantic::Magic) + ); + assert_eq!( + protection.header_words[3].semantic, + Some(HeaderWordSemantic::DestinationRva) + ); + assert_eq!( + protection.header_words[4].semantic, + Some(HeaderWordSemantic::PayloadSource) + ); + assert_eq!( + protection.header_words[5].semantic, + Some(HeaderWordSemantic::TotalLength) + ); + assert_eq!( + protection.header_words[6].semantic, + Some(HeaderWordSemantic::EndMarker) + ); + // Not used semantically by the pipeline, so no invented name. + assert_eq!(protection.header_words[2].semantic, None); + assert_eq!(protection.header_words[7].semantic, None); + } + + #[test] + fn declared_payload_checks_use_each_space() { + let data = protected(0x3000, 0x4000); + let protection = inspect(&data, &InspectionLimits::default()) + .protection + .unwrap(); + let payload = protection.payload.expect("payload"); + assert_eq!(payload.source_file_offset, 0x1100); + assert_eq!(payload.destination_rva, 0x20_0000); + assert_eq!(payload.prefix_length, 0x3000); + assert_eq!(payload.total_length, 0x4000); + let names: Vec<&str> = payload.checks.iter().map(|check| check.name).collect(); + assert_eq!( + names, + [ + "declared_prefix", + "source_prefix", + "declared_payload", + "source_raw_tail" + ] + ); + // The fixture is sized to hold the source prefix and raw tail, so + // every declared range is in bounds and the probe decodes it. + assert!(payload.checks.iter().all(|check| check.in_bounds)); + assert_eq!(protection.probe.status, ProbeOutcome::Decoded); + } + + #[test] + fn zero_and_overflow_descriptors_do_not_panic() { + // size_of_image = 0. + let mut data = protected(0x3000, 0x4000); + let opt = PE_OFF + 24; + data[opt + 56..opt + 60].copy_from_slice(&0u32.to_le_bytes()); + let out = inspect(&data, &InspectionLimits::default()); + assert!(out.pe.is_some()); + + // info[6] behind info[3]: the prefix length wraps into a huge value. + let mut data = protected(0x3000, 0x4000); + let mut info = [0u32; 8]; + primitives::decrypt_data1(&data, &mut info); + info[6] = 1; + let mut key = info[0]; + primitives::write_u32(&mut data, 0x1000, key); + for i in 0..7u32 { + let cell = info[(i + 1) as usize] ^ key; + primitives::write_u32(&mut data, 0x1004 + i * 4, cell); + key = i.wrapping_mul(i) ^ (key.wrapping_add(cell).wrapping_sub(i)); + } + let out = inspect(&data, &InspectionLimits::default()); + let protection = out.protection.unwrap(); + assert_eq!(protection.probe.status, ProbeOutcome::Unavailable); + assert!(!out.work.budget_limited); + } + + #[test] + fn prefix_probe_honours_the_scratch_budget() { + let data = protected(0x3000, 0x4000); + let limits = InspectionLimits { + prefix_scratch_bytes: 0x100, + ..InspectionLimits::default() + }; + let out = inspect(&data, &limits); + let protection = out.protection.unwrap(); + assert_eq!(protection.probe.status, ProbeOutcome::BudgetLimited); + assert!(out.work.budget_limited); + assert_eq!(out.work.prefix_bytes_decoded, 0); + } + + #[test] + fn candidate_list_honours_the_candidate_cap() { + let data = protected(0x3000, 0x4000); + let full = inspect(&data, &InspectionLimits::default()); + let limits = InspectionLimits { + max_candidates: 1, + ..InspectionLimits::default() + }; + let capped = inspect(&data, &limits); + if let (Some(full), Some(capped)) = (full.protection, capped.protection) { + assert!(capped.discovery.candidates.len() <= 1); + assert!(capped.discovery.candidates.len() <= full.discovery.candidates.len()); + } + } + + #[test] + fn issue_list_is_bounded() { + let data = vec![0u8; 8]; + let limits = InspectionLimits { + max_issues: 1, + ..InspectionLimits::default() + }; + let out = inspect(&data, &limits); + assert!(out.issues.len() <= 1); + } + + /// Replace the declared payload prefix with an encoded plaintext scratch. + /// `plain` is indexed from `info[3]`; the test-only encoder is the inverse + /// of the prefix recurrence in `decode_payload_scratch`. + fn encode_prefix(data: &mut [u8], info: &[u32; 8], plain: &[u8]) { + let source = info[4] as usize + 0x1000; + let mut key = info[0].wrapping_add(!((plain.len() as u32) & !3)); + let words = (plain.len() / 4) as u32; + for i in 0..words { + let off = (i * 4) as usize; + let word = primitives::get_u32(plain, off as u32); + let cell = word ^ key; + data[source + off..source + off + 4].copy_from_slice(&cell.to_le_bytes()); + key = i.wrapping_mul(i) ^ (key.wrapping_add(cell).wrapping_add(i)); + } + } + + #[test] + fn synthetic_pe32_shell_table_is_a_structural_candidate() { + let mut data = protected(0x3000, 0x4000); + let mut info = [0u32; 8]; + primitives::decrypt_data1(&data, &mut info); + // Standard (non-compact) shell table whose `+0x88` field is the shell + // marker, placed at/after the declared shell start (`info[6]-info[3]`, + // the locator's lower bound for a table candidate). + let shell_start = (info[6] - info[3]) as usize; + let table = shell_start + 0x200; + let marker = table + 0x88; + let mut plain = vec![0u8; 0x3000]; + for (offset, value) in [ + (marker, info[6]), + (marker + 4, 0x1800u32), + (table + 0x58, 0x1E0u32), + (table + 0x5C, 0x40u32), + (table + 0x98, 0x20_2000u32), + (table + 0x9C, 4u32), + (table + 0xA8, 0x20_2000u32), + (table + 0xAC, 0x80u32), + ] { + if offset + 4 <= plain.len() { + primitives::write_u32(&mut plain, offset as u32, value); + } + } + encode_prefix(&mut data, &info, &plain); + let out = inspect(&data, &InspectionLimits::default()); + let protection = out.protection.unwrap(); + assert_eq!(protection.probe.status, ProbeOutcome::Decoded); + let candidate = protection + .discovery + .candidates + .iter() + .find(|candidate| candidate.payload_offset == Some(table as u64)) + .expect("synthetic table must be found"); + assert_eq!(candidate.kind, ShellCandidateKind::Pe32ShellTable); + assert_eq!(candidate.status, CandidateStatus::StructuralCandidate); + assert_eq!(candidate.payload_offset, Some(table as u64)); + assert_eq!(candidate.image_rva, Some(0x20_0000 + table as u32)); + assert_eq!(candidate.source_file_offset, Some(0x1100 + table as u64)); + for (name, value) in [ + ("compact_layout", 0), + ("header_start", 0x1E0), + ("header_size", 0x40), + ("stage_descriptor_start", 0x20_2000), + ("stage_descriptor_size", 4), + ("checksum_start", 0x20_2000), + ("checksum_size", 0x80), + ] { + assert!( + candidate + .fields + .iter() + .any(|field| field.name == name && field.value == value), + "missing {name}=0x{value:X}: {:?}", + candidate.fields + ); + } + let header = candidate + .fields + .iter() + .find(|field| field.name == "header_start") + .unwrap(); + assert_eq!(header.space, Some(AddressSpace::WorkingImageRva)); + let header_size = candidate + .fields + .iter() + .find(|field| field.name == "header_size") + .unwrap(); + assert_eq!(header_size.space, None, "a size is not an address"); + // The descriptor's absolute RVA 0x202000 is offset 0x2000 from the + // payload base 0x200000, inside the 0x3000 decoded prefix. + assert!( + candidate + .fields + .iter() + .all(|field| field.name != "stage_beyond_prefix"), + "stage descriptor is inside the decoded prefix" + ); + assert!( + candidate + .reason + .contains("shape matches the declared image") + ); + } + + #[test] + fn serialized_inspection_is_stable_snake_case() { + let data = pe32(0x800, &sample_sections()); + let out = inspect(&data, &InspectionLimits::default()); + let value = serde_json::to_value(&out).expect("serializes"); + assert_eq!(value["pe"]["format"], "pe32"); + assert_eq!(value["pe"]["kind"], "native_exe"); + assert_eq!(value["pe"]["sections"][0]["backing"], "file_backed"); + assert_eq!( + value["pe"]["named_flags"][0]["field"], + "coff_characteristics" + ); + assert_eq!( + value["work"]["prefix_scratch_limit"], + DEFAULT_PREFIX_SCRATCH_BYTES + ); + assert!(value.get("protection").is_none()); + } + + #[test] + fn inspection_never_selects_or_recovers() { + let data = protection_like(); + let out = inspect(&data, &InspectionLimits::default()); + // No field in the inspection claim recovery: this is a structural + // assertion — the type has no selected/recovery field at all. + let value = serde_json::to_value(&out).unwrap(); + assert!(value.get("selected").is_none()); + assert!(value.get("recovery").is_none()); + } + + fn protection_like() -> Vec { + protected(0x3000, 0x4000) + } +} diff --git a/senbei-engine/src/windows/layout.rs b/senbei-engine/src/windows/layout.rs index 7e7bd51..e1dd6e0 100644 --- a/senbei-engine/src/windows/layout.rs +++ b/senbei-engine/src/windows/layout.rs @@ -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, diff --git a/senbei-engine/src/windows/layout/discovery.rs b/senbei-engine/src/windows/layout/discovery.rs index 9a1f126..c4d1dee 100644 --- a/senbei-engine/src/windows/layout/discovery.rs +++ b/senbei-engine/src/windows/layout/discovery.rs @@ -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 { + 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 { + 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) { 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 { }; 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] { diff --git a/senbei-engine/src/windows/mod.rs b/senbei-engine/src/windows/mod.rs index a868d07..2a08214 100644 --- a/senbei-engine/src/windows/mod.rs +++ b/senbei-engine/src/windows/mod.rs @@ -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) -> 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, 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, UnpackError>, E: FnOnce() -> Result, 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::>(), + ["outer"] + ); + assert!(!crate::windows::research::trace_enabled()); + } + #[test] fn inspect_profile_reports_recognition_without_running_a_route() { let profile = inspect_profile(&detected_dll_input()); diff --git a/senbei-engine/src/windows/research.rs b/senbei-engine/src/windows/research.rs new file mode 100644 index 0000000..87d08df --- /dev/null +++ b/senbei-engine/src/windows/research.rs @@ -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), + 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, + #[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, + /// 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, + 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> = 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(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( + 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, +} + +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) { + 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) { + 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::>(), + ["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::>(), + ["inner"] + ); + assert_eq!( + outer + .events + .iter() + .map(|event| event.name) + .collect::>(), + ["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()); + } +} diff --git a/senbei-io/src/android/archive_limits.rs b/senbei-io/src/android/archive_limits.rs index 910e0a2..9678da0 100644 --- a/senbei-io/src/android/archive_limits.rs +++ b/senbei-io/src/android/archive_limits.rs @@ -7,7 +7,7 @@ use std::sync::{ atomic::{AtomicBool, Ordering}, }; -use senbei_engine::android::ResourceLimits; +use senbei_engine::android::{LimitExceeded, ResourceLimits}; use zip::ZipArchive; use anyhow::{Context, Result, bail}; @@ -180,14 +180,25 @@ impl ArchiveBudget { label: &str, ) -> Result> { if size > self.max_entry_bytes { - bail!( + return Err(anyhow::Error::new(LimitExceeded::Entry { + requested: size, + limit: self.max_entry_bytes, + }) + .context(format!( "entry `{label}` exceeds extraction limit {}", self.max_entry_bytes - ); + ))); } let length = size.min(maximum as u64); if length > self.max_total_bytes.saturating_sub(self.bytes) { - bail!("manifest `{label}` exceeds the remaining extraction byte limit"); + return Err(anyhow::Error::new(LimitExceeded::Total { + requested: self.bytes.saturating_add(length), + adding: length, + limit: self.max_total_bytes, + }) + .context(format!( + "manifest `{label}` exceeds the remaining extraction byte limit" + ))); } let mut bytes = Vec::new(); bytes @@ -203,10 +214,14 @@ impl ArchiveBudget { .checked_add(entries) .context("archive entry count overflow")?; if total > self.max_entries { - bail!( + return Err(anyhow::Error::new(LimitExceeded::Entries { + requested: total, + limit: self.max_entries, + }) + .context(format!( "archive entry limit exceeded: {total} > {}", self.max_entries - ); + ))); } self.entries = total; Ok(()) @@ -222,9 +237,21 @@ impl ArchiveBudget { let remaining = self.max_total_bytes.saturating_sub(self.bytes); let allowance = self.max_entry_bytes.min(remaining); if declared_size > allowance { - bail!( + let exceeded = if declared_size > self.max_entry_bytes { + LimitExceeded::Entry { + requested: declared_size, + limit: self.max_entry_bytes, + } + } else { + LimitExceeded::Total { + requested: self.bytes.saturating_add(declared_size), + adding: declared_size, + limit: self.max_total_bytes, + } + }; + return Err(anyhow::Error::new(exceeded).context(format!( "entry `{label}` declares {declared_size} bytes, exceeding extraction limit {allowance}" - ); + ))); } // The advertised size is a stricter ceiling when it is smaller than // the budget. A dishonest header must not buy extra decompression work. @@ -243,7 +270,13 @@ impl ArchiveBudget { .checked_add(read as u64) .context("decompressed entry size overflow")?; if next > limit { - bail!("entry `{label}` exceeds extraction limit {limit} while decompressing"); + return Err(anyhow::Error::new(LimitExceeded::Entry { + requested: next, + limit, + }) + .context(format!( + "entry `{label}` exceeds extraction limit {limit} while decompressing" + ))); } self.bytes = self .bytes @@ -346,7 +379,11 @@ fn inspect_archive( bail!("invalid ZIP64 end record"); } if qword(&record, 4) > max_directory_bytes { - bail!("ZIP64 metadata exceeds the directory memory limit"); + return Err(anyhow::Error::new(LimitExceeded::Entry { + requested: qword(&record, 4), + limit: max_directory_bytes, + }) + .context("ZIP64 metadata exceeds the directory memory limit")); } zip64_record = Some(record_offset); directory_start = qword(&record, 48); @@ -356,10 +393,22 @@ fn inspect_archive( bail!("inconsistent ZIP entry counts"); } if entries > max_entries as u64 { - bail!("archive entry limit exceeded: {entries} > {max_entries}"); + return Err(anyhow::Error::new(LimitExceeded::Entries { + requested: usize::try_from(entries).unwrap_or(usize::MAX), + limit: max_entries, + }) + .context(format!( + "archive entry limit exceeded: {entries} > {max_entries}" + ))); } if directory_bytes > max_directory_bytes { - bail!("ZIP directory size {directory_bytes} exceeds memory limit {max_directory_bytes}"); + return Err(anyhow::Error::new(LimitExceeded::Entry { + requested: directory_bytes, + limit: max_directory_bytes, + }) + .context(format!( + "ZIP directory size {directory_bytes} exceeds memory limit {max_directory_bytes}" + ))); } file.seek(SeekFrom::Start(0))?; Ok(ArchiveInfo { @@ -420,6 +469,51 @@ mod tests { ); } + #[test] + fn archive_ceilings_keep_typed_causes_and_context() { + let mut budget = ArchiveBudget::new(4, 6, 1); + budget.register_entries(1).unwrap(); + let error = budget.register_entries(1).unwrap_err(); + assert!(matches!( + error.downcast_ref::(), + Some(LimitExceeded::Entries { .. }) + )); + assert!(format!("{error:#}").contains("entry limit")); + + let error = budget + .read_probe(&mut Cursor::new(b"abcde"), 5, 5, "manifest") + .unwrap_err(); + assert!(matches!( + error.downcast_ref::(), + Some(LimitExceeded::Entry { .. }) + )); + let error = budget + .copy_entry(&mut Cursor::new(b"abcde"), &mut Vec::new(), 5, "large") + .unwrap_err(); + assert!(matches!( + error.downcast_ref::(), + Some(LimitExceeded::Entry { .. }) + )); + assert!(format!("{error:#}").contains("extraction limit")); + budget + .copy_entry(&mut Cursor::new(b"abcd"), &mut Vec::new(), 4, "first") + .unwrap(); + let error = budget + .copy_entry(&mut Cursor::new(b"abc"), &mut Vec::new(), 3, "second") + .unwrap_err(); + assert!(matches!( + error.downcast_ref::(), + Some(LimitExceeded::Total { .. }) + )); + let error = budget + .read_probe(&mut Cursor::new(b"abc"), 3, 3, "manifest") + .unwrap_err(); + assert!(matches!( + error.downcast_ref::(), + Some(LimitExceeded::Total { .. }) + )); + } + #[test] fn failed_writes_still_consume_the_read_budget() { struct FailingWriter; @@ -457,8 +551,16 @@ mod tests { fn preflight_rejects_large_counts_and_directory_before_indexing() { let mut file = tempfile::tempfile().unwrap(); file.write_all(&end_record(50, 1000)).unwrap(); - assert!(preflight_archive(&mut file, 49, 1000).is_err()); - assert!(preflight_archive(&mut file, 50, 999).is_err()); + let count_error = preflight_archive(&mut file, 49, 1000).unwrap_err(); + assert!(matches!( + count_error.downcast_ref::(), + Some(LimitExceeded::Entries { .. }) + )); + let size_error = preflight_archive(&mut file, 50, 999).unwrap_err(); + assert!(matches!( + size_error.downcast_ref::(), + Some(LimitExceeded::Entry { .. }) + )); assert_eq!(preflight_archive(&mut file, 50, 1000).unwrap(), 50); } diff --git a/senbei-io/src/android/context.rs b/senbei-io/src/android/context.rs index 88676e4..6b74fe7 100644 --- a/senbei-io/src/android/context.rs +++ b/senbei-io/src/android/context.rs @@ -78,6 +78,10 @@ pub(crate) enum ContextAmbiguity { pub(crate) struct AndroidRunCache { pub(super) limits: senbei_engine::android::ResourceLimits, pub(super) archive: super::archive_limits::ArchiveBudget, + /// Capture the engine's own extraction/restoration reports for research + /// inspection. Off for every ordinary run: the reports are large and are + /// discarded after each restore. + pub(super) research: bool, apps: HashMap, /// Successfully restored protected libraries, keyed by encrypted content. libraries: HashMap, @@ -121,6 +125,11 @@ impl AndroidRunCache { } } + /// Whether this run keeps the engines' own reports for research output. + pub(crate) fn research(&self) -> bool { + self.research + } + pub(crate) fn modules_mut(&mut self, key: &AppKey) -> &mut ApplicationModules { self.apps.entry(key.clone()).or_default() } @@ -495,6 +504,9 @@ pub(crate) struct RestoredLibrary { /// test double, or an engine without a validation pass) — never that the /// output validated. `Some(empty)` is a completed, clean validation. pub validation: Option, + /// The extraction and restoration reports this restore actually produced, + /// kept only when the run asked for research output. `None` otherwise. + pub research: Option, } /// Injectable library restore. Tests supply a fake so application-context @@ -513,10 +525,27 @@ pub(crate) trait LibraryRestorer { /// Production restorer: stage-2 extract, ELF rebuild, embedded metadata unwrap. #[derive(Default)] -pub(crate) struct EngineRestorer(pub(super) senbei_engine::android::ResourceLimits); +pub(crate) struct EngineRestorer { + pub(super) limits: senbei_engine::android::ResourceLimits, + /// Keep the engines' reports instead of dropping them after each restore. + pub(super) research: bool, +} + +impl EngineRestorer { + /// A restorer for `limits`, keeping the engines' reports only for research. + pub(crate) fn new(limits: senbei_engine::android::ResourceLimits, research: bool) -> Self { + Self { limits, research } + } +} impl LibraryRestorer for EngineRestorer { fn restore(&mut self, input: &Path, dest: &Path, verbose: bool) -> Result { - crate::android::restore_so_with_engine_limits(input, dest, verbose, &self.0) + crate::android::restore_so_with_engine_limits( + input, + dest, + verbose, + &self.limits, + self.research, + ) } } diff --git a/senbei-io/src/android/mod.rs b/senbei-io/src/android/mod.rs index 38b1bfc..69ae332 100644 --- a/senbei-io/src/android/mod.rs +++ b/senbei-io/src/android/mod.rs @@ -254,27 +254,6 @@ pub fn is_protected_so_file(path: &Path) -> bool { is_elf64_aarch64(&bytes) && is_protected_libil2cpp(&bytes) } -/// [`probe_so_file_with_limits`] with the recognition profile it produced. -/// -/// A resource-limit failure is reported as `Blocked` with the error retained, -/// never as "not protected". -pub(crate) fn probe_so_profiled( - path: &Path, - limits: &ResourceLimits, -) -> Result<(senbei_engine::ProtectionProfile, Result)> { - let file = File::open(path).with_context(|| format!("open `{}`", path.display()))?; - let bytes = map_read_only(&file, path)?; - if !is_elf64_aarch64(&bytes) { - return Ok(( - senbei_engine::ProtectionProfile::new(senbei_engine::ObservedTarget::android(None)), - Ok(false), - )); - } - let (profile, result) = - senbei_engine::android::probe_libil2cpp_profiled_with_limits(&bytes, limits); - Ok((profile, result.map_err(|error| error.to_string()))) -} - pub(crate) fn probe_so_file_with_limits( path: &Path, limits: &senbei_engine::android::ResourceLimits, @@ -311,6 +290,7 @@ pub(crate) fn restore_so_with_engine_limits( dest: &Path, verbose: bool, limits: &ResourceLimits, + research: bool, ) -> Result { let temporary = tempfile::tempdir().context("create stage-2 workspace")?; let stage2_dir = temporary.path().join("stage2"); @@ -319,6 +299,14 @@ pub(crate) fn restore_so_with_engine_limits( limits, ) .context("extract stage-1/stage-2 payload")?; + // The report the extraction just produced. Serialized once, only for + // research runs; an ordinary run drops it with the rest of the workspace. + let extraction_report = research.then(|| { + report_value( + &extraction, + &[(input, ""), (temporary.path(), "")], + ) + }); // Every module 0x0C is collected. Two distinct images in one library are a // conflict for that library's application, not a last-writer-wins update. let mut modules = Vec::new(); @@ -357,8 +345,37 @@ pub(crate) fn restore_so_with_engine_limits( verbose, }, limits, - ) - .context("restore protected library")?; + ); + // A restore that failed after extraction is still a research finding: the + // extraction's seeds, records and modules are already known, and the + // original failure travels with them so nothing is lost. + let report = match report { + Ok(report) => report, + Err(error) => { + let restored = extraction_report + .map(|extraction| crate::report::AndroidResearchReport { + extraction, + restoration: None, + }) + .map(ResearchCapture::Library); + return Err(capture( + anyhow::Error::new(error).context("restore protected library"), + restored, + )); + } + }; + // The same restore's own report, serialized once for research output + // before the validation diagnostics are taken out of it below. + let restoration = research.then(|| { + report_value( + &report, + &[ + (input, ""), + (dest, ""), + (temporary.path(), ""), + ], + ) + }); // Keep only the validation verdict this call already produced. Nothing is // re-read or re-validated: the diagnostics describe the bytes just written. let validation = Some(ValidationDiagnostics { @@ -372,6 +389,13 @@ pub(crate) fn restore_so_with_engine_limits( method_index_module, module_image, validation, + research: match (extraction_report, restoration) { + (Some(extraction), restoration) => Some(crate::report::AndroidResearchReport { + extraction, + restoration, + }), + _ => None, + }, }) } @@ -400,10 +424,36 @@ pub fn restore_so_file_with_diagnostics( verbose: bool, limits: &ResourceLimits, ) -> Result<(Option>, Option)> { - let restored = context::EngineRestorer(*limits).restore(input, dest, verbose)?; + let restored = context::EngineRestorer::new(*limits, false).restore(input, dest, verbose)?; Ok((restored.embedded_metadata, restored.validation)) } +/// One single-file Android library restore. +pub(crate) struct ResearchedLibrary { + pub embedded_metadata: Option>, + /// Structural diagnostics for the image this restore wrote. + pub validation: Option, + /// The engines' own reports, kept only when research was requested. + pub research: Option, +} + +/// [`restore_so_file_with_diagnostics`], also keeping the engines' own reports +/// for research output. Nothing else changes: the same single restore runs. +pub(crate) fn restore_so_file_researched( + input: &Path, + dest: &Path, + verbose: bool, + limits: &ResourceLimits, + research: bool, +) -> Result { + let restored = context::EngineRestorer::new(*limits, research).restore(input, dest, verbose)?; + Ok(ResearchedLibrary { + embedded_metadata: restored.embedded_metadata, + validation: restored.validation, + research: restored.research, + }) +} + /// Fresh run-scoped cache. Library hits reuse their module context; metadata hits /// are keyed by encrypted bytes and the module that recovered them. #[cfg(test)] @@ -415,6 +465,13 @@ pub(crate) fn run_cache_with_limits(limits: &ResourceLimits) -> context::Android context::AndroidRunCache::with_limits(limits) } +/// The same cache, keeping the engines' reports for research output. +pub(crate) fn run_cache_for_research(limits: &ResourceLimits) -> context::AndroidRunCache { + let mut cache = context::AndroidRunCache::with_limits(limits); + cache.research = true; + cache +} + /// Assign loose libraries and metadata to application contexts. pub(crate) fn loose_scopes( libraries: &[PathBuf], @@ -434,6 +491,9 @@ pub(crate) struct LooseLibraryOutcome { /// Structural diagnostics from the restore that produced this output. /// `None` for duplicates, failures, and restorers without a report. pub validation: Option, + /// The engines' own extraction and restoration reports, kept only for + /// research inspection. `None` for every ordinary run. + pub research: Option, } pub(crate) fn restore_loose_library( @@ -452,7 +512,7 @@ pub(crate) fn restore_loose_library( app, verbose, cache, - &mut context::EngineRestorer(limits), + &mut context::EngineRestorer::new(limits, cache.research()), ) } @@ -474,6 +534,7 @@ fn restore_loose_library_with( status: EntryStatus::Duplicate, embedded: None, validation: None, + research: None, }); } // A prior content-only success still needs context extraction. Restore it @@ -499,6 +560,7 @@ fn restore_loose_library_with( status: EntryStatus::Failed(error), embedded: None, validation: None, + research: None, }); } embedded = Some(meta_dest); @@ -517,15 +579,30 @@ fn restore_loose_library_with( }, embedded, // A duplicate restored only for its module context has no - // output of its own, so it reports no diagnostics. - validation: if prior { None } else { restored.validation }, + // output of its own, so it reports no diagnostics, and the + // engine reports belong to the run that actually produced it. + validation: if prior { + None + } else { + restored.validation.clone() + }, + research: if prior { None } else { restored.research }, + }) + } + Err(error) => { + // A restore that failed after extraction keeps the extraction's + // own report; the error itself is unchanged. + let research = match error_research(&error) { + Some(ResearchCapture::Library(report)) => Some(report.clone()), + _ => None, + }; + Ok(LooseLibraryOutcome { + status: EntryStatus::Failed(error), + embedded: None, + validation: None, + research, }) } - Err(error) => Ok(LooseLibraryOutcome { - status: EntryStatus::Failed(error), - embedded: None, - validation: None, - }), } } @@ -538,6 +615,9 @@ pub(crate) struct LooseMetadataOutcome { pub provenance: Vec, /// Route the transform actually took (seeded, structural, or method-index). pub layout: senbei_engine::LayoutKind, + /// Seeds tried, discovery, and the transform's own report. Only a research + /// run keeps this. + pub research: Option, } pub(crate) fn restore_loose_metadata( @@ -571,8 +651,9 @@ pub(crate) fn restore_loose_metadata( let module = module.as_deref(); // Loose metadata retains one output per path, as before. Do not keep all // restored blobs in the folder cache just to avoid a repeated permutation. - let (out, report, layout) = - restore_metadata_bytes_with_module(&data, module).with_context(|| label.to_owned())?; + let (out, report, layout, research) = + restore_metadata_with_module(&data, module, cache.research()) + .with_context(|| label.to_owned())?; if report.remapped > 0 { write_metadata_blob(dest, &out)?; if verbose { @@ -584,6 +665,7 @@ pub(crate) fn restore_loose_metadata( remapped: report.remapped, provenance, layout, + research, }) } @@ -665,43 +747,47 @@ pub(crate) fn restore_package_cached( out_root, cache, verbose, - &mut context::EngineRestorer(limits), + &mut context::EngineRestorer::new(limits, cache.research()), ) } /// One folder split-set: every library in the group, then every metadata blob. /// A library-only pass records modules without writing metadata, so a metadata /// blob in an earlier sibling cannot run before a library in a later one. +/// `members` pairs each package with the relative path its outputs live under. +/// +/// The relative path is computed by the caller (see `job::rel_in_tree`) and is +/// always relative. This function never derives it: `Path::join` with an +/// absolute path discards the output root, so a fallback here could write +/// outside the caller's directory — unacceptable for a dry run or inspection, +/// whose whole contract is that it keeps nothing outside its own workspace. pub(crate) fn restore_apk_group( - packages: &[PathBuf], - root: &Path, + members: &[(&Path, &Path)], out_root: &Path, cache: &mut context::AndroidRunCache, verbose: bool, ) -> Result> { let limits = cache.limits; let mut outcomes = Vec::new(); - for package in packages { - let rel = package.strip_prefix(root).unwrap_or(package); + for (package, rel) in members { outcomes.extend(restore_package_pass( package, rel, out_root, cache, verbose, - &mut context::EngineRestorer(limits), + &mut context::EngineRestorer::new(limits, cache.research()), PackagePass::Libraries, )?); } - for package in packages { - let rel = package.strip_prefix(root).unwrap_or(package); + for (package, rel) in members { outcomes.extend(restore_package_pass( package, rel, out_root, cache, verbose, - &mut context::EngineRestorer(limits), + &mut context::EngineRestorer::new(limits, cache.research()), PackagePass::Metadata, )?); } @@ -724,6 +810,124 @@ pub fn content_identity(data: &[u8]) -> String { hex_digest(&digest.finalize()) } +/// A failure that still carries what the attempt had already observed. +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) enum ResearchCapture { + /// Extraction ran and produced a report; the restoration after it failed. + Library(crate::report::AndroidResearchReport), + /// A metadata transform's seeds, discovery, and failure reason. + Metadata(serde_json::Value), +} + +/// A transform error that still carries what the attempt observed. +/// +/// Research inspection wants the seeds it tried and the reason each failed even +/// when no output was produced. The error keeps its ordinary `anyhow` chain — +/// callers that do not care about research see exactly the same message. +#[derive(Debug)] +pub(crate) struct LossyError { + inner: anyhow::Error, + capture: ResearchCapture, +} + +impl LossyError { + pub(crate) fn new(inner: anyhow::Error, capture: ResearchCapture) -> Self { + Self { inner, capture } + } + + fn capture(&self) -> &ResearchCapture { + &self.capture + } +} + +impl std::fmt::Display for LossyError { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + self.inner.fmt(formatter) + } +} + +impl std::error::Error for LossyError { + fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { + // Keep the whole wrapped chain reachable: callers classify the original + // error (an unsupported version, a malformed blob) by walking it. + Some(self.inner.as_ref()) + } +} + +/// The research captured for a failure, if the error (or anything it wraps) +/// carries one. +pub(crate) fn error_research(error: &anyhow::Error) -> Option<&ResearchCapture> { + error + .chain() + .find_map(|cause| cause.downcast_ref::()) + .map(LossyError::capture) +} + +/// [`capture`] with the same rule, exposed to the module's tests so a failed +/// restore can be exercised without a protected fixture. +#[cfg(test)] +pub(crate) fn capture_for_tests( + error: anyhow::Error, + research: Option, +) -> anyhow::Error { + capture(error, research) +} + +/// Wrap `error` with the capture, when there is one. +fn capture(error: anyhow::Error, capture: Option) -> anyhow::Error { + match capture { + Some(capture) => LossyError::new(error, capture).into(), + None => error, + } +} + +/// Serialize one engine report for research output. +/// +/// The report is the engine's own, unchanged; only filesystem locations are +/// rewritten to logical labels. A research report outlives the run, and a +/// scratch path that no longer exists is noise — or worse, a misleading hint +/// about where an output was "kept". +fn report_value(report: &T, labels: &[(&Path, &str)]) -> serde_json::Value { + let mut value = serde_json::to_value(report).unwrap_or(serde_json::Value::Null); + scrub_paths(&mut value, labels); + value +} + +fn scrub_paths(value: &mut serde_json::Value, labels: &[(&Path, &str)]) { + // Longest location first: a nested path starts with its parent, and the + // more specific label is the one that describes it. + let mut rules: Vec<(String, &str)> = labels + .iter() + .map(|(path, label)| (path.display().to_string(), *label)) + .filter(|(rendered, _)| !rendered.is_empty()) + .collect(); + rules.sort_by_key(|(rendered, _)| std::cmp::Reverse(rendered.len())); + scrub_value(value, &rules); +} + +fn scrub_value(value: &mut serde_json::Value, rules: &[(String, &str)]) { + match value { + serde_json::Value::String(text) => { + for (rendered, label) in rules { + if text.contains(rendered.as_str()) { + *text = text.replace(rendered.as_str(), label); + } + } + } + serde_json::Value::Array(items) => { + for item in items { + scrub_value(item, rules); + } + } + serde_json::Value::Object(fields) => { + for field in fields.values_mut() { + scrub_value(field, rules); + } + } + _ => {} + } +} + /// Restore an il2cpp metadata blob. Paired v24.1 Android packages use the /// method-index profile recovered from module 0x0C; later Android layouts use /// the seeded MethodDef RID permutation before falling back to the structural @@ -745,20 +949,67 @@ pub(crate) fn restore_metadata_bytes_with_module( data: &[u8], method_index_module: Option<&[u8]>, ) -> anyhow::Result<(Vec, senbei_metadata::Report, senbei_engine::LayoutKind)> { + let (out, report, layout, _) = restore_metadata_with_module(data, method_index_module, false)?; + Ok((out, report, layout)) +} + +/// [`restore_metadata_bytes_with_module`], optionally keeping the facts the +/// transform observed on the way. +/// +/// The research value is produced by the same pass that does the work: the +/// seed candidates discovery found (or why it found none), the seeds actually +/// tried, and the transform's own report. Nothing is re-run for it, and it +/// survives a transform that fails — a failing trial is exactly what the +/// caller wants to see. +pub(crate) fn restore_metadata_with_module( + data: &[u8], + method_index_module: Option<&[u8]>, + research: bool, +) -> anyhow::Result<( + Vec, + senbei_metadata::Report, + senbei_engine::LayoutKind, + Option, +)> { use senbei_engine::LayoutKind; let version = data .get(4..8) .and_then(|bytes| <[u8; 4]>::try_from(bytes).ok()) .map(u32::from_le_bytes); + let mut facts = MetadataFacts { + version, + route: "method_indices", + module_0c_sha256: method_index_module.map(content_identity), + ..MetadataFacts::default() + }; + // Keep what the attempt has seen so far, then wrap the failure with it. + let fail = |facts: &mut MetadataFacts, error: anyhow::Error| -> anyhow::Error { + facts.error = Some(format!("{error:#}")); + let kept = research.then(|| facts.clone().into_value()); + capture(error, kept.map(ResearchCapture::Metadata)) + }; + if version == Some(24) { // v24.1 method indices come only from this application's module 0x0C. // Falling through to the structural remap would report "unsupported // version" and could be mistaken for a clean skip. No module is a // failed binding, not an unsupported layout. - let module = method_index_module - .ok_or_else(|| anyhow::anyhow!("no module 0x0C for v24.1 metadata"))?; + let Some(module) = method_index_module else { + let error = anyhow::anyhow!("no module 0x0C for v24.1 metadata"); + return Err(fail(&mut facts, error)); + }; let (out, report) = senbei_metadata::android::restore_method_indices_v24_1(data, module) - .map_err(anyhow::Error::new)?; + .map_err(anyhow::Error::new) + .map_err(|error| fail(&mut facts, error))?; + facts.version = Some(report.version); + facts.report = Some(serde_json::json!({ + "version": report.version, + "methods": report.methods, + "active_methods": report.active_methods, + "changed_indices": report.changed_indices, + "exception_count": report.exception_count, + "seed": report.seed, + })); return Ok(( out, senbei_metadata::Report { @@ -768,12 +1019,31 @@ pub(crate) fn restore_metadata_bytes_with_module( modules: 0, }, LayoutKind::MetadataMethodIndices, + research.then(|| facts.into_value()), )); } - if let Ok(discovery) = senbei_metadata::android::discover_method_token_seeds(data) - && matches!(discovery.version, 29 | 31 | 39) - { - let mut seeds = discovery.seed_candidates.clone(); + + // Seed discovery is the only step that can say why a seeded restore was + // never tried, so its own outcome is recorded for research. Whether the + // seeded route runs at all is decided exactly as before. + let mut seeded_layout = false; + match senbei_metadata::android::discover_method_token_seeds(data) { + Ok(found) if matches!(found.version, 29 | 31 | 39) => { + seeded_layout = true; + facts.seed_candidates = found.seed_candidates.clone(); + if research { + facts.discovery = serde_json::to_value(&found).ok(); + } + } + Ok(_) => {} + Err(error) => { + if research { + facts.discovery_error = Some(format!("{error}")); + } + } + } + if seeded_layout { + let mut seeds = facts.seed_candidates.clone(); if seeds.is_empty() { seeds.push(senbei_metadata::android::DEFAULT_METHOD_TOKEN_SEED); } @@ -782,7 +1052,24 @@ pub(crate) fn restore_metadata_bytes_with_module( // build with an unseeded permutation falls through to the structural // remap rather than producing a silently wrong file. for seed in seeds { + facts.tried_seeds.push(seed); if let Ok((out, report)) = senbei_metadata::android::restore_method_tokens(data, seed) { + facts.route = "seeded"; + facts.version = Some(report.version); + facts.report = Some(serde_json::json!({ + "version": report.version, + "seed": report.seed, + "encryption_status": report.encryption_status, + "images": report.images, + "images_with_methods": report.images_with_methods, + "types": report.types, + "methods": report.methods, + "visited_methods": report.visited_methods, + "already_correct_before": report.already_correct_before, + "correct_after": report.correct_after, + "changed_tokens": report.changed_tokens, + "transformed_images": report.transformed_images, + })); return Ok(( out, senbei_metadata::Report { @@ -792,12 +1079,66 @@ pub(crate) fn restore_metadata_bytes_with_module( modules: report.images_with_methods, }, LayoutKind::MetadataSeeded, + research.then(|| facts.into_value()), )); } } } - let (out, report) = senbei_metadata::deobfuscate(data).map_err(anyhow::Error::new)?; - Ok((out, report, LayoutKind::MetadataStructural)) + + facts.route = "structural"; + let (out, report) = senbei_metadata::deobfuscate(data) + .map_err(anyhow::Error::new) + .map_err(|error| fail(&mut facts, error))?; + facts.version = Some(report.version); + facts.report = Some(serde_json::json!({ + "version": report.version, + "methods": report.methods, + "remapped": report.remapped, + "modules": report.modules, + })); + Ok(( + out, + report, + LayoutKind::MetadataStructural, + research.then(|| facts.into_value()), + )) +} + +/// What one metadata transform observed, independent of whether it succeeded. +#[derive(Debug, Clone, Default)] +struct MetadataFacts { + route: &'static str, + version: Option, + /// Seeds the transform actually tried, in order. + tried_seeds: Vec, + /// Candidates seed discovery reported. + seed_candidates: Vec, + /// The discovery report, when it found a supported layout. + discovery: Option, + /// Why seed discovery declined, when it did. + discovery_error: Option, + /// The transform's own report. + report: Option, + /// Identity of the module `0x0C` this transform bound to, when it had one. + module_0c_sha256: Option, + /// Why the transform stopped, when it did. + error: Option, +} + +impl MetadataFacts { + fn into_value(self) -> serde_json::Value { + serde_json::json!({ + "route": self.route, + "version": self.version, + "tried_seeds": self.tried_seeds, + "seed_candidates": self.seed_candidates, + "discovery": self.discovery, + "discovery_error": self.discovery_error, + "report": self.report, + "module_0c_sha256": self.module_0c_sha256, + "error": self.error, + }) + } } /// What happened to one archive entry (or one loose Android target). @@ -820,6 +1161,12 @@ pub struct EntryOutcome { /// Structural diagnostics from the restore of this entry. `None` for /// metadata entries, duplicates, and restorers without a report. pub validation: Option, + /// The engines' own reports for a library entry. Only a research run keeps + /// them, and only for an entry that actually restored. + pub research: Option, + /// Seeds tried, discovery, and the transform report for a metadata entry. + /// Only a research run keeps them, and they survive a failed transform. + pub metadata_research: Option, } #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -897,17 +1244,34 @@ pub fn restore_package_with_limits( // package still skips those bytes; module context for metadata is rebuilt // inside this package (one package, or one manifest-scoped bundle, is one // application boundary). + restore_package_with_limits_and_research(package, rel, out_root, seen, verbose, &limits, false) +} + +/// [`restore_package_with_limits`], optionally keeping the engines' reports for +/// research output. One package is one application boundary either way. +pub(crate) fn restore_package_with_limits_and_research( + package: &Path, + rel: &Path, + out_root: &Path, + seen: &mut HashSet, + verbose: bool, + limits: &ResourceLimits, + research: bool, +) -> Result> { + let limits = *limits; let mut cache = context::AndroidRunCache::with_limits(&limits); + cache.research = research; for identity in seen.iter().cloned() { cache.insert_prior_success(identity); } + let research = cache.research(); let outcomes = restore_package_with_restorer( package, rel, out_root, &mut cache, verbose, - &mut context::EngineRestorer(limits), + &mut context::EngineRestorer::new(limits, research), ); // Publish successes even when the package returns `Err`. The caller's set // is only replaced after that, so a panic still leaves the old successes. @@ -1188,6 +1552,8 @@ fn restore_package_entry( layout: None, metadata_version: None, validation: None, + research: None, + metadata_research: None, }; if !is_so && !is_meta { return Ok(vec![outcome( @@ -1238,6 +1604,7 @@ fn restore_package_entry( let mut restored_outcome = outcome(EntryKind::So, EntryStatus::Restored, Vec::new()); restored_outcome.validation = restored.validation.clone(); + restored_outcome.research = restored.research.clone(); outcomes.push(restored_outcome); } if !prior && let Some(blob) = &restored.embedded_metadata { @@ -1252,6 +1619,8 @@ fn restore_package_entry( layout: None, metadata_version: None, validation: None, + research: None, + metadata_research: None, }), Err(error) => embedded_failed = Some(error), } @@ -1276,11 +1645,17 @@ fn restore_package_entry( } } } - Err(error) => vec![outcome( - EntryKind::So, - EntryStatus::Failed(error), - Vec::new(), - )], + Err(error) => { + // A restore that failed after extraction keeps what the + // extraction already reported, alongside the error. + let research = match error_research(&error) { + Some(ResearchCapture::Library(report)) => Some(report.clone()), + _ => None, + }; + let mut failed = outcome(EntryKind::So, EntryStatus::Failed(error), Vec::new()); + failed.research = research; + vec![failed] + } }, ); } @@ -1328,47 +1703,58 @@ fn restore_package_entry( // Metadata entry: write only when the restore actually changed protected // method fields — a clean blob needs no copy (same contract as loose files). // The binding was resolved before this write. - let (kind, status, layout) = match restore_metadata_bytes_with_module(&entry_data, module) { - Ok((out, report, layout)) if report.remapped > 0 => { - let kind = EntryKind::Metadata { - remapped: report.remapped, - }; - match write_metadata_blob(dest, &out) { - Ok(()) => { - state.cache.insert_metadata( - identity, - context_identity, - context::CachedMetadata::Restored { - remapped: report.remapped, - }, - ); - (kind, EntryStatus::Restored, Some(layout)) + let (kind, status, layout, metadata_research) = + match restore_metadata_with_module(&entry_data, module, state.cache.research()) { + Ok((out, report, layout, research)) if report.remapped > 0 => { + let kind = EntryKind::Metadata { + remapped: report.remapped, + }; + match write_metadata_blob(dest, &out) { + Ok(()) => { + state.cache.insert_metadata( + identity, + context_identity, + context::CachedMetadata::Restored { + remapped: report.remapped, + }, + ); + (kind, EntryStatus::Restored, Some(layout), research) + } + Err(error) => (kind, EntryStatus::Failed(error), Some(layout), research), } - Err(error) => (kind, EntryStatus::Failed(error), Some(layout)), } - } - // A blob that needed no change still reports the route that ran. - Ok((_, _report, layout)) => { - state.cache.insert_metadata( - identity, - context_identity, - context::CachedMetadata::Unchanged, - ); - ( - EntryKind::Metadata { remapped: 0 }, - EntryStatus::Unchanged, - Some(layout), - ) - } - Err(error) => ( - EntryKind::Metadata { remapped: 0 }, - EntryStatus::Failed(error), - None, - ), - }; + // A blob that needed no change still reports the route that ran. + Ok((_, _report, layout, research)) => { + state.cache.insert_metadata( + identity, + context_identity, + context::CachedMetadata::Unchanged, + ); + ( + EntryKind::Metadata { remapped: 0 }, + EntryStatus::Unchanged, + Some(layout), + research, + ) + } + Err(error) => { + // The seeds it tried and the reason it stopped survive the failure. + let research = error_research(&error).and_then(|capture| match capture { + ResearchCapture::Metadata(value) => Some(value.clone()), + ResearchCapture::Library(_) => None, + }); + ( + EntryKind::Metadata { remapped: 0 }, + EntryStatus::Failed(error), + None, + research, + ) + } + }; let mut entry_outcome = outcome(kind, status, provenance_labels(&provenance)); entry_outcome.layout = layout; entry_outcome.metadata_version = version; + entry_outcome.metadata_research = metadata_research; Ok(vec![entry_outcome]) } diff --git a/senbei-io/src/android/tests.rs b/senbei-io/src/android/tests.rs index ff15e65..b2d6e63 100644 --- a/senbei-io/src/android/tests.rs +++ b/senbei-io/src/android/tests.rs @@ -36,6 +36,7 @@ impl LibraryRestorer for ScriptedRestorer { // A scripted restore has no engine report behind it, so it claims // no validation verdict at all. validation: None, + research: None, }) } @@ -1349,3 +1350,242 @@ fn scripted_restore_claims_no_validation_verdict() { "a restorer without a report must not claim a clean verdict" ); } + +/// Research keeps what the transform actually did: the route, the seeds tried, +/// and the engine's own counters. Ordinary runs keep none of it. +#[test] +fn metadata_research_reports_the_route_that_ran() { + let data = metadata_fixture(); + + let (_, _, layout, research) = restore_metadata_with_module(&data, None, true).unwrap(); + let research = research.expect("research mode keeps the transform's facts"); + assert_eq!(research["version"], 31); + // The fixture has no seeded permutation to find, so the measured route is + // the structural remap — and the research names the route that actually ran. + assert_eq!(research["route"], "structural"); + assert!(research["tried_seeds"].as_array().is_some()); + assert!(research["report"].is_object(), "{research}"); + assert!(research["error"].is_null()); + assert_eq!( + research["module_0c_sha256"], + serde_json::Value::Null, + "no module was offered for this blob" + ); + // The layout the transform reported is the one the research names. + let (_, _, quiet_layout, quiet) = restore_metadata_with_module(&data, None, false).unwrap(); + assert!(quiet.is_none(), "an ordinary run keeps no research value"); + assert_eq!(quiet_layout, layout); +} + +/// A failed transform still reports the seeds it tried and why it stopped. +#[test] +fn metadata_research_survives_a_failed_transform() { + // A v24.1 header with no module 0x0C: the binding itself fails, before any + // transform could run. + let mut data = metadata_fixture(); + data[4..8].copy_from_slice(&24u32.to_le_bytes()); + + let error = restore_metadata_with_module(&data, None, true).unwrap_err(); + let capture = error_research(&error).expect("the failure carries its research"); + let ResearchCapture::Metadata(value) = capture else { + panic!("a metadata failure carries metadata research"); + }; + assert_eq!(value["route"], "method_indices"); + assert_eq!(value["version"], 24); + assert!( + value["error"] + .as_str() + .is_some_and(|text| text.contains("0x0C")), + "the reason is kept: {value}" + ); + // An ordinary run fails the same way, just without the research value. + let quiet = restore_metadata_with_module(&data, None, false).unwrap_err(); + assert!(error_research(&quiet).is_none()); +} + +/// A library restore that fails after extraction keeps the extraction's own +/// report, so the research output says how far it got. +#[test] +fn a_failed_library_restore_keeps_what_extraction_reported() { + let report = crate::report::AndroidResearchReport { + extraction: serde_json::json!({"stage1": {"payload_key": 0x1234}, "streams": []}), + restoration: None, + }; + let error = crate::android::capture_for_tests( + anyhow::anyhow!("baseline restore failed"), + Some(ResearchCapture::Library(report.clone())), + ); + let capture = error_research(&error).expect("the failure carries its research"); + let ResearchCapture::Library(kept) = capture else { + panic!("a library failure carries library research"); + }; + assert_eq!(kept.extraction, report.extraction); + assert!( + kept.restoration.is_none(), + "no restoration report exists for a restore that failed" + ); + // The original failure is still the error's message. + assert!(format!("{error:#}").contains("baseline restore failed")); +} + +/// A split set is restored with output paths computed by the caller. An +/// absolute relative path would make `Path::join` discard the output root and +/// escape it — precisely what a dry run/inspection must never do. +#[test] +fn a_split_set_never_writes_outside_the_output_root() { + let temp = tempfile::tempdir().unwrap(); + let root = temp.path().join("tree"); + std::fs::create_dir_all(&root).unwrap(); + let config = root.join("config.arm64_v8a.apk"); + let base = root.join("base.apk"); + let module_data = pair(3).1; + write_package( + &config, + &[ + ( + "AndroidManifest.xml", + manifest("com.example.split", "7").as_bytes(), + ), + ("lib/arm64-v8a/libil2cpp.so", &library_bytes(b"split-so")), + ], + ); + write_package( + &base, + &[ + ( + "AndroidManifest.xml", + manifest("com.example.split", "7").as_bytes(), + ), + ("assets/global-metadata.dat", &pair(3).0), + ], + ); + assert_eq!( + loose_apk_groups(&[base.clone(), config.clone()]).len(), + 1, + "same package and version form one split set" + ); + + let out = temp.path().join("workspace"); + let rels: Vec = [&base, &config] + .iter() + .map(|package| package.strip_prefix(&root).unwrap().to_path_buf()) + .collect(); + let members: Vec<(&Path, &Path)> = [&base, &config] + .iter() + .map(|package| package.as_path()) + .zip(rels.iter().map(|rel| rel.as_path())) + .collect(); + let mut cache = run_cache_for_research(&senbei_engine::android::ResourceLimits::default()); + let results = restore_apk_group(&members, &out, &mut cache, false); + assert!(results.is_ok(), "synthetic split set restores: {results:?}"); + + for rel in &rels { + assert!(!rel.is_absolute(), "relative paths stay relative: {rel:?}"); + assert!( + out.join(rel).starts_with(&out), + "every output stays under the workspace" + ); + } + let written: Vec = std::fs::read_dir(temp.path()) + .unwrap() + .filter_map(|entry| entry.ok().map(|entry| entry.path())) + .filter(|path| path != &root && path != &out) + .collect(); + assert!( + written.is_empty(), + "nothing appears beside the workspace: {written:?}" + ); + let _ = module_data; +} + +/// A caller cannot hand the group restore an absolute "relative" path by +/// accident through this API: it takes explicit pairs, and the folder driver +/// builds them with the same helper the rest of the run uses. This pins the +/// shape so a future refactor cannot reintroduce the `strip_prefix(..).unwrap_or` +/// fallback that made `Path::join` discard the output root. +#[test] +fn the_group_restore_never_derives_its_own_relative_path() { + let source = include_str!("mod.rs"); + let signature = source + .split("pub(crate) fn restore_apk_group(") + .nth(1) + .unwrap(); + let head = signature + .split(") -> Result>") + .next() + .unwrap(); + assert!( + head.contains("members: &[(&Path, &Path)]"), + "the group restore receives caller-computed relative paths: {head}" + ); + assert!( + !source.contains("strip_prefix(root).unwrap_or(package)"), + "the absolute-path fallback must not come back" + ); +} + +/// A restorer that fails with a resource ceiling, as the production one does +/// when an entry exceeds `--max-entry-mib`. +struct LimitedRestorer; + +impl LibraryRestorer for LimitedRestorer { + fn restore( + &mut self, + _input: &Path, + _dest: &Path, + _verbose: bool, + ) -> anyhow::Result { + Err(anyhow::Error::new( + senbei_engine::android::LimitExceeded::Entry { + requested: 4 * 1024 * 1024, + limit: 1024 * 1024, + }, + )) + } + + fn protected_override(&mut self, input: &Path) -> Option> { + std::fs::read(input).ok() + } +} + +/// A known target whose restore stopped on a resource ceiling is an error the +/// report can name — it is not "recognized, therefore complete". The status and +/// the cause come from the typed error, never from its message text. +#[test] +fn a_known_library_that_hits_a_ceiling_is_reported_incomplete() { + let temp = tempfile::tempdir().unwrap(); + let root = temp.path(); + let app = root.join("app"); + std::fs::create_dir_all(app.join("lib/arm64-v8a")).unwrap(); + let so = app.join("lib/arm64-v8a/libil2cpp.so"); + std::fs::write(&so, library_bytes(b"over-limit")).unwrap(); + + let mut cache = run_cache(); + let scoped = loose_scopes(std::slice::from_ref(&so), &[]); + let mut restorer = LimitedRestorer; + let outcome = restore_loose_library_with( + &so, + &root.join("out.so"), + "libil2cpp.so", + &scoped[0].key, + false, + &mut cache, + &mut restorer, + ) + .unwrap(); + + let EntryStatus::Failed(error) = &outcome.status else { + panic!("the ceiling must fail the restore: {:?}", outcome.status); + }; + assert!( + crate::job::analysis_incomplete(error), + "a LimitExceeded failure is infrastructure, not a rejected layout" + ); + let report = crate::job::android_library_input( + &so, + crate::report::InputStatus::Error, + &root.join("out.so"), + std::time::Instant::now(), + ); + assert_eq!(report.status, crate::report::InputStatus::Error); +} diff --git a/senbei-io/src/job.rs b/senbei-io/src/job.rs index cff7a5c..fa21cba 100644 --- a/senbei-io/src/job.rs +++ b/senbei-io/src/job.rs @@ -4,7 +4,7 @@ use std::time::Instant; use crate::atomic::write_atomic; pub use crate::report::{Collector, Mode, REPORT_FORMAT_VERSION, Report}; use crate::report::{ - CompanionReport, CompanionState, ContainerReport, EntryKind, EntryReport, EntryStatus, + CompanionReport, CompanionState, ContainerReport, Digest, EntryKind, EntryReport, EntryStatus, InputReport, InputStatus, OutputFile, Role, Stage, StageReport, StageStatus, }; pub use crate::windows::{ @@ -250,6 +250,11 @@ fn run_folder_inner( errors: scan_failed, ..Summary::default() }; + // Research inspection runs the ordinary drivers but reads their results as + // observations: a failed recovery is a finding, not a failed inspection. + let research = reporter + .as_deref() + .is_some_and(|reporter| reporter.mode() == Mode::Inspect); if let Some(reporter) = reporter.as_deref_mut() { reporter.set_scan(crate::report::ScanReport { non_target_skipped: scan_stats.skipped, @@ -265,23 +270,28 @@ fn run_folder_inner( // Wrap in catch_unwind so a single bad file never aborts the folder run. // A reporting run goes through the profiled entry point so the report - // carries the route the pipeline actually selected; an ordinary run - // keeps the unchanged call. + // carries the route the pipeline actually selected; a research run + // additionally keeps its structural facts. An ordinary run keeps the + // unchanged call. let profiled = reporter.is_some(); let input_owned = input.clone(); let dest_owned = dest.clone(); let result = senbei_engine::catch_unwind_quiet(|| { if profiled { - let (profile, result) = - unpack_one_profiled(&input_owned, &dest_owned, verbose_steps); - (Some(profile), result) + let (profile, observed, result) = + unpack_one_researched(&input_owned, &dest_owned, verbose_steps, research); + (Some(profile), observed, result) } else { - (None, unpack_one_v(&input_owned, &dest_owned, verbose_steps)) + ( + None, + None, + unpack_one_v(&input_owned, &dest_owned, verbose_steps), + ) } }); match result { - Ok((profile, Ok((kind, report)))) => { + Ok((profile, observed, Ok((kind, report)))) => { s.unpacked += 1; crate::ui::ok(&bar, suppress_file_lines, &rel, kind, &dest); if let Some(log) = &log { @@ -295,20 +305,27 @@ fn run_folder_inner( } } if let Some(reporter) = reporter.as_deref_mut() { - reporter.push(windows_input(input, &dest, kind, &report, profile, started)); + let mut reported = windows_input(input, &dest, kind, &report, profile, started); + apply_windows_research(&mut reported, observed); + reporter.push(inspect_status_if_research(reported, research)); } } - Ok((profile, Err(e))) => { + Ok((profile, observed, Err(e))) => { + // A recovery that ran and failed is an ordinary driver outcome. + // The per-input report is what inspection reads, and + // `inspect_status` turns it into a finding rather than an error. s.errors += 1; crate::ui::err(&bar, suppress_file_lines, &rel, &e); if let Some(log) = &log { log.step(&format!("ERR {rel:?}: {e:#}")); } if let Some(reporter) = reporter.as_deref_mut() { - reporter.push(match profile { + let mut reported = match profile { Some(profile) => failed_input_with_profile(input, &e, profile, started), None => failed_input(input, &e, started), - }); + }; + apply_windows_research(&mut reported, observed); + reporter.push(inspect_status_if_research(reported, research)); } } Err(panic) => { @@ -334,7 +351,11 @@ fn run_folder_inner( // Module 0x0C stays inside the application that produced it: an extracted // `lib//` tree shares with that tree's `assets/` metadata only, and a // package shares only with splits of the same package name and version. - let mut android_cache = crate::android::run_cache_with_limits(limits); + let mut android_cache = if research { + crate::android::run_cache_for_research(limits) + } else { + crate::android::run_cache_with_limits(limits) + }; let loose = crate::android::loose_scopes(&scan.android_so, metas); for scoped in loose.iter().filter(|scoped| { scan.android_so @@ -360,70 +381,81 @@ fn run_folder_inner( }); let report_outcome; let mut report_validation: Option = None; + let mut report_research: Option = None; + let mut report_incomplete = false; match result { - Ok(Ok(outcome)) => match outcome.status { - crate::android::EntryStatus::Duplicate => { - s.skipped += 1; - if let Some(log) = &log { - log.step(&format!("SKIP {rel:?}: duplicate of an earlier target")); - } - report_outcome = Some(InputStatus::Skipped); - } - crate::android::EntryStatus::Failed(e) => { - s.errors += 1; - crate::ui::err(&bar, suppress_file_lines, &rel, &e); - if let Some(log) = &log { - log.step(&format!("ERR {rel:?}: {e:#}")); - } - report_outcome = Some(InputStatus::Error); - } - crate::android::EntryStatus::Restored => { - s.unpacked += 1; - // Surface the engine's advisory findings. They never fail - // a restore, so they stay warnings on the same log/UI path. - report_validation = outcome.validation.clone(); - if let Some(validation) = &report_validation { - if !suppress_file_lines { - for message in &validation.messages { - eprintln!("- {} {}", rel.display(), message); - } - } + Ok(Ok(mut outcome)) => { + // A restore that failed after extraction still reports what the + // extraction observed, so the research facts are taken first. + report_research = outcome.research.take(); + match outcome.status { + crate::android::EntryStatus::Duplicate => { + s.skipped += 1; if let Some(log) = &log { - for message in &validation.messages { - log.step(&format!("WARN {rel:?}: {message}")); + log.step(&format!("SKIP {rel:?}: duplicate of an earlier target")); + } + report_outcome = Some(InputStatus::Skipped); + } + crate::android::EntryStatus::Failed(e) => { + s.errors += 1; + crate::ui::err(&bar, suppress_file_lines, &rel, &e); + if let Some(log) = &log { + log.step(&format!("ERR {rel:?}: {e:#}")); + } + // Only a resource or I/O ceiling truncates the + // analysis; a rejected candidate is a finding. + report_incomplete = analysis_incomplete(&e); + report_outcome = Some(InputStatus::Error); + } + crate::android::EntryStatus::Restored => { + s.unpacked += 1; + // Surface the engine's advisory findings. They never fail + // a restore, so they stay warnings on the same log/UI path. + report_validation = outcome.validation.clone(); + if let Some(validation) = &report_validation { + if !suppress_file_lines { + for message in &validation.messages { + eprintln!("- {} {}", rel.display(), message); + } + } + if let Some(log) = &log { + for message in &validation.messages { + log.step(&format!("WARN {rel:?}: {message}")); + } } } - } - crate::ui::ok_label( - &bar, - suppress_file_lines, - &rel.display().to_string(), - "So", - &dest, - ); - if let Some(log) = &log { - log.step(&format!("OK {rel:?} -> {dest:?} (Android SO)")); - } - if let Some(meta_dest) = outcome.embedded { - s.metadata += 1; crate::ui::ok_label( &bar, suppress_file_lines, - &format!("{} (embedded metadata)", rel.display()), - "metadata", - &meta_dest, + &rel.display().to_string(), + "So", + &dest, ); if let Some(log) = &log { - log.step(&format!("META {rel:?} (embedded) -> {meta_dest:?}")); + log.step(&format!("OK {rel:?} -> {dest:?} (Android SO)")); } + if let Some(meta_dest) = outcome.embedded { + s.metadata += 1; + crate::ui::ok_label( + &bar, + suppress_file_lines, + &format!("{} (embedded metadata)", rel.display()), + "metadata", + &meta_dest, + ); + if let Some(log) = &log { + log.step(&format!("META {rel:?} (embedded) -> {meta_dest:?}")); + } + } + report_outcome = Some(InputStatus::Ok); + } + crate::android::EntryStatus::NotTarget + | crate::android::EntryStatus::Unchanged => { + s.skipped += 1; + report_outcome = Some(InputStatus::Skipped); } - report_outcome = Some(InputStatus::Ok); } - crate::android::EntryStatus::NotTarget | crate::android::EntryStatus::Unchanged => { - s.skipped += 1; - report_outcome = Some(InputStatus::Skipped); - } - }, + } Ok(Err(e)) => { s.errors += 1; crate::ui::err(&bar, suppress_file_lines, &rel, &e); @@ -449,8 +481,10 @@ fn run_folder_inner( && let Some(status) = report_outcome { let mut reported = android_library_input(&scoped.path, status, &dest, started); + reported.analysis_incomplete = report_incomplete; apply_android_validation(&mut reported, report_validation.as_ref()); - reporter.push(reported); + reported.android_research = report_research; + reporter.push(inspect_status_if_research(reported, research)); } bar.inc(1); } @@ -463,14 +497,23 @@ fn run_folder_inner( for group in &package_groups { if group.len() > 1 { s.packages += group.len(); - let group_owned = group.clone(); - let root_owned = root.to_path_buf(); + // Relative output paths are computed here, by the same helper the + // rest of the driver uses: they must stay relative so joining them + // under the output root cannot escape it. + let rels: Vec = group + .iter() + .map(|package| rel_in_tree(root, package).into_owned()) + .collect(); + let members: Vec<(&Path, &Path)> = group + .iter() + .map(|package| package.as_path()) + .zip(rels.iter().map(|rel| rel.as_path())) + .collect(); let out_root_owned = out_root.clone(); let group_started = Instant::now(); let result = senbei_engine::catch_unwind_quiet(|| { crate::android::restore_apk_group( - &group_owned, - &root_owned, + &members, &out_root_owned, &mut android_cache, verbose_steps, @@ -490,7 +533,12 @@ fn run_folder_inner( .iter() .filter(|outcome| outcome.label.starts_with(&prefix)) .collect(); - reporter.push(package_input(package, entries, group_started)); + reporter.push(package_input( + package, + entries, + package_inventory(package, limits, research).as_ref(), + group_started, + )); } } apply_package_outcomes(outcomes, &mut s, &bar, suppress_file_lines, &log); @@ -501,16 +549,37 @@ fn run_folder_inner( if let Some(log) = &log { log.step(&format!("ERR {rel:?}: {e:#}")); } + // The failure belongs to the group, but the report is + // per-split: each member names the cause once, and the + // group is not counted again per restore phase. + if let Some(reporter) = reporter.as_deref_mut() { + for package in group { + let mut reported = failed_input(package, &e, group_started); + reported.android_research = crate::android::error_research(&e) + .and_then(|capture| match capture { + crate::android::ResearchCapture::Library(report) => { + Some(report.clone()) + } + crate::android::ResearchCapture::Metadata(_) => None, + }); + reporter.push(reported); + } + } } Err(panic) => { - let e = anyhow::anyhow!("unexpected panic: {}", panic_payload(&panic)); + let e = anyhow::anyhow!( + "unexpected panic during package restore: {}", + panic_payload(&panic) + ); s.errors += 1; crate::ui::err(&bar, suppress_file_lines, &rel, &e); if let Some(log) = &log { - log.step(&format!( - "ERR {rel:?}: panic during package restore: {}", - panic_payload(&panic) - )); + log.step(&format!("ERR {rel:?}: {e:#}")); + } + if let Some(reporter) = reporter.as_deref_mut() { + for package in group { + reporter.push(failed_input(package, &e, group_started)); + } } } } @@ -536,7 +605,12 @@ fn run_folder_inner( match result { Ok(Ok(outcomes)) => { if let Some(reporter) = reporter.as_deref_mut() { - reporter.push(package_input(package, outcomes.iter().collect(), started)); + reporter.push(package_input( + package, + outcomes.iter().collect(), + package_inventory(package, limits, research).as_ref(), + started, + )); } apply_package_outcomes(outcomes, &mut s, &bar, suppress_file_lines, &log); } @@ -610,7 +684,9 @@ fn run_folder_inner( )); } if let Some(reporter) = reporter.as_deref_mut() { - reporter.push(metadata_input(&scoped.path, &report, Some(&dest), started)); + let mut reported = metadata_input(&scoped.path, &report, Some(&dest), started); + reported.metadata_research = report.research.clone(); + reporter.push(inspect_status_if_research(reported, research)); } } // Recognised metadata that needed no change (not -GMD-obfuscated): @@ -624,7 +700,9 @@ fn run_folder_inner( )); } if let Some(reporter) = reporter.as_deref_mut() { - reporter.push(metadata_input(&scoped.path, &report, None, started)); + let mut reported = metadata_input(&scoped.path, &report, None, started); + reported.metadata_research = report.research.clone(); + reporter.push(inspect_status_if_research(reported, research)); } } Ok(Err(e)) => { @@ -658,27 +736,12 @@ fn run_folder_inner( } } if let Some(reporter) = reporter.as_deref_mut() { - let mut input = failed_input(&scoped.path, &e, started); - let identity = identity_of(&scoped.path); - input.metadata = identity; - input.metadata_version = - unsupported.or_else(|| identity.map(|identity| identity.raw_version)); - if let Some(version) = unsupported { - // Left untouched by design; not a failure of this run. - input.status = InputStatus::Skipped; - input.errors.clear(); - input.profile = Some(crate::report::metadata_unchanged_profile(identity)); - input.warning(format!( - "unsupported metadata version {version}, left untouched" - )); - } else { - input.profile = Some(crate::report::metadata_failed_profile( - identity, - senbei_engine::LayoutKind::MetadataStructural, - &format!("{e:#}"), - )); - } - reporter.push(input); + reporter.push(metadata_failure_input( + &scoped.path, + &e, + unsupported, + started, + )); } } Err(panic) => { @@ -793,6 +856,11 @@ fn run_file_inner( let name = out_name(Path::new(input.file_name().unwrap_or_default())); let dest = out_root.join(name); let mut s = Summary::default(); + // Research inspection runs this same driver and reads its results as + // observations; everything else keeps the ordinary classification. + let research = reporter + .as_deref() + .is_some_and(|reporter| reporter.mode() == Mode::Inspect); let prefix = { use std::io::Read; @@ -816,8 +884,8 @@ fn run_file_inner( let is_android_package = !is_android_so && crate::android::is_app_package(input, &prefix); if is_meta { - match deobfuscate_metadata_to_with_module(input, &dest, verbose && quiet == 0, None) { - Ok((report, layout)) if report.remapped > 0 => { + match deobfuscate_metadata_researched(input, &dest, verbose && quiet == 0, research, None) { + Ok((report, layout, metadata_research)) if report.remapped > 0 => { s.metadata = 1; if let Some(log) = &log { log.step(&format!( @@ -832,16 +900,13 @@ fn run_file_inner( ); } if let Some(reporter) = reporter.as_deref_mut() { - reporter.push(single_metadata_input( - input, - &report, - layout, - Some(&dest), - t0, - )); + let mut reported = + single_metadata_input(input, &report, layout, Some(&dest), research, t0); + reported.metadata_research = metadata_research; + reporter.push(inspect_status_if_research(reported, research)); } } - Ok((report, layout)) => { + Ok((report, layout, metadata_research)) => { if let Some(log) = &log { log.step(&format!( "META {:?}: v{} already de-obfuscated", @@ -855,7 +920,10 @@ fn run_file_inner( ); } if let Some(reporter) = reporter.as_deref_mut() { - reporter.push(single_metadata_input(input, &report, layout, None, t0)); + let mut reported = + single_metadata_input(input, &report, layout, None, research, t0); + reported.metadata_research = metadata_research; + reporter.push(inspect_status_if_research(reported, research)); } } Err(e) => { @@ -868,27 +936,38 @@ fn run_file_inner( eprintln!("error: {e:#}"); } if let Some(reporter) = reporter.as_deref_mut() { - let mut input_report = failed_input(input, &e, t0); - let identity = identity_of(input); - input_report.metadata = identity; - input_report.metadata_version = identity.map(|identity| identity.raw_version); - input_report.profile = Some(crate::report::metadata_failed_profile( - identity, - senbei_engine::LayoutKind::MetadataStructural, - &format!("{e:#}"), - )); - reporter.push(input_report); + let unsupported = unsupported_version(&e); + reporter.push(metadata_failure_input(input, &e, unsupported, t0)); } } } } else if is_android_so { - match crate::android::restore_so_file_with_diagnostics( - input, - &dest, - verbose && quiet == 0, - limits, - ) { - Ok((embedded, validation)) => { + let restore = if research { + crate::android::restore_so_file_researched( + input, + &dest, + verbose && quiet == 0, + limits, + research, + ) + .map(|restored| { + ( + restored.embedded_metadata, + restored.validation, + restored.research, + ) + }) + } else { + crate::android::restore_so_file_with_diagnostics( + input, + &dest, + verbose && quiet == 0, + limits, + ) + .map(|(embedded, validation)| (embedded, validation, None)) + }; + match restore { + Ok((embedded, validation, android_research)) => { s.unpacked = 1; if let Some(log) = &log { log.step(&format!("OK {:?} -> {:?} (Android SO)", input, dest)); @@ -924,7 +1003,8 @@ fn run_file_inner( if let Some(reporter) = reporter.as_deref_mut() { let mut reported = android_library_input(input, InputStatus::Ok, &dest, t0); apply_android_validation(&mut reported, validation.as_ref()); - reporter.push(reported); + reported.android_research = android_research; + reporter.push(inspect_status_if_research(reported, research)); } } Err(e) => { @@ -936,7 +1016,23 @@ fn run_file_inner( eprintln!("error: {e:#}"); } if let Some(reporter) = reporter.as_deref_mut() { - reporter.push(android_library_input(input, InputStatus::Error, &dest, t0)); + let mut reported = android_library_input_with_error( + input, + InputStatus::Error, + &dest, + t0, + Some(&e), + ); + // A restore that failed after extraction keeps what the + // extraction already reported. + reported.android_research = + crate::android::error_research(&e).and_then(|capture| match capture { + crate::android::ResearchCapture::Library(report) => { + Some(report.clone()) + } + crate::android::ResearchCapture::Metadata(_) => None, + }); + reporter.push(inspect_status_if_research(reported, research)); } } } @@ -944,18 +1040,24 @@ fn run_file_inner( s.packages = 1; let rel = PathBuf::from(input.file_name().unwrap_or_default()); let mut seen = std::collections::HashSet::new(); - match crate::android::restore_package_with_limits( + match crate::android::restore_package_with_limits_and_research( input, &rel, &out_root, &mut seen, verbose && quiet == 0, limits, + research, ) { Ok(outcomes) => { let bar = crate::ui::progress(0, true); if let Some(reporter) = reporter.as_deref_mut() { - reporter.push(package_input(input, outcomes.iter().collect(), t0)); + reporter.push(package_input( + input, + outcomes.iter().collect(), + package_inventory(input, limits, research).as_ref(), + t0, + )); } apply_package_outcomes(outcomes, &mut s, &bar, quiet >= 1, &log); } @@ -974,16 +1076,19 @@ fn run_file_inner( } } else { // A reporting run uses the profiled entry point so the report carries - // the route that was actually selected; the unprofiled call is - // unchanged for every other run. - let profiled = if reporter.is_some() { - Some(unpack_one_profiled(input, &dest, verbose && quiet == 0)) - } else { - None - }; - let (profile, result) = match profiled { - Some((profile, result)) => (Some(profile), result), - None => (None, unpack_one_v(input, &dest, verbose && quiet == 0)), + // the route that was actually selected; a research run keeps its + // structural facts too. The unprofiled call is unchanged otherwise. + let (profile, observed, result) = match reporter.is_some() { + true => { + let (profile, observed, result) = + unpack_one_researched(input, &dest, verbose && quiet == 0, research); + (Some(profile), observed, result) + } + false => ( + None, + None, + unpack_one_v(input, &dest, verbose && quiet == 0), + ), }; match result { Ok((kind, report)) => { @@ -1011,7 +1116,9 @@ fn run_file_inner( } } if let Some(reporter) = reporter.as_deref_mut() { - reporter.push(windows_input(input, &dest, kind, &report, profile, t0)); + let mut reported = windows_input(input, &dest, kind, &report, profile, t0); + apply_windows_research(&mut reported, observed); + reporter.push(inspect_status_if_research(reported, research)); } } Err(e) => { @@ -1023,10 +1130,12 @@ fn run_file_inner( eprintln!("error: {e:#}"); } if let Some(reporter) = reporter { - reporter.push(match profile { + let mut reported = match profile { Some(profile) => failed_input_with_profile(input, &e, profile, t0), None => failed_input(input, &e, t0), - }); + }; + apply_windows_research(&mut reported, observed); + reporter.push(inspect_status_if_research(reported, research)); } } } @@ -1133,14 +1242,32 @@ fn deobfuscate_metadata_to_with_module( verbose: bool, method_index_module: Option<&[u8]>, ) -> anyhow::Result<(senbei_metadata::Report, senbei_engine::LayoutKind)> { + let (report, layout, _) = + deobfuscate_metadata_researched(input, dest, verbose, false, method_index_module)?; + Ok((report, layout)) +} + +/// [`deobfuscate_metadata_to_with_module`], optionally keeping what the +/// transform observed (tried seeds, discovery, its own report). +fn deobfuscate_metadata_researched( + input: &Path, + dest: &Path, + verbose: bool, + research: bool, + method_index_module: Option<&[u8]>, +) -> anyhow::Result<( + senbei_metadata::Report, + senbei_engine::LayoutKind, + Option, +)> { let data = std::fs::read(input)?; // The Android seeded-permutation variant is tried first (it validates // every restored RID); the structural remap is the fallback and the // Windows path. The [`senbei_metadata::Error`] is preserved in the chain // (rather than stringified) so the folder driver can apply its // unsupported-version policy. - let (out, report, layout) = - crate::android::restore_metadata_bytes_with_module(&data, method_index_module) + let (out, report, layout, metadata_research) = + crate::android::restore_metadata_with_module(&data, method_index_module, research) .map_err(|e| e.context(format!("{input:?}")))?; if report.remapped > 0 { if let Some(parent) = dest.parent() { @@ -1151,7 +1278,7 @@ fn deobfuscate_metadata_to_with_module( println!("Write to {}", dest.display()); } } - Ok((report, layout)) + Ok((report, layout, metadata_research)) } /// Write an embedded metadata blob (unwrapped from a restored Android @@ -1234,74 +1361,154 @@ fn apply_package_outcomes( // Inspect and dry-run drivers // --------------------------------------------------------------------------- -/// Inspect `path` without recovering or writing anything. +/// Inspect `path`: run the real static recovery and report everything it saw. /// -/// Reads only what detection needs: a short prefix per file, the protected -/// library probe for selected `.so` files, package manifests and central -/// directories, and the 8-byte il2cpp metadata header. No output, no log, and -/// no temporary file outside what a package inventory needs to read a nested -/// manifest. The report never claims recovery or a static-validation verdict. +/// Inspection is the research mode, so it runs the ordinary drivers — same +/// scan, same routing, same trial-and-validate layout selection, same Android +/// application context and deduplication — into a temporary directory that is +/// dropped afterwards. No output survives, no log is written, and the input +/// binary is never executed. The report therefore describes attempts that +/// really ran, plus the structural facts the engines published for them. pub fn inspect_path( path: &Path, scan_all: bool, limits: &senbei_engine::android::ResourceLimits, ) -> anyhow::Result { let mut collector = Collector::new(Mode::Inspect); + let workspace = tempfile::tempdir()?; + let out_dir = workspace.path().to_path_buf(); if path.is_dir() { - inspect_folder(path, scan_all, limits, &mut collector); + run_folder_inner( + path, + Some(&out_dir), + 2, + false, + true, + scan_all, + limits, + Some(&mut collector), + )?; } else { - let started = Instant::now(); - match inspect_file(path, limits) { - Ok(input) => collector.push(input), - Err(error) => collector.push(inspect_failed_input(path, &error, started)), - } + run_file_inner( + path, + Some(&out_dir), + 2, + false, + true, + limits, + Some(&mut collector), + )?; } Ok(collector.finish()) } -fn inspect_folder( - root: &Path, - scan_all: bool, - limits: &senbei_engine::android::ResourceLimits, - collector: &mut Collector, -) { - let scan = crate::scan::find_targets_with_limits(root, scan_all, limits); - collector.set_scan(crate::report::ScanReport { - non_target_skipped: scan.stats.skipped, - walk_errors: scan.stats.walk_errors, - probe_errors: scan.stats.probe_errors, - }); - let mut inputs: Vec<&PathBuf> = Vec::new(); - inputs.extend(scan.crackproof.iter()); - inputs.extend(scan.metadata.iter()); - inputs.extend(scan.android_so.iter()); - inputs.extend(scan.android_packages.iter()); - for path in inputs { - let started = Instant::now(); - match inspect_file(path, limits) { - Ok(input) => collector.push(input), - Err(error) => collector.push(inspect_failed_input(path, &error, started)), - } +/// Restate one driver report as an inspection observation. +/// +/// The drivers classify an input by what they did with it. Inspection asks a +/// different question — "what is this, and what happened when it was tried" — +/// so a recognised target stays `recognized` whether recovery succeeded, +/// failed, or found nothing to change. Only a genuine read or infrastructure +/// failure is an error, and a recovery failure is a research finding rather +/// than a failed inspection. +/// Restate a driver report as an inspection observation when the run is a +/// research inspection; leave an ordinary unpack report untouched. +fn inspect_status_if_research(input: InputReport, research: bool) -> InputReport { + if research { + inspect_status(input) + } else { + input } } -/// Inspect one file, choosing the report from its content. -fn inspect_file( - input: &Path, - limits: &senbei_engine::android::ResourceLimits, -) -> anyhow::Result { - let started = Instant::now(); - let prefix = read_prefix(input)?; - if senbei_metadata::is_metadata(&prefix) { - return Ok(inspect_metadata(input, &prefix, started)); +/// Record what a research unpack observed on a Windows input report. +fn apply_windows_research(report: &mut InputReport, observed: Option) { + let Some(observed) = observed else { + return; + }; + report.source = Some(observed.source); + if let Some(companion) = report.companion.as_mut() { + // The sibling's identity, from the bytes the pipeline already read. + companion.source = observed.companion; } - if crate::android::is_app_package(input, &prefix) { - return inspect_app_package(input, limits, started); + report.research = observed.report; + // The digest describes bytes that were produced and then dropped; the file + // itself is never kept, which `Collector` states on the output stage. + report.recovered = observed.recovered; +} + +fn inspect_status(mut input: InputReport) -> InputReport { + // A file that cannot be read was never inspected: that is a real failure, + // not a finding about the protection. + if read_prefix(Path::new(&input.path)).is_err() { + input.status = InputStatus::Error; + return input; } - if crate::android::is_elf64_aarch64(&prefix) { - return inspect_android_library(input, limits, started); + // A container is incomplete when any of its entries was. + input.analysis_incomplete |= input.entries.iter().any(|entry| entry.analysis_incomplete); + let recognition = input.profile.as_ref().map(|profile| profile.recognition); + let container_target = input.entries.iter().any(|entry| { + matches!( + entry.status, + EntryStatus::Restored + | EntryStatus::Unchanged + | EntryStatus::Duplicate + | EntryStatus::Error + ) + }); + let recognized = match recognition { + Some(senbei_engine::RecognitionStatus::Recognized) => true, + // A container has no single profile: any entry that was probed and + // acted on says the container held a target. + None => container_target, + _ => false, + }; + if input.analysis_incomplete { + // The analysis stopped on an I/O or resource failure before it could + // conclude anything. A known target does not make a truncated analysis + // complete, so this stays an error with its reason. + input.status = InputStatus::Error; + } else if recognized { + // A recovery that ran and failed is a finding about a real target, not + // a failed inspection. + input.status = InputStatus::Recognized; + } else { + // A plain non-target: the driver calls that an error because it could + // not unpack it, but inspection only observed that there is no target. + input.status = InputStatus::Skipped; } - inspect_windows(input, started) + input +} + +/// Whether a failure stopped the analysis before it could describe the input. +/// +/// A candidate route that simply did not apply is a research finding. An I/O +/// failure, a resource ceiling, or a broken container means the analysis never +/// reached a conclusion, and calling that "recognized" would claim more than +/// was established. Classification is by error type, never by message text. +pub(crate) fn analysis_incomplete(error: &anyhow::Error) -> bool { + error.chain().any(|cause| { + if cause.downcast_ref::().is_some() { + return true; + } + if cause + .downcast_ref::() + .is_some() + { + return true; + } + // The Android engines wrap limits and I/O in their own error types; + // their source chains are walked by `chain()` above, and the direct + // variants are caught here. + matches!( + cause.downcast_ref::(), + Some(senbei_engine::android::ExtractionError::Io { .. }) + | Some(senbei_engine::android::ExtractionError::Limit(_)) + ) || matches!( + cause.downcast_ref::(), + Some(senbei_engine::android::RestoreError::Io { .. }) + | Some(senbei_engine::android::RestoreError::Limit(_)) + ) + }) } fn read_prefix(path: &Path) -> anyhow::Result> { @@ -1313,182 +1520,6 @@ fn read_prefix(path: &Path) -> anyhow::Result> { Ok(buffer) } -/// Inspect a Windows input without recovering it. -/// -/// The stub and its optional `._` sibling are read separately and independently: -/// inspection reports the pairing it observed and never turns a missing or -/// non-pairing sibling into a recovery failure. That matters because the file -/// entry point *does* refuse a companion-declaring stub without its payload — -/// correct for recovery, wrong for a description of what is on disk. -fn inspect_windows(input: &Path, started: Instant) -> anyhow::Result { - // The stub's own bytes must be readable for inspection to say anything. - // Failure here is a genuine read error and fails inspection. - let stub = std::fs::read(input)?; - let (companion, state) = if crate::windows::is_pe_extension(input) { - match read_optional_companion(input) { - // A sibling pairs only when its header matches this stub's payload - // region; `splice_companion` is that exact test. - Ok(Some(payload)) => { - if crate::windows::splice_companion(&stub, &payload).is_some() { - (Some(payload), CompanionState::Spliced) - } else { - // A sibling exists but is not this stub's payload. - (Some(payload), CompanionState::Unmatched) - } - } - Ok(None) => (None, CompanionState::Absent), - // A sibling exists but cannot be read. Inspection still describes - // the stub; the unreadable sibling is reported, not raised. - Err(_) => (None, CompanionState::Unreadable), - } - } else { - (None, CompanionState::Absent) - }; - - // Inspect the bytes recovery would actually unpack: the spliced payload - // when the pairing is real, otherwise the file as it sits on disk. - let spliced_pair = match (state, companion.as_deref()) { - (CompanionState::Spliced, Some(payload)) => { - crate::windows::splice_companion(&stub, payload) - } - _ => None, - }; - let inspected: &[u8] = spliced_pair.as_deref().unwrap_or(&stub); - - let mut profile = senbei_engine::inspect_profile(inspected); - if spliced_pair.is_some() { - // Evidence of a pairing that was actually performed, not of one that - // was merely expected. - profile.record_companion_spliced(); - } - let mut report = InputReport::new(input, Role::Content); - report.status = match profile.recognition { - senbei_engine::RecognitionStatus::Recognized => InputStatus::Recognized, - _ => InputStatus::Skipped, - }; - report.companion = - crate::windows::is_pe_extension(input).then(|| companion_report(input, state)); - // A sibling that does not pair, or cannot be read, describes the input — - // neither is a failure of the inspection. - if let Some(companion) = report.companion.as_mut() { - match companion.state { - CompanionState::Unmatched => { - companion.detail = - Some("a sibling `._` exists but is not this stub's payload".to_owned()); - } - CompanionState::Unreadable => { - companion.detail = Some("the sibling `._` could not be read".to_owned()); - } - _ => {} - } - } - report.profile = Some(profile); - report.stages = vec![ - StageReport::new(Stage::Detection, StageStatus::Ok).timed(crate::report::now_ms(started)), - StageReport::new(Stage::Recovery, StageStatus::Skipped) - .detail("inspection only: no recovery was run"), - ]; - report.duration_ms = crate::report::now_ms(started); - Ok(report) -} - -/// Companion state for a run that only knows whether a payload was spliced. -/// -/// `Spliced` means the pairing actually happened; otherwise any sibling on disk -/// was not this stub's payload. -fn observed_companion_state(input: &Path, spliced: bool) -> CompanionState { - if spliced { - return CompanionState::Spliced; - } - match sibling_path(input) { - Some(path) if path.is_file() => CompanionState::Unmatched, - _ => CompanionState::Absent, - } -} - -/// `._`, the companion payload path for `input`. -fn sibling_path(input: &Path) -> Option { - let name = input.file_name()?; - let mut sibling = name.to_os_string(); - sibling.push("._"); - Some(input.with_file_name(sibling)) -} - -/// What the `._` companion relationship is for `input`, observed on disk. -fn companion_report(input: &Path, state: CompanionState) -> CompanionReport { - let path = sibling_path(input); - CompanionReport { - state, - path: match state { - CompanionState::Absent => None, - _ => path.map(|path| path.display().to_string()), - }, - detail: None, - } -} - -fn inspect_metadata(input: &Path, prefix: &[u8], started: Instant) -> InputReport { - let mut report = InputReport::new(input, Role::Content); - let identity = senbei_metadata::identify(prefix); - report.metadata = identity; - report.metadata_version = identity.map(|identity| identity.raw_version); - // Header identification is a layout/capability fact, not a protection or - // recovery verdict. - report.status = InputStatus::Skipped; - report.profile = Some(crate::report::metadata_unchanged_profile(identity)); - report.stages = vec![ - StageReport::new(Stage::Detection, StageStatus::Ok).timed(crate::report::now_ms(started)), - StageReport::new(Stage::Recovery, StageStatus::Skipped) - .detail("inspection only: no transform was run"), - ]; - report.duration_ms = crate::report::now_ms(started); - report -} - -fn inspect_android_library( - input: &Path, - limits: &senbei_engine::android::ResourceLimits, - started: Instant, -) -> anyhow::Result { - let (profile, result) = crate::android::probe_so_profiled(input, limits)?; - let mut report = InputReport::new(input, Role::Content); - report.status = match (&profile.recognition, &result) { - (senbei_engine::RecognitionStatus::Recognized, _) => InputStatus::Recognized, - _ => InputStatus::Skipped, - }; - if let Err(error) = &result { - report.error(format!("{error:#}")); - report.status = InputStatus::Error; - } - report.profile = Some(profile); - report.stages = vec![ - StageReport::new(Stage::Detection, StageStatus::Ok).timed(crate::report::now_ms(started)), - StageReport::new(Stage::Recovery, StageStatus::Skipped) - .detail("inspection only: no restore was run"), - ]; - report.duration_ms = crate::report::now_ms(started); - Ok(report) -} - -fn inspect_app_package( - input: &Path, - limits: &senbei_engine::android::ResourceLimits, - started: Instant, -) -> anyhow::Result { - let mut report = InputReport::new(input, Role::Container); - let container = crate::android::inspect_package(input, limits)?; - report.status = InputStatus::Skipped; - report.container = Some(container); - report.stages = vec![ - StageReport::new(Stage::ManifestInventory, StageStatus::Ok) - .timed(crate::report::now_ms(started)), - StageReport::new(Stage::EntryProbe, StageStatus::Skipped) - .detail("inspection only: container entries were listed, not probed"), - ]; - report.duration_ms = crate::report::now_ms(started); - Ok(report) -} - /// Run the real recovery and keep nothing. /// /// The recovery path is the ordinary one — same routing, same trial-and-validate @@ -1556,6 +1587,39 @@ pub fn unpack_one_profiled( ) -> ( senbei_engine::ProtectionProfile, anyhow::Result<(senbei_engine::Kind, senbei_engine::IntegrityReport)>, +) { + let (profile, _, result) = unpack_one_researched(input, dest, verbose, false); + (profile, result) +} + +/// What a reporting unpack observed from the bytes it already had in hand. +pub(crate) struct UnpackResearch { + /// Identity of the physical input file, never of a synthetic spliced view. + pub source: Digest, + /// Identity of the `._` sibling whose bytes were read for pairing. + pub companion: Option, + /// Structural research, kept only when the run asked for it. + pub report: Option, + /// Identity of the recovered image, which is discarded rather than written. + pub recovered: Option, +} + +/// [`unpack_one_profiled`], optionally keeping the structural inspection of +/// both the protected input and the image recovery produced. +/// +/// The recovery itself is the ordinary one and runs exactly once: the trace +/// sink only records what the pipeline publishes. Research mode inspects the +/// same bytes recovery used (the spliced view when a companion paired) and the +/// restored image before its bytes are dropped. +fn unpack_one_researched( + input: &Path, + dest: &Path, + verbose: bool, + research: bool, +) -> ( + senbei_engine::ProtectionProfile, + Option, + anyhow::Result<(senbei_engine::Kind, senbei_engine::IntegrityReport)>, ) { // Read the stub and its `._` sibling exactly as the file entry point does. let (stub, companion) = match read_stub_and_companion(input) { @@ -1564,30 +1628,87 @@ pub fn unpack_one_profiled( let mut profile = observed_profile(input); profile.recovery = senbei_engine::RecoveryStatus::Blocked; profile.push_error(format!("{error:#}")); - return (profile, Err(error)); + return (profile, None, Err(error)); } }; + // The bytes recovery will actually see. A companion that pairs replaces + // the stub's payload region; anything else leaves the file as it is. + let spliced = companion + .as_deref() + .and_then(|payload| crate::windows::splice_companion(&stub, payload)); + let (view, input_view) = match spliced.as_deref() { + Some(view) => (view, crate::report::ResearchInputView::SplicedCompanion), + None => (stub.as_slice(), crate::report::ResearchInputView::Original), + }; + let inspected = research.then(|| senbei_engine::inspect_research(view)); + // Identity of the file as it sits on disk, before any splice, and of the + // sibling whose bytes were read for pairing. Both hash bytes already in + // memory: the report must never read a companion a second time. + let source = Digest::of(&stub); + let companion_digest = companion.as_deref().map(Digest::of); // The byte entry point owns the splice, companion overlays, and the check // over the image actually returned — the same steps as `unpack_one_v`. - let (profile, recovered) = - crate::windows::unpack_bytes_profiled_v(&stub, companion.as_deref(), verbose); + // The trace sink only observes, and only a research run asks for it. + let (trace, (profile, recovered)) = if research { + let (trace, outcome) = senbei_engine::with_research_trace(|| { + crate::windows::unpack_bytes_profiled_v(&stub, companion.as_deref(), verbose) + }); + (Some(trace), outcome) + } else { + ( + None, + crate::windows::unpack_bytes_profiled_v(&stub, companion.as_deref(), verbose), + ) + }; let image = match recovered { Ok(image) => image, // The profile already records which candidates ran and why they failed. - Err(error) => return (profile, Err(error.into())), + Err(error) => { + let observed = Some(UnpackResearch { + source, + companion: companion_digest, + report: match (inspected, trace) { + (Some(input), Some(trace)) => Some(crate::report::WindowsResearchReport { + input_view, + input, + restored: None, + trace, + }), + _ => None, + }, + recovered: None, + }); + return (profile, observed, Err(error.into())); + } }; + // Inspect the post-overlay image now, while its bytes are still here, then + // let them go: research inspection never keeps a recovered file. + let observed = Some(UnpackResearch { + source, + companion: companion_digest, + report: match (inspected, trace) { + (Some(input), Some(trace)) => Some(crate::report::WindowsResearchReport { + input_view, + input, + restored: Some(senbei_engine::inspect_research(&image.bytes)), + trace, + }), + _ => None, + }, + recovered: Some(Digest::of(&image.bytes)), + }); if let Some(parent) = dest.parent() && let Err(error) = std::fs::create_dir_all(parent) { - return (profile, Err(error.into())); + return (profile, observed, Err(error.into())); } if let Err(error) = write_atomic(dest, &image.bytes) { - return (profile, Err(error.into())); + return (profile, observed, Err(error.into())); } if verbose { println!("Write to {}", dest.display()); } - (profile, Ok((image.kind, image.integrity))) + (profile, observed, Ok((image.kind, image.integrity))) } /// The input's bytes and its `._` companion payload, when one exists. @@ -1627,6 +1748,88 @@ fn read_stub_and_companion(input: &Path) -> anyhow::Result<(Vec, Option._`, the companion payload path for `input`. +fn sibling_path(input: &Path) -> Option { + let name = input.file_name()?; + let mut sibling = name.to_os_string(); + sibling.push("._"); + Some(input.with_file_name(sibling)) +} + +/// Outcome of looking for `._`, with the bytes when there were any. +/// +/// The bytes are kept so the report can name the sibling's identity without +/// reading it a second time; a `._` that exists but cannot be read is its own +/// state, never a mismatch. +pub(crate) enum CompanionProbe { + Absent, + Read(Vec), + Unreadable(String), +} + +pub(crate) fn probe_companion(input: &Path) -> CompanionProbe { + let Some(path) = sibling_path(input) else { + return CompanionProbe::Absent; + }; + match std::fs::read(&path) { + Ok(bytes) => CompanionProbe::Read(bytes), + Err(error) if error.kind() == std::io::ErrorKind::NotFound => CompanionProbe::Absent, + // A directory, a lock, or a permission problem: the sibling is there, + // but its bytes were never seen, so it must not be called a mismatch. + Err(error) => CompanionProbe::Unreadable(format!("{error}")), + } +} + +/// Companion state for a run that only knows whether a payload was spliced. +/// +/// `Spliced` means the pairing actually happened. Otherwise the sibling is +/// reported for what it is: unreadable if it could not be read, unmatched when +/// its bytes exist but do not pair with this stub, absent when there is none. +pub(crate) fn observed_companion_state( + input: &Path, + spliced: bool, +) -> (CompanionState, Option, Option) { + if spliced { + return (CompanionState::Spliced, None, None); + } + match probe_companion(input) { + CompanionProbe::Absent => (CompanionState::Absent, None, None), + CompanionProbe::Read(bytes) => (CompanionState::Unmatched, Some(Digest::of(&bytes)), None), + CompanionProbe::Unreadable(reason) => (CompanionState::Unreadable, None, Some(reason)), + } +} + +/// What the `._` companion relationship is for `input`, observed on disk. +/// +/// `source` is the identity of a sibling whose bytes were seen. `Unreadable` +/// carries no identity because none were: a digest of nothing would be a lie. +pub(crate) fn companion_report( + input: &Path, + state: CompanionState, + source: Option, + unreadable: Option, +) -> CompanionReport { + let path = sibling_path(input); + CompanionReport { + state, + path: match state { + CompanionState::Absent => None, + _ => path.map(|path| path.display().to_string()), + }, + detail: match state { + CompanionState::Unmatched => { + Some("a sibling `._` exists but is not this stub's payload".to_owned()) + } + CompanionState::Unreadable => Some(match unreadable { + Some(reason) => format!("the sibling `._` could not be read: {reason}"), + None => "the sibling `._` could not be read".to_owned(), + }), + _ => None, + }, + source, + } +} + /// Input report for a Windows PE whose outcome a profiled run reported. fn windows_input( input: &Path, @@ -1644,10 +1847,9 @@ fn windows_input( }; let profile = profile.unwrap_or_else(|| recovered_profile(kind, report)); entry.companion = crate::windows::is_pe_extension(input).then(|| { - companion_report( - input, - observed_companion_state(input, profile.observed.external_companion), - ) + let (state, source, unreadable) = + observed_companion_state(input, profile.observed.external_companion); + companion_report(input, state, source, unreadable) }); entry.profile = Some(profile); entry.outputs = vec![OutputFile::from_path(dest)]; @@ -1716,6 +1918,7 @@ fn recovered_profile( fn failed_input(input: &Path, error: &anyhow::Error, started: Instant) -> InputReport { let mut entry = InputReport::new(input, Role::Content); entry.status = InputStatus::Error; + entry.analysis_incomplete = analysis_incomplete(error); let detail = format!("{error:#}"); entry.error(detail.clone()); entry.profile = Some(failure_profile(input, &detail)); @@ -1738,13 +1941,13 @@ fn failed_input_with_profile( ) -> InputReport { let mut entry = InputReport::new(input, Role::Content); entry.status = InputStatus::Error; + entry.analysis_incomplete = analysis_incomplete(error); let detail = format!("{error:#}"); entry.error(detail.clone()); entry.companion = crate::windows::is_pe_extension(input).then(|| { - companion_report( - input, - observed_companion_state(input, profile.observed.external_companion), - ) + let (state, source, unreadable) = + observed_companion_state(input, profile.observed.external_companion); + companion_report(input, state, source, unreadable) }); entry.profile = Some(profile); entry @@ -1754,27 +1957,6 @@ fn failed_input_with_profile( entry } -/// Input report for an input inspection could not read. -/// -/// Inspection is detection only, so a read error must not be dressed up as a -/// failed recovery: no candidate is marked attempted, `recovery` stays -/// `not_attempted`, `static_validation` stays `not_run`, and no route is -/// selected. Whatever header evidence was obtainable is still reported. -fn inspect_failed_input(input: &Path, error: &anyhow::Error, started: Instant) -> InputReport { - let mut entry = InputReport::new(input, Role::Content); - entry.status = InputStatus::Error; - let detail = format!("{error:#}"); - entry.error(detail.clone()); - let mut profile = observed_profile(input); - profile.push_error(detail.clone()); - entry.profile = Some(profile); - entry - .stages - .push(StageReport::new(Stage::Detection, StageStatus::Failed).detail(detail)); - entry.duration_ms = crate::report::now_ms(started); - entry -} - /// Best-effort observation of an input whose inspection failed. /// /// Reads only what detection reads. Recognition and the routes that *would* be @@ -1886,14 +2068,27 @@ fn failure_profile(input: &Path, detail: &str) -> senbei_engine::ProtectionProfi } /// Input report for a restored (or skipped) loose Android library. -fn android_library_input( +pub(crate) fn android_library_input( input: &Path, status: InputStatus, dest: &Path, started: Instant, +) -> InputReport { + android_library_input_with_error(input, status, dest, started, None) +} + +/// [`android_library_input`], also recording whether the failure was a resource +/// or I/O ceiling rather than an ordinary candidate rejection. +fn android_library_input_with_error( + input: &Path, + status: InputStatus, + dest: &Path, + started: Instant, + error: Option<&anyhow::Error>, ) -> InputReport { let mut entry = InputReport::new(input, Role::Content); entry.status = status; + entry.analysis_incomplete = error.is_some_and(analysis_incomplete); match status { InputStatus::Ok => { entry.profile = Some(crate::report::android_recovered_profile()); @@ -1954,6 +2149,35 @@ fn apply_android_validation( report.stages.push(stage); } +/// Profile for a metadata blob whose transform ran, validated, and needed no +/// change. +/// +/// The route was really taken and the bytes really validated, so the attempt is +/// recorded — but a clean blob is no protection evidence, so recognition stays +/// `not_recognized` and no protection verdict is claimed. Without this an +/// inspection of an already-clean blob would say `not_attempted` while the +/// research section next to it showed the route and its report. +fn metadata_validated_unchanged_profile( + identity: Option, + route: senbei_engine::LayoutKind, +) -> senbei_engine::ProtectionProfile { + use senbei_engine::{AttemptOutcome, LayoutAttempt, ProtectionProfile}; + let mut profile = ProtectionProfile::new(senbei_engine::ObservedTarget::metadata( + identity.map(|identity| identity.raw_version), + )); + profile.candidates = vec![LayoutAttempt { + layout: route, + outcome: AttemptOutcome::Succeeded, + warnings: Vec::new(), + errors: Vec::new(), + }]; + profile.selected = Some(route); + profile.recovery = senbei_engine::RecoveryStatus::Succeeded; + profile.static_validation = senbei_engine::ValidationStatus::NotRun; + profile.recognition = senbei_engine::RecognitionStatus::NotRecognized; + profile +} + /// Input report for one loose il2cpp metadata blob. fn metadata_input( input: &Path, @@ -1980,12 +2204,18 @@ fn metadata_input( .timed(crate::report::now_ms(started)), ); } else { - // Identified, valid, and already canonical: nothing to restore. + // Identified, valid, and already canonical: nothing to write. The + // transform still ran and validated, so a research report may say so + // even though the status stays "nothing needed". entry.status = InputStatus::Skipped; - entry.profile = Some(crate::report::metadata_unchanged_profile(identity)); - entry - .stages - .push(StageReport::new(Stage::Recovery, StageStatus::Skipped)); + entry.profile = Some(match report.research { + Some(_) => metadata_validated_unchanged_profile(identity, report.layout), + None => crate::report::metadata_unchanged_profile(identity), + }); + entry.stages.push( + StageReport::new(Stage::Recovery, StageStatus::Skipped) + .detail("the transform ran and validated; nothing needed rewriting"), + ); } entry.duration_ms = crate::report::now_ms(started); entry @@ -1997,6 +2227,7 @@ fn single_metadata_input( report: &senbei_metadata::Report, layout: senbei_engine::LayoutKind, dest: Option<&Path>, + research: bool, started: Instant, ) -> InputReport { let identity = identity_of(input); @@ -2008,10 +2239,11 @@ fn single_metadata_input( } else { InputStatus::Skipped }; - entry.profile = Some(if dest.is_some() { - crate::report::metadata_recovered_profile(identity, layout) - } else { - crate::report::metadata_unchanged_profile(identity) + entry.profile = Some(match (dest.is_some(), research) { + (true, _) => crate::report::metadata_recovered_profile(identity, layout), + // The transform ran and validated; only the rewrite was unnecessary. + (false, true) => metadata_validated_unchanged_profile(identity, layout), + (false, false) => crate::report::metadata_unchanged_profile(identity), }); entry.outputs = dest .map(|dest| vec![OutputFile::from_path(dest)]) @@ -2031,28 +2263,93 @@ fn single_metadata_input( entry } +/// Report for an il2cpp metadata input whose transform failed. +/// +/// One rule for folder and single-file runs, in every mode: an unsupported +/// version was left untouched by design and is a skip; anything else is a real +/// failure of this input, with the transform's own reason preserved. Research +/// keeps the seeds and discovery the failing attempt produced. +fn metadata_failure_input( + input: &Path, + error: &anyhow::Error, + unsupported: Option, + started: Instant, +) -> InputReport { + // `failed_input` already classified the typed error; an unsupported + // version is a deliberate skip, not an incomplete analysis. + let mut report = failed_input(input, error, started); + if unsupported.is_some() { + report.analysis_incomplete = false; + } + let identity = identity_of(input); + report.metadata = identity; + report.metadata_version = unsupported.or_else(|| identity.map(|identity| identity.raw_version)); + report.metadata_research = + crate::android::error_research(error).and_then(|capture| match capture { + crate::android::ResearchCapture::Metadata(value) => Some(value.clone()), + crate::android::ResearchCapture::Library(_) => None, + }); + if let Some(version) = unsupported { + // Left untouched by design; not a failure of this run. + report.status = InputStatus::Skipped; + report.errors.clear(); + report.profile = Some(crate::report::metadata_unchanged_profile(identity)); + report.warning(format!( + "unsupported metadata version {version}, left untouched" + )); + } else { + report.profile = Some(crate::report::metadata_failed_profile( + identity, + senbei_engine::LayoutKind::MetadataStructural, + &format!("{error:#}"), + )); + } + report +} + +/// Membership of a package, read only for a research inspection. +/// +/// This is a container listing (central directories and a bounded manifest +/// read), not a second restore: it never touches a protected entry's payload. +fn package_inventory( + package: &Path, + limits: &senbei_engine::android::ResourceLimits, + research: bool, +) -> Option { + if !research { + return None; + } + crate::android::inspect_package(package, limits).ok() +} + /// Input report for one app package, from the entries it produced. +/// +/// `inventory` additionally lists what the container holds — its manifests and +/// the entries a restore would probe — kept apart from the entries that were +/// actually probed, so a membership list is never read as inspected content. fn package_input( package: &Path, outcomes: Vec<&crate::android::EntryOutcome>, + inventory: Option<&crate::report::ContainerReport>, started: Instant, ) -> InputReport { let mut entry = InputReport::new(package, Role::Container); - entry.container = Some(ContainerReport { - kind: package - .extension() - .and_then(|value| value.to_str()) - .map(|value| value.to_ascii_lowercase()) - .unwrap_or_default(), - // Inventory is only recorded by an explicit inspect run; a restore - // reports what it actually produced. - manifests: Vec::new(), - entry_count: outcomes.len(), - candidate_entries: outcomes - .iter() - .map(|outcome| outcome.label.clone()) - .collect(), - nested_packages: Vec::new(), + entry.container = Some(match inventory { + Some(inventory) => inventory.clone(), + None => ContainerReport { + kind: package + .extension() + .and_then(|value| value.to_str()) + .map(|value| value.to_ascii_lowercase()) + .unwrap_or_default(), + manifests: Vec::new(), + entry_count: outcomes.len(), + candidate_entries: outcomes + .iter() + .map(|outcome| outcome.label.clone()) + .collect(), + nested_packages: Vec::new(), + }, }); entry.entries = outcomes .iter() @@ -2073,6 +2370,9 @@ fn package_input( .detail(diagnostics.join("; ")), ); } + // A container's analysis is incomplete when any entry's was: the + // membership report may be truncated by the same ceiling. + entry.analysis_incomplete = entry.entries.iter().any(|entry| entry.analysis_incomplete); entry.status = if entry .entries .iter() @@ -2114,6 +2414,8 @@ fn entry_report(outcome: &crate::android::EntryOutcome) -> EntryReport { report.provenance = outcome.provenance.clone(); report.layout = outcome.layout; report.metadata_version = outcome.metadata_version; + report.android_research = outcome.research.clone(); + report.metadata_research = outcome.metadata_research.clone(); if let SourceKind::Metadata { remapped } = outcome.kind { report.remapped = Some(remapped); } @@ -2122,6 +2424,9 @@ fn entry_report(outcome: &crate::android::EntryOutcome) -> EntryReport { } if let crate::android::EntryStatus::Failed(error) = &outcome.status { report.errors.push(format!("{error:#}")); + // A resource or I/O ceiling stopped this entry before its structure + // could be judged; a structural rejection is an observed finding. + report.analysis_incomplete = analysis_incomplete(error); } // The engine's advisory findings for this entry's own output. Only a // restored entry has an output they could describe. @@ -2240,3 +2545,251 @@ mod tests { ); } } + +#[cfg(test)] +mod research_tests { + use super::*; + use std::io::Write; + + /// Two splits that name the same package and version form one split set. + /// A restore failure there belongs to the group, but each split still gets + /// a report naming the cause — otherwise the JSON would say "no errors" + /// and an inspection would exit 0 over a failed restore. + #[test] + fn a_failed_split_set_reports_an_error_for_every_split() { + let td = tempfile::tempdir().unwrap(); + let root = td.path(); + let manifest = |package: &str, version: u32| { + format!( + "\n\ + \n" + ) + }; + let write = |name: &str, entries: &[(&str, Vec)]| { + let path = root.join(name); + let file = std::fs::File::create(&path).unwrap(); + let mut archive = zip::ZipWriter::new(file); + for (entry, data) in entries { + archive + .start_file( + *entry, + zip::write::SimpleFileOptions::default() + .compression_method(zip::CompressionMethod::Stored), + ) + .unwrap(); + archive.write_all(data).unwrap(); + } + archive.finish().unwrap(); + path + }; + // Same package and version: one split set. The library entry is larger + // than the entry ceiling, so the group restore really fails. + // The scan's size floor is applied before any content probe, so the + // archives carry an asset that clears it. + // Stored, not deflated: the scan's floor is the on-disk file size. + let padding: Vec = (0..8 * 1024).map(|index| (index % 251) as u8).collect(); + let base = write( + "base.apk", + &[ + ( + "AndroidManifest.xml", + manifest("com.example.split", 7).into_bytes(), + ), + ("assets/pad.bin", padding.clone()), + ], + ); + let config = write( + "config.apk", + &[ + ( + "AndroidManifest.xml", + manifest("com.example.split", 7).into_bytes(), + ), + ("assets/pad.bin", padding), + // Larger than the entry ceiling, so the group restore fails. + ("lib/arm64-v8a/libil2cpp.so", vec![0xAA; 2048]), + ], + ); + + let limits = senbei_engine::android::ResourceLimits { + max_entry_bytes: 512, + ..senbei_engine::android::ResourceLimits::default() + }; + let mut collector = Collector::new(Mode::Inspect); + run_folder_inner( + root, + Some(&td.path().join("out")), + 2, + false, + true, + false, + &limits, + Some(&mut collector), + ) + .unwrap(); + let value: serde_json::Value = serde_json::from_str(&collector.finish().to_json()).unwrap(); + let inputs = value["inputs"].as_array().unwrap(); + assert!( + inputs.len() >= 2, + "each split is reported separately: {value}" + ); + // A resource ceiling is an honest failure, not a failed inspection of a + // non-target: it is counted once per reported split, never twice for the + // group's two restore phases. + assert_eq!( + value["summary"]["errors"], 2, + "one error per split, counted exactly once: {value}" + ); + for package in [&base, &config] { + let reported = inputs + .iter() + .find(|input| input["path"] == package.display().to_string()) + .unwrap_or_else(|| panic!("{} must be reported: {value}", package.display())); + assert_eq!(reported["status"], "error", "{reported}"); + assert!( + !reported["errors"].as_array().unwrap().is_empty(), + "the cause travels with the split: {reported}" + ); + } + } +} + +#[cfg(test)] +mod single_package_research_tests { + use super::*; + use std::io::Write; + + /// A single package inspected on its own keeps the same per-entry engine + /// report a folder run would: the research flag must reach its restore + /// cache, not only the folder's shared one. + #[test] + fn a_single_package_inspection_keeps_its_entry_report() { + let td = tempfile::tempdir().unwrap(); + let apk = td.path().join("app.apk"); + let mut metadata = 0xFAB1_1BAF_u32.to_le_bytes().to_vec(); + metadata.extend_from_slice(&31u32.to_le_bytes()); + metadata.resize(0x300, 0); + // A plausible v31 header is not needed: the transform reports its own + // failure, and a failing transform is exactly what carries research. + let file = std::fs::File::create(&apk).unwrap(); + let mut archive = zip::ZipWriter::new(file); + let options = zip::write::SimpleFileOptions::default() + .compression_method(zip::CompressionMethod::Stored); + archive.start_file("AndroidManifest.xml", options).unwrap(); + archive + .write_all( + b"\n\ + \n", + ) + .unwrap(); + archive + .start_file("assets/global-metadata.dat", options) + .unwrap(); + archive.write_all(&metadata).unwrap(); + archive.start_file("assets/pad.bin", options).unwrap(); + archive + .write_all( + &(0..8 * 1024) + .map(|index| (index % 251) as u8) + .collect::>(), + ) + .unwrap(); + archive.finish().unwrap(); + + let report = inspect_path( + &apk, + false, + &senbei_engine::android::ResourceLimits::default(), + ) + .expect("inspection returns a report"); + let value: serde_json::Value = serde_json::from_str(&report.to_json()).unwrap(); + let input = &value["inputs"][0]; + assert_eq!(input["role"], "container"); + let entries = input["entries"].as_array().unwrap(); + assert_eq!(entries.len(), 1, "the metadata entry was probed: {input}"); + assert!( + entries[0]["metadata_research"].is_object(), + "a single package keeps the transform's research: {input}" + ); + } +} + +#[cfg(test)] +mod incomplete_analysis_tests { + use super::*; + + fn limited() -> anyhow::Error { + anyhow::Error::new(senbei_engine::android::LimitExceeded::Entry { + requested: 4096, + limit: 1024, + }) + } + + /// A resource ceiling stops the analysis before it can conclude anything. + /// A known target does not make that a complete inspection. + #[test] + fn a_resource_ceiling_keeps_inspection_incomplete() { + let error = limited(); + assert!(analysis_incomplete(&error)); + // And it survives the Android engines' own wrappers. + let wrapped = anyhow::Error::new(senbei_engine::android::ExtractionError::Limit( + senbei_engine::android::LimitExceeded::Entry { + requested: 4096, + limit: 1024, + }, + )); + assert!(analysis_incomplete(&wrapped)); + } + + /// An ordinary rejected candidate is a finding: the analysis concluded that + /// this layout does not apply. + #[test] + fn a_rejected_candidate_is_not_incomplete() { + assert!(!analysis_incomplete(&anyhow::anyhow!( + "stage5 marker not found — this build's layout is not supported" + ))); + assert!(!analysis_incomplete(&anyhow::Error::new( + senbei_engine::android::RestoreError::Invalid("not a linker-walkable image".to_owned()) + ))); + } + + /// The report restates a known target as recognized — unless the analysis + /// stopped on a resource or I/O ceiling. + #[test] + fn an_incomplete_analysis_stays_an_error_even_for_a_known_target() { + let td = tempfile::tempdir().unwrap(); + let path = td.path().join("libil2cpp.so"); + std::fs::write(&path, b"not really an ELF").unwrap(); + let mut input = InputReport::new(&path, Role::Content); + input.status = InputStatus::Error; + input.profile = Some(crate::report::android_failed_profile("limit")); + input.analysis_incomplete = true; + let reported = inspect_status(input); + assert_eq!(reported.status, InputStatus::Error); + assert!(reported.analysis_incomplete); + + // The same target without an incompleteness marker is a finding. + let mut complete = InputReport::new(&path, Role::Content); + complete.status = InputStatus::Error; + complete.profile = Some(crate::report::android_failed_profile("layout rejected")); + let reported = inspect_status(complete); + assert_eq!(reported.status, InputStatus::Recognized); + assert!(!reported.analysis_incomplete); + } + + /// A container whose entry hit a ceiling is incomplete as a whole. + #[test] + fn a_container_inherits_an_incomplete_entry() { + let mut entry = EntryReport::new("app.apk::lib/arm64-v8a/libil2cpp.so", EntryStatus::Error); + entry.analysis_incomplete = true; + entry.errors.push("resource limit".to_owned()); + let td = tempfile::tempdir().unwrap(); + let path = td.path().join("app.apk"); + std::fs::write(&path, b"PK").unwrap(); + let mut input = InputReport::new(&path, Role::Container); + input.entries = vec![entry]; + let reported = inspect_status(input); + assert_eq!(reported.status, InputStatus::Error); + assert!(reported.analysis_incomplete); + } +} diff --git a/senbei-io/src/report.rs b/senbei-io/src/report.rs index 392089d..88a29ba 100644 --- a/senbei-io/src/report.rs +++ b/senbei-io/src/report.rs @@ -12,9 +12,11 @@ //! only where a stage was measured (`None` otherwise); hashes are taken from //! the bytes that were actually produced; a route is only marked selected if //! a pipeline accepted it. -//! * Inspection never claims recovery. An [`Mode::Inspect`] run reports -//! recognition and the planned routes, never `selected`, `recovered`, or a -//! static-validation verdict. +//! * Research inspection retains no output files. An [`Mode::Inspect`] run may +//! perform full static recovery to discover parameters, but selected routes, +//! recovered identities and validation verdicts come only from actual work. +//! Parsed input facts, bounded probe candidates and recovery traces stay +//! separate so local plausibility is never mistaken for a recovery verdict. //! //! A container (`.apk`/`.apks`/`.xapk`) is reported as one input with //! [`Role::Container`]: its manifest inventory is listed separately from the @@ -32,6 +34,8 @@ use senbei_engine::{ RecoveryStatus, ValidationStatus, }; +mod text; + /// Version of the serialized [`Report`] schema. pub const REPORT_FORMAT_VERSION: u32 = 1; @@ -39,7 +43,7 @@ pub const REPORT_FORMAT_VERSION: u32 = 1; #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] #[serde(rename_all = "snake_case")] pub enum Mode { - /// Detection only: no recovery, no output, no log. + /// Research analysis, including static recovery; retain no output or log. Inspect, /// Restore and write outputs. Unpack, @@ -65,8 +69,8 @@ pub enum InputStatus { Ok, /// Produced output that fails the static integrity check. Suspect, - /// Inspection recognized a protected target. Nothing was recovered, so - /// this is never counted as an output. + /// Inspection recognized a protected target. Its profile separately records + /// whether static recovery succeeded; no output file is retained. Recognized, /// Not a target, already handled, or a layout this build does not know. Skipped, @@ -208,6 +212,37 @@ pub struct CompanionReport { pub state: CompanionState, pub path: Option, pub detail: Option, + /// Identity of the physical companion, distinct from the spliced view. + pub source: Option, +} + +/// Which bytes the research report's input offsets address. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] +#[serde(rename_all = "snake_case")] +pub enum ResearchInputView { + Original, + /// The loader's header page followed by its matching external payload. + SplicedCompanion, +} + +/// Structural observations and actual static-recovery discoveries for a PE. +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct WindowsResearchReport { + pub input_view: ResearchInputView, + pub input: senbei_engine::windows::WindowsInspection, + /// The post-overlay image, inspected before its bytes were discarded. + pub restored: Option, + pub trace: senbei_engine::windows::ResearchTrace, +} + +/// Existing Android engine reports captured from the actual static pipeline. +/// +/// The nested schemas belong to the extraction/restoration engines. Temporary +/// output locations are replaced with logical labels by the I/O adapter. +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct AndroidResearchReport { + pub extraction: serde_json::Value, + pub restoration: Option, } /// One manifest parsed from a container. @@ -271,11 +306,14 @@ pub struct EntryReport { /// Source label, e.g. `base.apk::lib/arm64-v8a/libil2cpp.so`. pub name: String, pub status: EntryStatus, + pub analysis_incomplete: bool, pub kind: Option, /// Route selected for this entry, when one was. pub layout: Option, pub metadata_version: Option, pub remapped: Option, + pub android_research: Option, + pub metadata_research: Option, /// Libraries whose decoded module was paired with this metadata entry. pub provenance: Vec, /// Where the restored bytes were written (absent in dry-run/inspect). @@ -289,10 +327,13 @@ impl EntryReport { Self { name: name.into(), status, + analysis_incomplete: false, kind: None, layout: None, metadata_version: None, remapped: None, + android_research: None, + metadata_research: None, provenance: Vec::new(), output: None, warnings: Vec::new(), @@ -307,6 +348,14 @@ pub struct InputReport { pub path: String, pub role: Role, pub status: InputStatus, + /// I/O, resource limits or infrastructure prevented the requested analysis. + /// A rejected recovery candidate alone does not set this flag. + pub analysis_incomplete: bool, + /// Identity of the physical input, never of a synthetic spliced view. + pub source: Option, + pub research: Option, + pub android_research: Option, + pub metadata_research: Option, /// Engine profile: recognition evidence, candidate routes, and — only when /// recovery actually ran — the selected route and static-validation verdict. pub profile: Option, @@ -335,6 +384,11 @@ impl InputReport { path: path.display().to_string(), role, status: InputStatus::Skipped, + analysis_incomplete: false, + source: None, + research: None, + android_research: None, + metadata_research: None, profile: None, companion: None, container: None, @@ -367,8 +421,8 @@ pub struct SummaryReport { pub inputs: usize, /// Inputs that produced output. pub recovered: usize, - /// Inputs whose protection was recognized. Only an `inspect` run fills - /// this: it is detection evidence, never a recovery claim. + /// Inputs whose protection was recognized during research inspection. + /// This count is independent of whether their static recovery succeeded. pub recognized: usize, /// Inputs that were not targets or were left untouched. pub skipped: usize, @@ -431,8 +485,17 @@ impl Report { /// Human-readable rendering, one block per input, for non-`--json` runs. pub fn render_text(&self) -> String { let mut text = String::new(); + if let Some(scan) = self.scan { + text.push_str(&format!( + "scan: {} probed non-targets · {} walk errors · {} probe errors\n", + scan.non_target_skipped, scan.walk_errors, scan.probe_errors + )); + if scan.walk_errors > 0 || scan.probe_errors > 0 { + text.push_str("warning: analysis is incomplete; some directory entries or selected files could not be examined\n"); + } + } for input in &self.inputs { - text.push_str(&render_input(input)); + text.push_str(&text::render_input(input)); } if !self.errors.is_empty() { for error in &self.errors { @@ -443,93 +506,6 @@ impl Report { } } -fn render_input(input: &InputReport) -> String { - let mut text = format!("{}\n", input.path); - text.push_str(&format!(" role: {:?}\n", input.role)); - if let Some(profile) = &input.profile { - text.push_str(&format!(" recognition: {:?}\n", profile.recognition)); - if !profile.evidence.is_empty() { - text.push_str(&format!(" evidence: {:?}\n", profile.evidence)); - } - for candidate in &profile.candidates { - let mut line = format!( - " route {}: {:?}", - layout_name(candidate.layout), - candidate.outcome - ); - if !candidate.errors.is_empty() { - line.push_str(&format!(" ({})", candidate.errors.join("; "))); - } - text.push_str(&line); - text.push('\n'); - } - if let Some(selected) = profile.selected { - text.push_str(&format!(" selected: {:?}\n", layout_name(selected))); - } - text.push_str(&format!(" recovery: {:?}\n", profile.recovery)); - text.push_str(&format!( - " static validation: {:?}\n", - profile.static_validation - )); - } - if let Some(metadata) = &input.metadata { - text.push_str(&format!( - " metadata: version {} ({:?}, capabilities {:?})\n", - metadata.raw_version, metadata.layout, metadata.capabilities - )); - } - if let Some(container) = &input.container { - text.push_str(&format!( - " container: {} · {} entries · {} manifests\n", - container.kind, - container.entry_count, - container.manifests.len() - )); - for manifest in &container.manifests { - text.push_str(&format!( - " manifest {} → {} {}\n", - manifest.source, - manifest.package.as_deref().unwrap_or(""), - manifest.version.as_deref().unwrap_or("") - )); - } - for entry in &container.candidate_entries { - text.push_str(&format!(" candidate {entry}\n")); - } - } - for entry in &input.entries { - text.push_str(&format!( - " entry {}: {:?}{}\n", - entry.name, - entry.status, - entry - .output - .as_ref() - .map(|output| format!(" -> {}", output.path)) - .unwrap_or_default() - )); - } - if let Some(recovered) = &input.recovered { - text.push_str(&format!( - " recovered: {} bytes · {}\n", - recovered.size, recovered.sha256 - )); - } - text.push_str(&format!(" status: {:?}\n", input.status)); - text -} - -fn layout_name(layout: LayoutKind) -> &'static str { - match layout { - LayoutKind::Dll => "dll", - LayoutKind::ExeStyle => "exe_style", - LayoutKind::AndroidStaged => "android_staged", - LayoutKind::MetadataStructural => "metadata_structural", - LayoutKind::MetadataSeeded => "metadata_seeded", - LayoutKind::MetadataMethodIndices => "metadata_method_indices", - } -} - /// Accumulates inputs during one invocation. pub struct Collector { mode: Mode, @@ -556,16 +532,37 @@ impl Collector { self.mode } - /// Record the folder scan tallies for a folder run. + /// Record scan tallies and keep unexamined inputs visible to exit policies. pub fn set_scan(&mut self, scan: ScanReport) { + let previous = self + .scan + .map_or(0, |scan| scan.walk_errors.saturating_add(scan.probe_errors)); + let failed = scan.walk_errors.saturating_add(scan.probe_errors); + self.summary.errors = self + .summary + .errors + .saturating_sub(previous) + .saturating_add(failed); self.scan = Some(scan); } /// Record one finished input and fold its status into the summary. pub fn push(&mut self, mut input: InputReport) { - if self.mode == Mode::DryRun { - // Nothing produced by a dry run is retained, so no output file may - // be reported. The attempt itself keeps its real outcome. + if self.mode == Mode::Inspect + && (input.analysis_incomplete + || input.entries.iter().any(|entry| entry.analysis_incomplete)) + { + input.analysis_incomplete = true; + input.status = InputStatus::Error; + } + if matches!(self.mode, Mode::DryRun | Mode::Inspect) { + // Research inspection and dry runs keep their actual recovery + // outcomes, but never advertise temporary artifacts as outputs. + let discarded = if self.mode == Mode::Inspect { + "research inspection: no output file was retained" + } else { + "dry run: the produced output was discarded" + }; if !input.outputs.is_empty() { // The produced byte count is a real result of the attempt even // though the file itself is not kept. A hash is only carried @@ -582,8 +579,7 @@ impl Collector { for stage in &mut input.stages { if stage.stage == Stage::OutputWrite { stage.status = StageStatus::Skipped; - stage.detail = - Some("dry run: the produced output was discarded".to_owned()); + stage.detail = Some(discarded.to_owned()); } } if !input @@ -593,7 +589,7 @@ impl Collector { { input.stages.push( StageReport::new(Stage::OutputWrite, StageStatus::Skipped) - .detail("dry run: the produced output was discarded"), + .detail(discarded), ); } input.outputs.clear(); @@ -609,7 +605,22 @@ impl Collector { self.summary.recovered += 1; self.summary.suspect += 1; } - InputStatus::Recognized => self.summary.recognized += 1, + InputStatus::Recognized => { + self.summary.recognized += 1; + if self.mode == Mode::Inspect + && let Some(profile) = &input.profile + { + if profile.recovery == RecoveryStatus::Succeeded { + self.summary.recovered += 1; + } + if matches!( + profile.static_validation, + ValidationStatus::Warnings | ValidationStatus::Failed + ) { + self.summary.suspect += 1; + } + } + } InputStatus::Skipped => self.summary.skipped += 1, InputStatus::Error => self.summary.errors += 1, } @@ -815,6 +826,95 @@ mod tests { assert_eq!(report.summary.recovered, 0); } + #[test] + fn research_counts_actual_recovery_and_suspect_without_retaining_output_paths() { + let mut input = sample_input(InputStatus::Recognized); + let mut profile = + ProtectionProfile::new(senbei_engine::ObservedTarget::windows(None, None)); + profile.recognition = RecognitionStatus::Recognized; + profile.recovery = RecoveryStatus::Succeeded; + profile.static_validation = ValidationStatus::Warnings; + input.profile = Some(profile); + input.outputs.push(OutputFile::from_bytes( + Path::new("temporary/image.exe"), + b"bytes", + )); + let mut collector = Collector::new(Mode::Inspect); + collector.push(input); + let report = collector.finish(); + assert_eq!(report.summary.recognized, 1); + assert_eq!(report.summary.recovered, 1); + assert_eq!(report.summary.suspect, 1); + assert_eq!(report.summary.errors, 0); + assert!(report.inputs[0].outputs.is_empty()); + assert!(!report.to_json().contains("temporary/image.exe")); + assert!( + report.inputs[0] + .stages + .iter() + .any(|stage| stage.stage == Stage::OutputWrite + && stage.status == StageStatus::Skipped) + ); + } + + #[test] + fn research_recovery_failure_is_a_finding_not_a_read_failure() { + let mut input = sample_input(InputStatus::Recognized); + let mut profile = + ProtectionProfile::new(senbei_engine::ObservedTarget::windows(None, None)); + profile.recognition = RecognitionStatus::Recognized; + profile.recovery = RecoveryStatus::Failed; + profile.push_error("no candidate validated"); + input.profile = Some(profile); + let mut collector = Collector::new(Mode::Inspect); + collector.push(input); + let report = collector.finish(); + assert_eq!(report.summary.recognized, 1); + assert_eq!(report.summary.recovered, 0); + assert_eq!(report.summary.errors, 0); + assert!(report.render_text().contains("no candidate validated")); + } + + #[test] + fn incomplete_research_cannot_be_hidden_by_a_recognized_status() { + let mut input = sample_input(InputStatus::Recognized); + let mut entry = EntryReport::new("package::library.so", EntryStatus::Error); + entry.analysis_incomplete = true; + entry + .errors + .push("resource ceiling prevented restoration".to_owned()); + input.entries.push(entry); + let mut collector = Collector::new(Mode::Inspect); + collector.push(input); + let report = collector.finish(); + assert_eq!(report.summary.errors, 1); + assert_eq!(report.inputs[0].status, InputStatus::Error); + assert!(report.inputs[0].analysis_incomplete); + assert!(report.render_text().contains("analysis incomplete")); + } + + #[test] + fn scan_failures_fail_report_only_modes_and_do_not_erase_input_errors() { + for mode in [Mode::Inspect, Mode::DryRun] { + let mut collector = Collector::new(mode); + collector.push(sample_input(InputStatus::Error)); + collector.set_scan(ScanReport { + walk_errors: 2, + probe_errors: 3, + non_target_skipped: 4, + }); + assert_eq!(collector.summary.errors, 6); + collector.set_scan(ScanReport { + walk_errors: 1, + ..ScanReport::default() + }); + let report = collector.finish(); + assert_eq!(report.summary.errors, 2); + assert!(report.render_text().contains("analysis is incomplete")); + assert!(report.render_text().contains("1 walk errors")); + } + } + #[test] fn digest_matches_a_known_sha256() { let digest = Digest::of(b"abc"); diff --git a/senbei-io/src/report/text.rs b/senbei-io/src/report/text.rs new file mode 100644 index 0000000..189cc28 --- /dev/null +++ b/senbei-io/src/report/text.rs @@ -0,0 +1,784 @@ +//! Human-readable research reports. JSON retains the same underlying evidence. + +use std::fmt::Write; + +use senbei_engine::windows::{ResearchTrace, TraceValue, WindowsInspection}; +use serde::Serialize; +use serde_json::Value; + +use super::{AndroidResearchReport, InputReport}; + +fn label(value: &impl Serialize) -> String { + match serde_json::to_value(value) { + Ok(Value::String(text)) => text.replace('_', " "), + Ok(value) => value.to_string(), + Err(_) => "unavailable".to_owned(), + } +} + +fn hex>(value: Option) -> String { + value + .map(|value| format!("0x{:X}", value.into())) + .unwrap_or_else(|| "unavailable".to_owned()) +} + +fn diagnostic(text: &mut String, indent: &str, kind: &str, message: &str) { + for line in message.lines() { + let _ = writeln!(text, "{indent}{kind}: {line}"); + } +} + +pub(super) fn render_input(input: &InputReport) -> String { + let mut text = format!("{}\n", input.path); + if input.analysis_incomplete { + let _ = writeln!( + text, + " analysis incomplete: I/O, resource limits or infrastructure prevented the requested work" + ); + } + if let Some(source) = &input.source { + let _ = writeln!( + text, + " source: {} bytes (0x{:X})", + source.size, source.size + ); + let _ = writeln!(text, " SHA-256: {}", source.sha256); + } + if let Some(profile) = &input.profile { + let target = &profile.observed; + let _ = writeln!( + text, + " target: {} · {} · {}", + label(&target.platform), + target + .format + .as_ref() + .map(label) + .unwrap_or_else(|| "format unavailable".to_owned()), + target + .kind + .as_ref() + .map(label) + .unwrap_or_else(|| "kind not applicable or unavailable".to_owned()) + ); + let _ = writeln!( + text, + " protection recognition: {}", + label(&profile.recognition) + ); + if !profile.evidence.is_empty() { + let evidence = profile + .evidence + .iter() + .map(label) + .collect::>() + .join(", "); + let _ = writeln!(text, " evidence: {evidence}"); + } + for candidate in &profile.candidates { + let _ = writeln!( + text, + " route {}: {}", + label(&candidate.layout), + label(&candidate.outcome) + ); + for message in &candidate.warnings { + diagnostic(&mut text, " ", "warning", message); + } + for message in &candidate.errors { + diagnostic(&mut text, " ", "reason", message); + } + } + if let Some(selected) = profile.selected { + let _ = writeln!(text, " selected route: {}", label(&selected)); + } + let _ = writeln!(text, " static recovery: {}", label(&profile.recovery)); + let _ = writeln!( + text, + " output static validation: {}", + label(&profile.static_validation) + ); + } + if let Some(companion) = &input.companion { + let _ = writeln!( + text, + " companion: {}{}", + label(&companion.state), + companion + .path + .as_ref() + .map(|path| format!(" · {path}")) + .unwrap_or_default() + ); + if let Some(source) = &companion.source { + let _ = writeln!( + text, + " {} bytes · SHA-256 {}", + source.size, source.sha256 + ); + } + if let Some(detail) = &companion.detail { + diagnostic(&mut text, " ", "detail", detail); + } + } + if let Some(research) = &input.research { + let _ = writeln!( + text, + " analysis input view: {}", + label(&research.input_view) + ); + if research.input_view == super::ResearchInputView::SplicedCompanion { + let _ = writeln!( + text, + " file offsets below 0x1000 address the stub; offsets at/above 0x1000 address companion offset (file offset - 0x1000)" + ); + } + render_windows(&mut text, "protected input", &research.input); + render_trace(&mut text, &research.trace); + if let Some(restored) = &research.restored { + if let (Some(before), Some(after)) = (&research.input.pe, &restored.pe) { + let _ = writeln!( + text, + " protected → recovered: entry RVA {} → {} · SizeOfImage {} → {} · sections {} → {}", + hex(before.entry_point_rva), + hex(after.entry_point_rva), + hex(before.size_of_image), + hex(after.size_of_image), + before.sections.len(), + after.sections.len() + ); + let _ = writeln!( + text, + " DLL characteristics {} → {}", + hex(before.dll_characteristics), + hex(after.dll_characteristics) + ); + } + render_windows(&mut text, "recovered image (not retained)", restored); + } + } + if let Some(metadata) = &input.metadata { + let _ = writeln!( + text, + " IL2CPP metadata version: {} · layout definition {}", + metadata.raw_version, + label(&metadata.layout) + ); + let _ = writeln!( + text, + " seeded method tokens: {}", + metadata.capabilities.seeded_method_tokens + ); + let _ = writeln!( + text, + " structural method tokens: {}", + metadata.capabilities.structural_method_tokens + ); + let _ = writeln!( + text, + " method-index restoration: {} · application context required: {}", + metadata.capabilities.method_index_restore, + metadata.capabilities.method_index_requires_context + ); + } + if let Some(container) = &input.container { + let _ = writeln!( + text, + " container: {} · {} entries · {} manifests", + container.kind, + container.entry_count, + container.manifests.len() + ); + for manifest in &container.manifests { + let _ = writeln!( + text, + " manifest {} → {} {}", + manifest.source, + manifest.package.as_deref().unwrap_or(""), + manifest.version.as_deref().unwrap_or("") + ); + } + for entry in &container.candidate_entries { + let _ = writeln!(text, " candidate: {entry}"); + } + } + if let Some(research) = &input.android_research { + render_android(&mut text, " ", research); + } + if let Some(research) = &input.metadata_research { + let _ = writeln!(text, " metadata transform evidence:"); + render_tree(&mut text, " ", research); + } + for entry in &input.entries { + let _ = writeln!( + text, + " entry {}: {}{}", + entry.name, + label(&entry.status), + entry + .output + .as_ref() + .map(|output| format!(" → {}", output.path)) + .unwrap_or_default() + ); + if entry.analysis_incomplete { + let _ = writeln!( + text, + " analysis incomplete: requested entry analysis could not finish" + ); + } + if let Some(layout) = entry.layout { + let _ = writeln!(text, " route: {}", label(&layout)); + } + if let Some(version) = entry.metadata_version { + let _ = writeln!(text, " metadata version: {version}"); + } + if let Some(remapped) = entry.remapped { + let _ = writeln!(text, " remapped method fields: {remapped}"); + } + for source in &entry.provenance { + let _ = writeln!(text, " module context source: {source}"); + } + for message in &entry.warnings { + diagnostic(&mut text, " ", "warning", message); + } + for message in &entry.errors { + diagnostic(&mut text, " ", "error", message); + } + if let Some(research) = &entry.android_research { + render_android(&mut text, " ", research); + } + if let Some(research) = &entry.metadata_research { + let _ = writeln!(text, " metadata transform evidence:"); + render_tree(&mut text, " ", research); + } + } + for source in &input.provenance { + let _ = writeln!(text, " module context source: {source}"); + } + for stage in &input.stages { + let _ = writeln!( + text, + " stage {}: {}{}", + label(&stage.stage), + label(&stage.status), + stage + .duration_ms + .map(|elapsed| format!(" · {elapsed} ms")) + .unwrap_or_default() + ); + if let Some(detail) = &stage.detail { + diagnostic(&mut text, " ", "detail", detail); + } + } + let mut seen = std::collections::BTreeSet::new(); + for (kind, messages) in [("warning", &input.warnings), ("error", &input.errors)] { + for message in messages { + if seen.insert((kind, message.as_str())) { + diagnostic(&mut text, " ", kind, message); + } + } + } + if let Some(profile) = &input.profile { + for (kind, messages) in [("warning", &profile.warnings), ("error", &profile.errors)] { + for message in messages { + if seen.insert((kind, message.as_str())) { + diagnostic(&mut text, " ", kind, message); + } + } + } + } + if let Some(recovered) = &input.recovered { + let _ = writeln!( + text, + " recovered: {} bytes · SHA-256 {}", + recovered.size, recovered.sha256 + ); + } + let _ = writeln!( + text, + " inspection status: {} · {} ms", + label(&input.status), + input.duration_ms + ); + text +} + +fn render_windows(text: &mut String, heading: &str, inspection: &WindowsInspection) { + let _ = writeln!(text, " {heading}: {} bytes", inspection.input_len); + if let Some(pe) = &inspection.pe { + let machine = match pe.machine { + Some(0x14c) => "x86", + Some(0x8664) => "x86-64", + Some(0xaa64) => "ARM64", + _ => "unknown machine", + }; + let _ = writeln!( + text, + " PE header: {} · {machine} ({})", + hex(pe.pe_offset), + hex(pe.machine) + ); + let _ = writeln!( + text, + " PE type: {} · {}", + pe.format + .as_ref() + .map(label) + .unwrap_or_else(|| "unavailable".to_owned()), + pe.kind + .as_ref() + .map(label) + .unwrap_or_else(|| "unavailable".to_owned()) + ); + let _ = writeln!( + text, + " image base: {} · SizeOfImage: {} · SizeOfHeaders: {}", + hex(pe.image_base), + hex(pe.size_of_image), + hex(pe.size_of_headers) + ); + let _ = writeln!( + text, + " entry point: RVA {} · file offset {} · file-backed: {}", + hex(pe.entry_point_rva), + hex(pe.entry_point_file_offset), + pe.entry_point_available + .map(|value| value.to_string()) + .unwrap_or_else(|| "unavailable".to_owned()) + ); + let _ = writeln!( + text, + " alignments: section {} · file {}", + hex(pe.section_alignment), + hex(pe.file_alignment) + ); + let _ = writeln!( + text, + " declared flags: COFF {} · DLL {} (runtime behavior not tested)", + hex(pe.characteristics), + hex(pe.dll_characteristics) + ); + for flag in &pe.named_flags { + let _ = writeln!( + text, + " {}: {} (0x{:04X})", + label(&flag.field), + flag.name, + flag.bit + ); + } + let _ = writeln!(text, " sections ({}):", pe.sections.len()); + let _ = writeln!( + text, + " # name RVA virtual size raw offset raw size R W X" + ); + for section in &pe.sections { + let p = §ion.permissions; + let name = section.name.escape_debug().to_string(); + let _ = writeln!( + text, + " {:>2} {:<10} 0x{:08X} 0x{:08X} 0x{:08X} 0x{:08X} {} {} {}", + section.index, + name, + section.virtual_address, + section.virtual_size, + section.raw_offset, + section.raw_size, + if p.read { 'R' } else { '-' }, + if p.write { 'W' } else { '-' }, + if p.execute { 'X' } else { '-' } + ); + let _ = writeln!( + text, + " characteristics: 0x{:08X} · raw backing: {} · raw range in file: {}", + section.characteristics, + label(§ion.backing), + section.raw_in_bounds + ); + if section.virtual_size > section.raw_size { + let _ = writeln!( + text, + " declared virtual tail beyond raw backing: 0x{:X} bytes", + section.virtual_size - section.raw_size + ); + } + for anomaly in §ion.anomalies { + let _ = writeln!(text, " observation: {}", label(anomaly)); + } + } + let _ = writeln!(text, " data directories ({}):", pe.directories.len()); + for directory in &pe.directories { + let _ = writeln!( + text, + " {:>2} {:<18} {} 0x{:08X} · size 0x{:X} · file {} · {}", + directory.index, + directory.name, + label(&directory.address_space), + directory.address, + directory.size, + hex(directory.file_offset), + label(&directory.mapping) + ); + if let Some(note) = directory.note { + let _ = writeln!(text, " {note}"); + } + } + if pe.unsectioned.is_empty() { + let _ = writeln!(text, " unsectioned file ranges: none"); + } else { + let _ = writeln!( + text, + " unsectioned file ranges (not automatically protector payloads):" + ); + for region in &pe.unsectioned { + let _ = writeln!( + text, + " {}: file 0x{:X} · length 0x{:X}", + label(®ion.kind), + region.offset, + region.length + ); + } + } + match &pe.overlay { + Some(region) => { + let _ = writeln!( + text, + " trailing overlay: file 0x{:X} · length 0x{:X}", + region.offset, region.length + ); + } + None => { + let _ = writeln!(text, " trailing overlay: none"); + } + } + if let Some(issue) = &pe.parse_issue { + diagnostic(text, " ", "parse issue", issue); + } + } + if let Some(protection) = &inspection.protection { + let _ = writeln!( + text, + " header-table decode: magic {} · supported KONN: {}", + hex(protection.magic), + protection.magic_recognized + ); + for word in &protection.header_words { + let _ = writeln!( + text, + " info[{}] @ file 0x{:X}: raw 0x{:08X} → decoded 0x{:08X}{}", + word.index, + word.source_file_offset, + word.raw_word, + word.decoded_word, + word.semantic + .as_ref() + .map(|semantic| format!(" · {}", label(semantic))) + .unwrap_or_default() + ); + } + if let Some(payload) = &protection.payload { + let _ = writeln!( + text, + " {}: file 0x{:X} → working-image RVA 0x{:X}", + if protection.magic_recognized { + "declared payload" + } else { + "candidate payload interpretation (magic not recognized)" + }, + payload.source_file_offset, + payload.destination_rva + ); + let _ = writeln!( + text, + " prefix length 0x{:X} · total length 0x{:X}", + payload.prefix_length, payload.total_length + ); + for check in &payload.checks { + let _ = writeln!( + text, + " {}: start 0x{:X} · length 0x{:X} · end 0x{:X} · limit 0x{:X} · in bounds {} · overflow {}", + check.name, + check.start, + check.length, + check.end, + check.limit, + check.in_bounds, + check.overflow + ); + } + } + let probe = &protection.probe; + let _ = writeln!( + text, + " payload probe: {} · scratch requested 0x{:X} · constructed 0x{:X} · ceiling 0x{:X}", + label(&probe.status), + probe.requested_length, + probe.decoded_length, + probe.limit_bytes + ); + let _ = writeln!( + text, + " prefix span 0x{:X} · raw-tail span 0x{:X} · actual prefix cipher bytes decoded 0x{:X}", + probe.prefix_bytes, probe.tail_bytes, inspection.work.prefix_bytes_decoded + ); + if let Some(reason) = probe.reason { + let _ = writeln!(text, " {reason}"); + } + if !probe.first_words.is_empty() { + let words = probe + .first_words + .iter() + .map(|word| format!("0x{word:08X}")) + .collect::>() + .join(", "); + let _ = writeln!(text, " decoded prefix initial words: {words}"); + } + let discovery = &protection.discovery; + let _ = writeln!( + text, + " shell discovery: {} · {} positions scanned · {} candidates reported", + label(&discovery.status), + discovery.positions_scanned, + discovery.candidates.len() + ); + if let Some(reason) = discovery.reason { + let _ = writeln!(text, " {reason}"); + } + for candidate in &discovery.candidates { + let _ = writeln!( + text, + " {}: {} · decoded offset {} · image RVA {} · source file {}", + label(&candidate.kind), + label(&candidate.status), + hex(candidate.payload_offset), + hex(candidate.image_rva), + hex(candidate.source_file_offset) + ); + let _ = writeln!(text, " {}", candidate.reason); + for field in &candidate.fields { + let _ = writeln!( + text, + " {} = 0x{:X}{}", + field.name, + field.value, + field + .space + .as_ref() + .map(|space| format!(" ({})", label(space))) + .unwrap_or_default() + ); + } + } + } + for issue in &inspection.issues { + let _ = writeln!( + text, + " {} [{}]: {}", + label(&issue.severity), + issue.area, + issue.message + ); + } + if inspection.work.budget_limited { + let _ = writeln!( + text, + " inspection work was budget-limited; omitted probes are not negative evidence" + ); + } +} + +fn render_trace(text: &mut String, trace: &ResearchTrace) { + let _ = writeln!( + text, + " actual static-pipeline discoveries ({} events):", + trace.events.len() + ); + let mut previous = String::new(); + for event in &trace.events { + let stage = label(&event.stage); + if previous != stage { + let _ = writeln!(text, " {stage}:"); + previous = stage; + } + let value = match &event.value { + TraceValue::U32(value) => format!("0x{value:08X} ({value})"), + TraceValue::U64(value) => format!("0x{value:X} ({value})"), + TraceValue::Bool(value) => value.to_string(), + TraceValue::Text(value) => value.clone(), + TraceValue::U32s(values) => values + .iter() + .map(|value| format!("0x{value:08X}")) + .collect::>() + .join(", "), + TraceValue::Range { start, length } => { + format!("start 0x{start:X} · length 0x{length:X}") + } + }; + let provenance = event + .address + .as_ref() + .map(|address| format!(" @ {} 0x{:X}", label(&address.space), address.offset)) + .unwrap_or_default(); + let _ = writeln!(text, " {}: {value}{provenance}", event.name); + if let Some(note) = event.note { + let _ = writeln!(text, " {note}"); + } + } + if trace.truncated { + let _ = writeln!( + text, + " trace truncated at {} events; {} events omitted", + trace.limit, trace.dropped + ); + } +} + +fn render_android(text: &mut String, indent: &str, research: &AndroidResearchReport) { + let _ = writeln!(text, "{indent}Android extraction evidence:"); + render_tree(text, &format!("{indent} "), &research.extraction); + if let Some(restoration) = &research.restoration { + let _ = writeln!(text, "{indent}Android restoration evidence:"); + render_tree(text, &format!("{indent} "), restoration); + } +} + +fn render_tree(text: &mut String, indent: &str, value: &Value) { + match value { + Value::Object(fields) => { + for (name, value) in fields { + match value { + Value::Array(_) | Value::Object(_) => { + let _ = writeln!(text, "{indent}{name}:"); + render_tree(text, &format!("{indent} "), value); + } + Value::Number(number) => { + let numeric = number + .as_u64() + .map(|value| format!("{value} (0x{value:X})")) + .unwrap_or_else(|| number.to_string()); + let _ = writeln!(text, "{indent}{name}: {numeric}"); + } + Value::String(value) => { + let _ = writeln!(text, "{indent}{name}: {}", value.escape_debug()); + } + _ => { + let _ = writeln!(text, "{indent}{name}: {value}"); + } + } + } + } + Value::Array(values) => { + for (index, value) in values.iter().enumerate() { + let _ = writeln!(text, "{indent}[{index}]"); + render_tree(text, &format!("{indent} "), value); + } + } + _ => { + let _ = writeln!(text, "{indent}{value}"); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::report::{ + CompanionReport, CompanionState, Digest, Role, Stage, StageReport, StageStatus, + }; + use senbei_engine::{Kind, ObservedTarget, ProtectionProfile, TargetFormat}; + use std::path::Path; + + #[test] + fn text_keeps_target_source_context_and_diagnostics() { + let mut input = InputReport::new(Path::new("module.exe"), Role::Content); + input.source = Some(Digest::of(b"source bytes")); + input.profile = Some(ProtectionProfile::new(ObservedTarget::windows( + Some(TargetFormat::Pe32), + Some(Kind::NativeExe), + ))); + input.companion = Some(CompanionReport { + state: CompanionState::Absent, + path: None, + detail: None, + source: None, + }); + input + .provenance + .push("application-scoped module 0x0C".to_owned()); + input.warning("partial discovery"); + input.error("candidate did not validate"); + input.stages.push( + StageReport::new(Stage::Recovery, StageStatus::Failed) + .detail("parameters were unavailable"), + ); + let text = render_input(&input); + for fact in [ + "SHA-256:", + "pe32", + "native exe", + "companion: absent", + "application-scoped module", + "warning: partial discovery", + "error: candidate did not validate", + "parameters were unavailable", + ] { + assert!(text.contains(fact), "missing {fact}: {text}"); + } + } + + #[test] + fn trace_values_have_hex_provenance_and_explicit_truncation() { + use senbei_engine::windows::{AddressSpace, ResearchEvent, ResearchStage, TraceAddress}; + let trace = ResearchTrace { + events: vec![ResearchEvent { + stage: ResearchStage::Payload, + name: "header_seed", + value: TraceValue::U32(0x1234), + address: Some(TraceAddress { + space: AddressSpace::FileOffset, + offset: 0x1000, + }), + note: Some("observed during static recovery"), + }], + truncated: true, + dropped: 2, + limit: 1, + }; + let mut text = String::new(); + render_trace(&mut text, &trace); + for fact in [ + "0x00001234", + "file offset 0x1000", + "observed during static recovery", + "trace truncated at 1 events; 2 events omitted", + ] { + assert!(text.contains(fact), "missing {fact}: {text}"); + } + } + + #[test] + fn nested_android_and_metadata_evidence_is_not_hidden() { + let mut input = InputReport::new(Path::new("library.so"), Role::Content); + input.android_research = Some(AndroidResearchReport { + extraction: serde_json::json!({"decoder": {"header_seed": 0x1234}, "module_registry": [{"command_id": 0x9b}]}), + restoration: Some( + serde_json::json!({"validation": {"diagnostics": ["mapping warning"]}}), + ), + }); + input.metadata_research = + Some(serde_json::json!({"tried_seeds": [0x5678], "route": "seeded"})); + let text = render_input(&input); + for fact in [ + "header_seed: 4660 (0x1234)", + "module_registry:", + "command_id: 155 (0x9B)", + "mapping warning", + "tried_seeds:", + "route: seeded", + ] { + assert!(text.contains(fact), "missing {fact}: {text}"); + } + } +} diff --git a/senbei-io/src/windows/companion.rs b/senbei-io/src/windows/companion.rs index 25eda75..5c550ff 100644 --- a/senbei-io/src/windows/companion.rs +++ b/senbei-io/src/windows/companion.rs @@ -278,13 +278,13 @@ pub(super) mod tests { } } - /// Inspection must describe a companion-declaring stub, not reproduce the - /// recovery entry point's refusal. + /// Inspection describes a companion-declaring stub *and* what happened when + /// its recovery was attempted. /// /// [`stub`] is a generated PE32+ loader whose entry record declares the - /// `._` suffix, so `read_unpacker_input` errors on it when the payload is - /// missing or does not pair. Inspection is detection only and must keep - /// the stub's recognition while reporting the pairing as inventory. + /// `._` suffix. The recovery entry point refuses it when the payload is + /// missing or does not pair; inspection runs that same attempt and reports + /// it as a finding about this input, never as a failure of the inspection. fn inspect_report(path: &std::path::Path) -> serde_json::Value { let report = crate::job::inspect_path( path, @@ -295,35 +295,23 @@ pub(super) mod tests { serde_json::from_str(&report.to_json()).expect("valid report") } - fn assert_no_recovery_claim(input: &serde_json::Value) { + /// Nothing was produced and no route was accepted, whatever the attempt did. + fn assert_no_recovered_output(input: &serde_json::Value) { assert_eq!(input["status"], "recognized", "the stub is recognized"); - let profile = &input["profile"]; - assert_eq!(profile["recognition"], "recognized"); + assert_eq!(input["profile"]["recognition"], "recognized"); assert!( - profile["selected"].is_null(), - "inspection selects no route: {profile}" + input["profile"]["selected"].is_null(), + "no route was accepted: {input}" ); - assert_eq!(profile["recovery"], "not_attempted"); - assert_eq!(profile["static_validation"], "not_run"); assert!( input["outputs"].as_array().unwrap().is_empty(), "inspection writes nothing" ); assert!(input["recovered"].is_null()); - for candidate in profile["candidates"].as_array().unwrap() { - assert_eq!( - candidate["outcome"], "not_attempted", - "inspection runs no route: {candidate}" - ); - } - assert!( - input["errors"].as_array().unwrap().is_empty(), - "a companion relationship is inventory, not an error: {input}" - ); } #[test] - fn inspect_of_a_companion_stub_without_its_payload_stays_detection() { + fn inspect_of_a_companion_stub_without_its_payload_reports_the_attempt() { let dir = tempfile::tempdir().unwrap(); let input = dir.path().join("module.exe"); std::fs::write(&input, stub()).unwrap(); @@ -333,13 +321,29 @@ pub(super) mod tests { let value = inspect_report(&input); let reported = &value["inputs"][0]; - assert_no_recovery_claim(reported); + assert_no_recovered_output(reported); assert_eq!(reported["companion"]["state"], "absent"); assert!(reported["companion"]["path"].is_null()); assert_eq!( reported["profile"]["observed"]["external_companion"], false, "nothing was spliced, so no external-companion claim" ); + // The refused attempt is reported, not hidden: recovery is blocked and + // the reason travels with it. + assert_eq!(reported["profile"]["recovery"], "blocked"); + assert!( + !reported["profile"]["errors"].as_array().unwrap().is_empty(), + "the refusal reason must be in the profile: {reported}" + ); + // Recognition survives: a missing payload describes this input, it does + // not unmake the stub. + assert_eq!(reported["profile"]["recognition"], "recognized"); + assert!( + reported["research"].is_object(), + "research inspection reports the input structure: {reported}" + ); + assert_eq!(reported["research"]["input_view"], "original"); + assert_eq!(value["summary"]["errors"], 0); } #[test] @@ -353,11 +357,16 @@ pub(super) mod tests { let value = inspect_report(&input); let reported = &value["inputs"][0]; - assert_no_recovery_claim(reported); + assert_no_recovered_output(reported); assert_eq!(reported["companion"]["state"], "unmatched"); assert!(reported["companion"]["path"].is_string()); assert!(reported["companion"]["detail"].is_string()); assert_eq!(reported["profile"]["observed"]["external_companion"], false); + // The unreadable-as-a-payload sibling is still identified on disk. + assert!( + reported["companion"]["source"].is_object(), + "the physical sibling has an identity: {reported}" + ); } #[test] @@ -375,14 +384,15 @@ pub(super) mod tests { assert_eq!(reported["status"], "recognized"); assert_eq!(reported["companion"]["state"], "spliced"); assert_eq!(reported["profile"]["observed"]["external_companion"], true); - // A real pairing is evidence; recovery still did not run. - assert_eq!(reported["profile"]["recovery"], "not_attempted"); - assert!(reported["profile"]["selected"].is_null()); - assert_eq!(reported["profile"]["static_validation"], "not_run"); + assert!(reported["companion"]["source"].is_object()); + // The input offsets describe the spliced view recovery was given. + assert_eq!(reported["research"]["input_view"], "spliced_companion"); + assert!(reported["outputs"].as_array().unwrap().is_empty()); + assert!(reported["recovered"].is_null()); } #[test] - fn folder_inspect_of_companion_stubs_stays_detection() { + fn folder_inspect_of_companion_stubs_reports_each_attempt() { let dir = tempfile::tempdir().unwrap(); let missing = dir.path().join("missing.exe"); let unmatched = dir.path().join("unmatched.dll"); @@ -406,13 +416,13 @@ pub(super) mod tests { assert!(states.contains(&"absent"), "{states:?}"); assert!(states.contains(&"unmatched"), "{states:?}"); for input in inputs { - assert_no_recovery_claim(input); + assert_no_recovered_output(input); } assert_eq!(value["summary"]["errors"], 0); } - /// A genuine read error still fails the input, but never fabricates a - /// recovery attempt that inspection did not make. + /// A genuine read error fails the input, and never fabricates a recovery + /// attempt that inspection did not make. #[test] fn inspect_read_error_does_not_invent_a_failed_recovery() { let dir = tempfile::tempdir().unwrap(); @@ -428,9 +438,53 @@ pub(super) mod tests { assert_eq!(input["status"], "error"); assert!(!input["errors"].as_array().unwrap().is_empty()); let profile = &input["profile"]; - assert_eq!(profile["recovery"], "not_attempted"); assert!(profile["selected"].is_null()); assert_eq!(profile["static_validation"], "not_run"); assert!(profile["candidates"].as_array().unwrap().is_empty()); + assert_eq!(value["summary"]["errors"], 1); + } +} + +#[cfg(test)] +mod research_tests { + use crate::job::{CompanionProbe, companion_report, observed_companion_state, probe_companion}; + use crate::report::CompanionState; + + /// An unreadable `._` sibling is reported as unreadable, never as a + /// mismatch, and no identity is invented for bytes that were never read. + #[test] + fn a_companion_that_cannot_be_read_is_not_a_mismatch() { + let temp = tempfile::tempdir().unwrap(); + let input = temp.path().join("stub.exe"); + std::fs::write(&input, b"MZ").unwrap(); + // A directory where the payload should be: it exists but cannot be read. + std::fs::create_dir(temp.path().join("stub.exe._")).unwrap(); + + assert!( + matches!(probe_companion(&input), CompanionProbe::Unreadable(_)), + "an unreadable sibling has its own state" + ); + let (state, source, reason) = observed_companion_state(&input, false); + assert_eq!(state, CompanionState::Unreadable); + assert!(source.is_none(), "no bytes were seen, so no identity"); + let report = companion_report(&input, state, source, reason); + assert_eq!(report.state, CompanionState::Unreadable); + assert!( + report + .detail + .as_deref() + .is_some_and(|detail| detail.contains("could not be read")), + "{report:?}" + ); + + // Absent stays absent, and a readable but non-pairing sibling is a + // mismatch whose identity the probe already computed. + let plain = temp.path().join("plain.exe"); + std::fs::write(&plain, b"MZ").unwrap(); + assert!(matches!(probe_companion(&plain), CompanionProbe::Absent)); + std::fs::write(temp.path().join("plain.exe._"), b"payload").unwrap(); + let (state, source, _) = observed_companion_state(&plain, false); + assert_eq!(state, CompanionState::Unmatched); + assert!(source.is_some(), "the bytes read for pairing identify it"); } }