-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathreplace_qauth.js
More file actions
210 lines (177 loc) Β· 7.54 KB
/
replace_qauth.js
File metadata and controls
210 lines (177 loc) Β· 7.54 KB
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
// @ts-check
const { JSDOM } = require('jsdom');
const traverse = require('@babel/traverse').default;
const parser = require('@babel/parser');
/**
* deobfuscateCode: Simple and direct approach - find calls, match with results, replace with executed values
*
* @param {string} sourceCode - Original source code
* @param {Array} originalResults - Analysis results from findAndResolveCalls
* @param {string} exposedSourceCode - Source code with window assignments
* @returns {Object} - { deobfuscatedCode: string, replacements: number, errors: Array }
*/
function deobfuscateCode(sourceCode, originalResults, exposedSourceCode) {
console.log('π Starting simple deobfuscation process...\n');
// Create lookup map for quick access
const resultsMap = new Map();
originalResults.forEach((result) => {
if (result.resolved && result.rootName) {
const key = `${result.calleeName}-${result.arguments.number}-${result.arguments.string}`;
resultsMap.set(key, result);
}
});
console.log(`π Created lookup map with ${resultsMap.size} resolvable calls`);
// Create JSDOM instance
let dom;
try {
dom = new JSDOM(`<!DOCTYPE html><html><head><script>${exposedSourceCode}</script></head><body></body></html>`, {
runScripts: 'dangerously',
resources: 'usable',
});
console.log('β
JSDOM created successfully');
} catch (error) {
console.error('β Failed to create JSDOM:', error.message);
return { deobfuscatedCode: sourceCode, replacements: 0, errors: [error.message] };
}
const window = dom.window;
let modifiedCode = sourceCode;
let replacementCount = 0;
const errors = [];
// Parse AST and find all function calls
try {
const ast = parser.parse(sourceCode, {
sourceType: 'module',
plugins: ['jsx', 'typescript'],
locations: true,
allowImportExportEverywhere: true,
allowReturnOutsideFunction: true,
});
// Collect all calls to replace (in reverse order to avoid position shifts)
const callsToReplace = [];
traverse(ast, {
CallExpression(path) {
const node = path.node;
// Match our pattern: function(number, string)
if (node.arguments.length !== 2) return;
const [arg0, arg1] = node.arguments;
if (arg0.type !== 'NumericLiteral' || arg1.type !== 'StringLiteral') return;
if (node.callee.type !== 'Identifier') return;
const calleeName = node.callee.name;
const numValue = arg0.value;
const strValue = arg1.value;
// Check if we have this call in our results
const key = `${calleeName}-${numValue}-${strValue}`;
const matchedResult = resultsMap.get(key);
if (matchedResult) {
callsToReplace.push({
start: node.start,
end: node.end,
calleeName,
numValue,
strValue,
rootName: matchedResult.rootName,
});
}
},
});
console.log(`π― Found ${callsToReplace.length} calls to replace`);
// Sort by position (reverse order)
callsToReplace.sort((a, b) => b.start - a.start);
// Replace each call
callsToReplace.forEach((call, index) => {
try {
const windowFuncName = `__${call.rootName}`;
if (typeof window[windowFuncName] !== 'function') {
errors.push(`Function window.${windowFuncName} not found`);
return;
}
// Execute the function
const result = window[windowFuncName](call.numValue, call.strValue);
// Format result
let formattedResult;
if (typeof result === 'string') {
formattedResult = JSON.stringify(result);
} else {
formattedResult = String(result);
}
// Replace in source code
const before = modifiedCode.substring(0, call.start);
const after = modifiedCode.substring(call.end);
modifiedCode = before + formattedResult + after;
replacementCount++;
console.log(
` β
[${index + 1}/${callsToReplace.length}] ${call.calleeName}(${call.numValue}, "${call.strValue}") β ${formattedResult}`
);
} catch (error) {
const errorMsg = `Failed to execute ${call.calleeName}(${call.numValue}, "${call.strValue}"): ${error.message}`;
errors.push(errorMsg);
console.log(` β [${index + 1}/${callsToReplace.length}] ${errorMsg}`);
}
});
} catch (parseError) {
console.error('β Failed to parse source code:', parseError.message);
errors.push(`Parse error: ${parseError.message}`);
}
// Clean up
dom.window.close();
console.log(`\nπ Deobfuscation complete: ${replacementCount} replacements applied`);
return {
deobfuscatedCode: modifiedCode,
replacements: replacementCount,
errors,
};
}
/**
* completeDeobfuscation: One-stop function for the entire process
*
* @param {string} sourceCode - Original source code
* @param {Object} analysisResult - Result from analyzeAndExpose function
* @returns {Object} - Complete deobfuscation results
*/
function completeDeobfuscation(sourceCode, analysisResult) {
console.log('π Starting complete deobfuscation workflow...\n');
const { originalResults, exposedSourceCode, stats } = analysisResult;
if (!originalResults || originalResults.length === 0) {
console.log('β No analysis results provided');
return {
success: false,
deobfuscatedCode: sourceCode,
replacements: 0,
errors: ['No analysis results provided'],
};
}
const result = deobfuscateCode(sourceCode, originalResults, exposedSourceCode);
const summary = {
totalCallsFound: originalResults.length,
resolvableCalls: originalResults.filter((r) => r.resolved).length,
successfulReplacements: result.replacements,
errors: result.errors.length,
rootFunctionsUsed: stats ? Object.keys(stats.rootFunctions).length : 0,
};
console.log('\n' + '='.repeat(60));
console.log(' DEOBFUSCATION COMPLETE');
console.log('='.repeat(60));
console.log(`π Summary:`);
console.log(` β’ Total calls found: ${summary.totalCallsFound}`);
console.log(` β’ Resolvable calls: ${summary.resolvableCalls}`);
console.log(` β’ Successful replacements: ${summary.successfulReplacements}`);
console.log(` β’ Failed executions: ${summary.errors}`);
console.log(` β’ Root functions used: ${summary.rootFunctionsUsed}`);
if (summary.resolvableCalls > 0) {
console.log(
` β’ Success rate: ${((summary.successfulReplacements / summary.resolvableCalls) * 100).toFixed(1)}%`
);
}
console.log('='.repeat(60));
return {
success: summary.successfulReplacements > 0,
deobfuscatedCode: result.deobfuscatedCode,
replacements: result.replacements,
errors: result.errors,
summary,
};
}
module.exports = {
deobfuscateCode,
completeDeobfuscation,
};