-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.js
1653 lines (1475 loc) · 66.1 KB
/
main.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
//================================Setup======================================
const HashMap = require('hashmap'); // load hashmap
const esprima = require('esprima'); // load esprima
const ASTUtils = require("esprima-ast-utils"); // load esprima-ast-utils
const Functions = require('./functions'); // load helper functions
const commandLineArgs = require('command-line-args'); // load command-line-args
const commandLineUsage = require('command-line-usage')
const fs = require('fs');
const myHeader = require('./assets/header')
const chalk = require('chalk')
//===================parse command line arguments============================
const optionDefinitions = [
{ name: 'verbose', alias: 'v', type: Number },
{ name: 'weight', alias: 'w', type: Boolean},
{ name: 'src', alias: 's', type: String },
{ name: 'header', alias: 'a', type: Boolean},
{ name: 'inplaceMode', alias: 'i', type: Boolean},
{ name: 'fastMode', alias: 'f', type: Boolean},
{ name: 'help', alias: 'h', type: Boolean}
]
const options = commandLineArgs(optionDefinitions)
const calcualteWeight = options.weight;
const verbose = (options.verbose === undefined) ? 0 : (options.verbose === null)? 1 : 2;
const showHeader = options.header;
const filePath = options.src;
const inplaceMode = options.inplaceMode;
const fastMode = options.fastMode;
const sections = [
{
content: chalk.green(myHeader),
raw: true
},
{
header: 'AMJ',
content: 'Analyser for Malicious JavaScript'
},
{
header: 'Options',
optionList: [
{
name: 'help', alias: 'h', description: 'Display this usage guide.'
},
{
name: 'src', alias: 's', description: 'The input files to process',
typeLabel: '{underline file}'
},
{
name: 'header', alias: 'a', description: 'The input files to process',
},
{
name: 'vervise', alias: 'v', description: '-v Printout features captured, -v 2 Debug mode',
},
{
name: 'weight', alias: 'w', description: 'Print weighted feature arrays',
},
{
name: 'inplaceMode', alias: 'i', description: 'When this flag is set, MJSA will unpack {underline eval()} inplace',
},
{
name: 'fastMode', alias: 'f', description: 'When this flag is set, MJSA will only parse at most 100 elements any objects and skip long instructions',
}
]
},
{
header: 'Examples',
content: [
{
desc: '1. Printout the capture features from {underline user.js}',
example: '$ node amj.js -s user.js -v'
},
{
desc: '2. Printout the weighted feature array from {underline user.js} in fast mode',
example: '$ node amj.js -s user.js -w -f'
}
]
},
{
content: 'Project home: {underline https://github.com/hl5814/AMJ}'
}
]
const usage = commandLineUsage(sections)
if (options.help) {
console.log(usage)
}
//===============================MainProgram=================================
var init_varMap = new Functions.VariableMap(new HashMap());
var pre_funcs = ["MJSA_TEST", "document", "eval", "unescape", "replace", "write", "writeln", "atob", "btoa", "toString", "String.fromCharCode", "fromCharCode",
"parseInt", "alert", "Array","charCodeAt" , "substr", "substring", "concat","join","split","reverse", "slice", "push"];
for (var f in pre_funcs) {
init_varMap.setVariable(pre_funcs[f], [{ type: 'pre_Function', value: pre_funcs[f] }] );
}
init_varMap.setVariable("String", [{ type: 'ObjectExpression', value: {"fromCharCode": [{type: 'pre_Function', value: "fromCharCode"}]} }] );
var resultMap = new HashMap();
const FEATURES = [ "VariableWithFunctionExpression", // x = function(){};
"VariableWithExpression",
"VariableWithThisExpression", // x = this;
"VariableWithUnaryExpression", // x = -a;
"VariableWithBinaryExpression", // x = a + b;
"VariableWithCallExpression", // x = eval(xx)
"VariableWithLogicalExpression", // x = 1^2;
"VariableWithBitOperation", // x = 0||1&&2;
"FunctionObfuscation", // x = eval;
"StringConcatenation", // "a"+"b"
"PredefinedFuncCalls", // String.fromCharCode(65)
"DOCUMENT_Operations", // document.write(..)
"WINDOW_Operations", // window.btoa(..)
"FuncCallOnBinaryExpr", // foo(x+y)
"FuncCallOnUnaryExpr", // bar(-x)
"FuncCallOnStringVariable", // foo("x") where function must be defined either by user or predefined
"FuncCallOnCallExpr", // foo(var(x));
"FuncCallOnNonLocalArray", // foo(x[2]) where x is not defined in scope
"FuncCallOnUnkonwnReference", // foo(x.f) or foo(x[y]) where x is defiend but f and y not defeind in scope
"HtmlCommentInScriptBlock", // <script> <!-- xxx //--> </script>
"AssigningToThis", // this = 1;
"ConditionalCompilationCode", // @cc_on|@if|@end|@_win32|@_win64
"DotNotationInFunctionName", // function a.prototype(){}
"LongArray", // array contains >1000 elements (e.g.var x = [1,2,3,...., 1000])
"LongExpression", // expression > 1000 tokens (e.g. var x = 1+2+3+4+...+1000);
"UnfoldEvalSuccess", // eval(..)
"Unescape", // ..unescape(..)
"UnfoldUnescapeSuccess"] // execute unescape successfully
const SCOPES = [ "in_test",
"in_main",
"in_if",
"in_loop",
"in_function",
"in_try",
"in_switch",
"in_return",
"in_file"];
const KEYWORDS = [ "break", "case", "catch", "continue", "debugger", "default",
"delete", "do", "else", "finally", "for", "function", "if",
"in", "instanceof", "new", "return", "switch", "this", "throw",
"try", "typeof", "var", "const", "void", "while", "with","document","MY_MJSA_THIS"];
const PUNCTUATORS = [ "!","!=","!==","%","%=","&","&&","&=","(",")","*","*=","+",
"++","+=",",","-","--","-=",".","/","/=",":",";","<","<<","<<=",
"<=","=","==","===",">",">=",">>",">>=",">>>",">>>=","?","[","]",
"^","^=","{","|","|=","||","}","~"];
const LENGTH = ["TokenPerFile", "CommentPerFile"]
for (const k of KEYWORDS) resultMap.set(k, 0);
for (const p of PUNCTUATORS) resultMap.set(p, 0);
for (const f of FEATURES) resultMap.set(f, 0);
for (const s of SCOPES) resultMap.set(s, 0);
for (const l of LENGTH) resultMap.set(l, 0);
var FILE_LENGTH = 0;
var COMMENT_LENGTH = 0;
var FEATURE_TOTAL = 0;
var SCOPE_TOTAL = 0;
var KEYWORD_TOTAL = 0;
var PUNCTUATOR_TOTAL = 0;
function updateResultMap(resultMap, featureType, scope, point=1) {
var prevValue = resultMap.get(featureType);
resultMap.set(featureType, prevValue+point);
FEATURE_TOTAL++;
for (var s of scope) {
prevValue = resultMap.get(s);
resultMap.set(s, prevValue+point);
SCOPE_TOTAL++;
}
}
function showResult(resultMap) {
var resultArray = [];
if (FILE_LENGTH > 0) {
resultMap.set("CommentPerFile", (COMMENT_LENGTH/FILE_LENGTH).toFixed(4));
}
resultMap.forEach(function(value, key){
console.log(value,key)
if (KEYWORDS.indexOf(key) > -1) {
var val = (value > 0) ? (value/KEYWORD_TOTAL).toFixed(4) : 0;
} else if (PUNCTUATORS.indexOf(key) > -1) {
var val = (value > 0) ? (value/PUNCTUATOR_TOTAL).toFixed(4) : 0;
} else if (FEATURES.indexOf(key) > -1) {
var val = (value > 0) ? (value/FEATURE_TOTAL).toFixed(4) : 0;
} else if (SCOPES.indexOf(key) > -1) {
var val = (value > 0) ? (value/SCOPE_TOTAL).toFixed(4) : 0;
} else {
var val = value;
}
resultArray.push(val);
});
console.log(`"`+filePath+`",`+resultArray)
}
function printHeader(resultMap) {
var header = [];
resultMap.forEach(function(value, key){
header.push(`"`+key+`"`);
});
console.log("header,"+header);
}
function listEqual(list1, list2) {
if (list1.length != list2.length) return false;
for (var i in list1) {
if (list1[i].type != list2[i].type ||
list1[i].value != list2[i].value)
return false;
}
return true;
}
Set.prototype.my_add=function(values){
var hasSame = false;
var toAddList = [];
for (var v in values) {
var exists = false;
this.forEach(function(item) {
if (values[v].type == "ArrayExpression") {
for (var val in values[v].value) {
if (item[0].value[val] === undefined) continue;
// console.log("values[v].value[val]", values[v].value[val])
// console.log("item[0].value[val]", item[0].value[val])
if (values[v].value[val][0] != item[0].value[val][0]) {
// if (values[v].value[val][0] == item[0].value[val][0]) {
if (item[0].value[val][0] === undefined) continue;
if (item[0].type == 'Null' || item[0].type == "undefined") {
continue;
}
item[0].value[val].push(values[v].value[val][0]);
// console.log("->item[0].value[val]", item[0].value[val])
// }
exists = false;
break;
}
}
exists = true;
} else if (values[v].type == "ObjectExpression") {
for (var val in values[v].value) {
if (item[0].value[val] === undefined) continue;
if (values[v].value[val][0] != item[0].value[val][0]) {
item[0].value[val].push(values[v].value[val][0]);
exists = false;
break;
}
}
exists = true;
} else if (values[v].type == item[0].type && values[v].value == item[0].value) {
exists = true;
}
});
if (!exists) {
this.add([values[v]]);
}
}
}
var FuncDepthCount = 0;
function parseFuncBody(thisAST, func, args, funcName, scope, coefficient, varMap, verbose=false){
if (FuncDepthCount++ > 5000) return;
try{
var eVarMap = new Functions.VariableMap(varMap._varMap);
var diffMap = new Functions.VariableMap(new HashMap());
var trueArgs = [];
if (args !== undefined) {
for (var a of args) {
if (a.type == "CallExpression") {
var fName = a.value.callee.name;
if (fName === undefined) { }
var rValue;
try {
const funcBodyVarMapList = parseProgram(ASTUtils.getCode(a.value), fName, coefficient, eVarMap, verbose);
var hasReturnValue = eVarMap.get(fName+"_return");
if (hasReturnValue !== undefined && hasReturnValue.length >0) {
rValue = hasReturnValue.pop();
} else {
var returnValue;
var innerFunc = eVarMap.get(fName)[0];
if (innerFunc.type == "user_Function") {
ASTUtils.traverse(innerFunc.value, function(node){
if (node.type == "ReturnStatement" && node.argument !== null){
rValue = thisAST.getVariableInitValue("", node.argument, eVarMap, verbose)[1];
}
});
funcBodyVarMapList.forEach(function(val1) {
var prevVal = varMap.get(val1.key);
if (prevVal !== undefined) {
var typeSet = new Set();
typeSet.my_add(val1.value);
diffMap.setVariable(val1.key, typeSet);
}
});
diffMap.multipleUpdate(varMap);
}
}
} catch(err){}
if (rValue !== undefined) {
trueArgs = trueArgs.concat(rValue);
} else {
trueArgs.push(a)
}
} else {
trueArgs.push(a)
}
}
}
var parameters = func.value.params;
var parameterList = [];
var argMap = {};
var codeBody = ASTUtils.getCode(func.value.body).slice(1, -1);
var assignString = "";
if (parameters !== undefined && codeBody !== undefined) {
var funcArguments = [];
for (var ta in trueArgs) {
var tta = trueArgs[ta];
if (tta instanceof Array) {
funcArguments = funcArguments.concat(tta);
} else {
funcArguments.push(tta)
}
}
if (funcArguments !== undefined) {
for (var a in funcArguments) {
var arg = funcArguments[a];
if (arg !== undefined && arg.type == "ArrayMemberExpression") {
var elementValue = thisAST.getTrueValueFromMemberExpression([arg], varMap, verbose)[0];
if (parameters[a] !== undefined) {
if (parameters[a].type == "Identifier") {
parameterList.push(parameters[a].name);
assignString += ("var " + parameters[a].name + " = " + elementValue.value + ";");
} else if (parameters[a].type == "AssignmentPattern") { }
}
} else if (arg !== undefined && arg.type == "Numeric" || arg.type == "String") {
if (parameters[a] !== undefined) {
if (parameters[a].type == "Identifier") {
parameterList.push(parameters[a].name);
assignString += ("var " + parameters[a].name + " = " + arg.value + ";");
} else if (parameters[a].type == "AssignmentPattern") { }
}
} else if (arg !== undefined && arg.type == "Identifier") {
var globalValue = varMap.get(arg.value);
if (parameters[a] !== undefined) {
if (parameters[a].type == "Identifier") {
parameterList.push(parameters[a].name);
if (globalValue !== undefined) {
argMap[parameters[a].name] = arg.value;
eVarMap.setVariable(parameters[a].name, globalValue);
} else {
assignString += ("var " + parameters[a].name + " = " + arg.value + ";");
}
} else if (parameters[a].type == "AssignmentPattern") { }
}
}
}
}
codeBody = assignString + codeBody;
const funcBodyVarMapList = parseProgram(codeBody, funcName, coefficient, eVarMap, verbose);
var rVal = [];
var hasReturnValue = eVarMap.get(funcName+"_return");
if (hasReturnValue !== undefined && hasReturnValue.length >0) {
rVal = hasReturnValue.pop();
} else {
ASTUtils.traverse(func.value, function(node){
if (node.type == "ReturnStatement" && node.argument !== null){
rVal.push(thisAST.getVariableInitValue("", node.argument, eVarMap, verbose)[1]);
}
});
funcBodyVarMapList.forEach(function(val1) {
var prevVal = varMap.get(val1.key);
if (prevVal !== undefined && (parameterList.indexOf(val1.key) == -1)) {
var typeSet = new Set();
typeSet.my_add(val1.value);
diffMap.setVariable(val1.key, typeSet);
} else {
if (argMap.hasOwnProperty(val1.key)) {
var typeSet = new Set();
typeSet.my_add(val1.value);
diffMap.setVariable(argMap[val1.key], typeSet);
}
}
});
diffMap.multipleUpdate(varMap);
}
}
var validReturn = [];
if (rVal !== undefined && rVal.length >0) {
for (var r of rVal){
if (r.type != "undefined" && r.value != "undefined") {
validReturn.push(r);
}
}
}
if (validReturn.length > 0) {
return validReturn;
}
} catch(err){}
}
function parseProgram(program, scope, coefficient, varMap, verbose, depth=0){
var NUMBER_OF_EVAL = 0;
if (program === null || program === undefined || program.replace(/\s+/g, "") == "") return varMap.toList();
var ast = ASTUtils.parse(program);
// parse main program tokens
if (scope == "User_Program") {
resultMap.set("TokenPerFile", (ast.tokens.length/FILE_LENGTH).toFixed(4));
for (const pt of ast.tokens) {
if (pt.type == "Keyword") {
var prevValue = resultMap.get(pt.value);
resultMap.set(pt.value, prevValue+1);
KEYWORD_TOTAL++;
} else if (pt.type == "Punctuator") {
var prevValue = resultMap.get(pt.value);
resultMap.set(pt.value, prevValue+1);
PUNCTUATOR_TOTAL++;
} else if (pt.type == "Identifier") {
if (pt.value == "document") {
var prevValue = resultMap.get(pt.value);
resultMap.set(pt.value, prevValue+1);
KEYWORD_TOTAL++;
}
}
}
}
var local_variables = [];
// iterate through each AST node
for (var i in ast.body){
var astNode = new Functions.AST(ast);
if (verbose>1 && (ast.body[i].type != "Line")) {
console.log("======================\n", ast.body[i],"\n======================\n");
}
if (ast.body[i].type == "Line" || ast.body[i].type == "Block") {
var commentLine = ASTUtils.getCode(ast.body[i]);
COMMENT_LENGTH += commentLine.length;
var hasAt = commentLine.match(/@cc_on|@if|@end|@_win32|@_win64/);
if (hasAt !== null) {
if (verbose>0) console.log("FEATURE[ConditionalCompilationCode]");
updateResultMap(resultMap, "ConditionalCompilationCode", coefficient);
}
}
var tokenLength = astNode.getRangeLengthOfExpression(i, ast);
if (tokenLength > 1000) {
if (verbose>0) console.log("FEATURE[LongExpression]:" + coefficient[coefficient.length-1] + ":" + scope + ":Expression with " + tokenLength + " tokens.");
updateResultMap(resultMap, "LongExpression", coefficient);
if (fastMode) continue;
}
/* Variable Declaration */
if (astNode.isVariableDeclaration(i)) {
ASTUtils.traverse(ast.body[i], function(node, parent){
if (node.type == "SequenceExpression") {
var exprs = node.expressions;
var codes = ASTUtils.getCode(node)
var startIndex = 0;
for (const exp of exprs) {
parseProgram(ASTUtils.getCode(exp), scope, coefficient, varMap, verbose);
}
}
});
var declaration_blocks = astNode.getAllDeclarationBlocks(i);
var declaration_kind = astNode.getAllDeclarationKind(i);
for (var block of declaration_blocks) {
var variableName_Type = astNode.getVariableInitValue(block.id.name, block.init, varMap, verbose);
var variableName_Types = variableName_Type[1];
// block scope declarations will be delete at the end of the scope
if (declaration_kind == "let" || declaration_kind == "const") {
local_variables.push(variableName_Type[0]);
}
varMap.setVariable(variableName_Type[0], variableName_Types, verbose)
var lastDeclaratorNode;
var found = false;
ASTUtils.traverse(ast.body[i], function(node, parent){
if (node.type == "VariableDeclarator") lastDeclaratorNode = node;
if (node.type == "FunctionExpression"){
if (verbose>0) console.log("FEATURE[VariableWithFunctionExpression]:" + coefficient[coefficient.length-1] + ":" + scope + ":Init Variable by:" + ASTUtils.getCode(parent));
var emptyVarMap = new Functions.VariableMap(varMap._varMap);
// assume all function parameters might be String type when parsing function body
astNode.updateFunctionParams(i, emptyVarMap);
var returnStatement = astNode.getReturnInstructions(i, emptyVarMap, ast);
var codeBody = ASTUtils.getCode(node);
astNode.removeJumpInstructions(i, ast);
// parse function body
var coef = coefficient.slice();
coef.push("in_function");
parseProgram(ASTUtils.getCode(node.body).slice(1,-1), ASTUtils.getCode(node), coef, emptyVarMap, verbose);
coef.push("in_return")
for (var returnS of returnStatement) {
// parse return statement
parseProgram(returnS, "ReturnStatement in " + codeBody, coef, emptyVarMap, verbose);
}
updateResultMap(resultMap, "VariableWithFunctionExpression", coefficient);
} else if (node.type == "BinaryExpression" && parent !== null && parent.type == "VariableDeclarator") {
var bitOperators = [">>", "<<", "|", "&", "^", "~", ">>>", ">>=", "<<=", "|=", "&=", "^=", "~=", ">>>="];
if (bitOperators.indexOf(node.operator) != -1) {
if (verbose>0) console.log("FEATURE[VariableWithBitOperation]:" + coefficient[coefficient.length-1] + ":" + scope + ":Init Variable by:" + ASTUtils.getCode(lastDeclaratorNode));
updateResultMap(resultMap, "VariableWithBitOperation", coefficient);
}
} else if (node.type == "UnaryExpression" && parent !== null && parent.type == "VariableDeclarator") {
if (node.operator == "~") {
if (verbose>0) console.log("FEATURE[VariableWithBitOperation]:" + coefficient[coefficient.length-1] + ":" + scope + ":Init Variable by:" + ASTUtils.getCode(lastDeclaratorNode));
updateResultMap(resultMap, "VariableWithBitOperation", coefficient);
}
} else if (node.type == "ThisExpression") {
if (verbose>0) console.log("FEATURE[VariableWithThisExpression]:" + coefficient[coefficient.length-1] + ":" + scope + ":Init Variable by:" + ASTUtils.getCode(lastDeclaratorNode));
updateResultMap(resultMap, "VariableWithThisExpression", coefficient);
} else if (node.type == "CallExpression" && !found) {
var callee;
if (node.callee.type == "MemberExpression") {
callee = node.callee.property.name;
} else if (node.callee.type == "FunctionExpression") {
astNode.removeJumpInstructions(i, ast);
var coef = coefficient.slice();
coef.push("in_function")
var funcBody = ASTUtils.getCode(node);
parseProgram(funcBody.slice(funcBody.indexOf("{"),funcBody.lastIndexOf("}")+1), "CallExpression", coef, varMap, verbose);
callee = node.callee.name;
} else {
callee = node.callee.name;
}
if (callee !== undefined ) {
var funcNames = varMap.get(callee);
if (funcNames !== undefined) {
for (var func of funcNames) {
if (func.type == "user_Function" && !fastMode){
var returnVal;
var args = astNode.getFunctionArguments(node, varMap);
var rVal = parseFuncBody(astNode, func, args, funcName, scope, coefficient, varMap, verbose);
if (rVal !== undefined) {
found = true;
varMap.setVariable(variableName_Type[0], rVal, verbose)
varMap.setVariable(funcName+"_return_"+variableName_Type[0], rVal, verbose);
}
}
}
}
}
}
});
for (var v in variableName_Types) {
if (variableName_Types[v] === undefined) continue;
if (variableName_Types[v].type == "ArrayExpression" || variableName_Types[v].type == "NewExpression") {
var numElements = astNode.getNumberOfElementsInArrayExpression(i, ast);
if (numElements > 1000){
if (verbose>0) console.log("FEATURE[LongArray]:" + coefficient[coefficient.length-1] + ":" + scope + ":" + variableName_Type[0] + " contains " + numElements + " objects");
updateResultMap(resultMap, "LongArray", coefficient);
}
} else if (variableName_Types[v].type == "pre_Function"){
if (verbose>0) console.log("FEATURE[FunctionObfuscation]:" + coefficient[coefficient.length-1] + ":" + scope + ":[", variableName_Type[0], "] -> [", variableName_Types[v].value, "]")
updateResultMap(resultMap, "FunctionObfuscation", coefficient);
} else if (variableName_Types[v].type == "BinaryExpression") {
if (verbose>0) console.log("FEATURE[VariableWithBinaryExpression]:" + coefficient[coefficient.length-1] + ":" + scope + ":Init Variable by:" + variableName_Type[0] + " = " +variableName_Types[v].value);
updateResultMap(resultMap, "VariableWithBinaryExpression", coefficient);
} else if (variableName_Types[v].type == "UnaryExpression") {
if (verbose>0) console.log("FEATURE[VariableWithUnaryExpression]:" + coefficient[coefficient.length-1] + ":" + scope + ":Init Variable by:" + variableName_Type[0] + " = " +variableName_Types[v].value);
updateResultMap(resultMap, "VariableWithUnaryExpression", coefficient);
} else if (variableName_Types[v].type == "CallExpression"){
if (verbose>0) console.log("FEATURE[VariableWithCallExpression]:" + coefficient[coefficient.length-1] + ":" + scope + ":Init Variable by:" + ASTUtils.getCode(ast.body[i]));
updateResultMap(resultMap, "VariableWithCallExpression", coefficient);
} else if (variableName_Types[v].type == "LogicalExpression"){
if (verbose>0) console.log("FEATURE[VariableWithLogicalExpression]:" + coefficient[coefficient.length-1] + ":" + scope + ":Init Variable by:" + variableName_Type[0] + " = " +variableName_Types[v].value);
updateResultMap(resultMap, "VariableWithLogicalExpression", coefficient);
} else if (variableName_Types[v].type == "Expression"){
if (verbose>0) console.log("FEATURE[VariableWithExpression]:" + coefficient[coefficient.length-1] + ":" + scope + ":Init Variable by:" + variableName_Type[0] + " = " +variableName_Types[v].value);
updateResultMap(resultMap, "VariableWithExpression", coefficient);
}
// else
}
}
} else if (astNode.isExpressionStatement(i)) {
var exprList = [];
if (astNode.isSequenceExpression(i)) {
for (var expression of ast.body[i].expression.expressions) {
exprList.push(expression);
}
}
if (astNode.isAssignmentExpression(i) || exprList.length > 0) {
if (astNode.isAssignmentExpression(i)) {
exprList.push(ast.body[i].expression);
}
for (var expression of exprList){
var var_values = astNode.getAssignmentLeftRight(expression, varMap, verbose);
var lastAssignmentNode;
var found = false;
ASTUtils.traverse(expression, function(node, parent){
if (node.type == "AssignmentExpression") lastAssignmentNode = node;
if (node.type == "SequenceExpression" && parent !== null && parent.type == "AssignmentExpression") {
var exprs = node.expressions;
var codes = ASTUtils.getCode(node)
var startIndex = 0;
for (const exp of exprs) {
parseProgram(ASTUtils.getCode(exp), scope, coefficient, varMap, verbose);
}
} else if (node.type == "ArrayExpression" && parent !== null && parent.type == "AssignmentExpression"){
if (node.elements.length > 1000){
if (verbose>0) console.log("FEATURE[LongArray] : " + var_values[0] + " contains " + node.elements.length + " objects");
updateResultMap(resultMap, "LongArray", coefficient);
}
} else if (node.type == "ThisExpression"){
if (verbose>0) console.log("FEATURE[VariableWithThisExpression]:" + coefficient[coefficient.length-1] + ":" + scope + ":Assign Variable by:" + ASTUtils.getCode(lastAssignmentNode));
updateResultMap(resultMap, "VariableWithThisExpression", coefficient);
} else if (node.type == "LogicalExpression" && parent !== null && parent.type == "AssignmentExpression"){
if (verbose>0) console.log("FEATURE[VariableWithLogicalExpression]:" + coefficient[coefficient.length-1] + ":" + scope + ":Assign Variable by:" + ASTUtils.getCode(lastAssignmentNode));
updateResultMap(resultMap, "VariableWithLogicalExpression", coefficient);
} else if (node.type == "AssignmentExpression") {
var var_value = astNode.checkStaticMemberFunctionCall(node, varMap);
if (var_value !== undefined) {
if (verbose>0) console.log("FEATURE[FunctionObfuscation]:" + coefficient[coefficient.length-1] + ":" + scope + ":[", var_value[0], "] -> [", var_value[1].value, "]")
updateResultMap(resultMap, "FunctionObfuscation", coefficient);
}
} else if (node.type == "CallExpression" && !found){
var callee;
if (node.callee.type == "MemberExpression") {
callee = node.callee.property.name;
} else if (node.callee.type == "FunctionExpression") {
astNode.removeJumpInstructions(i, ast);
// e.g. x = a[...] + (function foo(){...}());
// remove the call bracket at the end of function expression
// i.e. function a(){...}()
var coef = coefficient.slice();
coef.push("in_function")
var funcBody = ASTUtils.getCode(node);
parseProgram(funcBody.slice(funcBody.indexOf("{"),funcBody.lastIndexOf("}")+1), "CallExpression", coef, varMap, verbose);
callee = node.callee.name;
} else {
callee = node.callee.name;
}
if (callee !== undefined ) {
var funcNames = varMap.get(callee);
if (funcNames !== undefined) {
for (var func of funcNames) {
if (func.type == "user_Function" && !fastMode){
var returnVal;
var args = astNode.getFunctionArguments(node, varMap);
var rVal = parseFuncBody(astNode, func, args, funcName, scope, coefficient, varMap, verbose);
if (rVal !== undefined) {
var_values[1] = rVal;
found = true;
varMap.setVariable(funcName+"_return_"+var_values[0], rVal);
} else {
if (args !== undefined){
try{
for (var a of args){
if (a.type == "Identifier") {
var a_values = varMap.get(a.value);
for (var a_value of a_values) {
if (a_value.type == "String") {
if (verbose>0) console.log("FEATURE[FuncCallOnStringVariable]:" + coefficient[coefficient.length-1] + ":" + scope + ":"+ASTUtils.getCode(node));
updateResultMap(resultMap, "FuncCallOnStringVariable", coefficient);
}
}
} else if (a.type == "String") {
if (verbose>0) console.log("FEATURE[FuncCallOnStringVariable]:" + coefficient[coefficient.length-1] + ":" + scope + ":"+ASTUtils.getCode(node));
updateResultMap(resultMap, "FuncCallOnStringVariable", coefficient);
}
}
} catch(err){}
}
}
} else if (func.type == "pre_Function") {
if (verbose>0) console.log("FEATURE[PredefinedFuncCalls]:" + coefficient[coefficient.length-1] + ":" + scope + ":", ASTUtils.getCode(node));
updateResultMap(resultMap, "PredefinedFuncCalls", coefficient);
}
}
}
}
} else if (node.type == "FunctionExpression" && parent !== null && parent.type == "AssignmentExpression"){
if (verbose>0) console.log("FEATURE[VariableWithFunctionExpression]:" + coefficient[coefficient.length-1] + ":" + scope + ":Assign Variable by:" + ASTUtils.getCode(parent));
var emptyVarMap = new Functions.VariableMap(varMap._varMap);
// assume all function parameters might be String type when parsing function body
astNode.updateFunctionParams(i, emptyVarMap);
var returnStatement = astNode.getReturnInstructions(i, emptyVarMap, ast);
var codeBody = ASTUtils.getCode(node);
astNode.removeJumpInstructions(i, ast);
// parse function body
var coef = coefficient.slice();
coef.push("in_function");
parseProgram(ASTUtils.getCode(node.body).slice(1,-1), codeBody, coef, emptyVarMap, verbose);
coef.push("in_return");
for (var returnS of returnStatement) {
// parse return statement
parseProgram(returnS, "ReturnStatement in " + codeBody, coef, emptyVarMap, verbose);
}
updateResultMap(resultMap, "VariableWithFunctionExpression", coefficient);
} else if (node.type == "BinaryExpression" && parent !== null && parent.type == "AssignmentExpression") {
var bitOperators = [">>", "<<", "|", "&", "^", ">>>", ">>=", "<<=", "|=", "&=", "^=", "~=", ">>>="];
if (bitOperators.indexOf(node.operator) != -1) {
if (verbose>0) console.log("FEATURE[VariableWithBitOperation]:" + coefficient[coefficient.length-1] + ":" + scope + ":Assign Variable by:" + ASTUtils.getCode(parent));
updateResultMap(resultMap, "VariableWithBitOperation", coefficient);
}
} else if (node.type == "UnaryExpression" && parent !== null && parent.type == "AssignmentExpression") {
if (node.operator == "~") {
if (verbose>0) console.log("FEATURE[VariableWithBitOperation]:" + coefficient[coefficient.length-1] + ":" + scope + ":Assign Variable by:" + ASTUtils.getCode(parent));
updateResultMap(resultMap, "VariableWithBitOperation", coefficient);
}
}
});
// MemberExperssion objects:
// varMap has already been updated in getAssignmentLeftRight()
if (var_values == "SKIP") continue;
// Checking if MY_MJSA_THIS variable is been used on left hand side
if (var_values[0] == "MY_MJSA_THIS") {
var prevValue = resultMap.get("MY_MJSA_THIS");
resultMap.set("MY_MJSA_THIS", prevValue+1);
KEYWORD_TOTAL++;
if (verbose>0) console.log("FEATURE[AssigningToThis]:" + coefficient[coefficient.length-1] + ":" + scope + ":Assign Variable to 'this': " + ASTUtils.getCode(ast.body[i]));
updateResultMap(resultMap, "AssigningToThis", coefficient);
}
variableName_Types = var_values[1];
for (var v in variableName_Types) {
if (variableName_Types[v].type == "BinaryExpression") {
if (verbose>0) console.log("FEATURE[VariableWithBinaryExpression]:" + coefficient[coefficient.length-1] + ":" + scope + ":Assign Variable by:" + var_values[0] + " = " +variableName_Types[v].value);
updateResultMap(resultMap, "VariableWithBinaryExpression", coefficient);
} else if (variableName_Types[v].type == "UnaryExpression") {
if (verbose>0) console.log("FEATURE[VariableWithUnaryExpression]:" + coefficient[coefficient.length-1] + ":" + scope + ":Assign Variable by:" + var_values[0] + " = " +variableName_Types[v].value);
updateResultMap(resultMap, "VariableWithUnaryExpression", coefficient);
} else if (variableName_Types[v].type == "CallExpression"){
if (verbose>0) console.log("FEATURE[VariableWithCallExpression]:" + coefficient[coefficient.length-1] + ":" + scope + ":Assign Variable by:" + ASTUtils.getCode(ast.body[i]));
updateResultMap(resultMap, "VariableWithCallExpression", coefficient);
} else if (variableName_Types[v].type == "Expression"){
if (verbose>0) console.log("FEATURE[VariableWithExpression]:" + coefficient[coefficient.length-1] + ":" + scope + ":Assign Variable by:" + var_values[0] + " = " +variableName_Types[v].value);
updateResultMap(resultMap, "VariableWithExpression", coefficient);
}
}
varMap.updateVariable(var_values[0], var_values[1], verbose);
}
} else if (astNode.isUpdateExpression(i)) {
var var_value = astNode.getUpdateExpression(i, varMap, verbose);
// ++, --, etc.
} else {
// single identifier expressions, (e.g. x;) skip to next expression
if (astNode._node.body[i].expression.type == "Identifier") {
var var_values = varMap.get(astNode._node.body[i].expression.name);
if (var_values === undefined) {
varMap.updateVariable(astNode._node.body[i].expression.name, [{ type: 'undefined', value: 'undefined' }]);
}
continue;
}
var funcName = "";
// if expression is function call
if (astNode._node.body[i].expression.callee !== undefined) {
funcName = astNode.getCalleeName(i, varMap);
var callee = astNode.getVariableInitValue("", astNode._node.body[i].expression, varMap, verbose)[1];
}
var funcNames = varMap.get(funcName);
for (var f in funcNames) {
if (funcNames[f].type != "pre_Function" && funcNames[f].type != "user_Function" ) {
continue;
}
var user_defined_funName = "";
if (funcNames[f] != undefined && funcNames[f].value != funcName && funcNames[f].type == "pre_Function"){
user_defined_funName = funcName;
}
// try to execute the function call with user defined functions
if (funcNames[f].type == "user_Function" && !fastMode){
// console.log("==> here")
var returnVal;
var args = astNode.getFunctionArguments(astNode._node.body[i].expression, varMap);
var rVal = parseFuncBody(astNode, funcNames[f], args, funcName, scope, coefficient, varMap, verbose);
if (rVal !== undefined) {
var prevReturn = varMap.get(funcName+"_return");
if (prevReturn === undefined){
varMap.setVariable(funcName+"_return", [rVal]);
} else {
prevReturn.push(rVal);
varMap.setVariable(funcName+"_return", prevReturn);
}
continue;
}
}
if (funcNames[f].type == "pre_Function" || funcNames[f].type == "user_Function") {
var args = astNode.getFunctionArguments(astNode._node.body[i].expression, varMap);
// JS will ignore extra parameters, if function is defined with only one parameter
// Attacker might add more unuse d parameters to confuse the detector
if (args.length >= 1) {
for (var arg of args) {
if (arg.type == "String") {
if (verbose>0) console.log("FEATURE[FuncCallOnStringVariable]:" + coefficient[coefficient.length-1] + ":" + scope + ":" + funcName + "(STRING) => " + funcNames[f].value + "(" + arg.value + ")");
updateResultMap(resultMap, "FuncCallOnStringVariable", coefficient);
} else if (arg.type == "Identifier" ||
arg.type == "ArrayMemberExpression" ||
arg.type == "FieldMemberExpression" ) {
// pre-processing
if (arg.type == "ArrayMemberExpression") {
var object = arg.value[0];
var indices = arg.value[1];
var r_vs;
if (object instanceof Array) {
var indx = [];
while (object instanceof Array) {
var obj = varMap.get(object[0]);
indx = indx.concat(object[1]);
object = object[0];
}
try {
for (var ii = indx.length-1; ii >=0;ii--){
var objIndex = indx[ii].value;
if (obj !== undefined) {
if (obj[0].type == "ObjectExpression") {
objIndex = objIndex.replace(/"/g,"");
obj = obj[0].value[objIndex];
} else {
obj = obj[0].value[objIndex];
}
}
}
} catch (err) {
if (verbose>0) console.log("FEATURE[FuncCallOnUnkonwnReference]:" + coefficient[coefficient.length-1] + ":" + scope + ":" + ASTUtils.getCode(astNode._node.body[i]));
updateResultMap(resultMap, "FuncCallOnUnkonwnReference", coefficient);
}
r_vs = obj;
} else {
r_vs = varMap.get(object);
if (r_vs === undefined) {
if (verbose>0) console.log("FEATURE[FuncCallOnNonLocalArray]:" + coefficient[coefficient.length-1] + ":" + scope + ": Accessing non-local array object: " + ASTUtils.getCode(astNode._node.body[i]));
updateResultMap(resultMap, "FuncCallOnNonLocalArray", coefficient);
}
}
var ref_values = [];
for (var inx in indices){
// skip " when handling object field access aka o["f"] => o.f
// indices will be `"f"` instead of [{type:"Numeric", value:2}]
if (indices[inx] == "") continue;
index = indices[inx].value;
for (var r in r_vs){
var array_values = r_vs[r];
if (r_vs[r].type == "ObjectExpression") {
const field = r_vs[r].value[index.replace(/"/g,"")];
if (field !== undefined) {
ref_values = ref_values.concat(field);
}
continue;
}
if (r_vs[r].type == "ArrayExpression" || r_vs[r].type == "NewExpression") {
if (index !== undefined) {
try{
ref_values = ref_values.concat(r_vs[r].value[index]);
}catch (err) {
if (verbose>0) console.log("FEATURE[FuncCallOnUnkonwnReference]:" + coefficient[coefficient.length-1] + ":" + scope + ":" + ASTUtils.getCode(astNode._node.body[i]));
updateResultMap(resultMap, "FuncCallOnUnkonwnReference", coefficient);
}
}
}
}
}
} else if (arg.type == "FieldMemberExpression") {
var object = arg.value[0];
var fields = arg.value[1];
var r_vs = varMap.get(object);
if (object instanceof Array) {
var field = [];
while (object instanceof Array) {
var obj = varMap.get(object[0]);
field = field.concat(object[1]);
object = object[0];
}
try {
for (var ii = field.length-1; ii >=0;ii--){
var objIndex = field[ii].value;
if (obj !== undefined) {
if (obj[0].type == "ObjectExpression") {
obj = obj[0].value[objIndex];
} else {
obj = obj[0].value[objIndex];
}
}
}
} catch (err) {
if (verbose>0) console.log("FEATURE[FuncCallOnUnkonwnReference]:" + coefficient[coefficient.length-1] + ":" + scope + ":" + ASTUtils.getCode(astNode._node.body[i]));
updateResultMap(resultMap, "FuncCallOnUnkonwnReference", coefficient);
}
r_vs = obj;
}
var ref_values = [];
for (var f in fields) {
const field = fields[f];
for (var r in r_vs){
if (r_vs[r].type == "ObjectExpression" && field !== undefined) {
if (r_vs[r].value[field.value] === undefined) {
if (verbose>0) console.log("FEATURE[FuncCallOnUnkonwnReference]:" + coefficient[coefficient.length-1] + ":" + scope + ":" + ASTUtils.getCode(astNode._node.body[i]));
updateResultMap(resultMap, "FuncCallOnUnkonwnReference", coefficient);
} else {
ref_values = ref_values.concat(r_vs[r].value[field.value]);
}
}
}
}
} else {
/* args[0].type == "Identifier"
* we assume the parameter passed in can be type String */
var ref_values = varMap.get(arg.value, verbose);
if (ref_values === undefined) {
ref_values = [ { type: 'String', value: 'UNKNOWN' } ];
}
}
if (ref_values.length == 0) {
continue;
}
// ref_values are all possible values for one variable, e.g. {key:a, value:["Str1",0,"Str2"]}
for (var ref in ref_values) {
if (ref_values[ref] && ref_values[ref].type == "String") {
if (verbose>0) console.log("FEATURE[FuncCallOnStringVariable]:" + coefficient[coefficient.length-1] + ":" + scope + ":"+funcName+"(Object->STRING) => [" + arg.value + "] ==> "+funcName+"(" + ref_values[ref].value + ")");
updateResultMap(resultMap, "FuncCallOnStringVariable", coefficient);
} else if (ref_values[ref] && ref_values[ref].type == "Expression") {
if (verbose>0) console.log("FEATURE[FuncCallOnStringVariable]:" + coefficient[coefficient.length-1] + ":" + scope + ":"+funcName+"(Expr) => [" + arg.value + "] ==> "+funcName+"(" + ref_values[ref].value + ")");
updateResultMap(resultMap, "FuncCallOnStringVariable", coefficient);
}
}
} else if (arg.type == "BinaryExpression") {
if (verbose>0) console.log("FEATURE[FuncCallOnBinaryExpr]:" + coefficient[coefficient.length-1] + ":" + scope + ":"+funcName+"(" + arg.type + ") => "+funcName+"(" + arg.value + ")");
updateResultMap(resultMap, "FuncCallOnBinaryExpr", coefficient);
} else if (arg.type == "UnaryExpression") {
if (verbose>0) console.log("FEATURE[FuncCallOnUnaryExpr]:" + coefficient[coefficient.length-1] + ":" + scope + ":"+funcName+"(" + arg.type + ") => "+funcName+"(" + arg.value + ")");
updateResultMap(resultMap, "FuncCallOnUnaryExpr", coefficient);
} else if (arg.type == "CallExpression") {
if (verbose>0) console.log("FEATURE[FuncCallOnCallExpr]:" + coefficient[coefficient.length-1] + ":" + scope + ":"+funcName+"(" + arg.type + ") => "+ ASTUtils.getCode(astNode._node.body[i]));
updateResultMap(resultMap, "FuncCallOnCallExpr", coefficient);
} else { /* case for "Numeric"*/ }
}
}
}
}
}
} else if (astNode.isFunctionDeclaration(i)) {
// if node type is FunctionDeclaration, it must has function Name
var funcName = astNode.getFunctionName(i);
var funcBody = ASTUtils.getCode(ast.body[i]);