forked from CapacitorSet/box-js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
_run.js
193 lines (163 loc) · 5.04 KB
/
_run.js
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
const cp = require("child_process");
const fs = require("fs");
const path = require("path");
const walk = require("walk-sync");
const argv = require("./argv.js").run;
// Read and format JSON flag documentation
if (argv.help || process.argv.length === 2) {
const columnify = require("columnify");
console.log(`box-js is a utility to analyze malicious JavaScript files.
Usage:
box-js [flags] <files|directories>
Pass a list of samples to be analyzed. Note that directories are searched
recursively, so you can pass a directory that contains several samples and
they will be analyzed in parallel.
Creates one .results directory for each sample; see README.md for more
information.
Flags:
`);
console.log(columnify(
require("./argv.js").flags.run.map((flag) => ({
name: (flag.alias ? `-${flag.alias}, ` : "") + `--${flag.name}`,
description: flag.description,
})),
{
config: {
description: {
maxWidth: 80,
},
},
}
));
process.exit(0);
}
if (argv.version) {
console.log(require("./package.json").version);
process.exit(0);
}
if (argv.license) {
console.log(fs.readFileSync(__dirname + "/LICENSE", "utf8"));
process.exit(0);
}
let timeout = argv.timeout;
if (!timeout) {
console.log("Using a 10 seconds timeout, pass --timeout to specify another timeout in seconds");
timeout = 10;
}
Array.prototype.functionalSplit = function(f) {
// Call f on every item, put it in a if f returns true, put it in b otherwise.
const a = [];
const b = [];
for (const elem of this)
if (f(elem))
a.push(elem);
else
b.push(elem);
return [a, b];
}
const args = process.argv.slice(2);
args.push(`--timeout=${timeout}`);
const [targets, options] = args.functionalSplit(fs.existsSync);
// Array of {filepath, filename}
const tasks = [];
const [folders, files] = targets.functionalSplit(path => fs.statSync(path).isDirectory());
files
.map(filepath => ({
filepath,
filename: path.basename(filepath),
}))
.forEach(task => tasks.push(task));
folders
.map(root => ({root, files: walk(root, {directories: false})}))
.map(({root, files}) => files.map(file => root + "/" + file))
.reduce((a, b) => a.concat(b), []) // flatten
.map(filepath => ({
filepath,
filename: path.basename(filepath),
}))
.forEach(task => tasks.push(task));
if (tasks.length === 0) {
console.log("Please pass one or more filenames or directories as an argument.");
process.exit(255);
}
// Prevent "possible memory leak" warning
process.setMaxListeners(Infinity);
const q = require("queue")();
// Screw you, buggy option parser
if (argv.threads === 0) q.concurrency = Infinity;
else if (argv.threads) q.concurrency = argv.threads;
else q.concurrency = require("os").cpus().length;
if (tasks.length > 1) // If batch mode
if (argv.threads)
console.log(`Analyzing ${tasks.length} items with ${q.concurrency} threads`)
else
console.log(`Analyzing ${tasks.length} items with ${q.concurrency} threads (use --threads to change this value)`)
const outputDir = argv["output-dir"] || "./";
tasks.forEach(({filepath, filename}) => q.push(cb => analyze(filepath, filename, cb)));
let completed = 0;
q.on("success", () => {
completed++;
if (tasks.length !== 1)
console.log(`Progress: ${completed}/${tasks.length} (${(100 * completed/tasks.length).toFixed(2)}%)`);
});
q.start();
function analyze(filepath, filename, cb) {
let directory = path.join(outputDir, filename + ".results");
// Find a suitable directory name
for (let i = 1; fs.existsSync(directory); i++)
directory = path.join(outputDir, filename + "." + i + ".results");
fs.mkdirSync(directory);
directory += "/"; // For ease of use
const worker = cp.fork(path.join(__dirname, "analyze"), [filepath, directory, ...options]);
const killTimeout = setTimeout(() => {
console.log(`Analysis for ${filename} timed out.`);
if (!argv.preprocess)
console.log("Hint: if the script is heavily obfuscated, --preprocess --unsafe-preprocess can speed up the emulation.");
worker.kill();
if (argv.debug) process.exit(2);
cb();
}, timeout * 1000);
let expectShellError = false;
worker.on("message", function(message) {
switch (message) {
case "expect-shell-error":
expectShellError = true;
break;
case "no-expect-shell-error":
expectShellError = false;
break;
}
});
worker.on("exit", function(code) {
if (argv.debug && expectShellError) {
// Use the appropriate exit code, as documented in the README
process.exit(5);
}
if (code === 1) {
console.log(`
* If the error is about a weird \"Unknown ActiveXObject\", try --no-kill.
* Otherwise, report a bug at https://github.com/CapacitorSet/box-js/issues/ .`);
}
clearTimeout(killTimeout);
worker.kill();
if (argv.debug) process.exit(code);
cb();
});
worker.on("error", function(err) {
console.log("error!");
console.log(err);
clearTimeout(killTimeout);
worker.kill();
if (argv.debug) process.exit(1);
cb();
});
process.on("exit", () => {
worker.kill();
cb();
});
process.on("SIGINT", () => {
worker.kill();
cb();
});
// process.on('uncaughtException', () => worker.kill());
}