Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use typeMap #129

Merged
merged 4 commits into from
Nov 12, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 32 additions & 12 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -161,7 +161,7 @@ if (res.script !== code) {

### Boilerplate code for starting from scratch
```javascript
import {applyIteratively, treeModifier, logger} from 'flast';
import {applyIteratively, logger} from 'flast';
// Optional loading from file
// import fs from 'node:fs';
// const inputFilename = process.argv[2] || 'target.js';
Expand All @@ -173,22 +173,42 @@ const code = `(function() {
})();`;

logger.setLogLevelDebug();

/**
* Replace specific strings with other strings
* @param {Arborist} arb
* @return {Arborist}
*/
function replaceSpecificLiterals(arb) {
const replacements = {
'Hello': 'General',
'there!': 'Kenobi!',
};
// Iterate over only the relevant nodes by targeting specific types using the typeMap property on the root node
const relevantNodes = [
...(arb.ast[0].typeMap.Literal || []),
// ...(arb.ast.typeMap.TemplateLiteral || []), // unnecessary for this example, but this is how to add more types
];
for (const n of relevantNodes) {
if (replacements[n.value]) {
// dynamically define a replacement node by creating an object with a type and value properties
// markNode(n) would delete the node, while markNode(n, {...}) would replace the node with the supplied node.
arb.markNode(n, {type: 'Literal', value: replacements[n.value]});
}
}
return arb;
}

let script = code;
// Use this function to target the relevant nodes
const f = n => n.type === 'Literal' && replacements[n.value];
// Use this function to modify the nodes according to your needs.
// markNode(n) would delete the node, while markNode(n, {...}) would replace the node with the supplied node.
const m = (n, arb) => arb.markNode(n, {
type: 'Literal',
value: replacements[n.value],
});
const swc = treeModifier(f, m, 'StarWarsChanger');
script = applyIteratively(script, [swc]);

script = applyIteratively(script, [
replaceSpecificLiterals,
]);

if (code !== script) {
console.log(script);
// fs.writeFileSync(inputFilename + '-deob.js', script, 'utf-8');
} else console.log(`No changes`);

```
***

Expand Down
62 changes: 31 additions & 31 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

12 changes: 6 additions & 6 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "restringer",
"version": "2.0.3",
"version": "2.0.4",
"description": "Deobfuscate Javascript with emphasis on reconstructing strings",
"main": "index.js",
"type": "module",
Expand All @@ -12,10 +12,10 @@
"test": "tests"
},
"dependencies": {
"flast": "^2.0.3",
"flast": "^2.1.0",
"isolated-vm": "^5.0.1",
"jsdom": "^25.0.1",
"obfuscation-detector": "^2.0.2"
"obfuscation-detector": "^2.0.3"
},
"scripts": {
"test": "node --test --trace-warnings --no-node-snapshot",
Expand All @@ -40,9 +40,9 @@
},
"homepage": "https://github.com/PerimeterX/Restringer#readme",
"devDependencies": {
"@babel/eslint-parser": "^7.25.8",
"@babel/plugin-syntax-import-assertions": "^7.25.7",
"eslint": "^9.12.0",
"@babel/eslint-parser": "^7.25.9",
"@babel/plugin-syntax-import-assertions": "^7.26.0",
"eslint": "^9.14.0",
"globals": "^15.12.0",
"husky": "^9.1.6"
}
Expand Down
9 changes: 7 additions & 2 deletions src/modules/safe/normalizeComputed.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,13 @@ import {badIdentifierCharsRegex, validIdentifierBeginning} from '../config.js';
* @return {Arborist}
*/
function normalizeComputed(arb, candidateFilter = () => true) {
for (let i = 0; i < arb.ast.length; i++) {
const n = arb.ast[i];
const relevantNodes = [
...(arb.ast[0].typeMap.MemberExpression || []),
...(arb.ast[0].typeMap.MethodDefinition || []),
...(arb.ast[0].typeMap.Property || []),
];
for (let i = 0; i < relevantNodes.length; i++) {
const n = relevantNodes[i];
if (n.computed && // Filter for only member expressions using bracket notation
// Ignore member expressions with properties which can't be non-computed, like arr[2] or window['!obj']
// or those having another variable reference as their property like window[varHoldingFuncName]
Expand Down
9 changes: 6 additions & 3 deletions src/modules/safe/normalizeEmptyStatements.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,12 @@
* @return {Arborist}
*/
function normalizeEmptyStatements(arb, candidateFilter = () => true) {
for (let i = 0; i < arb.ast.length; i++) {
const n = arb.ast[i];
if (n.type === 'EmptyStatement' && candidateFilter(n)) {
const relevantNodes = [
...(arb.ast[0].typeMap.EmptyStatement || []),
];
for (let i = 0; i < relevantNodes.length; i++) {
const n = relevantNodes[i];
if (candidateFilter(n)) {
// A for loop is sometimes used to assign variables without providing a loop body, just an empty statement.
// If we delete that empty statement the syntax breaks
// e.g. for (var i = 0, b = 8;;); - this is a valid for statement.
Expand Down
10 changes: 6 additions & 4 deletions src/modules/safe/parseTemplateLiteralsIntoStringLiterals.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,12 @@ import {createNewNode} from '../utils/createNewNode.js';
* @return {Arborist}
*/
function parseTemplateLiteralsIntoStringLiterals(arb, candidateFilter = () => true) {
for (let i = 0; i < arb.ast.length; i++) {
const n = arb.ast[i];
if (n.type === 'TemplateLiteral' &&
!n.expressions.some(exp => exp.type !== 'Literal') &&
const relevantNodes = [
...(arb.ast[0].typeMap.TemplateLiteral || []),
];
for (let i = 0; i < relevantNodes.length; i++) {
const n = relevantNodes[i];
if (!n.expressions.some(exp => exp.type !== 'Literal') &&
candidateFilter(n)) {
let newStringLiteral = '';
for (let j = 0; j < n.expressions.length; j++) {
Expand Down
8 changes: 6 additions & 2 deletions src/modules/safe/rearrangeSequences.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,12 @@
* @return {Arborist}
*/
function rearrangeSequences(arb, candidateFilter = () => true) {
for (let i = 0; i < arb.ast.length; i++) {
const n = arb.ast[i];
const relevantNodes = [
...(arb.ast[0].typeMap.ReturnStatement || []),
...(arb.ast[0].typeMap.IfStatement || []),
];
for (let i = 0; i < relevantNodes.length; i++) {
const n = relevantNodes[i];
if ((
n.type === 'ReturnStatement' && n.argument?.type === 'SequenceExpression' ||
n.type === 'IfStatement' && n.test.type === 'SequenceExpression'
Expand Down
10 changes: 6 additions & 4 deletions src/modules/safe/rearrangeSwitches.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,12 @@ const maxRepetition = 50;
* @return {Arborist}
*/
function rearrangeSwitches(arb, candidateFilter = () => true) {
for (let i = 0; i < arb.ast.length; i++) {
const n = arb.ast[i];
if (n.type === 'SwitchStatement' &&
n.discriminant.type === 'Identifier' &&
const relevantNodes = [
...(arb.ast[0].typeMap.SwitchStatement || []),
];
for (let i = 0; i < relevantNodes.length; i++) {
const n = relevantNodes[i];
if (n.discriminant.type === 'Identifier' &&
n?.discriminant.declNode?.parentNode?.init?.type === 'Literal' &&
candidateFilter(n)) {
let ordered = [];
Expand Down
10 changes: 6 additions & 4 deletions src/modules/safe/removeDeadNodes.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,12 @@ const relevantParents = [
* @return {Arborist}
*/
function removeDeadNodes(arb, candidateFilter = () => true) {
for (let i = 0; i < arb.ast.length; i++) {
const n = arb.ast[i];
if (n.type === 'Identifier' &&
relevantParents.includes(n.parentNode.type) &&
const relevantNodes = [
...(arb.ast[0].typeMap.Identifier || []),
];
for (let i = 0; i < relevantNodes.length; i++) {
const n = relevantNodes[i];
if (relevantParents.includes(n.parentNode.type) &&
(!n?.declNode?.references?.length && !n?.references?.length) &&
candidateFilter(n)) {
const parent = n.parentNode;
Expand Down
10 changes: 6 additions & 4 deletions src/modules/safe/removeRedundantBlockStatements.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,12 @@
* @return {Arborist}
*/
function removeRedundantBlockStatements(arb, candidateFilter = () => true) {
for (let i = 0; i < arb.ast.length; i++) {
const n = arb.ast[i];
if (n.type === 'BlockStatement' &&
['BlockStatement', 'Program'].includes(n.parentNode.type) &&
const relevantNodes = [
...(arb.ast[0].typeMap.BlockStatement || []),
];
for (let i = 0; i < relevantNodes.length; i++) {
const n = relevantNodes[i];
if (['BlockStatement', 'Program'].includes(n.parentNode.type) &&
candidateFilter(n)) {
const parent = n.parentNode;
if (parent.body?.length > 1) {
Expand Down
10 changes: 6 additions & 4 deletions src/modules/safe/replaceBooleanExpressionsWithIf.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,12 @@
* @return {Arborist}
*/
function replaceBooleanExpressionsWithIf(arb, candidateFilter = () => true) {
for (let i = 0; i < arb.ast.length; i++) {
const n = arb.ast[i];
if (n.type === 'ExpressionStatement' &&
(n.expression.operator === '&&' || n.expression.operator === '||') && candidateFilter(n)) {
const relevantNodes = [
...(arb.ast[0].typeMap.ExpressionStatement || []),
];
for (let i = 0; i < relevantNodes.length; i++) {
const n = relevantNodes[i];
if (['&&', '||'].includes(n.expression.operator) && candidateFilter(n)) {
// || requires inverted logic (only execute the consequent if all operands are false)
const testExpression =
n.expression.operator === '||'
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,12 @@
* @return {Arborist}
*/
function replaceCallExpressionsWithUnwrappedIdentifier(arb, candidateFilter = () => true) {
for (let i = 0; i < arb.ast.length; i++) {
const n = arb.ast[i];
if (n.type === 'CallExpression' &&
((n.callee?.declNode?.parentNode?.type === 'VariableDeclarator' &&
const relevantNodes = [
...(arb.ast[0].typeMap.CallExpression || []),
];
for (let i = 0; i < relevantNodes.length; i++) {
const n = relevantNodes[i];
if (((n.callee?.declNode?.parentNode?.type === 'VariableDeclarator' &&
/FunctionExpression/.test(n.callee.declNode.parentNode?.init?.type)) ||
(n.callee?.declNode?.parentNode?.type === 'FunctionDeclaration' &&
n.callee.declNode.parentKey === 'id')) &&
Expand Down
10 changes: 6 additions & 4 deletions src/modules/safe/replaceEvalCallsWithLiteralContent.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,12 @@ import {generateHash} from '../utils/generateHash.js';
*/
function replaceEvalCallsWithLiteralContent(arb, candidateFilter = () => true) {
const cache = getCache(arb.ast[0].scriptHash);
for (let i = 0; i < arb.ast.length; i++) {
const n = arb.ast[i];
if (n.type === 'CallExpression' &&
n.callee?.name === 'eval' &&
const relevantNodes = [
...(arb.ast[0].typeMap.CallExpression || []),
];
for (let i = 0; i < relevantNodes.length; i++) {
const n = relevantNodes[i];
if (n.callee?.name === 'eval' &&
n.arguments[0]?.type === 'Literal' &&
candidateFilter(n)) {
const cacheName = `replaceEval-${generateHash(n.src)}`;
Expand Down
Loading
Loading