AST(Abstract Syntax Tree,抽象语法树) 是源代码的抽象语法结构的树状表示。JS 代码先经过词法分析生成 token 流,再经过语法分析构建成树形结构,最终可通过代码生成还原为可执行代码。AST 反混淆的核心思路就是:解析 → 遍历修改 → 重新生成。
AST转换 https://astexplorer.net/ https://babeljs.io/repl
想直接做对实际混淆的JS太大了有点无从下手,先做一个小的demo吧
安装
bun add -d @babel/core
pnpm install @babel/core @babel/parser @babel/traverse @babel/generator @babel/types --save-dev@babel/parser 将代码解析成 AST
@babel/traverse 遍历/修改 AST 节点
@babel/generator 将 AST 转回代码
@babel/types 创建/判断 AST 节点类型
@babel/core:Babel 的核心包
实际情形很多,过于复杂。应保持最小情况修改,不对未知的情况进行修改删除。
以保证代码运行结果一致为首要原则。
文本层混淆(纯表面变换,不改变 AST 结构)
代码压缩,十六进制字符串,形式转换
数值拆分(改变了ast结构)
const parser = require("@babel/parser");const traverse = require("@babel/traverse").default;const generate = require("@babel/generator").default;const t = require("@babel/types");
const sourceCode = `(function hello(){let total=7*0;for(let i=2^2;i<0xa;i++){total+=i;}console.log("\x54\x6f\x74\x61\x6c\x3a\x20"+total);return total;})()`
// 2. 将源代码解析为 ASTconst ast = parser.parse(sourceCode);
traverse(ast, { // 数字类型还原16进制转10进制 NumericLiteral(path) { delete path.node.extra }, // 计算表达式 BinaryExpression(path){ const evaluated = path.evaluate() if(evaluated.confident){ path.replaceWith(t.valueToNode(evaluated.value)) } }});
// generate 将 AST 转换回源代码,默认会格式化代码,十六进制字符串使用真实值const result = generate(ast)console.log('=== 最终解混淆结果 ===')console.log(result.code)标识符层混淆(AST 节点重命名)
变量名、函数名、参数名乱码化。
由于最初原始的名字已经彻底丢失,无法还原,只能使用相对更易读一点的方式进行重命名,使用{类型+序号}的方式。后续优化可能对可识别具体类型值的变量使用更具体的变量类型,或者引入AI猜测变量名。
const parser = require("@babel/parser");const traverse = require("@babel/traverse").default;const generate = require("@babel/generator").default;const t = require("@babel/types");
const sourceCode = ` (function _0x1f2a(_0xabc789) { let _0xabc123 = _0xabc789;
for (let _0xdef456 = 0; _0xdef456 < 10; _0xdef456++) { _0xabc123 += _0xdef456; }
console["\x6c\x6f\x67"]("\x54\x6f\x74\x61\x6c\x3a\x20" + _0xabc123); return _0xabc123;})(0);`
// 2. 将源代码解析为 ASTconst ast = parser.parse(sourceCode);
let f=0,p=0,v=0;// 深度优先、从上到下traverse(ast, { // 按序号重命名变量 Identifier(path) { if (path.node.name.startsWith('_0x')) { // 如果父节点是函数 if (t.isFunction(path.parent)) { // 函数重命名 if(path.key === 'id'){ path.node.name = `f${f++}` } // 参数重命名 if(path.listKey === 'params'){ path.node.name = `p${p++}` } } // 如果是声明处的变量 if (t.isVariableDeclarator(path.parent)) { const binding = path.scope.getBinding(path.node.name) // 修改引用路径,只包含「读取」操作 const readPaths = binding.referencePaths.map(p => p.node) // 只包含「写入/赋值」操作, "_0xdef456++", 自增赋值没有left节点,filter筛选去掉undefined const writePaths = binding.constantViolations.map(p => p.node.left).filter(p => p); const allPaths = [path.node, ...readPaths, ...writePaths]; for (let p of allPaths) { p.name = `v${v}`; } v++; } } }, // 对象访问形式,点式访问 MemberExpression(path){ if (t.isStringLiteral(path.node.property)){ const object = path.node.object.name const property = path.node.property.value // 替换为点式访问节点 path.replaceWith( t.memberExpression( t.identifier(object), t.identifier(property), false // computed = false 表示用点访问 ) ) } }});
// generate 将 AST 转换回源代码,默认会格式化代码,十六进制字符串使用真实值const result = generate(ast)console.log('=== 最终解混淆结果 ===')console.log(result.code)/*(function f0(p1) { let v0 = v1; for (let v2 = 0; v2 < 10; v2++) { v0 += v2; } console.log("Total: " + v0); return v0;})(0);*/数据层混淆(隐藏常量与字符串)
字符串阵列化、布尔常量混淆、对象属性打散.
若新增 数组乱序 + 移位 ,则需要按照代码执行顺序维护 数组 的当前状态,会更复杂。
const parser = require("@babel/parser");const traverse = require("@babel/traverse").default;const generate = require("@babel/generator").default;const t = require("@babel/types");
const sourceCode = `// 10. 字符串阵列化:将所有字符串集中存到数组var str_arr = ['log', 'name', 'admin', 'role', 'super' ];if(![]){ str_arr[0] = 1;}// 14. 对象属性打散 + 10. 字符串阵列化:属性名和属性值都用数组下标引用var user = {};user[str_arr[1]] = str_arr[2]; // 乱序后 str_arr[1] 是 'name', str_arr[2] 是 'admin'user[str_arr[3]] = str_arr[4]; // 乱序后 str_arr[3] 是 'super', str_arr[4] 是 'role'
// 13. 布尔常量混淆:if(true) 变成 if(!0)if (!0) { // 14. 对象属性打散:user.name 变成 user[str_arr[1]] // 10. 字符串阵列化:console.log 变成 console[str_arr[0]] console[str_arr[0]](user[str_arr[1]]);}`;// 2. 将源代码解析为 ASTconst ast = parser.parse(sourceCode);
let decode_name = "", decode_arr = []traverse(ast, { // 先找数组 VariableDeclarator(path) { if (t.isArrayExpression(path.node.init)) { // console.log(generate(path.node).code) decode_name = path.node.id.name decode_arr = path.node.init.elements.map(n => n.value) // const binding = path.scope.getBinding(path.node.id.name); // debugger; // 按照代码执行顺序维护 decode_arr 的当前状态 // 7次引用 // binding.referencePaths.forEach(p => { // console.log(p) // }) } }, MemberExpression(path) { // 找到使用解码数组的节点 if (path.node.object.name === decode_name && path.node.computed) { const index = path.node.property.value; // 替换节点为对应的值 decode_arr[index] path.replaceWith(t.valueToNode(decode_arr[index])) } }, // 拆除常量布尔IF语句 IfStatement(path){ const test = path.get("test").evaluateTruthy(); if(test === true){ // 提取body中的所有节点到父节点,保持块作用域。 path.replaceWithMultiple(path.node.consequent); }else if(test === false){ // 始终为false的死代码,直接删除节点。 path.remove() } }, // 进入时执行,删除注释 enter(path) { // 删除节点上的注释 path.node.leadingComments = null; path.node.trailingComments = null; path.node.innerComments = null; }})
traverse(ast, { MemberExpression(path){ if (t.isStringLiteral(path.node.property)){ const object = path.node.object.name const property = path.node.property.value // 替换为点式访问节点 path.replaceWith( t.memberExpression( t.identifier(object), t.identifier(property), false // computed = false 表示用点访问 ) ) } }})// =============================================// 输出最终结果// =============================================const result = generate(ast)console.log('=== 最终解混淆结果 ===')console.log(result.code)/*var str_arr = ['log', 'name', 'admin', 'role', 'super'];var user = {};user.name = "admin";user.role = "super";{ console.log(user.name);}*/代码结构层混淆(改变 AST 控制流)
花指令,不透明谓词,逗号表达式,IIFE 包装,成员表达式转 IIFE,函数拆分/内联,死代码注入
const parser = require("@babel/parser");const traverse = require("@babel/traverse").default;const generate = require("@babel/generator").default;const t = require("@babel/types");const fs = require("fs");
// 1. 我们要处理的源代码// const inputPath = "ast/demo1.js";// const sourceCode = fs.readFileSync(inputPath, "utf-8");const sourceCode = `// 18. IIFE 包装:将整体代码包入立即执行函数,隔离作用域(function() {
// 20. 函数拆分:将原本的 a+b 拆成两个小函数互相调用 function _addStep1(x, y) { return x + y; // 实际加法 } function _addStep2(x, y) { return _addStep1(x, y); // 中转调用 }
// 17. 逗号表达式:将多条语句压缩成一个逗号表达式 // 16. 不透明谓词:看似有条件分支,实际 x*x%2 永远等于 0,必定走真分支 var result = ( _res = null, x = 2, x * x % 2 === 0 ? ( _res = _addStep2(10, 5) // 真分支:执行真正的赋值 ) : ( _res = "never reach" // 假分支:永远不会执行 ), _res // 逗号表达式最终返回最后一个表达式的值 );
// 15. 花指令:插入永远不会执行的垃圾代码,干扰静态分析 if (!1) { var junkData = "This is useless"; for (var i = 0; i < 100; i++) { junkData += i; } console.log(junkData); }
// 19. 成员表达式转 IIFE:将 console.log 动态化 // 原本的 console['log'](result) 被替换为一个返回该方法的 IIFE (function(obj, prop, val) { return obj[prop](val); // 相当于 console['log'](result) })(console, 'log', result);
})();`;// 2. 将源代码解析为 ASTconst ast = parser.parse(sourceCode);
traverse(ast, { // 字面量变量和函数直接替换 => 计算表达式 => 删除未使用的变量和代码
})// =============================================// 输出最终结果// =============================================const result = generate(ast)console.log('=== 最终解混淆结果 ===')console.log(result.code)控制流混淆(核心高级手段)
https://bbs.kanxue.com/thread-272487-1.htm#msg_header_h2_12
const parser = require("@babel/parser");const traverse = require("@babel/traverse").default;const generate = require("@babel/generator").default;const t = require("@babel/types");const fs = require("fs");
// 1. 我们要处理的源代码// const inputPath = "ast/demo1.js";// const sourceCode = fs.readFileSync(inputPath, "utf-8");const sourceCode = `const _0x34e16a = '3,4,0,5,1,2'['split'](',');let _0x2eff02 = 0x0;while (!![]) { switch (_0x34e16a[_0x2eff02++]) { case'0': let _0x38cb15 = _0x4588f1 + _0x470e97; continue; case'1': let _0x1e0e5e = _0x37b9f3[_0x50cee0(0x2e0, 0x2e8, 0x2e1, 0x2e4)]; continue; case'2': let _0x35d732 = [_0x388d4b(-0x134, -0x134, -0x139, -0x138)](_0x38cb15 >> _0x4588f1); continue; case'3': let _0x4588f1 = 0x1; continue; case'4': let _0x470e97 = 0x2; continue; case'5': let _0x37b9f3 = 0x5 || _0x38cb15; continue; } break;}
`;// 2. 将源代码解析为 ASTconst ast = parser.parse(sourceCode);
traverse(ast, { WhileStatement(path) { // switch 节点 let switchNode = path.node.body.body[0]; // switch 语句内的控制流数组名,本例中是 _0x34e16a let arrayName = switchNode.discriminant.object.name; // 获得所有 while 前面的兄弟节点,本例中获取到的是声明两个变量的节点,即 const _0x34e16a 和 let _0x2eff02 let prevSiblings = path.getAllPrevSiblings(); // 定义缓存控制流数组 let array = [] // forEach 方法遍历所有节点 prevSiblings.forEach(pervNode => { let {id, init} = pervNode.node.declarations[0]; // 如果节点 id.name 与 switch 语句内的控制流数组名相同 if (arrayName === id.name) { // 获取节点整个表达式的参数、分割方法、分隔符 let object = init.callee.object.value; let property = init.callee.property.value; let argument = init.arguments[0].value; // 模拟执行 '3,4,0,5,1,2'['split'](',') 语句 array = object[property](argument) // 也可以直接取参数进行分割,方法不通用,比如分隔符换成 | 就不行了 // array = init.callee.object.value.split(','); } // 前面的兄弟节点就可以删除了 pervNode.remove(); });
// 储存正确顺序的控制流语句 let replace = []; // 遍历控制流数组,按正确顺序取 case 内容 array.forEach(index => { let consequent = switchNode.cases[index].consequent; // 如果最后一个节点是 continue 语句,则删除 ContinueStatement 节点 if (t.isContinueStatement(consequent[consequent.length - 1])) { consequent.pop(); } // concat 方法拼接多个数组,即正确顺序的 case 内容 replace = replace.concat(consequent); } ); // 替换整个 while 节点,两种方法都可以 path.replaceWithMultiple(replace); }})// =============================================// 输出最终结果// =============================================const result = generate(ast)console.log('=== 最终解混淆结果 ===')console.log(result.code)待完成。。。
!function () { const _$_E = [2, 8, 4, 6, 0, 5, 11, 7, 9, 10, 1, 3]; let _$f6 = 0; while (1) { _$aa = _$_E[_$f6++]; if (_$aa < 12) { if (_$aa < 4) { if (_$aa === 0) { _$kV = _$b9['$_ss']; } else if (_$aa === 1) { _$kV.lcd = _$mu; } else if (_$aa === 2) { _$$r = [4, 16, 64, 256, 1024, 4096, 16384, 65536]; } else { return; } } else if (_$aa < 8) { if (_$aa === 4) { _$ce = !_$iw; } else if (_$aa === 5) { _$ce = _$kV; } else if (_$aa === 6) { !_$ce ? _$f6 += 0 : 0; } else { _$jk(57); } } else { if (_$aa === 8) { _$b9 = window, _$j7 = String, _$_Q = Array, _$ly = document, _$bv = Math.random, _$by = Math.round, _$iw = Date; } else if (_$aa === 9) { _$f6 += 2; } else if (_$aa === 10) { _$kV = _$b9['$_ss'] = {}; } else { !_$ce ? _$f6 += 2 : 0; } } } else; }}()动态执行混淆(运行时生成代码)
eval
反调试/反分析混淆(对抗开发者工具)
debugger、格式化检测
其他
相关反混淆项目
https://github.com/ben-sb/javascript-deobfuscator
https://github.com/relative/synchrony
https://github.com/kuizuo/js-deobfuscator
https://github.com/j4k0xb/webcrack
JS加密/混淆
https://obfuscator.io/legacy-playground
https://www.bejson.com/encrypt/jsobfuscate/
混淆JS样例 https://static.geetest.com/static/js/slide.7.9.3.js https://static.geetest.com/static/js/fullpage.9.2.0-guwyxh.js https://static.geetest.com/v4/static/v1.9.6-1db46d/js/gcaptcha4.js https://static.geetest.com/v4/gct/gct4.5a2e755576738ba0499d714db4f1c9e0.js https://static.geetest.com/v4/bypass.js https://www.czbeihu.gov.cn/MMB1_4add83119126cad64d529ca03bea4d7d/ZYbKRgIknL7izCT.js https://fwgl.zfcxjw.cq.gov.cn:9090/DaGPddCX1LOD/loU7UHj8yHz6.2a95215.js