Skip to content

Commit

Permalink
merge pull request #9 from lorenzoferre/vm-module
Browse files Browse the repository at this point in the history
evaluation of functions with literal node type as inputs
  • Loading branch information
lorenzoferre authored Dec 6, 2023
2 parents 7ddeb9b + 6bb4e27 commit cce634e
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 1 deletion.
2 changes: 2 additions & 0 deletions src/deobfuscator.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import replaceNullToUndefined from "./techniques/replace-null-to-undefined.js";
import evaluateConditionStatement from "./techniques/evaluate-condition-statement.js";
import controlFlowUnflattening from "./techniques/control-flow-unflattening.js";
import removeEmptyStatement from "./techniques/remove-empty-statement.js";
import evaluateFunction from "./techniques/evaluate-function.js";

export default function deobfuscate(code) {
do {
Expand All @@ -38,6 +39,7 @@ export default function deobfuscate(code) {
evaluateConditionStatement,
controlFlowUnflattening,
removeEmptyStatement,
evaluateFunction,
],
comments: false,
compact: false,
Expand Down
36 changes: 36 additions & 0 deletions src/techniques/evaluate-function.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import { setChanged } from "../utils/util.js";
import _generate from "@babel/generator";
const generate = _generate.default;
import vm from "vm";

const context = vm.createContext();
var functionName;

export default function (babel) {
const { types: t } = babel;

return {
name: "evaluate-function",
visitor: {
FunctionDeclaration(path) {
const { node } = path;
functionName = node.id.name;
const func = generate(node).code;
vm.runInContext(func, context);
},
CallExpression(path) {
const { node } = path;
const { callee } = node;
if (callee.name !== functionName) return;
const args = node.arguments;
if (!args.every(arg => t.isLiteral(arg))) return;
const expressionCode = generate(node).code;
const value = vm.runInContext(expressionCode, context);
if (value) {
path.replaceWith(t.valueToNode(value));
setChanged(true);
}
},
},
};
}
1 change: 0 additions & 1 deletion test/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,6 @@ test("hex to value", () => {

test("bracket to dot", () => {
assert.strictEqual(deobfuscate(`console["log"]("a")`), `console.log("a");`);
assert.strictEqual(deobfuscate(`console.log(o["a"]);`), `console.log(o.a);`);
});

test("remove empty statement", () => {
Expand Down

0 comments on commit cce634e

Please sign in to comment.