Preface Link to this heading

This article assumes a preliminary understanding of Abstract Syntax Tree structure and BabelJS. Click Here to read my introductory article on the usage of Babel.

Definitions Link to this heading

Both dead code and unreachable code are obfuscation techniques relying on the injection of junk code that does not alter the main functionality of a program. Their only purpose is to bloat the appearance of the source code to make it more confusing for a human to analyze. Though being similar, there’s a slight difference between the two.

What is Dead Code? Link to this heading

Dead code is a section of code that is executed, but its results are never used in the rest of the program. In addition to increasing the file size, dead code also increases the program runtime and CPU usage since it is being executed.

What is unreachable code? Link to this heading

Unreachable code is a section of code that is never executed, since there is no existing control flow path that leads to its execution. This results in an increase in file size, but shouldn’t affect the runtime of the program since its contents are never executed.

Examples Link to this heading

Example 1: [Dead Code] Unused Variables and Functions Link to this heading

An unused variable/function is something that is declared (and often, but not always, initialized), but is never used in the program. Therefore, for a variable to be unused, it must:

  1. Be constant, and
  2. Have no references

The following obfuscated script contains many of them:

javascript
 1/**
 2 * unreferencedVariablesObfuscated.js
 3 * Lots of useless variables!
 4 */
 5
 6var a = 3;
 7var b;
 8function useless1(yeet) {
 9  console.log(yeet);
10  console.log("I'm useless :(");
11}
12const c = 7;
13let d = 293;
14const u = "My favourite";
15var useless2 = function (bruh) {
16  console.log(bruh.useless, ":(");
17};
18
19function notHello() {
20  console.log("No!");
21  console.log(i + lmaod, u, el, dgajd, fg + lmaod);
22}
23let dbgad = 23172;
24let dgajd = "is";
25var i = "Hello";
26let vnajkfdhg;
27var dnakd;
28let bvs = new Date();
29var h = "yeet";
30let bv = 23;
31var fg = "steak";
32var lmaod = "!";
33const el = "food";
34let n = 1363;
35let vch = "dghda" + 2;
36let lol = performance.now();
37const sayHello = function () {
38  console.log(i + lmaod, u, el, dgajd, fg + lmaod);
39};
40let dga = 3653817;
41let sfa = "362813";
42sayHello();
43let lmao;
44var fldfioan;

Analysis Methodology Link to this heading

Let’s begin our analysis by pasting the obfuscated script into AST Explorer

A view of the obfuscated code in AST Explorer

We can observe from the AST structure that each new variable creation results in the creation of one of two types of nodes:

  1. A VariableDeclaration, for variables assigned with let, var, and const. 2. Each of these VariableDeclarations contains an array of VariableDeclarators. It is the VariableDeclarator that actually contains the information of the variables, including its id and init values. So, we can make VariableDeclarator nodes our focus of interest to avoid unnecessary extra traversals.

  2. A FunctionDeclaration, for functions declared with a function statement.

Based on this, we can deem our target node types of interest to be VariableDeclarator and FunctionDeclaration.

Recall that we want to identify all constant variables and non-referenced variables, then remove them. It’s important to note that variables in different scopes (e.g. local vs. global), may share the same name but have different values. So, we cannot simply base our solution on how many times a variable name occurs in a program.

This would be a convoluted process if not for Babel’s ‘Scope’ API. I won’t dive too deep into the available scope APIs, but you can refer to the Babel Plugin Handbook to learn more about them. In our case, the scope.getBinding(${identifierName}) method will be incredibly useful for us, as it directly returns information regarding if a variable is constant and all of its references (or lack thereof).

We can use our observations to construct the following deobfuscation logic:

  1. Traverse the AST for VariableDeclarators and FunctionDeclarations. Since both node types have both have the id property, we can write a single plugin for both.
    • Tip: To write a function that works for multiple visitor nodes, we can add an | seperating them in the method name as a string like this: "VariableDeclarator|FunctionDeclaration"
  2. Use the path.scope.getBinding(${identifierName}) method with the name of the current variable as the argument.
  3. If the method returns constant as true and referenced as false, the declaration is considered to be dead code and can be safely removed with path.removed()

The babel implementation is shown below:

Babel Implementation Link to this heading

