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