Initial commit: noxis JVM bytecode obfuscator
Workspace of 9 crates (noxis, noxis-core, noxis-classfile, noxis-analysis, noxis-passes, noxis-runtime, noxis-jar, noxis-verify, noxis-structure-check). AGPL-3.0-only license, Rust 2024 edition, unsafe_code denied.
This commit is contained in:
commit
a641e69455
140 changed files with 17197 additions and 0 deletions
170
crates/noxis-passes/src/resources/mod.rs
Normal file
170
crates/noxis-passes/src/resources/mod.rs
Normal file
|
|
@ -0,0 +1,170 @@
|
|||
//! Пасс ресурсов: патч текстовых файлов архива по маппингу классов.
|
||||
//!
|
||||
//! Без этого обфускация Fabric-мода просто не стартует: `fabric.mod.json`
|
||||
//! хранит main-class точкой, `*.mixins.json` — пути внутренними именами,
|
||||
//! refmap и access widener — тоже. Материал: `info/evo-weaknesses.md` §3/§8
|
||||
//! (у разобранного образца ресурсы вообще не трогали).
|
||||
//!
|
||||
//! Замена **границная**, а не подстрочная: `org/example/Foo` не должен
|
||||
//! совпасть внутри `myorg/example/FooBar`. Правило то же, что у проверенного
|
||||
//! референса: сначала дескрипторный вид `Lpkg/Class;`, затем внутренний вид
|
||||
//! с `/`, затем бинарный с `.`, длинные имена первыми.
|
||||
|
||||
/// Интеграционные тесты пасса.
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
use std::cmp::Reverse;
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use noxis_classfile::Program;
|
||||
use noxis_core::{Context, CoreError, Pass, PassId, PassReport};
|
||||
|
||||
/// Расширения текстовых ресурсов, которые имеют смысл переписывать.
|
||||
const TEXT_EXTS: [&str; 9] = [
|
||||
".json",
|
||||
".mcmeta",
|
||||
".properties",
|
||||
".txt",
|
||||
".xml",
|
||||
".yml",
|
||||
".yaml",
|
||||
".cfg",
|
||||
".accesswidener",
|
||||
];
|
||||
|
||||
/// Service loader'ы: файла без расширения, но каждая строка — имя класса.
|
||||
const SERVICES_PREFIX: &str = "META-INF/services/";
|
||||
|
||||
/// Пасс патча ресурсов.
|
||||
#[derive(Debug, Default, Clone, Copy)]
|
||||
pub struct ResourcesPass;
|
||||
|
||||
impl Pass for ResourcesPass {
|
||||
fn id(&self) -> PassId {
|
||||
PassId::Resources
|
||||
}
|
||||
|
||||
fn apply(&self, ctx: &mut Context, program: &mut Program) -> Result<PassReport, CoreError> {
|
||||
let map = ctx.mapping.classes.clone();
|
||||
if map.is_empty() {
|
||||
return Ok(PassReport {
|
||||
pass: PassId::Resources,
|
||||
transformed: 0,
|
||||
skipped: program.resources.len(),
|
||||
notes: vec!["маппинг классов пуст — ресурсы не тронуты".into()],
|
||||
});
|
||||
}
|
||||
|
||||
let mut patched = 0usize;
|
||||
let mut skipped = 0usize;
|
||||
|
||||
for resource in &mut program.resources {
|
||||
if !is_text(&resource.path) {
|
||||
skipped += 1;
|
||||
continue;
|
||||
}
|
||||
let Ok(text) = std::str::from_utf8(&resource.data) else {
|
||||
skipped += 1;
|
||||
continue;
|
||||
};
|
||||
let updated = remap_text(text, &map);
|
||||
if updated == text {
|
||||
skipped += 1;
|
||||
continue;
|
||||
}
|
||||
resource.data = updated.into_bytes();
|
||||
patched += 1;
|
||||
}
|
||||
|
||||
let mut notes = Vec::new();
|
||||
if patched > 0 {
|
||||
notes.push(format!("патч ресурсов: {patched}, пропущено: {skipped}"));
|
||||
}
|
||||
|
||||
Ok(PassReport {
|
||||
pass: PassId::Resources,
|
||||
transformed: patched,
|
||||
skipped,
|
||||
notes,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Текстовый ли это ресурс.
|
||||
///
|
||||
/// Бинарии (картинки, `.class` в `versions/`, нативные библиотеки) не
|
||||
/// трогаем: их переписывание ломает содержимое молча.
|
||||
pub fn is_text(path: &str) -> bool {
|
||||
if path.starts_with(SERVICES_PREFIX) {
|
||||
return !path.ends_with('/');
|
||||
}
|
||||
let lower = path.to_ascii_lowercase();
|
||||
TEXT_EXTS.iter().any(|ext| lower.ends_with(ext))
|
||||
}
|
||||
|
||||
/// Переписывает все ссылки на классы в тексте по таблице `old → new`.
|
||||
pub fn remap_text(text: &str, map: &BTreeMap<String, String>) -> String {
|
||||
if map.is_empty() {
|
||||
return text.to_string();
|
||||
}
|
||||
|
||||
// Длинные имена первыми: иначе `org/example/Foo` совпадёт внутри
|
||||
// `org/example/FooBar` ещё до того, как до него дойдёт очередь.
|
||||
let mut pairs: Vec<(&String, &String)> = map.iter().collect();
|
||||
pairs.sort_by_key(|(from, _)| Reverse(from.len()));
|
||||
|
||||
let mut out = text.to_string();
|
||||
for (from, to) in pairs {
|
||||
out = out.replace(&format!("L{from};"), &format!("L{to};"));
|
||||
out = replace_delimited(&out, from, to, false);
|
||||
out = replace_delimited(&out, &from.replace('/', "."), &to.replace('/', "."), true);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Заменяет все вхождения `old`, отделённые от surrounding текста границами
|
||||
/// имени. `dotted` выбирает набор запрещённых соседей: `/` или `.`.
|
||||
fn replace_delimited(text: &str, old: &str, new: &str, dotted: bool) -> String {
|
||||
let mut out = String::with_capacity(text.len());
|
||||
let mut rest = text;
|
||||
|
||||
while let Some(at) = rest.find(old) {
|
||||
let before = &rest[..at];
|
||||
let after = &rest[at + old.len()..];
|
||||
|
||||
if is_boundary(before.chars().next_back(), dotted)
|
||||
&& is_boundary(after.chars().next(), dotted)
|
||||
{
|
||||
out.push_str(before);
|
||||
out.push_str(new);
|
||||
rest = after;
|
||||
continue;
|
||||
}
|
||||
|
||||
// Совпадение частичное — пропускаем первый символ и ищем дальше.
|
||||
let mut chars = rest[at..].chars();
|
||||
out.push_str(before);
|
||||
match chars.next() {
|
||||
Some(first) => {
|
||||
out.push(first);
|
||||
rest = chars.as_str();
|
||||
}
|
||||
None => break,
|
||||
}
|
||||
}
|
||||
|
||||
out.push_str(rest);
|
||||
out
|
||||
}
|
||||
|
||||
/// `true`, если символ слева/справа допускает начало/конец имени класса.
|
||||
fn is_boundary(neighbour: Option<char>, dotted: bool) -> bool {
|
||||
let Some(ch) = neighbour else {
|
||||
return true;
|
||||
};
|
||||
if ch.is_alphanumeric() || ch == '_' || ch == '$' {
|
||||
return false;
|
||||
}
|
||||
if dotted { ch != '.' } else { ch != '/' }
|
||||
}
|
||||
160
crates/noxis-passes/src/resources/tests.rs
Normal file
160
crates/noxis-passes/src/resources/tests.rs
Normal file
|
|
@ -0,0 +1,160 @@
|
|||
//! Тесты пасса ресурсов: границы совпадений и патч содержимого.
|
||||
|
||||
#![allow(clippy::expect_used, clippy::unwrap_used)]
|
||||
|
||||
use noxis_classfile::{Program, Resource};
|
||||
use noxis_core::{Config, Context, Pass};
|
||||
|
||||
use super::{ResourcesPass, is_text, remap_text};
|
||||
|
||||
fn mapping() -> std::collections::BTreeMap<String, String> {
|
||||
let mut map = std::collections::BTreeMap::new();
|
||||
map.insert("org/example/Foo".to_string(), "a/b/C".to_string());
|
||||
map.insert("org/example/FooBar".to_string(), "a/b/D".to_string());
|
||||
map
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn descriptor_form_is_replaced() {
|
||||
let text = "Lorg/example/Foo; [Lorg/example/FooBar;";
|
||||
assert_eq!(
|
||||
remap_text(text, &mapping()),
|
||||
"La/b/C; [La/b/D;",
|
||||
"дескрипторный вид обязан заменяться без проверки границ"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn internal_form_respects_boundaries() {
|
||||
let map = mapping();
|
||||
assert_eq!(remap_text("owner=Lorg/example/Foo;", &map), "owner=La/b/C;");
|
||||
assert_eq!(
|
||||
remap_text("myorg/example/Foo", &map),
|
||||
"myorg/example/Foo",
|
||||
"совпадение внутри более длинного пути не трогаем"
|
||||
);
|
||||
assert_eq!(
|
||||
remap_text("org/example/FooBaz", &map),
|
||||
"org/example/FooBaz",
|
||||
"суффикс не должен совпасть с префиксом"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dotted_form_respects_boundaries() {
|
||||
let map = mapping();
|
||||
assert_eq!(
|
||||
remap_text("\"org.example.Foo\" => \"x\"", &map),
|
||||
"\"a.b.C\" => \"x\""
|
||||
);
|
||||
assert_eq!(
|
||||
remap_text("myorg.example.Foo", &map),
|
||||
"myorg.example.Foo",
|
||||
"точка внутри имени не является границей"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn longest_name_wins() {
|
||||
assert_eq!(
|
||||
remap_text("Lorg/example/FooBar;", &mapping()),
|
||||
"La/b/D;",
|
||||
"длинное имя обрабатывается раньше короткого"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty_map_is_a_noop() {
|
||||
let text = "Lorg/example/Foo; и org.example.Foo";
|
||||
assert_eq!(remap_text(text, &Default::default()), text);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unicode_text_survives_unrelated_substitution() {
|
||||
let text = "комментарий: Лорем_ипсум — org/example/Bar";
|
||||
assert_eq!(remap_text(text, &mapping()), text);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn text_detection_covers_known_formats() {
|
||||
assert!(is_text("fabric.mod.json"));
|
||||
assert!(is_text("demo.mixins.json"));
|
||||
assert!(is_text("META-INF/services/org.example.Loader"));
|
||||
assert!(is_text("mod.accesswidener"));
|
||||
assert!(is_text("META-INF/versions/1.20/mod.json"));
|
||||
|
||||
assert!(!is_text("assets/tex.png"));
|
||||
assert!(!is_text("lib/native.so"));
|
||||
assert!(!is_text("META-INF/services/"));
|
||||
}
|
||||
|
||||
fn context_with_mapping() -> Context {
|
||||
let mut ctx = Context::new(Config {
|
||||
seed: Some(3),
|
||||
..Config::default()
|
||||
});
|
||||
ctx.mapping
|
||||
.classes
|
||||
.insert("org/example/Foo".into(), "a/b/C".into());
|
||||
ctx
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pass_patches_text_and_counts_the_rest() {
|
||||
let mut program = Program {
|
||||
classes: Vec::new(),
|
||||
resources: vec![
|
||||
Resource {
|
||||
path: "fabric.mod.json".into(),
|
||||
data: br#"{"entrypoints":{"main":["org.example.Foo"]}}"#.to_vec(),
|
||||
},
|
||||
Resource {
|
||||
path: "META-INF/services/org.example.Foo".into(),
|
||||
data: b"# keep\n".to_vec(),
|
||||
},
|
||||
Resource {
|
||||
path: "assets/icon.png".into(),
|
||||
data: vec![0x89, 0x50, 0x4E, 0x47],
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
let mut ctx = context_with_mapping();
|
||||
let report = ResourcesPass
|
||||
.apply(&mut ctx, &mut program)
|
||||
.expect("resources");
|
||||
|
||||
assert_eq!(report.transformed, 1, "патчим только JSON");
|
||||
assert_eq!(report.skipped, 2);
|
||||
|
||||
let json = std::str::from_utf8(&program.resources[0].data).unwrap();
|
||||
assert!(
|
||||
json.contains("a.b.C"),
|
||||
"binary-имя в JSON не заменено: {json}"
|
||||
);
|
||||
assert!(!json.contains("org.example.Foo"), "старое имя осталось");
|
||||
assert_eq!(program.resources[2].data, vec![0x89, 0x50, 0x4E, 0x47]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pass_is_a_noop_without_a_mapping() {
|
||||
let mut program = Program {
|
||||
classes: Vec::new(),
|
||||
resources: vec![Resource {
|
||||
path: "fabric.mod.json".into(),
|
||||
data: br#"{"x":"org.example.Foo"}"#.to_vec(),
|
||||
}],
|
||||
};
|
||||
|
||||
let mut ctx = Context::new(Config::default());
|
||||
let report = ResourcesPass
|
||||
.apply(&mut ctx, &mut program)
|
||||
.expect("resources");
|
||||
|
||||
assert_eq!(report.transformed, 0);
|
||||
assert_eq!(report.skipped, 1);
|
||||
assert!(
|
||||
!report.notes.is_empty(),
|
||||
"должна быть заметка о пустом маппинге"
|
||||
);
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue