forked from echo094/decode-js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathobfuscator.js
executable file
·1272 lines (1231 loc) · 35.1 KB
/
obfuscator.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
/**
* 整合自下面两个项目:
* * cilame/v_jstools
* * Cqxstevexw/decodeObfuscator
*/
import { parse } from '@babel/parser'
import _generate from '@babel/generator'
import _traverse from '@babel/traverse'
import * as t from '@babel/types'
import * as vm from 'node:vm'
import { VM } from 'vm2'
const generator = _generate.default
const traverse = _traverse.default
let globalContext = vm.createContext()
let vm2 = new VM({
allowAsync: false,
sandbox: globalContext,
})
function virtualGlobalEval(jsStr) {
return vm2.run(String(jsStr))
}
function decodeObject(ast) {
let obj_node = {}
function collectObject(path) {
const id = path.node.id
const init = path.node.init
if (!t.isIdentifier(id) || !t.isObjectExpression(init)) {
return
}
const name = id.name
let valid = true
let count = 0
let obj = {}
for (const item of init.properties) {
if (!t.isObjectProperty(item) || !t.isLiteral(item.value)) {
valid = false
break
}
if (!t.isIdentifier(item.key)) {
valid = false
break
}
++count
obj[item.key.name] = item.value
}
if (!valid || !count) {
return
}
obj_node[name] = obj
}
traverse(ast, {
VariableDeclarator: collectObject,
})
let obj_used = {}
function replaceObject(path) {
const name = path.node.object
const key = path.node.property
if (!t.isIdentifier(name) || !t.isIdentifier(key)) {
return
}
if (!Object.prototype.hasOwnProperty.call(obj_node, name.name)) {
return
}
path.replaceWith(obj_node[name.name][key.name])
obj_used[name.name] = true
}
traverse(ast, {
MemberExpression: replaceObject,
})
function deleteObject(path) {
const id = path.node.id
const init = path.node.init
if (!t.isIdentifier(id) || !t.isObjectExpression(init)) {
return
}
const name = id.name
if (!Object.prototype.hasOwnProperty.call(obj_node, name)) {
return
}
path.remove()
let used = 'false'
if (Object.prototype.hasOwnProperty.call(obj_used, name)) {
used = 'true'
}
console.log(`删除对象: ${name} -> ${used}`)
}
traverse(ast, {
VariableDeclarator: deleteObject,
})
return ast
}
function decodeGlobal(ast) {
// 找到关键的函数
let ob_func_str = []
let ob_dec_name = []
let ob_string_func_name
// **Fallback**, in case the `find_ob_sort_list_by_feature` does not work
// Function to sort string list ("func2")
function find_ob_sort_func(path) {
function get_ob_sort(path) {
for (let arg of path.node.arguments) {
if (t.isIdentifier(arg)) {
ob_string_func_name = arg.name
break
}
}
if (!ob_string_func_name) {
return
}
let rm_path = path
while (!rm_path.parentPath.isProgram()) {
rm_path = rm_path.parentPath
}
ob_func_str.push('!' + generator(rm_path.node, { minified: true }).code)
path.stop()
rm_path.remove()
}
if (!path.getFunctionParent()) {
path.traverse({ CallExpression: get_ob_sort })
if (ob_string_func_name) {
path.stop()
}
}
}
// If the sort func is found, we can get the "func1" from its name.
function find_ob_sort_list_by_name(path) {
if (path.node.name != ob_string_func_name) {
return
}
if (path.findParent((path) => path.removed)) {
return
}
let is_list = false
let parent = path.parentPath
if (parent.isFunctionDeclaration() && path.key === 'id') {
is_list = true
} else if (parent.isVariableDeclarator() && path.key === 'id') {
is_list = true
} else if (parent.isAssignmentExpression() && path.key === 'left') {
is_list = true
} else {
let bind_path = parent.getFunctionParent()
while (bind_path) {
if (t.isFunctionExpression(bind_path)) {
bind_path = bind_path.parentPath
} else if (!bind_path.parentPath) {
break
} else if (t.isSequenceExpression(bind_path.parentPath)) {
// issue #11
bind_path = bind_path.parentPath
} else if (t.isReturnStatement(bind_path.parentPath)) {
// issue #11
// function _a (x, y) {
// return _a = function (p, q) {
// // #ref
// }, _a(x, y)
// }
bind_path = bind_path.getFunctionParent()
} else {
break
}
}
if (!bind_path) {
console.warn('Unexpected reference!')
return
}
ob_dec_name.push(bind_path.node.id.name)
ob_func_str.push(generator(bind_path.node, { minified: true }).code)
bind_path.remove()
}
if (is_list) {
ob_func_str.unshift(generator(parent.node, { minified: true }).code)
parent.remove()
}
}
// **Prefer** Find the string list func ("func1") by matching its feature:
// function aaa() {
// const bbb = [...]
// aaa = function () {
// return bbb;
// };
// return aaa();
// }
// After finding the possible func1, this method will check all the binding
// references and put the child encode function into list.
function find_ob_sort_list_by_feature(path) {
if (path.getFunctionParent()) {
return
}
if (
!t.isIdentifier(path.node.id) ||
path.node.params.length ||
!t.isBlockStatement(path.node.body) ||
path.node.body.body.length != 3
) {
return
}
const name_func = path.node.id.name
let string_var = -1
const body = path.node.body.body
try {
if (
body[0].declarations.length != 1 ||
!(string_var = body[0].declarations[0].id.name) ||
!t.isArrayExpression(body[0].declarations[0].init) ||
name_func != body[1].expression.left.name ||
body[1].expression.right.params.length ||
string_var != body[1].expression.right.body.body[0].argument.name ||
body[2].argument.arguments.length ||
name_func != body[2].argument.callee.name
) {
return
}
} catch {
//
}
const binding = path.scope.getBinding(name_func)
if (!binding.referencePaths) {
return
}
let paths = binding.referencePaths
let find_func2 = false
let path_remove = []
paths.map(function (refer_path) {
let bindpath = refer_path
if (t.isCallExpression(bindpath.parent)) {
if (name_func == bindpath.parent.callee.name) {
bindpath = bindpath.getFunctionParent()
if (name_func == bindpath.node.id.name) {
return
}
path_remove.push([bindpath, 'func3'])
} else if (name_func == bindpath.parent.arguments[0]?.name) {
bindpath = bindpath.parentPath
if (t.isExpressionStatement(bindpath.parent)) {
bindpath = bindpath.parentPath
}
find_func2 = true
path_remove.push([bindpath, 'func2'])
} else {
console.error('Unexpected reference')
}
}
})
if (!find_func2 || !path_remove.length) {
return
}
ob_string_func_name = name_func
ob_func_str.push(generator(path.node, { minified: true }).code)
path_remove.map(function (item) {
let bindpath = item[0]
if (item[1] == 'func3') {
ob_dec_name.push(bindpath.node.id.name)
}
ob_func_str.push(generator(bindpath.node, { minified: true }).code)
bindpath.remove()
})
path.stop()
path.remove()
}
traverse(ast, { FunctionDeclaration: find_ob_sort_list_by_feature })
if (!ob_string_func_name) {
console.warn('Try fallback mode...')
traverse(ast, { ExpressionStatement: find_ob_sort_func })
if (!ob_string_func_name) {
console.error('Cannot find string list!')
return false
}
traverse(ast, { Identifier: find_ob_sort_list_by_name })
if (ob_func_str.length < 3 || !ob_dec_name.length) {
console.error('Essential code missing!')
return false
}
}
console.log(`String List Name: ${ob_string_func_name}`)
virtualGlobalEval(ob_func_str.join(';'))
// 循环删除混淆函数
let call_dict = {}
let exist_names = ob_dec_name
let collect_codes = []
let collect_names = []
function do_parse_value(path) {
let name = path.node.callee.name
if (path.node.callee && exist_names.indexOf(name) != -1) {
let old_call = path + ''
try {
// 运行成功则说明函数为直接调用并返回字符串
let new_str = virtualGlobalEval(old_call)
console.log(`map: ${old_call} -> ${new_str}`)
call_dict[old_call] = new_str
} catch (e) {
// 运行失败则说明函数为其它混淆函数的子函数
console.log(`sub: ${old_call}`)
}
}
}
function do_collect_remove(path) {
// 可以删除所有已收集混淆函数的定义
// 因为根函数已被删除 即使保留也无法运行
let name = path.node?.left?.name
if (!name) {
name = path.node?.id?.name
}
if (exist_names.indexOf(name) != -1) {
// console.log(`del: ${name}`)
path.remove()
}
}
function do_collect_func(path) {
// function A (...) { return function B (...) }
if (
path.node.body.body.length == 1 &&
path.node.body.body[0].type == 'ReturnStatement' &&
path.node.body.body[0].argument?.type == 'CallExpression' &&
path.node.body.body[0].argument.callee.type == 'Identifier' &&
// path.node.params.length == 5 &&
path.node.id
) {
let call_func = path.node.body.body[0].argument.callee.name
if (exist_names.indexOf(call_func) == -1) {
return
}
let name = path.node.id.name
let t = generator(path.node, { minified: true }).code
if (collect_names.indexOf(name) == -1) {
collect_codes.push(t)
collect_names.push(name)
} else {
console.log(`err: redef ${name}`)
}
}
}
function do_collect_var(path) {
// var A = B
let left, right
if (t.isVariableDeclarator(path.node)) {
left = path.node.id
right = path.node.init
} else {
left = path.node.left
right = path.node.right
}
if (right?.type == 'Identifier' && exist_names.indexOf(right.name) != -1) {
let name = left.name
let t = 'var ' + generator(path.node, { minified: true }).code
if (collect_names.indexOf(name) == -1) {
collect_codes.push(t)
collect_names.push(name)
} else {
console.warning(`redef ${name}`)
}
}
}
while (exist_names.length) {
// 查找已收集混淆函数的调用并建立替换关系
traverse(ast, { CallExpression: do_parse_value })
// 删除被使用过的定义
traverse(ast, { FunctionDeclaration: do_collect_remove })
traverse(ast, { VariableDeclarator: do_collect_remove })
traverse(ast, { AssignmentExpression: do_collect_remove })
// 收集所有调用已收集混淆函数的混淆函数
collect_codes = []
collect_names = []
traverse(ast, { FunctionDeclaration: do_collect_func })
traverse(ast, { VariableDeclarator: do_collect_var })
traverse(ast, { AssignmentExpression: do_collect_var })
exist_names = collect_names
// 执行找到的函数
virtualGlobalEval(collect_codes.join(';'))
}
// 替换混淆函数
function do_replace(path) {
let old_call = path + ''
if (Object.prototype.hasOwnProperty.call(call_dict, old_call)) {
path.replaceWith(t.StringLiteral(call_dict[old_call]))
}
}
traverse(ast, { CallExpression: do_replace })
return true
}
function mergeObject(path) {
// var _0xb28de8 = {};
// _0xb28de8["abcd"] = function(_0x22293f, _0x5a165e) {
// return _0x22293f == _0x5a165e;
// };
// _0xb28de8.dbca = function(_0xfbac1e, _0x23462f, _0x556555) {
// return _0xfbac1e(_0x23462f, _0x556555);
// };
// _0xb28de8.aaa = function(_0x57e640) {
// return _0x57e640();
// };
// _0xb28de8["bbb"] = "eee";
// var _0x15e145 = _0xb28de8;
// |
// |
// |
// v
// var _0xb28de8 = {
// "abcd": function (_0x22293f, _0x5a165e) {
// return _0x22293f == _0x5a165e;
// },
// "dbca": function (_0xfbac1e, _0x23462f, _0x556555) {
// return _0xfbac1e(_0x23462f, _0x556555);
// },
// "aaa": function (_0x57e640) {
// return _0x57e640();
// },
// "bbb": "eee"
// };
const { id, init } = path.node
if (!t.isObjectExpression(init)) {
// 判断是否是定义对象
return
}
let name = id.name
let properties = init.properties
let scope = path.scope
let binding = scope.getBinding(name)
if (!binding || !binding.constant) {
// 确认该对象没有被多次定义
return
}
let paths = binding.referencePaths
// 添加已有的key
let keys = {}
for (let prop of properties) {
let key = null
if (t.isStringLiteral(prop.key)) {
key = prop.key.value
}
if (t.isIdentifier(prop.key)) {
key = prop.key.name
}
if (key) {
keys[key] = true
}
}
// 遍历作用域检测是否含有局部混淆特征并合并成员
let check = true
let dupe = false
let modified = false
let containfun = false
function checkFunction(right) {
if (!t.isFunctionExpression(right)) {
return false
}
// 符合要求的函数必须有且仅有一条return语句
if (right.body.body.length !== 1) {
return false
}
let retStmt = right.body.body[0]
if (!t.isReturnStatement(retStmt)) {
return false
}
// 检测是否是3种格式之一
if (t.isBinaryExpression(retStmt.argument)) {
return true
}
if (t.isLogicalExpression(retStmt.argument)) {
return true
}
if (t.isCallExpression(retStmt.argument)) {
// 函数调用类型 调用的函数必须是传入的第一个参数
if (!t.isIdentifier(retStmt.argument.callee)) {
return false
}
if (retStmt.argument.callee.name !== right.params[0].name) {
return false
}
return true
}
return false
}
function collectProperties(_path) {
const left = _path.node.left
const right = _path.node.right
if (!t.isMemberExpression(left)) {
return
}
const object = left.object
const property = left.property
if (!t.isIdentifier(object, { name: name })) {
return
}
let key = null
if (t.isStringLiteral(property)) {
key = property.value
}
if (t.isIdentifier(property)) {
key = property.name
}
if (!key) {
return
}
if (check) {
// 不允许出现重定义
if (Object.prototype.hasOwnProperty.call(keys, key)) {
dupe = true
return
}
// 判断是否为特征函数
containfun = containfun | checkFunction(right)
// 添加到列表
properties.push(t.ObjectProperty(t.valueToNode(key), right))
keys[key] = true
modified = true
} else {
if (
_path.parentPath.node.type == 'VariableDeclarator' ||
_path.parentPath.node.type == 'AssignmentExpression'
) {
_path.replaceWith(left)
} else {
_path.remove()
}
}
}
// 检测已有的key中是否存在混淆函数
for (let prop of properties) {
containfun = containfun | checkFunction(prop.value)
}
// 第一次遍历作用域
scope.traverse(scope.block, {
AssignmentExpression: collectProperties,
})
if (!modified) {
return
}
if (dupe) {
console.log(`不进行合并: ${name} dupe:${dupe} spec:${containfun}`)
return
}
// 第二次遍历作用域
console.log(`尝试性合并: ${name}`)
check = false
scope.traverse(scope.block, {
AssignmentExpression: collectProperties,
})
paths.map(function (refer_path) {
try {
let bindpath = refer_path.parentPath
if (!t.isVariableDeclarator(bindpath.node)) return
let bindname = bindpath.node.id.name
bindpath.scope.rename(bindname, name, bindpath.scope.block)
bindpath.remove()
} catch (e) {
console.log(e)
}
})
}
let loop_count = 0
let block_unlock_end = false
function unpackCall(path) {
// var _0xb28de8 = {
// "abcd": function(_0x22293f, _0x5a165e) {
// return _0x22293f == _0x5a165e;
// },
// "dbca": function(_0xfbac1e, _0x23462f, _0x556555) {
// return _0xfbac1e(_0x23462f, _0x556555);
// },
// "aaa": function(_0x57e640) {
// return _0x57e640();
// },
// "bbb": "eee",
// "ccc": A[x][y][...]
// };
// var aa = _0xb28de8["abcd"](123, 456);
// var bb = _0xb28de8["dbca"](bcd, 11, 22);
// var cc = _0xb28de8["aaa"](dcb);
// var dd = _0xb28de8["bbb"];
// var ee = _0xb28de8["ccc"];
// |
// |
// |
// v
// var aa = 123 == 456;
// var bb = bcd(11, 22);
// var cc = dcb();
// var dd = "eee";
// var ee = A[x][y][...];
let node = path.node
// 变量必须定义为Object类型才可能是代码块加密内容
if (!t.isObjectExpression(node.init)) {
return
}
let objPropertiesList = node.init.properties
if (objPropertiesList.length == 0) {
return
}
// 遍历Object 判断每个元素是否符合格式
let objName = node.id.name
let objKeys = {}
// 有时会有重复的定义
let replCount = 0
let containfun = false
objPropertiesList.map(function (prop) {
if (!t.isObjectProperty(prop)) {
return
}
let key = prop.key.value
if (t.isFunctionExpression(prop.value)) {
// 符合要求的函数必须有且仅有一条return语句
if (prop.value.body.body.length !== 1) {
return
}
let retStmt = prop.value.body.body[0]
if (!t.isReturnStatement(retStmt)) {
return
}
// 检测是否是3种格式之一
let repfunc = null
if (t.isBinaryExpression(retStmt.argument)) {
// 二元运算类型
repfunc = function (_path, args) {
_path.replaceWith(
t.binaryExpression(retStmt.argument.operator, args[0], args[1])
)
}
containfun = true
} else if (t.isLogicalExpression(retStmt.argument)) {
// 逻辑判断类型
repfunc = function (_path, args) {
_path.replaceWith(
t.logicalExpression(retStmt.argument.operator, args[0], args[1])
)
}
containfun = true
} else if (t.isCallExpression(retStmt.argument)) {
// 函数调用类型 调用的函数必须是传入的第一个参数
if (!t.isIdentifier(retStmt.argument.callee)) {
return
}
if (retStmt.argument.callee.name !== prop.value.params[0].name) {
return
}
repfunc = function (_path, args) {
_path.replaceWith(t.callExpression(args[0], args.slice(1)))
}
containfun = true
}
if (repfunc) {
objKeys[key] = repfunc
++replCount
}
} else if (t.isStringLiteral(prop.value)) {
let retStmt = prop.value.value
objKeys[key] = function (_path) {
_path.replaceWith(t.stringLiteral(retStmt))
}
++replCount
} else if (t.isMemberExpression(prop.value)) {
let retStmt = prop.value
objKeys[key] = function (_path) {
_path.replaceWith(retStmt)
}
++replCount
}
})
// 如果Object内的元素不全符合要求 很有可能是普通的字符串类型 不需要替换
if (!replCount) {
return
}
if (objPropertiesList.length !== replCount) {
console.log(
`不完整替换: ${objName} ${replCount}/${objPropertiesList.length}`
)
return
}
// 从第2轮循环开始 不含有混淆函数就不净化了
if (loop_count > 1 && !containfun) {
console.log(`无函数替换: ${objName}`)
return
}
// 遍历作用域进行替换 分为函数调用和字符串调用
console.log(`处理代码块: ${objName}`)
let objUsed = {}
let end = true
function getReplaceFunc(_node) {
// 这边的节点类型是 MemberExpression
if (!t.isIdentifier(_node.object) || _node.object.name !== objName) {
return null
}
// 这里开始所有的调用应该都在列表中
let key = null
if (t.isStringLiteral(_node.property)) {
key = _node.property.value
} else if (t.isIdentifier(_node.property)) {
key = _node.property.name
} else if (t.isMemberExpression(_node.property)) {
const code = generator(_node.property, { minified: true }).code
console.log(`嵌套的调用: ${objName}[${code}]`)
end = false
return null
} else {
const code = generator(_node.property, { minified: true }).code
console.log(`意外的调用: ${objName}[${code}]`)
return null
}
if (!Object.prototype.hasOwnProperty.call(objKeys, key)) {
// 这里应该是在死代码中 因为key不存在
return null
}
objUsed[key] = true
return objKeys[key]
}
const fnPath = path.getFunctionParent() || path.scope.path
fnPath.traverse({
CallExpression: function (_path) {
const _node = _path.node.callee
// 函数名必须为Object成员
if (!t.isMemberExpression(_node)) {
return
}
let func = getReplaceFunc(_node)
let args = _path.node.arguments
if (func) {
func(_path, args)
}
},
MemberExpression: function (_path) {
let func = getReplaceFunc(_path.node)
if (func) {
func(_path)
}
},
})
if (!end) {
// 出现嵌套调用
block_unlock_end = false
return
}
// 不管有没有全部使用 只要替换过就删除
const usedCount = Object.keys(objUsed).length
if (usedCount !== replCount) {
console.log(`不完整使用: ${objName} ${usedCount}/${replCount}`)
}
if (usedCount) {
path.remove()
}
}
function calcBinary(path) {
let tps = ['StringLiteral', 'BooleanLiteral', 'NumericLiteral']
let nod = path.node
function judge(e) {
return (
tps.indexOf(e.type) != -1 ||
(e.type == 'UnaryExpression' && tps.indexOf(e.argument.type) != -1)
)
}
function make_rep(e) {
if (typeof e == 'number') {
return t.NumericLiteral(e)
}
if (typeof e == 'string') {
return t.StringLiteral(e)
}
if (typeof e == 'boolean') {
return t.BooleanLiteral(e)
}
throw Error('unknown type' + typeof e)
}
if (judge(nod.left) && judge(nod.right)) {
path.replaceWith(make_rep(eval(path + '')))
}
}
function decodeCodeBlock(ast) {
// 合并字面量
traverse(ast, { BinaryExpression: { exit: calcBinary } })
// 先合并分离的Object定义
traverse(ast, { VariableDeclarator: { exit: mergeObject } })
// 在变量定义完成后判断是否为代码块加密内容
while (!block_unlock_end) {
block_unlock_end = true
++loop_count
traverse(ast, { VariableDeclarator: { exit: unpackCall } })
// 清理多余的语句避免死循环
traverse(ast, { UnaryExpression: purifyBoolean })
traverse(ast, { IfStatement: cleanIFCode })
traverse(ast, { ConditionalExpression: cleanIFCode })
}
// 合并字面量(在解除区域混淆后会出现新的可合并分割)
traverse(ast, { BinaryExpression: { exit: calcBinary } })
return ast
}
function purifyBoolean(path) {
// 简化 ![] 和 !![]
const node0 = path.node
if (node0.operator !== '!') {
return
}
const node1 = node0.argument
if (t.isArrayExpression(node1) && node1.elements.length === 0) {
path.replaceWith(t.booleanLiteral(false))
return
}
if (!t.isUnaryExpression(node1) || node1.operator !== '!') {
return
}
const node2 = node1.argument
if (t.isArrayExpression(node2) && node2.elements.length === 0) {
path.replaceWith(t.booleanLiteral(true))
}
}
function cleanIFCode(path) {
function clear(path, toggle) {
// 判定成立
if (toggle) {
if (path.node.consequent.type == 'BlockStatement') {
path.replaceWithMultiple(path.node.consequent.body)
} else {
path.replaceWith(path.node.consequent)
}
return
}
// 判定不成立
if (!path.node.alternate) {
path.remove()
return
}
if (path.node.alternate.type == 'BlockStatement') {
path.replaceWithMultiple(path.node.alternate.body)
} else {
path.replaceWith(path.node.alternate)
}
}
// 判断判定是否恒定
const test = path.node.test
const types = ['StringLiteral', 'NumericLiteral', 'BooleanLiteral']
if (test.type === 'BinaryExpression') {
if (
types.indexOf(test.left.type) !== -1 &&
types.indexOf(test.right.type) !== -1
) {
const left = JSON.stringify(test.left.value)
const right = JSON.stringify(test.right.value)
clear(path, eval(left + test.operator + right))
}
} else if (types.indexOf(test.type) !== -1) {
clear(path, eval(JSON.stringify(test.value)))
}
}
function cleanSwitchCode(path) {
// 扁平控制:
// 会使用一个恒为true的while语句包裹一个switch语句
// switch语句的执行顺序又while语句上方的字符串决定
// 首先碰断是否符合这种情况
const node = path.node
let valid = false
if (t.isBooleanLiteral(node.test) && node.test.value) {
valid = true
}
if (t.isArrayExpression(node.test) && node.test.elements.length === 0) {
valid = true
}
if (!valid) {
return
}
if (!t.isBlockStatement(node.body)) {
return
}
const body = node.body.body
if (
!t.isSwitchStatement(body[0]) ||
!t.isMemberExpression(body[0].discriminant) ||
!t.isBreakStatement(body[1])
) {
return
}
// switch语句的两个变量
const swithStm = body[0]
const arrName = swithStm.discriminant.object.name
const argName = swithStm.discriminant.property.argument.name
console.log(`扁平化还原: ${arrName}[${argName}]`)
// 在while上面的节点寻找这两个变量
let arr = []
path.getAllPrevSiblings().forEach((pre_path) => {
const { declarations } = pre_path.node
let { id, init } = declarations[0]
if (arrName == id.name) {
arr = init.callee.object.value.split('|')
pre_path.remove()
}
if (argName == id.name) {
pre_path.remove()
}
})
// 重建代码块
const caseList = swithStm.cases
let resultBody = []
arr.map((targetIdx) => {
// 从当前序号开始直到遇到continue
let valid = true
targetIdx = parseInt(targetIdx)
while (valid && targetIdx < caseList.length) {
const targetBody = caseList[targetIdx].consequent
const test = caseList[targetIdx].test
if (!t.isStringLiteral(test) || parseInt(test.value) !== targetIdx) {
console.log(`switch中出现乱序的序号: ${test.value}:${targetIdx}`)
}
for (let i = 0; i < targetBody.length; ++i) {
const s = targetBody[i]
if (t.isContinueStatement(s)) {
valid = false
break
}
if (t.isReturnStatement(s)) {
valid = false
resultBody.push(s)
break
}
if (t.isBreakStatement(s)) {
console.log(`switch中出现意外的break: ${arrName}[${argName}]`)
} else {
resultBody.push(s)
}
}
targetIdx++
}
})
// 替换整个while语句
path.replaceInline(resultBody)
}
function cleanDeadCode(ast) {
traverse(ast, { UnaryExpression: purifyBoolean })
traverse(ast, { IfStatement: cleanIFCode })
traverse(ast, { ConditionalExpression: cleanIFCode })
traverse(ast, { WhileStatement: { exit: cleanSwitchCode } })
return ast
}
function standardIfStatement(path) {
const consequent = path.get('consequent')
const alternate = path.get('alternate')
const test = path.get('test')
const evaluateTest = test.evaluateTruthy()
if (!consequent.isBlockStatement()) {
consequent.replaceWith(t.BlockStatement([consequent.node]))
}
if (alternate.node !== null && !alternate.isBlockStatement()) {
alternate.replaceWith(t.BlockStatement([alternate.node]))
}
if (consequent.node.body.length == 0) {
if (alternate.node == null) {
path.replaceWith(test.node)
} else {
consequent.replaceWith(alternate.node)
alternate.remove()
path.node.alternate = null
test.replaceWith(t.unaryExpression('!', test.node, true))
}
}
if (alternate.isBlockStatement() && alternate.node.body.length == 0) {
alternate.remove()
path.node.alternate = null
}
if (evaluateTest === true) {
path.replaceWithMultiple(consequent.node.body)
} else if (evaluateTest === false) {
alternate.node === null
? path.remove()
: path.replaceWithMultiple(alternate.node.body)
}
}
function standardLoop(path) {
const node = path.node
if (!t.isBlockStatement(node.body)) {
node.body = t.BlockStatement([node.body])
}
}
function splitSequence(path) {
let { scope, parentPath, node } = path
let expressions = node.expressions
if (parentPath.isReturnStatement({ argument: node })) {
let lastExpression = expressions.pop()
for (let expression of expressions) {
parentPath.insertBefore(t.ExpressionStatement(expression))
}