javascript
 1/**
 2 * Deobfuscator.js
 3 * The babel script used to deobfuscate the target file
 4 *
 5 */
 6const parser = require("@babel/parser");
 7const traverse = require("@babel/traverse").default;
 8const t = require("@babel/types");
 9const generate = require("@babel/generator").default;
10const beautify = require("js-beautify");
11const { readFileSync, writeFile } = require("fs");
12const { Referenced } = require("@babel/traverse/lib/path/lib/virtual-types");
13const { constants } = require("buffer");
14
15/**
16 * Main function to deobfuscate the code.
17 * @param source The source code of the file to be deobfuscated
18 *
19 */
20function deobfuscate(source) {
21  //Parse AST of Source Code
22  const ast = parser.parse(source);
23
24  // Visitor for constant folding
25  const removedUnusedVariablesVisitor = {
26    "VariableDeclarator|FunctionDeclaration"(path) {
27      const { node, scope } = path;
28      const { constant, referenced } = scope.getBinding(node.id.name);
29      // If the variable is constant and never referenced, remove it.
30      if (constant && !referenced) {
31        path.remove();
32      }
33    },
34  };
35
36  // Execute the visitor
37  traverse(ast, removedUnusedVariablesVisitor);
38
39  // Code Beautification
40  let deobfCode = generate(ast, { comments: false }).code;
41  deobfCode = beautify(deobfCode, {
42    indent_size: 2,
43    space_in_empty_paren: true,
44  });
45  // Output the deobfuscated result
46  writeCodeToFile(deobfCode);
47}
48/**
49 * Writes the deobfuscated code to output.js
50 * @param code The deobfuscated code
51 */
52function writeCodeToFile(code) {
53  let outputPath = "output.js";
54  writeFile(outputPath, code, (err) => {
55    if (err) {
56      console.log("Error writing file", err);
57    } else {
58      console.log(`Wrote file to ${outputPath}`);
59    }
60  });
61}
62
63deobfuscate(readFileSync("./unreferencedVariablesObfuscated.js", "utf8"));

After processing the obfuscated script with the babel plugin above, we get the following result:

Post-Deobfuscation Result Link to this heading

javascript
 1const u = "My favourite";
 2let dgajd = "is";
 3var i = "Hello";
 4var fg = "steak";
 5var lmaod = "!";
 6const el = "food";
 7
 8const sayHello = function () {
 9  console.log(i + lmaod, u, el, dgajd, fg + lmaod);
10};
11
12sayHello();

And all non-referenced variables are restored.

Extra: By manual analysis, you can probably realize that all the variables declared above the sayHello function can have their values substituted in place of their identifiers inside of the console.log statement. How to accomplish that is outside the scope of this article. But, if you’re interested in learning how to do it, you can read my article about it here.

Example 2: [Dead Code] Empty Statements Link to this heading

An empty statement is simply a semi-colon (;) with no same-line code before it. This script is littered with them:

javascript
1/**
2 * emptyStatementSrc.js
3 * Ugly 'obfuscated' code.
4 */
5const a = 2;
6const b = 3;
7console.log("a is", a, "b is", b);

The presence of empty statements doesn’t really add much to obfuscation, but removing them will still remove unnecessary noise and optimize the appearance.

Analysis Methodology Link to this heading

We begin by pasting the example obfuscated script into AST Explorer

A view of the obfuscated code in AST Explorer

We can observe that the top-level view is polluted by EmptyStatement nodes, causing a slight inconvenience when trying to navigate through the AST structure.

The deobfuscator logic is very simple:

  1. Traverse the AST for EmptyStatement nodes.
  2. When one is encountered, delete it with path.remove()

The babel implementation is shown below:

javascript
 1/**
 2 * Deobfuscator.js
 3 * The babel script used to deobfuscate the target file
 4 *
 5 */
 6const parser = require("@babel/parser");
 7const traverse = require("@babel/traverse").default;
 8const t = require("@babel/types");
 9const generate = require("@babel/generator").default;
