feat(profile): report detection and recovery evidence

This commit is contained in:
Momoko-Ayase committed 2026-11-05 21:34:39 +08:00
1 parent 0961d23538
commit 682beae9e7
8 files changed
+1320 -27

No files matched your search

+4 -1
View File
@@ -7,6 +7,9 @@ mod stream;
pub use error::Error;
pub use pipeline::{ExtractOptions, extract_stage2, extract_stage2_with_limits};
pub use probe::{is_protected_libil2cpp, probe_libil2cpp_with_limits};
pub use probe::{
is_protected_libil2cpp, is_protected_libil2cpp_profiled, probe_libil2cpp_profiled_with_limits,
probe_libil2cpp_with_limits, record_android_recovered,
};
pub use report::ExtractionReport;
pub use stage1::{DEFAULT_CIPHER_CONSTANT, DEFAULT_OUTER_SIZE};
+137
View File
@@ -1,10 +1,15 @@
use std::path::Path;
use senbei_crypto::android::Module9bConfig;
use senbei_elf::AARCH64_MACHINE;
use super::error::Error;
use super::stage1::{self, DEFAULT_CIPHER_CONSTANT, DEFAULT_OUTER_SIZE};
use crate::android::ResourceLimits;
use crate::profile::{
AttemptOutcome, LayoutAttempt, LayoutKind, ObservedTarget, ProtectionEvidence,
ProtectionProfile, RecognitionStatus, TargetFormat,
};
/// Return whether `data` has a supported protected AArch64 IL2CPP layout.
///
@@ -38,9 +43,84 @@ pub fn probe_libil2cpp_with_limits(data: &[u8], limits: &ResourceLimits) -> Resu
Ok(Module9bConfig::parse_embedded(&stage1.plaintext).is_ok())
}
/// [`is_protected_libil2cpp`] with the profile that produced the answer.
///
/// A false answer is `NotRecognized`. A size that exceeds the default ceilings
/// stays a [`Error::Limit`] inside the profile rather than silently becoming
/// "not protected": `RecognitionStatus::Blocked` plus the limit text. The
/// matched case lists the staged route as `NotAttempted`; the probe never
/// claims recovery.
#[must_use]
pub fn is_protected_libil2cpp_profiled(data: &[u8]) -> (ProtectionProfile, bool) {
let (profile, result) = probe_libil2cpp_profiled_with_limits(data, &ResourceLimits::default());
let protected = result.unwrap_or(false);
(profile, protected)
}
/// [`probe_libil2cpp_with_limits`] with its evidence preserved.
///
/// The profile is returned even when the probe returns [`Error::Limit`], and in
/// that case `recognition` is `Blocked`, never `NotRecognized`.
pub fn probe_libil2cpp_profiled_with_limits(
data: &[u8],
limits: &ResourceLimits,
) -> (ProtectionProfile, Result<bool, Error>) {
let mut profile = ProtectionProfile::new(ObservedTarget::android(android_target_format(data)));
match probe_libil2cpp_with_limits(data, limits) {
Ok(true) => {
profile.recognition = RecognitionStatus::Recognized;
profile.evidence = vec![
ProtectionEvidence::PrivateSection,
ProtectionEvidence::AesSchedule,
];
profile
.candidates
.push(LayoutAttempt::not_attempted(LayoutKind::AndroidStaged));
(profile, Ok(true))
}
Ok(false) => {
profile.recognition = RecognitionStatus::NotRecognized;
(profile, Ok(false))
}
Err(error) => {
profile.recognition = RecognitionStatus::Blocked;
profile.push_error(error.to_string());
if let Error::Limit(_) = error {
profile
.candidates
.push(LayoutAttempt::not_attempted(LayoutKind::AndroidStaged));
}
(profile, Err(error))
}
}
}
fn android_target_format(data: &[u8]) -> Option<TargetFormat> {
let elf = senbei_elf::parse(data).ok()?;
(elf.header.e_machine == AARCH64_MACHINE).then_some(TargetFormat::Elf64Aarch64)
}
/// Mark a matched Android profile as recovered after a successful restore.
///
/// The I/O adapter calls this after the staged restore actually writes an
/// image; the probe alone must not claim recovery.
pub fn record_android_recovered(profile: &mut ProtectionProfile) {
if profile.recognition == RecognitionStatus::Recognized {
profile.candidates = vec![LayoutAttempt {
layout: LayoutKind::AndroidStaged,
outcome: AttemptOutcome::Succeeded,
warnings: Vec::new(),
errors: Vec::new(),
}];
profile.selected = Some(LayoutKind::AndroidStaged);
profile.recovery = crate::profile::RecoveryStatus::Succeeded;
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::profile::RecoveryStatus;
/// Stage 1 header words, encrypted with the default cipher constant.
fn encrypt_header(words: [u32; 8]) -> [u8; 0x20] {
@@ -130,4 +210,61 @@ mod tests {
);
assert!(!is_protected_libil2cpp(&[]));
}
#[test]
fn profiled_limit_is_blocked_with_the_error_retained() {
let image = elf_with_payload_size(8);
let limits = ResourceLimits {
max_entry_bytes: 4,
max_total_bytes: 4,
..ResourceLimits::default()
};
let (profile, result) = probe_libil2cpp_profiled_with_limits(&image, &limits);
assert!(matches!(result, Err(Error::Limit(_))));
assert_eq!(profile.recognition, RecognitionStatus::Blocked);
assert_ne!(profile.recognition, RecognitionStatus::NotRecognized);
assert!(!profile.errors.is_empty());
assert!(
profile
.errors
.iter()
.any(|error| error.contains("resource limit")),
"{:?}",
profile.errors
);
assert_eq!(profile.selected, None);
assert_eq!(profile.candidates[0].outcome, AttemptOutcome::NotAttempted);
}
#[test]
fn profiled_not_protected_image_is_recognized_as_absent() {
let (profile, result) =
probe_libil2cpp_profiled_with_limits(&[], &ResourceLimits::default());
assert!(result.is_ok_and(|protected| !protected));
assert_eq!(profile.recognition, RecognitionStatus::NotRecognized);
assert!(profile.candidates.is_empty());
assert_eq!(
profile.observed.platform,
crate::profile::Platform::AndroidElf
);
}
#[test]
fn profiled_matched_image_lists_staged_route_without_claiming_recovery() {
// A complete, parseable Stage 1 + module 0x0C would require a full
// protected image; this fixture only reaches the pre-probe format
// branch, so verify the route contract on a profile built from it.
let mut profile =
ProtectionProfile::new(ObservedTarget::android(Some(TargetFormat::Elf64Aarch64)));
profile.recognition = RecognitionStatus::Recognized;
profile
.candidates
.push(LayoutAttempt::not_attempted(LayoutKind::AndroidStaged));
assert_eq!(profile.recovery, RecoveryStatus::NotAttempted);
assert_eq!(profile.selected, None);
record_android_recovered(&mut profile);
assert_eq!(profile.recovery, RecoveryStatus::Succeeded);
assert_eq!(profile.selected, Some(LayoutKind::AndroidStaged));
assert_eq!(profile.candidates[0].outcome, AttemptOutcome::Succeeded);
}
}
+2 -1
View File
@@ -8,7 +8,8 @@ mod restore;
pub use extract::{
DEFAULT_CIPHER_CONSTANT, DEFAULT_OUTER_SIZE, Error as ExtractionError, ExtractOptions,
ExtractionReport, extract_stage2, extract_stage2_with_limits, is_protected_libil2cpp,
probe_libil2cpp_with_limits,
is_protected_libil2cpp_profiled, probe_libil2cpp_profiled_with_limits,
probe_libil2cpp_with_limits, record_android_recovered,
};
pub use limits::{
ByteBudget, DEFAULT_MAX_DEPTH, DEFAULT_MAX_ENTRIES, DEFAULT_MAX_ENTRY_BYTES,
+10 -2
View File
@@ -2,13 +2,21 @@
pub mod android;
mod panic_capture;
pub mod profile;
pub mod windows;
pub use panic_capture::catch_unwind_quiet;
pub use profile::{
AttemptOutcome, LayoutAttempt, LayoutKind, ObservedTarget, PROFILE_FORMAT_VERSION, Platform,
ProtectionEvidence, ProtectionProfile, RecognitionStatus, RecoveryStatus, TargetFormat,
ValidationStatus,
};
pub use windows::{
Detected, IntegrityReport, Kind, UnpackError, check_integrity, detect, unpack_auto,
unpack_auto_v, unpack_dll, unpack_dll_v, unpack_exe, unpack_exe_v,
Detected, IntegrityFinding, IntegrityReport, IntegritySeverity, Kind, UnpackError,
check_integrity, detect, inspect_profile, unpack_auto, unpack_auto_profiled,
unpack_auto_profiled_v, unpack_auto_v, unpack_dll, unpack_dll_v, unpack_exe,
unpack_exe_profiled, unpack_exe_profiled_v, unpack_exe_v,
};
/// Deterministic worker-thread cap shared by filesystem scanning and engines.
+432
View File
@@ -0,0 +1,432 @@
//! Versioned, machine-readable protection profile.
//!
//! A profile separates four questions that the unpack pipelines answer at
//! different stages:
//!
//! 1. Is this a supported protected target? ([`RecognitionStatus`])
//! 2. Which layout route was tried, and what happened? ([`LayoutAttempt`])
//! 3. Did recovery produce an image? ([`RecoveryStatus`])
//! 4. Does that image pass the static checks? ([`ValidationStatus`])
//!
//! The profile records only what was observed in the input and what the
//! pipelines reported. It deliberately carries no inferred protection build,
//! vendor version, or runtime-behaviour claim. A caller can serialize it as-is;
//! the schema is versioned by [`PROFILE_FORMAT_VERSION`].
use serde::Serialize;
use crate::windows::{IntegrityReport, IntegritySeverity, Kind};
/// Version of the serialized [`ProtectionProfile`] schema.
pub const PROFILE_FORMAT_VERSION: u32 = 1;
/// Host format family of the observed input.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum Platform {
WindowsPe,
AndroidElf,
Il2cppMetadata,
}
/// Container format recognized from the input header.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum TargetFormat {
Pe32,
Pe32Plus,
Elf64Aarch64,
Il2cppMetadata,
}
/// One observed signal that supports (or rejects) protective handling.
///
/// These are evidence of *what was found*, not an identification of a product
/// build. `HeaderMagic` means the input's header key table carries the supported
/// magic; `ExternalCompanionDeclaration` means the loader never reads past its
/// own file without a companion suffix; `CompanionSpliced` means a matching
/// `._` payload was actually used; `PrivateSection` means Android's private
/// loader section exists; `AesSchedule` means the seeded AES schedule parsed.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum ProtectionEvidence {
HeaderMagic,
ExternalCompanionDeclaration,
CompanionSpliced,
PrivateSection,
AesSchedule,
/// An obfuscated metadata blob was structurally transformed and the result
/// validated. The IO metadata adapter records this only after the transform
/// actually succeeds; a mere metadata magic match is not evidence.
ValidatedMetadataTransform,
}
/// What recognition concluded, independent of recovery.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum RecognitionStatus {
NotAttempted,
Recognized,
NotRecognized,
/// Recognition could not run because an input ceiling was exceeded. This
/// is not the same as "not protected"; the caller read a limit error.
Blocked,
}
/// What recovery concluded.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum RecoveryStatus {
NotAttempted,
Succeeded,
Failed,
/// Recovery was not attempted because a prerequisite (a companion payload,
/// or a resource ceiling) was missing or exceeded.
Blocked,
}
/// Result of the static validation over the final image.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum ValidationStatus {
NotRun,
Clean,
Warnings,
Failed,
}
/// Recovery route considered for an input.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum LayoutKind {
/// The legacy DLL layout.
Dll,
/// The EXE-style shell layout (also the external-companion route).
ExeStyle,
/// Android staged extraction + ELF restoration. A matched probe may list
/// this as `NotAttempted`; that is not a recovery claim.
AndroidStaged,
/// Structural IL2CPP metadata transform.
MetadataStructural,
/// Seeded IL2CPP metadata restoration.
MetadataSeeded,
/// IL2CPP method-index recovery.
MetadataMethodIndices,
}
/// Outcome of one layout attempt.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum AttemptOutcome {
/// The route was planned but not run because a prior route was accepted.
NotAttempted,
Succeeded,
/// The route produced an image, but a fatal static check rejected it.
Rejected,
/// The route returned an error.
Failed,
}
/// The observed input, before any recovery.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct ObservedTarget {
pub platform: Platform,
pub format: Option<TargetFormat>,
pub kind: Option<Kind>,
/// IL2CPP metadata format version, when the adapter parsed one.
pub metadata_version: Option<u32>,
/// True only when the recovered image came from an external `._` companion
/// that was actually spliced into the input.
pub external_companion: bool,
}
impl ObservedTarget {
#[must_use]
pub fn windows(format: Option<TargetFormat>, kind: Option<Kind>) -> Self {
Self {
platform: Platform::WindowsPe,
format,
kind,
metadata_version: None,
external_companion: false,
}
}
#[must_use]
pub fn android(format: Option<TargetFormat>) -> Self {
Self {
platform: Platform::AndroidElf,
format,
kind: None,
metadata_version: None,
external_companion: false,
}
}
#[must_use]
pub fn metadata(version: Option<u32>) -> Self {
Self {
platform: Platform::Il2cppMetadata,
format: Some(TargetFormat::Il2cppMetadata),
kind: None,
metadata_version: version,
external_companion: false,
}
}
}
/// One attempted route, kept even when a later route succeeds.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct LayoutAttempt {
pub layout: LayoutKind,
pub outcome: AttemptOutcome,
pub warnings: Vec<String>,
pub errors: Vec<String>,
}
impl LayoutAttempt {
#[must_use]
pub fn not_attempted(layout: LayoutKind) -> Self {
Self {
layout,
outcome: AttemptOutcome::NotAttempted,
warnings: Vec::new(),
errors: Vec::new(),
}
}
}
/// Versioned result of inspecting and (optionally) recovering one input.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct ProtectionProfile {
pub format_version: u32,
pub observed: ObservedTarget,
pub evidence: Vec<ProtectionEvidence>,
pub recognition: RecognitionStatus,
pub recovery: RecoveryStatus,
pub static_validation: ValidationStatus,
/// Candidate routes in evaluation order. An accepted route keeps the
/// failures that preceded it.
pub candidates: Vec<LayoutAttempt>,
/// The route whose output was accepted, when recovery succeeded.
pub selected: Option<LayoutKind>,
/// Defects still present after the final validation. Empty when clean.
pub warnings: Vec<String>,
/// Unresolved failures: rejected/failed candidates when no route was
/// accepted, or fatal findings on an accepted image. Empty when none.
pub errors: Vec<String>,
}
impl ProtectionProfile {
#[must_use]
pub fn new(observed: ObservedTarget) -> Self {
Self {
format_version: PROFILE_FORMAT_VERSION,
observed,
evidence: Vec::new(),
recognition: RecognitionStatus::NotAttempted,
recovery: RecoveryStatus::NotAttempted,
static_validation: ValidationStatus::NotRun,
candidates: Vec::new(),
selected: None,
warnings: Vec::new(),
errors: Vec::new(),
}
}
pub fn push_warning(&mut self, message: impl Into<String>) {
self.warnings.push(message.into());
}
pub fn push_error(&mut self, message: impl Into<String>) {
self.errors.push(message.into());
}
/// Record that an external `._` companion was spliced into the input.
///
/// The I/O layer calls this only after the splice actually happened. The
/// observed target then reports the external-companion layout and the EXE
/// route as the only candidate, without changing any pipeline result.
pub fn record_companion_spliced(&mut self) {
self.observed.external_companion = true;
push_unique(&mut self.evidence, ProtectionEvidence::CompanionSpliced);
if self.candidates.is_empty() {
self.candidates
.push(LayoutAttempt::not_attempted(LayoutKind::ExeStyle));
}
}
/// The attempt for `layout`, if it was planned or run.
pub fn attempt_mut(&mut self, layout: LayoutKind) -> Option<&mut LayoutAttempt> {
self.candidates
.iter_mut()
.find(|attempt| attempt.layout == layout)
}
/// Record an attempt, adding a planned `NotAttempted` entry first when this
/// layout has not been seen yet. Returns the updated attempt.
pub(crate) fn record_attempt(
&mut self,
layout: LayoutKind,
outcome: AttemptOutcome,
warnings: Vec<String>,
errors: Vec<String>,
) -> &mut LayoutAttempt {
if self.attempt_mut(layout).is_none() {
self.candidates.push(LayoutAttempt::not_attempted(layout));
}
let attempt = self
.attempt_mut(layout)
.expect("attempt was just inserted or already existed");
attempt.outcome = outcome;
attempt.warnings = warnings;
attempt.errors = errors;
attempt
}
/// Replace the validation fields with the final image's report.
///
/// The I/O layer calls this after companion overlays so the profile
/// describes the bytes that are actually returned, not the pre-overlay
/// image.
pub fn record_static_validation(&mut self, report: &IntegrityReport) {
self.static_validation = validation_status(report);
self.warnings = messages(report, IntegritySeverity::Warning);
self.errors = messages(report, IntegritySeverity::Fatal);
}
}
fn push_unique(evidence: &mut Vec<ProtectionEvidence>, value: ProtectionEvidence) {
if !evidence.contains(&value) {
evidence.push(value);
}
}
fn validation_status(report: &IntegrityReport) -> ValidationStatus {
if report.ok() {
ValidationStatus::Clean
} else if report.has_fatal() {
ValidationStatus::Failed
} else {
ValidationStatus::Warnings
}
}
fn messages(report: &IntegrityReport, severity: IntegritySeverity) -> Vec<String> {
report
.findings
.iter()
.filter(|finding| finding.severity == severity)
.map(|finding| finding.message.clone())
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
use crate::windows::{IntegrityFinding, IntegrityReport};
fn report(findings: &[(IntegritySeverity, &str)]) -> IntegrityReport {
IntegrityReport {
issues: findings
.iter()
.map(|(_, issue)| (*issue).to_owned())
.collect(),
findings: findings
.iter()
.map(|(severity, message)| IntegrityFinding {
severity: *severity,
message: (*message).to_owned(),
})
.collect(),
}
}
#[test]
fn new_profile_is_versioned_and_unattempted() {
let profile = ProtectionProfile::new(ObservedTarget::windows(
Some(TargetFormat::Pe32Plus),
Some(Kind::NativeDll),
));
assert_eq!(profile.format_version, PROFILE_FORMAT_VERSION);
assert_eq!(profile.recognition, RecognitionStatus::NotAttempted);
assert_eq!(profile.recovery, RecoveryStatus::NotAttempted);
assert_eq!(profile.static_validation, ValidationStatus::NotRun);
assert!(profile.candidates.is_empty());
assert!(profile.selected.is_none());
}
#[test]
fn validation_status_separates_warnings_from_fatal_findings() {
let clean = ProtectionProfile::new(ObservedTarget::android(None));
let mut clean = clean;
clean.record_static_validation(&report(&[]));
assert_eq!(clean.static_validation, ValidationStatus::Clean);
assert!(clean.warnings.is_empty() && clean.errors.is_empty());
let mut warned = ProtectionProfile::new(ObservedTarget::android(None));
warned.record_static_validation(&report(&[(IntegritySeverity::Warning, "w")]));
assert_eq!(warned.static_validation, ValidationStatus::Warnings);
assert_eq!(warned.warnings, ["w"]);
assert!(warned.errors.is_empty());
let mut failed = ProtectionProfile::new(ObservedTarget::android(None));
failed.record_static_validation(&report(&[
(IntegritySeverity::Warning, "w"),
(IntegritySeverity::Fatal, "f"),
]));
assert_eq!(failed.static_validation, ValidationStatus::Failed);
assert_eq!(failed.warnings, ["w"]);
assert_eq!(failed.errors, ["f"]);
}
#[test]
fn attempts_keep_order_and_are_updated_in_place() {
let mut profile = ProtectionProfile::new(ObservedTarget::windows(None, None));
profile
.candidates
.push(LayoutAttempt::not_attempted(LayoutKind::Dll));
profile
.candidates
.push(LayoutAttempt::not_attempted(LayoutKind::ExeStyle));
profile.record_attempt(
LayoutKind::Dll,
AttemptOutcome::Rejected,
Vec::new(),
vec!["bad".to_owned()],
);
profile.record_attempt(
LayoutKind::ExeStyle,
AttemptOutcome::Succeeded,
Vec::new(),
Vec::new(),
);
assert_eq!(profile.candidates.len(), 2);
assert_eq!(profile.candidates[0].layout, LayoutKind::Dll);
assert_eq!(profile.candidates[0].outcome, AttemptOutcome::Rejected);
assert_eq!(profile.candidates[1].outcome, AttemptOutcome::Succeeded);
}
#[test]
fn serialized_profile_uses_versioned_snake_case_schema() {
let mut profile = ProtectionProfile::new(ObservedTarget::windows(
Some(TargetFormat::Pe32Plus),
Some(Kind::NativeDll),
));
profile.evidence.push(ProtectionEvidence::HeaderMagic);
profile.record_attempt(
LayoutKind::ExeStyle,
AttemptOutcome::Succeeded,
Vec::new(),
Vec::new(),
);
let value = serde_json::to_value(&profile).expect("profile serializes");
assert_eq!(value["format_version"], 1);
assert_eq!(value["observed"]["platform"], "windows_pe");
assert_eq!(value["observed"]["format"], "pe32_plus");
assert_eq!(value["observed"]["kind"], "native_dll");
assert_eq!(value["evidence"][0], "header_magic");
assert_eq!(value["candidates"][0]["layout"], "exe_style");
assert_eq!(value["candidates"][0]["outcome"], "succeeded");
}
}
+479 -12
View File
@@ -8,6 +8,13 @@ mod layout;
pub(crate) mod parallel;
use senbei_crypto::primitives;
use serde::Serialize;
use crate::profile::{
AttemptOutcome, LayoutAttempt, LayoutKind, ObservedTarget, ProtectionEvidence,
ProtectionProfile, RecognitionStatus, RecoveryStatus, TargetFormat,
};
use integrity::IntegritySeverity as ProfileSeverity;
pub(crate) use crate::panic_capture::{PanicCapture, current_panic_capture, with_panic_capture};
@@ -64,7 +71,8 @@ pub(crate) fn is_supported_magic(magic: u32) -> bool {
magic == MAGIC_KONN
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum Kind {
NativeExe,
ManagedExe,
@@ -197,6 +205,246 @@ pub fn unpack_auto_v(input: &[u8], verbose: bool) -> Result<(Kind, Vec<u8>), Unp
Ok((detected.kind, out))
}
/// Inspect a Windows input without recovering it.
///
/// Recognizes the supported header magic, records the PE format/kind, and lists
/// the routes a recovery would attempt. No candidate is run, so
/// [`ProtectionProfile::selected`](crate::profile::ProtectionProfile::selected)
/// stays `None` and every candidate is `NotAttempted`. Companion splicing is
/// the I/O layer's job: pass the spliced bytes and mark the profile with
/// [`ProtectionProfile::record_companion_spliced`](crate::profile::ProtectionProfile::record_companion_spliced).
#[must_use]
pub fn inspect_profile(input: &[u8]) -> ProtectionProfile {
let detected = detect(input);
inspect_detected(input, detected)
}
fn inspect_detected(input: &[u8], detected: Option<Detected>) -> ProtectionProfile {
let mut profile = ProtectionProfile::new(ObservedTarget::windows(
pe_target_format(input),
detected.map(|detected| detected.kind),
));
let Some(detected) = detected else {
profile.recognition = RecognitionStatus::NotRecognized;
return profile;
};
profile.recognition = RecognitionStatus::Recognized;
profile.evidence.push(ProtectionEvidence::HeaderMagic);
profile.candidates = planned_routes(detected.kind);
profile
}
fn planned_routes(kind: Kind) -> Vec<LayoutAttempt> {
match kind {
Kind::NativeExe | Kind::ManagedExe => {
vec![LayoutAttempt::not_attempted(LayoutKind::ExeStyle)]
}
Kind::NativeDll | Kind::ManagedDll => vec![
LayoutAttempt::not_attempted(LayoutKind::Dll),
LayoutAttempt::not_attempted(LayoutKind::ExeStyle),
],
}
}
fn pe_target_format(input: &[u8]) -> Option<TargetFormat> {
let headers = senbei_pe::parse(input).ok()?;
Some(if headers.is_pe32_plus {
TargetFormat::Pe32Plus
} else {
TargetFormat::Pe32
})
}
/// Detect, recover, and return the profile that records the route taken.
///
/// This is [`unpack_auto`] with its evidence preserved: the profile is returned
/// on success and on [`Err`], so a failed attempt still says which routes ran
/// and why they were rejected.
pub fn unpack_auto_profiled(
input: &[u8],
) -> (ProtectionProfile, Result<(Kind, Vec<u8>), UnpackError>) {
unpack_auto_profiled_v(input, false)
}
/// Verbose counterpart of [`unpack_auto_profiled`].
pub fn unpack_auto_profiled_v(
input: &[u8],
verbose: bool,
) -> (ProtectionProfile, Result<(Kind, Vec<u8>), UnpackError>) {
let detected = detect(input);
let mut profile = inspect_detected(input, detected);
let Some(detected) = detected else {
let error = UnpackError::NotCrackproof;
profile.push_error(error.to_string());
return (profile, Err(error));
};
let result = match detected.kind {
Kind::NativeExe | Kind::ManagedExe => {
run_exe_attempt(&mut profile, input, verbose).map(|out| (detected.kind, out))
}
Kind::NativeDll | Kind::ManagedDll => select_dll_layout_profiled(
&mut profile,
|| dll::unpack_dll_v(input, verbose),
|| exe::unpack_v(input, verbose),
)
.map(|out| (detected.kind, out)),
};
(profile, result)
}
/// Run only the EXE-style route and return its profile.
///
/// The external-companion I/O path uses this after splicing, because that
/// layout is definitionally the EXE-style shell.
pub fn unpack_exe_profiled(input: &[u8]) -> (ProtectionProfile, Result<Vec<u8>, UnpackError>) {
unpack_exe_profiled_v(input, false)
}
/// Verbose counterpart of [`unpack_exe_profiled`].
pub fn unpack_exe_profiled_v(
input: &[u8],
verbose: bool,
) -> (ProtectionProfile, Result<Vec<u8>, UnpackError>) {
let detected = detect(input);
let mut profile = inspect_detected(input, detected);
if detected.is_none() {
let error = UnpackError::NotCrackproof;
profile.push_error(error.to_string());
return (profile, Err(error));
}
// This entry point will never run the DLL route, so a DLL-kind detection's
// planned DLL candidate must not appear as an untried option.
profile
.candidates
.retain(|attempt| attempt.layout == LayoutKind::ExeStyle);
let result = run_exe_attempt(&mut profile, input, verbose);
(profile, result)
}
fn run_exe_attempt(
profile: &mut ProtectionProfile,
input: &[u8],
verbose: bool,
) -> Result<Vec<u8>, UnpackError> {
match exe::unpack_v(input, verbose) {
Ok(out) => {
let report = integrity::check(&out);
let warnings = profile_messages(&report, ProfileSeverity::Warning);
profile.record_attempt(
LayoutKind::ExeStyle,
AttemptOutcome::Succeeded,
warnings,
Vec::new(),
);
profile.selected = Some(LayoutKind::ExeStyle);
profile.recovery = RecoveryStatus::Succeeded;
profile.record_static_validation(&report);
Ok(out)
}
Err(error) => {
profile.record_attempt(
LayoutKind::ExeStyle,
AttemptOutcome::Failed,
Vec::new(),
vec![error.to_string()],
);
profile.recovery = RecoveryStatus::Failed;
profile.push_error(error.to_string());
Err(error)
}
}
}
/// `select_dll_layout`, additionally recording each candidate in `profile`.
///
/// Routing and gates are exactly those of [`select_dll_layout`]: the DLL layout
/// is accepted whenever it has no fatal finding, warnings included; the EXE
/// layout runs only after the DLL layout errors or is structurally invalid.
fn select_dll_layout_profiled<D, E>(
profile: &mut ProtectionProfile,
dll_layout: D,
exe_layout: E,
) -> Result<Vec<u8>, UnpackError>
where
D: FnOnce() -> Result<Vec<u8>, UnpackError>,
E: FnOnce() -> Result<Vec<u8>, UnpackError>,
{
match accept_dll_layout(dll_layout()) {
Ok((output, report)) => {
record_accepted(profile, LayoutKind::Dll, report);
Ok(output)
}
Err(dll) => {
record_rejected(profile, LayoutKind::Dll, &dll);
match accept_dll_layout(exe_layout()) {
Ok((output, report)) => {
record_accepted(profile, LayoutKind::ExeStyle, report);
Ok(output)
}
Err(exe) => {
record_rejected(profile, LayoutKind::ExeStyle, &exe);
profile.recovery = RecoveryStatus::Failed;
let error = UnpackError::PipelineFallbackFailed {
dll: Box::new(dll.error),
exe: Box::new(exe.error),
};
profile.push_error(error.to_string());
Err(error)
}
}
}
}
}
fn record_accepted(profile: &mut ProtectionProfile, layout: LayoutKind, report: IntegrityReport) {
let warnings = profile_messages(&report, ProfileSeverity::Warning);
profile.record_attempt(layout, AttemptOutcome::Succeeded, warnings, Vec::new());
profile.selected = Some(layout);
profile.recovery = RecoveryStatus::Succeeded;
profile.record_static_validation(&report);
}
fn record_rejected(profile: &mut ProtectionProfile, layout: LayoutKind, failure: &LayoutFailure) {
let (warnings, errors) = match &failure.report {
Some(report) => (
profile_messages(report, ProfileSeverity::Warning),
profile_messages(report, ProfileSeverity::Fatal),
),
None => (Vec::new(), vec![failure.error.to_string()]),
};
let outcome = if failure.report.is_some() {
AttemptOutcome::Rejected
} else {
AttemptOutcome::Failed
};
profile.record_attempt(layout, outcome, warnings, errors);
}
fn profile_messages(report: &IntegrityReport, severity: ProfileSeverity) -> Vec<String> {
report
.findings
.iter()
.filter(|finding| finding.severity == severity)
.map(|finding| finding.message.clone())
.collect()
}
/// One rejected layout attempt and the report that rejected it, if the
/// pipeline produced an image at all.
struct LayoutFailure {
error: UnpackError,
report: Option<IntegrityReport>,
}
impl std::fmt::Debug for LayoutFailure {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("LayoutFailure")
.field("error", &self.error)
.field("rejected_by_integrity", &self.report.is_some())
.finish()
}
}
/// Pick between the older DLL layout and the EXE-style shell layout.
///
/// `Ok` from a pipeline is not proof it chose the right layout: a wrong layout
@@ -225,18 +473,28 @@ where
}
fn validate_dll_layout(output: Result<Vec<u8>, UnpackError>) -> Result<Vec<u8>, UnpackError> {
let output = output?;
if let Some(report) = dll_layout_invalid(&output) {
return Err(UnpackError::InvalidLayoutCandidate {
issues: report
.findings
.into_iter()
.filter(|finding| finding.severity == integrity::IntegritySeverity::Fatal)
.map(|finding| finding.message)
.collect(),
});
accept_dll_layout(output)
.map(|(output, _)| output)
.map_err(|failure| failure.error)
}
/// Run one pipeline and apply the layout gate with a single integrity check.
fn accept_dll_layout(
output: Result<Vec<u8>, UnpackError>,
) -> Result<(Vec<u8>, IntegrityReport), LayoutFailure> {
let output = output.map_err(|error| LayoutFailure {
error,
report: None,
})?;
let report = integrity::check(&output);
if !report.has_fatal() {
return Ok((output, report));
}
Ok(output)
let issues = profile_messages(&report, ProfileSeverity::Fatal);
Err(LayoutFailure {
error: UnpackError::InvalidLayoutCandidate { issues },
report: Some(report),
})
}
/// Structural defects that mean a DLL layout candidate must not be accepted.
@@ -251,6 +509,7 @@ fn validate_dll_layout(output: Result<Vec<u8>, UnpackError>) -> Result<Vec<u8>,
///
/// Severity comes from [`IntegrityReport::has_fatal`], which the checker sets
/// when it records each finding. This does not re-read issue text.
#[cfg(test)]
fn dll_layout_invalid(image: &[u8]) -> Option<IntegrityReport> {
let report = integrity::check(image);
report.has_fatal().then_some(report)
@@ -320,6 +579,7 @@ mod tests {
#[cfg(test)]
mod dll_layout_selection {
use super::*;
use crate::profile::{Platform, ValidationStatus};
fn pipeline_err(stage: &'static str) -> UnpackError {
UnpackError::InputTooShort {
@@ -615,4 +875,211 @@ mod dll_layout_selection {
integrity::check(&readable).issues
);
}
// -----------------------------------------------------------------------
// Profiled routing: same gates, evidence preserved.
// -----------------------------------------------------------------------
fn profiled<D, E>(
dll_layout: D,
exe_layout: E,
) -> (ProtectionProfile, Result<Vec<u8>, UnpackError>)
where
D: FnOnce() -> Result<Vec<u8>, UnpackError>,
E: FnOnce() -> Result<Vec<u8>, UnpackError>,
{
let mut profile = ProtectionProfile::new(ObservedTarget::windows(
Some(TargetFormat::Pe32Plus),
Some(Kind::NativeDll),
));
profile.recognition = RecognitionStatus::Recognized;
profile.candidates = planned_routes(Kind::NativeDll);
let result = select_dll_layout_profiled(&mut profile, dll_layout, exe_layout);
(profile, result)
}
#[test]
fn profiled_keeps_accepting_dll_route_and_leaves_exe_unattempted() {
let dll_image = valid_native_dll();
let (profile, result) = profiled(
|| Ok(dll_image.clone()),
|| panic!("EXE layout must not run when the DLL layout is valid"),
);
assert_eq!(result.unwrap(), dll_image);
assert_eq!(profile.selected, Some(LayoutKind::Dll));
assert_eq!(profile.recovery, RecoveryStatus::Succeeded);
assert_eq!(profile.static_validation, ValidationStatus::Clean);
assert_eq!(profile.candidates.len(), 2);
assert_eq!(profile.candidates[0].layout, LayoutKind::Dll);
assert_eq!(profile.candidates[0].outcome, AttemptOutcome::Succeeded);
assert_eq!(profile.candidates[1].layout, LayoutKind::ExeStyle);
assert_eq!(profile.candidates[1].outcome, AttemptOutcome::NotAttempted);
assert!(profile.errors.is_empty());
}
#[test]
fn profiled_fallback_retains_the_rejected_dll_attempt_first() {
let dll_image = SyntheticPe {
entry_rva: 0x9000,
..SyntheticPe::default()
}
.build();
let exe_image = valid_native_dll();
let (profile, result) = profiled(|| Ok(dll_image.clone()), || Ok(exe_image.clone()));
assert_eq!(result.unwrap(), exe_image);
assert_eq!(profile.selected, Some(LayoutKind::ExeStyle));
let dll = &profile.candidates[0];
assert_eq!(dll.layout, LayoutKind::Dll);
assert_eq!(dll.outcome, AttemptOutcome::Rejected);
assert!(
dll.errors
.iter()
.any(|error| error.contains("entry point RVA")),
"{:?}",
dll.errors
);
let exe = &profile.candidates[1];
assert_eq!(exe.outcome, AttemptOutcome::Succeeded);
// The accepted image is clean, so the rejected candidate's fatal
// findings stay on its own attempt rather than the profile top level.
assert!(profile.errors.is_empty());
}
#[test]
fn profiled_failure_reports_every_route_and_no_selection() {
let invalid = SyntheticPe {
entry_rva: 0x9000,
..SyntheticPe::default()
}
.build();
let (profile, result) = profiled(|| Ok(invalid.clone()), || Ok(invalid.clone()));
assert!(result.is_err());
assert_eq!(profile.selected, None);
assert_eq!(profile.recovery, RecoveryStatus::Failed);
assert!(!profile.errors.is_empty());
assert_eq!(profile.candidates.len(), 2);
assert_eq!(profile.candidates[0].outcome, AttemptOutcome::Rejected);
assert_eq!(profile.candidates[1].outcome, AttemptOutcome::Rejected);
}
#[test]
fn profiled_pipeline_errors_are_recorded_per_route() {
let (profile, result) = profiled(
|| Err(pipeline_err("dll")),
|| Err(pipeline_err("exe-layout")),
);
assert!(matches!(
result,
Err(UnpackError::PipelineFallbackFailed { .. })
));
assert_eq!(profile.candidates[0].outcome, AttemptOutcome::Failed);
assert_eq!(profile.candidates[1].outcome, AttemptOutcome::Failed);
assert!(profile.candidates[0].errors[0].contains("got 3"));
assert!(profile.candidates[1].errors[0].contains("got 10"));
}
#[test]
fn profiled_dll_warning_keeps_the_route_and_records_the_warning() {
let warned = SyntheticPe {
reloc: false,
..SyntheticPe::default()
}
.build();
let (profile, result) = profiled(
|| Ok(warned.clone()),
|| panic!("warnings must not trigger the EXE layout"),
);
assert_eq!(result.unwrap(), warned);
assert_eq!(profile.selected, Some(LayoutKind::Dll));
assert_eq!(profile.static_validation, ValidationStatus::Warnings);
assert!(!profile.warnings.is_empty());
assert_eq!(profile.candidates[0].outcome, AttemptOutcome::Succeeded);
assert!(!profile.candidates[0].warnings.is_empty());
}
/// A minimal protected-shaped input `detect` accepts: enough bytes for the
/// header key table, a valid PE signature, the DLL characteristic, and a
/// PE32+ optional header. Generates header words at offset 4096 so that
/// `keys[1]` is the supported magic.
fn detected_dll_input() -> Vec<u8> {
let mut data = SyntheticPe::default().build();
data.resize(0x1100, 0);
let pe = 0x80usize;
let chars = 0x2000u16 | 0x0002;
data[pe + 22..pe + 24].copy_from_slice(&chars.to_le_bytes());
// Header key derivation: keys[0] = word(4096);
// keys[1] = keys[0] ^ word(4100). Choose keys[0] = 1 so the stored
// cell yields the magic.
let key0 = 1u32;
let cell = key0 ^ MAGIC_KONN;
data[4096..4100].copy_from_slice(&key0.to_le_bytes());
data[4100..4104].copy_from_slice(&cell.to_le_bytes());
data
}
#[test]
fn inspect_profile_reports_recognition_without_running_a_route() {
let profile = inspect_profile(&detected_dll_input());
assert_eq!(profile.recognition, RecognitionStatus::Recognized);
assert_eq!(profile.observed.platform, Platform::WindowsPe);
assert_eq!(profile.observed.format, Some(TargetFormat::Pe32Plus));
assert_eq!(profile.observed.kind, Some(Kind::NativeDll));
assert!(profile.evidence.contains(&ProtectionEvidence::HeaderMagic));
assert_eq!(profile.selected, None);
assert_eq!(profile.recovery, RecoveryStatus::NotAttempted);
assert_eq!(profile.static_validation, ValidationStatus::NotRun);
assert_eq!(profile.candidates.len(), 2);
assert!(
profile
.candidates
.iter()
.all(|attempt| attempt.outcome == AttemptOutcome::NotAttempted)
);
}
#[test]
fn profiled_entrypoints_reject_unknown_input_with_evidence() {
let sample = vec![0_u8; 64];
let (profile, result) = unpack_auto_profiled(&sample);
assert!(matches!(result, Err(UnpackError::NotCrackproof)));
assert_eq!(profile.recognition, RecognitionStatus::NotRecognized);
assert!(profile.candidates.is_empty());
assert!(!profile.errors.is_empty());
let (profile, result) = unpack_exe_profiled(&sample);
assert!(matches!(result, Err(UnpackError::NotCrackproof)));
assert_eq!(profile.recognition, RecognitionStatus::NotRecognized);
assert!(!profile.errors.is_empty());
}
#[test]
fn companion_splice_evidence_is_explicit() {
let mut profile = inspect_profile(&detected_dll_input());
assert!(!profile.observed.external_companion);
profile.record_companion_spliced();
assert!(profile.observed.external_companion);
assert!(
profile
.evidence
.contains(&ProtectionEvidence::CompanionSpliced)
);
// Pairing proves a splice, not that the loader declares an external
// suffix. That declaration requires separate entry-record evidence.
assert!(
!profile
.evidence
.contains(&ProtectionEvidence::ExternalCompanionDeclaration)
);
// Idempotent, and it never claims recovery.
profile.record_companion_spliced();
assert_eq!(
profile
.evidence
.iter()
.filter(|evidence| **evidence == ProtectionEvidence::CompanionSpliced)
.count(),
1
);
assert_eq!(profile.recovery, RecoveryStatus::NotAttempted);
}
}
+2 -2
View File
@@ -99,7 +99,7 @@ pub(super) fn prepare_companion(
}
#[cfg(test)]
mod tests {
pub(super) mod tests {
use super::*;
fn put32(bytes: &mut [u8], offset: usize, value: u32) {
@@ -107,7 +107,7 @@ mod tests {
}
/// Generated PE and entry record; no protected binary bytes are embedded.
fn stub() -> Vec<u8> {
pub(crate) fn stub() -> Vec<u8> {
let mut bytes = vec![0; 0x3000];
bytes[..2].copy_from_slice(b"MZ");
put32(&mut bytes, 0x3c, 0x80);
+254 -9
View File
@@ -1,6 +1,7 @@
//! Windows filesystem adapter for PE companion payloads and byte APIs.
use senbei_engine as unpacker;
use senbei_engine::profile::ProtectionProfile;
use std::path::Path;
use crate::atomic::write_atomic;
@@ -506,21 +507,144 @@ fn unpack_bytes_impl(
companion: Option<&[u8]>,
force_exe: bool,
) -> Result<UnpackedImage, unpacker::UnpackError> {
let spliced = companion::prepare_companion(input, companion)?;
unpack_bytes_profiled_impl(input, companion, force_exe, false).1
}
/// In-memory unpack that returns the route evidence alongside the result.
///
/// The profile is returned on success and on `Err`. It records the actual
/// Windows route (DLL-first with EXE fallback, or EXE-only for a spliced
/// companion / forced EXE), every candidate attempt, and — after the companion
/// export/TLS/CLR overlays — the final image's static validation. When the
/// splice succeeded the observed target says so and the EXE-style route is the
/// only candidate, matching [`unpack_spliced_or_auto`].
pub fn unpack_bytes_profiled(
input: &[u8],
companion: Option<&[u8]>,
) -> (
ProtectionProfile,
Result<UnpackedImage, unpacker::UnpackError>,
) {
unpack_bytes_profiled_impl(input, companion, false, false)
}
/// Verbose counterpart of [`unpack_bytes_profiled`].
pub fn unpack_bytes_profiled_v(
input: &[u8],
companion: Option<&[u8]>,
verbose: bool,
) -> (
ProtectionProfile,
Result<UnpackedImage, unpacker::UnpackError>,
) {
unpack_bytes_profiled_impl(input, companion, false, verbose)
}
/// [`unpack_bytes_force_exe`] with the route profile.
pub fn unpack_bytes_force_exe_profiled(
input: &[u8],
companion: Option<&[u8]>,
) -> (
ProtectionProfile,
Result<UnpackedImage, unpacker::UnpackError>,
) {
unpack_bytes_profiled_impl(input, companion, true, false)
}
/// Verbose counterpart of [`unpack_bytes_force_exe_profiled`].
pub fn unpack_bytes_force_exe_profiled_v(
input: &[u8],
companion: Option<&[u8]>,
verbose: bool,
) -> (
ProtectionProfile,
Result<UnpackedImage, unpacker::UnpackError>,
) {
unpack_bytes_profiled_impl(input, companion, true, verbose)
}
fn unpack_bytes_profiled_impl(
input: &[u8],
companion: Option<&[u8]>,
force_exe: bool,
verbose: bool,
) -> (
ProtectionProfile,
Result<UnpackedImage, unpacker::UnpackError>,
) {
let spliced = match companion::prepare_companion(input, companion) {
Ok(spliced) => spliced,
Err(error) => {
let mut profile = unpacker::inspect_profile(input);
profile.recovery = unpacker::RecoveryStatus::Blocked;
if matches!(
error,
unpacker::UnpackError::CompanionMissing | unpacker::UnpackError::CompanionMismatch
) {
profile
.evidence
.push(unpacker::ProtectionEvidence::ExternalCompanionDeclaration);
profile
.candidates
.retain(|attempt| attempt.layout == unpacker::LayoutKind::ExeStyle);
}
profile.push_error(error.to_string());
return (profile, Err(error));
}
};
let bytes: &[u8] = spliced.as_deref().unwrap_or(input);
let (kind, mut out) = unpack_spliced_or_auto(bytes, spliced.is_some(), force_exe, false)?;
let exe_only = spliced.is_some() || force_exe;
let (mut profile, recovered) = if exe_only {
let (profile, result) = unpacker::unpack_exe_profiled_v(bytes, verbose);
(profile, result)
} else {
let (profile, result) = unpacker::unpack_auto_profiled_v(bytes, verbose);
(profile, result.map(|(_, out)| out))
};
if spliced.is_some() {
profile.record_companion_spliced();
}
let mut out = match recovered {
Ok(out) => out,
Err(error) => return (profile, Err(error)),
};
if spliced.is_some() {
overlay_exports_from_stub(&mut out, input);
restore_tls_from_stub(&mut out, input);
restore_managed_from_stub(&mut out, input)?;
if let Err(error) = restore_managed_from_stub(&mut out, input) {
profile.recovery = unpacker::RecoveryStatus::Failed;
// The candidate's checks remain on its attempt. No final image was
// produced after the failed overlay, so final validation did not run.
profile.static_validation = unpacker::ValidationStatus::NotRun;
profile.warnings.clear();
profile.errors.clear();
profile.push_error(error.to_string());
return (profile, Err(error));
}
}
let integrity = unpacker::check_integrity(&out);
Ok(UnpackedImage {
kind,
bytes: out,
integrity,
companion: spliced.is_some(),
})
// The overlays change the image; the profile must describe the bytes
// actually returned, not the pre-overlay candidate.
profile.record_static_validation(&integrity);
// The profile's observed target was produced by the same detection that
// routed recovery; reuse it instead of scanning the header again.
let kind = match profile.observed.kind {
Some(kind) => kind,
None => {
let error = unpacker::UnpackError::NotCrackproof;
profile.push_error(error.to_string());
return (profile, Err(error));
}
};
(
profile,
Ok(UnpackedImage {
kind,
bytes: out,
integrity,
companion: spliced.is_some(),
}),
)
}
/// Like [`unpack_one`], but prints detailed `[N/9]` step progress (and a final
@@ -710,4 +834,125 @@ mod tests {
assert_eq!(out, before);
}
}
// -----------------------------------------------------------------------
// Profiled byte entry points.
// -----------------------------------------------------------------------
fn detected_dll_without_companion_declaration() -> Vec<u8> {
// Header key table at 4096 makes `detect` succeed; the rest of the
// file is deliberately not a valid protected image, so recovery fails
// after recognition. That is exactly the evidence path under test.
let mut data = vec![0_u8; 0x1100];
data[..2].copy_from_slice(b"MZ");
data[0x3c..0x40].copy_from_slice(&0x80u32.to_le_bytes());
data[0x80..0x84].copy_from_slice(b"PE\0\0");
data[0x80 + 4..0x80 + 6].copy_from_slice(&0x8664u16.to_le_bytes());
data[0x80 + 6..0x80 + 8].copy_from_slice(&1u16.to_le_bytes());
data[0x80 + 20..0x80 + 22].copy_from_slice(&0xf0u16.to_le_bytes());
data[0x80 + 22..0x80 + 24].copy_from_slice(&0x2000u16.to_le_bytes());
data[0x80 + 24..0x80 + 26].copy_from_slice(&0x20bu16.to_le_bytes());
let key0 = 1u32;
let cell = key0 ^ 0x4E4E_4F4B;
data[HEADER_OFF..HEADER_OFF + 4].copy_from_slice(&key0.to_le_bytes());
data[HEADER_OFF + 4..HEADER_OFF + 8].copy_from_slice(&cell.to_le_bytes());
data
}
#[test]
fn profiled_entry_points_return_the_profile_with_a_failed_recovery() {
let input = detected_dll_without_companion_declaration();
let (profile, result) = unpack_bytes_profiled(&input, None);
assert!(result.is_err(), "fixture is not a recoverable image");
assert_eq!(profile.recognition, unpacker::RecognitionStatus::Recognized);
assert_eq!(profile.observed.kind, Some(unpacker::Kind::NativeDll));
assert_eq!(profile.observed.platform, unpacker::Platform::WindowsPe);
assert_eq!(profile.selected, None);
assert!(!profile.errors.is_empty());
assert_eq!(profile.candidates[0].layout, unpacker::LayoutKind::Dll);
assert_eq!(
profile.candidates[0].outcome,
unpacker::AttemptOutcome::Failed
);
assert_eq!(profile.candidates[1].layout, unpacker::LayoutKind::ExeStyle);
assert_eq!(
profile.candidates[1].outcome,
unpacker::AttemptOutcome::Failed
);
}
#[test]
fn profiled_force_exe_route_runs_only_the_exe_candidate() {
let input = detected_dll_without_companion_declaration();
let (profile, result) = unpack_bytes_force_exe_profiled(&input, None);
assert!(result.is_err());
assert_eq!(profile.candidates.len(), 1);
assert_eq!(profile.candidates[0].layout, unpacker::LayoutKind::ExeStyle);
assert!(!profile.observed.external_companion);
}
#[test]
fn profiled_companion_error_keeps_the_inspection_evidence() {
// The companion declaration stub is the one from companion.rs's own
// tests; without its payload the error is CompanionMissing.
let input = companion::tests::stub();
let (profile, result) = unpack_bytes_profiled(&input, None);
let error = result.err().expect("companion is missing");
assert_eq!(error, unpacker::UnpackError::CompanionMissing);
assert_eq!(profile.recognition, unpacker::RecognitionStatus::Recognized);
assert_eq!(profile.recovery, unpacker::RecoveryStatus::Blocked);
assert_eq!(
profile.static_validation,
unpacker::ValidationStatus::NotRun
);
assert!(
profile
.evidence
.contains(&unpacker::ProtectionEvidence::ExternalCompanionDeclaration)
);
assert!(
!profile
.evidence
.contains(&unpacker::ProtectionEvidence::CompanionSpliced)
);
assert!(
profile
.candidates
.iter()
.all(|attempt| attempt.outcome == unpacker::AttemptOutcome::NotAttempted)
);
assert!(!profile.errors.is_empty());
assert_eq!(profile.selected, None);
}
#[test]
fn profiled_splice_marks_the_external_companion_and_exe_route() {
let input = companion::tests::stub();
let payload = &input[HEADER_OFF..];
let (profile, result) = unpack_bytes_profiled(&input, Some(payload));
// The synthetic stub is recognized and spliced, but its payload is not
// a recoverable protected image, so recovery fails after the splice.
assert!(result.is_err());
assert!(profile.observed.external_companion);
assert!(
profile
.evidence
.contains(&unpacker::ProtectionEvidence::CompanionSpliced)
);
assert_eq!(profile.candidates.len(), 1);
assert_eq!(profile.candidates[0].layout, unpacker::LayoutKind::ExeStyle);
assert_eq!(profile.selected, None);
}
#[test]
fn profiled_unknown_input_is_not_recognized() {
let (profile, result) = unpack_bytes_profiled(&[], None);
assert!(matches!(result, Err(unpacker::UnpackError::NotCrackproof)));
assert_eq!(
profile.recognition,
unpacker::RecognitionStatus::NotRecognized
);
assert!(profile.candidates.is_empty());
assert_eq!(profile.observed.kind, None);
}
}