AST_通用插件

AST 通用工具

框架

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
const fs = require('fs');
const types = require("@babel/types");
const parser = require("@babel/parser");
const template = require("@babel/template").default;
const traverse = require("@babel/traverse").default;
const generator = require("@babel/generator").default;


//js混淆代码读取
process.argv.length > 2 ? encodeFile = process.argv[2] : encodeFile = "./5s.js"; //默认的js文件
process.argv.length > 3 ? decodeFile = process.argv[3] : decodeFile = encodeFile.replace(".js", "") + "_ok.js";

//将源代码解析为AST
let sourceCode = fs.readFileSync(encodeFile, { encoding: "utf-8" });
let ast = parser.parse(sourceCode);
console.time("处理完毕,耗时");



console.timeEnd("处理完毕,耗时");
let { code } = generator(ast, opts = {
"compact": false, // 是否压缩代码
"comments": false, // 是否保留注释
"jsescOption": { "minimal": true }, //Unicode转义
});

fs.writeFile(decodeFile, code, (err) => { });

字符串合并

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
const AddObjPro = {
BinaryExpression(path) {
const { left, right, operator } = path.node;

// 检查条件:
// 1. 操作符是 '+'
// 2. 左右操作数都是静态字符串或可以合并的表达式
if (operator === '+') {
// 尝试获取左操作数的字符串值
const leftValue = getStaticStringValue(left);
// 尝试获取右操作数的字符串值
const rightValue = getStaticStringValue(right);

// 如果左右操作数都是静态字符串,则合并
if (leftValue !== null && rightValue !== null) {
const combinedString = leftValue + rightValue;

// 创建新的 StringLiteral 节点
const newStringLiteral = types.stringLiteral(combinedString);

// 替换当前节点
path.replaceWith(newStringLiteral);
}
}
},
};

// 4. 辅助函数:获取静态字符串值
function getStaticStringValue(node) {
if (types.isStringLiteral(node)) {
return node.value; // 直接提取字符串值
} else if (
types.isBinaryExpression(node) &&
node.operator === '+'
) {
// 递归处理嵌套的 BinaryExpression
const leftValue = getStaticStringValue(node.left);
const rightValue = getStaticStringValue(node.right);

// 如果左右操作数都是静态字符串,则合并
if (leftValue !== null && rightValue !== null) {
return leftValue + rightValue;
}
}
return null; // 非静态字符串节点
}

traverse(ast, AddObjPro);

16进制转换为 数字

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
const hexadecimalToInt = {
NumericLiteral(path) {
const { value, extra } = path.node;

// 检查是否是十六进制数字
if (extra && extra.raw.startsWith('0x')) {
// 将十六进制转换为十进制
const decimalValue = parseInt(extra.raw, 16);

// 创建新的 NumericLiteral 节点
const newNumericLiteral = types.numericLiteral(decimalValue);

// 替换当前节点
path.replaceWith(newNumericLiteral);
}
},
};

traverse(ast, hexadecimalToInt);

花指令替换


AST_通用插件
https://hybpjx.cn/2024/08/31/AST-速记/
作者
hybpjx
发布于
2024年8月31日
许可协议