Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion crates/untwist-deobfuscate/src/calls/agnostic/assembled.rs
Original file line number Diff line number Diff line change
Expand Up @@ -159,7 +159,10 @@ impl<'a> Scan<'_, '_, 'a> {
let alias = self.alias_of(statements.get(next)?, table)?;
let references = self.scoping.get_resolved_reference_ids(table).len();
let unchecked = flow_rule_disabled(BUILT_LITERAL);
if !unchecked && (references != writes.len() + 1 || self.scoping.symbol_is_mutated(table)) {
if !unchecked
&& (references != writes.len() + 1
|| crate::calls::agnostic::rebound(self.scoping, table))
{
return None;
}
Some((alias, Assembled { fields, writes }))
Expand Down
6 changes: 3 additions & 3 deletions crates/untwist-deobfuscate/src/calls/agnostic/bind.rs
Original file line number Diff line number Diff line change
Expand Up @@ -195,7 +195,7 @@ fn inlinable_of(defs: &DefTable<'_>, scoping: &Scoping) -> FxHashSet<u32> {
for (_, found) in defs.present() {
if let Some(func) = inlinable_func(&found) {
if plain_param_syms(func).iter().all(|sym| {
!scoping.symbol_is_mutated(*sym)
!crate::calls::agnostic::rebound(scoping, *sym)
&& defs.get(*sym).is_none_or(|d| d.writes.is_empty())
}) {
inlinable.insert(func.span.start);
Expand Down Expand Up @@ -322,7 +322,7 @@ impl<'s, 'a> Bindings<'s, 'a> {
bindings.unsealed_maps = std::mem::take(&mut bindings.map_uses).unsealed(resolve);
let annex = std::mem::take(&mut bindings.annex);
bindings.defs.each_present_mut(|symbol, def| {
def.set_to(MUTATED, scoping.symbol_is_mutated(symbol));
def.set_to(MUTATED, crate::calls::agnostic::rebound(scoping, symbol));
if annex.contains(scoping.symbol_name(symbol)) {
def.set(OPAQUE);
}
Expand Down Expand Up @@ -545,7 +545,7 @@ impl<'s, 'a> Bindings<'s, 'a> {
}
match self.defs.get(symbol) {
Some(defs) => !defs.mutated && defs.writes.is_empty(),
None => !self.scoping.symbol_is_mutated(symbol),
None => !crate::calls::agnostic::rebound(self.scoping, symbol),
}
}

Expand Down
8 changes: 4 additions & 4 deletions crates/untwist-deobfuscate/src/calls/agnostic/bootstrap.rs
Original file line number Diff line number Diff line change
Expand Up @@ -324,7 +324,7 @@ fn shape<'a>(
.id
.as_ref()
.and_then(|id| id.symbol_id.get())
.filter(|symbol| !scoping.symbol_is_mutated(*symbol))
.filter(|symbol| !crate::calls::agnostic::rebound(scoping, *symbol))
.ok_or(DISPATCH_SHAPE)?;
if dispatch.optional {
return Err(DISPATCH_SHAPE);
Expand Down Expand Up @@ -452,7 +452,7 @@ impl<'a> Uses<'_, 'a> {
let escapes = self.helper_reads.iter().any(|read| read == name);
!escapes
&& (dead
|| (!self.scoping.symbol_is_mutated(*symbol)
|| (!crate::calls::agnostic::rebound(self.scoping, *symbol)
&& calls().all(|(_, call)| {
call.arguments
.get(at)
Expand Down Expand Up @@ -711,14 +711,14 @@ pub(super) fn prove<'a>(
let (outer, shape) = found?;
let table_symbol = outer.table;
let table = table_of(scoping, outer.elements).ok_or(TABLE_NOT_LITERAL)?;
if scoping.symbol_is_mutated(table_symbol) || !outer.plain {
if crate::calls::agnostic::rebound(scoping, table_symbol) || !outer.plain {
return Err(TABLE_ESCAPES);
}
let mut aliases = FxHashSet::default();
for params in &table.functions {
for index in &shape.aliases {
if let Some(symbol) = params.items.get(*index).and_then(binding_symbol) {
if scoping.symbol_is_mutated(symbol) {
if crate::calls::agnostic::rebound(scoping, symbol) {
return Err(REQUIRE_ESCAPES);
}
aliases.insert(symbol);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ fn for_in_pair<'a>(
};
let key = id.symbol_id.get()?;
let plain = declarator.init.is_none()
&& !scoping.symbol_is_mutated(key)
&& !crate::calls::agnostic::rebound(scoping, key)
&& names(scoping, &each.right, definition);
plain.then_some((key, &**each))
}
Expand Down Expand Up @@ -126,7 +126,7 @@ pub(super) fn getter_read(
return None;
}
let definition = params.items.get(1).and_then(binding_symbol)?;
if scoping.symbol_is_mutated(definition)
if crate::calls::agnostic::rebound(scoping, definition)
|| calls
.iter()
.any(|call| !call.arguments.get(1).is_some_and(function_literal))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@ fn caches_confined(
escapes: false,
};
uses.visit_program(program);
!uses.escapes && !scoping.symbol_is_mutated(symbol)
!uses.escapes && !crate::calls::agnostic::rebound(scoping, symbol)
})
}

Expand Down Expand Up @@ -229,7 +229,7 @@ pub(super) fn module_record<'a>(scoping: &Scoping, shape: &Shape<'a>) -> Option<
return None;
};
let symbol = id.symbol_id.get()?;
if scoping.symbol_is_mutated(symbol) {
if crate::calls::agnostic::rebound(scoping, symbol) {
return None;
}
let mut caches = Vec::new();
Expand Down Expand Up @@ -300,7 +300,7 @@ pub(super) fn dispatched_objects(
continue;
}
if let Some(symbol) = binding_symbol(param) {
if !scoping.symbol_is_mutated(symbol) {
if !crate::calls::agnostic::rebound(scoping, symbol) {
objects.push(symbol);
}
}
Expand Down
10 changes: 7 additions & 3 deletions crates/untwist-deobfuscate/src/calls/agnostic/bound_this.rs
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ impl Literals<'_> {
let Some((symbol, object)) = object_declarator(declarator) else {
return;
};
if self.tables.contains(&symbol) || self.scoping.symbol_is_mutated(symbol) {
if self.tables.contains(&symbol) || crate::calls::agnostic::rebound(self.scoping, symbol) {
return;
}
if let Some(literal) = literal_of(object) {
Expand Down Expand Up @@ -125,8 +125,12 @@ impl Literals<'_> {
let alias = self.alias_of(statements.get(next)?, table)?;
let references = self.scoping.get_resolved_reference_ids(table).len();
let unchecked = flow_rule_disabled(BUILT_LITERAL);
let sole = references == writes + 1 && !self.scoping.symbol_is_mutated(table);
if writes == 0 || !(unchecked || sole) || self.scoping.symbol_is_mutated(alias) {
let sole =
references == writes + 1 && !crate::calls::agnostic::rebound(self.scoping, table);
if writes == 0
|| !(unchecked || sole)
|| crate::calls::agnostic::rebound(self.scoping, alias)
{
return None;
}
self.tables.insert(table);
Expand Down
171 changes: 171 additions & 0 deletions crates/untwist-deobfuscate/src/calls/agnostic/chain_text.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,171 @@
use oxc_ast::ast::*;
use oxc_ast_visit::{walk_js, VisitJs};
use untwist_core::ast_util::js_text::js_text;

const CHAIN_NAMES: [&str; 8] = [
"__proto__",
"prototype",
"setPrototypeOf",
"getPrototypeOf",
"getOwnPropertyDescriptor",
"getOwnPropertyDescriptors",
"__lookupSetter__",
"__defineSetter__",
];

const RUNNER_NAMES: [&str; 8] = [
"eval",
"Function",
"constructor",
"execScript",
"setTimeout",
"setInterval",
"setImmediate",
"importScripts",
];

const FUNCTION_FORM: (&str, &str) = ("(function () {\n", "\n});");

pub(super) fn text_spares_chains(text: &str, depth: u8) -> bool {
let Some(next) = depth.checked_sub(1) else {
return false;
};
let wrapped = format!("{}{text}{}", FUNCTION_FORM.0, FUNCTION_FORM.1);
[text, wrapped.as_str()].iter().any(|form| {
crate::proof::with_parsed_text(form, |program| {
let mut scan = ChainText::default();
scan.visit_program(program);
(!scan.open).then_some(scan.nested)
})
.flatten()
.flatten()
.is_some_and(|nested| nested.iter().all(|inner| text_spares_chains(inner, next)))
})
}

#[derive(Default)]
struct ChainText {
open: bool,
nested: Vec<String>,
}

impl ChainText {
fn name(&mut self, name: &str) {
self.open |= CHAIN_NAMES.contains(&name);
}

fn runner_callee(callee: &Expression<'_>) -> bool {
match callee.without_parentheses() {
Expression::Identifier(id) => RUNNER_NAMES.contains(&id.name.as_str()),
Expression::StaticMemberExpression(member) => {
RUNNER_NAMES.contains(&member.property.name.as_str())
}
_ => false,
}
}

fn texts(&mut self, arguments: &[Argument<'_>]) {
for argument in arguments {
match argument {
Argument::StringLiteral(text) => self.nested.push(js_text(text.value).into_owned()),
Argument::TemplateLiteral(template) if template.expressions.is_empty() => {
match template.quasis.first().and_then(|quasi| quasi.value.cooked) {
Some(cooked) => self.nested.push(js_text(cooked).into_owned()),
None => self.open = true,
}
}
Argument::NumericLiteral(_)
| Argument::FunctionExpression(_)
| Argument::ArrowFunctionExpression(_) => {}
_ => self.open = true,
}
}
}
}

impl<'a> VisitJs<'a> for ChainText {
fn visit_identifier_reference(&mut self, it: &IdentifierReference<'a>) {
self.name(&it.name);
self.open |= RUNNER_NAMES.contains(&it.name.as_str());
}

fn visit_binding_identifier(&mut self, it: &BindingIdentifier<'a>) {
self.name(&it.name);
}

fn visit_identifier_name(&mut self, it: &IdentifierName<'a>) {
self.name(&it.name);
self.open |= RUNNER_NAMES.contains(&it.name.as_str());
}

fn visit_string_literal(&mut self, it: &StringLiteral<'a>) {
self.name(&js_text(it.value));
}

fn visit_template_element(&mut self, it: &TemplateElement<'a>) {
match it.value.cooked {
Some(cooked) => self.name(&js_text(cooked)),
None => self.open = true,
}
}

fn visit_computed_member_expression(&mut self, it: &ComputedMemberExpression<'a>) {
let literal = matches!(
it.expression.without_parentheses(),
Expression::StringLiteral(_) | Expression::NumericLiteral(_)
);
self.open |= !literal;
walk_js::walk_computed_member_expression(self, it);
}

fn visit_with_statement(&mut self, it: &WithStatement<'a>) {
self.open = true;
walk_js::walk_with_statement(self, it);
}

fn visit_tagged_template_expression(&mut self, it: &TaggedTemplateExpression<'a>) {
self.open = true;
walk_js::walk_tagged_template_expression(self, it);
}

fn visit_import_expression(&mut self, it: &ImportExpression<'a>) {
self.open = true;
walk_js::walk_import_expression(self, it);
}

fn visit_call_expression(&mut self, it: &CallExpression<'a>) {
if Self::runner_callee(&it.callee) {
self.texts(&it.arguments);
for argument in &it.arguments {
if let Some(expr) = argument.as_expression() {
if matches!(
expr,
Expression::FunctionExpression(_) | Expression::ArrowFunctionExpression(_)
) {
self.visit_expression(expr);
}
}
}
self.visit_runner_callee(&it.callee);
return;
}
walk_js::walk_call_expression(self, it);
}

fn visit_new_expression(&mut self, it: &NewExpression<'a>) {
if Self::runner_callee(&it.callee) {
self.texts(&it.arguments);
self.visit_runner_callee(&it.callee);
return;
}
walk_js::walk_new_expression(self, it);
}
}

impl ChainText {
fn visit_runner_callee(&mut self, callee: &Expression<'_>) {
if let Expression::StaticMemberExpression(member) = callee.without_parentheses() {
self.visit_expression(&member.object);
}
}
}
2 changes: 1 addition & 1 deletion crates/untwist-deobfuscate/src/calls/agnostic/holds.rs
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ impl<'a> VisitJs<'a> for MemberTarget {
}
}

fn writes_a_member(target: &AssignmentTarget<'_>) -> bool {
pub(in crate::calls::agnostic) fn writes_a_member(target: &AssignmentTarget<'_>) -> bool {
let mut scan = MemberTarget::default();
scan.visit_assignment_target(target);
scan.found
Expand Down
42 changes: 31 additions & 11 deletions crates/untwist-deobfuscate/src/calls/agnostic/judge.rs
Original file line number Diff line number Diff line change
Expand Up @@ -424,11 +424,13 @@ impl<'s, 'a> Sites<'s, 'a> {
pub(super) fn judge_collected(mut self) -> (Agnostic<'a>, bool, bool) {
self.judge_script_sinks();
if !self.walks_on() {
self.out.text_unknown = true;
return self.into_saturated();
}
let calls = std::mem::take(&mut self.calls);
for call in calls {
if !self.walks_on() {
self.out.text_unknown = true;
return self.into_saturated();
}
self.judge_call(call);
Expand All @@ -447,7 +449,11 @@ impl<'s, 'a> Sites<'s, 'a> {
self.check_template(template.span, &template.quasi, self.unbounded_text());
}
}
if saturated_while_watching || !self.element_bounds_hold() {
if !self.element_bounds_hold() {
self.out.text_unknown |= !self.element_bounds_hold_beside_blocks();
return self.into_saturated();
}
if saturated_while_watching {
return self.into_saturated();
}
let (chains, natives) = self.assumptions_hold();
Expand All @@ -465,18 +471,32 @@ impl<'s, 'a> Sites<'s, 'a> {
}

fn element_bounds_hold(&self) -> bool {
self.element_bounds_hold_without(|_| false)
}

fn element_bounds_hold_beside_blocks(&self) -> bool {
let blocks = &self.fresh.bindings.loose;
self.element_bounds_hold_without(|span| blocks.exempt(span) || self.in_machinery(span))
}

fn element_bounds_hold_without(&self, exempt: impl Fn(Span) -> bool) -> bool {
!self.bounds_used.get()
|| !self.out.sites.iter().any(|site| {
matches!(
site.root,
ProtoRoot::Array | ProtoRoot::Object | ProtoRoot::Either
) && match &site.key {
AKey::Named(name) => {
!name.is_empty() && name.bytes().all(|byte| byte.is_ascii_digit())
|| !self
.out
.sites
.iter()
.filter(|site| !exempt(site.span))
.any(|site| {
matches!(
site.root,
ProtoRoot::Array | ProtoRoot::Object | ProtoRoot::Either
) && match &site.key {
AKey::Named(name) => {
!name.is_empty() && name.bytes().all(|byte| byte.is_ascii_digit())
}
AKey::Index | AKey::Pending(_) | AKey::Filtered(_) | AKey::Unknown => true,
}
AKey::Index | AKey::Pending(_) | AKey::Filtered(_) | AKey::Unknown => true,
}
})
})
}

pub(super) fn assumptions_hold(&self) -> (bool, bool) {
Expand Down
Loading