-
Notifications
You must be signed in to change notification settings - Fork 85
/
analyze.js
1317 lines (1188 loc) · 47.5 KB
/
analyze.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
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
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const lib = require("./lib");
const loop_rewriter = require("./loop_rewriter");
const equality_rewriter = require("./equality_rewriter");
const escodegen = require("escodegen");
const acorn = require("acorn");
const fs = require("fs");
const iconv = require("iconv-lite");
const path = require("path");
const {VM} = require("vm2");
const child_process = require("child_process");
const argv = require("./argv.js").run;
const jsdom = require("jsdom").JSDOM;
const dom = new jsdom(`<html><head></head><body></body></html>`);
const { DOMParser } = require('xmldom');
const filename = process.argv[2];
// JScriptMemberFunctionStatement plugin registration
// Plugin system is now different in Acorn 8.*, so commenting out.
//require("./patches/prototype-plugin.js")(acorn);
lib.debug("Analysis launched: " + JSON.stringify(process.argv));
lib.verbose("Box-js version: " + require("./package.json").version);
let git_path = path.join(__dirname, ".git");
if (fs.existsSync(git_path) && fs.lstatSync(git_path).isDirectory()) {
lib.verbose("Commit: " + fs.readFileSync(path.join(__dirname, ".git/refs/heads/master"), "utf8").replace(/\n/, ""));
} else {
lib.verbose("No git folder found.");
}
lib.verbose(`Analyzing ${filename}`, false);
const sampleBuffer = fs.readFileSync(filename);
let encoding;
if (argv.encoding) {
lib.debug("Using argv encoding");
encoding = argv.encoding;
} else {
lib.debug("Using detected encoding");
encoding = require("jschardet").detect(sampleBuffer).encoding;
if (encoding === null) {
lib.warning("jschardet (v" + require("jschardet/package.json").version + ") couldn't detect encoding, using UTF-8");
encoding = "utf8";
} else {
lib.debug("jschardet (v" + require("jschardet/package.json").version + ") detected encoding " + encoding);
}
}
let code = iconv.decode(sampleBuffer, encoding);
let rawcode;
if (argv["activex-as-ioc"]) {
rawcode = iconv.decode(sampleBuffer, encoding);
}
/*
if (code.match("<job") || code.match("<script")) { // The sample may actually be a .wsf, which is <job><script>..</script><script>..</script></job>.
lib.debug("Sample seems to be WSF");
code = code.replace(/<\??\/?\w+( [\w=\"\']*)*\??>/g, ""); // XML tags
code = code.replace(/<!\[CDATA\[/g, "");
code = code.replace(/\]\]>/g, "");
}
*/
function lacksBinary(name) {
const path = child_process.spawnSync("command", ["-v", name], {
shell: true
}).stdout;
return path.length === 0;
}
function escapeRegExp(string) {
return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string
}
function stripSingleLineComments(s) {
const lines = s.split("\n");
var r = "";
for (const line of lines) {
var lineStrip = line.trim() + "\r";
for (const subLine of lineStrip.split("\r")) {
// Full line comment?
var subLineStrip = subLine.trim();
if (subLineStrip.startsWith("//")) continue;
r += subLineStrip + "\n";
}
}
return r;
}
function isAlphaNumeric(str) {
var code, i;
if (str.length == 0) return false;
code = str.charCodeAt(0);
if (!(code > 47 && code < 58) && // numeric (0-9)
!(code > 64 && code < 91) && // upper alpha (A-Z)
!(code > 96 && code < 123)) { // lower alpha (a-z)
return false;
}
return true;
};
function hideStrs(s) {
var inStrSingle = false;
var inStrDouble = false;
var inStrBackTick = false;
var inComment = false;
var inCommentSingle = false;
var inRegex = false
var oldInRegex = false
var currStr = undefined;
var prevChar = "";
var prevPrevChar = "";
var allStrs = {};
var escapedSlash = false;
var prevEscapedSlash = false;
var counter = 1000000;
var r = "";
var skip = false;
var justExitedComment = false;
var slashSubstr = ""
var resetSlashes = false;
var justStartedRegex = false;
var inSquareBrackets = false;
var skippedSpace = false;
s = stripSingleLineComments(s);
// For debugging.
var window = " ";
// Special case. Regex uses like '/.../["test"]' are really hard
// to deal with. Hide all '["test"]' instances.
var tmpName = "HIDE_" + counter++;
s = s.replace(/\["test"\]/g, tmpName);
allStrs[tmpName] = '["test"]';
tmpName = "HIDE_" + counter++;
s = s.replace(/\['test'\]/g, tmpName);
allStrs[tmpName] = "['test']";
// Similar to the above, obfuscator.io constructs like
// '/.../[0x_fff(' are also really hard to deal with. Replace
// those also.
tmpName = "HIDE_" + counter++;
// Ony match exprs that start with the '/' and keep the '/' in the
// code to close out the regex. We are doing this because
// Replacement name must start with HIDE_.
s = s.replace(/\/\[_0x/g, "/" + tmpName);
allStrs[tmpName] = "[_0x";
//console.log("prevprev,prev,curr,dbl,single,commsingl,comm,regex,oldinregex,slash,justexitcom");
for (let i = 0; i < s.length; i++) {
// Track consecutive backslashes. We use this to tell if the
// current back slash has been escaped (even # of backslashes)
// or is escaping the next character (odd # of slashes).
if (prevChar == "\\" && (slashSubstr.length == 0)) {
slashSubstr = "\\";
}
else if (prevChar == "\\" && (slashSubstr.length > 0)) {
slashSubstr += "\\";
}
else if (prevChar != "\\") {
slashSubstr = "";
}
// Backslash escaping gets 'reset' when hitting a space.
var currChar = s[i];
if ((currChar == " ") && slashSubstr) {
slashSubstr = "";
resetSlashes = true;
}
// Debugging.
//window = window.slice(1,) + currChar;
//console.log(window);
// Start /* */ comment?
var oldInComment = inComment;
inComment = inComment || ((prevChar == "/") && (currChar == "*") && !inStrDouble && !inStrSingle && !inCommentSingle && !inStrBackTick && (!inRegex || !oldInRegex));
//console.log(JSON.stringify([prevPrevChar, prevChar, currChar, inStrDouble, inStrSingle, inCommentSingle, inComment, inRegex, oldInRegex, slashSubstr, justExitedComment]))
//console.log(r);
// In /* */ comment?
if (inComment) {
// We are stripping /* */ comments, so drop the '/' if we
// just entered the comment.
if (oldInComment != inComment) {
inRegex = false;
r = r.slice(0, -1);
}
// Dropping /* */ comments, so don't save current char.
// Out of comment?
if ((prevChar == "*") && (currChar == "/") && !skippedSpace) {
inComment = false;
// Handle FP single line comment detection for things
// like '/* comm1 *//* comm2 */'.
justExitedComment = true;
}
// Keep going until we leave the comment. Recognizing some
// constructs is hard with whitespace, so strip that out
// when tracking previous characters.
if (currChar != " ") {
prevPrevChar = prevChar;
prevChar = currChar;
skippedSpace = false;
}
else {
skippedSpace = true;
}
continue;
}
// Start // comment?
inCommentSingle = inCommentSingle || ((prevChar == "/") && (currChar == "/") && !inStrDouble && !inStrSingle && !inComment && !justExitedComment && !inStrBackTick);
// Could have falsely jumped out of a /**/ comment if it contains a //.
if ((prevChar == "/") && (currChar == "/") && !inComment && justExitedComment) {
inComment = true;
justExitedComment = false;
continue
}
justExitedComment = false;
// In // comment?
if (inCommentSingle) {
// Not in a regex if we are in a '// ...' comment.
inRegex = false;
// Save comment text unmodified.
r += currChar;
// Out of comment?
if ((currChar == "\n") || (currChar == "\r")) {
inCommentSingle = false;
}
// Keep going until we leave the comment.
if (currChar != " ") {
prevPrevChar = prevChar;
prevChar = currChar;
}
continue;
}
// Start /.../ regex expression?
oldInRegex = inRegex;
// Assume that regex expressions can't be preceded by ')' or
// an alphanumeric character. This is to try to tell divisiion
// from the start of a regex.
inRegex = inRegex || ((prevChar != "/") && (prevChar != ")") && !isAlphaNumeric(prevChar) &&
(currChar == "/") && !inStrDouble && !inStrSingle && !inComment && !inCommentSingle && !inStrBackTick);
// In /.../ regex expression?
if (inRegex) {
// Save regex unmodified.
r += currChar;
// In character set (square brackets)?
if (currChar == "[") inSquareBrackets = true;
if (currChar == "]") inSquareBrackets = false;
// Out of regex?
//
// Unescaped '/' can appear in a regex (nice). Try to
// guess whether the '/' actually ends the regex based on
// the char after the '/'. Add chars that CANNOT appear
// after a regex def as needed.
//
// ex. var f=/[!"#$%&'()*+,/\\:;<=>?@[\]^`{|}~]/g;
if (!justStartedRegex &&
!inSquareBrackets &&
(prevChar == "/") && (prevPrevChar != "\\") &&
((slashSubstr.length % 2) == 0) &&
("\\:[]?".indexOf(currChar) == -1)) {
inRegex = false;
}
// Track seeing the '/' starting the regex.
justStartedRegex = !oldInRegex;
// Keep going until we leave the regex.
if (currChar != " ") {
prevPrevChar = prevChar;
prevChar = currChar;
}
if (resetSlashes) prevChar = " ";
resetSlashes = false;
continue;
}
// Looking at an escaped back slash (1 char back)?
escapedSlash = (prevChar == "\\" && prevPrevChar == "\\");
// Start/end single quoted string?
if ((currChar == "'") &&
((prevChar != "\\") || ((prevChar == "\\") && ((slashSubstr.length % 2) == 0) && inStrSingle)) &&
!inStrDouble && !inStrBackTick) {
// Switch being in/out of string.
inStrSingle = !inStrSingle;
// Finished up a string we were tracking?
if (!inStrSingle) {
currStr += "'";
const strName = "HIDE_" + counter++;
allStrs[strName] = currStr;
r += strName;
skip = true;
}
else {
currStr = "";
}
};
// Start/end double quoted string?
if ((currChar == '"') &&
((prevChar != "\\") || ((prevChar == "\\") && ((slashSubstr.length % 2) == 0) && inStrDouble)) &&
!inStrSingle && !inStrBackTick && !inCommentSingle && !inComment && !inRegex) {
// Switch being in/out of string.
inStrDouble = !inStrDouble;
// Finished up a string we were tracking?
if (!inStrDouble) {
currStr += '"';
const strName = "HIDE_" + counter++;
allStrs[strName] = currStr;
r += strName;
skip = true;
}
else {
currStr = "";
}
};
// Start/end backtick quoted string?
if ((currChar == '`') &&
((prevChar != "\\") || ((prevChar == "\\") && escapedSlash && !prevEscapedSlash && inStrBackTick)) &&
!inStrSingle && !inStrDouble && !inCommentSingle && !inComment && !inRegex) {
// Switch being in/out of string.
inStrBackTick = !inStrBackTick;
// Finished up a string we were tracking?
if (!inStrBackTick) {
currStr += '`';
const strName = "HIDE_" + counter++;
allStrs[strName] = currStr;
r += strName;
skip = true;
}
else {
currStr = "";
}
};
// Save the current character if we are tracking a string.
if (inStrDouble || inStrSingle || inStrBackTick) {
currStr += currChar;
}
// Not in a string. Just save the original character in the
// result string.
else if (!skip) {
r += currChar;
};
skip = false;
// Track what is now the previous character so we can handle
// escaped quotes in strings.
prevPrevChar = prevChar;
if (currChar != " ") prevChar = currChar;
if (resetSlashes) prevChar = " ";
resetSlashes = false;
prevEscapedSlash = escapedSlash;
}
//console.log(JSON.stringify([prevPrevChar, prevChar, currChar, inStrDouble, inStrSingle, inCommentSingle, inComment, inRegex, slashSubstr, justExitedComment]))
return [r, allStrs];
}
function unhideStrs(s, map) {
// Replace each HIDE_NNNN with the hidden string.
var oldPos = 0;
var currPos = s.indexOf("HIDE_");
var r = "";
var done = (currPos < 0);
while (!done) {
// Add in the previous non-hidden string contents.
r += s.slice(oldPos, currPos);
// Pull out the name of the hidden string.
var tmpPos = currPos + "HIDE_".length + 7;
// Get the original string.
var hiddenName = s.slice(currPos, tmpPos);
var origVal = map[hiddenName];
// Add in the unhidden string.
r += origVal;
// Move to the next string to unhide.
oldPos = tmpPos;
currPos = s.slice(tmpPos).indexOf("HIDE_");
done = (currPos < 0);
currPos = tmpPos + currPos;
}
// Add in remaining original string that had nothing hidden.
r += s.slice(tmpPos);
// Done.
return r;
}
// JScript lets you stick the actual code to run in a conditional
// comment like '/*@if(@_jscript_version >= 4)....*/'. If there,
// extract that code out.
function extractCode(code) {
// See if we can pull code out from conditional comments.
// /*@if(@_jscript_version >= 4) ... @else @*/
// /*@if(1) ... @end@*/
//
// /*@cc_on
// @if(1) ... @end@*/
//
// /*@cc_on @*//*@if (1)
// ... @end @*/
const commentPat = /\/\*(?:@cc_on\s+)?@if\s*\([^\)]+\)(.+?)@(else|end)\s*@\s*\*\//s
var codeMatch = code.match(commentPat);
if (!codeMatch) {
const commentPat1 = /\/\*\s*@cc_on\s*@\*\/\s*\/\*\s*@if\s*\([^\)]+\)(.+?)@(else|end)\s*@\s*\*\//s;
codeMatch = code.match(commentPat1);
if (!codeMatch) {
// /*@cc_on\n...@*/
const commentPat2 = /\/\*\s*@cc_on *\r?\n(.+?)\r?\n@\*\//;
codeMatch = code.match(commentPat2);
if (!codeMatch) {
return code;
}
}
}
var r = codeMatch[1];
lib.info("Extracted code to analyze from conditional JScript comment.");
return r;
}
function rewrite(code, useException=false) {
//console.log("!!!! CODE: 0 !!!!");
//console.log(code);
//console.log("!!!! CODE: 0 !!!!");
// box-js is assuming that the JS will be run on Windows with cscript or wscript.
// Neither of these engines supports strict JS mode, so remove those calls from
// the code.
code = code.toString().replace(/"use strict"/g, '"STRICT MODE NOT SUPPORTED"');
code = code.toString().replace(/'use strict'/g, "'STRICT MODE NOT SUPPORTED'");
// The following 2 code rewrites should not be applied to patterns
// in string literals. Hide the string literals first.
//
// This also strips all comments.
var counter = 1000000;
const [newCode, strMap] = hideStrs(code);
code = newCode;
//console.log("!!!! CODE: 1 !!!!");
//console.log(code);
//console.log("!!!! CODE: 1 !!!!");
//console.log("!!!! STRMAP !!!!");
//console.log(strMap);
//console.log("!!!! STRMAP !!!!");
// WinHTTP ActiveX objects let you set options like 'foo.Option(n)
// = 12'. Acorn parsing fails on these with a assigning to rvalue
// syntax error, so rewrite things like this so we can parse
// (replace these expressions with comments). We have to do this
// with regexes rather than modifying the parse tree since these
// expressions cannot be parsed by acorn.
var rvaluePat = /[\n;][^\n^;]*?\([^\n^;]+?\)\s*=[^=^>][^\n^;]+?\r?(?=[;])/g;
code = code.toString().replace(rvaluePat, ';/* ASSIGNING TO RVALUE */');
rvaluePat = /[\n;][^\n^;]*?\([^\n^;]+?\)\s*=[^=^>][^\n^;]+?\r?(?=[\n])/g;
code = code.toString().replace(rvaluePat, ';// ASSIGNING TO RVALUE');
//console.log("!!!! CODE: 2 !!!!");
//console.log(code);
//console.log("!!!! CODE: 2 !!!!");
// Now unhide the string literals.
code = unhideStrs(code, strMap);
//console.log("!!!! CODE: 3 !!!!");
//console.log(code);
//console.log("!!!! CODE: 3 !!!!");
// Some samples (for example that use JQuery libraries as a basis to which to
// add malicious code) won't emulate properly for some reason if there is not
// an assignment line at the start of the code. Add one here (this should not
// change the behavior of the code).
code = "__bogus_var_name__ = 12;\n\n" + code;
if (code.match("@cc_on")) {
lib.debug("Code uses conditional compilation");
if (!argv["no-cc_on-rewrite"]) {
code = code
.replace(/\/\*@cc_on/gi, "")
.replace(/@cc_on/gi, "")
.replace(/\/\*@/g, "\n").replace(/@\*\//g, "\n");
// "@if" processing requires m4 and cc, but don't require them otherwise
if (/@if/.test(code)) {
/*
"@if (cond) source" becomes "\n _boxjs_if(cond)" with JS
"\n _boxjs_if(cond)" becomes "\n #if (cond) \n source" with m4
"\n #if (cond) \n source" becomes "source" with the C preprocessor
*/
code = code
.replace(/@if\s*/gi, "\n_boxjs_if")
.replace(/@elif\s*/gi, "\n_boxjs_elif")
.replace(/@else/gi, "\n#else\n")
.replace(/@end/gi, "\n#endif\n")
.replace(/@/g, "_boxjs_at");
// Require m4, cc
if (lacksBinary("cc")) lib.kill("You must install a C compiler (executable 'cc' not found).");
if (lacksBinary("m4")) lib.kill("You must install m4.");
code = `
define(\`_boxjs_if', #if ($1)\n)
define(\`_boxjs_elif', #elif ($1)\n)
` + code;
lib.info(" Replacing @cc_on statements (use --no-cc_on-rewrite to skip)...", false);
const outputM4 = child_process.spawnSync("m4", [], {
input: code
});
const outputCc = child_process.spawnSync("cc", [
"-E", "-P", // preprocess, don't compile
"-xc", // read from stdin, lang: c
"-D_boxjs_at_x86=1", "-D_boxjs_at_win16=0", "-D_boxjs_at_win32=1", "-D_boxjs_at_win64=1", // emulate Windows 32 bit
"-D_boxjs_at_jscript=1",
"-o-", // print to stdout
"-", // read from stdin
], {
input: outputM4.stdout.toString("utf8"),
});
code = outputCc.stdout.toString("utf8");
}
code = code.replace(/_boxjs_at/g, "@");
} else {
lib.warn(
`The code appears to contain conditional compilation statements.
If you run into unexpected results, try uncommenting lines that look like
/*@cc_on
<JavaScript code>
@*/
`
);
}
}
if (!argv["no-rewrite"]) {
try {
lib.verbose("Rewriting code...", false);
if (argv["dumb-concat-simplify"]) {
lib.verbose(" Simplifying \"dumb\" concatenations (remove --dumb-concat-simplify to skip)...", false);
code = code.replace(/'[ \r\n]*\+[ \r\n]*'/gm, "");
code = code.replace(/"[ \r\n]*\+[ \r\n]*"/gm, "");
}
let tree;
try {
//console.log("!!!! CODE FINAL !!!!");
//console.log(code);
//console.log("!!!! CODE FINAL !!!!");
tree = acorn.parse(code, {
ecmaVersion: "latest",
allowReturnOutsideFunction: true, // used when rewriting function bodies
plugins: {
// enables acorn plugin needed by prototype rewrite
JScriptMemberFunctionStatement: !argv["no-rewrite-prototype"],
},
});
} catch (e) {
if (useException) return 'throw("Parse Error")';
lib.error("Couldn't parse with Acorn:");
lib.error(e);
lib.error("");
if (filename.match(/jse$/)) {
lib.error(
`This appears to be a JSE (JScript.Encode) file.
Please compile the decoder and decode it first:
cc decoder.c -o decoder
./decoder ${filename} ${filename.replace(/jse$/, "js")}
`
);
} else {
lib.error(
// @@@ Emacs JS mode does not properly parse this block.
//`This doesn't seem to be a JavaScript/WScript file.
//If this is a JSE file (JScript.Encode), compile
//decoder.c and run it on the file, like this:
//
//cc decoder.c -o decoder
//./decoder ${filename} ${filename}.js
//
//`
"Decode JSE. 'cc decoder.c -o decoder'. './decoder ${filename} ${filename}.js'"
);
}
process.exit(4);
return;
}
// Loop rewriting is looking for loops in the original unmodified code so
// do this before any other modifications.
if (argv["rewrite-loops"]) {
lib.verbose(" Rewriting loops...", false);
traverse(tree, loop_rewriter.rewriteSimpleWaitLoop);
traverse(tree, loop_rewriter.rewriteSimpleControlLoop);
traverse(tree, loop_rewriter.rewriteLongWhileLoop);
};
// Rewrite == checks so that comparisons of the current script name to
// a hard coded script name always return true.
if (argv["loose-script-name"] && code.includes("==")) {
lib.verbose(" Rewriting == checks...", false);
traverse(tree, equality_rewriter.rewriteScriptCheck);
}
if (argv.preprocess) {
lib.verbose(` Preprocessing with uglify-es v${require("uglify-es/package.json").version} (remove --preprocess to skip)...`, false);
const unsafe = !!argv["unsafe-preprocess"];
lib.debug("Unsafe preprocess: " + unsafe);
const result = require("uglify-es").minify(code, {
parse: {
bare_returns: true, // used when rewriting function bodies
},
compress: {
passes: 3,
booleans: true,
collapse_vars: true,
comparisons: true,
conditionals: true,
dead_code: true,
drop_console: false,
evaluate: true,
if_return: true,
inline: true,
join_vars: false, // readability
keep_fargs: unsafe, // code may rely on Function.length
keep_fnames: unsafe, // code may rely on Function.prototype.name
keep_infinity: true, // readability
loops: true,
negate_iife: false, // readability
properties: true,
pure_getters: false, // many variables are proxies, which don't have pure getters
/* If unsafe preprocessing is enabled, tell uglify-es that Math.* functions
* have no side effects, and therefore can be removed if the result is
* unused. Related issue: mishoo/UglifyJS2#2227
*/
pure_funcs: unsafe ?
// https://stackoverflow.com/a/10756976
Object.getOwnPropertyNames(Math).map(key => `Math.${key}`) : null,
reduce_vars: true,
/* Using sequences (a; b; c; -> a, b, c) provides some performance benefits
* (https://github.com/CapacitorSet/box-js/commit/5031ba7114b60f1046e53b542c0e4810aad68a76#commitcomment-23243778),
* but it makes code harder to read. Therefore, this behaviour is disabled.
*/
sequences: false,
toplevel: true,
typeofs: false, // typeof foo == "undefined" -> foo === void 0: the former is more readable
unsafe,
unused: true,
},
output: {
beautify: true,
comments: true,
},
});
if (result.error) {
lib.error("Couldn't preprocess with uglify-es: " + JSON.stringify(result.error));
} else {
code = result.code;
}
}
if (!argv["no-rewrite-prototype"]) {
lib.verbose(" Replacing `function A.prototype.B()` (use --no-rewrite-prototype to skip)...", false);
traverse(tree, function(key, val) {
if (!val) return;
if (val.type !== "FunctionDeclaration" &&
val.type !== "FunctionExpression") return;
if (!val.id) return;
if (val.id.type !== "MemberExpression") return;
r = require("./patches/prototype.js")(val);
return r;
});
}
if (!argv["no-hoist-prototype"]) {
lib.verbose(" Hoisting `function A.prototype.B()` (use --no-hoist-prototype to skip)...", false);
hoist(tree);
}
if (argv["function-rewrite"]) {
lib.verbose(" Rewriting functions (remove --function-rewrite to skip)...", false);
traverse(tree, function(key, val) {
if (key !== "callee") return;
if (val.autogenerated) return;
switch (val.type) {
case "MemberExpression":
return require("./patches/this.js")(val.object, val);
default:
return require("./patches/nothis.js")(val);
}
});
}
if (!argv["no-typeof-rewrite"]) {
lib.verbose(" Rewriting typeof calls (use --no-typeof-rewrite to skip)...", false);
traverse(tree, function(key, val) {
if (!val) return;
if (val.type !== "UnaryExpression") return;
if (val.operator !== "typeof") return;
if (val.autogenerated) return;
return require("./patches/typeof.js")(val.argument);
});
}
if (!argv["no-eval-rewrite"]) {
lib.verbose(" Rewriting eval calls (use --no-eval-rewrite to skip)...", false);
traverse(tree, function(key, val) {
if (!val) return;
if (val.type !== "CallExpression") return;
if (val.callee.type !== "Identifier") return;
if (val.callee.name !== "eval") return;
return require("./patches/eval.js")(val.arguments);
});
}
if (!argv["no-catch-rewrite"]) { // JScript quirk
lib.verbose(" Rewriting try/catch statements (use --no-catch-rewrite to skip)...", false);
traverse(tree, function(key, val) {
if (!val) return;
if (val.type !== "TryStatement") return;
if (!val.handler) return;
if (val.autogenerated) return;
return require("./patches/catch.js")(val);
});
}
code = escodegen.generate(tree);
//console.log("!!!! CODE !!!!");
//console.log(code);
// The modifications may have resulted in more concatenations, eg. "a" + ("foo", "b") + "c" -> "a" + "b" + "c"
if (argv["dumb-concat-simplify"]) {
lib.verbose(" Simplifying \"dumb\" concatenations (remove --dumb-concat-simplify to skip)...", false);
code = code.replace(/'[ \r\n]*\+[ \r\n]*'/gm, "");
code = code.replace(/"[ \r\n]*\+[ \r\n]*"/gm, "");
}
lib.verbose("Rewritten successfully.", false);
} catch (e) {
if (argv["ignore-rewrite-errors"]) {
lib.warning("Code rewriting failed. Analyzing original sample.");
}
else {
console.log("An error occurred during rewriting:");
console.log(e);
process.exit(3);
}
}
}
return code;
}
// Extract the actual code to analyze from conditional JScript
// comments if needed.
if (argv["extract-conditional-code"]) {
code = extractCode(code);
}
// Track if we are throttling large/frequent file writes.
if (argv["throttle-writes"]) {
lib.throttleFileWrites(true);
};
// Track if we are throttling frequent command executions.
if (argv["throttle-commands"]) {
lib.throttleCommands(true);
};
// Rewrite the code if needed.
code = rewrite(code);
// prepend extra JS containing mock objects in the given file(s) onto the code
if (argv["prepended-code"]) {
var prependedCode = ""
var files = []
// get all the files in the directory and sort them alphebetically
var isDir = false;
try {
isDir = fs.lstatSync(argv["prepended-code"]).isDirectory();
}
catch (e) {}
if (isDir) {
dir_files = fs.readdirSync(argv["prepended-code"]);
for (var i = 0; i < dir_files.length; i++) {
files.push(path.join(argv["prepended-code"], dir_files[i]))
}
// make sure we're adding mock code in the right order
files.sort()
} else {
// Use default boilerplate code?
if (argv["prepended-code"] == "default") {
const defaultBP = __dirname + "/boilerplate.js";
files.push(defaultBP);
}
else {
files.push(argv["prepended-code"]);
}
}
for (var i = 0; i < files.length; i++) {
prependedCode += fs.readFileSync(files[i], 'utf-8') + "\n\n"
}
code = prependedCode + "\n\n" + code
}
// prepend patch code, unless it is already there.
if (!code.includes("let __PATCH_CODE_ADDED__ = true;")) {
code = fs.readFileSync(path.join(__dirname, "patch.js"), "utf8") + code;
}
else {
console.log("Patch code already added.");
}
// append more code
code += "\n\n" + fs.readFileSync(path.join(__dirname, "appended-code.js"));
lib.logJS(code);
Array.prototype.Count = function() {
return this.length;
};
// Set the fake scripting engine to report.
var fakeEngineShort = "wscript.exe"
if (argv["fake-script-engine"]) {
fakeEngineShort = argv["fake-script-engine"];
}
var fakeEngineFull = "C:\\WINDOWS\\system32\\" + fakeEngineShort;
// Fake command line options can be set with the --fake-cl-args option.
var commandLineArgs = [];
if (argv["fake-cl-args"]) {
commandLineArgs = argv["fake-cl-args"].split(",");
}
// Fake sample file name can be set with the --fake-sample-name option.
var sampleName = "CURRENT_SCRIPT_IN_FAKED_DIR.js";
var sampleFullName = "C:\Users\\Sysop12\\AppData\\Roaming\\Microsoft\\Templates\\" + sampleName;
if (argv["fake-sample-name"]) {
// Sample name with full path?
var dirChar = undefined;
if (argv["fake-sample-name"].indexOf("\\") >= 0) {
dirChar = "\\";
}
if (argv["fake-sample-name"].indexOf("/") >= 0) {
dirChar = "/";
}
if (dirChar) {
// Break out the immediate sample name and full name.
sampleName = argv["fake-sample-name"].slice(argv["fake-sample-name"].lastIndexOf(dirChar) + 1);
sampleFullName = argv["fake-sample-name"];
}
else {
sampleName = argv["fake-sample-name"];
sampleFullName = "C:\Users\\Sysop12\\AppData\\Roaming\\Microsoft\\Templates\\" + sampleName;
}
lib.logIOC("Sample Name",
{"sample-name": sampleName, "sample-name-full": sampleFullName},
"Using fake sample file name " + sampleFullName + " when analyzing.");
}
else if (argv["real-script-name"]) {
sampleName = path.basename(filename);
sampleFullName = filename;
lib.logIOC("Sample Name",
{"sample-name": sampleName, "sample-name-full": sampleFullName},
"Using real sample file name " + sampleFullName + " when analyzing.");
}
else {
lib.logIOC("Sample Name",
{"sample-name": sampleName, "sample-name-full": sampleFullName},
"Using standard fake sample file name " + sampleFullName + " when analyzing.");
}
// Fake up the WScript object for Windows JScript.
var wscript_proxy = new Proxy({
arguments: new Proxy((n) => commandLineArgs[n], {
get: function(target, name) {
name = name.toString().toLowerCase();
switch (name) {
case "unnamed":
return commandLineArgs;
case "length":
return commandLineArgs.length;
case "showUsage":
return {
typeof: "unknown",
};
case "named":
return commandLineArgs;
default:
return new Proxy(
target[name], {
get: (target, name) => name.toLowerCase() === "typeof" ? "unknown" : target[name],
}
);
}
},
}),
buildversion: "1234",
interactive: true,
fullname: fakeEngineFull,
name: fakeEngineShort,
path: "C:\\TestFolder\\",
scriptfullname: sampleFullName,
scriptname: sampleName,
quit: function() {
lib.logIOC("WScript", "Quit()", "The sample explicitly called WScript.Quit().");
//console.trace()
if ((!argv["ignore-wscript-quit"]) || lib.doWscriptQuit()) {
process.exit(0);
}
},
get stderr() {
lib.error("WScript.StdErr not implemented");
},
get stdin() {
lib.error("WScript.StdIn not implemented");
},
get stdout() {
lib.error("WScript.StdOut not implemented");
},
version: "5.8",
get connectobject() {
lib.error("WScript.ConnectObject not implemented");
},
createobject: ActiveXObject,
get disconnectobject() {
lib.error("WScript.DisconnectObject not implemented");
},
echo() {},
get getobject() {
lib.error("WScript.GetObject not implemented");
},
// Note that Sleep() is implemented in patch.js because it requires
// access to the variable _globalTimeOffset, which belongs to the script
// and not to the emulator.
[Symbol.toPrimitive]: () => "Windows Script Host",
tostring: "Windows Script Host",
}, {
get(target, prop) {
// For whatever reasons, WScript.* properties are case insensitive.
if (typeof prop === "string")
prop = prop.toLowerCase();
return target[prop];
}
});
const sandbox = {
saveAs : function(data, fname) {
// TODO: If Blob need to extract the data.
lib.writeFile(fname, data);
},
setInterval : function() {},
setTimeout : function(func, time) {
// The interval should be an int, so do a basic check for int.
if ((typeof(time) !== "number") || (time == null)) {
throw("time is not a number.");
}
// Just call the function immediately, no waiting.
if (typeof(func) === "function") {
func();
}