mirror of
https://github.com/Momoko-Ayase/Senbei.git
synced 2026-11-25 02:52:47 +08:00
feat(cli): add inspect, dry-run and structured reports
This commit is contained in:
1 parent
767eae2a79
commit
7e6664d89e
12 files changed
+3622
-140
No files matched your search
@@ -490,6 +490,11 @@ pub(crate) struct RestoredLibrary {
|
||||
pub embedded_metadata: Option<Vec<u8>>,
|
||||
pub method_index_module: Option<Vec<u8>>,
|
||||
pub module_image: Option<String>,
|
||||
/// 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<super::ValidationDiagnostics>,
|
||||
}
|
||||
|
||||
/// Injectable library restore. Tests supply a fake so application-context
|
||||
|
||||
+260
-25
@@ -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<ContainerReport> {
|
||||
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<String>,
|
||||
}
|
||||
|
||||
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<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,
|
||||
@@ -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<Option<Vec<u8>>> {
|
||||
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<Vec<u8>>, Option<ValidationDiagnostics>)> {
|
||||
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<PathBuf>,
|
||||
/// Structural diagnostics from the restore that produced this output.
|
||||
/// `None` for duplicates, failures, and restorers without a report.
|
||||
pub validation: Option<ValidationDiagnostics>,
|
||||
}
|
||||
|
||||
pub(crate) fn restore_loose_library(
|
||||
@@ -273,6 +473,7 @@ fn restore_loose_library_with<R: context::LibraryRestorer>(
|
||||
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<R: context::LibraryRestorer>(
|
||||
return Ok(LooseLibraryOutcome {
|
||||
status: EntryStatus::Failed(error),
|
||||
embedded: None,
|
||||
validation: None,
|
||||
});
|
||||
}
|
||||
embedded = Some(meta_dest);
|
||||
@@ -314,11 +516,15 @@ fn restore_loose_library_with<R: context::LibraryRestorer>(
|
||||
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<String>,
|
||||
/// 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<u8>, 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<u8>, senbei_metadata::Report)> {
|
||||
) -> anyhow::Result<(Vec<u8>, 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<String>,
|
||||
/// Route the transform took, for metadata entries only.
|
||||
pub layout: Option<senbei_engine::LayoutKind>,
|
||||
/// Raw il2cpp metadata version, for metadata entries only.
|
||||
pub metadata_version: Option<u32>,
|
||||
/// Structural diagnostics from the restore of this entry. `None` for
|
||||
/// metadata entries, duplicates, and restorers without a report.
|
||||
pub validation: Option<ValidationDiagnostics>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
@@ -965,6 +1185,9 @@ fn restore_package_entry<R: Read + Seek, T: context::LibraryRestorer>(
|
||||
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<R: Read + Seek, T: context::LibraryRestorer>(
|
||||
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<R: Read + Seek, T: context::LibraryRestorer>(
|
||||
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<R: Read + Seek, T: context::LibraryRestorer>(
|
||||
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<R: Read + Seek, T: context::LibraryRestorer>(
|
||||
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(
|
||||
|
||||
@@ -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<String>,
|
||||
}
|
||||
|
||||
impl LibraryRestorer for DiagnosticRestorer {
|
||||
fn restore(
|
||||
&mut self,
|
||||
input: &Path,
|
||||
dest: &Path,
|
||||
verbose: bool,
|
||||
) -> anyhow::Result<RestoredLibrary> {
|
||||
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<Vec<u8>> {
|
||||
self.inner.protected_override(input)
|
||||
}
|
||||
}
|
||||
|
||||
fn pair(seed: u32) -> (Vec<u8>, Vec<u8>) {
|
||||
// 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<u8> {
|
||||
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"
|
||||
);
|
||||
}
|
||||
+1277
-15
File diff suppressed because it is too large.
Load diff
@@ -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;
|
||||
@@ -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 `<input>._` 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<String>,
|
||||
}
|
||||
|
||||
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<String>,
|
||||
pub detail: Option<String>,
|
||||
}
|
||||
|
||||
/// 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<String>,
|
||||
pub version: Option<String>,
|
||||
/// 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<ManifestReport>,
|
||||
/// 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<String>,
|
||||
/// Nested packages discovered at the top level of a bundle.
|
||||
pub nested_packages: Vec<String>,
|
||||
}
|
||||
|
||||
/// 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<String>,
|
||||
pub duration_ms: Option<u64>,
|
||||
}
|
||||
|
||||
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<String>) -> 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<EntryKind>,
|
||||
/// Route selected for this entry, when one was.
|
||||
pub layout: Option<LayoutKind>,
|
||||
pub metadata_version: Option<u32>,
|
||||
pub remapped: Option<usize>,
|
||||
/// 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).
|
||||
pub output: Option<OutputFile>,
|
||||
pub warnings: Vec<String>,
|
||||
pub errors: Vec<String>,
|
||||
}
|
||||
|
||||
impl EntryReport {
|
||||
pub fn new(name: impl Into<String>, 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<ProtectionProfile>,
|
||||
pub companion: Option<CompanionReport>,
|
||||
pub container: Option<ContainerReport>,
|
||||
pub entries: Vec<EntryReport>,
|
||||
/// Output files left on disk. Empty for inspect and dry-run.
|
||||
pub outputs: Vec<OutputFile>,
|
||||
/// Digest of the recovered image, when recovery produced one.
|
||||
pub recovered: Option<Digest>,
|
||||
/// Metadata header identity, when the input was an il2cpp metadata blob.
|
||||
pub metadata: Option<senbei_metadata::MetadataIdentity>,
|
||||
/// Raw il2cpp metadata version, duplicated for flat consumers.
|
||||
pub metadata_version: Option<u32>,
|
||||
/// Libraries whose decoded module was paired with this metadata input.
|
||||
pub provenance: Vec<String>,
|
||||
pub stages: Vec<StageReport>,
|
||||
pub warnings: Vec<String>,
|
||||
pub errors: Vec<String>,
|
||||
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<String>) {
|
||||
self.warnings.push(message.into());
|
||||
}
|
||||
|
||||
pub fn error(&mut self, message: impl Into<String>) {
|
||||
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<ScanReport>,
|
||||
pub inputs: Vec<InputReport>,
|
||||
pub summary: SummaryReport,
|
||||
/// Run-level failures that are not attributable to one input.
|
||||
pub errors: Vec<String>,
|
||||
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("<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,
|
||||
started: Instant,
|
||||
scan: Option<ScanReport>,
|
||||
inputs: Vec<InputReport>,
|
||||
summary: SummaryReport,
|
||||
errors: Vec<String>,
|
||||
}
|
||||
|
||||
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<String>) {
|
||||
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<senbei_metadata::MetadataIdentity>,
|
||||
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<senbei_metadata::MetadataIdentity>,
|
||||
) -> 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<senbei_metadata::MetadataIdentity>,
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -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());
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user