如何基于babel将控制流扁平化还原为switch-case?
解读
国内主流反爬前端代码在 Webpack 打包后,会再用 javascript-obfuscator、jsfuck 或自研插件做“控制流扁平化(Control-Flow Flattening)”。
其核心是把顺序执行的 if/while/for 打散成“分发器 + 死代码 + 真实块”,运行时靠一个状态变量(通常叫 _0xabc123)在 while(true) 里不断 switch(state) 跳转。
爬虫工程师拿到这样的代码后,第一步就是“反扁平化”:把 switch-case 重新拼成人类可读的顺序结构,才能继续定位加密入口、补环境或扣算法。
Babel 是国内企业面试里唯一被默认识别的 AST 工具链,考点集中在:
- 能否用 @babel/parser 把混淆代码解析成可遍历的 AST;
- 能否用 scope/path 接口把“状态机”识别出来;
- 能否写小型路径级插件,把 switch 的 Case 块按真实后继关系重排,并删除死分支;
- 最后通过 generator 还原成“正常”的 if-else/while,方便后续调试。
面试官会追问:如果分发器是数组 + 自增索引、或者 case 值被异或加密、甚至嵌套了两级状态机,你的插件如何通用化?因此答案必须给出可扩展的骨架,而不是一次性脚本。
知识点
- Babel 三件套:@babel/parser、@babel/traverse、@babel/generator 的调用顺序与选项(sourceType: "unambiguous"、plugins: ["jsx", "typescript"])。
- path.getFunctionParent()/scope.getBinding() 定位“状态变量”与“分发器数组”。
- SwitchStatement / SwitchCase 的 AST 结构:discriminant、consequent、breakStatement。
- 控制流图(CFG)基本块、前驱、后继概念;死代码删除(DCE)与常量折叠(constant folding)。
- 国内常见“二次混淆”:case 值做 p ^ 0xdead、字符串字面量被拆成 拼接,需先做 hex/string 还原。
- 合规边界:反混淆仅用于内部风控、搜索索引等授权场景,不得绕过版权保护或存储个人隐私数据。
答案
下面给出一段可在 Node 14+ 直接运行的 Babel 插件骨架,能把最常见的“while-switch”扁平化还原成顺序 if-else;遇到更复杂的嵌套状态机,只需在 exit 阶段递归调用同一插件即可。
// deflatten.js
const parser = require("@babel/parser");
const traverse = require("@babel/traverse").default;
const generate = require("@babel/generator").default;
const t = require("@babel/types");
function deflattenPlugin() {
return {
visitor: {
WhileStatement(path) {
// 1. 识别 while(true) + switch(dispatcher)
const { test, body } = path.node;
if (!t.isBooleanLiteral(test, { value: true })) return;
const switchStmt = body.body.find(t.isSwitchStatement);
if (!switchStmt) return;
const stateVar = switchStmt.discriminant;
if (!t.isIdentifier(stateVar)) return;
// 2. 找到状态变量的绑定,确认它是局部 var/let
const binding = path.scope.getBinding(stateVar.name);
if (!binding || binding.kind !== "var" && binding.kind !== "let") return;
// 3. 收集所有 case 块,建立 map<caseValue, casePath>
const caseMap = new Map();
const casePathMap = new Map();
path.get("body.body").forEach(p => {
if (p.isSwitchStatement()) {
p.get("cases").forEach(casePath => {
const testVal = casePath.node.test;
if (t.isNumericLiteral(testVal) || t.isStringLiteral(testVal)) {
const key = testVal.value;
caseMap.set(key, casePath.node);
casePathMap.set(key, casePath);
}
});
}
});
// 4. 从入口 case 0 开始遍历,记录真实执行顺序
const visited = new Set();
const order = [];
let current = 0;
while (caseMap.has(current) && !visited.has(current)) {
visited.add(current);
const casePath = casePathMap.get(current);
order.push(casePath);
// 找下一个状态:case 块最后一句通常是 state = xxx;
let nextState = null;
casePath.traverse({
AssignmentExpression(p) {
if (t.isIdentifier(p.node.left, { name: stateVar.name })) {
const right = p.node.right;
if (t.isNumericLiteral(right)) nextState = right.value;
}
}
});
if (nextState == null) break;
current = nextState;
}
// 5. 按顺序拼接 consequent,去掉 break & state = xxx
const newBody = [];
order.forEach(casePath => {
casePath.node.consequent.forEach(stmt => {
if (t.isBreakStatement(stmt)) return;
if (t.isExpressionStatement(stmt) &&
t.isAssignmentExpression(stmt.expression) &&
t.isIdentifier(stmt.expression.left, { name: stateVar.name })) return;
newBody.push(stmt);
});
});
// 6. 替换原 while 节点
path.replaceWithMultiple(newBody);
}
}
};
}
// CLI 用法: node deflatten.js input.js > output.js
const code = require("fs").readFileSync(process.argv[2], "utf8");
const ast = parser.parse(code, { sourceType: "unambiguous" });
traverse(ast, deflattenPlugin());
console.log(generate(ast, { compact: false }).code);
运行效果示例(输入为扁平化代码):
while(true){
switch(_0x1a2b){
case 0: console.log(1); _0x1a2b = 1; break;
case 1: console.log(2); _0x1a2b = 2; break;
case 2: return;
}
}
输出:
console.log(1);
console.log(2);
return;
面试现场可再补充三点:
- 如果 case 值被异或,可在插件最前面加一步
BinaryExpression(path)常量折叠; - 若状态变量是数组
dispatcher[index++],则把index当成隐式状态,逻辑一致; - 插件写成
export default deflattenPlugin后,可直接塞到企业级 Babel 配置plugins: [deflattenPlugin],与 Webpack 构建链路打通。
拓展思考
- 嵌套状态机:外层 switch 的某个 case 里又出现新的 while-switch,需要把插件写成递归
traverse(innerBlock, deflattenPlugin()),并维护全局计数器防止死循环。 - 异步扁平化:国内部分站点把 await 也打平到状态机,此时 case 块里会出现
return Promise.then(()=>{state=xx}),需要先把await语法树还原成同步风格,再做反扁平化。 - 性能与合规:PB 级抓取场景下,反混淆插件要在 Node 端流式处理,每文件平均 <30 ms;同时需记录原始 robots.txt 声明与数据授权链,确保后续落地到 Hive/Doris 时通过法务审计。