forked from PerimeterX/restringer
-
Notifications
You must be signed in to change notification settings - Fork 1
/
restringer.js
executable file
·1515 lines (1447 loc) · 54.3 KB
/
restringer.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
#!/usr/bin/env node
// noinspection JSValidateJSDoc
const fs = require('fs');
const {VM, NodeVM} = require('vm2');
const jsdom = require('jsdom').JSDOM;
const version = require(__dirname + '/package').version;
const detectObfuscation = require('obfuscation-detector');
const processors = require(__dirname + '/processors/processors');
const {generateFlatAST, parseCode, generateCode, Arborist} = require('flast');
const safeImplementations = require(__dirname + '/helpers/safeImplementations');
const {debugLog, debugErr, DEBUGMODEON} = require(__dirname + '/helpers/debugHelper');
const {
badTypes,
trapStrings,
skipProperties,
disableObjects,
skipIdentifiers,
badArgumentTypes,
skipBuiltinFunctions,
badIdentifierCharsRegex,
propertiesThatModifyContent,
} = require(__dirname + '/helpers/config');
class REstringer {
static __version__ = version;
jQuerySrc = '';
badValue = '--BAD-VAL--'; // Internal value used to indicate eval failed
validIdentifierBeginning = /^[A-Za-z$_]/;
/**
* @param {string} script The target script to be deobfuscated
* @param {boolean} normalize Run optional methods which will make the script more readable
*/
constructor(script, normalize = true) {
this.script = script;
this.normalize = normalize;
this.modified = false;
this.obfuscationName = 'Generic';
this._cache = {}; // Cache for eval result
this.cyclesCounter = 0; // Used for logging
this.totalChangesCounter = 0;
// Required to avoid infinite loops, but it's good to keep the number high
// since as long as there's a difference between iteration, something is working
this.maxCycles = 500;
this._preprocessors = [];
this._postprocessors = [];
this._ast = [];
this._arborist = null;
}
// * * * * * * Determining Obfuscation Type * * * * * * * * //
/**
* Determine the type of the obfuscation, and populate the appropriate pre and post processors.
*/
determineObfuscationType() {
const detectedObfuscationType = detectObfuscation(this.script, false).slice(-1)[0];
if (detectedObfuscationType) {
const relevantProcessors = processors[detectedObfuscationType]();
if (relevantProcessors?.preprocessors?.length) this._preprocessors = relevantProcessors.preprocessors;
if (relevantProcessors?.postprocessors?.length) this._postprocessors = relevantProcessors.postprocessors;
this.obfuscationName = detectedObfuscationType;
}
debugLog(`[+] Obfuscation type is ${this.obfuscationName}`);
return this.obfuscationName;
}
// * * * * * * Helper Methods * * * * * * * * //
/**
* Make the script more readable without actually deobfuscating or affecting its functionality.
*/
_normalizeScript() {
debugLog(`[!] Started script normalization...`, 2);
const startTime = Date.now();
this.runLoop([
this._normalizeComputed,
this._normalizeRedundantNotOperator,
this._normalizeEmptyStatements,
]);
debugLog(`[!] --> Normalization took ${(Date.now() - startTime) / 1000} seconds`, 2);
}
/**
* Change all member expressions and class methods which has a property which can support it - to non-computed.
* E.g.
* console['log'] -> console.log
*/
_normalizeComputed() {
const candidates = this._ast.filter(n =>
n.computed && // This will keep only member expressions using bracket notation
// Ignore member expressions with properties which can't be non-computed, like arr[2] or window['!obj']
// or those having another variable reference as their property like window[varHoldingFuncName]
(n.type === 'MemberExpression' &&
n.property.type === 'Literal' &&
this.validIdentifierBeginning.test(n.property.value) &&
!badIdentifierCharsRegex.exec(n.property.value)) ||
/**
* Ignore the same cases for method names and object properties, for example
* class A {
* ['!hello']() {} // Can't change the name of this method
* ['miao']() {} // This can be changed to 'miao() {}'
* }
* const obj = {
* ['!hello']: 1, // Will be ignored
* ['miao']: 4 // Will be changed to 'miao: 4'
* };
*/
(['MethodDefinition', 'Property'].includes(n.type) &&
n.key.type === 'Literal' &&
this.validIdentifierBeginning.test(n.key.value) &&
!badIdentifierCharsRegex.exec(n.key.value)));
for (const c of candidates) {
const relevantProperty = c.type === 'MemberExpression' ? 'property' : 'key';
const nonComputed = Object.assign({}, c);
nonComputed.computed = false;
nonComputed[relevantProperty] = {
type: 'Identifier',
name: c[relevantProperty].value,
};
this._markNode(c, nonComputed);
}
}
/**
* Remove unrequired empty statements.
*/
_normalizeEmptyStatements() {
const candidates = this._ast.filter(n => n.type === 'EmptyStatement');
for (const c of candidates) {
// A for loop is sometimes used to assign variables without providing a loop body, just an empty statement.
// If we delete that empty statement the syntax breaks
// e.g. for (var i = 0, b = 8;;); - this is a valid for statement.
if (!/For.*Statement/.test(c.parentNode.type)) this._markNode(c);
}
}
/**
* Replace redundant not operators with actual value (e.g. !true -> false)
*/
_normalizeRedundantNotOperator() {
const relevantNodeTypes = ['Literal', 'ArrayExpression', 'ObjectExpression', 'UnaryExpression'];
const candidates = this._ast.filter(n =>
n.type === 'UnaryExpression' &&
relevantNodeTypes.includes(n.argument.type) &&
n.operator === '!');
for (const c of candidates) {
if (this._canUnaryExpressionBeResolved(c.argument)) {
const newNode = this._evalInVm(c.src);
this._markNode(c, newNode);
}
}
}
/**
* Remove nodes code which is only declared but never used.
* NOTE: This is a dangerous operation which shouldn't run by default, invokations of the so-called dead code
* may be dynamically built during execution. Handle with care.
*/
removeDeadNodes() {
const relevantParents = ['VariableDeclarator', 'AssignmentExpression', 'FunctionDeclaration', 'ClassDeclaration'];
const candidates = this._ast.filter(n =>
n.type === 'Identifier' &&
relevantParents.includes(n.parentNode.type) &&
(!n?.declNode?.references?.length && !n?.references?.length)).map(n => n.parentNode);
for (const c of candidates) {
this._markNode(c);
}
}
/**
* A wrapper for Arborist's markNode method that verifies replacement isn't a bad value before marking.
* @param targetNode The node to replace or remove.
* @param replacementNode If exists, replace the target node with this node.
*/
_markNode(targetNode, replacementNode) {
if (replacementNode !== this.badValue) {
if (this._isInAst(targetNode) && !this._isMarked(targetNode)) {
this._arborist.markNode(targetNode, replacementNode);
this._ast = this._arborist.ast;
}
}
}
/**
* @param {ASTNode} targetNode
* @returns {boolean} true if the target node or one of its ancestors is marked for either replacement or deletion;
* false otherwise.
*/
_isMarked(targetNode) {
let n = targetNode;
while (n) {
if (n.markedNode) return true;
n = n.parentNode;
}
return false;
}
/**
* @param {ASTNode} targetNode
* @returns {boolean} true if targetNode exists and is unchanged in current AST; false otherwise.
*/
_isInAst(targetNode) {
const targetNodeId = targetNode.nodeId;
const matches = this._ast.filter(n => n.nodeId === targetNodeId);
if (matches && matches.length) {
return matches[0].src === targetNode.src;
}
return false;
}
/**
* Return the source code of the ordered nodes.
* @param {ASTNode[]} nodes
*/
_createOrderedSrc(nodes) {
nodes.forEach((n, idx) => {
if (n.type === 'CallExpression') {
if (n.parentNode.type === 'ExpressionStatement') nodes[idx] = n.parentNode;
else if (n.callee.type === 'FunctionExpression') {
const newNode = generateFlatAST(`(${n.src});`)[1];
newNode.nodeId = 9999999; // Exceedingly high nodeId ensures IIFEs are placed last.
nodes[idx] = newNode;
}
}
});
const orderedNodes = [...new Set(nodes)].sort(
(a, b) => a.nodeId > b.nodeId ? 1 : b.nodeId > a.nodeId ? -1 : 0);
let output = '';
orderedNodes.forEach(n => {
const addSemicolon = ['VariableDeclarator', 'AssignmentExpression'].includes(n.type);
output += (n.type === 'VariableDeclarator' ? `${n.parentNode.kind} ` : '') + n.src + (addSemicolon ? ';' : '') + '\n';
});
return output;
}
/**
* Create a node from a value by its type.
* @returns {ASTNode|string} The created node if successful; badValue string otherwise
*/
_createNewNode(value) {
let newNode = this.badValue;
try {
if (![undefined, null].includes(value) && value.__proto__.constructor.name === 'Node') value = generateCode(value);
switch (this._getType(value)) {
case 'String':
case 'Number':
case 'Boolean':
if (['-', '+', '!'].includes(String(value)[0]) && String(value).length > 1) {
newNode = {
type: 'UnaryExpression',
operator: String(value)[0],
argument: this._createNewNode(String(value).substring(1)),
};
} else if (['Infinity', 'NaN'].includes(String(value))) {
newNode = {
type: 'Identifier',
name: String(value),
};
} else {
newNode = {
type: 'Literal',
value: value,
raw: String(value),
};
}
break;
case 'Array': {
const elements = [];
for (const el of Array.from(value)) {
elements.push(this._createNewNode(el));
}
newNode = {
type: 'ArrayExpression',
elements,
};
break;
}
case 'Object': {
const properties = [];
for (const [k, v] of Object.entries(value)) {
const key = this._createNewNode(k);
const val = this._createNewNode(v);
if ([key, val].includes(this.badValue)) {
// noinspection ExceptionCaughtLocallyJS
throw Error();
}
properties.push({
type: 'Property',
key,
value: val,
});
}
newNode = {
type: 'ObjectExpression',
properties,
};
break;
}
case 'Undefined':
newNode = {
type: 'Identifier',
name: 'undefined',
};
break;
case 'Null':
newNode = {
type: 'Literal',
raw: 'null',
};
break;
case 'Function': // Covers functions and classes
try {
newNode = parseCode(value).body[0];
} catch {} // Probably a native function
}
} catch (e) {
debugErr(`[-] Unable to create a new node: ${e}`, 1);
}
return newNode;
}
// * * * * * * Getters * * * * * * * * //
/**
* Extract and return the type of whatever object is provided
* @param {*} unknownObject
* @return {string}
*/
_getType(unknownObject) {
const match = ({}).toString.call(unknownObject).match(/\[object (.*)\]/);
return match ? match[1] : '';
}
/**
* @param {ASTNode} callExpression
* @return {string} The name of the identifier / value of the literal at the base of the call expression.
*/
_getCalleeName(callExpression) {
const callee = callExpression.callee?.object?.object || callExpression.callee?.object || callExpression.callee;
return callee.name || callee.value;
}
/**
* @param {ASTNode} targetNode
* @return {ASTNode[]} A flat array of all decendants of the target node
*/
_getDescendants(targetNode) {
const offsprings = [];
const stack = [targetNode];
while (stack.length) {
const currentNode = stack.pop();
for (const childNode of (currentNode.childNodes || [])) {
if (!offsprings.includes(childNode)) {
offsprings.push(childNode);
stack.push(childNode);
}
}
}
return offsprings;
}
/**
*
* @param {ASTNode} originNode
* @return {ASTNode[]} A flat array of all available declarations and call expressions relevant to
* the context of the origin node.
*/
_getDeclarationWithContext(originNode) {
const cacheNameId = `context-${originNode.nodeId}`;
const cacheNameSrc = `context-${originNode.src}`;
let cached = this._cache[cacheNameId] || this._cache[cacheNameSrc];
if (!cached) {
const collectedContext = [originNode];
const examineStack = [originNode];
const collectedContextIds = [];
const collectedRanges = [];
while (examineStack.length) {
const relevantNode = examineStack.pop();
if (this._isMarked(relevantNode)) continue;
collectedContextIds.push(relevantNode.nodeId);
collectedRanges.push(relevantNode.range);
let relevantScope;
const assignments = [];
const references = [];
switch (relevantNode.type) {
case 'VariableDeclarator':
relevantScope = relevantNode.init?.scope || relevantNode.id.scope;
// Since the variable wasn't initialized, extract value from assignments
if (!relevantNode.init) {
assignments.push(...relevantNode.id.references.filter(r =>
r.parentNode.type === 'AssignmentExpression' &&
r.parentKey === 'left'));
} else {
// Collect references found in init
references.push(...this._getDescendants(relevantNode.init).filter(n =>
n.type === 'Identifier' &&
n.declNode &&
(n.parentNode.type !== 'MemberExpression' ||
n.parentKey === 'object'))
.map(n => n.declNode));
}
// Collect assignments to variable properties
assignments.push(...relevantNode.id.references.filter(r =>
r.parentNode.type === 'MemberExpression' &&
((r.parentNode.parentNode.type === 'AssignmentExpression' &&
r.parentNode.parentKey === 'left') ||
(r.parentKey === 'object' &&
propertiesThatModifyContent.includes(r.parentNode.property?.value || r.parentNode.property.name))))
.map(r => r.parentNode.parentNode));
// Find augmenting functions
references.push(...relevantNode.id.references.filter(r =>
r.parentNode.type === 'CallExpression' &&
r.parentKey === 'arguments')
.map(r => r.parentNode));
break;
case 'AssignmentExpression':
relevantScope = relevantNode.right?.scope;
break;
case 'CallExpression':
relevantScope = relevantNode.callee.scope;
references.push(...relevantNode.arguments.filter(a => a.type === 'Identifier'));
break;
case 'MemberExpression':
relevantScope = relevantNode.object.scope;
examineStack.push(relevantNode.property);
break;
default:
relevantScope = relevantNode.scope;
}
const contextToCollect = relevantScope.through
.map(ref => ref.identifier?.declNode?.parentNode)
.filter(ref => !!ref)
.concat(assignments)
.concat(references)
.map(ref => ref.type === 'Identifier' ? ref.parentNode : ref);
for (const rn of contextToCollect) {
if (rn && !collectedContextIds.includes(rn.nodeId) && !this._isNodeInRanges(rn, collectedRanges)) {
collectedRanges.push(rn.range);
collectedContextIds.push(rn.nodeId);
collectedContext.push(rn);
examineStack.push(rn);
for (const cn of (rn.chileNodes || [])) {
examineStack.push(cn);
}
}
}
}
const skipCollectionTypes = [
'Literal',
'Identifier',
'MemberExpression',
];
cached = collectedContext.filter(n => !skipCollectionTypes.includes(n.type));
this._cache[cacheNameId] = cached; // Caching context for the same node
this._cache[cacheNameSrc] = cached; // Caching context for a different node with similar content
}
return cached;
}
/**
* If this member expression is a part of another member expression - return the first parentNode
* which has a declaration in the code.
* E.g. a.b[c.d] --> if candidate is c.d, the c identifier will be returned.
* a.b.c.d --> if the candidate is c.d, the a identifier will be returned.
* @param {ASTNode} memberExpression
* @return {ASTNode} The main object object with an available declaration
*/
_getMainDeclaredObjectOfMemberExpression(memberExpression) {
let mainObject = memberExpression;
while (mainObject && !mainObject.declNode && mainObject.type === 'MemberExpression') mainObject = mainObject.object;
return mainObject;
}
// * * * * * * Booleans * * * * * * * * //
/**
*
* @param {ASTNode} binaryExpression
* @return {boolean} true if ultimately the binary expression contains only literals; false otherwise
*/
_doesBinaryExpressionContainOnlyLiterals(binaryExpression) {
switch (binaryExpression.type) {
case 'BinaryExpression':
return this._doesBinaryExpressionContainOnlyLiterals(binaryExpression.left) &&
this._doesBinaryExpressionContainOnlyLiterals(binaryExpression.right);
case 'UnaryExpression':
return this._doesBinaryExpressionContainOnlyLiterals(binaryExpression.argument);
case 'Literal':
return true;
}
return false;
}
/**
* @param argument
* @return {boolean} true if unary expression's argument can be resolved (i.e. independent of other identifier); false otherwise.
*/
_canUnaryExpressionBeResolved(argument) {
switch (argument.type) { // Examples for each type of argument which can be resolved:
case 'ArrayExpression':
return !argument.elements.length; // ![]
case 'ObjectExpression':
return !argument.properties.length; // !{}
case 'Identifier':
return argument.name === 'undefined'; // !undefined
case 'TemplateLiteral':
return !argument.expressions.length; // !`template literals with no expressions`
case 'UnaryExpression':
return this._canUnaryExpressionBeResolved(argument.argument);
}
return true;
}
/**
* @param {ASTNode} targetNode
* @param {number[][]} ranges
* @return {boolean} true if the target node is contained in the provided array of ranges; false otherwise.
*/
_isNodeInRanges(targetNode, ranges) {
const [nodeStart, nodeEnd] = targetNode.range;
for (const [rangeStart, rangeEnd] of ranges) {
if (nodeStart >= rangeStart && nodeEnd <= rangeEnd) return true;
}
return false;
}
/**
* @param {ASTNode} targetNode
* @param {number[][]} ranges
* @return {boolean} true if any of the ranges provided is contained by the target node; false otherwise.
*/
_doesNodeContainRanges(targetNode, ranges) {
const [nodeStart, nodeEnd] = targetNode.range;
for (const [rangeStart, rangeEnd] of ranges) {
if (nodeStart <= rangeStart && nodeEnd >= rangeEnd) return true;
}
return false;
}
/**
* @param {ASTNode[]} refs
* @return {boolean} true if any of the references might modify the original value; false otherwise.
*/
_areReferencesModified(refs) {
// Verify no reference is on the left side of an assignment
return Boolean(refs.filter(r => r.parentNode.type === 'AssignmentExpression' && r.parentKey === 'left').length ||
// Verify no reference is part of an update expression
refs.filter(r => r.parentNode.type === 'UpdateExpression').length ||
// Verify no variable with the same name is declared in a subscope
refs.filter(r => r.parentNode.type === 'VariableDeclarator' && r.parentKey === 'id').length ||
// Verify there are no member expressions among the references which are being assigned to
refs.filter(r => r.type === 'MemberExpression' &&
(this._ast.filter(n => n.type === 'AssignmentExpression' && n.left.src === r.src &&
([r.object.declNode?.nodeId, r.object?.nodeId].includes(n.left.object.declNode?.nodeId)))).length).length ||
// Verify no modifying calls are executed on any of the references
refs.filter(r => r.parentNode.type === 'MemberExpression' &&
r.parentNode.parentNode.type === 'CallExpression' &&
r.parentNode.parentNode.callee?.object?.nodeId === r.nodeId &&
propertiesThatModifyContent.includes(r.parentNode.property?.value || r.parentNode.property?.name)).length);
}
// * * * * * * Evals * * * * * * * * //
/**
* Eval a string in a ~safe~ VM environment
* @param {string} stringToEval
* @return {string|ASTNode} A node based on the eval result if successful; badValue string otherwise.
*/
_evalInVm(stringToEval) {
const vmOptions = {
timeout: 5 * 1000,
sandbox: {...disableObjects},
};
const cacheName = `eval-${stringToEval}`;
if (this._cache[cacheName] === undefined) {
this._cache[cacheName] = this.badValue;
try {
// Break known trap strings
for (const ts of trapStrings) {
stringToEval = stringToEval.replace(ts.trap, ts.replaceWith);
}
const res = (new VM(vmOptions)).run(stringToEval);
if (!res.VMError && !badTypes.includes(this._getType(res))) {
// To exclude results based on randomness or timing, eval again and compare results
const res2 = (new VM(vmOptions)).run(stringToEval);
if (JSON.stringify(res) === JSON.stringify(res2)) {
this._cache[cacheName] = this._createNewNode(res);
}
}
} catch (e) {
debugErr(`[-] Error in _evalInVm: ${e}`, 1);
}
}
return this._cache[cacheName];
}
/**
* Place a string into a file and evaluate it with a simulated browser environment.
* @param {string} stringToEval
* @param {boolean} injectjQuery Inject jQuery into the VM if true.
* @return {string} The output string if successful; empty string otherwise.
*/
_evalWithDom(stringToEval, injectjQuery = false) {
const cacheName = `evalWithDom-${stringToEval}`;
if (!this._cache[cacheName]) {
let out = '';
const vm = new NodeVM({
console: 'redirect',
timeout: 100 * 1000,
sandbox: {jsdom},
});
try {
// Setup the DOM, and allow script to run wild: <img src='I_too_like_to_run_scripts_dangerously.jpg'/>
let runString = 'const dom = new jsdom(`<html><head></head><body></body></html>`, {runScripts: \'dangerously\'}); ' +
'const window = dom.window; ' +
'const document = window.document; ';
// Lazy load the jQuery when needed, and inject it to the head
if (injectjQuery) {
this.jQuerySrc = this.jQuerySrc || fs.readFileSync(__dirname + '/../tools/jquery.slim.min.js');
runString += 'const jqueryScript = document.createElement(\'script\'); ' +
'jqueryScript.src = ' + this.jQuerySrc + '; ' +
'document.head.appendChild(jqueryScript);';
}
// Inject the string to eval as a script into the body
runString += 'const script = document.createElement(\'script\'); ' +
'script.src = ' + stringToEval + '; ' +
'document.body.appendChild(script);';
// Catch and save the console.log's message
vm.on('console.log', function (msg) {
out = msg;
});
vm.run(runString);
} catch (e) {
debugErr(`[-] Error in _evalWithDom: ${e}`, 1);
}
this._cache[cacheName] = out;
}
return this._cache[cacheName];
}
// * * * * * * Main Deobfuscation Methods * * * * * * * * //
/**
* Replace definite member expressions with their intended value.
* E.g.
* '123'[0]; ==> '1';
* 'hello'.length ==> 5;
*/
_resolveDefiniteMemberExpressions() {
const candidates = this._ast.filter(n =>
n.type === 'MemberExpression' &&
n.property.type === 'Literal' &&
['ArrayExpression', 'Literal'].includes(n.object.type) &&
(n.object?.value?.length || n.object?.elements?.length));
for (const c of candidates) {
const newValue = this._evalInVm(c.src);
this._markNode(c, newValue);
}
}
/**
* Resolve member expressions to the value they stand for, if they're defined in the script.
* E.g.
* const a = [1, 2, 3];
* const b = a[2]; // <-- will be resolved to 3
* const c = 0;
* const d = a[c]; // <-- will be resolved to 1
* ---
* const a = {hello: 'world'};
* const b = a['hello']; // <-- will be resolved to 'world'
*/
_resolveMemberExpressionsLocalReferences() {
const candidates = this._ast.filter(n =>
n.type === 'MemberExpression' &&
['Identifier', 'Literal'].includes(n.property.type) &&
!skipProperties.includes(n.property?.name || n.property?.value));
for (const c of candidates) {
// If this member expression is the callee of a call expression - skip it
if (c.parentNode.type === 'CallExpression' && c.parentKey === 'callee') continue;
// If this member expression is a part of another member expression - get the first parentNode
// which has a declaration in the code;
// E.g. a.b[c.d] --> if candidate is c.d, the c identifier will be selected;
// a.b.c.d --> if the candidate is c.d, the a identifier will be selected;
let relevantIdentifier = this._getMainDeclaredObjectOfMemberExpression(c);
if (relevantIdentifier && relevantIdentifier.declNode) {
// Skip if the relevant identifier is on the left side of an assignment.
if (relevantIdentifier.parentNode.parentNode.type === 'AssignmentExpression' &&
relevantIdentifier.parentNode.parentKey === 'left') continue;
const declNode = relevantIdentifier.declNode;
// Skip if the identifier was declared as a function's parameter.
if (/Function/.test(declNode.parentNode.type) &&
(declNode.parentNode.params || []).filter(p => p.nodeId === declNode.nodeId).length) continue;
const context = this._createOrderedSrc(this._getDeclarationWithContext(relevantIdentifier.declNode.parentNode));
if (context) {
const src = `${context}\n${c.src}`;
const newNode = this._evalInVm(src);
if (newNode !== this.badValue) {
let isEmptyReplacement = false;
switch (newNode.type) {
case 'ArrayExpression':
if (!newNode.elements.length) isEmptyReplacement = true;
break;
case 'ObjectExpression':
if (!newNode.properties.length) isEmptyReplacement = true;
break;
case 'Literal':
if (!String(newNode.value).length) isEmptyReplacement = true;
break;
}
if (!isEmptyReplacement) {
this._markNode(c, newNode);
}
}
}
}
}
}
/**
* Resolve the value of member expressions to objects which hold literals that were directly assigned to the expression.
* E.g.
* function a() {}
* a.b = 3;
* a.c = '5';
* console.log(a.b + a.c); // a.b + a.c will be replaced with '35'
*/
_resolveMemberExpressionsWithDirectAssignment() {
const candidates = this._ast.filter(n =>
n.type === 'MemberExpression' &&
n.object.declNode &&
n.parentNode.type === 'AssignmentExpression' &&
n.parentNode.right.type === 'Literal');
for (const c of candidates) {
const prop = c.property?.value || c.property?.name;
const valueUses = c.object.declNode.references.filter(n =>
n.parentNode.type === 'MemberExpression' &&
(n.parentNode.property.computed ?
n.parentNode.property?.value === prop :
n.parentNode.property?.name === prop) &&
n.parentNode.nodeId !== c.nodeId)
.map(n => n.parentNode);
if (valueUses.length) {
// Skip if the value is reassigned
if (valueUses.filter(n => n.parentNode.type === 'AssignmentExpression' && n.parentKey === 'left').length) continue;
const replacementNode = c.parentNode.right;
valueUses.forEach(n => this._markNode(n, replacementNode));
}
}
}
/**
* Resolve call expressions which are defined on an object's prototype and are applied to an object's instance.
* E.g.
* String.prototype.secret = function() {return 'secret ' + this}
* 'hello'.secret(); // <-- will be resolved to 'secret hello'
*/
_resolveInjectedPrototypeMethodCalls() {
const candidates = this._ast.filter(n =>
n.type === 'AssignmentExpression' &&
n.left.type === 'MemberExpression' &&
[n.left.object.property?.name, n.left.object.property?.value].includes('prototype') &&
n.operator === '=' &&
(/FunctionExpression/.test(n.right?.type) || n.right?.type === 'Identifier'));
for (const c of candidates) {
const methodName = c.left.property?.name || c.left.property?.value;
const context = this._getDeclarationWithContext(c);
const references = this._ast.filter(n =>
n.type === 'CallExpression' &&
n.callee.type === 'MemberExpression' &&
[n.callee.property?.name, n.callee.property?.value].includes(methodName));
for (const ref of references) {
const refContext = [
...new Set([
...this._getDeclarationWithContext(ref.callee),
...this._getDeclarationWithContext(ref.callee?.object),
...this._getDeclarationWithContext(ref.callee?.property),
]),
];
const src = `${this._createOrderedSrc([...context, ...refContext])}\n${ref.src}`;
const newNode = this._evalInVm(src);
this._markNode(ref, newNode);
}
}
}
/**
* Resolve member expressions to their targeted index in an array.
* E.g.
* const a = [1, 2, 3]; b = a[0]; c = a[2];
* ==>
* const a = [1, 2, 3]; b = 1; c = 3;
*/
_resolveMemberExpressionReferencesToArrayIndex() {
const minArrayLength = 20;
const candidates = this._ast.filter(n =>
n.type === 'VariableDeclarator' &&
n.init?.type === 'ArrayExpression' &&
n.id?.references &&
n.init.elements.length > minArrayLength);
for (const c of candidates) {
const refs = c.id.references.map(n => n.parentNode);
if (!refs.filter(n =>
(n.property && n.property?.type !== 'Literal') ||
Object.is(parseInt(n.property), NaN).length).length) {
for (const ref of refs) {
if ((ref.parentNode.type === 'AssignmentExpression' &&
ref.parentKey === 'left') ||
ref.type !== 'MemberExpression') continue;
try {
this._markNode(ref, c.init.elements[parseInt(ref.property.value)]);
} catch (e) {
debugErr(`[-] Unable to mark node for replacement: ${e}`, 1);
}
}
}
}
}
/**
* Resolve definite binary expressions.
* E.g.
* 5 * 3 ==> 15;
* '2' + 2 ==> '22';
*/
_resolveDefiniteBinaryExpressions() {
const candidates = this._ast.filter(n =>
n.type === 'BinaryExpression' &&
this._doesBinaryExpressionContainOnlyLiterals(n));
for (const c of candidates) {
const newNode = this._evalInVm(c.src);
this._markNode(c, newNode);
}
}
/**
* E.g.
* `hello ${'world'}!`; // <-- will be parsed into 'hello world!'
*/
_parseTemplateLiteralsIntoStringLiterals() {
const candidates = this._ast.filter(n =>
n.type === 'TemplateLiteral' &&
!n.expressions.filter(exp => exp.type !== 'Literal').length);
for (const c of candidates) {
let newStringLiteral = '';
for (let i = 0; i < c.expressions.length; i++) {
newStringLiteral += c.quasis[i].value.raw + c.expressions[i].value;
}
newStringLiteral += c.quasis.slice(-1)[0].value.raw;
this._markNode(c, this._createNewNode(newStringLiteral));
}
}
/**
* Remove redundant block statements which have another block statement as their body.
* E.g.
* if (a) {{do_a();}} ===> if (a) {do_a();}
*/
_removeNestedBlockStatements() {
const candidates = this._ast.filter(n =>
n.type === 'BlockStatement' &&
n.parentNode.type === 'BlockStatement');
for (const c of candidates) {
this._markNode(c.parentNode, c);
}
}
/**
* Remove redundant logical expressions which will always resolve in the same way.
* E.g.
* if (false && ...) do_a(); else do_b(); ==> do_b();
* if (... || true) do_c(); else do_d(); ==> do_c();
*/
_removeRedundantLogicalExpressions() {
const candidates = this._ast.filter(n =>
n.type === 'IfStatement' &&
n.test.type === 'LogicalExpression');
for (const c of candidates) {
if (c.test.operator === '&&') {
if (c.test.left.type === 'Literal') {
if (c.test.left.value) {
this._markNode(c.test, c.test.right);
} else {
this._markNode(c.test, c.test.left);
}
} else if (c.test.right.type === 'Literal') {
if (c.test.right.value) {
this._markNode(c.test, c.test.left);
} else {
this._markNode(c.test, c.test.right);
}
}
} else if (c.test.operator === '||') {
if (c.test.left.type === 'Literal') {
if (c.test.left.value) {
this._markNode(c.test, c.test.left);
} else {
this._markNode(c.test, c.test.right);
}
} else if (c.test.right.type === 'Literal') {
if (c.test.right.value) {
this._markNode(c.test, c.test.right);
} else {
this._markNode(c.test, c.test.left);
}
}
}
}
}
/**
* Replace if statements which will always resolve the same way with their relevant consequent or alternative.
* E.g.
* if (true) do_a(); else do_b(); if (false) do_c(); else do_d();
* ==>
* do_a(); do_d();
*/
_resolveDeterministicIfStatements() {
const candidates = this._ast.filter(n =>
n.type === 'IfStatement' &&
n.test.type === 'Literal');
for (const c of candidates) {
if (c.test.value) {
if (c.consequent) this._markNode(c, c.consequent);
else this._markNode(c);
} else {
if (c.alternate) this._markNode(c, c.alternate);
else this._markNode(c);
}
}
}
/**
* Replace variables which only point at other variables and do not change, with their target.
* E.g.
* const a = [...];
* const b = a;
* const c = b[0]; // <-- will be replaced with `const c = a[0];`
*/
_replaceReferencedProxy() {
const candidates = this._ast.filter(n =>
(n.type === 'VariableDeclarator' &&
['Identifier', 'MemberExpression'].includes(n.id.type) &&
['Identifier', 'MemberExpression'].includes(n.init?.type)) &&
!/For.*Statement/.test(n.parentNode.parentNode.type));
for (const c of candidates) {
const relevantIdentifier = this._getMainDeclaredObjectOfMemberExpression(c.id)?.declNode || c.id;
const refs = relevantIdentifier.references || [];
const replacementNode = c.init;
if (refs.length && !this._areReferencesModified(refs) && !this._areReferencesModified([replacementNode])) {
for (const ref of refs) {
this._markNode(ref, replacementNode);
}
}
}
}
/**
* Resolve calls to builtin functions (like atob or String(), etc...).
* Use safe implmentations of known functions when available.
*/
_resolveBuiltinCalls() {
const availableSafeImplementations = Object.keys(safeImplementations);
const callsWithOnlyLiteralArugments = this._ast.filter(n =>
n.type === 'CallExpression' &&
!n.arguments.filter(a => a.type !== 'Literal').length);
const candidates = callsWithOnlyLiteralArugments.filter(n =>
n.callee.type === 'Identifier' &&
!n.callee.declNode &&
!skipBuiltinFunctions.includes(n.callee.name));
candidates.push(...callsWithOnlyLiteralArugments.filter(n =>
n.callee.type === 'MemberExpression' &&
!n.callee.object.declNode &&
!skipIdentifiers.includes(n.callee.object?.name) &&
!skipProperties.includes(n.callee.property?.name || n.callee.property?.value)));
candidates.push(...this._ast.filter(n =>
n.type === 'CallExpression' &&
availableSafeImplementations.includes((n.callee.name))));
for (const c of candidates) {
try {
const callee = c.callee;
const safeImplementation = safeImplementations[callee.name];
if (safeImplementation) {
const args = c.arguments.map(a => a.value);
const tempValue = safeImplementation(...args);
if (tempValue) {
this._markNode(c, this._createNewNode(tempValue));
}
} else {
const newNode = this._evalInVm(c.src);
this._markNode(c, newNode);
}
} catch {}
}
}
/**