10const beautify = require("js-beautify");
11const { readFileSync, writeFile } = require("fs");
12
13/**
14 * Main function to deobfuscate the code.
15 * @param source The source code of the file to be deobfuscated
16 *
17 */
18function deobfuscate(source) {
19  //Parse AST of Source Code
20  const ast = parser.parse(source);
21
22  // Visitor for deleting empty statements
23  const deleteEmptyStatementsVisitor = {
24    EmptyStatement(path) {
25      path.remove();
26    },
27  };
28
29  // Execute the visitor
30  traverse(ast, deleteEmptyStatementsVisitor);
31
32  // Code Beautification
33  let deobfCode = generate(ast, { comments: false }).code;
34  deobfCode = beautify(deobfCode, {
35    indent_size: 2,
36    space_in_empty_paren: true,
37  });
38  // Output the deobfuscated result
39  writeCodeToFile(deobfCode);
40}
41/**
42 * Writes the deobfuscated code to output.js
43 * @param code The deobfuscated code
44 */
45function writeCodeToFile(code) {
46  let outputPath = "output.js";
47  writeFile(outputPath, code, (err) => {
48    if (err) {
49      console.log("Error writing file", err);
50    } else {
51      console.log(`Wrote file to ${outputPath}`);
52    }
53  });
54}
55
56deobfuscate(readFileSync("./emptyStatementSrc.js", "utf8"));

After processing the obfuscated script with the babel plugin above, we get the following result:

Post-Deobfuscation Result Link to this heading

javascript
1const a = 2;
2const b = 3;
3console.log("a is", a, "b is", b);

And all of the useless EmptyStatements are now removed, enabling easier reading and navigation through the AST.

Example 3: [Unreachable Code] If Statements and Logical Expressions Link to this heading

Let’s take the following ‘obfuscated’ code snippet as an example:

javascript
 1/**
 2 * unreachableLogicalCodeObfuscated.js
 3 */
 4
 5if (!![]) {
 6  console.log("This always runs! 1");
 7} else {
 8  console.log("This never runs.");
 9}
10
11if (40 > 80) {
12  console.log("This never runs.");
13} else if (1 < 2) {
14  console.log("This always runs! 2");
15} else {
16  console.log("This never runs.");
17}
18
19![] ? console.log("This never runs.") : console.log("This always runs! 3");
20
21// Chained example
22
23if (!![]) {
24  console.log("This always runs! 4");
25  ![]
26    ? console.log("This never runs.")
27    : false
28    ? console.log("This never runs")
29    : 40 < 20
30    ? console.log("This never runs.")
31    : 80 > 1
32    ? console.log("This always runs! 5")
33    : 40 > 2
34    ? console.log("This never runs.")
35    : console.log("This never runs.");
36} else {
37  console.log("This never runs.");
38}

This is an extremely simple example, especially since the console.log calls tell you exactly what runs and what doesn’t. Keep in mind that code you find in the wild will probably be layered with other obfuscation techniques too. However, this is a good example for understanding the core concept. Rest assured though: the method I’ll discuss should still be universal to all types of unreachable code obfuscation.

Analysis Methodology Link to this heading

As always, we start our analysis by pasting the code into AST Explorer

A view of the obfuscated code in AST Explorer

We can see that at the top level, the file consists of IfStatements and an ExpressionStatement. If we expand the ExpressionStatement, we can see that ternary operator logical expressions are actually of type ConditionalExpression. Expanding an IfStatement and a ConditionalExpression for comparison, we can notice some similarities:

Comparison of IfStatement vs. ConditionalExpression nodes

We can see that aside from their type, both an IfStatement and a ConditionalExpression both have the exact same structure. That is, both contain:

  • A test property, which is the test condition. It will either evaluate to true or false.

  • A consequent property, which contains the code to be executed if test evaluates to a truthy value.

  • A alternate property, which contains the code to be executed if test evaluates to a falsy value.

    • Note: This property is optional, since an If Statement need not be accompanied by an else.

For our deobfuscator, we’ll make use of one of the babel API methods: NodePath.evaluateTruthy().

This method takes in a path, then evaluates its node. If the node evaluates to a truthy value, the method returns true. If the node evaluates to a falsy value, the method returns false. See: Truthy Values vs. Falsy Values

