diff --git a/Cargo.lock b/Cargo.lock index c23a682..d4a4a52 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -479,6 +479,8 @@ dependencies = [ "senbei-engine", "senbei-metadata", "senbei-pe", + "serde", + "serde_json", "sha2", "tempfile", "walkdir", diff --git a/senbei-cli/src/main.rs b/senbei-cli/src/main.rs index 201fd5e..f5bd566 100644 --- a/senbei-cli/src/main.rs +++ b/senbei-cli/src/main.rs @@ -3,108 +3,326 @@ use senbei_io::{job, pause, scan}; use std::path::Path; fn main() -> std::process::ExitCode { - let mut args = std::env::args().skip(1); - let mut path: Option = None; - let mut out: Option = None; - let mut quiet: u8 = 0; - let mut no_pause = false; - let mut no_log = false; - let mut verbose = false; - let mut scan_all = false; - let mut strict_integrity = false; - let mut limits = ResourceLimits::default(); - - while let Some(a) = args.next() { - match a.as_str() { - "-h" | "--help" => { - print_help(); - return std::process::ExitCode::SUCCESS; - } - "-V" | "--version" => { - println!("Senbei {}", env!("CARGO_PKG_VERSION")); - return std::process::ExitCode::SUCCESS; - } - "-q" | "--quiet" => quiet = quiet.saturating_add(1), - "-v" | "--verbose" => verbose = true, - "--no-pause" => no_pause = true, - "--no-log" => no_log = true, - "--scan-all" => scan_all = true, - "--strict-integrity" => strict_integrity = true, - flag @ ("--max-entry-mib" | "--max-total-mib" | "--max-entries" | "--max-depth") => { - if let Err(message) = set_resource_limit(&mut limits, flag, args.next().as_deref()) - { - eprintln!("error: {message}"); - return std::process::ExitCode::from(2); - } - } - "--out" => match args.next() { - Some(v) if !v.starts_with('-') => out = Some(v), - _ => { - eprintln!("error: --out requires a directory argument"); - return std::process::ExitCode::from(2); - } - }, - other if other.starts_with('-') => { - eprintln!("error: unknown option '{other}'"); - print_help(); - return std::process::ExitCode::from(2); - } - other => { - if let Some(prev) = &path { - eprintln!("error: multiple input paths given ('{prev}' and '{other}')"); - return std::process::ExitCode::from(2); - } - path = Some(other.to_string()); - } - } - } - - let code = match path { - None => { - print_help(); - 2 - } - Some(p) => { - if quiet < 2 { - println!("Senbei {}", env!("CARGO_PKG_VERSION")); - } - let p = Path::new(&p); - let out_path = out.as_deref().map(Path::new); - let result = if p.is_dir() { - job::run_folder_with_limits( - p, - out_path, - quiet, - verbose, - no_log, - scan_all || scan::scan_all_env(), - &limits, - ) - } else { - job::run_file_with_limits(p, out_path, quiet, verbose, no_log, &limits) - }; - match result { - Ok(summary) => { - if quiet < 2 { - println!("{}", summary.line()); - println!("done in {} ms", summary.duration_ms); - } - exit_code(&summary, strict_integrity) - } - Err(error) => { - if quiet < 2 { - eprintln!("error: {error:#}"); - } - 1 - } - } + let mut options = match Options::parse(std::env::args().skip(1)) { + Ok(Outcome::Run(options)) => options, + Ok(Outcome::Handled(code)) => return code, + Err(message) => { + eprintln!("error: {message}"); + return std::process::ExitCode::from(2); } }; - - pause::maybe_pause(no_pause); + let code = execute(&mut options); + if !options.machine { + pause::maybe_pause(options.no_pause); + } std::process::ExitCode::from(code) } +/// Which operation the command line asked for. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Command { + /// Detection only. Writes nothing. + Inspect, + /// Recover and write outputs. + Unpack, +} + +struct Options { + command: Command, + path: String, + out: Option, + quiet: u8, + no_pause: bool, + no_log: bool, + verbose: bool, + scan_all: bool, + strict_integrity: bool, + limits: ResourceLimits, + /// Machine-readable output on stdout and nothing else. + machine: bool, + /// Run the real recovery but keep no ordinary output and no log. + dry_run: bool, +} + +enum Outcome { + Run(Options), + Handled(std::process::ExitCode), +} + +impl Options { + fn parse(args: impl Iterator) -> Result { + let mut args = args.peekable(); + let mut command = Command::Unpack; + let mut subcommand: Option = None; + let mut path: Option = None; + let mut out: Option = None; + let mut quiet: u8 = 0; + let mut no_pause = false; + let mut no_log = false; + let mut verbose = false; + let mut scan_all = false; + let mut strict_integrity = false; + let mut machine = false; + let mut dry_run = false; + let mut limits = ResourceLimits::default(); + + while let Some(a) = args.next() { + match a.as_str() { + "-h" | "--help" => { + print_help(); + return Ok(Outcome::Handled(std::process::ExitCode::SUCCESS)); + } + "-V" | "--version" => { + println!("Senbei {}", env!("CARGO_PKG_VERSION")); + return Ok(Outcome::Handled(std::process::ExitCode::SUCCESS)); + } + "-q" | "--quiet" => quiet = quiet.saturating_add(1), + "-v" | "--verbose" => verbose = true, + "--no-pause" => no_pause = true, + "--no-log" => no_log = true, + "--scan-all" => scan_all = true, + "--strict-integrity" => strict_integrity = true, + "--json" => machine = true, + "--dry-run" => dry_run = true, + flag + @ ("--max-entry-mib" | "--max-total-mib" | "--max-entries" | "--max-depth") => { + set_resource_limit(&mut limits, flag, args.next().as_deref())?; + } + "--out" => match args.next() { + Some(v) if !v.starts_with('-') => out = Some(v), + _ => return Err("--out requires a directory argument".to_owned()), + }, + other if other.starts_with('-') => { + print_help(); + return Err(format!("unknown option '{other}'")); + } + // A subcommand is only a subcommand when it is the first + // positional word. `senbei inspect` therefore means the + // subcommand, while `senbei foo/inspect` is a path. + other + if path.is_none() + && subcommand.is_none() + && matches!(other, "inspect" | "unpack") => + { + command = if other == "inspect" { + Command::Inspect + } else { + Command::Unpack + }; + subcommand = Some(other.to_owned()); + } + other => { + if let Some(prev) = &path { + return Err(format!( + "multiple input paths given ('{prev}' and '{other}')" + )); + } + path = Some(other.to_string()); + } + } + } + + let Some(path) = path else { + // A subcommand with no path is a usage error; no arguments at all + // still prints help and exits 2, as before. + if let Some(subcommand) = subcommand { + return Err(format!("'{subcommand}' requires an input path")); + } + print_help(); + return Ok(Outcome::Handled(std::process::ExitCode::from(2))); + }; + + // These combinations would silently mean different things, so they are + // rejected rather than guessed at. + if command == Command::Inspect { + if dry_run { + return Err("'inspect' never recovers; 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(), + ); + } + } + if machine { + // Machine output owns stdout; interleaved progress would corrupt it. + quiet = quiet.max(1); + no_log = true; + } + let dry_run = dry_run && command == Command::Unpack; + if dry_run { + // A dry run keeps nothing: no ordinary output directory, no log. + if out.is_some() { + return Err("--dry-run writes no output; --out is not allowed".to_owned()); + } + no_log = true; + } + + Ok(Outcome::Run(Options { + command, + path, + out, + quiet, + no_pause, + no_log, + verbose, + scan_all, + strict_integrity, + limits, + machine, + dry_run, + })) + } +} + +/// Run the parsed command. Kept separate from argument parsing and the pause +/// prompt so the execution step can be wrapped on its own. +fn execute(options: &mut Options) -> u8 { + let path = Path::new(&options.path); + let scan_all = options.scan_all || scan::scan_all_env(); + match options.command { + Command::Inspect => execute_inspect(options, path, scan_all), + Command::Unpack if options.dry_run => execute_dry_run(options, path, scan_all), + Command::Unpack => execute_unpack(options, path, scan_all), + } +} + +/// Detection completes even when an input is not a target; only an input that +/// could not be read makes inspection 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); + if options.machine { + println!("{}", report.to_json()); + } else if options.quiet < 2 { + print!("{}", report.render_text()); + } + code + } + Err(error) => { + if options.machine { + let report = job::error_report(job::Mode::Inspect, &format!("{error:#}")); + println!("{}", report.to_json()); + } else if options.quiet < 2 { + eprintln!("error: {error:#}"); + } + 1 + } + } +} + +fn execute_dry_run(options: &Options, path: &Path, scan_all: bool) -> u8 { + match job::dry_run_path(path, scan_all, &options.limits) { + Ok(report) => { + let code = report_exit_code(&report, options.strict_integrity); + if options.machine { + println!("{}", report.to_json()); + } else if options.quiet < 2 { + print!("{}", report.render_text()); + println!("{}", report.summary_line()); + } + code + } + Err(error) => { + if options.machine { + let report = job::error_report(job::Mode::DryRun, &format!("{error:#}")); + println!("{}", report.to_json()); + } else if options.quiet < 2 { + eprintln!("error: {error:#}"); + } + 1 + } + } +} + +fn execute_unpack(options: &Options, path: &Path, scan_all: bool) -> u8 { + if options.quiet < 2 && !options.machine { + println!("Senbei {}", env!("CARGO_PKG_VERSION")); + } + let out_path = options.out.as_deref().map(Path::new); + // A machine run goes through the same drivers with an observer attached; + // the observer never changes routing, output, or messages. + let mut collector = job::Collector::new(job::Mode::Unpack); + let result = if options.machine { + if path.is_dir() { + job::run_folder_reported( + path, + out_path, + options.quiet, + options.verbose, + options.no_log, + scan_all, + &options.limits, + &mut collector, + ) + } else { + job::run_file_reported( + path, + out_path, + options.quiet, + options.verbose, + options.no_log, + &options.limits, + &mut collector, + ) + } + } else if path.is_dir() { + job::run_folder_with_limits( + path, + out_path, + options.quiet, + options.verbose, + options.no_log, + scan_all, + &options.limits, + ) + } else { + job::run_file_with_limits( + path, + out_path, + options.quiet, + options.verbose, + options.no_log, + &options.limits, + ) + }; + + match result { + Ok(summary) => { + if options.machine { + println!("{}", collector.finish().to_json()); + } else if options.quiet < 2 { + println!("{}", summary.line()); + println!("done in {} ms", summary.duration_ms); + } + exit_code(&summary, options.strict_integrity) + } + Err(error) => { + if options.machine { + let mut failed = collector; + failed.push_error(format!("{error:#}")); + println!("{}", failed.finish().to_json()); + } else if options.quiet < 2 { + eprintln!("error: {error:#}"); + } + 1 + } + } +} + +/// Exit status from a report: the same policy as the summary-driven one. +fn report_exit_code(report: &job::Report, strict_integrity: bool) -> u8 { + if report.summary.errors > 0 || (strict_integrity && report.summary.suspect > 0) { + 1 + } else { + 0 + } +} + /// Process status for a finished run. /// /// Suspect outputs are still written. By default a suspect file is a warning @@ -151,13 +369,31 @@ fn set_resource_limit( fn print_help() { println!( - "senbei [--out DIR] [-v|--verbose] [-q|--quiet]... [--scan-all] [--strict-integrity] [--max-entry-mib N] [--max-total-mib N] [--max-entries N] [--max-depth N] [--no-log] [--no-pause] [-V|--version] [-h|--help]" + "senbei [inspect|unpack] [--out DIR] [-v|--verbose] [-q|--quiet]... [--json] [--dry-run] [--scan-all] [--strict-integrity] [--max-entry-mib N] [--max-total-mib N] [--max-entries N] [--max-depth N] [--no-log] [--no-pause] [-V|--version] [-h|--help]" ); println!( - " input a Crackproof PE (.exe/.dll), an il2cpp global-metadata.dat,\n\ + " \n\ + \x20 a Crackproof PE (.exe/.dll), an il2cpp global-metadata.dat,\n\ \x20 a protected Android AArch64 library (.so), an Android app\n\ \x20 package (.apk/.apks/.xapk), or a folder containing any of\n\ - \x20 these" + \x20 these. The bare form is the same as 'unpack'." + ); + 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." + ); + println!(" unpack PATH detection and recovery; writes outputs (the default)."); + println!( + " --json write one versioned machine-readable report to stdout and\n\ + \x20 nothing else. Implies quiet and --no-log." + ); + println!( + " --dry-run run the real recovery but keep nothing: no output tree and\n\ + \x20 no log. Android extraction still uses its own temporary\n\ + \x20 workspace, which is discarded." ); println!( " --scan-all probe selected .exe/.dll/.so/metadata names below the\n\ @@ -183,6 +419,10 @@ fn print_help() { defaults.max_entries, defaults.max_depth, ); + println!( + " Exit codes: 0 success, 1 a target failed (or a suspect with\n\ + \x20 --strict-integrity), 2 the command line was rejected." + ); } #[cfg(test)] @@ -281,3 +521,78 @@ mod resource_limits { assert_eq!(limits, ResourceLimits::default()); } } + +#[cfg(test)] +mod command_line { + use super::*; + + fn parse(args: &[&str]) -> Result { + match Options::parse(args.iter().map(|arg| (*arg).to_string()))? { + Outcome::Run(options) => Ok(options), + Outcome::Handled(code) => Err(format!( + "handled: {}", + code == std::process::ExitCode::SUCCESS + )), + } + } + + #[test] + fn bare_path_is_an_unpack() { + let options = parse(&["app.exe"]).unwrap(); + assert_eq!(options.command, Command::Unpack); + assert_eq!(options.path, "app.exe"); + assert!(!options.dry_run); + assert!(!options.machine); + } + + #[test] + fn legacy_flags_still_apply_around_a_bare_path() { + let options = parse(&["app.exe", "--out", "o", "-q", "-v", "--no-log"]).unwrap(); + assert_eq!(options.path, "app.exe"); + assert_eq!(options.out.as_deref(), Some("o")); + assert_eq!(options.quiet, 1); + assert!(options.verbose); + assert!(options.no_log); + } + + #[test] + fn explicit_subcommands_are_recognised() { + assert_eq!(parse(&["inspect", "x"]).unwrap().command, Command::Inspect); + assert_eq!(parse(&["unpack", "x"]).unwrap().command, Command::Unpack); + // A directory literally named like a subcommand still works via path. + assert_eq!(parse(&["./inspect"]).unwrap().path, "./inspect"); + } + + #[test] + fn json_implies_quiet_and_no_log() { + let options = parse(&["--json", "app.exe"]).unwrap(); + assert!(options.machine); + assert!(options.quiet >= 1); + assert!(options.no_log); + } + + #[test] + fn dry_run_refuses_an_output_directory() { + assert!(parse(&["--dry-run", "--out", "o", "app.exe"]).is_err()); + let options = parse(&["--dry-run", "app.exe"]).unwrap(); + assert!(options.dry_run); + assert!(options.no_log); + } + + #[test] + fn inspect_rejects_recovery_only_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 + ); + } + + #[test] + fn a_subcommand_without_a_path_is_a_usage_error() { + assert!(parse(&["inspect"]).is_err()); + assert!(parse(&["unpack"]).is_err()); + } +} diff --git a/senbei-cli/tests/reporting.rs b/senbei-cli/tests/reporting.rs new file mode 100644 index 0000000..11163b2 --- /dev/null +++ b/senbei-cli/tests/reporting.rs @@ -0,0 +1,553 @@ +//! CLI behaviour of `inspect`, `unpack`, `--json`, and `--dry-run`. +//! +//! These tests drive the binary against generated fixtures only: nothing here +//! needs the optional protected corpus, so they run everywhere. They pin the +//! three contracts the flags exist for: +//! +//! * `--json` writes one versioned document to stdout and nothing else. +//! * `inspect` writes no output, no log, and no temporary file, and never +//! claims a route succeeded. +//! * `--dry-run` runs the real recovery and still leaves no ordinary output +//! and no log behind. + +use std::path::{Path, PathBuf}; +use std::process::{Command, Output}; + +#[test] +fn unreadable_unpack_input_blocks_routes_instead_of_inventing_an_attempt() { + let dir = tempfile::tempdir().unwrap(); + let input = dir.path().join("missing.dll"); + let dest = dir.path().join("unused.dll"); + let (profile, result) = senbei_io::job::unpack_one_profiled(&input, &dest, false); + assert!(result.is_err()); + assert_eq!(profile.recovery, senbei_engine::RecoveryStatus::Blocked); + assert_eq!( + profile.static_validation, + senbei_engine::ValidationStatus::NotRun + ); + assert!(profile.candidates.is_empty()); + assert!(profile.selected.is_none()); + assert!(!dest.exists()); +} + +fn senbei() -> Command { + let mut command = Command::new(env!("CARGO_BIN_EXE_senbei")); + command.arg("--no-pause"); + command +} + +fn run(args: &[&str]) -> Output { + senbei().args(args).output().expect("spawn senbei") +} + +/// Every path below `root`, so a test can prove nothing appeared. +fn tree(root: &Path) -> Vec { + let mut paths = Vec::new(); + let mut stack = vec![root.to_path_buf()]; + while let Some(dir) = stack.pop() { + let Ok(entries) = std::fs::read_dir(&dir) else { + continue; + }; + for entry in entries.flatten() { + let path = entry.path(); + if path.is_dir() { + stack.push(path.clone()); + } + paths.push(path); + } + } + paths.sort(); + paths +} + +fn parse_json(output: &Output) -> serde_json::Value { + let text = String::from_utf8(output.stdout.clone()).expect("utf-8 stdout"); + serde_json::from_str(text.trim()) + .unwrap_or_else(|error| panic!("stdout was not one JSON document: {error}\n{text}")) +} + +fn logs_below(root: &Path) -> Vec { + tree(root) + .into_iter() + .filter(|path| { + path.file_name() + .and_then(|name| name.to_str()) + .is_some_and(|name| name.starts_with("senbei-") && name.ends_with(".log")) + }) + .collect() +} + +/// The folder scan's size floor: a selected name below it is never opened, so +/// fixtures have to clear it to appear in a folder run. +const SCAN_FLOOR: usize = 4128; + +fn write_plain(dir: &Path, name: &str) -> PathBuf { + let path = dir.join(name); + let mut bytes = b"not a protected image at all".to_vec(); + bytes.resize(SCAN_FLOOR + 128, 0); + std::fs::write(&path, bytes).unwrap(); + path +} + +/// A metadata header of the given version, without a real body. Identification +/// reads only the 8-byte header, so this is enough to exercise the capability +/// and unsupported-version paths. +fn write_metadata(dir: &Path, version: u32) -> PathBuf { + let path = dir.join("global-metadata.dat"); + let mut bytes = 0xFAB1_1BAF_u32.to_le_bytes().to_vec(); + bytes.extend_from_slice(&version.to_le_bytes()); + bytes.resize(SCAN_FLOOR + 128, 0); + std::fs::write(&path, bytes).unwrap(); + path +} + +// --------------------------------------------------------------------------- +// JSON purity +// --------------------------------------------------------------------------- + +#[test] +fn json_inspect_writes_one_versioned_document_and_nothing_else() { + 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)); + // No banner, no progress, no log path: stdout is the document alone. + assert!(output.stderr.is_empty(), "stderr must be empty"); + let value = parse_json(&output); + assert_eq!(value["format_version"], 1); + assert_eq!(value["tool"]["name"], "senbei"); + assert_eq!(value["mode"], "inspect"); + assert!(value["inputs"].is_array()); + assert_eq!(value["inputs"][0]["path"], input.display().to_string()); + assert_eq!(value["inputs"][0]["status"], "skipped"); +} + +#[test] +fn json_unpack_reports_outputs_and_status() { + let td = tempfile::tempdir().unwrap(); + let input = write_plain(td.path(), "plain.exe"); + let out = td.path().join("out"); + let output = run(&[ + input.to_str().unwrap(), + "--out", + out.to_str().unwrap(), + "--json", + ]); + assert!(output.stderr.is_empty(), "stderr must be empty"); + let value = parse_json(&output); + assert_eq!(value["mode"], "unpack"); + // A non-target is a per-input error in unpack mode, and the document says so. + assert_eq!(value["summary"]["errors"], 1); + assert_eq!(value["inputs"][0]["status"], "error"); + assert!( + !value["inputs"][0]["errors"].as_array().unwrap().is_empty(), + "the failure reason must be in the report" + ); + assert_eq!(output.status.code(), Some(1)); +} + +#[test] +fn json_error_status_is_reported_in_the_document() { + let output = run(&["inspect", "Z:/definitely/not/here", "--json"]); + assert_eq!(output.status.code(), Some(1)); + let value = parse_json(&output); + assert_eq!(value["format_version"], 1); + assert_eq!(value["summary"]["errors"], 1); +} + +// --------------------------------------------------------------------------- +// Inspect writes nothing +// --------------------------------------------------------------------------- + +#[test] +fn inspect_writes_no_output_no_log_and_no_temporary() { + let td = tempfile::tempdir().unwrap(); + write_plain(td.path(), "plain.exe"); + write_metadata(td.path(), 31); + let before = tree(td.path()); + + let output = run(&["inspect", td.path().to_str().unwrap()]); + assert!(output.status.success(), "inspect must succeed: {output:?}"); + assert_eq!( + tree(td.path()), + before, + "inspect must not create, change, or remove anything" + ); +} + +#[test] +fn inspect_never_claims_recovery_or_validation() { + let td = tempfile::tempdir().unwrap(); + write_plain(td.path(), "plain.exe"); + let output = run(&["inspect", td.path().to_str().unwrap(), "--json"]); + let value = parse_json(&output); + for input in value["inputs"].as_array().unwrap() { + assert!( + input["profile"]["selected"].is_null(), + "inspect must not select a route: {input}" + ); + assert_eq!(input["profile"]["recovery"], "not_attempted"); + assert_eq!(input["profile"]["static_validation"], "not_run"); + assert!( + input["outputs"].as_array().unwrap().is_empty(), + "inspect must not report outputs" + ); + assert!(input["recovered"].is_null()); + } +} + +#[test] +fn inspect_reports_metadata_capability_without_a_protection_verdict() { + let td = tempfile::tempdir().unwrap(); + write_metadata(td.path(), 31); + let output = run(&["inspect", td.path().to_str().unwrap(), "--json"]); + let value = parse_json(&output); + let input = &value["inputs"][0]; + assert_eq!(input["metadata"]["raw_version"], 31); + assert_eq!(input["metadata"]["layout"], "known"); + assert_eq!(input["metadata_version"], 31); + // Identification is a header fact; it is never protection evidence. + assert!(input["profile"]["evidence"].as_array().unwrap().is_empty()); +} + +#[test] +fn inspect_reports_an_unsupported_metadata_version_without_failing_the_run() { + let td = tempfile::tempdir().unwrap(); + write_metadata(td.path(), 27); + let output = run(&["inspect", td.path().to_str().unwrap(), "--json"]); + assert!(output.status.success()); + let value = parse_json(&output); + let input = &value["inputs"][0]; + assert_eq!(input["metadata_version"], 27); + assert_eq!(input["metadata"]["layout"], "unverified"); + assert_eq!(input["status"], "skipped"); + assert_eq!(value["summary"]["errors"], 0); +} + +// --------------------------------------------------------------------------- +// Dry run keeps nothing +// --------------------------------------------------------------------------- + +#[test] +fn dry_run_writes_no_ordinary_output_and_no_log() { + let td = tempfile::tempdir().unwrap(); + write_plain(td.path(), "plain.exe"); + write_metadata(td.path(), 31); + let before = tree(td.path()); + + let output = run(&["--dry-run", td.path().to_str().unwrap()]); + assert!( + logs_below(td.path()).is_empty(), + "dry run must not write a log" + ); + assert_eq!( + tree(td.path()), + before, + "dry run must not leave outputs, logs, or temporaries behind" + ); + assert!( + !output.stdout.is_empty(), + "a dry run still reports what it tried" + ); +} + +#[test] +fn dry_run_json_describes_an_attempt_that_really_ran() { + let td = tempfile::tempdir().unwrap(); + // A single file is always attempted, so the report shows a real failure + // rather than the scan declining to select it. + let input = write_plain(td.path(), "plain.exe"); + let output = run(&["--dry-run", input.to_str().unwrap(), "--json"]); + let value = parse_json(&output); + assert_eq!(value["mode"], "dry_run"); + let reported = &value["inputs"][0]; + assert_eq!(reported["path"], input.display().to_string()); + // The pipeline was really consulted: an unreadable-as-protected input is + // reported as not recognized, with the reason recorded. + assert_eq!(reported["profile"]["recognition"], "not_recognized"); + assert!( + !reported["profile"]["errors"].as_array().unwrap().is_empty(), + "the failure reason must be in the profile" + ); + assert!( + reported["outputs"].as_array().unwrap().is_empty(), + "a dry run reports no output files" + ); + assert_eq!(reported["status"], "error"); +} + +#[test] +fn dry_run_refuses_an_output_directory() { + let output = run(&["--dry-run", "--out", "out", "plain.exe"]); + assert_eq!(output.status.code(), Some(2)); + assert!(String::from_utf8_lossy(&output.stderr).contains("--dry-run")); +} + +// --------------------------------------------------------------------------- +// Backward compatibility +// --------------------------------------------------------------------------- + +#[test] +fn legacy_positional_invocation_is_unchanged() { + let td = tempfile::tempdir().unwrap(); + let input = write_plain(td.path(), "plain.exe"); + let out = td.path().join("out"); + + let legacy = run(&[input.to_str().unwrap(), "--out", out.to_str().unwrap()]); + assert_eq!(legacy.status.code(), Some(1), "a non-target is an error"); + let text = String::from_utf8_lossy(&legacy.stdout); + assert!(text.starts_with("Senbei "), "banner is still printed"); + assert!(text.contains("0 unpacked"), "{text}"); + assert!(text.contains("done in "), "{text}"); + + // The explicit alias behaves identically. + let aliased = run(&[ + "unpack", + input.to_str().unwrap(), + "--out", + out.to_str().unwrap(), + ]); + assert_eq!(aliased.status.code(), legacy.status.code()); +} + +#[test] +fn quiet_level_two_stays_silent() { + let td = tempfile::tempdir().unwrap(); + let input = write_plain(td.path(), "plain.exe"); + let output = run(&[ + input.to_str().unwrap(), + "--out", + td.path().join("out").to_str().unwrap(), + "-q", + "-q", + "--no-log", + ]); + assert!(output.stdout.is_empty(), "quiet>=2 stdout"); + assert!(output.stderr.is_empty(), "quiet>=2 stderr"); +} + +#[test] +fn inspect_help_is_documented() { + let output = run(&["--help"]); + assert!(output.status.success()); + let text = String::from_utf8(output.stdout).unwrap(); + for needle in ["inspect", "--json", "--dry-run", "unpack"] { + assert!(text.contains(needle), "help must document {needle}"); + } +} + +#[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}"); + } + let output = run(&["inspect", "--dry-run", "x"]); + assert_eq!(output.status.code(), Some(2)); +} + +// --------------------------------------------------------------------------- +// Containers and companions +// --------------------------------------------------------------------------- + +/// A minimal plain-text `AndroidManifest.xml` the manifest reader accepts. +const MANIFEST: &str = r#" + + +"#; + +/// CRC-32 (IEEE) as used by ZIP local and central headers. +fn crc32(data: &[u8]) -> u32 { + let mut table = [0u32; 256]; + for (index, slot) in table.iter_mut().enumerate() { + let mut value = index as u32; + for _ in 0..8 { + value = if value & 1 != 0 { + 0xEDB8_8320 ^ (value >> 1) + } else { + value >> 1 + }; + } + *slot = value; + } + let mut crc = 0xFFFF_FFFFu32; + for byte in data { + crc = table[((crc ^ u32::from(*byte)) & 0xFF) as usize] ^ (crc >> 8); + } + crc ^ 0xFFFF_FFFF +} + +/// A ZIP at `path` holding `entries` as **stored** (uncompressed) members. +/// +/// Written by hand so the fixture needs no extra dependency: the point of the +/// test is the inventory, not the compressor. +fn write_zip(path: &Path, entries: &[(&str, &[u8])]) { + let mut out: Vec = Vec::new(); + let mut directory: Vec = Vec::new(); + for (name, data) in entries { + let offset = out.len() as u32; + let crc = crc32(data); + let size = data.len() as u32; + out.extend_from_slice(&0x0403_4B50u32.to_le_bytes()); + out.extend_from_slice(&20u16.to_le_bytes()); // version needed + out.extend_from_slice(&0u16.to_le_bytes()); // flags + out.extend_from_slice(&0u16.to_le_bytes()); // stored + out.extend_from_slice(&0u16.to_le_bytes()); // time + out.extend_from_slice(&0u16.to_le_bytes()); // date + out.extend_from_slice(&crc.to_le_bytes()); + out.extend_from_slice(&size.to_le_bytes()); + out.extend_from_slice(&size.to_le_bytes()); + out.extend_from_slice(&(name.len() as u16).to_le_bytes()); + out.extend_from_slice(&0u16.to_le_bytes()); // extra length + out.extend_from_slice(name.as_bytes()); + out.extend_from_slice(data); + + directory.extend_from_slice(&0x0201_4B50u32.to_le_bytes()); + directory.extend_from_slice(&20u16.to_le_bytes()); // made by + directory.extend_from_slice(&20u16.to_le_bytes()); // needed + directory.extend_from_slice(&0u16.to_le_bytes()); // flags + directory.extend_from_slice(&0u16.to_le_bytes()); // stored + directory.extend_from_slice(&0u16.to_le_bytes()); + directory.extend_from_slice(&0u16.to_le_bytes()); + directory.extend_from_slice(&crc.to_le_bytes()); + directory.extend_from_slice(&size.to_le_bytes()); + directory.extend_from_slice(&size.to_le_bytes()); + directory.extend_from_slice(&(name.len() as u16).to_le_bytes()); + directory.extend_from_slice(&0u16.to_le_bytes()); // extra + directory.extend_from_slice(&0u16.to_le_bytes()); // comment + directory.extend_from_slice(&0u16.to_le_bytes()); // disk + directory.extend_from_slice(&0u16.to_le_bytes()); // internal attrs + directory.extend_from_slice(&0u32.to_le_bytes()); // external attrs + directory.extend_from_slice(&offset.to_le_bytes()); + directory.extend_from_slice(name.as_bytes()); + } + let directory_offset = out.len() as u32; + let directory_size = directory.len() as u32; + out.extend_from_slice(&directory); + out.extend_from_slice(&0x0605_4B50u32.to_le_bytes()); + out.extend_from_slice(&0u16.to_le_bytes()); // disk + out.extend_from_slice(&0u16.to_le_bytes()); // directory disk + out.extend_from_slice(&(entries.len() as u16).to_le_bytes()); + out.extend_from_slice(&(entries.len() as u16).to_le_bytes()); + out.extend_from_slice(&directory_size.to_le_bytes()); + out.extend_from_slice(&directory_offset.to_le_bytes()); + out.extend_from_slice(&0u16.to_le_bytes()); // comment length + std::fs::write(path, out).unwrap(); +} + +#[test] +fn inspect_reports_a_container_inventory_separately_from_its_entries() { + let td = tempfile::tempdir().unwrap(); + let apk = td.path().join("base.apk"); + write_zip( + &apk, + &[ + ("AndroidManifest.xml", MANIFEST.as_bytes()), + // A large asset: an inventory must not need to read it. + ("assets/big.bin", &vec![0u8; 200_000]), + ("lib/arm64-v8a/libil2cpp.so", b"\x7fELF-not-really"), + ], + ); + + let output = run(&["inspect", apk.to_str().unwrap(), "--json"]); + let value = parse_json(&output); + let input = &value["inputs"][0]; + assert_eq!(input["role"], "container"); + assert_eq!(input["container"]["kind"], "apk"); + let manifests = input["container"]["manifests"].as_array().unwrap(); + assert_eq!(manifests.len(), 1); + 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. + 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()); + assert!(input["outputs"].as_array().unwrap().is_empty()); + // Inventory is membership, not inspected protected content. + assert!(input["profile"].is_null()); + assert_eq!(input["status"], "skipped"); +} + +/// A synthetic PE whose header key table carries the supported magic, so it is +/// detectable. No protected bytes are included: only the header layout. +fn fake_protected_pe() -> Vec { + const MAGIC: u32 = 0x4E4E_4F4B; + let mut bytes = vec![0u8; 0x2000]; + bytes[..2].copy_from_slice(b"MZ"); + bytes[0x3c..0x40].copy_from_slice(&0x80u32.to_le_bytes()); + bytes[0x80..0x84].copy_from_slice(b"PE\0\0"); + // IMAGE_FILE_HEADER.Characteristics: not a DLL. + bytes[0x86..0x88].copy_from_slice(&0x0102u16.to_le_bytes()); + // Optional header magic (PE32+) and no CLR directory. + bytes[0x98..0x9a].copy_from_slice(&0x20Bu16.to_le_bytes()); + // Header key table: keys[0] = cell[0]; keys[1] = keys[0] ^ cell[1]. + let cell0 = 0x1234_5678u32; + let cell1 = cell0 ^ MAGIC; + bytes[4096..4100].copy_from_slice(&cell0.to_le_bytes()); + bytes[4100..4104].copy_from_slice(&cell1.to_le_bytes()); + bytes +} + +#[test] +fn inspect_reports_a_non_matching_companion_without_an_error() { + let td = tempfile::tempdir().unwrap(); + let input = td.path().join("app.exe"); + std::fs::write(&input, fake_protected_pe()).unwrap(); + // A sibling `._` that cannot be this stub's payload. + let mut companion = input.file_name().unwrap().to_os_string(); + companion.push("._"); + std::fs::write(input.with_file_name(companion), vec![0xFFu8; 32]).unwrap(); + + let output = run(&["inspect", input.to_str().unwrap(), "--json"]); + assert!( + output.status.success(), + "inspection does not fail on a bad pairing" + ); + let value = parse_json(&output); + let input = &value["inputs"][0]; + assert_eq!(input["profile"]["recognition"], "recognized"); + assert_eq!(input["companion"]["state"], "unmatched"); + assert!(input["companion"]["path"].is_string()); + assert_eq!(input["profile"]["observed"]["external_companion"], false); + assert!(input["outputs"].as_array().unwrap().is_empty()); +} + +#[test] +fn unpack_reports_the_companion_state_it_actually_used() { + let td = tempfile::tempdir().unwrap(); + let input = td.path().join("app.exe"); + std::fs::write(&input, fake_protected_pe()).unwrap(); + let out = td.path().join("out"); + let output = run(&[ + input.to_str().unwrap(), + "--out", + out.to_str().unwrap(), + "--json", + ]); + let value = parse_json(&output); + let reported = &value["inputs"][0]; + // No companion was present, and the report says exactly that. + assert_eq!(reported["companion"]["state"], "absent"); + assert!(reported["companion"]["path"].is_null()); + // The failure is recorded on the input, and the profile says which route ran. + assert_eq!(reported["status"], "error"); + assert_eq!(reported["profile"]["recovery"], "failed"); + let candidates = reported["profile"]["candidates"].as_array().unwrap(); + assert!(!candidates.is_empty(), "the attempted route is recorded"); + assert!(candidates.iter().any(|c| c["outcome"] == "failed")); +} + +#[test] +fn a_relative_path_is_reported_verbatim() { + let td = tempfile::tempdir().unwrap(); + write_plain(td.path(), "plain.exe"); + let output = Command::new(env!("CARGO_BIN_EXE_senbei")) + .current_dir(td.path()) + .args(["--no-pause", "inspect", "plain.exe", "--json"]) + .output() + .unwrap(); + let value = parse_json(&output); + assert_eq!(value["inputs"][0]["path"], "plain.exe"); +} diff --git a/senbei-io/Cargo.toml b/senbei-io/Cargo.toml index d59ac89..8eb6708 100644 --- a/senbei-io/Cargo.toml +++ b/senbei-io/Cargo.toml @@ -15,6 +15,8 @@ senbei-engine.workspace = true senbei-elf.workspace = true senbei-pe.workspace = true senbei-metadata.workspace = true +serde.workspace = true +serde_json.workspace = true sha2.workspace = true tempfile.workspace = true walkdir.workspace = true diff --git a/senbei-io/src/android/context.rs b/senbei-io/src/android/context.rs index f416699..88676e4 100644 --- a/senbei-io/src/android/context.rs +++ b/senbei-io/src/android/context.rs @@ -490,6 +490,11 @@ pub(crate) struct RestoredLibrary { pub embedded_metadata: Option>, pub method_index_module: Option>, pub module_image: Option, + /// Structural diagnostics from the engine's validation pass over the output + /// it just wrote. `None` means the restorer produced no report at all (a + /// test double, or an engine without a validation pass) — never that the + /// output validated. `Some(empty)` is a completed, clean validation. + pub validation: Option, } /// Injectable library restore. Tests supply a fake so application-context diff --git a/senbei-io/src/android/mod.rs b/senbei-io/src/android/mod.rs index 00bac4a..38b1bfc 100644 --- a/senbei-io/src/android/mod.rs +++ b/senbei-io/src/android/mod.rs @@ -40,6 +40,7 @@ use sha2::{Digest, Sha256}; use zip::ZipArchive; pub use crate::METADATA_FILE_NAME; +use crate::report::{ContainerReport, ManifestReport}; /// Package extensions recognised as Android app packages. Packages are /// *containers*: membership is decided by extension plus the ZIP magic, while @@ -83,6 +84,162 @@ pub fn is_app_package(path: &Path, prefix: &[u8]) -> bool { is_package_name(path) && prefix.starts_with(b"PK\x03\x04") } +/// Inventory an app package without restoring anything. +/// +/// Reads the ZIP central directories and the bounded root manifests only; no +/// `.so` or `global-metadata.dat` entry is extracted, so this is a membership +/// report, not an inspection of protected content. Entries that a restore +/// *would* probe are listed by name. +pub fn inspect_package(package: &Path, limits: &ResourceLimits) -> Result { + let kind = package + .extension() + .and_then(|value| value.to_str()) + .map(|value| value.to_ascii_lowercase()) + .unwrap_or_default(); + let bundle = kind == "apks" || kind == "xapk"; + let mut budget = archive_limits::ArchiveBudget::from_limits(limits); + let mut archive = budget.open_archive(package)?; + let entry_count = archive.len(); + let mut manifests = Vec::new(); + let mut candidate_entries = Vec::new(); + let mut nested_packages = Vec::new(); + + let mut nested_indices = Vec::new(); + for index in 0..archive.len() { + let (name, is_dir) = { + let entry = archive.by_index(index)?; + (entry.enclosed_name(), entry.is_dir()) + }; + if is_dir { + continue; + } + let Some(name) = name else { + bail!("unsafe entry path in package `{}`", package.display()); + }; + if bundle { + if name + .extension() + .and_then(|value| value.to_str()) + .is_some_and(|value| value.eq_ignore_ascii_case("apk")) + { + nested_indices.push(index); + nested_packages.push(name.display().to_string()); + } + } else if is_android_entry_name(&name) { + candidate_entries.push(name.display().to_string()); + } + } + + if !bundle { + let inventory = context::inventory_manifest_package( + &mut archive, + package, + package + .parent() + .filter(|parent| !parent.as_os_str().is_empty()) + .unwrap_or_else(|| Path::new(".")), + &package.display().to_string(), + &mut budget, + )?; + manifests.push(manifest_report(&package.display().to_string(), &inventory)); + return Ok(ContainerReport { + kind, + manifests, + entry_count, + candidate_entries, + nested_packages, + }); + } + + // A bundle: each nested APK is its own package. Extract it to a temporary + // file (no protected entry is read) so its manifest can name it. + std::mem::drop(archive); + let temporary = tempfile::tempdir().context("create inventory workspace")?; + let mut budget = archive_limits::ArchiveBudget::from_limits(limits); + let mut archive = budget.open_archive(package)?; + for index in nested_indices { + let name = { + let entry = archive.by_index(index)?; + entry.enclosed_name() + }; + let Some(name) = name else { + continue; + }; + let path = extract_entry(&mut archive, index, &temporary, &name, &mut budget) + .with_context(|| format!("extract `{}`", name.display()))?; + let mut nested = budget.open_archive(&path)?; + let inventory = context::inventory_manifest_package( + &mut nested, + &path, + package, + &name.display().to_string(), + &mut budget, + )?; + manifests.push(manifest_report(&name.display().to_string(), &inventory)); + for nested_index in 0..nested.len() { + let (entry_name, is_dir) = { + let entry = nested.by_index(nested_index)?; + (entry.enclosed_name(), entry.is_dir()) + }; + if is_dir { + continue; + } + if let Some(entry_name) = entry_name + && is_android_entry_name(&entry_name) + { + candidate_entries.push(format!("{}::{}", name.display(), entry_name.display())); + } + } + } + Ok(ContainerReport { + kind, + manifests, + entry_count, + candidate_entries, + nested_packages, + }) +} + +fn manifest_report(source: &str, inventory: &context::PackageInventory) -> ManifestReport { + let (package, version) = match &inventory.key { + context::AppKey::Manifest { + package, version, .. + } => (Some(package.clone()), Some(version.clone())), + _ => (None, None), + }; + ManifestReport { + source: source.to_owned(), + named: package.is_some() && version.is_some(), + package, + version, + } +} + +/// Structural diagnostics the restore engine reported for one output. +/// +/// These are the cross-table findings from the engine's own validation pass +/// (see [`senbei_engine::android::RestoreReport`]). A restore that returns +/// success still validates; a finding here says a linker could not walk a table +/// in the bytes that were produced. It never fails a restore, so it is reported +/// as a warning, never as an error. Restorers that cannot report one leave the +/// field empty. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct ValidationDiagnostics { + pub messages: Vec, +} + +impl ValidationDiagnostics { + /// A completed validation with no findings. + pub fn clean() -> Self { + Self::default() + } + + /// True when the validation ran and found nothing. + pub fn is_clean(&self) -> bool { + self.messages.is_empty() + } +} + /// Probe a file on disk: true when it is a protected AArch64 library. /// Reads the whole file (the payload section is found through the /// section-header table at the end); call only after [`is_elf64_aarch64`] @@ -97,6 +254,27 @@ pub fn is_protected_so_file(path: &Path) -> bool { is_elf64_aarch64(&bytes) && is_protected_libil2cpp(&bytes) } +/// [`probe_so_file_with_limits`] with the recognition profile it produced. +/// +/// A resource-limit failure is reported as `Blocked` with the error retained, +/// never as "not protected". +pub(crate) fn probe_so_profiled( + path: &Path, + limits: &ResourceLimits, +) -> Result<(senbei_engine::ProtectionProfile, Result)> { + let file = File::open(path).with_context(|| format!("open `{}`", path.display()))?; + let bytes = map_read_only(&file, path)?; + if !is_elf64_aarch64(&bytes) { + return Ok(( + senbei_engine::ProtectionProfile::new(senbei_engine::ObservedTarget::android(None)), + Ok(false), + )); + } + let (profile, result) = + senbei_engine::android::probe_libil2cpp_profiled_with_limits(&bytes, limits); + Ok((profile, result.map_err(|error| error.to_string()))) +} + pub(crate) fn probe_so_file_with_limits( path: &Path, limits: &senbei_engine::android::ResourceLimits, @@ -168,7 +346,7 @@ pub(crate) fn restore_so_with_engine_limits( .pop() .map(|(image, bytes)| (Some(image), Some(bytes))) .unwrap_or((None, None)); - restore_libil2cpp_with_limits( + let report = restore_libil2cpp_with_limits( &RestoreOptions { input: input.to_path_buf(), output: dest.to_path_buf(), @@ -181,6 +359,11 @@ pub(crate) fn restore_so_with_engine_limits( limits, ) .context("restore protected library")?; + // 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 { + messages: report.validation.diagnostics, + }); let restored_file = File::open(dest).with_context(|| format!("read restored `{}`", dest.display()))?; let restored = map_read_only(&restored_file, dest)?; @@ -188,6 +371,7 @@ pub(crate) fn restore_so_with_engine_limits( embedded_metadata: senbei_metadata::android::extract_embedded_metadata(&restored), method_index_module, module_image, + validation, }) } @@ -202,9 +386,22 @@ pub fn restore_so_file_with_limits( verbose: bool, limits: &ResourceLimits, ) -> Result>> { - Ok(context::EngineRestorer(*limits) - .restore(input, dest, verbose)? - .embedded_metadata) + Ok(restore_so_file_with_diagnostics(input, dest, verbose, limits)?.0) +} + +/// [`restore_so_file_with_limits`], also returning the validation diagnostics +/// the engine reported for the image it just wrote. +/// +/// The diagnostics come from that restore's own report; nothing is re-read or +/// re-validated. They are advisory and never fail the restore. +pub fn restore_so_file_with_diagnostics( + input: &Path, + dest: &Path, + verbose: bool, + limits: &ResourceLimits, +) -> Result<(Option>, Option)> { + let restored = context::EngineRestorer(*limits).restore(input, dest, verbose)?; + Ok((restored.embedded_metadata, restored.validation)) } /// Fresh run-scoped cache. Library hits reuse their module context; metadata hits @@ -234,6 +431,9 @@ pub(crate) struct LooseLibraryOutcome { pub status: EntryStatus, /// Embedded metadata already written as part of this successful restore. pub embedded: Option, + /// Structural diagnostics from the restore that produced this output. + /// `None` for duplicates, failures, and restorers without a report. + pub validation: Option, } pub(crate) fn restore_loose_library( @@ -273,6 +473,7 @@ fn restore_loose_library_with( return Ok(LooseLibraryOutcome { status: EntryStatus::Duplicate, embedded: None, + validation: None, }); } // A prior content-only success still needs context extraction. Restore it @@ -297,6 +498,7 @@ fn restore_loose_library_with( return Ok(LooseLibraryOutcome { status: EntryStatus::Failed(error), embedded: None, + validation: None, }); } embedded = Some(meta_dest); @@ -314,11 +516,15 @@ fn restore_loose_library_with( EntryStatus::Restored }, 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 }, }) } Err(error) => Ok(LooseLibraryOutcome { status: EntryStatus::Failed(error), embedded: None, + validation: None, }), } } @@ -330,6 +536,8 @@ pub(crate) struct LooseMetadataOutcome { pub version: u32, pub remapped: usize, pub provenance: Vec, + /// Route the transform actually took (seeded, structural, or method-index). + pub layout: senbei_engine::LayoutKind, } pub(crate) fn restore_loose_metadata( @@ -363,7 +571,7 @@ 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) = + let (out, report, layout) = restore_metadata_bytes_with_module(&data, module).with_context(|| label.to_owned())?; if report.remapped > 0 { write_metadata_blob(dest, &out)?; @@ -375,6 +583,7 @@ pub(crate) fn restore_loose_metadata( version: report.version, remapped: report.remapped, provenance, + layout, }) } @@ -528,13 +737,15 @@ pub fn content_identity(data: &[u8]) -> String { /// canonical form. Both paths are no-ops (`remapped == 0`) on an /// already-clean blob. pub fn restore_metadata_bytes(data: &[u8]) -> anyhow::Result<(Vec, senbei_metadata::Report)> { - restore_metadata_bytes_with_module(data, None) + let (out, report, _route) = restore_metadata_bytes_with_module(data, None)?; + Ok((out, report)) } pub(crate) fn restore_metadata_bytes_with_module( data: &[u8], method_index_module: Option<&[u8]>, -) -> anyhow::Result<(Vec, senbei_metadata::Report)> { +) -> anyhow::Result<(Vec, senbei_metadata::Report, senbei_engine::LayoutKind)> { + use senbei_engine::LayoutKind; let version = data .get(4..8) .and_then(|bytes| <[u8; 4]>::try_from(bytes).ok()) @@ -556,6 +767,7 @@ pub(crate) fn restore_metadata_bytes_with_module( remapped: report.changed_indices, modules: 0, }, + LayoutKind::MetadataMethodIndices, )); } if let Ok(discovery) = senbei_metadata::android::discover_method_token_seeds(data) @@ -579,12 +791,13 @@ pub(crate) fn restore_metadata_bytes_with_module( remapped: report.changed_tokens, modules: report.images_with_methods, }, + LayoutKind::MetadataSeeded, )); } } } let (out, report) = senbei_metadata::deobfuscate(data).map_err(anyhow::Error::new)?; - Ok((out, report)) + Ok((out, report, LayoutKind::MetadataStructural)) } /// What happened to one archive entry (or one loose Android target). @@ -600,6 +813,13 @@ pub struct EntryOutcome { /// Libraries whose module `0x0C` was paired with this metadata entry. /// Empty for libraries and for metadata that had no paired module. pub provenance: Vec, + /// Route the transform took, for metadata entries only. + pub layout: Option, + /// Raw il2cpp metadata version, for metadata entries only. + pub metadata_version: Option, + /// Structural diagnostics from the restore of this entry. `None` for + /// metadata entries, duplicates, and restorers without a report. + pub validation: Option, } #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -965,6 +1185,9 @@ fn restore_package_entry( kind, status, provenance, + layout: None, + metadata_version: None, + validation: None, }; if !is_so && !is_meta { return Ok(vec![outcome( @@ -1010,7 +1233,12 @@ fn restore_package_entry( let mut outcomes = Vec::new(); let mut embedded_failed = None; if !prior { - outcomes.push(outcome(EntryKind::So, EntryStatus::Restored, Vec::new())); + // The engine's own validation diagnostics for exactly + // these bytes; nothing is re-validated here. + let mut restored_outcome = + outcome(EntryKind::So, EntryStatus::Restored, Vec::new()); + restored_outcome.validation = restored.validation.clone(); + outcomes.push(restored_outcome); } if !prior && let Some(blob) = &restored.embedded_metadata { let meta_dest = embedded_metadata_dest(dest); @@ -1021,6 +1249,9 @@ fn restore_package_entry( kind: EntryKind::EmbeddedMetadata, status: EntryStatus::Restored, provenance: Vec::new(), + layout: None, + metadata_version: None, + validation: None, }), Err(error) => embedded_failed = Some(error), } @@ -1088,18 +1319,17 @@ fn restore_package_entry( remapped: *remapped, }, }; - return Ok(vec![outcome( - kind, - EntryStatus::Duplicate, - provenance_labels(&provenance), - )]); + let mut entry_outcome = + outcome(kind, EntryStatus::Duplicate, provenance_labels(&provenance)); + entry_outcome.metadata_version = version; + return Ok(vec![entry_outcome]); } // 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_and_status = match restore_metadata_bytes_with_module(&entry_data, module) { - Ok((out, report)) if report.remapped > 0 => { + 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, }; @@ -1112,29 +1342,34 @@ fn restore_package_entry( remapped: report.remapped, }, ); - (kind, EntryStatus::Restored) + (kind, EntryStatus::Restored, Some(layout)) } - Err(error) => (kind, EntryStatus::Failed(error)), + Err(error) => (kind, EntryStatus::Failed(error), Some(layout)), } } - Ok(_) => { + // 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) + ( + EntryKind::Metadata { remapped: 0 }, + EntryStatus::Unchanged, + Some(layout), + ) } Err(error) => ( EntryKind::Metadata { remapped: 0 }, EntryStatus::Failed(error), + None, ), }; - Ok(vec![outcome( - kind_and_status.0, - kind_and_status.1, - provenance_labels(&provenance), - )]) + let mut entry_outcome = outcome(kind, status, provenance_labels(&provenance)); + entry_outcome.layout = layout; + entry_outcome.metadata_version = version; + Ok(vec![entry_outcome]) } fn record_module( diff --git a/senbei-io/src/android/tests.rs b/senbei-io/src/android/tests.rs index 7634ea5..ff15e65 100644 --- a/senbei-io/src/android/tests.rs +++ b/senbei-io/src/android/tests.rs @@ -33,6 +33,9 @@ impl LibraryRestorer for ScriptedRestorer { embedded_metadata: self.embedded.clone(), method_index_module: Some(module), module_image: Some("module-0c.bin".to_owned()), + // A scripted restore has no engine report behind it, so it claims + // no validation verdict at all. + validation: None, }) } @@ -45,6 +48,33 @@ impl LibraryRestorer for ScriptedRestorer { } } +/// A [`ScriptedRestorer`] that also reports validation diagnostics, as a real +/// engine restore does. Kept separate so the many existing scripted cases keep +/// meaning "no engine report". +struct DiagnosticRestorer { + inner: ScriptedRestorer, + diagnostics: Vec, +} + +impl LibraryRestorer for DiagnosticRestorer { + fn restore( + &mut self, + input: &Path, + dest: &Path, + verbose: bool, + ) -> anyhow::Result { + let mut restored = self.inner.restore(input, dest, verbose)?; + restored.validation = Some(ValidationDiagnostics { + messages: self.diagnostics.clone(), + }); + Ok(restored) + } + + fn protected_override(&mut self, input: &Path) -> Option> { + self.inner.protected_override(input) + } +} + fn pair(seed: u32) -> (Vec, Vec) { // Local copy of the v24.1 fixture transform. Seeds 1..=5 and `0x77700DCC` // miss exactly `0..255` after the repeated high-half image, which is the @@ -1223,3 +1253,99 @@ fn axml_attr(name: u32, raw: u32, value_type: u8, data: u32) -> Vec { record.extend(u32::to_le_bytes(data)); record } + +/// The engine's validation diagnostics travel from a restore into the entry +/// outcome a reporter reads, for loose libraries and package entries alike. +/// +/// They are advisory: the restore still succeeds, the output is still written, +/// and nothing is re-validated or re-read to produce them. +#[test] +fn validation_diagnostics_reach_restored_outcomes() { + let temp = tempfile::tempdir().unwrap(); + let root = temp.path(); + let finding = "dynamic symbol table is not referenced by a load segment"; + let library = library_bytes(b"diag"); + 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).unwrap(); + + let mut cache = run_cache(); + let mut restorer = DiagnosticRestorer { + inner: ScriptedRestorer { + embedded: None, + modules: vec![(library, vec![0xAB; 16])], + }, + diagnostics: vec![finding.to_owned()], + }; + + let scoped = loose_scopes(std::slice::from_ref(&so), &[]); + let outcome = restore_loose_library_with( + &so, + &root.join("out.so"), + "libil2cpp.so", + &scoped[0].key, + false, + &mut cache, + &mut restorer, + ) + .unwrap(); + assert!(matches!(outcome.status, EntryStatus::Restored)); + assert_eq!( + outcome.validation.as_ref().map(|v| v.messages.clone()), + Some(vec![finding.to_owned()]) + ); + assert!(root.join("out.so").is_file(), "the output is still written"); + + // Repeated bytes are a duplicate: no output of their own, so no verdict. + let duplicate = restore_loose_library_with( + &so, + &root.join("out-duplicate.so"), + "libil2cpp.so", + &scoped[0].key, + false, + &mut cache, + &mut restorer, + ) + .unwrap(); + assert!(matches!(duplicate.status, EntryStatus::Duplicate)); + assert!( + duplicate.validation.is_none(), + "a duplicate restored only for its module context reports no verdict" + ); +} + +/// A restorer with no engine report leaves the verdict empty instead of +/// claiming a clean validation it never performed. +#[test] +fn scripted_restore_claims_no_validation_verdict() { + let temp = tempfile::tempdir().unwrap(); + let root = temp.path(); + let library = library_bytes(b"no-report"); + 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).unwrap(); + + let mut cache = run_cache(); + let mut restorer = ScriptedRestorer { + embedded: None, + modules: vec![(library, vec![0xCD; 16])], + }; + let scoped = loose_scopes(std::slice::from_ref(&so), &[]); + let outcome = restore_loose_library_with( + &so, + &root.join("out.so"), + "libil2cpp.so", + &scoped[0].key, + false, + &mut cache, + &mut restorer, + ) + .unwrap(); + assert!(matches!(outcome.status, EntryStatus::Restored)); + assert!( + outcome.validation.is_none(), + "a restorer without a report must not claim a clean verdict" + ); +} diff --git a/senbei-io/src/job.rs b/senbei-io/src/job.rs index 5641bec..cff7a5c 100644 --- a/senbei-io/src/job.rs +++ b/senbei-io/src/job.rs @@ -1,8 +1,16 @@ use std::path::{Path, PathBuf}; +use std::time::Instant; use crate::atomic::write_atomic; +pub use crate::report::{Collector, Mode, REPORT_FORMAT_VERSION, Report}; +use crate::report::{ + CompanionReport, CompanionState, ContainerReport, EntryKind, EntryReport, EntryStatus, + InputReport, InputStatus, OutputFile, Role, Stage, StageReport, StageStatus, +}; pub use crate::windows::{ - UnpackedImage, unpack_bytes, unpack_bytes_force_exe, unpack_one, unpack_one_v, + UnpackedImage, unpack_bytes, unpack_bytes_force_exe, unpack_bytes_force_exe_profiled, + unpack_bytes_force_exe_profiled_v, unpack_bytes_profiled, unpack_bytes_profiled_v, unpack_one, + unpack_one_v, }; /// Summary of a folder-mode run. @@ -116,6 +124,63 @@ pub fn run_folder_with_limits( no_log: bool, scan_all: bool, limits: &senbei_engine::android::ResourceLimits, +) -> anyhow::Result { + run_folder_inner( + root, out_dir, quiet, verbose, no_log, scan_all, limits, None, + ) +} + +/// Folder mode, additionally recording a per-input report. +/// +/// Behaviour, ordering, deduplication, and outputs are those of +/// [`run_folder_with_limits`]; the collector only observes. +#[allow(clippy::too_many_arguments)] +pub fn run_folder_reported( + root: &Path, + out_dir: Option<&Path>, + quiet: u8, + verbose: bool, + no_log: bool, + scan_all: bool, + limits: &senbei_engine::android::ResourceLimits, + report: &mut Collector, +) -> anyhow::Result { + run_folder_inner( + root, + out_dir, + quiet, + verbose, + no_log, + scan_all, + limits, + Some(report), + ) +} + +/// A report carrying only a run-level failure. +/// +/// Used when a run cannot start at all (an unreadable input, a rejected +/// command line), so `--json` callers still receive one versioned document. +pub fn error_report(mode: Mode, message: &str) -> Report { + let mut collector = Collector::new(mode); + collector.push_error(message); + collector.finish() +} + +/// Folder mode, additionally recording a per-input report. +/// +/// Behaviour, ordering, deduplication, and outputs are those of +/// [`run_folder_with_limits`]; the collector only observes. +#[allow(clippy::too_many_arguments)] +fn run_folder_inner( + root: &Path, + out_dir: Option<&Path>, + quiet: u8, + verbose: bool, + no_log: bool, + scan_all: bool, + limits: &senbei_engine::android::ResourceLimits, + mut reporter: Option<&mut Collector>, ) -> anyhow::Result { let t0 = std::time::Instant::now(); let out_root = out_dir @@ -185,20 +250,38 @@ pub fn run_folder_with_limits( errors: scan_failed, ..Summary::default() }; + if let Some(reporter) = reporter.as_deref_mut() { + reporter.set_scan(crate::report::ScanReport { + non_target_skipped: scan_stats.skipped, + walk_errors: scan_stats.walk_errors, + probe_errors: scan_stats.probe_errors, + }); + } for input in candidates { let rel = rel_in_tree(root, input); let dest = out_root.join(out_name(&rel)); + let started = Instant::now(); // Wrap in catch_unwind so a single bad file never aborts the folder run. + // A reporting run goes through the profiled entry point so the report + // carries the route the pipeline actually selected; an ordinary run + // keeps the unchanged call. + let profiled = reporter.is_some(); let input_owned = input.clone(); let dest_owned = dest.clone(); let result = senbei_engine::catch_unwind_quiet(|| { - unpack_one_v(&input_owned, &dest_owned, verbose_steps) + if profiled { + let (profile, result) = + unpack_one_profiled(&input_owned, &dest_owned, verbose_steps); + (Some(profile), result) + } else { + (None, unpack_one_v(&input_owned, &dest_owned, verbose_steps)) + } }); match result { - Ok(Ok((kind, report))) => { + Ok((profile, Ok((kind, report)))) => { s.unpacked += 1; crate::ui::ok(&bar, suppress_file_lines, &rel, kind, &dest); if let Some(log) = &log { @@ -211,13 +294,22 @@ pub fn run_folder_with_limits( log.step(&format!("SUSPECT {rel:?}: {}", report.issues.join("; "))); } } + if let Some(reporter) = reporter.as_deref_mut() { + reporter.push(windows_input(input, &dest, kind, &report, profile, started)); + } } - Ok(Err(e)) => { + Ok((profile, Err(e))) => { s.errors += 1; crate::ui::err(&bar, suppress_file_lines, &rel, &e); if let Some(log) = &log { log.step(&format!("ERR {rel:?}: {e:#}")); } + if let Some(reporter) = reporter.as_deref_mut() { + reporter.push(match profile { + Some(profile) => failed_input_with_profile(input, &e, profile, started), + None => failed_input(input, &e, started), + }); + } } Err(panic) => { s.errors += 1; @@ -229,6 +321,9 @@ pub fn run_folder_with_limits( panic_payload(&panic) )); } + if let Some(reporter) = reporter.as_deref_mut() { + reporter.push(failed_input(input, &e, started)); + } } } bar.inc(1); @@ -252,6 +347,7 @@ pub fn run_folder_with_limits( let dest_owned = dest.clone(); let key = scoped.key.clone(); let label = rel.display().to_string(); + let started = Instant::now(); let result = senbei_engine::catch_unwind_quiet(|| { crate::android::restore_loose_library( &input_owned, @@ -262,6 +358,8 @@ pub fn run_folder_with_limits( &mut android_cache, ) }); + let report_outcome; + let mut report_validation: Option = None; match result { Ok(Ok(outcome)) => match outcome.status { crate::android::EntryStatus::Duplicate => { @@ -269,6 +367,7 @@ pub fn run_folder_with_limits( if let Some(log) = &log { log.step(&format!("SKIP {rel:?}: duplicate of an earlier target")); } + report_outcome = Some(InputStatus::Skipped); } crate::android::EntryStatus::Failed(e) => { s.errors += 1; @@ -276,9 +375,25 @@ pub fn run_folder_with_limits( if let Some(log) = &log { log.step(&format!("ERR {rel:?}: {e:#}")); } + report_outcome = Some(InputStatus::Error); } crate::android::EntryStatus::Restored => { s.unpacked += 1; + // Surface the engine's advisory findings. They never fail + // a restore, so they stay warnings on the same log/UI path. + report_validation = outcome.validation.clone(); + if let Some(validation) = &report_validation { + if !suppress_file_lines { + for message in &validation.messages { + eprintln!("- {} {}", rel.display(), message); + } + } + if let Some(log) = &log { + for message in &validation.messages { + log.step(&format!("WARN {rel:?}: {message}")); + } + } + } crate::ui::ok_label( &bar, suppress_file_lines, @@ -302,9 +417,11 @@ pub fn run_folder_with_limits( log.step(&format!("META {rel:?} (embedded) -> {meta_dest:?}")); } } + report_outcome = Some(InputStatus::Ok); } crate::android::EntryStatus::NotTarget | crate::android::EntryStatus::Unchanged => { s.skipped += 1; + report_outcome = Some(InputStatus::Skipped); } }, Ok(Err(e)) => { @@ -313,6 +430,7 @@ pub fn run_folder_with_limits( if let Some(log) = &log { log.step(&format!("ERR {rel:?}: {e:#}")); } + report_outcome = Some(InputStatus::Error); } Err(panic) => { s.errors += 1; @@ -324,8 +442,16 @@ pub fn run_folder_with_limits( panic_payload(&panic) )); } + report_outcome = Some(InputStatus::Error); } } + if let Some(reporter) = reporter.as_deref_mut() + && let Some(status) = report_outcome + { + let mut reported = android_library_input(&scoped.path, status, &dest, started); + apply_android_validation(&mut reported, report_validation.as_ref()); + reporter.push(reported); + } bar.inc(1); } // Loose sibling APKs that name the same package and version are one split @@ -340,6 +466,7 @@ pub fn run_folder_with_limits( let group_owned = group.clone(); let root_owned = root.to_path_buf(); let out_root_owned = out_root.clone(); + let group_started = Instant::now(); let result = senbei_engine::catch_unwind_quiet(|| { crate::android::restore_apk_group( &group_owned, @@ -352,6 +479,20 @@ pub fn run_folder_with_limits( let rel = rel_in_tree(root, &group[0]); match result { Ok(Ok(outcomes)) => { + // The summary and UI keep the flat split-set order; each + // split is additionally reported as its own container input, + // matched by the `::` label prefix. + if let Some(reporter) = reporter.as_deref_mut() { + for package in group { + let rel = rel_in_tree(root, package); + let prefix = format!("{}::", rel.display()); + let entries: Vec<_> = outcomes + .iter() + .filter(|outcome| outcome.label.starts_with(&prefix)) + .collect(); + reporter.push(package_input(package, entries, group_started)); + } + } apply_package_outcomes(outcomes, &mut s, &bar, suppress_file_lines, &log); } Ok(Err(e)) => { @@ -382,6 +523,7 @@ pub fn run_folder_with_limits( let package_owned = package.clone(); let rel_owned = rel.clone().into_owned(); let out_root_owned = out_root.clone(); + let started = Instant::now(); let result = senbei_engine::catch_unwind_quiet(|| { crate::android::restore_package_cached( &package_owned, @@ -393,6 +535,9 @@ pub fn run_folder_with_limits( }); match result { Ok(Ok(outcomes)) => { + if let Some(reporter) = reporter.as_deref_mut() { + reporter.push(package_input(package, outcomes.iter().collect(), started)); + } apply_package_outcomes(outcomes, &mut s, &bar, suppress_file_lines, &log); } Ok(Err(e)) => { @@ -401,6 +546,9 @@ pub fn run_folder_with_limits( if let Some(log) = &log { log.step(&format!("ERR {rel:?}: {e:#}")); } + if let Some(reporter) = reporter.as_deref_mut() { + reporter.push(failed_input(package, &e, started)); + } } Err(panic) => { // A panic may leave a partial module recorded. Keeping the cache @@ -414,6 +562,9 @@ pub fn run_folder_with_limits( panic_payload(&panic) )); } + if let Some(reporter) = reporter.as_deref_mut() { + reporter.push(failed_input(package, &e, started)); + } } } bar.inc(1); @@ -435,6 +586,7 @@ pub fn run_folder_with_limits( let dest_owned = dest.clone(); let key = scoped.key.clone(); let label = rel.display().to_string(); + let started = Instant::now(); let result = senbei_engine::catch_unwind_quiet(|| { crate::android::restore_loose_metadata( &meta_owned, @@ -457,6 +609,9 @@ pub fn run_folder_with_limits( provenance_suffix(&report.provenance) )); } + if let Some(reporter) = reporter.as_deref_mut() { + reporter.push(metadata_input(&scoped.path, &report, Some(&dest), started)); + } } // Recognised metadata that needed no change (not -GMD-obfuscated): // leave it untouched and don't write a redundant copy. @@ -468,6 +623,9 @@ pub fn run_folder_with_limits( provenance_suffix(&report.provenance) )); } + if let Some(reporter) = reporter.as_deref_mut() { + reporter.push(metadata_input(&scoped.path, &report, None, started)); + } } Ok(Err(e)) => { // A metadata version we don't handle is NOT a run failure: the @@ -478,7 +636,8 @@ pub fn run_folder_with_limits( // contract. Genuine corruption (Malformed) stays an error — // silently exiting 0 would let a failed de-obfuscation pass CI // while the il2cpp game assembly still crashes. - if let Some(v) = unsupported_version(&e) { + let unsupported = unsupported_version(&e); + if let Some(v) = unsupported { s.skipped += 1; if !suppress_file_lines { eprintln!( @@ -498,6 +657,29 @@ pub fn run_folder_with_limits( log.step(&format!("META ERR {rel:?}: {e:#}")); } } + if let Some(reporter) = reporter.as_deref_mut() { + let mut input = failed_input(&scoped.path, &e, started); + let identity = identity_of(&scoped.path); + input.metadata = identity; + input.metadata_version = + unsupported.or_else(|| identity.map(|identity| identity.raw_version)); + if let Some(version) = unsupported { + // Left untouched by design; not a failure of this run. + input.status = InputStatus::Skipped; + input.errors.clear(); + input.profile = Some(crate::report::metadata_unchanged_profile(identity)); + input.warning(format!( + "unsupported metadata version {version}, left untouched" + )); + } else { + input.profile = Some(crate::report::metadata_failed_profile( + identity, + senbei_engine::LayoutKind::MetadataStructural, + &format!("{e:#}"), + )); + } + reporter.push(input); + } } Err(panic) => { s.errors += 1; @@ -512,6 +694,9 @@ pub fn run_folder_with_limits( panic_payload(&panic) )); } + if let Some(reporter) = reporter.as_deref_mut() { + reporter.push(failed_input(&scoped.path, &e, started)); + } } } } @@ -555,6 +740,35 @@ pub fn run_file_with_limits( verbose: bool, no_log: bool, limits: &senbei_engine::android::ResourceLimits, +) -> anyhow::Result { + run_file_inner(input, out_dir, quiet, verbose, no_log, limits, None) +} + +/// Single-file mode, additionally recording a per-input report. +/// +/// Routing, output paths, and messages are those of +/// [`run_file_with_limits`]; the collector only observes. +pub fn run_file_reported( + input: &Path, + out_dir: Option<&Path>, + quiet: u8, + verbose: bool, + no_log: bool, + limits: &senbei_engine::android::ResourceLimits, + report: &mut Collector, +) -> anyhow::Result { + run_file_inner(input, out_dir, quiet, verbose, no_log, limits, Some(report)) +} + +#[allow(clippy::too_many_arguments)] +fn run_file_inner( + input: &Path, + out_dir: Option<&Path>, + quiet: u8, + verbose: bool, + no_log: bool, + limits: &senbei_engine::android::ResourceLimits, + mut reporter: Option<&mut Collector>, ) -> anyhow::Result { let t0 = std::time::Instant::now(); let out_root = out_dir @@ -602,8 +816,8 @@ pub fn run_file_with_limits( let is_android_package = !is_android_so && crate::android::is_app_package(input, &prefix); if is_meta { - match deobfuscate_metadata_to(input, &dest, verbose && quiet == 0) { - Ok(report) if report.remapped > 0 => { + match deobfuscate_metadata_to_with_module(input, &dest, verbose && quiet == 0, None) { + Ok((report, layout)) if report.remapped > 0 => { s.metadata = 1; if let Some(log) = &log { log.step(&format!( @@ -617,8 +831,17 @@ pub fn run_file_with_limits( report.version, dest, report.remapped ); } + if let Some(reporter) = reporter.as_deref_mut() { + reporter.push(single_metadata_input( + input, + &report, + layout, + Some(&dest), + t0, + )); + } } - Ok(report) => { + Ok((report, layout)) => { if let Some(log) = &log { log.step(&format!( "META {:?}: v{} already de-obfuscated", @@ -631,6 +854,9 @@ pub fn run_file_with_limits( report.version ); } + if let Some(reporter) = reporter.as_deref_mut() { + reporter.push(single_metadata_input(input, &report, layout, None, t0)); + } } Err(e) => { s.errors = 1; @@ -641,16 +867,28 @@ pub fn run_file_with_limits( if quiet == 0 { eprintln!("error: {e:#}"); } + if let Some(reporter) = reporter.as_deref_mut() { + let mut input_report = failed_input(input, &e, t0); + let identity = identity_of(input); + input_report.metadata = identity; + input_report.metadata_version = identity.map(|identity| identity.raw_version); + input_report.profile = Some(crate::report::metadata_failed_profile( + identity, + senbei_engine::LayoutKind::MetadataStructural, + &format!("{e:#}"), + )); + reporter.push(input_report); + } } } } else if is_android_so { - match crate::android::restore_so_file_with_limits( + match crate::android::restore_so_file_with_diagnostics( input, &dest, verbose && quiet == 0, limits, ) { - Ok(embedded) => { + Ok((embedded, validation)) => { s.unpacked = 1; if let Some(log) = &log { log.step(&format!("OK {:?} -> {:?} (Android SO)", input, dest)); @@ -683,6 +921,11 @@ pub fn run_file_with_limits( } } } + if let Some(reporter) = reporter.as_deref_mut() { + let mut reported = android_library_input(input, InputStatus::Ok, &dest, t0); + apply_android_validation(&mut reported, validation.as_ref()); + reporter.push(reported); + } } Err(e) => { s.errors = 1; @@ -692,6 +935,9 @@ pub fn run_file_with_limits( if quiet == 0 { eprintln!("error: {e:#}"); } + if let Some(reporter) = reporter.as_deref_mut() { + reporter.push(android_library_input(input, InputStatus::Error, &dest, t0)); + } } } } else if is_android_package { @@ -708,6 +954,9 @@ pub fn run_file_with_limits( ) { Ok(outcomes) => { let bar = crate::ui::progress(0, true); + if let Some(reporter) = reporter.as_deref_mut() { + reporter.push(package_input(input, outcomes.iter().collect(), t0)); + } apply_package_outcomes(outcomes, &mut s, &bar, quiet >= 1, &log); } Err(e) => { @@ -718,10 +967,25 @@ pub fn run_file_with_limits( if quiet == 0 { eprintln!("error: {e:#}"); } + if let Some(reporter) = reporter { + reporter.push(failed_input(input, &e, t0)); + } } } } else { - match unpack_one_v(input, &dest, verbose && quiet == 0) { + // A reporting run uses the profiled entry point so the report carries + // the route that was actually selected; the unprofiled call is + // unchanged for every other run. + let profiled = if reporter.is_some() { + Some(unpack_one_profiled(input, &dest, verbose && quiet == 0)) + } else { + None + }; + let (profile, result) = match profiled { + Some((profile, result)) => (Some(profile), result), + None => (None, unpack_one_v(input, &dest, verbose && quiet == 0)), + }; + match result { Ok((kind, report)) => { s.unpacked = 1; if let Some(log) = &log { @@ -746,6 +1010,9 @@ pub fn run_file_with_limits( ); } } + if let Some(reporter) = reporter.as_deref_mut() { + reporter.push(windows_input(input, &dest, kind, &report, profile, t0)); + } } Err(e) => { s.errors = 1; @@ -755,6 +1022,12 @@ pub fn run_file_with_limits( if quiet == 0 { eprintln!("error: {e:#}"); } + if let Some(reporter) = reporter { + reporter.push(match profile { + Some(profile) => failed_input_with_profile(input, &e, profile, t0), + None => failed_input(input, &e, t0), + }); + } } } } @@ -851,7 +1124,7 @@ pub fn deobfuscate_metadata_to( dest: &Path, verbose: bool, ) -> anyhow::Result { - deobfuscate_metadata_to_with_module(input, dest, verbose, None) + deobfuscate_metadata_to_with_module(input, dest, verbose, None).map(|(report, _)| report) } fn deobfuscate_metadata_to_with_module( @@ -859,14 +1132,14 @@ fn deobfuscate_metadata_to_with_module( dest: &Path, verbose: bool, method_index_module: Option<&[u8]>, -) -> anyhow::Result { +) -> anyhow::Result<(senbei_metadata::Report, senbei_engine::LayoutKind)> { let data = std::fs::read(input)?; // The Android seeded-permutation variant is tried first (it validates // every restored RID); the structural remap is the fallback and the // Windows path. The [`senbei_metadata::Error`] is preserved in the chain // (rather than stringified) so the folder driver can apply its // unsupported-version policy. - let (out, report) = + let (out, report, layout) = crate::android::restore_metadata_bytes_with_module(&data, method_index_module) .map_err(|e| e.context(format!("{input:?}")))?; if report.remapped > 0 { @@ -878,7 +1151,7 @@ fn deobfuscate_metadata_to_with_module( println!("Write to {}", dest.display()); } } - Ok(report) + Ok((report, layout)) } /// Write an embedded metadata blob (unwrapped from a restored Android @@ -957,6 +1230,917 @@ fn apply_package_outcomes( } } +// --------------------------------------------------------------------------- +// Inspect and dry-run drivers +// --------------------------------------------------------------------------- + +/// Inspect `path` without recovering or writing anything. +/// +/// Reads only what detection needs: a short prefix per file, the protected +/// library probe for selected `.so` files, package manifests and central +/// directories, and the 8-byte il2cpp metadata header. No output, no log, and +/// no temporary file outside what a package inventory needs to read a nested +/// manifest. The report never claims recovery or a static-validation verdict. +pub fn inspect_path( + path: &Path, + scan_all: bool, + limits: &senbei_engine::android::ResourceLimits, +) -> anyhow::Result { + let mut collector = Collector::new(Mode::Inspect); + if path.is_dir() { + inspect_folder(path, scan_all, limits, &mut collector); + } else { + let started = Instant::now(); + match inspect_file(path, limits) { + Ok(input) => collector.push(input), + Err(error) => collector.push(inspect_failed_input(path, &error, started)), + } + } + Ok(collector.finish()) +} + +fn inspect_folder( + root: &Path, + scan_all: bool, + limits: &senbei_engine::android::ResourceLimits, + collector: &mut Collector, +) { + let scan = crate::scan::find_targets_with_limits(root, scan_all, limits); + collector.set_scan(crate::report::ScanReport { + non_target_skipped: scan.stats.skipped, + walk_errors: scan.stats.walk_errors, + probe_errors: scan.stats.probe_errors, + }); + let mut inputs: Vec<&PathBuf> = Vec::new(); + inputs.extend(scan.crackproof.iter()); + inputs.extend(scan.metadata.iter()); + inputs.extend(scan.android_so.iter()); + inputs.extend(scan.android_packages.iter()); + for path in inputs { + let started = Instant::now(); + match inspect_file(path, limits) { + Ok(input) => collector.push(input), + Err(error) => collector.push(inspect_failed_input(path, &error, started)), + } + } +} + +/// Inspect one file, choosing the report from its content. +fn inspect_file( + input: &Path, + limits: &senbei_engine::android::ResourceLimits, +) -> anyhow::Result { + let started = Instant::now(); + let prefix = read_prefix(input)?; + if senbei_metadata::is_metadata(&prefix) { + return Ok(inspect_metadata(input, &prefix, started)); + } + if crate::android::is_app_package(input, &prefix) { + return inspect_app_package(input, limits, started); + } + if crate::android::is_elf64_aarch64(&prefix) { + return inspect_android_library(input, limits, started); + } + inspect_windows(input, started) +} + +fn read_prefix(path: &Path) -> anyhow::Result> { + use std::io::Read; + let mut file = std::fs::File::open(path)?; + let mut buffer = vec![0_u8; 8 * 1024]; + let read = file.read(&mut buffer)?; + buffer.truncate(read); + Ok(buffer) +} + +/// Inspect a Windows input without recovering it. +/// +/// The stub and its optional `._` sibling are read separately and independently: +/// inspection reports the pairing it observed and never turns a missing or +/// non-pairing sibling into a recovery failure. That matters because the file +/// entry point *does* refuse a companion-declaring stub without its payload — +/// correct for recovery, wrong for a description of what is on disk. +fn inspect_windows(input: &Path, started: Instant) -> anyhow::Result { + // The stub's own bytes must be readable for inspection to say anything. + // Failure here is a genuine read error and fails inspection. + let stub = std::fs::read(input)?; + let (companion, state) = if crate::windows::is_pe_extension(input) { + match read_optional_companion(input) { + // A sibling pairs only when its header matches this stub's payload + // region; `splice_companion` is that exact test. + Ok(Some(payload)) => { + if crate::windows::splice_companion(&stub, &payload).is_some() { + (Some(payload), CompanionState::Spliced) + } else { + // A sibling exists but is not this stub's payload. + (Some(payload), CompanionState::Unmatched) + } + } + Ok(None) => (None, CompanionState::Absent), + // A sibling exists but cannot be read. Inspection still describes + // the stub; the unreadable sibling is reported, not raised. + Err(_) => (None, CompanionState::Unreadable), + } + } else { + (None, CompanionState::Absent) + }; + + // Inspect the bytes recovery would actually unpack: the spliced payload + // when the pairing is real, otherwise the file as it sits on disk. + let spliced_pair = match (state, companion.as_deref()) { + (CompanionState::Spliced, Some(payload)) => { + crate::windows::splice_companion(&stub, payload) + } + _ => None, + }; + let inspected: &[u8] = spliced_pair.as_deref().unwrap_or(&stub); + + let mut profile = senbei_engine::inspect_profile(inspected); + if spliced_pair.is_some() { + // Evidence of a pairing that was actually performed, not of one that + // was merely expected. + profile.record_companion_spliced(); + } + let mut report = InputReport::new(input, Role::Content); + report.status = match profile.recognition { + senbei_engine::RecognitionStatus::Recognized => InputStatus::Recognized, + _ => InputStatus::Skipped, + }; + report.companion = + crate::windows::is_pe_extension(input).then(|| companion_report(input, state)); + // A sibling that does not pair, or cannot be read, describes the input — + // neither is a failure of the inspection. + if let Some(companion) = report.companion.as_mut() { + match companion.state { + CompanionState::Unmatched => { + companion.detail = + Some("a sibling `._` exists but is not this stub's payload".to_owned()); + } + CompanionState::Unreadable => { + companion.detail = Some("the sibling `._` could not be read".to_owned()); + } + _ => {} + } + } + report.profile = Some(profile); + report.stages = vec![ + StageReport::new(Stage::Detection, StageStatus::Ok).timed(crate::report::now_ms(started)), + StageReport::new(Stage::Recovery, StageStatus::Skipped) + .detail("inspection only: no recovery was run"), + ]; + report.duration_ms = crate::report::now_ms(started); + Ok(report) +} + +/// Companion state for a run that only knows whether a payload was spliced. +/// +/// `Spliced` means the pairing actually happened; otherwise any sibling on disk +/// was not this stub's payload. +fn observed_companion_state(input: &Path, spliced: bool) -> CompanionState { + if spliced { + return CompanionState::Spliced; + } + match sibling_path(input) { + Some(path) if path.is_file() => CompanionState::Unmatched, + _ => CompanionState::Absent, + } +} + +/// `._`, the companion payload path for `input`. +fn sibling_path(input: &Path) -> Option { + let name = input.file_name()?; + let mut sibling = name.to_os_string(); + sibling.push("._"); + Some(input.with_file_name(sibling)) +} + +/// What the `._` companion relationship is for `input`, observed on disk. +fn companion_report(input: &Path, state: CompanionState) -> CompanionReport { + let path = sibling_path(input); + CompanionReport { + state, + path: match state { + CompanionState::Absent => None, + _ => path.map(|path| path.display().to_string()), + }, + detail: None, + } +} + +fn inspect_metadata(input: &Path, prefix: &[u8], started: Instant) -> InputReport { + let mut report = InputReport::new(input, Role::Content); + let identity = senbei_metadata::identify(prefix); + report.metadata = identity; + report.metadata_version = identity.map(|identity| identity.raw_version); + // Header identification is a layout/capability fact, not a protection or + // recovery verdict. + report.status = InputStatus::Skipped; + report.profile = Some(crate::report::metadata_unchanged_profile(identity)); + report.stages = vec![ + StageReport::new(Stage::Detection, StageStatus::Ok).timed(crate::report::now_ms(started)), + StageReport::new(Stage::Recovery, StageStatus::Skipped) + .detail("inspection only: no transform was run"), + ]; + report.duration_ms = crate::report::now_ms(started); + report +} + +fn inspect_android_library( + input: &Path, + limits: &senbei_engine::android::ResourceLimits, + started: Instant, +) -> anyhow::Result { + let (profile, result) = crate::android::probe_so_profiled(input, limits)?; + let mut report = InputReport::new(input, Role::Content); + report.status = match (&profile.recognition, &result) { + (senbei_engine::RecognitionStatus::Recognized, _) => InputStatus::Recognized, + _ => InputStatus::Skipped, + }; + if let Err(error) = &result { + report.error(format!("{error:#}")); + report.status = InputStatus::Error; + } + report.profile = Some(profile); + report.stages = vec![ + StageReport::new(Stage::Detection, StageStatus::Ok).timed(crate::report::now_ms(started)), + StageReport::new(Stage::Recovery, StageStatus::Skipped) + .detail("inspection only: no restore was run"), + ]; + report.duration_ms = crate::report::now_ms(started); + Ok(report) +} + +fn inspect_app_package( + input: &Path, + limits: &senbei_engine::android::ResourceLimits, + started: Instant, +) -> anyhow::Result { + let mut report = InputReport::new(input, Role::Container); + let container = crate::android::inspect_package(input, limits)?; + report.status = InputStatus::Skipped; + report.container = Some(container); + report.stages = vec![ + StageReport::new(Stage::ManifestInventory, StageStatus::Ok) + .timed(crate::report::now_ms(started)), + StageReport::new(Stage::EntryProbe, StageStatus::Skipped) + .detail("inspection only: container entries were listed, not probed"), + ]; + report.duration_ms = crate::report::now_ms(started); + Ok(report) +} + +/// Run the real recovery and keep nothing. +/// +/// The recovery path is the ordinary one — same routing, same trial-and-validate +/// layout selection, same Android staged restore — but every output goes to a +/// temporary directory that is dropped afterwards, and no run log is written. +/// The report therefore describes an attempt that really ran, while the caller's +/// filesystem is left untouched (apart from the Android engine's own temporary +/// workspace, which is always discarded). +pub fn dry_run_path( + path: &Path, + scan_all: bool, + limits: &senbei_engine::android::ResourceLimits, +) -> anyhow::Result { + let mut collector = Collector::new(Mode::DryRun); + let workspace = tempfile::tempdir()?; + let out_dir = workspace.path().to_path_buf(); + if path.is_dir() { + run_folder_inner( + path, + Some(&out_dir), + 2, + false, + true, + scan_all, + limits, + Some(&mut collector), + )?; + } else { + run_file_inner( + path, + Some(&out_dir), + 2, + false, + true, + limits, + Some(&mut collector), + )?; + } + Ok(collector.finish()) +} + +// --------------------------------------------------------------------------- +// Report construction +// --------------------------------------------------------------------------- + +/// Metadata header identity for `path`, when the file has one. +pub(crate) fn identity_of(path: &Path) -> Option { + let mut head = [0_u8; 8]; + use std::io::Read; + let mut file = std::fs::File::open(path).ok()?; + file.read_exact(&mut head).ok()?; + senbei_metadata::identify(&head) +} + +/// Unpack one file the way [`unpack_one_v`] does, keeping the route profile. +/// +/// Output bytes and error values are those of [`unpack_one_v`]; only the +/// profile is additional. Reporting runs use this so the report names the +/// route the pipeline actually selected, the routes it rejected first, and the +/// static-check verdict for the bytes finally written. +pub fn unpack_one_profiled( + input: &Path, + dest: &Path, + verbose: bool, +) -> ( + senbei_engine::ProtectionProfile, + anyhow::Result<(senbei_engine::Kind, senbei_engine::IntegrityReport)>, +) { + // Read the stub and its `._` sibling exactly as the file entry point does. + let (stub, companion) = match read_stub_and_companion(input) { + Ok(pair) => pair, + Err(error) => { + let mut profile = observed_profile(input); + profile.recovery = senbei_engine::RecoveryStatus::Blocked; + profile.push_error(format!("{error:#}")); + return (profile, Err(error)); + } + }; + // The byte entry point owns the splice, companion overlays, and the check + // over the image actually returned — the same steps as `unpack_one_v`. + let (profile, recovered) = + crate::windows::unpack_bytes_profiled_v(&stub, companion.as_deref(), verbose); + let image = match recovered { + Ok(image) => image, + // The profile already records which candidates ran and why they failed. + Err(error) => return (profile, Err(error.into())), + }; + if let Some(parent) = dest.parent() + && let Err(error) = std::fs::create_dir_all(parent) + { + return (profile, Err(error.into())); + } + if let Err(error) = write_atomic(dest, &image.bytes) { + return (profile, Err(error.into())); + } + if verbose { + println!("Write to {}", dest.display()); + } + (profile, Ok((image.kind, image.integrity))) +} + +/// The input's bytes and its `._` companion payload, when one exists. +/// +/// Mirrors the file entry point's companion discovery: a missing sibling is +/// simply absent, while an unreadable one is an error rather than a silent +/// mismatch. +/// The `._` sibling when one exists and is readable. +/// +/// `Ok(None)` means there is no sibling. `Err` means one exists but could not +/// be read — a real condition the caller must classify, not treat as absent. +fn read_optional_companion(input: &Path) -> anyhow::Result>> { + let Some(path) = sibling_path(input) else { + return Ok(None); + }; + match std::fs::read(&path) { + Ok(bytes) => Ok(Some(bytes)), + Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(None), + Err(error) => Err(anyhow::Error::from(error) + .context(format!("couldn't read companion {}", path.display()))), + } +} + +fn read_stub_and_companion(input: &Path) -> anyhow::Result<(Vec, Option>)> { + let stub = std::fs::read(input)?; + let Some(name) = input.file_name() else { + return Ok((stub, None)); + }; + let mut sibling = name.to_os_string(); + sibling.push("._"); + let companion = input.with_file_name(sibling); + match std::fs::read(&companion) { + Ok(bytes) => Ok((stub, Some(bytes))), + Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok((stub, None)), + Err(error) => Err(anyhow::Error::from(error) + .context(format!("couldn't read companion {}", companion.display()))), + } +} + +/// Input report for a Windows PE whose outcome a profiled run reported. +fn windows_input( + input: &Path, + dest: &Path, + kind: senbei_engine::Kind, + report: &senbei_engine::IntegrityReport, + profile: Option, + started: Instant, +) -> InputReport { + let mut entry = InputReport::new(input, Role::Content); + entry.status = if report.ok() { + InputStatus::Ok + } else { + InputStatus::Suspect + }; + let profile = profile.unwrap_or_else(|| recovered_profile(kind, report)); + entry.companion = crate::windows::is_pe_extension(input).then(|| { + companion_report( + input, + observed_companion_state(input, profile.observed.external_companion), + ) + }); + entry.profile = Some(profile); + entry.outputs = vec![OutputFile::from_path(dest)]; + entry + .stages + .push(StageReport::new(Stage::Detection, StageStatus::Ok)); + entry.stages.push( + StageReport::new(Stage::Recovery, StageStatus::Ok).timed(crate::report::now_ms(started)), + ); + entry.stages.push(StageReport::new( + Stage::StaticValidation, + if report.ok() { + StageStatus::Ok + } else { + StageStatus::Failed + }, + )); + entry.stages.push( + StageReport::new(Stage::OutputWrite, StageStatus::Ok).detail(dest.display().to_string()), + ); + entry.duration_ms = crate::report::now_ms(started); + entry +} + +/// Profile for a successful Windows unpack when only the outcome is known. +/// +/// Only used when a caller has no profiled result to hand. It states exactly +/// what was observed: the detected kind, the route that kind routes to, and the +/// final integrity verdict. +fn recovered_profile( + kind: senbei_engine::Kind, + report: &senbei_engine::IntegrityReport, +) -> senbei_engine::ProtectionProfile { + use senbei_engine::{ + AttemptOutcome, LayoutAttempt, ProtectionEvidence, ProtectionProfile, RecognitionStatus, + RecoveryStatus, + }; + let mut profile = + ProtectionProfile::new(senbei_engine::ObservedTarget::windows(None, Some(kind))); + profile.recognition = RecognitionStatus::Recognized; + profile.evidence = vec![ProtectionEvidence::HeaderMagic]; + profile.recovery = RecoveryStatus::Succeeded; + profile.record_static_validation(report); + let layout = match kind { + senbei_engine::Kind::NativeDll | senbei_engine::Kind::ManagedDll => { + senbei_engine::LayoutKind::Dll + } + _ => senbei_engine::LayoutKind::ExeStyle, + }; + profile.selected = Some(layout); + profile.candidates = vec![LayoutAttempt { + layout, + outcome: AttemptOutcome::Succeeded, + warnings: profile.warnings.clone(), + errors: profile.errors.clone(), + }]; + profile +} + +/// Input report for an input that failed before producing output. +/// +/// The profile is rebuilt from the input's own header so the report says which +/// route failed and what was recognized, rather than only the error text. This +/// reads the header again — it is report construction, not a second pipeline +/// run, and the observed bytes are the same ones the pipeline saw. +fn failed_input(input: &Path, error: &anyhow::Error, started: Instant) -> InputReport { + let mut entry = InputReport::new(input, Role::Content); + entry.status = InputStatus::Error; + let detail = format!("{error:#}"); + entry.error(detail.clone()); + entry.profile = Some(failure_profile(input, &detail)); + entry + .stages + .push(StageReport::new(Stage::Recovery, StageStatus::Failed).detail(detail)); + entry.duration_ms = crate::report::now_ms(started); + entry +} + +/// Input report for a Windows PE whose profiled run failed. +/// +/// The profile comes from the run itself, so it keeps every candidate that was +/// tried and the error that stopped each — no header re-read, no inference. +fn failed_input_with_profile( + input: &Path, + error: &anyhow::Error, + profile: senbei_engine::ProtectionProfile, + started: Instant, +) -> InputReport { + let mut entry = InputReport::new(input, Role::Content); + entry.status = InputStatus::Error; + let detail = format!("{error:#}"); + entry.error(detail.clone()); + entry.companion = crate::windows::is_pe_extension(input).then(|| { + companion_report( + input, + observed_companion_state(input, profile.observed.external_companion), + ) + }); + entry.profile = Some(profile); + entry + .stages + .push(StageReport::new(Stage::Recovery, StageStatus::Failed).detail(detail)); + entry.duration_ms = crate::report::now_ms(started); + entry +} + +/// Input report for an input inspection could not read. +/// +/// Inspection is detection only, so a read error must not be dressed up as a +/// failed recovery: no candidate is marked attempted, `recovery` stays +/// `not_attempted`, `static_validation` stays `not_run`, and no route is +/// selected. Whatever header evidence was obtainable is still reported. +fn inspect_failed_input(input: &Path, error: &anyhow::Error, started: Instant) -> InputReport { + let mut entry = InputReport::new(input, Role::Content); + entry.status = InputStatus::Error; + let detail = format!("{error:#}"); + entry.error(detail.clone()); + let mut profile = observed_profile(input); + profile.push_error(detail.clone()); + entry.profile = Some(profile); + entry + .stages + .push(StageReport::new(Stage::Detection, StageStatus::Failed).detail(detail)); + entry.duration_ms = crate::report::now_ms(started); + entry +} + +/// Best-effort observation of an input whose inspection failed. +/// +/// Reads only what detection reads. Recognition and the routes that *would* be +/// tried are reported as planned; nothing is marked attempted. +fn observed_profile(input: &Path) -> senbei_engine::ProtectionProfile { + use senbei_engine::{LayoutAttempt, ProtectionProfile, RecoveryStatus, ValidationStatus}; + let mut profile = match read_prefix(input) { + Ok(prefix) if senbei_metadata::is_metadata(&prefix) => { + crate::report::metadata_unchanged_profile(senbei_metadata::identify(&prefix)) + } + Ok(_) if crate::windows::is_pe_extension(input) => match std::fs::read(input) { + Ok(stub) => { + let (bytes, spliced) = match read_optional_companion(input) { + Ok(Some(payload)) => match crate::windows::splice_companion(&stub, &payload) { + Some(spliced) => (spliced, true), + None => (stub, false), + }, + _ => (stub, false), + }; + let mut profile = senbei_engine::inspect_profile(&bytes); + if spliced { + profile.record_companion_spliced(); + } + profile + } + Err(_) => ProtectionProfile::new(senbei_engine::ObservedTarget::windows(None, None)), + }, + Ok(prefix) if crate::android::is_elf64_aarch64(&prefix) => { + ProtectionProfile::new(senbei_engine::ObservedTarget::android(None)) + } + Ok(prefix) if crate::android::is_app_package(input, &prefix) => { + ProtectionProfile::new(senbei_engine::ObservedTarget::android(None)) + } + _ => ProtectionProfile::new(senbei_engine::ObservedTarget::windows(None, None)), + }; + // Nothing was attempted: every planned route stays planned. + for candidate in &mut profile.candidates { + *candidate = LayoutAttempt::not_attempted(candidate.layout); + } + profile.selected = None; + profile.recovery = RecoveryStatus::NotAttempted; + profile.static_validation = ValidationStatus::NotRun; + profile +} + +/// Profile of an input whose recovery failed. +fn failure_profile(input: &Path, detail: &str) -> senbei_engine::ProtectionProfile { + use senbei_engine::{AttemptOutcome, LayoutKind, ProtectionProfile, RecoveryStatus}; + let Ok(prefix) = read_prefix(input) else { + let mut profile = + ProtectionProfile::new(senbei_engine::ObservedTarget::windows(None, None)); + profile.recovery = RecoveryStatus::Failed; + profile.push_error(detail.to_owned()); + return profile; + }; + if senbei_metadata::is_metadata(&prefix) { + return crate::report::metadata_failed_profile( + senbei_metadata::identify(&prefix), + LayoutKind::MetadataStructural, + detail, + ); + } + if crate::windows::is_pe_extension(input) { + let mut profile = match crate::windows::read_unpacker_input(input) { + Ok(unpacker_input) => { + let spliced = unpacker_input.stub.is_some(); + let mut profile = senbei_engine::inspect_profile(&unpacker_input.bytes); + if spliced { + profile.record_companion_spliced(); + } + profile + } + // The input could not be read at all as a PE. + Err(_) => ProtectionProfile::new(senbei_engine::ObservedTarget::windows(None, None)), + }; + // The route that was tried is the one the pipeline would have used; a + // spliced companion forces the EXE-style shell. + let (layout, errors) = match profile + .candidates + .iter() + .find(|candidate| candidate.outcome == AttemptOutcome::NotAttempted) + .map(|candidate| candidate.layout) + { + Some(layout) => (layout, vec![detail.to_owned()]), + None => (LayoutKind::ExeStyle, vec![detail.to_owned()]), + }; + if let Some(attempt) = profile.attempt_mut(layout) { + attempt.outcome = AttemptOutcome::Failed; + attempt.errors = errors; + } else { + profile.candidates.push(senbei_engine::LayoutAttempt { + layout, + outcome: AttemptOutcome::Failed, + warnings: Vec::new(), + errors, + }); + } + profile.recovery = RecoveryStatus::Failed; + profile.push_error(detail.to_owned()); + return profile; + } + if crate::android::is_elf64_aarch64(&prefix) { + return crate::report::android_failed_profile(detail); + } + let mut profile = ProtectionProfile::new(senbei_engine::ObservedTarget::windows(None, None)); + profile.recovery = RecoveryStatus::Failed; + profile.push_error(detail.to_owned()); + profile +} + +/// Input report for a restored (or skipped) loose Android library. +fn android_library_input( + input: &Path, + status: InputStatus, + dest: &Path, + started: Instant, +) -> InputReport { + let mut entry = InputReport::new(input, Role::Content); + entry.status = status; + match status { + InputStatus::Ok => { + entry.profile = Some(crate::report::android_recovered_profile()); + entry.outputs = vec![OutputFile::from_path(dest)]; + entry.stages.push( + StageReport::new(Stage::Recovery, StageStatus::Ok) + .timed(crate::report::now_ms(started)), + ); + } + InputStatus::Skipped => { + entry + .stages + .push(StageReport::new(Stage::Recovery, StageStatus::Skipped)); + } + _ => { + let detail = entry.errors.first().cloned().unwrap_or_default(); + entry.profile = Some(crate::report::android_failed_profile(&detail)); + entry + .stages + .push(StageReport::new(Stage::Recovery, StageStatus::Failed)); + } + } + entry.duration_ms = crate::report::now_ms(started); + entry +} + +/// Record a restore's validation verdict and advisory findings on a report. +/// +/// `static_validation` becomes `clean` or `warnings`; diagnostics are warnings, +/// never errors, because the engine's own restore accepted these bytes. +fn apply_android_validation( + report: &mut InputReport, + validation: Option<&crate::android::ValidationDiagnostics>, +) { + // No engine report is not a verdict: leave static_validation untouched. + let Some(validation) = validation else { + return; + }; + let Some(profile) = report.profile.as_mut() else { + return; + }; + if profile.recovery != senbei_engine::RecoveryStatus::Succeeded { + return; + } + profile.static_validation = if validation.is_clean() { + senbei_engine::ValidationStatus::Clean + } else { + senbei_engine::ValidationStatus::Warnings + }; + profile.warnings.extend(validation.messages.iter().cloned()); + report.warnings.extend(validation.messages.iter().cloned()); + // The stage itself succeeded — the restore validated the output. Findings + // are carried as detail and warnings, not as a failed stage. + let mut stage = StageReport::new(Stage::StaticValidation, StageStatus::Ok); + if !validation.is_clean() { + stage = stage.detail(validation.messages.join("; ")); + } + report.stages.push(stage); +} + +/// Input report for one loose il2cpp metadata blob. +fn metadata_input( + input: &Path, + report: &crate::android::LooseMetadataOutcome, + dest: Option<&Path>, + started: Instant, +) -> InputReport { + let identity = identity_of(input); + let mut entry = InputReport::new(input, Role::Content); + entry.metadata = identity; + entry.metadata_version = Some(report.version); + entry.provenance = report.provenance.clone(); + if dest.is_some() { + entry.status = InputStatus::Ok; + entry.profile = Some(crate::report::metadata_recovered_profile( + identity, + report.layout, + )); + entry.outputs = dest + .map(|dest| vec![OutputFile::from_path(dest)]) + .unwrap_or_default(); + entry.stages.push( + StageReport::new(Stage::Recovery, StageStatus::Ok) + .timed(crate::report::now_ms(started)), + ); + } else { + // Identified, valid, and already canonical: nothing to restore. + entry.status = InputStatus::Skipped; + entry.profile = Some(crate::report::metadata_unchanged_profile(identity)); + entry + .stages + .push(StageReport::new(Stage::Recovery, StageStatus::Skipped)); + } + entry.duration_ms = crate::report::now_ms(started); + entry +} + +/// Input report for a single-file metadata run. +fn single_metadata_input( + input: &Path, + report: &senbei_metadata::Report, + layout: senbei_engine::LayoutKind, + dest: Option<&Path>, + started: Instant, +) -> InputReport { + let identity = identity_of(input); + let mut entry = InputReport::new(input, Role::Content); + entry.metadata = identity; + entry.metadata_version = Some(report.version); + entry.status = if dest.is_some() { + InputStatus::Ok + } else { + InputStatus::Skipped + }; + entry.profile = Some(if dest.is_some() { + crate::report::metadata_recovered_profile(identity, layout) + } else { + crate::report::metadata_unchanged_profile(identity) + }); + entry.outputs = dest + .map(|dest| vec![OutputFile::from_path(dest)]) + .unwrap_or_default(); + entry.stages.push( + StageReport::new( + Stage::Recovery, + if dest.is_some() { + StageStatus::Ok + } else { + StageStatus::Skipped + }, + ) + .timed(crate::report::now_ms(started)), + ); + entry.duration_ms = crate::report::now_ms(started); + entry +} + +/// Input report for one app package, from the entries it produced. +fn package_input( + package: &Path, + outcomes: Vec<&crate::android::EntryOutcome>, + started: Instant, +) -> InputReport { + let mut entry = InputReport::new(package, Role::Container); + entry.container = Some(ContainerReport { + kind: package + .extension() + .and_then(|value| value.to_str()) + .map(|value| value.to_ascii_lowercase()) + .unwrap_or_default(), + // Inventory is only recorded by an explicit inspect run; a restore + // reports what it actually produced. + manifests: Vec::new(), + entry_count: outcomes.len(), + candidate_entries: outcomes + .iter() + .map(|outcome| outcome.label.clone()) + .collect(), + nested_packages: Vec::new(), + }); + entry.entries = outcomes + .iter() + .map(|outcome| entry_report(outcome)) + .collect(); + // A container has no single profile; its validation verdict carries every + // advisory finding a restored entry reported. + let diagnostics: Vec = outcomes + .iter() + .filter(|outcome| matches!(outcome.status, crate::android::EntryStatus::Restored)) + .filter_map(|outcome| outcome.validation.as_ref()) + .flat_map(|validation| validation.messages.iter().cloned()) + .collect(); + if !diagnostics.is_empty() { + entry.warnings.extend(diagnostics.clone()); + entry.stages.push( + StageReport::new(Stage::StaticValidation, StageStatus::Ok) + .detail(diagnostics.join("; ")), + ); + } + entry.status = if entry + .entries + .iter() + .any(|entry| entry.status == EntryStatus::Error) + { + InputStatus::Error + } else if entry + .entries + .iter() + .any(|entry| entry.status == EntryStatus::Restored) + { + InputStatus::Ok + } else { + InputStatus::Skipped + }; + entry.duration_ms = crate::report::now_ms(started); + entry +} + +fn entry_report(outcome: &crate::android::EntryOutcome) -> EntryReport { + use crate::android::EntryKind as SourceKind; + let (status, kind) = match &outcome.status { + crate::android::EntryStatus::Restored => { + (EntryStatus::Restored, Some(source_kind(outcome.kind))) + } + crate::android::EntryStatus::Duplicate => { + (EntryStatus::Duplicate, Some(source_kind(outcome.kind))) + } + crate::android::EntryStatus::NotTarget => (EntryStatus::NotTarget, None), + crate::android::EntryStatus::Unchanged => { + (EntryStatus::Unchanged, Some(source_kind(outcome.kind))) + } + crate::android::EntryStatus::Failed(_) => { + (EntryStatus::Error, Some(source_kind(outcome.kind))) + } + }; + let mut report = EntryReport::new(outcome.label.clone(), status); + report.kind = kind; + report.provenance = outcome.provenance.clone(); + report.layout = outcome.layout; + report.metadata_version = outcome.metadata_version; + if let SourceKind::Metadata { remapped } = outcome.kind { + report.remapped = Some(remapped); + } + if status == EntryStatus::Restored { + report.output = Some(OutputFile::from_path(&outcome.dest)); + } + if let crate::android::EntryStatus::Failed(error) = &outcome.status { + report.errors.push(format!("{error:#}")); + } + // The engine's advisory findings for this entry's own output. Only a + // restored entry has an output they could describe. + if status == EntryStatus::Restored + && let Some(validation) = &outcome.validation + { + report.warnings.extend(validation.messages.iter().cloned()); + } + report +} + +fn source_kind(kind: crate::android::EntryKind) -> EntryKind { + match kind { + crate::android::EntryKind::So => EntryKind::SharedLibrary, + crate::android::EntryKind::Metadata { .. } + | crate::android::EntryKind::EmbeddedMetadata => EntryKind::Metadata, + } +} + #[cfg(test)] mod tests { use super::*; @@ -977,4 +2161,82 @@ mod tests { let rel = rel_in_tree(root, under); assert_eq!(rel.as_ref(), Path::new(r"bin\app.exe")); } + + /// A restore's validation diagnostics reach the JSON report: the profile's + /// `static_validation` becomes `warnings`, the findings appear as warnings, + /// and a `static_validation` stage records them — while the input stays a + /// success and its output is still listed. + #[test] + fn validation_diagnostics_reach_the_json_report() { + use crate::android::ValidationDiagnostics; + + let started = Instant::now(); + let mut input = android_library_input( + Path::new("lib/arm64-v8a/libil2cpp.so"), + InputStatus::Ok, + Path::new("out/libil2cpp.unpack.so"), + started, + ); + apply_android_validation( + &mut input, + Some(&ValidationDiagnostics { + messages: vec!["a table a linker could not walk".to_owned()], + }), + ); + + let mut collector = Collector::new(Mode::Unpack); + collector.push(input); + let value: serde_json::Value = + serde_json::from_str(&collector.finish().to_json()).expect("valid report"); + + let reported = &value["inputs"][0]; + assert_eq!(reported["status"], "ok"); + assert_eq!(reported["profile"]["recovery"], "succeeded"); + assert_eq!(reported["profile"]["static_validation"], "warnings"); + assert_eq!( + reported["profile"]["warnings"][0], + "a table a linker could not walk" + ); + assert_eq!(reported["warnings"][0], "a table a linker could not walk"); + assert_eq!(reported["outputs"][0]["path"], "out/libil2cpp.unpack.so"); + // The advisory finding is a warning, never an error. + assert!(reported["errors"].as_array().unwrap().is_empty()); + assert!(reported["profile"]["errors"].as_array().unwrap().is_empty()); + let stages: Vec<&str> = reported["stages"] + .as_array() + .unwrap() + .iter() + .map(|stage| stage["stage"].as_str().unwrap()) + .collect(); + assert!(stages.contains(&"static_validation"), "{stages:?}"); + } + + /// No engine report means no verdict: a restore that reported none must not + /// claim a clean static validation. + #[test] + fn missing_validation_report_is_not_a_clean_verdict() { + let started = Instant::now(); + let mut input = android_library_input( + Path::new("lib/arm64-v8a/libil2cpp.so"), + InputStatus::Ok, + Path::new("out/libil2cpp.unpack.so"), + started, + ); + apply_android_validation(&mut input, None); + + let mut collector = Collector::new(Mode::Unpack); + collector.push(input); + let value: serde_json::Value = + serde_json::from_str(&collector.finish().to_json()).expect("valid report"); + assert_eq!( + value["inputs"][0]["profile"]["static_validation"], + "not_run" + ); + assert!( + value["inputs"][0]["warnings"] + .as_array() + .unwrap() + .is_empty() + ); + } } diff --git a/senbei-io/src/lib.rs b/senbei-io/src/lib.rs index 7ad202b..3f04592 100644 --- a/senbei-io/src/lib.rs +++ b/senbei-io/src/lib.rs @@ -8,6 +8,7 @@ mod atomic; pub mod job; pub mod logfile; pub mod pause; +pub mod report; pub mod scan; pub mod ui; pub mod windows; diff --git a/senbei-io/src/report.rs b/senbei-io/src/report.rs new file mode 100644 index 0000000..40b11b4 --- /dev/null +++ b/senbei-io/src/report.rs @@ -0,0 +1,823 @@ +//! Versioned, machine-readable run report. +//! +//! One [`Report`] describes one CLI invocation: which inputs were examined, +//! what each of them turned out to be, which routes were tried and selected, +//! what was written, and which defects were found. It is the only structure the +//! `--json` output serializes, so its shape is the contract reported by +//! [`REPORT_FORMAT_VERSION`]. +//! +//! Two rules shape the fields: +//! +//! * Every value is something that was actually observed. Timings are recorded +//! 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. +//! +//! A container (`.apk`/`.apks`/`.xapk`) is reported as one input with +//! [`Role::Container`]: its manifest inventory is listed separately from the +//! entries that were actually probed and restored, so a manifest list is never +//! mistaken for inspected protected content. + +use std::path::Path; +use std::time::Instant; + +use serde::Serialize; +use sha2::{Digest as _, Sha256}; + +use senbei_engine::{ + AttemptOutcome, LayoutKind, ProtectionEvidence, ProtectionProfile, RecognitionStatus, + RecoveryStatus, ValidationStatus, +}; + +/// Version of the serialized [`Report`] schema. +pub const REPORT_FORMAT_VERSION: u32 = 1; + +/// What the invocation was asked to do. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] +#[serde(rename_all = "snake_case")] +pub enum Mode { + /// Detection only: no recovery, no output, no log. + Inspect, + /// Restore and write outputs. + Unpack, + /// Run the real recovery, keep nothing (no ordinary output, no log). + DryRun, +} + +/// Whether the input is a protected file or a container of them. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] +#[serde(rename_all = "snake_case")] +pub enum Role { + /// A single protected file, metadata blob, or unrecognized file. + Content, + /// An app package whose entries are handled one by one. + Container, +} + +/// Outcome of one input, from the caller's point of view. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] +#[serde(rename_all = "snake_case")] +pub enum InputStatus { + /// Produced output. + 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. + Recognized, + /// Not a target, already handled, or a layout this build does not know. + Skipped, + /// A target that failed. + Error, +} + +/// Outcome of one container entry. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] +#[serde(rename_all = "snake_case")] +pub enum EntryStatus { + /// Restored or de-obfuscated and written. + Restored, + /// Byte-identical content was already restored from another source. + Duplicate, + /// Probed and not a protected target. + NotTarget, + /// A metadata blob whose protected fields were already canonical. + Unchanged, + /// Listed in a container inventory. Not probed, so not a target claim. + Inventoried, + /// Recognized as a target but the restore failed. + Error, +} + +/// What a container entry is. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] +#[serde(rename_all = "snake_case")] +pub enum EntryKind { + SharedLibrary, + Metadata, +} + +/// One measured or declared stage of an input. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] +#[serde(rename_all = "snake_case")] +pub enum Stage { + Detection, + ManifestInventory, + EntryProbe, + Recovery, + StaticValidation, + OutputWrite, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] +#[serde(rename_all = "snake_case")] +pub enum StageStatus { + Ok, + Skipped, + Failed, + Blocked, +} + +/// State of the `._` companion relationship. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] +#[serde(rename_all = "snake_case")] +pub enum CompanionState { + /// No sibling `._` file. + Absent, + /// A `._` payload was found and is the input's payload. + Spliced, + /// A sibling `._` exists but does not pair with this stub. + Unmatched, + /// A sibling `._` exists but could not be read. + Unreadable, +} + +/// Size and SHA-256 of bytes that were actually produced. +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct Digest { + pub size: u64, + pub sha256: String, +} + +impl Digest { + /// Digest of `bytes`. + pub fn of(bytes: &[u8]) -> Self { + let mut hasher = Sha256::new(); + hasher.update(bytes); + Self { + size: bytes.len() as u64, + sha256: senbei_crypto::hex_digest(&hasher.finalize()), + } + } +} + +/// One output file that was left on disk. +/// +/// `sha256` is present only when the producing step had the bytes in hand. An +/// engine that streams straight to its output file reports size alone rather +/// than re-reading the file just to hash it. +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct OutputFile { + pub path: String, + pub size: u64, + pub sha256: Option, +} + +impl OutputFile { + /// Output whose bytes are known. + pub fn from_bytes(path: &Path, bytes: &[u8]) -> Self { + Self { + path: path.display().to_string(), + size: bytes.len() as u64, + sha256: Some(Digest::of(bytes).sha256), + } + } + + /// Output that an engine streamed to disk. + /// + /// Size is observed from the file; no hash is reported because hashing + /// would mean reading a potentially huge output back solely for the + /// report. `sha256` is `Some` only where the producing step already held + /// the bytes. + pub fn from_path(path: &Path) -> Self { + Self { + path: path.display().to_string(), + size: std::fs::metadata(path).map(|meta| meta.len()).unwrap_or(0), + sha256: None, + } + } +} + +/// Non-target tallies from a folder scan, kept apart from input results. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize)] +pub struct ScanReport { + /// Named candidates that were probed and matched no detector. + pub non_target_skipped: usize, + /// Directory entries the walk could not read. + pub walk_errors: usize, + /// Selected files whose content probe failed. + pub probe_errors: usize, +} + +/// The companion relationship recorded for one Windows input. +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct CompanionReport { + pub state: CompanionState, + pub path: Option, + pub detail: Option, +} + +/// One manifest parsed from a container. +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct ManifestReport { + /// Where the manifest was read from: the package, or `package::entry`. + pub source: String, + pub package: Option, + pub version: Option, + /// True only when the manifest named both a package and a version. + pub named: bool, +} + +/// Container inventory: membership facts, not inspected content. +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct ContainerReport { + /// `apk`, `apks`, or `xapk`. + pub kind: String, + pub manifests: Vec, + /// Central-directory entry count of the top-level package. + pub entry_count: usize, + /// Entry names that would be probed during a restore. + pub candidate_entries: Vec, + /// Nested packages discovered at the top level of a bundle. + pub nested_packages: Vec, +} + +/// One stage of an input, with its measured duration when it was timed. +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct StageReport { + pub stage: Stage, + pub status: StageStatus, + pub detail: Option, + pub duration_ms: Option, +} + +impl StageReport { + pub fn new(stage: Stage, status: StageStatus) -> Self { + Self { + stage, + status, + detail: None, + duration_ms: None, + } + } + + pub fn detail(mut self, detail: impl Into) -> Self { + self.detail = Some(detail.into()); + self + } + + pub fn timed(mut self, elapsed_ms: u64) -> Self { + self.duration_ms = Some(elapsed_ms); + self + } +} + +/// One entry of a container, or one artifact produced for it. +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct EntryReport { + /// Source label, e.g. `base.apk::lib/arm64-v8a/libil2cpp.so`. + pub name: String, + pub status: EntryStatus, + pub kind: Option, + /// Route selected for this entry, when one was. + pub layout: Option, + pub metadata_version: Option, + pub remapped: Option, + /// Libraries whose decoded module was paired with this metadata entry. + pub provenance: Vec, + /// Where the restored bytes were written (absent in dry-run/inspect). + pub output: Option, + pub warnings: Vec, + pub errors: Vec, +} + +impl EntryReport { + pub fn new(name: impl Into, status: EntryStatus) -> Self { + Self { + name: name.into(), + status, + kind: None, + layout: None, + metadata_version: None, + remapped: None, + provenance: Vec::new(), + output: None, + warnings: Vec::new(), + errors: Vec::new(), + } + } +} + +/// Everything observed for one input. +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct InputReport { + pub path: String, + pub role: Role, + pub status: InputStatus, + /// Engine profile: recognition evidence, candidate routes, and — only when + /// recovery actually ran — the selected route and static-validation verdict. + pub profile: Option, + pub companion: Option, + pub container: Option, + pub entries: Vec, + /// Output files left on disk. Empty for inspect and dry-run. + pub outputs: Vec, + /// Digest of the recovered image, when recovery produced one. + pub recovered: Option, + /// Metadata header identity, when the input was an il2cpp metadata blob. + pub metadata: Option, + /// Raw il2cpp metadata version, duplicated for flat consumers. + pub metadata_version: Option, + /// Libraries whose decoded module was paired with this metadata input. + pub provenance: Vec, + pub stages: Vec, + pub warnings: Vec, + pub errors: Vec, + pub duration_ms: u64, +} + +impl InputReport { + pub fn new(path: &Path, role: Role) -> Self { + Self { + path: path.display().to_string(), + role, + status: InputStatus::Skipped, + profile: None, + companion: None, + container: None, + entries: Vec::new(), + outputs: Vec::new(), + recovered: None, + metadata: None, + metadata_version: None, + provenance: Vec::new(), + stages: Vec::new(), + warnings: Vec::new(), + errors: Vec::new(), + duration_ms: 0, + } + } + + pub fn warning(&mut self, message: impl Into) { + self.warnings.push(message.into()); + } + + pub fn error(&mut self, message: impl Into) { + self.errors.push(message.into()); + } +} + +/// Counts over the whole invocation. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)] +pub struct SummaryReport { + /// Inputs examined. + 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. + pub recognized: usize, + /// Inputs that were not targets or were left untouched. + pub skipped: usize, + /// Inputs whose output fails the static integrity check. + pub suspect: usize, + /// Inputs that failed. + pub errors: usize, + /// il2cpp metadata blobs de-obfuscated, including embedded ones. + pub metadata: usize, + /// App packages opened. + pub packages: usize, +} + +/// Identity of the tool that produced the report. +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct Tool { + pub name: String, + pub version: String, +} + +/// One invocation's report. +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct Report { + pub format_version: u32, + pub tool: Tool, + pub mode: Mode, + /// Folder scan tallies. `None` for a single-file run. + pub scan: Option, + pub inputs: Vec, + pub summary: SummaryReport, + /// Run-level failures that are not attributable to one input. + pub errors: Vec, + pub duration_ms: u64, +} + +impl Report { + /// Serialize as one JSON document. + pub fn to_json(&self) -> String { + // The report contains only owned, serializable values. + serde_json::to_string(self).unwrap_or_else(|error| { + format!( + "{{\"format_version\":{REPORT_FORMAT_VERSION},\"error\":\"report serialization failed: {error}\"}}" + ) + }) + } + + /// One-line summary in the same shape as [`crate::job::Summary::line`]. + pub fn summary_line(&self) -> String { + let s = &self.summary; + let mut line = format!( + "{} unpacked · {} skipped · {} errors · {} suspect · {} metadata", + s.recovered, s.skipped, s.errors, s.suspect, s.metadata + ); + if s.packages > 0 { + line.push_str(&format!(" · {} packages", s.packages)); + } + line + } + + /// Human-readable rendering, one block per input, for non-`--json` runs. + pub fn render_text(&self) -> String { + let mut text = String::new(); + for input in &self.inputs { + text.push_str(&render_input(input)); + } + if !self.errors.is_empty() { + for error in &self.errors { + text.push_str(&format!("error: {error}\n")); + } + } + text + } +} + +fn render_input(input: &InputReport) -> String { + let mut text = format!("{}\n", input.path); + text.push_str(&format!(" role: {:?}\n", input.role)); + if let Some(profile) = &input.profile { + text.push_str(&format!(" recognition: {:?}\n", profile.recognition)); + if !profile.evidence.is_empty() { + text.push_str(&format!(" evidence: {:?}\n", profile.evidence)); + } + for candidate in &profile.candidates { + let mut line = format!( + " route {}: {:?}", + layout_name(candidate.layout), + candidate.outcome + ); + if !candidate.errors.is_empty() { + line.push_str(&format!(" ({})", candidate.errors.join("; "))); + } + text.push_str(&line); + text.push('\n'); + } + if let Some(selected) = profile.selected { + text.push_str(&format!(" selected: {:?}\n", layout_name(selected))); + } + text.push_str(&format!(" recovery: {:?}\n", profile.recovery)); + text.push_str(&format!( + " static validation: {:?}\n", + profile.static_validation + )); + } + if let Some(metadata) = &input.metadata { + text.push_str(&format!( + " metadata: version {} ({:?}, capabilities {:?})\n", + metadata.raw_version, metadata.layout, metadata.capabilities + )); + } + if let Some(container) = &input.container { + text.push_str(&format!( + " container: {} · {} entries · {} manifests\n", + container.kind, + container.entry_count, + container.manifests.len() + )); + for manifest in &container.manifests { + text.push_str(&format!( + " manifest {} → {} {}\n", + manifest.source, + manifest.package.as_deref().unwrap_or(""), + manifest.version.as_deref().unwrap_or("") + )); + } + for entry in &container.candidate_entries { + text.push_str(&format!(" candidate {entry}\n")); + } + } + for entry in &input.entries { + text.push_str(&format!( + " entry {}: {:?}{}\n", + entry.name, + entry.status, + entry + .output + .as_ref() + .map(|output| format!(" -> {}", output.path)) + .unwrap_or_default() + )); + } + if let Some(recovered) = &input.recovered { + text.push_str(&format!( + " recovered: {} bytes · {}\n", + recovered.size, recovered.sha256 + )); + } + text.push_str(&format!(" status: {:?}\n", input.status)); + text +} + +fn layout_name(layout: LayoutKind) -> &'static str { + match layout { + LayoutKind::Dll => "dll", + LayoutKind::ExeStyle => "exe_style", + LayoutKind::AndroidStaged => "android_staged", + LayoutKind::MetadataStructural => "metadata_structural", + LayoutKind::MetadataSeeded => "metadata_seeded", + LayoutKind::MetadataMethodIndices => "metadata_method_indices", + } +} + +/// Accumulates inputs during one invocation. +pub struct Collector { + mode: Mode, + started: Instant, + scan: Option, + inputs: Vec, + summary: SummaryReport, + errors: Vec, +} + +impl Collector { + pub fn new(mode: Mode) -> Self { + Self { + mode, + started: Instant::now(), + scan: None, + inputs: Vec::new(), + summary: SummaryReport::default(), + errors: Vec::new(), + } + } + + pub fn mode(&self) -> Mode { + self.mode + } + + /// Record the folder scan tallies for a folder run. + pub fn set_scan(&mut self, scan: ScanReport) { + 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 !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 + // over when the producing step actually computed one. + if input.recovered.is_none() + && let Some(first) = input.outputs.first() + && let Some(sha256) = &first.sha256 + { + input.recovered = Some(Digest { + size: first.size, + sha256: sha256.clone(), + }); + } + 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()); + } + } + if !input + .stages + .iter() + .any(|stage| stage.stage == Stage::OutputWrite) + { + input.stages.push( + StageReport::new(Stage::OutputWrite, StageStatus::Skipped) + .detail("dry run: the produced output was discarded"), + ); + } + input.outputs.clear(); + } + for entry in &mut input.entries { + entry.output = None; + } + } + self.summary.inputs += 1; + match input.status { + InputStatus::Ok => self.summary.recovered += 1, + InputStatus::Suspect => { + self.summary.recovered += 1; + self.summary.suspect += 1; + } + InputStatus::Recognized => self.summary.recognized += 1, + InputStatus::Skipped => self.summary.skipped += 1, + InputStatus::Error => self.summary.errors += 1, + } + self.inputs.push(input); + } + + pub fn summary_mut(&mut self) -> &mut SummaryReport { + &mut self.summary + } + + /// Record a run-level failure that is not attributable to one input. + pub fn push_error(&mut self, message: impl Into) { + self.errors.push(message.into()); + } + + pub fn finish(self) -> Report { + Report { + format_version: REPORT_FORMAT_VERSION, + tool: Tool { + name: "senbei".to_owned(), + version: env!("CARGO_PKG_VERSION").to_owned(), + }, + mode: self.mode, + scan: self.scan, + inputs: self.inputs, + summary: self.summary, + errors: self.errors, + duration_ms: self.started.elapsed().as_millis() as u64, + } + } +} + +pub(crate) fn now_ms(since: Instant) -> u64 { + since.elapsed().as_millis() as u64 +} + +// --------------------------------------------------------------------------- +// Profile helpers shared by the platform adapters +// --------------------------------------------------------------------------- + +/// Profile for a protected Android library whose restore actually succeeded. +/// +/// The staged route is recorded as attempted and selected because the restore +/// wrote an image; no probe is repeated here. +pub(crate) fn android_recovered_profile() -> ProtectionProfile { + let mut profile = ProtectionProfile::new(senbei_engine::ObservedTarget::android(Some( + senbei_engine::TargetFormat::Elf64Aarch64, + ))); + profile.recognition = RecognitionStatus::Recognized; + profile.evidence = vec![ + ProtectionEvidence::PrivateSection, + ProtectionEvidence::AesSchedule, + ]; + profile.candidates = vec![senbei_engine::LayoutAttempt { + layout: LayoutKind::AndroidStaged, + outcome: AttemptOutcome::Succeeded, + warnings: Vec::new(), + errors: Vec::new(), + }]; + profile.selected = Some(LayoutKind::AndroidStaged); + profile.recovery = RecoveryStatus::Succeeded; + profile +} + +/// Profile for a library the scan selected but whose restore failed. +/// +/// Recognition is inherited from the scan probe that selected the file; the +/// route is recorded as failed with the error that stopped it. +pub(crate) fn android_failed_profile(error: &str) -> ProtectionProfile { + let mut profile = ProtectionProfile::new(senbei_engine::ObservedTarget::android(None)); + profile.recognition = RecognitionStatus::Recognized; + profile.candidates = vec![senbei_engine::LayoutAttempt { + layout: LayoutKind::AndroidStaged, + outcome: AttemptOutcome::Failed, + warnings: Vec::new(), + errors: vec![error.to_owned()], + }]; + profile.recovery = RecoveryStatus::Failed; + profile.push_error(error.to_owned()); + profile +} + +/// Profile for a metadata blob whose transform changed protected fields. +/// +/// A metadata magic match alone is not protection evidence, so this is only +/// used after the transform returned `remapped > 0` and validated. +pub(crate) fn metadata_recovered_profile( + identity: Option, + route: LayoutKind, +) -> ProtectionProfile { + let mut profile = ProtectionProfile::new(senbei_engine::ObservedTarget::metadata( + identity.map(|identity| identity.raw_version), + )); + profile.recognition = RecognitionStatus::Recognized; + profile.evidence = vec![ProtectionEvidence::ValidatedMetadataTransform]; + profile.candidates = vec![senbei_engine::LayoutAttempt { + layout: route, + outcome: AttemptOutcome::Succeeded, + warnings: Vec::new(), + errors: Vec::new(), + }]; + profile.selected = Some(route); + profile.recovery = RecoveryStatus::Succeeded; + // Not a PE image: the PE static check does not apply to metadata output. + profile.static_validation = ValidationStatus::NotRun; + profile +} + +/// Profile for a metadata blob that was identified but needed no change. +/// +/// Nothing was transformed, so no protection evidence is claimed. +pub(crate) fn metadata_unchanged_profile( + identity: Option, +) -> ProtectionProfile { + let mut profile = ProtectionProfile::new(senbei_engine::ObservedTarget::metadata( + identity.map(|identity| identity.raw_version), + )); + profile.recognition = RecognitionStatus::NotRecognized; + profile.static_validation = ValidationStatus::NotRun; + profile +} + +/// Profile for a metadata blob whose transform failed. +pub(crate) fn metadata_failed_profile( + identity: Option, + route: LayoutKind, + error: &str, +) -> ProtectionProfile { + let mut profile = ProtectionProfile::new(senbei_engine::ObservedTarget::metadata( + identity.map(|identity| identity.raw_version), + )); + profile.recognition = RecognitionStatus::Recognized; + profile.candidates = vec![senbei_engine::LayoutAttempt { + layout: route, + outcome: AttemptOutcome::Failed, + warnings: Vec::new(), + errors: vec![error.to_owned()], + }]; + profile.recovery = RecoveryStatus::Failed; + profile.push_error(error.to_owned()); + profile.static_validation = ValidationStatus::NotRun; + profile +} + +#[cfg(test)] +mod tests { + use super::*; + + fn sample_input(status: InputStatus) -> InputReport { + let mut input = InputReport::new(Path::new("a.exe"), Role::Content); + input.status = status; + input.recovered = Some(Digest::of(b"bytes")); + input + } + + #[test] + fn report_round_trips_through_json_with_a_version_field() { + let mut collector = Collector::new(Mode::DryRun); + collector.push(sample_input(InputStatus::Ok)); + collector.push(sample_input(InputStatus::Suspect)); + let report = collector.finish(); + assert_eq!(report.format_version, REPORT_FORMAT_VERSION); + let json = report.to_json(); + let value: serde_json::Value = serde_json::from_str(&json).expect("valid json"); + assert_eq!(value["format_version"], REPORT_FORMAT_VERSION); + assert_eq!(value["mode"], "dry_run"); + assert_eq!(value["summary"]["inputs"], 2); + assert_eq!(value["summary"]["suspect"], 1); + assert_eq!(value["summary"]["errors"], 0); + assert_eq!(value["tool"]["name"], "senbei"); + assert!(value["inputs"][0]["recovered"]["sha256"].is_string()); + } + + #[test] + fn error_status_counts_and_surfaces_in_the_summary() { + let mut collector = Collector::new(Mode::Unpack); + collector.push(sample_input(InputStatus::Error)); + collector.push(sample_input(InputStatus::Skipped)); + let report = collector.finish(); + assert_eq!(report.summary.errors, 1); + assert_eq!(report.summary.skipped, 1); + assert_eq!(report.summary.recovered, 0); + } + + #[test] + fn digest_matches_a_known_sha256() { + let digest = Digest::of(b"abc"); + assert_eq!(digest.size, 3); + assert_eq!( + digest.sha256, + "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad" + ); + } + + #[test] + fn inspect_profile_helpers_never_claim_recovery() { + let unchanged = metadata_unchanged_profile(None); + assert_eq!(unchanged.recovery, RecoveryStatus::NotAttempted); + assert!(unchanged.selected.is_none()); + assert!(unchanged.evidence.is_empty()); + assert_eq!(unchanged.static_validation, ValidationStatus::NotRun); + + let recovered = metadata_recovered_profile(None, LayoutKind::MetadataSeeded); + assert_eq!(recovered.selected, Some(LayoutKind::MetadataSeeded)); + assert_eq!( + recovered.evidence, + vec![ProtectionEvidence::ValidatedMetadataTransform] + ); + assert_eq!(recovered.static_validation, ValidationStatus::NotRun); + } +} diff --git a/senbei-io/src/windows/companion.rs b/senbei-io/src/windows/companion.rs index 466270a..25eda75 100644 --- a/senbei-io/src/windows/companion.rs +++ b/senbei-io/src/windows/companion.rs @@ -277,4 +277,160 @@ pub(super) mod tests { assert!(log.contains("module.exe._"), "{log}"); } } + + /// Inspection must describe a companion-declaring stub, not reproduce the + /// recovery entry point's refusal. + /// + /// [`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. + fn inspect_report(path: &std::path::Path) -> serde_json::Value { + let report = crate::job::inspect_path( + path, + false, + &senbei_engine::android::ResourceLimits::default(), + ) + .expect("inspection must not fail for a readable stub"); + serde_json::from_str(&report.to_json()).expect("valid report") + } + + fn assert_no_recovery_claim(input: &serde_json::Value) { + assert_eq!(input["status"], "recognized", "the stub is recognized"); + let profile = &input["profile"]; + assert_eq!(profile["recognition"], "recognized"); + assert!( + profile["selected"].is_null(), + "inspection selects no route: {profile}" + ); + 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() { + let dir = tempfile::tempdir().unwrap(); + let input = dir.path().join("module.exe"); + std::fs::write(&input, stub()).unwrap(); + + // The recovery entry point refuses this input. + assert!(super::super::read_unpacker_input(&input).is_err()); + + let value = inspect_report(&input); + let reported = &value["inputs"][0]; + assert_no_recovery_claim(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" + ); + } + + #[test] + fn inspect_of_a_companion_stub_with_a_non_matching_payload_reports_it() { + let dir = tempfile::tempdir().unwrap(); + let input = dir.path().join("module.exe"); + std::fs::write(&input, stub()).unwrap(); + std::fs::write(dir.path().join("module.exe._"), [0u8; 32]).unwrap(); + + assert!(super::super::read_unpacker_input(&input).is_err()); + + let value = inspect_report(&input); + let reported = &value["inputs"][0]; + assert_no_recovery_claim(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); + } + + #[test] + fn inspect_of_a_companion_stub_with_its_payload_reports_the_pairing() { + let dir = tempfile::tempdir().unwrap(); + let input = dir.path().join("module.exe"); + let bytes = stub(); + std::fs::write(&input, &bytes).unwrap(); + // The companion is byte-for-byte the stub's payload from the header. + std::fs::write(dir.path().join("module.exe._"), &bytes[HEADER_OFF..]).unwrap(); + assert!(super::super::read_unpacker_input(&input).is_ok()); + + let value = inspect_report(&input); + let reported = &value["inputs"][0]; + 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"); + } + + #[test] + fn folder_inspect_of_companion_stubs_stays_detection() { + let dir = tempfile::tempdir().unwrap(); + let missing = dir.path().join("missing.exe"); + let unmatched = dir.path().join("unmatched.dll"); + std::fs::write(&missing, stub()).unwrap(); + std::fs::write(&unmatched, stub()).unwrap(); + std::fs::write(dir.path().join("unmatched.dll._"), [0u8; 32]).unwrap(); + + let report = crate::job::inspect_path( + dir.path(), + false, + &senbei_engine::android::ResourceLimits::default(), + ) + .expect("folder inspection must not fail"); + let value: serde_json::Value = serde_json::from_str(&report.to_json()).unwrap(); + let inputs = value["inputs"].as_array().unwrap(); + assert_eq!(inputs.len(), 2, "both stubs are inspected: {value}"); + let states: Vec<&str> = inputs + .iter() + .map(|input| input["companion"]["state"].as_str().unwrap()) + .collect(); + assert!(states.contains(&"absent"), "{states:?}"); + assert!(states.contains(&"unmatched"), "{states:?}"); + for input in inputs { + assert_no_recovery_claim(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. + #[test] + fn inspect_read_error_does_not_invent_a_failed_recovery() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("gone.exe"); + let report = crate::job::inspect_path( + &path, + false, + &senbei_engine::android::ResourceLimits::default(), + ) + .expect("inspection returns a report even when the input cannot be read"); + let value: serde_json::Value = serde_json::from_str(&report.to_json()).unwrap(); + let input = &value["inputs"][0]; + 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()); + } } diff --git a/senbei-wasm/Cargo.lock b/senbei-wasm/Cargo.lock index 5943785..2acc7da 100644 --- a/senbei-wasm/Cargo.lock +++ b/senbei-wasm/Cargo.lock @@ -475,6 +475,8 @@ dependencies = [ "senbei-engine", "senbei-metadata", "senbei-pe", + "serde", + "serde_json", "sha2", "tempfile", "walkdir",