-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcli.js
More file actions
executable file
·301 lines (254 loc) · 9.33 KB
/
cli.js
File metadata and controls
executable file
·301 lines (254 loc) · 9.33 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
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
#!/usr/bin/env node
/**
* CLI interface for the JavaScript Reverse Engineering Tool
*/
const fs = require('fs');
const path = require('path');
const ReverseEngineer = require('./index.js');
const args = process.argv.slice(2);
function printHelp() {
console.log(`
JavaScript Reverse Engineering Tool
====================================
Usage:
reverse-engineer <command> <file> [options]
Commands:
analyze <file> - Analyze JavaScript code and show statistics
beautify <file> - Beautify/deobfuscate JavaScript code
strings <file> - Extract all unique strings from code
functions <file> - List all functions in the code
patterns <file> - Detect obfuscation patterns
complexity <file> - Analyze control flow and code complexity
report <file> - Generate full analysis report
Options:
-o, --output <file> - Save output to file (for beautify command)
-h, --help - Show this help message
Examples:
reverse-engineer analyze script.js
reverse-engineer beautify obfuscated.js -o clean.js
reverse-engineer strings malware.js
reverse-engineer report suspicious.js
`);
}
function readFile(filePath) {
try {
const fullPath = path.resolve(filePath);
if (!fs.existsSync(fullPath)) {
console.error(`Error: File not found: ${filePath}`);
process.exit(1);
}
return fs.readFileSync(fullPath, 'utf8');
} catch (error) {
console.error(`Error reading file: ${error.message}`);
process.exit(1);
}
}
function writeFile(filePath, content) {
try {
fs.writeFileSync(filePath, content, 'utf8');
console.log(`Output written to: ${filePath}`);
} catch (error) {
console.error(`Error writing file: ${error.message}`);
process.exit(1);
}
}
function main() {
if (args.length === 0 || args[0] === '-h' || args[0] === '--help') {
printHelp();
process.exit(0);
}
const command = args[0];
const filePath = args[1];
if (!filePath) {
console.error('Error: No input file specified');
printHelp();
process.exit(1);
}
const code = readFile(filePath);
const re = new ReverseEngineer(code);
switch (command) {
case 'analyze': {
console.log('\n=== Code Analysis ===\n');
const stats = re.getStatistics();
console.log('Statistics:');
console.log(` Total Lines: ${stats.totalLines}`);
console.log(` Non-Empty Lines: ${stats.nonEmptyLines}`);
console.log(` Functions: ${stats.functionCount}`);
console.log(` Variables: ${stats.variableCount}`);
console.log(` String Literals: ${stats.stringCount} (${stats.uniqueStrings} unique)`);
console.log(` Number Literals: ${stats.numberCount}`);
console.log(` Avg Line Length: ${stats.averageLineLength} chars`);
const patterns = re.getPatterns();
if (patterns.length > 0) {
console.log('\nDetected Patterns:');
patterns.forEach(p => console.log(` - ${p}`));
}
break;
}
case 'beautify': {
console.log('Beautifying code...');
const beautified = re.beautify();
if (!beautified) {
console.error('Error: Failed to beautify code');
process.exit(1);
}
const outputIndex = args.indexOf('-o') !== -1 ? args.indexOf('-o') : args.indexOf('--output');
if (outputIndex !== -1 && args[outputIndex + 1]) {
writeFile(args[outputIndex + 1], beautified);
} else {
console.log('\n' + beautified);
}
break;
}
case 'strings': {
console.log('\n=== Extracted Strings ===\n');
const strings = re.getStrings();
if (strings.length === 0) {
console.log('No strings found.');
} else {
strings.forEach((str, idx) => {
const preview = str.length > 60 ? str.substring(0, 60) + '...' : str;
console.log(`${idx + 1}. "${preview}"`);
});
console.log(`\nTotal: ${strings.length} unique strings`);
}
break;
}
case 'functions': {
console.log('\n=== Functions ===\n');
const functions = re.getFunctions();
if (functions.length === 0) {
console.log('No functions found.');
} else {
functions.forEach((func, idx) => {
const params = func.params.join(', ');
const modifiers = [];
if (func.async) modifiers.push('async');
if (func.generator) modifiers.push('generator');
const modStr = modifiers.length > 0 ? `[${modifiers.join(', ')}] ` : '';
console.log(`${idx + 1}. ${modStr}${func.name}(${params})`);
if (func.location) {
console.log(` Line: ${func.location.start.line}`);
}
});
console.log(`\nTotal: ${functions.length} functions`);
}
break;
}
case 'patterns': {
console.log('\n=== Detected Patterns ===\n');
const patterns = re.getPatterns();
if (patterns.length === 0) {
console.log('No suspicious patterns detected.');
} else {
patterns.forEach((pattern, idx) => {
console.log(`${idx + 1}. ${pattern}`);
});
}
break;
}
case 'complexity': {
console.log('\n=== Control Flow & Complexity Analysis ===\n');
const cf = re.getControlFlow();
// Complexity interpretation
let complexityLevel = 'Low';
let complexityColor = '✓';
if (cf.complexity > 20) {
complexityLevel = 'Very High';
complexityColor = '⚠⚠⚠';
} else if (cf.complexity > 10) {
complexityLevel = 'High';
complexityColor = '⚠⚠';
} else if (cf.complexity > 5) {
complexityLevel = 'Moderate';
complexityColor = '⚠';
}
console.log('COMPLEXITY METRICS:');
console.log(` Cyclomatic Complexity: ${cf.complexity} ${complexityColor}`);
console.log(` Complexity Level: ${complexityLevel}`);
console.log(` Max Nesting Depth: ${cf.maxNesting}`);
console.log(` Control Flow Structures: ${cf.structures.length}`);
if (cf.structures.length > 0) {
console.log('\nCONTROL FLOW STRUCTURES:');
// Group structures by type
const byType = {};
cf.structures.forEach(s => {
const type = s.type;
byType[type] = (byType[type] || 0) + 1;
});
Object.entries(byType).forEach(([type, count]) => {
console.log(` ${type}: ${count}`);
});
console.log('\nDETAILED STRUCTURES:');
cf.structures.forEach((struct, idx) => {
const indent = ' '.repeat(struct.nesting + 1);
let info = `${indent}${idx + 1}. ${struct.type}`;
if (struct.hasElse !== undefined) {
info += struct.hasElse ? ' (with else)' : ' (no else)';
}
if (struct.cases !== undefined) {
info += ` (${struct.cases} cases)`;
}
if (struct.hasCatch !== undefined || struct.hasFinally !== undefined) {
const parts = [];
if (struct.hasCatch) parts.push('catch');
if (struct.hasFinally) parts.push('finally');
info += ` (with ${parts.join(' and ')})`;
}
if (struct.location) {
info += ` [Line ${struct.location.start.line}]`;
}
console.log(info);
});
}
// Recommendations
console.log('\nRECOMMENDATIONS:');
const recs = re.getRecommendations();
recs.forEach(r => console.log(' ' + r));
break;
}
case 'report': {
console.log('\n=== Full Analysis Report ===\n');
const report = re.generateReport();
console.log('STATISTICS:');
console.log(` Total Lines: ${report.statistics.totalLines}`);
console.log(` Non-Empty Lines: ${report.statistics.nonEmptyLines}`);
console.log(` Functions: ${report.statistics.functionCount}`);
console.log(` Variables: ${report.statistics.variableCount}`);
console.log(` Unique Strings: ${report.statistics.uniqueStrings}`);
console.log(` Numbers: ${report.statistics.numberCount}`);
if (report.patterns.length > 0) {
console.log('\nDETECTED PATTERNS:');
report.patterns.forEach(p => console.log(` - ${p}`));
}
console.log('\nCOMPLEXITY:');
console.log(` Cyclomatic Complexity: ${report.controlFlow.complexity}`);
console.log(` Max Nesting Depth: ${report.controlFlow.maxNesting}`);
console.log(` Control Structures: ${report.controlFlow.structures.length}`);
console.log('\nFUNCTIONS:');
report.functions.slice(0, 10).forEach((func, idx) => {
console.log(` ${idx + 1}. ${func.name}(${func.params.join(', ')})`);
});
if (report.functions.length > 10) {
console.log(` ... and ${report.functions.length - 10} more`);
}
console.log('\nSAMPLE STRINGS:');
report.uniqueStrings.slice(0, 10).forEach((str, idx) => {
const preview = str.length > 50 ? str.substring(0, 50) + '...' : str;
console.log(` ${idx + 1}. "${preview}"`);
});
if (report.uniqueStrings.length > 10) {
console.log(` ... and ${report.uniqueStrings.length - 10} more`);
}
break;
}
default:
console.error(`Error: Unknown command: ${command}`);
printHelp();
process.exit(1);
}
}
if (require.main === module) {
main();
}
module.exports = { main };