mirror of
https://github.com/Momoko-Ayase/Senbei.git
synced 2026-11-24 02:52:47 +08:00
feat: localize console output and add a run observer
Engine errors, integrity findings, and driver outcomes carry message codes from senbei-i18n, with their English unchanged, so reports, logs, and --json stay byte-identical. Verbose pipeline steps go through a progress sink instead of println!, and an error chain is translated through its first coded cause. The CLI takes the display language from SENBEI_LANG, or else from the system's preferred UI language, and translates console text: usage errors, help, per-file lines, the run summary, and the summary lines of the inspect report. Structural research evidence and saved logs stay English. When a translation leaves out context the English chain has, the English follows on a muted line. A front end can attach a RunObserver and a CancelToken to the Collector to follow a run input by input, receive verbose steps as events, and stop before the next input. A cancelled report says so. The CLI never cancels, so its JSON is unchanged.
This commit is contained in:
1 parent
9481b0ccf9
commit
4853fe22c0
39 files changed
+2016
-684
No files matched your search
@@ -14,6 +14,7 @@ sha2.workspace = true
|
||||
tempfile.workspace = true
|
||||
thiserror.workspace = true
|
||||
senbei-crypto.workspace = true
|
||||
senbei-i18n.workspace = true
|
||||
senbei-elf.workspace = true
|
||||
senbei-pe.workspace = true
|
||||
|
||||
|
||||
@@ -84,7 +84,10 @@ pub fn probe_libil2cpp_profiled_with_limits(
|
||||
}
|
||||
Err(error) => {
|
||||
profile.recognition = RecognitionStatus::Blocked;
|
||||
profile.push_error(error.to_string());
|
||||
profile.push_error(match &error {
|
||||
Error::Limit(limit) => limit.message(),
|
||||
other => other.to_string().into(),
|
||||
});
|
||||
if let Error::Limit(_) = error {
|
||||
profile
|
||||
.candidates
|
||||
|
||||
@@ -110,6 +110,28 @@ pub enum LimitExceeded {
|
||||
Depth { requested: usize, limit: usize },
|
||||
}
|
||||
|
||||
impl LimitExceeded {
|
||||
/// The ceiling as a translatable message whose English is this error's.
|
||||
pub fn message(&self) -> senbei_i18n::Message {
|
||||
use senbei_i18n::Msg;
|
||||
let msg = match *self {
|
||||
Self::Entry { requested, limit } => Msg::LimitEntry { requested, limit },
|
||||
Self::Total {
|
||||
requested,
|
||||
adding,
|
||||
limit,
|
||||
} => Msg::LimitTotal {
|
||||
requested,
|
||||
adding,
|
||||
limit,
|
||||
},
|
||||
Self::Entries { requested, limit } => Msg::LimitEntries { requested, limit },
|
||||
Self::Depth { requested, limit } => Msg::LimitDepth { requested, limit },
|
||||
};
|
||||
senbei_i18n::Message::with_text(msg, self.to_string())
|
||||
}
|
||||
}
|
||||
|
||||
/// Running sum of retained or temporary bytes for one task.
|
||||
///
|
||||
/// Each call starts its own budget at zero. Charging checks the single-entry
|
||||
@@ -213,6 +235,37 @@ impl EntryBudget {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn limit_messages_keep_the_error_wording_and_translate_it() {
|
||||
use senbei_i18n::Lang;
|
||||
for error in [
|
||||
LimitExceeded::Entry {
|
||||
requested: 10,
|
||||
limit: 4,
|
||||
},
|
||||
LimitExceeded::Total {
|
||||
requested: 9,
|
||||
adding: 3,
|
||||
limit: 8,
|
||||
},
|
||||
LimitExceeded::Entries {
|
||||
requested: 101,
|
||||
limit: 100,
|
||||
},
|
||||
LimitExceeded::Depth {
|
||||
requested: 33,
|
||||
limit: 32,
|
||||
},
|
||||
] {
|
||||
let message = error.message();
|
||||
assert_eq!(message.text(), error.to_string());
|
||||
assert!(message.msg().is_some());
|
||||
for lang in Lang::ALL {
|
||||
assert_eq!(message.detail(lang), None, "{lang:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn defaults_match_the_documented_ceilings() {
|
||||
let limits = ResourceLimits::default();
|
||||
|
||||
@@ -8,6 +8,7 @@ use memmap2::{Mmap, MmapMut, MmapOptions};
|
||||
use senbei_crypto::android::{
|
||||
ContainerHeader, HuffmanLzDecoder, Module9bConfig, ProtectedDescriptor, transform_segment,
|
||||
};
|
||||
use senbei_i18n::Step;
|
||||
use serde::Serialize;
|
||||
use sha2::{Digest, Sha256};
|
||||
use tempfile::NamedTempFile;
|
||||
@@ -463,12 +464,12 @@ where
|
||||
data_cursor = encoded_end;
|
||||
}
|
||||
if verbose {
|
||||
eprintln!(
|
||||
crate::progress::detail_err(format_args!(
|
||||
"[{current:02}/{total:02}] writers={writer_count} encoded=0x{size:x}",
|
||||
current = segment_index + 1,
|
||||
total = header.segments.len(),
|
||||
size = encoded.size,
|
||||
);
|
||||
));
|
||||
}
|
||||
}
|
||||
Ok(statistics)
|
||||
@@ -2671,7 +2672,7 @@ pub fn restore_libil2cpp_with_limits(
|
||||
{
|
||||
let mut output = map_mut(temporary.as_file(), private_size, &temporary_path)?;
|
||||
if options.verbose {
|
||||
eprintln!("Decoding primary 0x9D target-image container...");
|
||||
crate::progress::stage(Step::AndroidPrimary);
|
||||
}
|
||||
let mut writer = FileLayoutWriter {
|
||||
output: &mut output,
|
||||
@@ -2711,7 +2712,7 @@ pub fn restore_libil2cpp_with_limits(
|
||||
|
||||
if !options.outer_only {
|
||||
if options.verbose {
|
||||
eprintln!("Decoding auxiliary 0x9D ELF materialization container...");
|
||||
crate::progress::stage(Step::AndroidAuxiliary);
|
||||
}
|
||||
let mut decoded = allocate_auxiliary(auxiliary_header.output_size, limits, &mut bytes)?;
|
||||
let auxiliary_len = decoded.len();
|
||||
@@ -2771,7 +2772,7 @@ pub fn restore_libil2cpp_with_limits(
|
||||
.set_len(mapping_bytes)
|
||||
.map_err(|error| Error::io("extend temporary output", &temporary_path, error))?;
|
||||
if options.verbose {
|
||||
eprintln!("Rebuilding static ELF dynamic-linker tables...");
|
||||
crate::progress::stage(Step::AndroidTables);
|
||||
}
|
||||
{
|
||||
let mut output = map_mut(temporary.as_file(), mapping_length, &temporary_path)?;
|
||||
|
||||
@@ -4,6 +4,7 @@ pub mod android;
|
||||
mod findings;
|
||||
mod panic_capture;
|
||||
pub mod profile;
|
||||
pub mod progress;
|
||||
mod threading;
|
||||
pub mod windows;
|
||||
|
||||
|
||||
@@ -13,6 +13,7 @@
|
||||
//! vendor version, or runtime-behaviour claim. A caller can serialize it as-is;
|
||||
//! the schema is versioned by [`PROFILE_FORMAT_VERSION`].
|
||||
|
||||
use senbei_i18n::Message;
|
||||
use serde::Serialize;
|
||||
|
||||
use crate::windows::{IntegrityReport, IntegritySeverity, Kind};
|
||||
@@ -180,8 +181,8 @@ impl ObservedTarget {
|
||||
pub struct LayoutAttempt {
|
||||
pub layout: LayoutKind,
|
||||
pub outcome: AttemptOutcome,
|
||||
pub warnings: Vec<String>,
|
||||
pub errors: Vec<String>,
|
||||
pub warnings: Vec<Message>,
|
||||
pub errors: Vec<Message>,
|
||||
}
|
||||
|
||||
impl LayoutAttempt {
|
||||
@@ -211,10 +212,10 @@ pub struct ProtectionProfile {
|
||||
/// 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>,
|
||||
pub warnings: Vec<Message>,
|
||||
/// Unresolved failures: rejected/failed candidates when no route was
|
||||
/// accepted, or fatal findings on an accepted image. Empty when none.
|
||||
pub errors: Vec<String>,
|
||||
pub errors: Vec<Message>,
|
||||
}
|
||||
|
||||
impl ProtectionProfile {
|
||||
@@ -234,11 +235,11 @@ impl ProtectionProfile {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn push_warning(&mut self, message: impl Into<String>) {
|
||||
pub fn push_warning(&mut self, message: impl Into<Message>) {
|
||||
self.warnings.push(message.into());
|
||||
}
|
||||
|
||||
pub fn push_error(&mut self, message: impl Into<String>) {
|
||||
pub fn push_error(&mut self, message: impl Into<Message>) {
|
||||
self.errors.push(message.into());
|
||||
}
|
||||
|
||||
@@ -269,8 +270,8 @@ impl ProtectionProfile {
|
||||
&mut self,
|
||||
layout: LayoutKind,
|
||||
outcome: AttemptOutcome,
|
||||
warnings: Vec<String>,
|
||||
errors: Vec<String>,
|
||||
warnings: Vec<Message>,
|
||||
errors: Vec<Message>,
|
||||
) -> &mut LayoutAttempt {
|
||||
if self.attempt_mut(layout).is_none() {
|
||||
self.candidates.push(LayoutAttempt::not_attempted(layout));
|
||||
@@ -312,7 +313,7 @@ fn validation_status(report: &IntegrityReport) -> ValidationStatus {
|
||||
}
|
||||
}
|
||||
|
||||
fn messages(report: &IntegrityReport, severity: IntegritySeverity) -> Vec<String> {
|
||||
fn messages(report: &IntegrityReport, severity: IntegritySeverity) -> Vec<Message> {
|
||||
report
|
||||
.findings
|
||||
.iter()
|
||||
@@ -330,13 +331,13 @@ mod tests {
|
||||
IntegrityReport {
|
||||
issues: findings
|
||||
.iter()
|
||||
.map(|(_, issue)| (*issue).to_owned())
|
||||
.map(|(_, issue)| Message::raw(issue.to_string()))
|
||||
.collect(),
|
||||
findings: findings
|
||||
.iter()
|
||||
.map(|(severity, message)| IntegrityFinding {
|
||||
severity: *severity,
|
||||
message: (*message).to_owned(),
|
||||
message: Message::raw(message.to_string()),
|
||||
})
|
||||
.collect(),
|
||||
}
|
||||
@@ -393,7 +394,7 @@ mod tests {
|
||||
LayoutKind::Dll,
|
||||
AttemptOutcome::Rejected,
|
||||
Vec::new(),
|
||||
vec!["bad".to_owned()],
|
||||
vec![Message::raw("bad")],
|
||||
);
|
||||
profile.record_attempt(
|
||||
LayoutKind::ExeStyle,
|
||||
|
||||
@@ -0,0 +1,154 @@
|
||||
//! Verbose progress from the recovery pipelines.
|
||||
//!
|
||||
//! With `verbose` on, a pipeline reports each step and its technical detail
|
||||
//! lines here instead of printing them. A front end installs a sink for its
|
||||
//! thread with [`with_sink`] and receives them as [`Event`]s. Without a sink
|
||||
//! they print as they always have: Windows pipelines to stdout, the Android
|
||||
//! pipeline to stderr, step titles in the process language
|
||||
//! ([`senbei_i18n::current`]). Detail lines are technical and stay English.
|
||||
|
||||
use std::cell::RefCell;
|
||||
use std::fmt;
|
||||
|
||||
use senbei_i18n::{Localize, Step};
|
||||
|
||||
/// One verbose progress event.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum Event {
|
||||
/// A pipeline step. `position` is `(n, total)` for the numbered Windows
|
||||
/// steps and `None` for the Android stages.
|
||||
Step {
|
||||
step: Step,
|
||||
position: Option<(u8, u8)>,
|
||||
},
|
||||
/// A technical detail line in English, with its leading indentation.
|
||||
Detail(String),
|
||||
}
|
||||
|
||||
type Sink = Box<dyn FnMut(&Event)>;
|
||||
|
||||
thread_local! {
|
||||
static SINK: RefCell<Option<Sink>> = const { RefCell::new(None) };
|
||||
}
|
||||
|
||||
/// Send this thread's progress events to `sink` while `f` runs.
|
||||
///
|
||||
/// The previous sink, if any, is restored afterwards, also on panic.
|
||||
/// Recovery runs on the calling thread, so events from parallel helpers are
|
||||
/// never lost; the pipelines report only from the thread that called them.
|
||||
pub fn with_sink<R>(sink: impl FnMut(&Event) + 'static, f: impl FnOnce() -> R) -> R {
|
||||
struct Restore(Option<Sink>);
|
||||
impl Drop for Restore {
|
||||
fn drop(&mut self) {
|
||||
let previous = self.0.take();
|
||||
SINK.with(|slot| *slot.borrow_mut() = previous);
|
||||
}
|
||||
}
|
||||
let previous = SINK.with(|slot| slot.borrow_mut().replace(Box::new(sink)));
|
||||
let _restore = Restore(previous);
|
||||
f()
|
||||
}
|
||||
|
||||
/// Deliver `event` to this thread's sink. False when none is installed, in
|
||||
/// which case the caller prints the line itself.
|
||||
pub fn emit(event: &Event) -> bool {
|
||||
SINK.with(|slot| match slot.borrow_mut().as_mut() {
|
||||
Some(sink) => {
|
||||
sink(event);
|
||||
true
|
||||
}
|
||||
None => false,
|
||||
})
|
||||
}
|
||||
|
||||
/// A numbered Windows pipeline step.
|
||||
pub(crate) fn step(n: u8, total: u8, step: Step) {
|
||||
let event = Event::Step {
|
||||
step,
|
||||
position: Some((n, total)),
|
||||
};
|
||||
if !emit(&event)
|
||||
&& let Event::Step { step, .. } = &event
|
||||
{
|
||||
println!("[{n}/{total}] {}", step.localize(senbei_i18n::current()));
|
||||
}
|
||||
}
|
||||
|
||||
/// A Windows detail line.
|
||||
pub(crate) fn detail(args: fmt::Arguments<'_>) {
|
||||
if !emit(&Event::Detail(args.to_string())) {
|
||||
println!("{args}");
|
||||
}
|
||||
}
|
||||
|
||||
/// An Android pipeline stage.
|
||||
pub(crate) fn stage(step: Step) {
|
||||
let event = Event::Step {
|
||||
step,
|
||||
position: None,
|
||||
};
|
||||
if !emit(&event)
|
||||
&& let Event::Step { step, .. } = &event
|
||||
{
|
||||
eprintln!("{}", step.localize(senbei_i18n::current()));
|
||||
}
|
||||
}
|
||||
|
||||
/// An Android detail line.
|
||||
pub(crate) fn detail_err(args: fmt::Arguments<'_>) {
|
||||
if !emit(&Event::Detail(args.to_string())) {
|
||||
eprintln!("{args}");
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
#[test]
|
||||
fn a_sink_receives_events_and_is_removed_afterwards() {
|
||||
let seen = Arc::new(Mutex::new(Vec::new()));
|
||||
let sink_seen = Arc::clone(&seen);
|
||||
with_sink(
|
||||
move |event| sink_seen.lock().unwrap().push(event.clone()),
|
||||
|| {
|
||||
step(1, 9, Step::DecryptHeader);
|
||||
detail(format_args!(" info[0] key = 0x{:08X}", 0x1234));
|
||||
stage(Step::AndroidPrimary);
|
||||
},
|
||||
);
|
||||
assert_eq!(
|
||||
*seen.lock().unwrap(),
|
||||
[
|
||||
Event::Step {
|
||||
step: Step::DecryptHeader,
|
||||
position: Some((1, 9)),
|
||||
},
|
||||
Event::Detail(" info[0] key = 0x00001234".to_owned()),
|
||||
Event::Step {
|
||||
step: Step::AndroidPrimary,
|
||||
position: None,
|
||||
},
|
||||
]
|
||||
);
|
||||
assert!(!emit(&Event::Detail(String::new())));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nested_sinks_restore_the_outer_one_even_after_a_panic() {
|
||||
let outer = Arc::new(Mutex::new(0));
|
||||
let counted = Arc::clone(&outer);
|
||||
with_sink(
|
||||
move |_| *counted.lock().unwrap() += 1,
|
||||
|| {
|
||||
let failed = std::panic::catch_unwind(|| {
|
||||
with_sink(|_| {}, || panic!("synthetic unwind"));
|
||||
});
|
||||
assert!(failed.is_err());
|
||||
detail(format_args!("after"));
|
||||
},
|
||||
);
|
||||
assert_eq!(*outer.lock().unwrap(), 1);
|
||||
}
|
||||
}
|
||||
@@ -20,6 +20,7 @@ use super::super::{
|
||||
};
|
||||
use senbei_crypto::bytecode::{Op, OpsLut, generate};
|
||||
use senbei_crypto::primitives::{self, *};
|
||||
use senbei_i18n::Step;
|
||||
|
||||
/// Per-code-block index for trace events. The four blocks share one research
|
||||
/// stage, so an explicit index keeps their events orderable.
|
||||
@@ -627,13 +628,31 @@ fn unpack_dll_inner(input: &[u8], verbose: bool) -> Result<Vec<u8>, UnpackError>
|
||||
);
|
||||
}
|
||||
if verbose {
|
||||
println!("[1/9] Initializing keys...");
|
||||
println!(" keys[0] key = 0x{:08X}", keys[0] as u32);
|
||||
println!(" keys[1] signature = 0x{:08X}", keys[1] as u32);
|
||||
println!(" keys[3] base = 0x{:08X}", keys[3] as u32);
|
||||
println!(" keys[4] src_off = 0x{:08X}", keys[4] as u32);
|
||||
println!(" keys[5] size = 0x{:08X}", keys[5] as u32);
|
||||
println!(" keys[6] anchor = 0x{:08X}", keys[6] as u32);
|
||||
crate::progress::step(1, 9, Step::InitKeys);
|
||||
crate::progress::detail(format_args!(
|
||||
" keys[0] key = 0x{:08X}",
|
||||
keys[0] as u32
|
||||
));
|
||||
crate::progress::detail(format_args!(
|
||||
" keys[1] signature = 0x{:08X}",
|
||||
keys[1] as u32
|
||||
));
|
||||
crate::progress::detail(format_args!(
|
||||
" keys[3] base = 0x{:08X}",
|
||||
keys[3] as u32
|
||||
));
|
||||
crate::progress::detail(format_args!(
|
||||
" keys[4] src_off = 0x{:08X}",
|
||||
keys[4] as u32
|
||||
));
|
||||
crate::progress::detail(format_args!(
|
||||
" keys[5] size = 0x{:08X}",
|
||||
keys[5] as u32
|
||||
));
|
||||
crate::progress::detail(format_args!(
|
||||
" keys[6] anchor = 0x{:08X}",
|
||||
keys[6] as u32
|
||||
));
|
||||
}
|
||||
|
||||
if !super::super::is_supported_magic(keys[1] as u32) {
|
||||
@@ -706,9 +725,15 @@ fn unpack_dll_inner(input: &[u8], verbose: bool) -> Result<Vec<u8>, UnpackError>
|
||||
);
|
||||
}
|
||||
if verbose {
|
||||
println!("[2/9] Decrypting key table...");
|
||||
println!(" size_of_image = 0x{:08X}", size_of_image as u32);
|
||||
println!(" base_offset = 0x{:08X}", base_offset as u32);
|
||||
crate::progress::step(2, 9, Step::DecryptKeyTable);
|
||||
crate::progress::detail(format_args!(
|
||||
" size_of_image = 0x{:08X}",
|
||||
size_of_image as u32
|
||||
));
|
||||
crate::progress::detail(format_args!(
|
||||
" base_offset = 0x{:08X}",
|
||||
base_offset as u32
|
||||
));
|
||||
}
|
||||
|
||||
// DecryptKeyTable.
|
||||
@@ -805,10 +830,19 @@ fn unpack_dll_inner(input: &[u8], verbose: bool) -> Result<Vec<u8>, UnpackError>
|
||||
research::emit_u32(ResearchStage::DllStages, "descriptor_shift", 21);
|
||||
}
|
||||
if verbose {
|
||||
println!("[3/9] Decrypting primary descriptor...");
|
||||
println!(" xor_accumulator = 0x{:08X}", xor_accumulator);
|
||||
println!(" checksum1 = 0x{:08X}", checksum1 as u32);
|
||||
println!(" decrypted_addr1 = 0x{:08X}", decrypted_addr1 as u32);
|
||||
crate::progress::step(3, 9, Step::DecryptPrimary);
|
||||
crate::progress::detail(format_args!(
|
||||
" xor_accumulator = 0x{:08X}",
|
||||
xor_accumulator
|
||||
));
|
||||
crate::progress::detail(format_args!(
|
||||
" checksum1 = 0x{:08X}",
|
||||
checksum1 as u32
|
||||
));
|
||||
crate::progress::detail(format_args!(
|
||||
" decrypted_addr1 = 0x{:08X}",
|
||||
decrypted_addr1 as u32
|
||||
));
|
||||
}
|
||||
let primary_end = decrypted_addr1.checked_add(3856);
|
||||
if decrypted_addr1 < keys[3]
|
||||
@@ -939,15 +973,15 @@ fn unpack_dll_inner(input: &[u8], verbose: bool) -> Result<Vec<u8>, UnpackError>
|
||||
);
|
||||
}
|
||||
if verbose {
|
||||
println!("[4/9] Processing relocations & decomp params...");
|
||||
println!(" addr2 = 0x{:08X}", addr2 as u32);
|
||||
println!(
|
||||
crate::progress::step(4, 9, Step::RelocsParams);
|
||||
crate::progress::detail(format_args!(" addr2 = 0x{:08X}", addr2 as u32));
|
||||
crate::progress::detail(format_args!(
|
||||
" decomp_params = [0x{:08X}, 0x{:08X}, 0x{:08X}, 0x{:08X}]",
|
||||
decomp_params[0] as u32,
|
||||
decomp_params[1] as u32,
|
||||
decomp_params[2] as u32,
|
||||
decomp_params[3] as u32
|
||||
);
|
||||
));
|
||||
}
|
||||
|
||||
let checksum2 = calculate_checksum(&out, (keys[6] + 5640) as u32) as i32;
|
||||
@@ -981,9 +1015,9 @@ fn unpack_dll_inner(input: &[u8], verbose: bool) -> Result<Vec<u8>, UnpackError>
|
||||
|
||||
let addr3b = get_i32(&out, decrypted_addr1 + 3728);
|
||||
if verbose {
|
||||
println!("[5/9] Decrypting code block 1 (addr3)...");
|
||||
println!(" checksum2 = 0x{:08X}", checksum2 as u32);
|
||||
println!(" addr3b = 0x{:08X}", addr3b as u32);
|
||||
crate::progress::step(5, 9, Step::DecryptBlock1);
|
||||
crate::progress::detail(format_args!(" checksum2 = 0x{:08X}", checksum2 as u32));
|
||||
crate::progress::detail(format_args!(" addr3b = 0x{:08X}", addr3b as u32));
|
||||
}
|
||||
|
||||
let crc_data_offset = decrypted_addr1 + 3488;
|
||||
@@ -1046,10 +1080,10 @@ fn unpack_dll_inner(input: &[u8], verbose: bool) -> Result<Vec<u8>, UnpackError>
|
||||
research::emit_u32(ResearchStage::DllStages, "crc_val", crc_val as u32);
|
||||
research::emit_u32(ResearchStage::DllStages, "checksum3", checksum3 as u32);
|
||||
if verbose {
|
||||
println!("[6/9] Decrypting code blocks 2-3 (addr3b, addr4)...");
|
||||
println!(" crc_val = 0x{:08X}", crc_val as u32);
|
||||
println!(" checksum3 = 0x{:08X}", checksum3 as u32);
|
||||
println!(" addr4 = 0x{:08X}", addr4 as u32);
|
||||
crate::progress::step(6, 9, Step::DecryptBlocks2To3);
|
||||
crate::progress::detail(format_args!(" crc_val = 0x{:08X}", crc_val as u32));
|
||||
crate::progress::detail(format_args!(" checksum3 = 0x{:08X}", checksum3 as u32));
|
||||
crate::progress::detail(format_args!(" addr4 = 0x{:08X}", addr4 as u32));
|
||||
}
|
||||
|
||||
let checksum4 = calculate_checksum(&out, (decrypted_addr1 + 3472) as u32) as i32;
|
||||
@@ -1108,9 +1142,9 @@ fn unpack_dll_inner(input: &[u8], verbose: bool) -> Result<Vec<u8>, UnpackError>
|
||||
DecompressionStage::DllCodeBlock4,
|
||||
)?;
|
||||
if verbose {
|
||||
println!("[7/9] Decrypting code block 4 (addr5)...");
|
||||
println!(" checksum4 = 0x{:08X}", checksum4 as u32);
|
||||
println!(" addr5 = 0x{:08X}", addr5 as u32);
|
||||
crate::progress::step(7, 9, Step::DecryptBlock4);
|
||||
crate::progress::detail(format_args!(" checksum4 = 0x{:08X}", checksum4 as u32));
|
||||
crate::progress::detail(format_args!(" addr5 = 0x{:08X}", addr5 as u32));
|
||||
}
|
||||
|
||||
let metadata_offset = addr5 + 12312;
|
||||
@@ -1188,15 +1222,15 @@ fn unpack_dll_inner(input: &[u8], verbose: bool) -> Result<Vec<u8>, UnpackError>
|
||||
trace_offset(section_image_base),
|
||||
);
|
||||
if verbose {
|
||||
println!("[8/9] Decrypting & decompressing sections...");
|
||||
println!(
|
||||
crate::progress::step(8, 9, Step::DllSections);
|
||||
crate::progress::detail(format_args!(
|
||||
" section_image_base = 0x{:08X}",
|
||||
section_image_base as u32
|
||||
);
|
||||
println!(
|
||||
));
|
||||
crate::progress::detail(format_args!(
|
||||
" section_data_offset = 0x{:08X}",
|
||||
section_data_offset as u32
|
||||
);
|
||||
));
|
||||
}
|
||||
|
||||
// Managed-only pre-fill of .text (Task 3.2). No-op for native (clr_rva == 0).
|
||||
@@ -1278,7 +1312,7 @@ fn unpack_dll_inner(input: &[u8], verbose: bool) -> Result<Vec<u8>, UnpackError>
|
||||
|
||||
out[..4096].copy_from_slice(&file_data[..4096]);
|
||||
if verbose {
|
||||
println!("[9/9] Fixing up PE header & section table...");
|
||||
crate::progress::step(9, 9, Step::FixHeaders);
|
||||
}
|
||||
|
||||
let section_header_base = get_u16(file_data, (pe_offset + 20) as u32) as i32 + pe_offset;
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
pub use senbei_crypto::{BufferOperation, DecompressionFailure};
|
||||
use senbei_i18n::{Message, Msg};
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum DecompressionStage {
|
||||
@@ -225,7 +226,7 @@ pub enum UnpackError {
|
||||
},
|
||||
|
||||
#[error("structurally invalid layout candidate: {}", issues.join("; "))]
|
||||
InvalidLayoutCandidate { issues: Vec<String> },
|
||||
InvalidLayoutCandidate { issues: Vec<Message> },
|
||||
|
||||
#[error(
|
||||
"PE32 second-stage range is invalid (offset {offset}, size {size}, image length {image_len})"
|
||||
@@ -254,6 +255,45 @@ pub enum UnpackError {
|
||||
},
|
||||
}
|
||||
|
||||
impl UnpackError {
|
||||
/// This error as a report message: the English it displays, with the
|
||||
/// catalog entry a front end translates.
|
||||
///
|
||||
/// Errors a user can act on have their own entry. Internal decode
|
||||
/// failures share one summary entry and keep their specific English as
|
||||
/// the recorded text.
|
||||
pub fn message(&self) -> Message {
|
||||
let msg = match self {
|
||||
Self::CompanionMissing => Msg::CompanionMissing,
|
||||
Self::CompanionMismatch => Msg::CompanionMismatch,
|
||||
Self::InputTooShort { actual, required } => Msg::InputTooShort {
|
||||
actual: *actual,
|
||||
required: *required,
|
||||
},
|
||||
Self::NotCrackProof => Msg::NotProtected,
|
||||
Self::InvalidPeOffset { offset, input_len } => Msg::InvalidPeOffset {
|
||||
offset: *offset,
|
||||
input_len: *input_len,
|
||||
},
|
||||
Self::UnsupportedDllPeMagic { found } => Msg::DllNeedsPe32Plus { found: *found },
|
||||
Self::Stage5MarkerNotFound => Msg::LayoutUnsupported,
|
||||
Self::InternalPanic {
|
||||
message,
|
||||
file,
|
||||
line,
|
||||
column,
|
||||
} => Msg::InternalPanic {
|
||||
file: file.clone(),
|
||||
line: *line,
|
||||
column: *column,
|
||||
message: message.clone(),
|
||||
},
|
||||
_ => Msg::DecodeFailed,
|
||||
};
|
||||
Message::with_text(msg, self.to_string())
|
||||
}
|
||||
}
|
||||
|
||||
impl From<senbei_crypto::Error> for UnpackError {
|
||||
fn from(error: senbei_crypto::Error) -> Self {
|
||||
match error {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
use senbei_crypto::bytecode::{Op, OpsLut, generate};
|
||||
use senbei_crypto::primitives;
|
||||
use senbei_crypto::primitives::*;
|
||||
use senbei_i18n::Step;
|
||||
|
||||
use super::super::error::*;
|
||||
use super::super::layout::{self, *};
|
||||
@@ -362,15 +363,15 @@ impl<'a> Unpacker<'a> {
|
||||
0x1004,
|
||||
);
|
||||
if verbose {
|
||||
println!("[1/9] Decrypting file header...");
|
||||
println!(" info[0] key = 0x{:08X}", u.info[0]);
|
||||
println!(" info[1] signature = 0x{:08X}", u.info[1]);
|
||||
println!(" info[2] = 0x{:08X}", u.info[2]);
|
||||
println!(" info[3] base = 0x{:08X}", u.info[3]);
|
||||
println!(" info[4] src_off = 0x{:08X}", u.info[4]);
|
||||
println!(" info[5] total_size = 0x{:08X}", u.info[5]);
|
||||
println!(" info[6] end_mark = 0x{:08X}", u.info[6]);
|
||||
println!(" info[7] = 0x{:08X}", u.info[7]);
|
||||
crate::progress::step(1, 9, Step::DecryptHeader);
|
||||
crate::progress::detail(format_args!(" info[0] key = 0x{:08X}", u.info[0]));
|
||||
crate::progress::detail(format_args!(" info[1] signature = 0x{:08X}", u.info[1]));
|
||||
crate::progress::detail(format_args!(" info[2] = 0x{:08X}", u.info[2]));
|
||||
crate::progress::detail(format_args!(" info[3] base = 0x{:08X}", u.info[3]));
|
||||
crate::progress::detail(format_args!(" info[4] src_off = 0x{:08X}", u.info[4]));
|
||||
crate::progress::detail(format_args!(" info[5] total_size = 0x{:08X}", u.info[5]));
|
||||
crate::progress::detail(format_args!(" info[6] end_mark = 0x{:08X}", u.info[6]));
|
||||
crate::progress::detail(format_args!(" info[7] = 0x{:08X}", u.info[7]));
|
||||
}
|
||||
if !super::super::is_supported_magic(u.info[1]) {
|
||||
return Err(UnpackError::HeaderMagicMismatch { found: u.info[1] });
|
||||
@@ -409,7 +410,7 @@ impl<'a> Unpacker<'a> {
|
||||
u.info[5] as u64,
|
||||
);
|
||||
if verbose {
|
||||
println!("[2/9] Decrypting payload...");
|
||||
crate::progress::step(2, 9, Step::DecryptPayload);
|
||||
}
|
||||
let pe32_table = u.load_payload();
|
||||
research::emit_u32(ResearchStage::Payload, "prefix_length", u.decrypt_size);
|
||||
@@ -505,8 +506,8 @@ impl<'a> Unpacker<'a> {
|
||||
);
|
||||
|
||||
if verbose {
|
||||
println!(" anchor = 0x{anchor:08X}");
|
||||
println!(" anchor layout offset = +0x{anchor_extra:X}");
|
||||
crate::progress::detail(format_args!(" anchor = 0x{anchor:08X}"));
|
||||
crate::progress::detail(format_args!(" anchor layout offset = +0x{anchor_extra:X}"));
|
||||
}
|
||||
|
||||
let p1 = get_u32(&u.decompressed, anchor.wrapping_add(8));
|
||||
@@ -555,14 +556,16 @@ impl<'a> Unpacker<'a> {
|
||||
stage1_descriptor.to_vec(),
|
||||
);
|
||||
if verbose {
|
||||
println!("[3/9] Locating config layout...");
|
||||
println!(" stage1 = 0x{:08X}", stage1);
|
||||
println!(" stage1_len = 0x{stage1_len:08X}");
|
||||
println!(
|
||||
crate::progress::step(3, 9, Step::LocateConfig);
|
||||
crate::progress::detail(format_args!(" stage1 = 0x{:08X}", stage1));
|
||||
crate::progress::detail(format_args!(" stage1_len = 0x{stage1_len:08X}"));
|
||||
crate::progress::detail(format_args!(
|
||||
" stage1 descriptor = [0x{:08X}, 0x{:08X}]",
|
||||
stage1_descriptor[0], stage1_descriptor[1]
|
||||
);
|
||||
println!(" stage1 key = xor 0x{xor_acc:08X} ^ chk 0x{chk1:08X} ^ val 0x{v:08X}");
|
||||
));
|
||||
crate::progress::detail(format_args!(
|
||||
" stage1 key = xor 0x{xor_acc:08X} ^ chk 0x{chk1:08X} ^ val 0x{v:08X}"
|
||||
));
|
||||
}
|
||||
|
||||
// Field offsets inside stage1 vary between CrackProof versions. Locate
|
||||
@@ -653,11 +656,13 @@ impl<'a> Unpacker<'a> {
|
||||
chk_src_start,
|
||||
);
|
||||
if verbose {
|
||||
println!("[4/9] Decrypting stage2...");
|
||||
println!(" stage2 = 0x{:08X}", stage2);
|
||||
println!(" stage2_off = 0x{stage2_off:04X}");
|
||||
println!(" checksum table = stage1+0x{chk_src_start:04X}");
|
||||
println!(" stage2 key = 0x{key2:08X}");
|
||||
crate::progress::step(4, 9, Step::DecryptStage2);
|
||||
crate::progress::detail(format_args!(" stage2 = 0x{:08X}", stage2));
|
||||
crate::progress::detail(format_args!(" stage2_off = 0x{stage2_off:04X}"));
|
||||
crate::progress::detail(format_args!(
|
||||
" checksum table = stage1+0x{chk_src_start:04X}"
|
||||
));
|
||||
crate::progress::detail(format_args!(" stage2 key = 0x{key2:08X}"));
|
||||
}
|
||||
|
||||
// The stage2 head/walk2 tables shift between CrackProof versions. The 4-entry
|
||||
@@ -690,17 +695,21 @@ impl<'a> Unpacker<'a> {
|
||||
let head_off = table_start.wrapping_add(32);
|
||||
let walk2_off = head_off.wrapping_sub(88);
|
||||
if verbose {
|
||||
println!(" operation table = stage2+0x{table_start:04X}");
|
||||
println!(" head/walk = +0x{head_off:04X}/+0x{walk2_off:04X}");
|
||||
crate::progress::detail(format_args!(
|
||||
" operation table = stage2+0x{table_start:04X}"
|
||||
));
|
||||
crate::progress::detail(format_args!(
|
||||
" head/walk = +0x{head_off:04X}/+0x{walk2_off:04X}"
|
||||
));
|
||||
for index in 0..2u32 {
|
||||
let entry = stage2.wrapping_add(head_off + index * 16);
|
||||
println!(
|
||||
crate::progress::detail(format_args!(
|
||||
" operation[{index}] = [0x{:08X}, 0x{:08X}, 0x{:08X}, 0x{:08X}]",
|
||||
get_u32(&u.decompressed, entry),
|
||||
get_u32(&u.decompressed, entry.wrapping_add(4)),
|
||||
get_u32(&u.decompressed, entry.wrapping_add(8)),
|
||||
get_u32(&u.decompressed, entry.wrapping_add(12)),
|
||||
);
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -751,10 +760,10 @@ impl<'a> Unpacker<'a> {
|
||||
u.key_offsets.to_vec(),
|
||||
);
|
||||
if verbose {
|
||||
println!(
|
||||
crate::progress::detail(format_args!(
|
||||
" key offsets = [0x{:08X}, 0x{:08X}, 0x{:08X}, 0x{:08X}]",
|
||||
u.key_offsets[0], u.key_offsets[1], u.key_offsets[2], u.key_offsets[3]
|
||||
);
|
||||
));
|
||||
}
|
||||
|
||||
let chk2 = u.calculate_checksum(anchor.wrapping_add(48 + anchor_extra));
|
||||
@@ -779,13 +788,15 @@ impl<'a> Unpacker<'a> {
|
||||
let stage3_dest = get_u32(&u.decompressed, at1.wrapping_add(8));
|
||||
let stage3_dlen = get_u32(&u.decompressed, at1.wrapping_add(12));
|
||||
if verbose {
|
||||
println!("[5/9] Decrypting stages 3-5...");
|
||||
println!(" stage3 = 0x{:08X}", stage3_field);
|
||||
println!(
|
||||
crate::progress::step(5, 9, Step::DecryptStages3To5);
|
||||
crate::progress::detail(format_args!(" stage3 = 0x{:08X}", stage3_field));
|
||||
crate::progress::detail(format_args!(
|
||||
" stage3 descriptor = [0x{stage3_field:08X}, 0x{stage3_slen:08X}, 0x{stage3_dest:08X}, 0x{stage3_dlen:08X}]"
|
||||
);
|
||||
println!(" stage3 key = xor 0x{xor_acc:08X} ^ chk 0x{chk2:08X} ^ val 0x{accum:08X}");
|
||||
println!(" stage3 accum seed = 0x{accum_seed:08X}");
|
||||
));
|
||||
crate::progress::detail(format_args!(
|
||||
" stage3 key = xor 0x{xor_acc:08X} ^ chk 0x{chk2:08X} ^ val 0x{accum:08X}"
|
||||
));
|
||||
crate::progress::detail(format_args!(" stage3 accum seed = 0x{accum_seed:08X}"));
|
||||
}
|
||||
let stage3_key = xor_acc ^ chk2 ^ accum;
|
||||
research::emit_range(
|
||||
@@ -858,7 +869,9 @@ impl<'a> Unpacker<'a> {
|
||||
rounds,
|
||||
);
|
||||
if verbose {
|
||||
println!(" selected stage3 accumulator rounds = {rounds}");
|
||||
crate::progress::detail(format_args!(
|
||||
" selected stage3 accumulator rounds = {rounds}"
|
||||
));
|
||||
}
|
||||
} else {
|
||||
restore_stage3(&mut u.decompressed);
|
||||
@@ -873,7 +886,7 @@ impl<'a> Unpacker<'a> {
|
||||
let stage3b_field = get_u32(&u.decompressed, at2);
|
||||
let stage3b_dlen = get_u32(&u.decompressed, at2.wrapping_add(12));
|
||||
if verbose {
|
||||
println!(" stage3b = 0x{:08X}", stage3b_field);
|
||||
crate::progress::detail(format_args!(" stage3b = 0x{:08X}", stage3b_field));
|
||||
}
|
||||
let chk3 = u.calculate_checksum(stage1.wrapping_add(chk_src_start.wrapping_add(24)));
|
||||
// v4_val lives at the end of stage3, immediately following `C3 CC CC CC`
|
||||
@@ -903,7 +916,7 @@ impl<'a> Unpacker<'a> {
|
||||
let stage4_field = get_u32(&u.decompressed, at3);
|
||||
let stage4_dlen = get_u32(&u.decompressed, at3.wrapping_add(12));
|
||||
if verbose {
|
||||
println!(" stage4 = 0x{:08X}", stage4_field);
|
||||
crate::progress::detail(format_args!(" stage4 = 0x{:08X}", stage4_field));
|
||||
}
|
||||
if let Err(reason) = u.decrypt_and_decompress_data(at3, xor_acc ^ chk4 ^ v5_val, None) {
|
||||
return Err(UnpackError::StageDecompressionFailed {
|
||||
@@ -988,12 +1001,14 @@ impl<'a> Unpacker<'a> {
|
||||
let stage5_dest = get_u32(&u.decompressed, at4.wrapping_add(8));
|
||||
let stage5_dlen = get_u32(&u.decompressed, at4.wrapping_add(12));
|
||||
if verbose {
|
||||
println!(" stage5 = 0x{:08X}", stage5_field);
|
||||
println!(
|
||||
crate::progress::detail(format_args!(" stage5 = 0x{:08X}", stage5_field));
|
||||
crate::progress::detail(format_args!(
|
||||
" stage5 descriptor = [0x{stage5_field:08X}, 0x{stage5_slen:08X}, 0x{stage5_dest:08X}, 0x{stage5_dlen:08X}]"
|
||||
);
|
||||
println!(" stage5 bytecode = 0x{data_offset:08X}");
|
||||
println!(" stage5 accumulator seed = 0x{accum2_seed:08X} at 0x{v6:08X}");
|
||||
));
|
||||
crate::progress::detail(format_args!(" stage5 bytecode = 0x{data_offset:08X}"));
|
||||
crate::progress::detail(format_args!(
|
||||
" stage5 accumulator seed = 0x{accum2_seed:08X} at 0x{v6:08X}"
|
||||
));
|
||||
}
|
||||
let stage5_lo = stage5_field.min(stage5_dest) as usize;
|
||||
let stage5_hi = stage5_field
|
||||
@@ -1047,7 +1062,9 @@ impl<'a> Unpacker<'a> {
|
||||
stage5_dlen as u64,
|
||||
);
|
||||
if verbose {
|
||||
println!(" selected stage5 accumulator rounds = {selected_rounds}");
|
||||
crate::progress::detail(format_args!(
|
||||
" selected stage5 accumulator rounds = {selected_rounds}"
|
||||
));
|
||||
}
|
||||
|
||||
// Inside stage5, the loader stores a table of (ptr, size) pairs at a
|
||||
@@ -1185,10 +1202,10 @@ impl<'a> Unpacker<'a> {
|
||||
Ok(next) => chain_crc = next,
|
||||
Err(UnpackError::ExeChecksumRangeOutOfBounds { .. }) => {
|
||||
if verbose {
|
||||
println!(
|
||||
crate::progress::detail(format_args!(
|
||||
" checksum chain terminates at 0x{:08X}: descriptor payload is outside protected input",
|
||||
walk3.wrapping_sub(16)
|
||||
);
|
||||
));
|
||||
}
|
||||
break;
|
||||
}
|
||||
@@ -1200,18 +1217,18 @@ impl<'a> Unpacker<'a> {
|
||||
}
|
||||
}
|
||||
if verbose {
|
||||
println!("[6/9] Decrypting section data...");
|
||||
println!(
|
||||
crate::progress::step(6, 9, Step::DecryptSections);
|
||||
crate::progress::detail(format_args!(
|
||||
" integrity = 0x{:08X}",
|
||||
get_u32(u.file_data, 56).wrapping_add(1985229329)
|
||||
);
|
||||
println!(" chain_crc = 0x{:08X}", chain_crc);
|
||||
));
|
||||
crate::progress::detail(format_args!(" chain_crc = 0x{:08X}", chain_crc));
|
||||
}
|
||||
for (addr, bytes) in walk3_backups {
|
||||
u.decompressed[addr..addr + 16].copy_from_slice(&bytes);
|
||||
}
|
||||
} else if verbose {
|
||||
println!("[6/9] Decrypting section data (new layout)...");
|
||||
crate::progress::step(6, 9, Step::DecryptSectionsNewLayout);
|
||||
}
|
||||
|
||||
let data_offset2 = bc2_off;
|
||||
@@ -1255,7 +1272,7 @@ impl<'a> Unpacker<'a> {
|
||||
|
||||
let at6 = walk4_slot;
|
||||
if verbose {
|
||||
println!("[7/9] Loading and decompressing sections...");
|
||||
crate::progress::step(7, 9, Step::LoadSections);
|
||||
}
|
||||
let mut walk4 = get_u32(&u.decompressed, at6);
|
||||
// Pass 1 (sequential): the 16-byte descriptors are decrypted in a
|
||||
@@ -1402,7 +1419,7 @@ impl<'a> Unpacker<'a> {
|
||||
|
||||
let at7 = walk5_slot;
|
||||
if verbose {
|
||||
println!("[8/9] Decrypting import strings...");
|
||||
crate::progress::step(8, 9, Step::DecryptImports);
|
||||
}
|
||||
// walk5 is the old layout's encrypted import-name pointer table. The new
|
||||
// layout has no such table — imports are rebuilt from the PE Import
|
||||
@@ -1464,7 +1481,7 @@ impl<'a> Unpacker<'a> {
|
||||
} // end !new_layout (walk5)
|
||||
|
||||
if verbose {
|
||||
println!("[9/9] Reconstructing PE headers...");
|
||||
crate::progress::step(9, 9, Step::RebuildHeaders);
|
||||
}
|
||||
u.decompressed[..4096].copy_from_slice(&u.file_data[..4096]);
|
||||
let opt_hdr_size = get_u16(u.file_data, pe_off.wrapping_add(20));
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
use super::super::super::layout;
|
||||
use super::super::super::research::{self, AddressSpace, ResearchStage};
|
||||
use super::*;
|
||||
use senbei_i18n::Step;
|
||||
|
||||
/// Name of the dd8 formula the PE32 selector actually chose. `None` is the
|
||||
/// selector's skip verdict, not "did not run".
|
||||
@@ -209,8 +210,8 @@ impl<'a> Unpacker<'a> {
|
||||
tbl as u64,
|
||||
);
|
||||
if verbose {
|
||||
println!("[3/9] Locating config layout (PE32)...");
|
||||
println!(" tbl = 0x{:X}, compact = {}", tbl, compact);
|
||||
crate::progress::step(3, 9, Step::Pe32LocateConfig);
|
||||
crate::progress::detail(format_args!(" tbl = 0x{:X}, compact = {}", tbl, compact));
|
||||
}
|
||||
|
||||
// ---- Stage 3: SecondStage ----
|
||||
@@ -234,10 +235,10 @@ impl<'a> Unpacker<'a> {
|
||||
header_checksum,
|
||||
);
|
||||
if verbose {
|
||||
println!(
|
||||
crate::progress::detail(format_args!(
|
||||
" ss = 0x{:08X}, size = 0x{:X}, shift = 0x{:X}",
|
||||
ss, ss_size, ss_shift
|
||||
);
|
||||
));
|
||||
}
|
||||
|
||||
// ---- PE32 fixed offsets ----
|
||||
@@ -304,11 +305,11 @@ impl<'a> Unpacker<'a> {
|
||||
info_table as u64,
|
||||
);
|
||||
if verbose {
|
||||
println!("[4/9] Decrypting stages (PE32)...");
|
||||
println!(
|
||||
crate::progress::step(4, 9, Step::Pe32Stages);
|
||||
crate::progress::detail(format_args!(
|
||||
" thirdStage start = 0x{:X}, infoTable = 0x{:X}",
|
||||
ts, info_table
|
||||
);
|
||||
));
|
||||
}
|
||||
|
||||
// ---- Process infoTable ----
|
||||
@@ -372,7 +373,9 @@ impl<'a> Unpacker<'a> {
|
||||
forth_key_rounds,
|
||||
);
|
||||
if verbose {
|
||||
println!(" fourth-stage key rounds = {forth_key_rounds}");
|
||||
crate::progress::detail(format_args!(
|
||||
" fourth-stage key rounds = {forth_key_rounds}"
|
||||
));
|
||||
}
|
||||
let forth_addr = dp_base.wrapping_add(0x40);
|
||||
let fk = header_checksum ^ second_stage_cs ^ forth_stage_key;
|
||||
@@ -433,11 +436,11 @@ impl<'a> Unpacker<'a> {
|
||||
// ---- EighthStage ----
|
||||
let seven_start_actual = get_u32(&self.decompressed, seven_addr);
|
||||
if verbose {
|
||||
println!("[5/9] Decrypting eighthStage (PE32)...");
|
||||
println!(
|
||||
crate::progress::step(5, 9, Step::Pe32EighthStage);
|
||||
crate::progress::detail(format_args!(
|
||||
" sevenStart = 0x{:X}, sevenDsz = 0x{:X}",
|
||||
seven_start_actual, seven_dsz
|
||||
);
|
||||
));
|
||||
}
|
||||
// Locate the customDecryptor LFSR block (scan backward from middle, then
|
||||
// forward as fallback).
|
||||
@@ -470,7 +473,9 @@ impl<'a> Unpacker<'a> {
|
||||
let eighth_key_rounds =
|
||||
stage_key_rounds(&self.decompressed, dp_base.wrapping_add(0x80), 4)?;
|
||||
if verbose {
|
||||
println!(" eighth-stage key rounds = {eighth_key_rounds}");
|
||||
crate::progress::detail(format_args!(
|
||||
" eighth-stage key rounds = {eighth_key_rounds}"
|
||||
));
|
||||
}
|
||||
let eighth_addr = dp_base.wrapping_add(0xC0);
|
||||
let eighth_dsz = get_u32(&self.decompressed, eighth_addr.wrapping_add(12));
|
||||
@@ -568,10 +573,10 @@ impl<'a> Unpacker<'a> {
|
||||
);
|
||||
let eighth_start = get_u32(&self.decompressed, eighth_addr);
|
||||
if verbose {
|
||||
println!(
|
||||
crate::progress::detail(format_args!(
|
||||
" eighthStart = 0x{:08X}, dsz = 0x{:X}",
|
||||
eighth_start, eighth_dsz
|
||||
);
|
||||
));
|
||||
}
|
||||
|
||||
// ---- Final processing offsets (anchored on the eighthStage config cluster) ----
|
||||
@@ -637,10 +642,10 @@ impl<'a> Unpacker<'a> {
|
||||
}
|
||||
if let Some((dist, base)) = best {
|
||||
if verbose {
|
||||
println!(
|
||||
crate::progress::detail(format_args!(
|
||||
" pe32 cluster via fileCS (no 0x7679): base=+0x{:X} dist_info3=0x{:X}",
|
||||
base, dist
|
||||
);
|
||||
));
|
||||
}
|
||||
m = Some(base);
|
||||
}
|
||||
@@ -723,10 +728,10 @@ impl<'a> Unpacker<'a> {
|
||||
}
|
||||
if let Some(c) = chosen {
|
||||
if verbose {
|
||||
println!(
|
||||
crate::progress::detail(format_args!(
|
||||
" pe32 fileLFSR via trial-validate: +0x{:X} (expected +0x{:X}, considered {})",
|
||||
c, off_file_lfsr, considered
|
||||
);
|
||||
));
|
||||
}
|
||||
lfsr_off = c;
|
||||
} else {
|
||||
@@ -818,7 +823,7 @@ impl<'a> Unpacker<'a> {
|
||||
|
||||
// ---- File data decompression ----
|
||||
if verbose {
|
||||
println!("[6/9] Loading and decompressing file data (PE32)...");
|
||||
crate::progress::step(6, 9, Step::Pe32Load);
|
||||
}
|
||||
let compress_data_offset = (!get_u32(self.file_data, 0x1080)).wrapping_add(0x1000);
|
||||
let compressed_info_addr = eighth_start.wrapping_add(off_compressed_info);
|
||||
@@ -1026,9 +1031,12 @@ impl<'a> Unpacker<'a> {
|
||||
);
|
||||
if let Some(big) = selection {
|
||||
if verbose {
|
||||
println!(
|
||||
"[7/9] Decrypting .text (PE32 dd8, formula={})...",
|
||||
if big { "0x8000*(page+1)" } else { "page+1" }
|
||||
crate::progress::step(
|
||||
7,
|
||||
9,
|
||||
Step::Pe32Text {
|
||||
formula: if big { "0x8000*(page+1)" } else { "page+1" },
|
||||
},
|
||||
);
|
||||
}
|
||||
research::emit_text(
|
||||
@@ -1070,7 +1078,7 @@ impl<'a> Unpacker<'a> {
|
||||
}
|
||||
}
|
||||
} else if verbose {
|
||||
println!("[7/9] Skipping .text dd8 (already plaintext)...");
|
||||
crate::progress::step(7, 9, Step::Pe32TextSkip);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1249,14 +1257,17 @@ impl<'a> Unpacker<'a> {
|
||||
block = block.wrapping_add(block_size);
|
||||
}
|
||||
if verbose && rearmed > 0 {
|
||||
println!(" re-armed {} TLS field relocations", rearmed);
|
||||
crate::progress::detail(format_args!(
|
||||
" re-armed {} TLS field relocations",
|
||||
rearmed
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---- Import table (PE32, 4-byte thunks) ----
|
||||
if verbose {
|
||||
println!("[8/9] Decrypting import strings (PE32)...");
|
||||
crate::progress::step(8, 9, Step::Pe32Imports);
|
||||
}
|
||||
let import_table_addr = eighth_start.wrapping_add(off_import_table);
|
||||
let mut import_table_ptr = get_u32(&self.decompressed, import_table_addr);
|
||||
@@ -1361,7 +1372,7 @@ impl<'a> Unpacker<'a> {
|
||||
|
||||
// ---- Output transforms ----
|
||||
if verbose {
|
||||
println!("[9/9] Rebuilding PE file layout (PE32)...");
|
||||
crate::progress::step(9, 9, Step::Pe32Rebuild);
|
||||
}
|
||||
let mut out = std::mem::take(&mut self.decompressed);
|
||||
// kmiat import relocation is an EXE-only fixup: it discards the original
|
||||
|
||||
@@ -18,6 +18,8 @@
|
||||
//!
|
||||
//! All reads are bounds-checked; the check never panics on any input.
|
||||
|
||||
use senbei_i18n::{Message, Msg};
|
||||
|
||||
mod clr;
|
||||
mod directories;
|
||||
|
||||
@@ -48,7 +50,7 @@ pub enum IntegritySeverity {
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct IntegrityFinding {
|
||||
pub severity: IntegritySeverity,
|
||||
pub message: String,
|
||||
pub message: Message,
|
||||
}
|
||||
|
||||
/// Result of a static integrity check over an unpacked image.
|
||||
@@ -56,7 +58,7 @@ pub struct IntegrityFinding {
|
||||
pub struct IntegrityReport {
|
||||
/// Each entry describes one detected defect. Empty means no defect found.
|
||||
/// Order and wording match [`IntegrityReport::findings`].
|
||||
pub issues: Vec<String>,
|
||||
pub issues: Vec<Message>,
|
||||
/// The same defects as `issues`, each tagged fatal or warning.
|
||||
pub findings: Vec<IntegrityFinding>,
|
||||
}
|
||||
@@ -78,7 +80,7 @@ impl IntegrityReport {
|
||||
.any(|finding| finding.severity == IntegritySeverity::Fatal)
|
||||
}
|
||||
|
||||
fn push(&mut self, severity: IntegritySeverity, message: impl Into<String>) {
|
||||
fn push(&mut self, severity: IntegritySeverity, message: impl Into<Message>) {
|
||||
let message = message.into();
|
||||
self.issues.push(message.clone());
|
||||
self.findings.push(IntegrityFinding { severity, message });
|
||||
@@ -152,9 +154,10 @@ fn check_common_entry_branches(
|
||||
if !valid {
|
||||
report.push(
|
||||
IntegritySeverity::Fatal,
|
||||
format!(
|
||||
"entry point {name} target 0x{target:X} is outside executable sections (DD8 selection is likely wrong)"
|
||||
),
|
||||
Msg::EntryStubTargetOutsideCode {
|
||||
branch: name,
|
||||
target,
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -168,23 +171,20 @@ pub fn check(out: &[u8]) -> IntegrityReport {
|
||||
|
||||
// --- DOS + PE headers ---------------------------------------------------
|
||||
if rd_u16(out, 0) != Some(0x5A4D) {
|
||||
r.push(IntegritySeverity::Fatal, "missing 'MZ' DOS signature");
|
||||
r.push(IntegritySeverity::Fatal, Msg::MissingMz);
|
||||
return r; // nothing else is meaningful
|
||||
}
|
||||
let pe_off = match rd_u32(out, 0x3C) {
|
||||
Some(v) => v,
|
||||
None => {
|
||||
r.push(
|
||||
IntegritySeverity::Fatal,
|
||||
"truncated DOS header (no e_lfanew)",
|
||||
);
|
||||
r.push(IntegritySeverity::Fatal, Msg::TruncatedDosHeader);
|
||||
return r;
|
||||
}
|
||||
};
|
||||
if rd_u32(out, pe_off) != Some(0x0000_4550) {
|
||||
r.push(
|
||||
IntegritySeverity::Fatal,
|
||||
format!("missing 'PE\\0\\0' signature at 0x{pe_off:X}"),
|
||||
Msg::MissingPeSignature { offset: pe_off },
|
||||
);
|
||||
return r;
|
||||
}
|
||||
@@ -192,7 +192,7 @@ pub fn check(out: &[u8]) -> IntegrityReport {
|
||||
let num_sections = match rd_u16(out, pe_off.wrapping_add(6)) {
|
||||
Some(v) => v as u32,
|
||||
None => {
|
||||
r.push(IntegritySeverity::Fatal, "truncated COFF header");
|
||||
r.push(IntegritySeverity::Fatal, Msg::TruncatedCoffHeader);
|
||||
return r;
|
||||
}
|
||||
};
|
||||
@@ -200,7 +200,7 @@ pub fn check(out: &[u8]) -> IntegrityReport {
|
||||
let magic = match rd_u16(out, opt) {
|
||||
Some(v) => v,
|
||||
None => {
|
||||
r.push(IntegritySeverity::Fatal, "truncated optional header");
|
||||
r.push(IntegritySeverity::Fatal, Msg::TruncatedOptionalHeader);
|
||||
return r;
|
||||
}
|
||||
};
|
||||
@@ -210,7 +210,7 @@ pub fn check(out: &[u8]) -> IntegrityReport {
|
||||
other => {
|
||||
r.push(
|
||||
IntegritySeverity::Fatal,
|
||||
format!("bad optional-header magic 0x{other:X}"),
|
||||
Msg::BadOptionalMagic { magic: other },
|
||||
);
|
||||
return r;
|
||||
}
|
||||
@@ -219,33 +219,29 @@ pub fn check(out: &[u8]) -> IntegrityReport {
|
||||
if num_sections == 0 || num_sections > 96 {
|
||||
r.push(
|
||||
IntegritySeverity::Fatal,
|
||||
format!("implausible section count {num_sections}"),
|
||||
Msg::ImplausibleSectionCount {
|
||||
count: num_sections,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
let size_of_image = rd_u32(out, pe_off.wrapping_add(80)).unwrap_or(0);
|
||||
if size_of_image == 0 {
|
||||
r.push(IntegritySeverity::Fatal, "SizeOfImage is zero");
|
||||
r.push(IntegritySeverity::Fatal, Msg::ZeroSizeOfImage);
|
||||
}
|
||||
|
||||
// --- Section table ------------------------------------------------------
|
||||
let headers = match senbei_pe::parse(out) {
|
||||
Ok(headers) => headers,
|
||||
Err(_) => {
|
||||
r.push(
|
||||
IntegritySeverity::Fatal,
|
||||
"section table extends past end of file",
|
||||
);
|
||||
r.push(IntegritySeverity::Fatal, Msg::SectionTablePastEof);
|
||||
return r;
|
||||
}
|
||||
};
|
||||
let parsed_sections = match senbei_pe::sections(out, headers) {
|
||||
Ok(sections) => sections,
|
||||
Err(_) => {
|
||||
r.push(
|
||||
IntegritySeverity::Fatal,
|
||||
"section table extends past end of file",
|
||||
);
|
||||
r.push(IntegritySeverity::Fatal, Msg::SectionTablePastEof);
|
||||
return r;
|
||||
}
|
||||
};
|
||||
@@ -258,10 +254,12 @@ pub fn check(out: &[u8]) -> IntegrityReport {
|
||||
if end > file_len {
|
||||
r.push(
|
||||
IntegritySeverity::Fatal,
|
||||
format!(
|
||||
"section #{i} raw data [0x{:X}..0x{end:X}] exceeds file size 0x{file_len:X}",
|
||||
section.raw_offset
|
||||
),
|
||||
Msg::SectionRawPastEof {
|
||||
index: i,
|
||||
start: section.raw_offset,
|
||||
end,
|
||||
file_len,
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -303,10 +301,7 @@ pub fn check(out: &[u8]) -> IntegrityReport {
|
||||
// (`IMAGE_FILE_RELOCS_STRIPPED`, or a module that is only ever loaded
|
||||
// at its preferred base). Rejecting the layout here would fall back
|
||||
// to the other pipeline and change bytes that previously unpacked.
|
||||
r.push(
|
||||
IntegritySeverity::Warning,
|
||||
"native DLL has no base relocation table (DD[5] is zero) — will crash when loaded at a non-preferred base",
|
||||
);
|
||||
r.push(IntegritySeverity::Warning, Msg::NoBaseRelocations);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -318,15 +313,12 @@ pub fn check(out: &[u8]) -> IntegrityReport {
|
||||
if ep == 0 {
|
||||
// A DLL may legitimately have no entry point; an EXE never does.
|
||||
if !is_dll {
|
||||
r.push(IntegritySeverity::Fatal, "entry point RVA is zero");
|
||||
r.push(IntegritySeverity::Fatal, Msg::ZeroEntryPoint);
|
||||
}
|
||||
} else if !is_managed {
|
||||
match rva_to_off(out, headers, ep, 16) {
|
||||
None => {
|
||||
r.push(
|
||||
IntegritySeverity::Fatal,
|
||||
format!("entry point RVA 0x{ep:X} does not map into any section"),
|
||||
);
|
||||
r.push(IntegritySeverity::Fatal, Msg::EntryUnmapped { rva: ep });
|
||||
}
|
||||
Some(off) => {
|
||||
let stub = &out[off as usize..off as usize + 16];
|
||||
@@ -335,21 +327,13 @@ pub fn check(out: &[u8]) -> IntegrityReport {
|
||||
// were not recovered. That is the suspect signal for an
|
||||
// already-chosen layout, not proof another layout is the
|
||||
// right one.
|
||||
r.push(
|
||||
IntegritySeverity::Warning,
|
||||
format!("entry point at RVA 0x{ep:X} is all zeros (stub not recovered)"),
|
||||
);
|
||||
r.push(IntegritySeverity::Warning, Msg::EntryAllZeros { rva: ep });
|
||||
} else if stub.iter().all(|&b| b == 0xCC) {
|
||||
// 16 bytes of int3 padding where the entry stub should be:
|
||||
// the stub region was never recovered, the loader walks
|
||||
// straight into a debug-break wall. Same severity as a
|
||||
// zeroed stub: the image is mapped, the bytes look unrestored.
|
||||
r.push(
|
||||
IntegritySeverity::Warning,
|
||||
format!(
|
||||
"entry point at RVA 0x{ep:X} is all int3 padding (stub not recovered)"
|
||||
),
|
||||
);
|
||||
r.push(IntegritySeverity::Warning, Msg::EntryAllInt3 { rva: ep });
|
||||
}
|
||||
// The entry must live in an executable section.
|
||||
let exec = secs.iter().any(|s| {
|
||||
@@ -361,7 +345,7 @@ pub fn check(out: &[u8]) -> IntegrityReport {
|
||||
if !exec {
|
||||
r.push(
|
||||
IntegritySeverity::Fatal,
|
||||
format!("entry point RVA 0x{ep:X} is not in an executable section"),
|
||||
Msg::EntryNotExecutable { rva: ep },
|
||||
);
|
||||
}
|
||||
if let Some(entry_stub) = out.get(off as usize..off as usize + 18) {
|
||||
@@ -387,7 +371,7 @@ pub fn check(out: &[u8]) -> IntegrityReport {
|
||||
match rva_to_off(out, headers, imp_rva, 20) {
|
||||
None => r.push(
|
||||
IntegritySeverity::Fatal,
|
||||
format!("import directory RVA 0x{imp_rva:X} does not map into any section"),
|
||||
Msg::ImportDirectoryUnmapped { rva: imp_rva },
|
||||
),
|
||||
Some(desc_off) => {
|
||||
// 256 descriptors is far beyond any real import table; the
|
||||
@@ -403,9 +387,10 @@ pub fn check(out: &[u8]) -> IntegrityReport {
|
||||
match rva_to_off(out, headers, name_rva, 1) {
|
||||
None => r.push(
|
||||
IntegritySeverity::Fatal,
|
||||
format!(
|
||||
"import descriptor {i} DLL name RVA 0x{name_rva:X} does not map into any section"
|
||||
),
|
||||
Msg::ImportNameUnmapped {
|
||||
index: i,
|
||||
rva: name_rva,
|
||||
},
|
||||
),
|
||||
Some(noff) => {
|
||||
if !looks_like_dll_name(out, noff) {
|
||||
@@ -415,9 +400,10 @@ pub fn check(out: &[u8]) -> IntegrityReport {
|
||||
// suspect signal, not an unmapped PE.
|
||||
r.push(
|
||||
IntegritySeverity::Warning,
|
||||
format!(
|
||||
"import descriptor {i} DLL name at RVA 0x{name_rva:X} is not readable ASCII (imports left encrypted?)"
|
||||
),
|
||||
Msg::ImportNameUnreadable {
|
||||
index: i,
|
||||
rva: name_rva,
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -441,16 +427,17 @@ pub fn check(out: &[u8]) -> IntegrityReport {
|
||||
match rva_to_off(out, headers, clr_rva, 0x48) {
|
||||
None => r.push(
|
||||
IntegritySeverity::Fatal,
|
||||
format!("CLR (COR20) directory RVA 0x{clr_rva:X} does not map into any section"),
|
||||
Msg::ClrDirectoryUnmapped { rva: clr_rva },
|
||||
),
|
||||
Some(coff) => {
|
||||
let cb = rd_u32(out, coff).unwrap_or(0);
|
||||
if cb != 0x48 {
|
||||
r.push(
|
||||
IntegritySeverity::Fatal,
|
||||
format!(
|
||||
"COR20 header at RVA 0x{clr_rva:X} has cb 0x{cb:X} (expected 0x48) — CLR header corrupt"
|
||||
),
|
||||
Msg::ClrHeaderBadSize {
|
||||
rva: clr_rva,
|
||||
size: cb,
|
||||
},
|
||||
);
|
||||
} else {
|
||||
// MetaData RVA/size live at COR20 + 0x08 / + 0x0C.
|
||||
@@ -459,18 +446,14 @@ pub fn check(out: &[u8]) -> IntegrityReport {
|
||||
match rva_to_off(out, headers, md_rva, 4) {
|
||||
None => r.push(
|
||||
IntegritySeverity::Fatal,
|
||||
format!(
|
||||
"CLR MetaData RVA 0x{md_rva:X} does not map into any section"
|
||||
),
|
||||
Msg::ClrMetadataUnmapped { rva: md_rva },
|
||||
),
|
||||
Some(moff) => {
|
||||
let sig = out.get(moff as usize..moff as usize + 4);
|
||||
if sig != Some(b"BSJB") {
|
||||
r.push(
|
||||
IntegritySeverity::Fatal,
|
||||
format!(
|
||||
"CLR MetaData at RVA 0x{md_rva:X} lacks 'BSJB' signature (metadata corrupt — managed image will not load)"
|
||||
),
|
||||
Msg::ClrMetadataNoBsjb { rva: md_rva },
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,6 +10,7 @@ pub(crate) mod parallel;
|
||||
pub mod research;
|
||||
|
||||
use senbei_crypto::primitives;
|
||||
use senbei_i18n::Message;
|
||||
use serde::Serialize;
|
||||
|
||||
use crate::profile::{
|
||||
@@ -309,7 +310,7 @@ pub fn unpack_auto_profiled_v(
|
||||
let mut profile = inspect_detected(input, detected);
|
||||
let Some(detected) = detected else {
|
||||
let error = UnpackError::NotCrackProof;
|
||||
profile.push_error(error.to_string());
|
||||
profile.push_error(error.message());
|
||||
return (profile, Err(error));
|
||||
};
|
||||
let result = match detected.kind {
|
||||
@@ -343,7 +344,7 @@ pub fn unpack_exe_profiled_v(
|
||||
let mut profile = inspect_detected(input, detected);
|
||||
if detected.is_none() {
|
||||
let error = UnpackError::NotCrackProof;
|
||||
profile.push_error(error.to_string());
|
||||
profile.push_error(error.message());
|
||||
return (profile, Err(error));
|
||||
}
|
||||
// This entry point will never run the DLL route, so a DLL-kind detection's
|
||||
@@ -383,10 +384,10 @@ fn run_exe_attempt(
|
||||
LayoutKind::ExeStyle,
|
||||
AttemptOutcome::Failed,
|
||||
Vec::new(),
|
||||
vec![error.to_string()],
|
||||
vec![error.message()],
|
||||
);
|
||||
profile.recovery = RecoveryStatus::Failed;
|
||||
profile.push_error(error.to_string());
|
||||
profile.push_error(error.message());
|
||||
Err(error)
|
||||
}
|
||||
}
|
||||
@@ -431,7 +432,7 @@ where
|
||||
dll: Box::new(dll.error),
|
||||
exe: Box::new(exe.error),
|
||||
};
|
||||
profile.push_error(error.to_string());
|
||||
profile.push_error(error.message());
|
||||
Err(error)
|
||||
}
|
||||
}
|
||||
@@ -453,7 +454,7 @@ fn record_rejected(profile: &mut ProtectionProfile, layout: LayoutKind, failure:
|
||||
profile_messages(report, ProfileSeverity::Warning),
|
||||
profile_messages(report, ProfileSeverity::Fatal),
|
||||
),
|
||||
None => (Vec::new(), vec![failure.error.to_string()]),
|
||||
None => (Vec::new(), vec![failure.error.message()]),
|
||||
};
|
||||
let outcome = if failure.report.is_some() {
|
||||
AttemptOutcome::Rejected
|
||||
@@ -463,7 +464,7 @@ fn record_rejected(profile: &mut ProtectionProfile, layout: LayoutKind, failure:
|
||||
profile.record_attempt(layout, outcome, warnings, errors);
|
||||
}
|
||||
|
||||
fn profile_messages(report: &IntegrityReport, severity: ProfileSeverity) -> Vec<String> {
|
||||
fn profile_messages(report: &IntegrityReport, severity: ProfileSeverity) -> Vec<Message> {
|
||||
report
|
||||
.findings
|
||||
.iter()
|
||||
|
||||
Reference in new issue
Block a user