The steps for creating the deobfuscator are as follows:

  1. Traverse the AST for IfStatements and ConditionalExpressions. Since both node types have the same structure, we can write a single plugin for both.
    • Tip: _To write a function that works for multiple visitor nodes, we can add an _ | seperating them in the method name as a string like this: "IfStatement|ConditionalExpression"
  2. When one is encountered, use the NodePath.evaluateTruthy() method on the test property’s NodePath.
  3. if the NodePath.evaluateTruthy() method returns true:
    1. Replace the path with the contents of consequent.
    2. (Optional) If the consequent is contained within a BlockStatement (curly braces), we can replace it with the consequent.body to get rid of the curly braces.
  4. if the NodePath.evaluateTruthy() method returns false:
    1. If the alternate property exists, replace the path with its contents.
    2. (Optional) If the alternate is contained within a BlockStatement (curly braces), we can replace it with the alternate.body to get rid of the curly braces.

The babel implementation is shown below:

Babel Implementation Link to this heading

javascript
 1/**
 2 * Deobfuscator.js
 3 * The babel script used to deobfuscate the target file
 4 *
 5 */
 6const parser = require("@babel/parser");
 7const traverse = require("@babel/traverse").default;
 8const t = require("@babel/types");
 9const generate = require("@babel/generator").default;
10const beautify = require("js-beautify");
11const { readFileSync, writeFile } = require("fs");
12
13/**
14 * Main function to deobfuscate the code.
15 * @param source The source code of the file to be deobfuscated
16 *
17 */
18function deobfuscate(source) {
19  //Parse AST of Source Code
20  const ast = parser.parse(source);
21
22  // Visitor for simplifying if statements and logical statements
23  const simplifyIfAndLogicalVisitor = {
24    "ConditionalExpression|IfStatement"(path) {
25      let { consequent, alternate } = path.node;
26      let testPath = path.get("test");
27      const value = testPath.evaluateTruthy();
28      if (value === true) {
29        if (t.isBlockStatement(consequent)) {
30          consequent = consequent.body;
31        }
32        path.replaceWithMultiple(consequent);
33      } else if (value === false) {
34        if (alternate != null) {
35          if (t.isBlockStatement(alternate)) {
36            alternate = alternate.body;
37          }
38          path.replaceWithMultiple(alternate);
39        } else {
40          path.remove();
41        }
42      }
43    },
44  };
45
46  // Execute the visitor
47  traverse(ast, simplifyIfAndLogicalVisitor);
48
49  // Code Beautification
50  let deobfCode = generate(ast, { comments: false }).code;
51  deobfCode = beautify(deobfCode, {
52    indent_size: 2,
53    space_in_empty_paren: true,
54  });
55  // Output the deobfuscated result
56  writeCodeToFile(deobfCode);
57}
58/**
59 * Writes the deobfuscated code to output.js
60 * @param code The deobfuscated code
61 */
62function writeCodeToFile(code) {
63  let outputPath = "output.js";
64  writeFile(outputPath, code, (err) => {
65    if (err) {
66      console.log("Error writing file", err);
67    } else {
68      console.log(`Wrote file to ${outputPath}`);
69    }
70  });
71}
72
73deobfuscate(readFileSync("./unreachableLogicalCodeObfuscated.js", "utf8"));

After processing the obfuscated script with the babel plugin above, we get the following result:

Post-Deobfuscation Result Link to this heading

javascript
1console.log("This always runs! 1");
2console.log("This always runs! 2");
3console.log("This always runs! 3");
4console.log("This always runs! 4");

And only the code which is designed to execute persists, a full restoration of the code!

Conclusion Link to this heading

Cleaning up dead/unreachable code is an essential component of the deobfuscation process. I would recommend doing it at least twice per program:

  1. Firstly, at the start of the deobfuscation process. This will make the obfuscated script much more manageable to navigate, as you can focus on the important parts of the program instead of junk code

  2. At the end of the deobfuscation process, as part of the clean-up stage. Simplifying obfuscated code tends to reveal more dead code that can be removed, and removing it at the end results in a cleaner final product.

This article also gave a nice introduction to one of the useful Babel API methods. Unfortunately, there isn’t much good documentation out there aside from the Babel Plugin Handbook. However, you can discover a lot more useful features Babel has to offer by reading its source code, or using the debugger of an IDE to list and test helper methods (the latter of which I personally prefer 😄).

If you’re interested, you can find the source code for all the examples in this repository.

Okay, that’s all I have for you today. I hope that this article helped you learn something new. Thanks for reading, and happy reversing!