fix(inspect): collect full static recovery research by default

Inspect the protected input and actual recovered image, with bounded structural evidence, source identities and scoped recovery traces. Keep ordinary unpack lightweight and retain no research output files or logs.

Preserve Android extraction, restoration and metadata evidence, distinguish incomplete analyses from rejected candidates, and render detailed text and JSON reports with explicit address provenance.
This commit is contained in:
Momoko-Ayase committed 2026-11-06 02:33:45 +08:00
1 parent 05a4337a5e
commit 1ee4344c1e
22 files changed
+7776 -758

No files matched your search

+116 -14
View File
@@ -7,7 +7,7 @@ use std::sync::{
atomic::{AtomicBool, Ordering},
};
use senbei_engine::android::ResourceLimits;
use senbei_engine::android::{LimitExceeded, ResourceLimits};
use zip::ZipArchive;
use anyhow::{Context, Result, bail};
@@ -180,14 +180,25 @@ impl ArchiveBudget {
label: &str,
) -> Result<Vec<u8>> {
if size > self.max_entry_bytes {
bail!(
return Err(anyhow::Error::new(LimitExceeded::Entry {
requested: size,
limit: self.max_entry_bytes,
})
.context(format!(
"entry `{label}` exceeds extraction limit {}",
self.max_entry_bytes
);
)));
}
let length = size.min(maximum as u64);
if length > self.max_total_bytes.saturating_sub(self.bytes) {
bail!("manifest `{label}` exceeds the remaining extraction byte limit");
return Err(anyhow::Error::new(LimitExceeded::Total {
requested: self.bytes.saturating_add(length),
adding: length,
limit: self.max_total_bytes,
})
.context(format!(
"manifest `{label}` exceeds the remaining extraction byte limit"
)));
}
let mut bytes = Vec::new();
bytes
@@ -203,10 +214,14 @@ impl ArchiveBudget {
.checked_add(entries)
.context("archive entry count overflow")?;
if total > self.max_entries {
bail!(
return Err(anyhow::Error::new(LimitExceeded::Entries {
requested: total,
limit: self.max_entries,
})
.context(format!(
"archive entry limit exceeded: {total} > {}",
self.max_entries
);
)));
}
self.entries = total;
Ok(())
@@ -222,9 +237,21 @@ impl ArchiveBudget {
let remaining = self.max_total_bytes.saturating_sub(self.bytes);
let allowance = self.max_entry_bytes.min(remaining);
if declared_size > allowance {
bail!(
let exceeded = if declared_size > self.max_entry_bytes {
LimitExceeded::Entry {
requested: declared_size,
limit: self.max_entry_bytes,
}
} else {
LimitExceeded::Total {
requested: self.bytes.saturating_add(declared_size),
adding: declared_size,
limit: self.max_total_bytes,
}
};
return Err(anyhow::Error::new(exceeded).context(format!(
"entry `{label}` declares {declared_size} bytes, exceeding extraction limit {allowance}"
);
)));
}
// The advertised size is a stricter ceiling when it is smaller than
// the budget. A dishonest header must not buy extra decompression work.
@@ -243,7 +270,13 @@ impl ArchiveBudget {
.checked_add(read as u64)
.context("decompressed entry size overflow")?;
if next > limit {
bail!("entry `{label}` exceeds extraction limit {limit} while decompressing");
return Err(anyhow::Error::new(LimitExceeded::Entry {
requested: next,
limit,
})
.context(format!(
"entry `{label}` exceeds extraction limit {limit} while decompressing"
)));
}
self.bytes = self
.bytes
@@ -346,7 +379,11 @@ fn inspect_archive(
bail!("invalid ZIP64 end record");
}
if qword(&record, 4) > max_directory_bytes {
bail!("ZIP64 metadata exceeds the directory memory limit");
return Err(anyhow::Error::new(LimitExceeded::Entry {
requested: qword(&record, 4),
limit: max_directory_bytes,
})
.context("ZIP64 metadata exceeds the directory memory limit"));
}
zip64_record = Some(record_offset);
directory_start = qword(&record, 48);
@@ -356,10 +393,22 @@ fn inspect_archive(
bail!("inconsistent ZIP entry counts");
}
if entries > max_entries as u64 {
bail!("archive entry limit exceeded: {entries} > {max_entries}");
return Err(anyhow::Error::new(LimitExceeded::Entries {
requested: usize::try_from(entries).unwrap_or(usize::MAX),
limit: max_entries,
})
.context(format!(
"archive entry limit exceeded: {entries} > {max_entries}"
)));
}
if directory_bytes > max_directory_bytes {
bail!("ZIP directory size {directory_bytes} exceeds memory limit {max_directory_bytes}");
return Err(anyhow::Error::new(LimitExceeded::Entry {
requested: directory_bytes,
limit: max_directory_bytes,
})
.context(format!(
"ZIP directory size {directory_bytes} exceeds memory limit {max_directory_bytes}"
)));
}
file.seek(SeekFrom::Start(0))?;
Ok(ArchiveInfo {
@@ -420,6 +469,51 @@ mod tests {
);
}
#[test]
fn archive_ceilings_keep_typed_causes_and_context() {
let mut budget = ArchiveBudget::new(4, 6, 1);
budget.register_entries(1).unwrap();
let error = budget.register_entries(1).unwrap_err();
assert!(matches!(
error.downcast_ref::<LimitExceeded>(),
Some(LimitExceeded::Entries { .. })
));
assert!(format!("{error:#}").contains("entry limit"));
let error = budget
.read_probe(&mut Cursor::new(b"abcde"), 5, 5, "manifest")
.unwrap_err();
assert!(matches!(
error.downcast_ref::<LimitExceeded>(),
Some(LimitExceeded::Entry { .. })
));
let error = budget
.copy_entry(&mut Cursor::new(b"abcde"), &mut Vec::new(), 5, "large")
.unwrap_err();
assert!(matches!(
error.downcast_ref::<LimitExceeded>(),
Some(LimitExceeded::Entry { .. })
));
assert!(format!("{error:#}").contains("extraction limit"));
budget
.copy_entry(&mut Cursor::new(b"abcd"), &mut Vec::new(), 4, "first")
.unwrap();
let error = budget
.copy_entry(&mut Cursor::new(b"abc"), &mut Vec::new(), 3, "second")
.unwrap_err();
assert!(matches!(
error.downcast_ref::<LimitExceeded>(),
Some(LimitExceeded::Total { .. })
));
let error = budget
.read_probe(&mut Cursor::new(b"abc"), 3, 3, "manifest")
.unwrap_err();
assert!(matches!(
error.downcast_ref::<LimitExceeded>(),
Some(LimitExceeded::Total { .. })
));
}
#[test]
fn failed_writes_still_consume_the_read_budget() {
struct FailingWriter;
@@ -457,8 +551,16 @@ mod tests {
fn preflight_rejects_large_counts_and_directory_before_indexing() {
let mut file = tempfile::tempfile().unwrap();
file.write_all(&end_record(50, 1000)).unwrap();
assert!(preflight_archive(&mut file, 49, 1000).is_err());
assert!(preflight_archive(&mut file, 50, 999).is_err());
let count_error = preflight_archive(&mut file, 49, 1000).unwrap_err();
assert!(matches!(
count_error.downcast_ref::<LimitExceeded>(),
Some(LimitExceeded::Entries { .. })
));
let size_error = preflight_archive(&mut file, 50, 999).unwrap_err();
assert!(matches!(
size_error.downcast_ref::<LimitExceeded>(),
Some(LimitExceeded::Entry { .. })
));
assert_eq!(preflight_archive(&mut file, 50, 1000).unwrap(), 50);
}
+31 -2
View File
@@ -78,6 +78,10 @@ pub(crate) enum ContextAmbiguity {
pub(crate) struct AndroidRunCache {
pub(super) limits: senbei_engine::android::ResourceLimits,
pub(super) archive: super::archive_limits::ArchiveBudget,
/// Capture the engine's own extraction/restoration reports for research
/// inspection. Off for every ordinary run: the reports are large and are
/// discarded after each restore.
pub(super) research: bool,
apps: HashMap<AppKey, ApplicationModules>,
/// Successfully restored protected libraries, keyed by encrypted content.
libraries: HashMap<String, CachedLibrary>,
@@ -121,6 +125,11 @@ impl AndroidRunCache {
}
}
/// Whether this run keeps the engines' own reports for research output.
pub(crate) fn research(&self) -> bool {
self.research
}
pub(crate) fn modules_mut(&mut self, key: &AppKey) -> &mut ApplicationModules {
self.apps.entry(key.clone()).or_default()
}
@@ -495,6 +504,9 @@ pub(crate) struct RestoredLibrary {
/// test double, or an engine without a validation pass) — never that the
/// output validated. `Some(empty)` is a completed, clean validation.
pub validation: Option<super::ValidationDiagnostics>,
/// The extraction and restoration reports this restore actually produced,
/// kept only when the run asked for research output. `None` otherwise.
pub research: Option<crate::report::AndroidResearchReport>,
}
/// Injectable library restore. Tests supply a fake so application-context
@@ -513,10 +525,27 @@ pub(crate) trait LibraryRestorer {
/// Production restorer: stage-2 extract, ELF rebuild, embedded metadata unwrap.
#[derive(Default)]
pub(crate) struct EngineRestorer(pub(super) senbei_engine::android::ResourceLimits);
pub(crate) struct EngineRestorer {
pub(super) limits: senbei_engine::android::ResourceLimits,
/// Keep the engines' reports instead of dropping them after each restore.
pub(super) research: bool,
}
impl EngineRestorer {
/// A restorer for `limits`, keeping the engines' reports only for research.
pub(crate) fn new(limits: senbei_engine::android::ResourceLimits, research: bool) -> Self {
Self { limits, research }
}
}
impl LibraryRestorer for EngineRestorer {
fn restore(&mut self, input: &Path, dest: &Path, verbose: bool) -> Result<RestoredLibrary> {
crate::android::restore_so_with_engine_limits(input, dest, verbose, &self.0)
crate::android::restore_so_with_engine_limits(
input,
dest,
verbose,
&self.limits,
self.research,
)
}
}
+480 -94
View File
@@ -254,27 +254,6 @@ pub fn is_protected_so_file(path: &Path) -> bool {
is_elf64_aarch64(&bytes) && is_protected_libil2cpp(&bytes)
}
/// [`probe_so_file_with_limits`] with the recognition profile it produced.
///
/// A resource-limit failure is reported as `Blocked` with the error retained,
/// never as "not protected".
pub(crate) fn probe_so_profiled(
path: &Path,
limits: &ResourceLimits,
) -> Result<(senbei_engine::ProtectionProfile, Result<bool, String>)> {
let file = File::open(path).with_context(|| format!("open `{}`", path.display()))?;
let bytes = map_read_only(&file, path)?;
if !is_elf64_aarch64(&bytes) {
return Ok((
senbei_engine::ProtectionProfile::new(senbei_engine::ObservedTarget::android(None)),
Ok(false),
));
}
let (profile, result) =
senbei_engine::android::probe_libil2cpp_profiled_with_limits(&bytes, limits);
Ok((profile, result.map_err(|error| error.to_string())))
}
pub(crate) fn probe_so_file_with_limits(
path: &Path,
limits: &senbei_engine::android::ResourceLimits,
@@ -311,6 +290,7 @@ pub(crate) fn restore_so_with_engine_limits(
dest: &Path,
verbose: bool,
limits: &ResourceLimits,
research: bool,
) -> Result<context::RestoredLibrary> {
let temporary = tempfile::tempdir().context("create stage-2 workspace")?;
let stage2_dir = temporary.path().join("stage2");
@@ -319,6 +299,14 @@ pub(crate) fn restore_so_with_engine_limits(
limits,
)
.context("extract stage-1/stage-2 payload")?;
// The report the extraction just produced. Serialized once, only for
// research runs; an ordinary run drops it with the rest of the workspace.
let extraction_report = research.then(|| {
report_value(
&extraction,
&[(input, "<input>"), (temporary.path(), "<workspace>")],
)
});
// Every module 0x0C is collected. Two distinct images in one library are a
// conflict for that library's application, not a last-writer-wins update.
let mut modules = Vec::new();
@@ -357,8 +345,37 @@ pub(crate) fn restore_so_with_engine_limits(
verbose,
},
limits,
)
.context("restore protected library")?;
);
// A restore that failed after extraction is still a research finding: the
// extraction's seeds, records and modules are already known, and the
// original failure travels with them so nothing is lost.
let report = match report {
Ok(report) => report,
Err(error) => {
let restored = extraction_report
.map(|extraction| crate::report::AndroidResearchReport {
extraction,
restoration: None,
})
.map(ResearchCapture::Library);
return Err(capture(
anyhow::Error::new(error).context("restore protected library"),
restored,
));
}
};
// The same restore's own report, serialized once for research output
// before the validation diagnostics are taken out of it below.
let restoration = research.then(|| {
report_value(
&report,
&[
(input, "<input>"),
(dest, "<output>"),
(temporary.path(), "<workspace>"),
],
)
});
// Keep only the validation verdict this call already produced. Nothing is
// re-read or re-validated: the diagnostics describe the bytes just written.
let validation = Some(ValidationDiagnostics {
@@ -372,6 +389,13 @@ pub(crate) fn restore_so_with_engine_limits(
method_index_module,
module_image,
validation,
research: match (extraction_report, restoration) {
(Some(extraction), restoration) => Some(crate::report::AndroidResearchReport {
extraction,
restoration,
}),
_ => None,
},
})
}
@@ -400,10 +424,36 @@ pub fn restore_so_file_with_diagnostics(
verbose: bool,
limits: &ResourceLimits,
) -> Result<(Option<Vec<u8>>, Option<ValidationDiagnostics>)> {
let restored = context::EngineRestorer(*limits).restore(input, dest, verbose)?;
let restored = context::EngineRestorer::new(*limits, false).restore(input, dest, verbose)?;
Ok((restored.embedded_metadata, restored.validation))
}
/// One single-file Android library restore.
pub(crate) struct ResearchedLibrary {
pub embedded_metadata: Option<Vec<u8>>,
/// Structural diagnostics for the image this restore wrote.
pub validation: Option<ValidationDiagnostics>,
/// The engines' own reports, kept only when research was requested.
pub research: Option<crate::report::AndroidResearchReport>,
}
/// [`restore_so_file_with_diagnostics`], also keeping the engines' own reports
/// for research output. Nothing else changes: the same single restore runs.
pub(crate) fn restore_so_file_researched(
input: &Path,
dest: &Path,
verbose: bool,
limits: &ResourceLimits,
research: bool,
) -> Result<ResearchedLibrary> {
let restored = context::EngineRestorer::new(*limits, research).restore(input, dest, verbose)?;
Ok(ResearchedLibrary {
embedded_metadata: restored.embedded_metadata,
validation: restored.validation,
research: restored.research,
})
}
/// Fresh run-scoped cache. Library hits reuse their module context; metadata hits
/// are keyed by encrypted bytes and the module that recovered them.
#[cfg(test)]
@@ -415,6 +465,13 @@ pub(crate) fn run_cache_with_limits(limits: &ResourceLimits) -> context::Android
context::AndroidRunCache::with_limits(limits)
}
/// The same cache, keeping the engines' reports for research output.
pub(crate) fn run_cache_for_research(limits: &ResourceLimits) -> context::AndroidRunCache {
let mut cache = context::AndroidRunCache::with_limits(limits);
cache.research = true;
cache
}
/// Assign loose libraries and metadata to application contexts.
pub(crate) fn loose_scopes(
libraries: &[PathBuf],
@@ -434,6 +491,9 @@ pub(crate) struct LooseLibraryOutcome {
/// Structural diagnostics from the restore that produced this output.
/// `None` for duplicates, failures, and restorers without a report.
pub validation: Option<ValidationDiagnostics>,
/// The engines' own extraction and restoration reports, kept only for
/// research inspection. `None` for every ordinary run.
pub research: Option<crate::report::AndroidResearchReport>,
}
pub(crate) fn restore_loose_library(
@@ -452,7 +512,7 @@ pub(crate) fn restore_loose_library(
app,
verbose,
cache,
&mut context::EngineRestorer(limits),
&mut context::EngineRestorer::new(limits, cache.research()),
)
}
@@ -474,6 +534,7 @@ fn restore_loose_library_with<R: context::LibraryRestorer>(
status: EntryStatus::Duplicate,
embedded: None,
validation: None,
research: None,
});
}
// A prior content-only success still needs context extraction. Restore it
@@ -499,6 +560,7 @@ fn restore_loose_library_with<R: context::LibraryRestorer>(
status: EntryStatus::Failed(error),
embedded: None,
validation: None,
research: None,
});
}
embedded = Some(meta_dest);
@@ -517,15 +579,30 @@ fn restore_loose_library_with<R: context::LibraryRestorer>(
},
embedded,
// A duplicate restored only for its module context has no
// output of its own, so it reports no diagnostics.
validation: if prior { None } else { restored.validation },
// output of its own, so it reports no diagnostics, and the
// engine reports belong to the run that actually produced it.
validation: if prior {
None
} else {
restored.validation.clone()
},
research: if prior { None } else { restored.research },
})
}
Err(error) => {
// A restore that failed after extraction keeps the extraction's
// own report; the error itself is unchanged.
let research = match error_research(&error) {
Some(ResearchCapture::Library(report)) => Some(report.clone()),
_ => None,
};
Ok(LooseLibraryOutcome {
status: EntryStatus::Failed(error),
embedded: None,
validation: None,
research,
})
}
Err(error) => Ok(LooseLibraryOutcome {
status: EntryStatus::Failed(error),
embedded: None,
validation: None,
}),
}
}
@@ -538,6 +615,9 @@ pub(crate) struct LooseMetadataOutcome {
pub provenance: Vec<String>,
/// Route the transform actually took (seeded, structural, or method-index).
pub layout: senbei_engine::LayoutKind,
/// Seeds tried, discovery, and the transform's own report. Only a research
/// run keeps this.
pub research: Option<serde_json::Value>,
}
pub(crate) fn restore_loose_metadata(
@@ -571,8 +651,9 @@ pub(crate) fn restore_loose_metadata(
let module = module.as_deref();
// Loose metadata retains one output per path, as before. Do not keep all
// restored blobs in the folder cache just to avoid a repeated permutation.
let (out, report, layout) =
restore_metadata_bytes_with_module(&data, module).with_context(|| label.to_owned())?;
let (out, report, layout, research) =
restore_metadata_with_module(&data, module, cache.research())
.with_context(|| label.to_owned())?;
if report.remapped > 0 {
write_metadata_blob(dest, &out)?;
if verbose {
@@ -584,6 +665,7 @@ pub(crate) fn restore_loose_metadata(
remapped: report.remapped,
provenance,
layout,
research,
})
}
@@ -665,43 +747,47 @@ pub(crate) fn restore_package_cached(
out_root,
cache,
verbose,
&mut context::EngineRestorer(limits),
&mut context::EngineRestorer::new(limits, cache.research()),
)
}
/// One folder split-set: every library in the group, then every metadata blob.
/// A library-only pass records modules without writing metadata, so a metadata
/// blob in an earlier sibling cannot run before a library in a later one.
/// `members` pairs each package with the relative path its outputs live under.
///
/// The relative path is computed by the caller (see `job::rel_in_tree`) and is
/// always relative. This function never derives it: `Path::join` with an
/// absolute path discards the output root, so a fallback here could write
/// outside the caller's directory — unacceptable for a dry run or inspection,
/// whose whole contract is that it keeps nothing outside its own workspace.
pub(crate) fn restore_apk_group(
packages: &[PathBuf],
root: &Path,
members: &[(&Path, &Path)],
out_root: &Path,
cache: &mut context::AndroidRunCache,
verbose: bool,
) -> Result<Vec<EntryOutcome>> {
let limits = cache.limits;
let mut outcomes = Vec::new();
for package in packages {
let rel = package.strip_prefix(root).unwrap_or(package);
for (package, rel) in members {
outcomes.extend(restore_package_pass(
package,
rel,
out_root,
cache,
verbose,
&mut context::EngineRestorer(limits),
&mut context::EngineRestorer::new(limits, cache.research()),
PackagePass::Libraries,
)?);
}
for package in packages {
let rel = package.strip_prefix(root).unwrap_or(package);
for (package, rel) in members {
outcomes.extend(restore_package_pass(
package,
rel,
out_root,
cache,
verbose,
&mut context::EngineRestorer(limits),
&mut context::EngineRestorer::new(limits, cache.research()),
PackagePass::Metadata,
)?);
}
@@ -724,6 +810,124 @@ pub fn content_identity(data: &[u8]) -> String {
hex_digest(&digest.finalize())
}
/// A failure that still carries what the attempt had already observed.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum ResearchCapture {
/// Extraction ran and produced a report; the restoration after it failed.
Library(crate::report::AndroidResearchReport),
/// A metadata transform's seeds, discovery, and failure reason.
Metadata(serde_json::Value),
}
/// A transform error that still carries what the attempt observed.
///
/// Research inspection wants the seeds it tried and the reason each failed even
/// when no output was produced. The error keeps its ordinary `anyhow` chain —
/// callers that do not care about research see exactly the same message.
#[derive(Debug)]
pub(crate) struct LossyError {
inner: anyhow::Error,
capture: ResearchCapture,
}
impl LossyError {
pub(crate) fn new(inner: anyhow::Error, capture: ResearchCapture) -> Self {
Self { inner, capture }
}
fn capture(&self) -> &ResearchCapture {
&self.capture
}
}
impl std::fmt::Display for LossyError {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.inner.fmt(formatter)
}
}
impl std::error::Error for LossyError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
// Keep the whole wrapped chain reachable: callers classify the original
// error (an unsupported version, a malformed blob) by walking it.
Some(self.inner.as_ref())
}
}
/// The research captured for a failure, if the error (or anything it wraps)
/// carries one.
pub(crate) fn error_research(error: &anyhow::Error) -> Option<&ResearchCapture> {
error
.chain()
.find_map(|cause| cause.downcast_ref::<LossyError>())
.map(LossyError::capture)
}
/// [`capture`] with the same rule, exposed to the module's tests so a failed
/// restore can be exercised without a protected fixture.
#[cfg(test)]
pub(crate) fn capture_for_tests(
error: anyhow::Error,
research: Option<ResearchCapture>,
) -> anyhow::Error {
capture(error, research)
}
/// Wrap `error` with the capture, when there is one.
fn capture(error: anyhow::Error, capture: Option<ResearchCapture>) -> anyhow::Error {
match capture {
Some(capture) => LossyError::new(error, capture).into(),
None => error,
}
}
/// Serialize one engine report for research output.
///
/// The report is the engine's own, unchanged; only filesystem locations are
/// rewritten to logical labels. A research report outlives the run, and a
/// scratch path that no longer exists is noise — or worse, a misleading hint
/// about where an output was "kept".
fn report_value<T: serde::Serialize>(report: &T, labels: &[(&Path, &str)]) -> serde_json::Value {
let mut value = serde_json::to_value(report).unwrap_or(serde_json::Value::Null);
scrub_paths(&mut value, labels);
value
}
fn scrub_paths(value: &mut serde_json::Value, labels: &[(&Path, &str)]) {
// Longest location first: a nested path starts with its parent, and the
// more specific label is the one that describes it.
let mut rules: Vec<(String, &str)> = labels
.iter()
.map(|(path, label)| (path.display().to_string(), *label))
.filter(|(rendered, _)| !rendered.is_empty())
.collect();
rules.sort_by_key(|(rendered, _)| std::cmp::Reverse(rendered.len()));
scrub_value(value, &rules);
}
fn scrub_value(value: &mut serde_json::Value, rules: &[(String, &str)]) {
match value {
serde_json::Value::String(text) => {
for (rendered, label) in rules {
if text.contains(rendered.as_str()) {
*text = text.replace(rendered.as_str(), label);
}
}
}
serde_json::Value::Array(items) => {
for item in items {
scrub_value(item, rules);
}
}
serde_json::Value::Object(fields) => {
for field in fields.values_mut() {
scrub_value(field, rules);
}
}
_ => {}
}
}
/// Restore an il2cpp metadata blob. Paired v24.1 Android packages use the
/// method-index profile recovered from module 0x0C; later Android layouts use
/// the seeded MethodDef RID permutation before falling back to the structural
@@ -745,20 +949,67 @@ pub(crate) fn restore_metadata_bytes_with_module(
data: &[u8],
method_index_module: Option<&[u8]>,
) -> anyhow::Result<(Vec<u8>, senbei_metadata::Report, senbei_engine::LayoutKind)> {
let (out, report, layout, _) = restore_metadata_with_module(data, method_index_module, false)?;
Ok((out, report, layout))
}
/// [`restore_metadata_bytes_with_module`], optionally keeping the facts the
/// transform observed on the way.
///
/// The research value is produced by the same pass that does the work: the
/// seed candidates discovery found (or why it found none), the seeds actually
/// tried, and the transform's own report. Nothing is re-run for it, and it
/// survives a transform that fails — a failing trial is exactly what the
/// caller wants to see.
pub(crate) fn restore_metadata_with_module(
data: &[u8],
method_index_module: Option<&[u8]>,
research: bool,
) -> anyhow::Result<(
Vec<u8>,
senbei_metadata::Report,
senbei_engine::LayoutKind,
Option<serde_json::Value>,
)> {
use senbei_engine::LayoutKind;
let version = data
.get(4..8)
.and_then(|bytes| <[u8; 4]>::try_from(bytes).ok())
.map(u32::from_le_bytes);
let mut facts = MetadataFacts {
version,
route: "method_indices",
module_0c_sha256: method_index_module.map(content_identity),
..MetadataFacts::default()
};
// Keep what the attempt has seen so far, then wrap the failure with it.
let fail = |facts: &mut MetadataFacts, error: anyhow::Error| -> anyhow::Error {
facts.error = Some(format!("{error:#}"));
let kept = research.then(|| facts.clone().into_value());
capture(error, kept.map(ResearchCapture::Metadata))
};
if version == Some(24) {
// v24.1 method indices come only from this application's module 0x0C.
// Falling through to the structural remap would report "unsupported
// version" and could be mistaken for a clean skip. No module is a
// failed binding, not an unsupported layout.
let module = method_index_module
.ok_or_else(|| anyhow::anyhow!("no module 0x0C for v24.1 metadata"))?;
let Some(module) = method_index_module else {
let error = anyhow::anyhow!("no module 0x0C for v24.1 metadata");
return Err(fail(&mut facts, error));
};
let (out, report) = senbei_metadata::android::restore_method_indices_v24_1(data, module)
.map_err(anyhow::Error::new)?;
.map_err(anyhow::Error::new)
.map_err(|error| fail(&mut facts, error))?;
facts.version = Some(report.version);
facts.report = Some(serde_json::json!({
"version": report.version,
"methods": report.methods,
"active_methods": report.active_methods,
"changed_indices": report.changed_indices,
"exception_count": report.exception_count,
"seed": report.seed,
}));
return Ok((
out,
senbei_metadata::Report {
@@ -768,12 +1019,31 @@ pub(crate) fn restore_metadata_bytes_with_module(
modules: 0,
},
LayoutKind::MetadataMethodIndices,
research.then(|| facts.into_value()),
));
}
if let Ok(discovery) = senbei_metadata::android::discover_method_token_seeds(data)
&& matches!(discovery.version, 29 | 31 | 39)
{
let mut seeds = discovery.seed_candidates.clone();
// Seed discovery is the only step that can say why a seeded restore was
// never tried, so its own outcome is recorded for research. Whether the
// seeded route runs at all is decided exactly as before.
let mut seeded_layout = false;
match senbei_metadata::android::discover_method_token_seeds(data) {
Ok(found) if matches!(found.version, 29 | 31 | 39) => {
seeded_layout = true;
facts.seed_candidates = found.seed_candidates.clone();
if research {
facts.discovery = serde_json::to_value(&found).ok();
}
}
Ok(_) => {}
Err(error) => {
if research {
facts.discovery_error = Some(format!("{error}"));
}
}
}
if seeded_layout {
let mut seeds = facts.seed_candidates.clone();
if seeds.is_empty() {
seeds.push(senbei_metadata::android::DEFAULT_METHOD_TOKEN_SEED);
}
@@ -782,7 +1052,24 @@ pub(crate) fn restore_metadata_bytes_with_module(
// build with an unseeded permutation falls through to the structural
// remap rather than producing a silently wrong file.
for seed in seeds {
facts.tried_seeds.push(seed);
if let Ok((out, report)) = senbei_metadata::android::restore_method_tokens(data, seed) {
facts.route = "seeded";
facts.version = Some(report.version);
facts.report = Some(serde_json::json!({
"version": report.version,
"seed": report.seed,
"encryption_status": report.encryption_status,
"images": report.images,
"images_with_methods": report.images_with_methods,
"types": report.types,
"methods": report.methods,
"visited_methods": report.visited_methods,
"already_correct_before": report.already_correct_before,
"correct_after": report.correct_after,
"changed_tokens": report.changed_tokens,
"transformed_images": report.transformed_images,
}));
return Ok((
out,
senbei_metadata::Report {
@@ -792,12 +1079,66 @@ pub(crate) fn restore_metadata_bytes_with_module(
modules: report.images_with_methods,
},
LayoutKind::MetadataSeeded,
research.then(|| facts.into_value()),
));
}
}
}
let (out, report) = senbei_metadata::deobfuscate(data).map_err(anyhow::Error::new)?;
Ok((out, report, LayoutKind::MetadataStructural))
facts.route = "structural";
let (out, report) = senbei_metadata::deobfuscate(data)
.map_err(anyhow::Error::new)
.map_err(|error| fail(&mut facts, error))?;
facts.version = Some(report.version);
facts.report = Some(serde_json::json!({
"version": report.version,
"methods": report.methods,
"remapped": report.remapped,
"modules": report.modules,
}));
Ok((
out,
report,
LayoutKind::MetadataStructural,
research.then(|| facts.into_value()),
))
}
/// What one metadata transform observed, independent of whether it succeeded.
#[derive(Debug, Clone, Default)]
struct MetadataFacts {
route: &'static str,
version: Option<u32>,
/// Seeds the transform actually tried, in order.
tried_seeds: Vec<u32>,
/// Candidates seed discovery reported.
seed_candidates: Vec<u32>,
/// The discovery report, when it found a supported layout.
discovery: Option<serde_json::Value>,
/// Why seed discovery declined, when it did.
discovery_error: Option<String>,
/// The transform's own report.
report: Option<serde_json::Value>,
/// Identity of the module `0x0C` this transform bound to, when it had one.
module_0c_sha256: Option<String>,
/// Why the transform stopped, when it did.
error: Option<String>,
}
impl MetadataFacts {
fn into_value(self) -> serde_json::Value {
serde_json::json!({
"route": self.route,
"version": self.version,
"tried_seeds": self.tried_seeds,
"seed_candidates": self.seed_candidates,
"discovery": self.discovery,
"discovery_error": self.discovery_error,
"report": self.report,
"module_0c_sha256": self.module_0c_sha256,
"error": self.error,
})
}
}
/// What happened to one archive entry (or one loose Android target).
@@ -820,6 +1161,12 @@ pub struct EntryOutcome {
/// Structural diagnostics from the restore of this entry. `None` for
/// metadata entries, duplicates, and restorers without a report.
pub validation: Option<ValidationDiagnostics>,
/// The engines' own reports for a library entry. Only a research run keeps
/// them, and only for an entry that actually restored.
pub research: Option<crate::report::AndroidResearchReport>,
/// Seeds tried, discovery, and the transform report for a metadata entry.
/// Only a research run keeps them, and they survive a failed transform.
pub metadata_research: Option<serde_json::Value>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -897,17 +1244,34 @@ pub fn restore_package_with_limits(
// package still skips those bytes; module context for metadata is rebuilt
// inside this package (one package, or one manifest-scoped bundle, is one
// application boundary).
restore_package_with_limits_and_research(package, rel, out_root, seen, verbose, &limits, false)
}
/// [`restore_package_with_limits`], optionally keeping the engines' reports for
/// research output. One package is one application boundary either way.
pub(crate) fn restore_package_with_limits_and_research(
package: &Path,
rel: &Path,
out_root: &Path,
seen: &mut HashSet<String>,
verbose: bool,
limits: &ResourceLimits,
research: bool,
) -> Result<Vec<EntryOutcome>> {
let limits = *limits;
let mut cache = context::AndroidRunCache::with_limits(&limits);
cache.research = research;
for identity in seen.iter().cloned() {
cache.insert_prior_success(identity);
}
let research = cache.research();
let outcomes = restore_package_with_restorer(
package,
rel,
out_root,
&mut cache,
verbose,
&mut context::EngineRestorer(limits),
&mut context::EngineRestorer::new(limits, research),
);
// Publish successes even when the package returns `Err`. The caller's set
// is only replaced after that, so a panic still leaves the old successes.
@@ -1188,6 +1552,8 @@ fn restore_package_entry<R: Read + Seek, T: context::LibraryRestorer>(
layout: None,
metadata_version: None,
validation: None,
research: None,
metadata_research: None,
};
if !is_so && !is_meta {
return Ok(vec![outcome(
@@ -1238,6 +1604,7 @@ fn restore_package_entry<R: Read + Seek, T: context::LibraryRestorer>(
let mut restored_outcome =
outcome(EntryKind::So, EntryStatus::Restored, Vec::new());
restored_outcome.validation = restored.validation.clone();
restored_outcome.research = restored.research.clone();
outcomes.push(restored_outcome);
}
if !prior && let Some(blob) = &restored.embedded_metadata {
@@ -1252,6 +1619,8 @@ fn restore_package_entry<R: Read + Seek, T: context::LibraryRestorer>(
layout: None,
metadata_version: None,
validation: None,
research: None,
metadata_research: None,
}),
Err(error) => embedded_failed = Some(error),
}
@@ -1276,11 +1645,17 @@ fn restore_package_entry<R: Read + Seek, T: context::LibraryRestorer>(
}
}
}
Err(error) => vec![outcome(
EntryKind::So,
EntryStatus::Failed(error),
Vec::new(),
)],
Err(error) => {
// A restore that failed after extraction keeps what the
// extraction already reported, alongside the error.
let research = match error_research(&error) {
Some(ResearchCapture::Library(report)) => Some(report.clone()),
_ => None,
};
let mut failed = outcome(EntryKind::So, EntryStatus::Failed(error), Vec::new());
failed.research = research;
vec![failed]
}
},
);
}
@@ -1328,47 +1703,58 @@ fn restore_package_entry<R: Read + Seek, T: context::LibraryRestorer>(
// Metadata entry: write only when the restore actually changed protected
// method fields — a clean blob needs no copy (same contract as loose files).
// The binding was resolved before this write.
let (kind, status, layout) = match restore_metadata_bytes_with_module(&entry_data, module) {
Ok((out, report, layout)) if report.remapped > 0 => {
let kind = EntryKind::Metadata {
remapped: report.remapped,
};
match write_metadata_blob(dest, &out) {
Ok(()) => {
state.cache.insert_metadata(
identity,
context_identity,
context::CachedMetadata::Restored {
remapped: report.remapped,
},
);
(kind, EntryStatus::Restored, Some(layout))
let (kind, status, layout, metadata_research) =
match restore_metadata_with_module(&entry_data, module, state.cache.research()) {
Ok((out, report, layout, research)) if report.remapped > 0 => {
let kind = EntryKind::Metadata {
remapped: report.remapped,
};
match write_metadata_blob(dest, &out) {
Ok(()) => {
state.cache.insert_metadata(
identity,
context_identity,
context::CachedMetadata::Restored {
remapped: report.remapped,
},
);
(kind, EntryStatus::Restored, Some(layout), research)
}
Err(error) => (kind, EntryStatus::Failed(error), Some(layout), research),
}
Err(error) => (kind, EntryStatus::Failed(error), Some(layout)),
}
}
// A blob that needed no change still reports the route that ran.
Ok((_, _report, layout)) => {
state.cache.insert_metadata(
identity,
context_identity,
context::CachedMetadata::Unchanged,
);
(
EntryKind::Metadata { remapped: 0 },
EntryStatus::Unchanged,
Some(layout),
)
}
Err(error) => (
EntryKind::Metadata { remapped: 0 },
EntryStatus::Failed(error),
None,
),
};
// A blob that needed no change still reports the route that ran.
Ok((_, _report, layout, research)) => {
state.cache.insert_metadata(
identity,
context_identity,
context::CachedMetadata::Unchanged,
);
(
EntryKind::Metadata { remapped: 0 },
EntryStatus::Unchanged,
Some(layout),
research,
)
}
Err(error) => {
// The seeds it tried and the reason it stopped survive the failure.
let research = error_research(&error).and_then(|capture| match capture {
ResearchCapture::Metadata(value) => Some(value.clone()),
ResearchCapture::Library(_) => None,
});
(
EntryKind::Metadata { remapped: 0 },
EntryStatus::Failed(error),
None,
research,
)
}
};
let mut entry_outcome = outcome(kind, status, provenance_labels(&provenance));
entry_outcome.layout = layout;
entry_outcome.metadata_version = version;
entry_outcome.metadata_research = metadata_research;
Ok(vec![entry_outcome])
}
+240
View File
@@ -36,6 +36,7 @@ impl LibraryRestorer for ScriptedRestorer {
// A scripted restore has no engine report behind it, so it claims
// no validation verdict at all.
validation: None,
research: None,
})
}
@@ -1349,3 +1350,242 @@ fn scripted_restore_claims_no_validation_verdict() {
"a restorer without a report must not claim a clean verdict"
);
}
/// Research keeps what the transform actually did: the route, the seeds tried,
/// and the engine's own counters. Ordinary runs keep none of it.
#[test]
fn metadata_research_reports_the_route_that_ran() {
let data = metadata_fixture();
let (_, _, layout, research) = restore_metadata_with_module(&data, None, true).unwrap();
let research = research.expect("research mode keeps the transform's facts");
assert_eq!(research["version"], 31);
// The fixture has no seeded permutation to find, so the measured route is
// the structural remap — and the research names the route that actually ran.
assert_eq!(research["route"], "structural");
assert!(research["tried_seeds"].as_array().is_some());
assert!(research["report"].is_object(), "{research}");
assert!(research["error"].is_null());
assert_eq!(
research["module_0c_sha256"],
serde_json::Value::Null,
"no module was offered for this blob"
);
// The layout the transform reported is the one the research names.
let (_, _, quiet_layout, quiet) = restore_metadata_with_module(&data, None, false).unwrap();
assert!(quiet.is_none(), "an ordinary run keeps no research value");
assert_eq!(quiet_layout, layout);
}
/// A failed transform still reports the seeds it tried and why it stopped.
#[test]
fn metadata_research_survives_a_failed_transform() {
// A v24.1 header with no module 0x0C: the binding itself fails, before any
// transform could run.
let mut data = metadata_fixture();
data[4..8].copy_from_slice(&24u32.to_le_bytes());
let error = restore_metadata_with_module(&data, None, true).unwrap_err();
let capture = error_research(&error).expect("the failure carries its research");
let ResearchCapture::Metadata(value) = capture else {
panic!("a metadata failure carries metadata research");
};
assert_eq!(value["route"], "method_indices");
assert_eq!(value["version"], 24);
assert!(
value["error"]
.as_str()
.is_some_and(|text| text.contains("0x0C")),
"the reason is kept: {value}"
);
// An ordinary run fails the same way, just without the research value.
let quiet = restore_metadata_with_module(&data, None, false).unwrap_err();
assert!(error_research(&quiet).is_none());
}
/// A library restore that fails after extraction keeps the extraction's own
/// report, so the research output says how far it got.
#[test]
fn a_failed_library_restore_keeps_what_extraction_reported() {
let report = crate::report::AndroidResearchReport {
extraction: serde_json::json!({"stage1": {"payload_key": 0x1234}, "streams": []}),
restoration: None,
};
let error = crate::android::capture_for_tests(
anyhow::anyhow!("baseline restore failed"),
Some(ResearchCapture::Library(report.clone())),
);
let capture = error_research(&error).expect("the failure carries its research");
let ResearchCapture::Library(kept) = capture else {
panic!("a library failure carries library research");
};
assert_eq!(kept.extraction, report.extraction);
assert!(
kept.restoration.is_none(),
"no restoration report exists for a restore that failed"
);
// The original failure is still the error's message.
assert!(format!("{error:#}").contains("baseline restore failed"));
}
/// A split set is restored with output paths computed by the caller. An
/// absolute relative path would make `Path::join` discard the output root and
/// escape it — precisely what a dry run/inspection must never do.
#[test]
fn a_split_set_never_writes_outside_the_output_root() {
let temp = tempfile::tempdir().unwrap();
let root = temp.path().join("tree");
std::fs::create_dir_all(&root).unwrap();
let config = root.join("config.arm64_v8a.apk");
let base = root.join("base.apk");
let module_data = pair(3).1;
write_package(
&config,
&[
(
"AndroidManifest.xml",
manifest("com.example.split", "7").as_bytes(),
),
("lib/arm64-v8a/libil2cpp.so", &library_bytes(b"split-so")),
],
);
write_package(
&base,
&[
(
"AndroidManifest.xml",
manifest("com.example.split", "7").as_bytes(),
),
("assets/global-metadata.dat", &pair(3).0),
],
);
assert_eq!(
loose_apk_groups(&[base.clone(), config.clone()]).len(),
1,
"same package and version form one split set"
);
let out = temp.path().join("workspace");
let rels: Vec<PathBuf> = [&base, &config]
.iter()
.map(|package| package.strip_prefix(&root).unwrap().to_path_buf())
.collect();
let members: Vec<(&Path, &Path)> = [&base, &config]
.iter()
.map(|package| package.as_path())
.zip(rels.iter().map(|rel| rel.as_path()))
.collect();
let mut cache = run_cache_for_research(&senbei_engine::android::ResourceLimits::default());
let results = restore_apk_group(&members, &out, &mut cache, false);
assert!(results.is_ok(), "synthetic split set restores: {results:?}");
for rel in &rels {
assert!(!rel.is_absolute(), "relative paths stay relative: {rel:?}");
assert!(
out.join(rel).starts_with(&out),
"every output stays under the workspace"
);
}
let written: Vec<PathBuf> = std::fs::read_dir(temp.path())
.unwrap()
.filter_map(|entry| entry.ok().map(|entry| entry.path()))
.filter(|path| path != &root && path != &out)
.collect();
assert!(
written.is_empty(),
"nothing appears beside the workspace: {written:?}"
);
let _ = module_data;
}
/// A caller cannot hand the group restore an absolute "relative" path by
/// accident through this API: it takes explicit pairs, and the folder driver
/// builds them with the same helper the rest of the run uses. This pins the
/// shape so a future refactor cannot reintroduce the `strip_prefix(..).unwrap_or`
/// fallback that made `Path::join` discard the output root.
#[test]
fn the_group_restore_never_derives_its_own_relative_path() {
let source = include_str!("mod.rs");
let signature = source
.split("pub(crate) fn restore_apk_group(")
.nth(1)
.unwrap();
let head = signature
.split(") -> Result<Vec<EntryOutcome>>")
.next()
.unwrap();
assert!(
head.contains("members: &[(&Path, &Path)]"),
"the group restore receives caller-computed relative paths: {head}"
);
assert!(
!source.contains("strip_prefix(root).unwrap_or(package)"),
"the absolute-path fallback must not come back"
);
}
/// A restorer that fails with a resource ceiling, as the production one does
/// when an entry exceeds `--max-entry-mib`.
struct LimitedRestorer;
impl LibraryRestorer for LimitedRestorer {
fn restore(
&mut self,
_input: &Path,
_dest: &Path,
_verbose: bool,
) -> anyhow::Result<RestoredLibrary> {
Err(anyhow::Error::new(
senbei_engine::android::LimitExceeded::Entry {
requested: 4 * 1024 * 1024,
limit: 1024 * 1024,
},
))
}
fn protected_override(&mut self, input: &Path) -> Option<Vec<u8>> {
std::fs::read(input).ok()
}
}
/// A known target whose restore stopped on a resource ceiling is an error the
/// report can name — it is not "recognized, therefore complete". The status and
/// the cause come from the typed error, never from its message text.
#[test]
fn a_known_library_that_hits_a_ceiling_is_reported_incomplete() {
let temp = tempfile::tempdir().unwrap();
let root = temp.path();
let app = root.join("app");
std::fs::create_dir_all(app.join("lib/arm64-v8a")).unwrap();
let so = app.join("lib/arm64-v8a/libil2cpp.so");
std::fs::write(&so, library_bytes(b"over-limit")).unwrap();
let mut cache = run_cache();
let scoped = loose_scopes(std::slice::from_ref(&so), &[]);
let mut restorer = LimitedRestorer;
let outcome = restore_loose_library_with(
&so,
&root.join("out.so"),
"libil2cpp.so",
&scoped[0].key,
false,
&mut cache,
&mut restorer,
)
.unwrap();
let EntryStatus::Failed(error) = &outcome.status else {
panic!("the ceiling must fail the restore: {:?}", outcome.status);
};
assert!(
crate::job::analysis_incomplete(error),
"a LimitExceeded failure is infrastructure, not a rejected layout"
);
let report = crate::job::android_library_input(
&so,
crate::report::InputStatus::Error,
&root.join("out.so"),
std::time::Instant::now(),
);
assert_eq!(report.status, crate::report::InputStatus::Error);
}
+987 -434
View File
File diff suppressed because it is too large. Load diff
+204 -104
View File
@@ -12,9 +12,11 @@
//! only where a stage was measured (`None` otherwise); hashes are taken from
//! the bytes that were actually produced; a route is only marked selected if
//! a pipeline accepted it.
//! * Inspection never claims recovery. An [`Mode::Inspect`] run reports
//! recognition and the planned routes, never `selected`, `recovered`, or a
//! static-validation verdict.
//! * Research inspection retains no output files. An [`Mode::Inspect`] run may
//! perform full static recovery to discover parameters, but selected routes,
//! recovered identities and validation verdicts come only from actual work.
//! Parsed input facts, bounded probe candidates and recovery traces stay
//! separate so local plausibility is never mistaken for a recovery verdict.
//!
//! A container (`.apk`/`.apks`/`.xapk`) is reported as one input with
//! [`Role::Container`]: its manifest inventory is listed separately from the
@@ -32,6 +34,8 @@ use senbei_engine::{
RecoveryStatus, ValidationStatus,
};
mod text;
/// Version of the serialized [`Report`] schema.
pub const REPORT_FORMAT_VERSION: u32 = 1;
@@ -39,7 +43,7 @@ pub const REPORT_FORMAT_VERSION: u32 = 1;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum Mode {
/// Detection only: no recovery, no output, no log.
/// Research analysis, including static recovery; retain no output or log.
Inspect,
/// Restore and write outputs.
Unpack,
@@ -65,8 +69,8 @@ pub enum InputStatus {
Ok,
/// Produced output that fails the static integrity check.
Suspect,
/// Inspection recognized a protected target. Nothing was recovered, so
/// this is never counted as an output.
/// Inspection recognized a protected target. Its profile separately records
/// whether static recovery succeeded; no output file is retained.
Recognized,
/// Not a target, already handled, or a layout this build does not know.
Skipped,
@@ -208,6 +212,37 @@ pub struct CompanionReport {
pub state: CompanionState,
pub path: Option<String>,
pub detail: Option<String>,
/// Identity of the physical companion, distinct from the spliced view.
pub source: Option<Digest>,
}
/// Which bytes the research report's input offsets address.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum ResearchInputView {
Original,
/// The loader's header page followed by its matching external payload.
SplicedCompanion,
}
/// Structural observations and actual static-recovery discoveries for a PE.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct WindowsResearchReport {
pub input_view: ResearchInputView,
pub input: senbei_engine::windows::WindowsInspection,
/// The post-overlay image, inspected before its bytes were discarded.
pub restored: Option<senbei_engine::windows::WindowsInspection>,
pub trace: senbei_engine::windows::ResearchTrace,
}
/// Existing Android engine reports captured from the actual static pipeline.
///
/// The nested schemas belong to the extraction/restoration engines. Temporary
/// output locations are replaced with logical labels by the I/O adapter.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct AndroidResearchReport {
pub extraction: serde_json::Value,
pub restoration: Option<serde_json::Value>,
}
/// One manifest parsed from a container.
@@ -271,11 +306,14 @@ pub struct EntryReport {
/// Source label, e.g. `base.apk::lib/arm64-v8a/libil2cpp.so`.
pub name: String,
pub status: EntryStatus,
pub analysis_incomplete: bool,
pub kind: Option<EntryKind>,
/// Route selected for this entry, when one was.
pub layout: Option<LayoutKind>,
pub metadata_version: Option<u32>,
pub remapped: Option<usize>,
pub android_research: Option<AndroidResearchReport>,
pub metadata_research: Option<serde_json::Value>,
/// Libraries whose decoded module was paired with this metadata entry.
pub provenance: Vec<String>,
/// Where the restored bytes were written (absent in dry-run/inspect).
@@ -289,10 +327,13 @@ impl EntryReport {
Self {
name: name.into(),
status,
analysis_incomplete: false,
kind: None,
layout: None,
metadata_version: None,
remapped: None,
android_research: None,
metadata_research: None,
provenance: Vec::new(),
output: None,
warnings: Vec::new(),
@@ -307,6 +348,14 @@ pub struct InputReport {
pub path: String,
pub role: Role,
pub status: InputStatus,
/// I/O, resource limits or infrastructure prevented the requested analysis.
/// A rejected recovery candidate alone does not set this flag.
pub analysis_incomplete: bool,
/// Identity of the physical input, never of a synthetic spliced view.
pub source: Option<Digest>,
pub research: Option<WindowsResearchReport>,
pub android_research: Option<AndroidResearchReport>,
pub metadata_research: Option<serde_json::Value>,
/// Engine profile: recognition evidence, candidate routes, and — only when
/// recovery actually ran — the selected route and static-validation verdict.
pub profile: Option<ProtectionProfile>,
@@ -335,6 +384,11 @@ impl InputReport {
path: path.display().to_string(),
role,
status: InputStatus::Skipped,
analysis_incomplete: false,
source: None,
research: None,
android_research: None,
metadata_research: None,
profile: None,
companion: None,
container: None,
@@ -367,8 +421,8 @@ pub struct SummaryReport {
pub inputs: usize,
/// Inputs that produced output.
pub recovered: usize,
/// Inputs whose protection was recognized. Only an `inspect` run fills
/// this: it is detection evidence, never a recovery claim.
/// Inputs whose protection was recognized during research inspection.
/// This count is independent of whether their static recovery succeeded.
pub recognized: usize,
/// Inputs that were not targets or were left untouched.
pub skipped: usize,
@@ -431,8 +485,17 @@ impl Report {
/// Human-readable rendering, one block per input, for non-`--json` runs.
pub fn render_text(&self) -> String {
let mut text = String::new();
if let Some(scan) = self.scan {
text.push_str(&format!(
"scan: {} probed non-targets · {} walk errors · {} probe errors\n",
scan.non_target_skipped, scan.walk_errors, scan.probe_errors
));
if scan.walk_errors > 0 || scan.probe_errors > 0 {
text.push_str("warning: analysis is incomplete; some directory entries or selected files could not be examined\n");
}
}
for input in &self.inputs {
text.push_str(&render_input(input));
text.push_str(&text::render_input(input));
}
if !self.errors.is_empty() {
for error in &self.errors {
@@ -443,93 +506,6 @@ impl Report {
}
}
fn render_input(input: &InputReport) -> String {
let mut text = format!("{}\n", input.path);
text.push_str(&format!(" role: {:?}\n", input.role));
if let Some(profile) = &input.profile {
text.push_str(&format!(" recognition: {:?}\n", profile.recognition));
if !profile.evidence.is_empty() {
text.push_str(&format!(" evidence: {:?}\n", profile.evidence));
}
for candidate in &profile.candidates {
let mut line = format!(
" route {}: {:?}",
layout_name(candidate.layout),
candidate.outcome
);
if !candidate.errors.is_empty() {
line.push_str(&format!(" ({})", candidate.errors.join("; ")));
}
text.push_str(&line);
text.push('\n');
}
if let Some(selected) = profile.selected {
text.push_str(&format!(" selected: {:?}\n", layout_name(selected)));
}
text.push_str(&format!(" recovery: {:?}\n", profile.recovery));
text.push_str(&format!(
" static validation: {:?}\n",
profile.static_validation
));
}
if let Some(metadata) = &input.metadata {
text.push_str(&format!(
" metadata: version {} ({:?}, capabilities {:?})\n",
metadata.raw_version, metadata.layout, metadata.capabilities
));
}
if let Some(container) = &input.container {
text.push_str(&format!(
" container: {} · {} entries · {} manifests\n",
container.kind,
container.entry_count,
container.manifests.len()
));
for manifest in &container.manifests {
text.push_str(&format!(
" manifest {} → {} {}\n",
manifest.source,
manifest.package.as_deref().unwrap_or("<unnamed>"),
manifest.version.as_deref().unwrap_or("")
));
}
for entry in &container.candidate_entries {
text.push_str(&format!(" candidate {entry}\n"));
}
}
for entry in &input.entries {
text.push_str(&format!(
" entry {}: {:?}{}\n",
entry.name,
entry.status,
entry
.output
.as_ref()
.map(|output| format!(" -> {}", output.path))
.unwrap_or_default()
));
}
if let Some(recovered) = &input.recovered {
text.push_str(&format!(
" recovered: {} bytes · {}\n",
recovered.size, recovered.sha256
));
}
text.push_str(&format!(" status: {:?}\n", input.status));
text
}
fn layout_name(layout: LayoutKind) -> &'static str {
match layout {
LayoutKind::Dll => "dll",
LayoutKind::ExeStyle => "exe_style",
LayoutKind::AndroidStaged => "android_staged",
LayoutKind::MetadataStructural => "metadata_structural",
LayoutKind::MetadataSeeded => "metadata_seeded",
LayoutKind::MetadataMethodIndices => "metadata_method_indices",
}
}
/// Accumulates inputs during one invocation.
pub struct Collector {
mode: Mode,
@@ -556,16 +532,37 @@ impl Collector {
self.mode
}
/// Record the folder scan tallies for a folder run.
/// Record scan tallies and keep unexamined inputs visible to exit policies.
pub fn set_scan(&mut self, scan: ScanReport) {
let previous = self
.scan
.map_or(0, |scan| scan.walk_errors.saturating_add(scan.probe_errors));
let failed = scan.walk_errors.saturating_add(scan.probe_errors);
self.summary.errors = self
.summary
.errors
.saturating_sub(previous)
.saturating_add(failed);
self.scan = Some(scan);
}
/// Record one finished input and fold its status into the summary.
pub fn push(&mut self, mut input: InputReport) {
if self.mode == Mode::DryRun {
// Nothing produced by a dry run is retained, so no output file may
// be reported. The attempt itself keeps its real outcome.
if self.mode == Mode::Inspect
&& (input.analysis_incomplete
|| input.entries.iter().any(|entry| entry.analysis_incomplete))
{
input.analysis_incomplete = true;
input.status = InputStatus::Error;
}
if matches!(self.mode, Mode::DryRun | Mode::Inspect) {
// Research inspection and dry runs keep their actual recovery
// outcomes, but never advertise temporary artifacts as outputs.
let discarded = if self.mode == Mode::Inspect {
"research inspection: no output file was retained"
} else {
"dry run: the produced output was discarded"
};
if !input.outputs.is_empty() {
// The produced byte count is a real result of the attempt even
// though the file itself is not kept. A hash is only carried
@@ -582,8 +579,7 @@ impl Collector {
for stage in &mut input.stages {
if stage.stage == Stage::OutputWrite {
stage.status = StageStatus::Skipped;
stage.detail =
Some("dry run: the produced output was discarded".to_owned());
stage.detail = Some(discarded.to_owned());
}
}
if !input
@@ -593,7 +589,7 @@ impl Collector {
{
input.stages.push(
StageReport::new(Stage::OutputWrite, StageStatus::Skipped)
.detail("dry run: the produced output was discarded"),
.detail(discarded),
);
}
input.outputs.clear();
@@ -609,7 +605,22 @@ impl Collector {
self.summary.recovered += 1;
self.summary.suspect += 1;
}
InputStatus::Recognized => self.summary.recognized += 1,
InputStatus::Recognized => {
self.summary.recognized += 1;
if self.mode == Mode::Inspect
&& let Some(profile) = &input.profile
{
if profile.recovery == RecoveryStatus::Succeeded {
self.summary.recovered += 1;
}
if matches!(
profile.static_validation,
ValidationStatus::Warnings | ValidationStatus::Failed
) {
self.summary.suspect += 1;
}
}
}
InputStatus::Skipped => self.summary.skipped += 1,
InputStatus::Error => self.summary.errors += 1,
}
@@ -815,6 +826,95 @@ mod tests {
assert_eq!(report.summary.recovered, 0);
}
#[test]
fn research_counts_actual_recovery_and_suspect_without_retaining_output_paths() {
let mut input = sample_input(InputStatus::Recognized);
let mut profile =
ProtectionProfile::new(senbei_engine::ObservedTarget::windows(None, None));
profile.recognition = RecognitionStatus::Recognized;
profile.recovery = RecoveryStatus::Succeeded;
profile.static_validation = ValidationStatus::Warnings;
input.profile = Some(profile);
input.outputs.push(OutputFile::from_bytes(
Path::new("temporary/image.exe"),
b"bytes",
));
let mut collector = Collector::new(Mode::Inspect);
collector.push(input);
let report = collector.finish();
assert_eq!(report.summary.recognized, 1);
assert_eq!(report.summary.recovered, 1);
assert_eq!(report.summary.suspect, 1);
assert_eq!(report.summary.errors, 0);
assert!(report.inputs[0].outputs.is_empty());
assert!(!report.to_json().contains("temporary/image.exe"));
assert!(
report.inputs[0]
.stages
.iter()
.any(|stage| stage.stage == Stage::OutputWrite
&& stage.status == StageStatus::Skipped)
);
}
#[test]
fn research_recovery_failure_is_a_finding_not_a_read_failure() {
let mut input = sample_input(InputStatus::Recognized);
let mut profile =
ProtectionProfile::new(senbei_engine::ObservedTarget::windows(None, None));
profile.recognition = RecognitionStatus::Recognized;
profile.recovery = RecoveryStatus::Failed;
profile.push_error("no candidate validated");
input.profile = Some(profile);
let mut collector = Collector::new(Mode::Inspect);
collector.push(input);
let report = collector.finish();
assert_eq!(report.summary.recognized, 1);
assert_eq!(report.summary.recovered, 0);
assert_eq!(report.summary.errors, 0);
assert!(report.render_text().contains("no candidate validated"));
}
#[test]
fn incomplete_research_cannot_be_hidden_by_a_recognized_status() {
let mut input = sample_input(InputStatus::Recognized);
let mut entry = EntryReport::new("package::library.so", EntryStatus::Error);
entry.analysis_incomplete = true;
entry
.errors
.push("resource ceiling prevented restoration".to_owned());
input.entries.push(entry);
let mut collector = Collector::new(Mode::Inspect);
collector.push(input);
let report = collector.finish();
assert_eq!(report.summary.errors, 1);
assert_eq!(report.inputs[0].status, InputStatus::Error);
assert!(report.inputs[0].analysis_incomplete);
assert!(report.render_text().contains("analysis incomplete"));
}
#[test]
fn scan_failures_fail_report_only_modes_and_do_not_erase_input_errors() {
for mode in [Mode::Inspect, Mode::DryRun] {
let mut collector = Collector::new(mode);
collector.push(sample_input(InputStatus::Error));
collector.set_scan(ScanReport {
walk_errors: 2,
probe_errors: 3,
non_target_skipped: 4,
});
assert_eq!(collector.summary.errors, 6);
collector.set_scan(ScanReport {
walk_errors: 1,
..ScanReport::default()
});
let report = collector.finish();
assert_eq!(report.summary.errors, 2);
assert!(report.render_text().contains("analysis is incomplete"));
assert!(report.render_text().contains("1 walk errors"));
}
}
#[test]
fn digest_matches_a_known_sha256() {
let digest = Digest::of(b"abc");
+784
View File
@@ -0,0 +1,784 @@
//! Human-readable research reports. JSON retains the same underlying evidence.
use std::fmt::Write;
use senbei_engine::windows::{ResearchTrace, TraceValue, WindowsInspection};
use serde::Serialize;
use serde_json::Value;
use super::{AndroidResearchReport, InputReport};
fn label(value: &impl Serialize) -> String {
match serde_json::to_value(value) {
Ok(Value::String(text)) => text.replace('_', " "),
Ok(value) => value.to_string(),
Err(_) => "unavailable".to_owned(),
}
}
fn hex<T: Into<u64>>(value: Option<T>) -> String {
value
.map(|value| format!("0x{:X}", value.into()))
.unwrap_or_else(|| "unavailable".to_owned())
}
fn diagnostic(text: &mut String, indent: &str, kind: &str, message: &str) {
for line in message.lines() {
let _ = writeln!(text, "{indent}{kind}: {line}");
}
}
pub(super) fn render_input(input: &InputReport) -> String {
let mut text = format!("{}\n", input.path);
if input.analysis_incomplete {
let _ = writeln!(
text,
" analysis incomplete: I/O, resource limits or infrastructure prevented the requested work"
);
}
if let Some(source) = &input.source {
let _ = writeln!(
text,
" source: {} bytes (0x{:X})",
source.size, source.size
);
let _ = writeln!(text, " SHA-256: {}", source.sha256);
}
if let Some(profile) = &input.profile {
let target = &profile.observed;
let _ = writeln!(
text,
" target: {} · {} · {}",
label(&target.platform),
target
.format
.as_ref()
.map(label)
.unwrap_or_else(|| "format unavailable".to_owned()),
target
.kind
.as_ref()
.map(label)
.unwrap_or_else(|| "kind not applicable or unavailable".to_owned())
);
let _ = writeln!(
text,
" protection recognition: {}",
label(&profile.recognition)
);
if !profile.evidence.is_empty() {
let evidence = profile
.evidence
.iter()
.map(label)
.collect::<Vec<_>>()
.join(", ");
let _ = writeln!(text, " evidence: {evidence}");
}
for candidate in &profile.candidates {
let _ = writeln!(
text,
" route {}: {}",
label(&candidate.layout),
label(&candidate.outcome)
);
for message in &candidate.warnings {
diagnostic(&mut text, " ", "warning", message);
}
for message in &candidate.errors {
diagnostic(&mut text, " ", "reason", message);
}
}
if let Some(selected) = profile.selected {
let _ = writeln!(text, " selected route: {}", label(&selected));
}
let _ = writeln!(text, " static recovery: {}", label(&profile.recovery));
let _ = writeln!(
text,
" output static validation: {}",
label(&profile.static_validation)
);
}
if let Some(companion) = &input.companion {
let _ = writeln!(
text,
" companion: {}{}",
label(&companion.state),
companion
.path
.as_ref()
.map(|path| format!(" · {path}"))
.unwrap_or_default()
);
if let Some(source) = &companion.source {
let _ = writeln!(
text,
" {} bytes · SHA-256 {}",
source.size, source.sha256
);
}
if let Some(detail) = &companion.detail {
diagnostic(&mut text, " ", "detail", detail);
}
}
if let Some(research) = &input.research {
let _ = writeln!(
text,
" analysis input view: {}",
label(&research.input_view)
);
if research.input_view == super::ResearchInputView::SplicedCompanion {
let _ = writeln!(
text,
" file offsets below 0x1000 address the stub; offsets at/above 0x1000 address companion offset (file offset - 0x1000)"
);
}
render_windows(&mut text, "protected input", &research.input);
render_trace(&mut text, &research.trace);
if let Some(restored) = &research.restored {
if let (Some(before), Some(after)) = (&research.input.pe, &restored.pe) {
let _ = writeln!(
text,
" protected → recovered: entry RVA {} → {} · SizeOfImage {} → {} · sections {} → {}",
hex(before.entry_point_rva),
hex(after.entry_point_rva),
hex(before.size_of_image),
hex(after.size_of_image),
before.sections.len(),
after.sections.len()
);
let _ = writeln!(
text,
" DLL characteristics {} → {}",
hex(before.dll_characteristics),
hex(after.dll_characteristics)
);
}
render_windows(&mut text, "recovered image (not retained)", restored);
}
}
if let Some(metadata) = &input.metadata {
let _ = writeln!(
text,
" IL2CPP metadata version: {} · layout definition {}",
metadata.raw_version,
label(&metadata.layout)
);
let _ = writeln!(
text,
" seeded method tokens: {}",
metadata.capabilities.seeded_method_tokens
);
let _ = writeln!(
text,
" structural method tokens: {}",
metadata.capabilities.structural_method_tokens
);
let _ = writeln!(
text,
" method-index restoration: {} · application context required: {}",
metadata.capabilities.method_index_restore,
metadata.capabilities.method_index_requires_context
);
}
if let Some(container) = &input.container {
let _ = writeln!(
text,
" container: {} · {} entries · {} manifests",
container.kind,
container.entry_count,
container.manifests.len()
);
for manifest in &container.manifests {
let _ = writeln!(
text,
" manifest {} → {} {}",
manifest.source,
manifest.package.as_deref().unwrap_or("<unnamed>"),
manifest.version.as_deref().unwrap_or("")
);
}
for entry in &container.candidate_entries {
let _ = writeln!(text, " candidate: {entry}");
}
}
if let Some(research) = &input.android_research {
render_android(&mut text, " ", research);
}
if let Some(research) = &input.metadata_research {
let _ = writeln!(text, " metadata transform evidence:");
render_tree(&mut text, " ", research);
}
for entry in &input.entries {
let _ = writeln!(
text,
" entry {}: {}{}",
entry.name,
label(&entry.status),
entry
.output
.as_ref()
.map(|output| format!(" → {}", output.path))
.unwrap_or_default()
);
if entry.analysis_incomplete {
let _ = writeln!(
text,
" analysis incomplete: requested entry analysis could not finish"
);
}
if let Some(layout) = entry.layout {
let _ = writeln!(text, " route: {}", label(&layout));
}
if let Some(version) = entry.metadata_version {
let _ = writeln!(text, " metadata version: {version}");
}
if let Some(remapped) = entry.remapped {
let _ = writeln!(text, " remapped method fields: {remapped}");
}
for source in &entry.provenance {
let _ = writeln!(text, " module context source: {source}");
}
for message in &entry.warnings {
diagnostic(&mut text, " ", "warning", message);
}
for message in &entry.errors {
diagnostic(&mut text, " ", "error", message);
}
if let Some(research) = &entry.android_research {
render_android(&mut text, " ", research);
}
if let Some(research) = &entry.metadata_research {
let _ = writeln!(text, " metadata transform evidence:");
render_tree(&mut text, " ", research);
}
}
for source in &input.provenance {
let _ = writeln!(text, " module context source: {source}");
}
for stage in &input.stages {
let _ = writeln!(
text,
" stage {}: {}{}",
label(&stage.stage),
label(&stage.status),
stage
.duration_ms
.map(|elapsed| format!(" · {elapsed} ms"))
.unwrap_or_default()
);
if let Some(detail) = &stage.detail {
diagnostic(&mut text, " ", "detail", detail);
}
}
let mut seen = std::collections::BTreeSet::new();
for (kind, messages) in [("warning", &input.warnings), ("error", &input.errors)] {
for message in messages {
if seen.insert((kind, message.as_str())) {
diagnostic(&mut text, " ", kind, message);
}
}
}
if let Some(profile) = &input.profile {
for (kind, messages) in [("warning", &profile.warnings), ("error", &profile.errors)] {
for message in messages {
if seen.insert((kind, message.as_str())) {
diagnostic(&mut text, " ", kind, message);
}
}
}
}
if let Some(recovered) = &input.recovered {
let _ = writeln!(
text,
" recovered: {} bytes · SHA-256 {}",
recovered.size, recovered.sha256
);
}
let _ = writeln!(
text,
" inspection status: {} · {} ms",
label(&input.status),
input.duration_ms
);
text
}
fn render_windows(text: &mut String, heading: &str, inspection: &WindowsInspection) {
let _ = writeln!(text, " {heading}: {} bytes", inspection.input_len);
if let Some(pe) = &inspection.pe {
let machine = match pe.machine {
Some(0x14c) => "x86",
Some(0x8664) => "x86-64",
Some(0xaa64) => "ARM64",
_ => "unknown machine",
};
let _ = writeln!(
text,
" PE header: {} · {machine} ({})",
hex(pe.pe_offset),
hex(pe.machine)
);
let _ = writeln!(
text,
" PE type: {} · {}",
pe.format
.as_ref()
.map(label)
.unwrap_or_else(|| "unavailable".to_owned()),
pe.kind
.as_ref()
.map(label)
.unwrap_or_else(|| "unavailable".to_owned())
);
let _ = writeln!(
text,
" image base: {} · SizeOfImage: {} · SizeOfHeaders: {}",
hex(pe.image_base),
hex(pe.size_of_image),
hex(pe.size_of_headers)
);
let _ = writeln!(
text,
" entry point: RVA {} · file offset {} · file-backed: {}",
hex(pe.entry_point_rva),
hex(pe.entry_point_file_offset),
pe.entry_point_available
.map(|value| value.to_string())
.unwrap_or_else(|| "unavailable".to_owned())
);
let _ = writeln!(
text,
" alignments: section {} · file {}",
hex(pe.section_alignment),
hex(pe.file_alignment)
);
let _ = writeln!(
text,
" declared flags: COFF {} · DLL {} (runtime behavior not tested)",
hex(pe.characteristics),
hex(pe.dll_characteristics)
);
for flag in &pe.named_flags {
let _ = writeln!(
text,
" {}: {} (0x{:04X})",
label(&flag.field),
flag.name,
flag.bit
);
}
let _ = writeln!(text, " sections ({}):", pe.sections.len());
let _ = writeln!(
text,
" # name RVA virtual size raw offset raw size R W X"
);
for section in &pe.sections {
let p = &section.permissions;
let name = section.name.escape_debug().to_string();
let _ = writeln!(
text,
" {:>2} {:<10} 0x{:08X} 0x{:08X} 0x{:08X} 0x{:08X} {} {} {}",
section.index,
name,
section.virtual_address,
section.virtual_size,
section.raw_offset,
section.raw_size,
if p.read { 'R' } else { '-' },
if p.write { 'W' } else { '-' },
if p.execute { 'X' } else { '-' }
);
let _ = writeln!(
text,
" characteristics: 0x{:08X} · raw backing: {} · raw range in file: {}",
section.characteristics,
label(&section.backing),
section.raw_in_bounds
);
if section.virtual_size > section.raw_size {
let _ = writeln!(
text,
" declared virtual tail beyond raw backing: 0x{:X} bytes",
section.virtual_size - section.raw_size
);
}
for anomaly in &section.anomalies {
let _ = writeln!(text, " observation: {}", label(anomaly));
}
}
let _ = writeln!(text, " data directories ({}):", pe.directories.len());
for directory in &pe.directories {
let _ = writeln!(
text,
" {:>2} {:<18} {} 0x{:08X} · size 0x{:X} · file {} · {}",
directory.index,
directory.name,
label(&directory.address_space),
directory.address,
directory.size,
hex(directory.file_offset),
label(&directory.mapping)
);
if let Some(note) = directory.note {
let _ = writeln!(text, " {note}");
}
}
if pe.unsectioned.is_empty() {
let _ = writeln!(text, " unsectioned file ranges: none");
} else {
let _ = writeln!(
text,
" unsectioned file ranges (not automatically protector payloads):"
);
for region in &pe.unsectioned {
let _ = writeln!(
text,
" {}: file 0x{:X} · length 0x{:X}",
label(&region.kind),
region.offset,
region.length
);
}
}
match &pe.overlay {
Some(region) => {
let _ = writeln!(
text,
" trailing overlay: file 0x{:X} · length 0x{:X}",
region.offset, region.length
);
}
None => {
let _ = writeln!(text, " trailing overlay: none");
}
}
if let Some(issue) = &pe.parse_issue {
diagnostic(text, " ", "parse issue", issue);
}
}
if let Some(protection) = &inspection.protection {
let _ = writeln!(
text,
" header-table decode: magic {} · supported KONN: {}",
hex(protection.magic),
protection.magic_recognized
);
for word in &protection.header_words {
let _ = writeln!(
text,
" info[{}] @ file 0x{:X}: raw 0x{:08X} → decoded 0x{:08X}{}",
word.index,
word.source_file_offset,
word.raw_word,
word.decoded_word,
word.semantic
.as_ref()
.map(|semantic| format!(" · {}", label(semantic)))
.unwrap_or_default()
);
}
if let Some(payload) = &protection.payload {
let _ = writeln!(
text,
" {}: file 0x{:X} → working-image RVA 0x{:X}",
if protection.magic_recognized {
"declared payload"
} else {
"candidate payload interpretation (magic not recognized)"
},
payload.source_file_offset,
payload.destination_rva
);
let _ = writeln!(
text,
" prefix length 0x{:X} · total length 0x{:X}",
payload.prefix_length, payload.total_length
);
for check in &payload.checks {
let _ = writeln!(
text,
" {}: start 0x{:X} · length 0x{:X} · end 0x{:X} · limit 0x{:X} · in bounds {} · overflow {}",
check.name,
check.start,
check.length,
check.end,
check.limit,
check.in_bounds,
check.overflow
);
}
}
let probe = &protection.probe;
let _ = writeln!(
text,
" payload probe: {} · scratch requested 0x{:X} · constructed 0x{:X} · ceiling 0x{:X}",
label(&probe.status),
probe.requested_length,
probe.decoded_length,
probe.limit_bytes
);
let _ = writeln!(
text,
" prefix span 0x{:X} · raw-tail span 0x{:X} · actual prefix cipher bytes decoded 0x{:X}",
probe.prefix_bytes, probe.tail_bytes, inspection.work.prefix_bytes_decoded
);
if let Some(reason) = probe.reason {
let _ = writeln!(text, " {reason}");
}
if !probe.first_words.is_empty() {
let words = probe
.first_words
.iter()
.map(|word| format!("0x{word:08X}"))
.collect::<Vec<_>>()
.join(", ");
let _ = writeln!(text, " decoded prefix initial words: {words}");
}
let discovery = &protection.discovery;
let _ = writeln!(
text,
" shell discovery: {} · {} positions scanned · {} candidates reported",
label(&discovery.status),
discovery.positions_scanned,
discovery.candidates.len()
);
if let Some(reason) = discovery.reason {
let _ = writeln!(text, " {reason}");
}
for candidate in &discovery.candidates {
let _ = writeln!(
text,
" {}: {} · decoded offset {} · image RVA {} · source file {}",
label(&candidate.kind),
label(&candidate.status),
hex(candidate.payload_offset),
hex(candidate.image_rva),
hex(candidate.source_file_offset)
);
let _ = writeln!(text, " {}", candidate.reason);
for field in &candidate.fields {
let _ = writeln!(
text,
" {} = 0x{:X}{}",
field.name,
field.value,
field
.space
.as_ref()
.map(|space| format!(" ({})", label(space)))
.unwrap_or_default()
);
}
}
}
for issue in &inspection.issues {
let _ = writeln!(
text,
" {} [{}]: {}",
label(&issue.severity),
issue.area,
issue.message
);
}
if inspection.work.budget_limited {
let _ = writeln!(
text,
" inspection work was budget-limited; omitted probes are not negative evidence"
);
}
}
fn render_trace(text: &mut String, trace: &ResearchTrace) {
let _ = writeln!(
text,
" actual static-pipeline discoveries ({} events):",
trace.events.len()
);
let mut previous = String::new();
for event in &trace.events {
let stage = label(&event.stage);
if previous != stage {
let _ = writeln!(text, " {stage}:");
previous = stage;
}
let value = match &event.value {
TraceValue::U32(value) => format!("0x{value:08X} ({value})"),
TraceValue::U64(value) => format!("0x{value:X} ({value})"),
TraceValue::Bool(value) => value.to_string(),
TraceValue::Text(value) => value.clone(),
TraceValue::U32s(values) => values
.iter()
.map(|value| format!("0x{value:08X}"))
.collect::<Vec<_>>()
.join(", "),
TraceValue::Range { start, length } => {
format!("start 0x{start:X} · length 0x{length:X}")
}
};
let provenance = event
.address
.as_ref()
.map(|address| format!(" @ {} 0x{:X}", label(&address.space), address.offset))
.unwrap_or_default();
let _ = writeln!(text, " {}: {value}{provenance}", event.name);
if let Some(note) = event.note {
let _ = writeln!(text, " {note}");
}
}
if trace.truncated {
let _ = writeln!(
text,
" trace truncated at {} events; {} events omitted",
trace.limit, trace.dropped
);
}
}
fn render_android(text: &mut String, indent: &str, research: &AndroidResearchReport) {
let _ = writeln!(text, "{indent}Android extraction evidence:");
render_tree(text, &format!("{indent} "), &research.extraction);
if let Some(restoration) = &research.restoration {
let _ = writeln!(text, "{indent}Android restoration evidence:");
render_tree(text, &format!("{indent} "), restoration);
}
}
fn render_tree(text: &mut String, indent: &str, value: &Value) {
match value {
Value::Object(fields) => {
for (name, value) in fields {
match value {
Value::Array(_) | Value::Object(_) => {
let _ = writeln!(text, "{indent}{name}:");
render_tree(text, &format!("{indent} "), value);
}
Value::Number(number) => {
let numeric = number
.as_u64()
.map(|value| format!("{value} (0x{value:X})"))
.unwrap_or_else(|| number.to_string());
let _ = writeln!(text, "{indent}{name}: {numeric}");
}
Value::String(value) => {
let _ = writeln!(text, "{indent}{name}: {}", value.escape_debug());
}
_ => {
let _ = writeln!(text, "{indent}{name}: {value}");
}
}
}
}
Value::Array(values) => {
for (index, value) in values.iter().enumerate() {
let _ = writeln!(text, "{indent}[{index}]");
render_tree(text, &format!("{indent} "), value);
}
}
_ => {
let _ = writeln!(text, "{indent}{value}");
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::report::{
CompanionReport, CompanionState, Digest, Role, Stage, StageReport, StageStatus,
};
use senbei_engine::{Kind, ObservedTarget, ProtectionProfile, TargetFormat};
use std::path::Path;
#[test]
fn text_keeps_target_source_context_and_diagnostics() {
let mut input = InputReport::new(Path::new("module.exe"), Role::Content);
input.source = Some(Digest::of(b"source bytes"));
input.profile = Some(ProtectionProfile::new(ObservedTarget::windows(
Some(TargetFormat::Pe32),
Some(Kind::NativeExe),
)));
input.companion = Some(CompanionReport {
state: CompanionState::Absent,
path: None,
detail: None,
source: None,
});
input
.provenance
.push("application-scoped module 0x0C".to_owned());
input.warning("partial discovery");
input.error("candidate did not validate");
input.stages.push(
StageReport::new(Stage::Recovery, StageStatus::Failed)
.detail("parameters were unavailable"),
);
let text = render_input(&input);
for fact in [
"SHA-256:",
"pe32",
"native exe",
"companion: absent",
"application-scoped module",
"warning: partial discovery",
"error: candidate did not validate",
"parameters were unavailable",
] {
assert!(text.contains(fact), "missing {fact}: {text}");
}
}
#[test]
fn trace_values_have_hex_provenance_and_explicit_truncation() {
use senbei_engine::windows::{AddressSpace, ResearchEvent, ResearchStage, TraceAddress};
let trace = ResearchTrace {
events: vec![ResearchEvent {
stage: ResearchStage::Payload,
name: "header_seed",
value: TraceValue::U32(0x1234),
address: Some(TraceAddress {
space: AddressSpace::FileOffset,
offset: 0x1000,
}),
note: Some("observed during static recovery"),
}],
truncated: true,
dropped: 2,
limit: 1,
};
let mut text = String::new();
render_trace(&mut text, &trace);
for fact in [
"0x00001234",
"file offset 0x1000",
"observed during static recovery",
"trace truncated at 1 events; 2 events omitted",
] {
assert!(text.contains(fact), "missing {fact}: {text}");
}
}
#[test]
fn nested_android_and_metadata_evidence_is_not_hidden() {
let mut input = InputReport::new(Path::new("library.so"), Role::Content);
input.android_research = Some(AndroidResearchReport {
extraction: serde_json::json!({"decoder": {"header_seed": 0x1234}, "module_registry": [{"command_id": 0x9b}]}),
restoration: Some(
serde_json::json!({"validation": {"diagnostics": ["mapping warning"]}}),
),
});
input.metadata_research =
Some(serde_json::json!({"tried_seeds": [0x5678], "route": "seeded"}));
let text = render_input(&input);
for fact in [
"header_seed: 4660 (0x1234)",
"module_registry:",
"command_id: 155 (0x9B)",
"mapping warning",
"tried_seeds:",
"route: seeded",
] {
assert!(text.contains(fact), "missing {fact}: {text}");
}
}
}
+88 -34
View File
@@ -278,13 +278,13 @@ pub(super) mod tests {
}
}
/// Inspection must describe a companion-declaring stub, not reproduce the
/// recovery entry point's refusal.
/// Inspection describes a companion-declaring stub *and* what happened when
/// its recovery was attempted.
///
/// [`stub`] is a generated PE32+ loader whose entry record declares the
/// `._` suffix, so `read_unpacker_input` errors on it when the payload is
/// missing or does not pair. Inspection is detection only and must keep
/// the stub's recognition while reporting the pairing as inventory.
/// `._` suffix. The recovery entry point refuses it when the payload is
/// missing or does not pair; inspection runs that same attempt and reports
/// it as a finding about this input, never as a failure of the inspection.
fn inspect_report(path: &std::path::Path) -> serde_json::Value {
let report = crate::job::inspect_path(
path,
@@ -295,35 +295,23 @@ pub(super) mod tests {
serde_json::from_str(&report.to_json()).expect("valid report")
}
fn assert_no_recovery_claim(input: &serde_json::Value) {
/// Nothing was produced and no route was accepted, whatever the attempt did.
fn assert_no_recovered_output(input: &serde_json::Value) {
assert_eq!(input["status"], "recognized", "the stub is recognized");
let profile = &input["profile"];
assert_eq!(profile["recognition"], "recognized");
assert_eq!(input["profile"]["recognition"], "recognized");
assert!(
profile["selected"].is_null(),
"inspection selects no route: {profile}"
input["profile"]["selected"].is_null(),
"no route was accepted: {input}"
);
assert_eq!(profile["recovery"], "not_attempted");
assert_eq!(profile["static_validation"], "not_run");
assert!(
input["outputs"].as_array().unwrap().is_empty(),
"inspection writes nothing"
);
assert!(input["recovered"].is_null());
for candidate in profile["candidates"].as_array().unwrap() {
assert_eq!(
candidate["outcome"], "not_attempted",
"inspection runs no route: {candidate}"
);
}
assert!(
input["errors"].as_array().unwrap().is_empty(),
"a companion relationship is inventory, not an error: {input}"
);
}
#[test]
fn inspect_of_a_companion_stub_without_its_payload_stays_detection() {
fn inspect_of_a_companion_stub_without_its_payload_reports_the_attempt() {
let dir = tempfile::tempdir().unwrap();
let input = dir.path().join("module.exe");
std::fs::write(&input, stub()).unwrap();
@@ -333,13 +321,29 @@ pub(super) mod tests {
let value = inspect_report(&input);
let reported = &value["inputs"][0];
assert_no_recovery_claim(reported);
assert_no_recovered_output(reported);
assert_eq!(reported["companion"]["state"], "absent");
assert!(reported["companion"]["path"].is_null());
assert_eq!(
reported["profile"]["observed"]["external_companion"], false,
"nothing was spliced, so no external-companion claim"
);
// The refused attempt is reported, not hidden: recovery is blocked and
// the reason travels with it.
assert_eq!(reported["profile"]["recovery"], "blocked");
assert!(
!reported["profile"]["errors"].as_array().unwrap().is_empty(),
"the refusal reason must be in the profile: {reported}"
);
// Recognition survives: a missing payload describes this input, it does
// not unmake the stub.
assert_eq!(reported["profile"]["recognition"], "recognized");
assert!(
reported["research"].is_object(),
"research inspection reports the input structure: {reported}"
);
assert_eq!(reported["research"]["input_view"], "original");
assert_eq!(value["summary"]["errors"], 0);
}
#[test]
@@ -353,11 +357,16 @@ pub(super) mod tests {
let value = inspect_report(&input);
let reported = &value["inputs"][0];
assert_no_recovery_claim(reported);
assert_no_recovered_output(reported);
assert_eq!(reported["companion"]["state"], "unmatched");
assert!(reported["companion"]["path"].is_string());
assert!(reported["companion"]["detail"].is_string());
assert_eq!(reported["profile"]["observed"]["external_companion"], false);
// The unreadable-as-a-payload sibling is still identified on disk.
assert!(
reported["companion"]["source"].is_object(),
"the physical sibling has an identity: {reported}"
);
}
#[test]
@@ -375,14 +384,15 @@ pub(super) mod tests {
assert_eq!(reported["status"], "recognized");
assert_eq!(reported["companion"]["state"], "spliced");
assert_eq!(reported["profile"]["observed"]["external_companion"], true);
// A real pairing is evidence; recovery still did not run.
assert_eq!(reported["profile"]["recovery"], "not_attempted");
assert!(reported["profile"]["selected"].is_null());
assert_eq!(reported["profile"]["static_validation"], "not_run");
assert!(reported["companion"]["source"].is_object());
// The input offsets describe the spliced view recovery was given.
assert_eq!(reported["research"]["input_view"], "spliced_companion");
assert!(reported["outputs"].as_array().unwrap().is_empty());
assert!(reported["recovered"].is_null());
}
#[test]
fn folder_inspect_of_companion_stubs_stays_detection() {
fn folder_inspect_of_companion_stubs_reports_each_attempt() {
let dir = tempfile::tempdir().unwrap();
let missing = dir.path().join("missing.exe");
let unmatched = dir.path().join("unmatched.dll");
@@ -406,13 +416,13 @@ pub(super) mod tests {
assert!(states.contains(&"absent"), "{states:?}");
assert!(states.contains(&"unmatched"), "{states:?}");
for input in inputs {
assert_no_recovery_claim(input);
assert_no_recovered_output(input);
}
assert_eq!(value["summary"]["errors"], 0);
}
/// A genuine read error still fails the input, but never fabricates a
/// recovery attempt that inspection did not make.
/// A genuine read error fails the input, and never fabricates a recovery
/// attempt that inspection did not make.
#[test]
fn inspect_read_error_does_not_invent_a_failed_recovery() {
let dir = tempfile::tempdir().unwrap();
@@ -428,9 +438,53 @@ pub(super) mod tests {
assert_eq!(input["status"], "error");
assert!(!input["errors"].as_array().unwrap().is_empty());
let profile = &input["profile"];
assert_eq!(profile["recovery"], "not_attempted");
assert!(profile["selected"].is_null());
assert_eq!(profile["static_validation"], "not_run");
assert!(profile["candidates"].as_array().unwrap().is_empty());
assert_eq!(value["summary"]["errors"], 1);
}
}
#[cfg(test)]
mod research_tests {
use crate::job::{CompanionProbe, companion_report, observed_companion_state, probe_companion};
use crate::report::CompanionState;
/// An unreadable `._` sibling is reported as unreadable, never as a
/// mismatch, and no identity is invented for bytes that were never read.
#[test]
fn a_companion_that_cannot_be_read_is_not_a_mismatch() {
let temp = tempfile::tempdir().unwrap();
let input = temp.path().join("stub.exe");
std::fs::write(&input, b"MZ").unwrap();
// A directory where the payload should be: it exists but cannot be read.
std::fs::create_dir(temp.path().join("stub.exe._")).unwrap();
assert!(
matches!(probe_companion(&input), CompanionProbe::Unreadable(_)),
"an unreadable sibling has its own state"
);
let (state, source, reason) = observed_companion_state(&input, false);
assert_eq!(state, CompanionState::Unreadable);
assert!(source.is_none(), "no bytes were seen, so no identity");
let report = companion_report(&input, state, source, reason);
assert_eq!(report.state, CompanionState::Unreadable);
assert!(
report
.detail
.as_deref()
.is_some_and(|detail| detail.contains("could not be read")),
"{report:?}"
);
// Absent stays absent, and a readable but non-pairing sibling is a
// mismatch whose identity the probe already computed.
let plain = temp.path().join("plain.exe");
std::fs::write(&plain, b"MZ").unwrap();
assert!(matches!(probe_companion(&plain), CompanionProbe::Absent));
std::fs::write(temp.path().join("plain.exe._"), b"payload").unwrap();
let (state, source, _) = observed_companion_state(&plain, false);
assert_eq!(state, CompanionState::Unmatched);
assert!(source.is_some(), "the bytes read for pairing identify it");
}
}