-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathextract_dynamic.py
More file actions
1479 lines (1303 loc) · 56.7 KB
/
extract_dynamic.py
File metadata and controls
1479 lines (1303 loc) · 56.7 KB
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 python3
# dynamic.py — box-js SVG analyzer with aggressive URL/ActiveX/WScript sink hooks
from __future__ import annotations
import argparse, base64, json, re, shutil, subprocess, sys, tempfile
from pathlib import Path
from typing import Iterable, Set, Tuple
BOXJS_CMD = "box-js"
BOXJS_TIMEOUT_DEFAULT = 30
BOXJS_BASE_FLAGS = ["--loglevel=info"] # prelude injected below
SVG_SCRIPT_RE = re.compile(r'(?is)<script\b[^>]*>(?:\s*<!\[CDATA\[)?(.*?)(?:\]\]>\s*)?</script>')
EMAIL_RE = re.compile(r'[a-zA-Z0-9._%+\-]+@[a-zA-Z0-9.\-]+\.[a-zA-Z]{2,}', re.IGNORECASE)
GENERIC_URL_RE = re.compile(r'(?i)\b(?:https?:\/\/|\/\/|mailto:)[^\s\'"<>{}|\\^`\[\]]+')
LOCAL_JS_FILENAME_RE = re.compile(r'^[\w\-\./\\]+\.boxed(?:\.js)?$', re.IGNORECASE)
BOXIOC_MARK = "[BOXIOC]"
FINALURL_MARK = "[FINALURL]"
def mask_email(email: str) -> str:
"""Mask email address for privacy: [email protected] -> u***@e*****.com"""
if '@' not in email:
return email
user, domain = email.split('@', 1)
# Mask username: keep first char + *** + last char (if >2 chars)
if len(user) <= 2:
masked_user = user[0] + '*' * max(1, len(user) - 1)
else:
masked_user = user[0] + '*' * max(1, len(user) - 2) + user[-1]
# Mask domain: keep first char + *** + TLD
domain_parts = domain.split('.')
if len(domain_parts) >= 2:
domain_main = domain_parts[0]
tld = '.'.join(domain_parts[1:])
if len(domain_main) <= 2:
masked_domain = domain_main[0] + '*' * max(1, len(domain_main) - 1)
else:
masked_domain = domain_main[0] + '*' * max(1, len(domain_main) - 2) + domain_main[-1]
masked_domain += '.' + tld
else:
# No TLD found, mask the whole domain
if len(domain) <= 2:
masked_domain = domain[0] + '*' * max(1, len(domain) - 1)
else:
masked_domain = domain[0] + '*' * max(1, len(domain) - 2) + domain[-1]
return masked_user + '@' + masked_domain
# --------- PRELUDE injected into box-js ---------
PRELUDE_JS = r"""
(function(){
var MARK='[BOXIOC]';
var FINALURL_MARK='[FINALURL]';
var g=(typeof globalThis!=='undefined')?globalThis:(typeof window!=='undefined'?window:this);
var urlParts = {}; // Track URL components
var finalUrls = new Set(); // Track complete URLs
// Add atob function for base64 decoding (missing in box-js)
if(typeof g.atob === 'undefined') {
g.atob = function(str) {
var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
var result = '';
var i = 0;
str = str.replace(/[^A-Za-z0-9+/]/g, '');
while (i < str.length) {
var a = chars.indexOf(str.charAt(i++));
var b = chars.indexOf(str.charAt(i++));
var c = chars.indexOf(str.charAt(i++));
var d = chars.indexOf(str.charAt(i++));
var bitmap = (a << 18) | (b << 12) | (c << 6) | d;
result += String.fromCharCode((bitmap >> 16) & 255);
if (c !== 64) result += String.fromCharCode((bitmap >> 8) & 255);
if (d !== 64) result += String.fromCharCode(bitmap & 255);
}
return result;
};
}
function looksURL(s){ try{s=String(s)}catch(e){return false}; return /^(https?:\/\/|\/\/|mailto:)/i.test(s) }
function looksPartialURL(s){ try{s=String(s)}catch(e){return false}; return /^(https?:\/\/|\/\/|mailto:|[a-zA-Z0-9.-]+\.[a-zA-Z]{2,})/i.test(s) }
function logIOC(x, why){
try{
var s=String(x);
if(looksURL(s)) {
console.log(MARK+' '+s+(why?(' ;; '+why):''));
finalUrls.add(s);
console.log(FINALURL_MARK+' '+s);
} else if(looksPartialURL(s) && s.length > 5) {
console.log(MARK+' '+s+(why?(' ;; '+why+' [partial]'):''));
}
}catch(e){}
}
function logIfURL(s, why){
if(looksURL(s)) {
console.log(MARK+' '+s+(why?(' ;; '+why):''));
finalUrls.add(s);
console.log(FINALURL_MARK+' '+s);
} else if(looksPartialURL(s) && s.length > 5) {
console.log(MARK+' '+s+(why?(' ;; '+why+' [partial]'):''));
}
}
// Track string concatenations that might build URLs
function trackConcat(result, parts, why) {
try {
var fullStr = String(result);
if(looksURL(fullStr)) {
console.log(MARK+' '+fullStr+' ;; '+why+' [concat]');
finalUrls.add(fullStr);
console.log(FINALURL_MARK+' '+fullStr);
}
} catch(e) {}
}
// ---- String concatenation hooks ----
try {
var origConcat = String.prototype.concat;
String.prototype.concat = function() {
var result = origConcat.apply(this, arguments);
trackConcat(result, [this].concat(Array.prototype.slice.call(arguments)), 'String.concat');
return result;
};
} catch(e) {}
// Hook the + operator by wrapping common string operations
try {
var origReplace = String.prototype.replace;
String.prototype.replace = function(search, replacement) {
var result = origReplace.call(this, search, replacement);
if(typeof replacement === 'string' && (looksPartialURL(this) || looksPartialURL(replacement))) {
trackConcat(result, [this, replacement], 'String.replace');
}
return result;
};
} catch(e) {}
// ---- Location family (href/assign/replace) ----
try{
var loc = { _href:"" };
Object.defineProperty(g, 'location', {
configurable:true,
get:function(){ return {
href: loc._href,
assign:function(u){
var finalUrl = String(u)||'';
logIOC(finalUrl,'location.assign');
loc._href=finalUrl;
if(looksURL(finalUrl)) {
finalUrls.add(finalUrl);
console.log(FINALURL_MARK+' '+finalUrl);
}
},
replace:function(u){
var finalUrl = String(u)||'';
logIOC(finalUrl,'location.replace');
loc._href=finalUrl;
if(looksURL(finalUrl)) {
finalUrls.add(finalUrl);
console.log(FINALURL_MARK+' '+finalUrl);
}
}
} },
set:function(v){
var s=(v&&v.href)?v.href:v;
var finalUrl = String(s)||'';
logIOC(finalUrl,'location=');
loc._href=finalUrl;
if(looksURL(finalUrl)) {
finalUrls.add(finalUrl);
console.log(FINALURL_MARK+' '+finalUrl);
}
}
});
Object.defineProperty(g, 'document', { configurable:true, value: { get location(){return g.location}, set location(v){ g.location=v } }});
}catch(e){}
// ---- window.open ----
try{ var o=g.open; g.open=function(u){logIOC(u,'open'); return o?o.apply(this,arguments):null} }catch(e){}
// ---- fetch ----
try{
if(g.fetch){
var of=g.fetch.bind(g);
g.fetch=function(input, init){
try{ var u=(input && typeof input==='object' && 'url' in input)?input.url:input; logIOC(u,'fetch') }catch(e){}
try{ return of(input,init) }catch(e){ return Promise.resolve({}) }
};
}
}catch(e){}
// ---- XHR.open ----
try{
if(g.XMLHttpRequest && g.XMLHttpRequest.prototype && g.XMLHttpRequest.prototype.open){
var xo=g.XMLHttpRequest.prototype.open;
g.XMLHttpRequest.prototype.open=function(m,u){ logIOC(u,'XMLHttpRequest.open'); return xo.apply(this,arguments) };
}
}catch(e){}
// ---- Image.src ----
try{
if(g.Image && g.Image.prototype){
var d=Object.getOwnPropertyDescriptor(g.Image.prototype,'src');
if(d && d.set){
Object.defineProperty(g.Image.prototype,'src',{
configurable:true,
get:d.get,
set:function(v){ logIOC(v,'Image.src'); try{return d.set.call(this,v)}catch(e){} }
});
}
}
}catch(e){}
// ---- navigator.sendBeacon ----
try{
if(g.navigator && typeof g.navigator.sendBeacon==='function'){
var sb=g.navigator.sendBeacon.bind(g.navigator);
g.navigator.sendBeacon=function(u,d){ logIOC(u,'sendBeacon'); try{ return sb(u,d) }catch(e){ return false } };
}
}catch(e){}
// ---- Common decoders -> log decoded strings that look like URLs ----
function wrap1(name){
try{
var fn=g[name]; if(typeof fn!=='function') return;
g[name]=function(a){
var r; try{ r=fn(a) }catch(e){ r='' }
logIfURL(r, name+'('+a+')');
return r;
};
}catch(e){}
}
['atob','decodeURI','decodeURIComponent','unescape'].forEach(wrap1);
// ---- eval / Function / timers: scan code for URLs after decode ----
var URLRX=/(https?:\/\/|\/\/)[^\s'"]+/ig;
function scanAndLog(s, why){
try{
var m, seen={};
while((m=URLRX.exec(String(s)))!==null){
var u=m[0]; if(!seen[u]){seen[u]=1; console.log(MARK+' '+u+' ;; '+why); }
}
}catch(e){}
}
try{
var oe=g.eval; g.eval=function(s){ scanAndLog(s,'eval'); return oe?oe(s):undefined };
}catch(e){}
try{
var OF=g.Function; g.Function=function(){ try{ var body=arguments[arguments.length-1]; scanAndLog(body,'Function') }catch(e){}; return OF.apply(this,arguments) };
}catch(e){}
try{
var ost=g.setTimeout; if(ost){ g.setTimeout=function(fn,ms){ try{ if(typeof fn==='string') scanAndLog(fn,'setTimeout') }catch(e){}; return ost.apply(this,arguments) } }
}catch(e){}
try{
var osi=g.setInterval; if(osi){ g.setInterval=function(fn,ms){ try{ if(typeof fn==='string') scanAndLog(fn,'setInterval') }catch(e){}; return osi.apply(this,arguments) } }
}catch(e){}
// ---- WScript & ActiveX hooks (box-js emulates these) ----
function wrapRunLike(obj, name, why){
try{
if(obj && typeof obj[name]==='function'){
var o=obj[name].bind(obj);
obj[name]=function(){ try{
var arg=arguments[0]; if(arg){ // often a command or URL
scanAndLog(arg, why); if(looksURL(arg)) console.log(MARK+' '+arg+' ;; '+why);
}
}catch(e){}; try{return o.apply(this,arguments)}catch(e){return undefined} };
}
}catch(e){}
}
try{
// WScript.Shell.Run / Exec
if(g.WScript && g.WScript.CreateObject){
var oco=g.WScript.CreateObject.bind(g.WScript);
g.WScript.CreateObject=function(progId){
var obj; try{ obj=oco(progId) }catch(e){ obj={} }
try{
if(/WScript\.Shell/i.test(progId) && obj){
wrapRunLike(obj, 'Run', 'WScript.Shell.Run');
wrapRunLike(obj, 'Exec', 'WScript.Shell.Exec');
}
}catch(e){}
return obj;
};
}
}catch(e){}
// ActiveXObject(XMLHTTP / WinHttpRequest / ADODB.Stream)
try{
var mkXHR=function(orig){
return {
open:function(m,u){ logIOC(u,'ActiveX.XMLHTTP.open'); try{ return orig.open?orig.open.apply(this,arguments):undefined }catch(e){ return undefined } },
send:function(){ try{ return orig.send?orig.send.apply(this,arguments):undefined }catch(e){ return undefined } }
};
};
var mkWinHttp=function(orig){
return {
Open:function(m,u,async){ logIOC(u,'WinHttpRequest.Open'); try{ return orig.Open?orig.Open.apply(this,arguments):undefined }catch(e){ return undefined } },
Send:function(){ try{ return orig.Send?orig.Send.apply(this,arguments):undefined }catch(e){ return undefined } }
};
};
function wrapAX(factory){
return function(progId){
var id=String(progId||'');
var obj;
try{ obj=factory(progId) }catch(e){ obj={} }
try{
if(/MSXML2\.XMLHTTP|Microsoft\.XMLHTTP/i.test(id) && obj) return mkXHR(obj);
if(/WinHttp\.WinHttpRequest/i.test(id) && obj) return mkWinHttp(obj);
if(/ADODB\.Stream/i.test(id) && obj){
// log SaveToFile path via simple proxy
var proxy=Object.create(obj);
try{
proxy.SaveToFile=function(path,mode){ console.log(MARK+' file://'+path+' ;; ADODB.Stream.SaveToFile'); try{ return obj.SaveToFile.apply(obj,arguments) }catch(e){ return undefined } };
}catch(e){}
return proxy;
}
}catch(e){}
return obj;
}
}
if(typeof g.ActiveXObject==='function'){
var oAX=g.ActiveXObject.bind(g);
g.ActiveXObject=wrapAX(oAX);
}
// Some samples use `new ActiveXObject(...)` path; above handles it since it's the same callable.
}catch(e){}
// ---- Final URL summary ----
try {
setTimeout(function() {
console.log('=== FINAL URL SUMMARY ===');
if(finalUrls.size > 0) {
finalUrls.forEach(function(url) {
console.log(FINALURL_MARK + ' ' + url + ' ;; FINAL_COMPLETE_URL');
});
} else {
console.log('No complete URLs detected');
}
console.log('=== END FINAL URL SUMMARY ===');
}, 100);
} catch(e) {}
})();
"""
def find_svgs(p: Path):
if p.is_file(): return [p]
return sorted(p.rglob("*.svg"))
def extract_scripts(svg_text: str):
scripts = []
# Extract inline scripts
for m in SVG_SCRIPT_RE.finditer(svg_text):
script_content = m.group(1) or ""
# Clean up script content for better parsing
script_content = clean_script_content(script_content)
if script_content.strip():
scripts.append(script_content)
# Extract data URI scripts
data_uri_pattern = re.compile(r'<script[^>]+src=["\']data:[^;]+;base64,([^"\']+)["\']', re.I)
for m in data_uri_pattern.finditer(svg_text):
b64_content = m.group(1)
try:
# Fix base64 padding if needed
missing_padding = len(b64_content) % 4
if missing_padding:
b64_content += '=' * (4 - missing_padding)
decoded = base64.b64decode(b64_content).decode('utf-8', errors='ignore')
decoded = clean_script_content(decoded)
if decoded.strip():
scripts.append(decoded)
except Exception:
pass # Skip if can't decode
return scripts
def clean_script_content(script: str) -> str:
"""Clean script content to remove CDATA, comments, and fix syntax issues"""
# Remove CDATA markers
script = re.sub(r'<!\[CDATA\[', '', script)
script = re.sub(r'\]\]>', '', script)
# Remove multi-line comments that start with ///
lines = script.split('\n')
cleaned_lines = []
for line in lines:
stripped = line.strip()
# Skip lines that are just comments or XML-like content
if (stripped.startswith('///') or
stripped.startswith('<!--') or
stripped.endswith('-->') or
stripped.startswith('<![CDATA[') or
stripped.endswith(']]>')):
continue
cleaned_lines.append(line)
return '\n'.join(cleaned_lines)
def convert_to_es5(js_code: str) -> str:
"""Convert modern JavaScript to ES5 compatible for box-js and add URL logging"""
# First, convert const and let to var for box-js compatibility
result = re.sub(r'\b(const|let)\b', 'var', js_code)
# Add atob implementation if atob is used
if 'atob(' in result and 'function atob(' not in result:
atob_impl = '''
if(typeof atob === 'undefined') {
var atob = function(str) {
var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
var result = '';
var i = 0;
str = str.replace(/[^A-Za-z0-9+/]/g, '');
while (i < str.length) {
var a = chars.indexOf(str.charAt(i++));
var b = chars.indexOf(str.charAt(i++));
var c = chars.indexOf(str.charAt(i++));
var d = chars.indexOf(str.charAt(i++));
var bitmap = (a << 18) | (b << 12) | (c << 6) | d;
result += String.fromCharCode((bitmap >> 16) & 255);
if (c !== 64) result += String.fromCharCode((bitmap >> 8) & 255);
if (d !== 64) result += String.fromCharCode(bitmap & 255);
}
return result;
};
}
'''
result = atob_impl + '\n' + result
# Add fetch implementation if fetch is used
if 'fetch(' in result and 'function fetch(' not in result:
fetch_impl = '''
if(typeof fetch === 'undefined') {
var fetch = function(url, options) {
console.log("[FINALURL] Dynamic execution code: fetch(" + JSON.stringify(url) + ")");
// Return a mock promise that resolves to empty response
return {
then: function(callback) {
if (callback) {
try {
var mockResponse = {
text: function() {
return {
then: function(textCallback) {
if (textCallback) textCallback("");
return { then: function() {}, catch: function() {} };
},
catch: function() { return { then: function() {} }; }
};
}
};
callback(mockResponse);
} catch(e) {}
}
return { then: function() {}, catch: function() {} };
},
catch: function() { return { then: function() {} }; }
};
};
}
'''
result = fetch_impl + '\n' + result
# Handle simple hex decoding pattern (Pattern 2 simplified)
if 'parseInt(' in result and '.substr(' in result and 'String.fromCharCode(' in result and '[].constructor.constructor' in result:
print(f" [DEBUG] Detected simple hex decoding pattern, analyzing...")
# This pattern uses simple hex decoding: parseInt(hex.substr(i, 2), 16)
# Override Function constructor BEFORE the original execution happens
function_override = '''
// Override Function constructor to log what gets executed
var origFunction = [].constructor.constructor;
[].constructor.constructor = function(code) {
console.log("[FINALURL] Generic eval code: " + code);
// Try to execute and catch any URLs
try {
return origFunction(code);
} catch (e) {
console.log("[ERROR] Simple hex execution failed: " + e);
return function() {};
}
};
'''
# Insert the override at the beginning of the script
result = function_override + result
# Handle hex-encoded dynamic execution pattern
elif ('[].constructor.constructor' in result or 'ckD(YuZ)()' in result) and 'oJx' in result:
print(f" [DEBUG] Detected hex-encoded dynamic execution pattern, analyzing...")
# This pattern uses dynamic hex decoding and then executes the result
# Override Function constructor BEFORE the original execution happens
function_override = '''
// Override Function constructor to log what gets executed
var origFunction = [].constructor.constructor;
[].constructor.constructor = function(code) {
console.log("[FINALURL] Dynamic execution code: " + code);
// Try to execute and catch any URLs
try {
return origFunction(code);
} catch (e) {
console.log("[ERROR] Dynamic execution failed: " + e);
return function() {};
}
};
'''
# Insert the override at the beginning of the script
result = function_override + result
# Handle XOR + dynamic eval construction pattern
elif ('Object.keys(L).sort()' in result or 'decodeURIComponent(e)' in result) and 'charCodeAt(C++' in result:
print(f" [DEBUG] Detected XOR + dynamic eval construction pattern, analyzing...")
# This pattern uses XOR decoding and dynamic eval construction
# Add atob function and eval override BEFORE the original execution happens
eval_override = '''
// Add missing atob function for box-js compatibility
if(typeof atob === 'undefined') {
var atob = function(str) {
var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
var result = '';
var i = 0;
str = str.replace(/[^A-Za-z0-9+/]/g, '');
while (i < str.length) {
var a = chars.indexOf(str.charAt(i++));
var b = chars.indexOf(str.charAt(i++));
var c = chars.indexOf(str.charAt(i++));
var d = chars.indexOf(str.charAt(i++));
var bitmap = (a << 18) | (b << 12) | (c << 6) | d;
result += String.fromCharCode((bitmap >> 16) & 255);
if (c !== 64) result += String.fromCharCode((bitmap >> 8) & 255);
if (d !== 64) result += String.fromCharCode(bitmap & 255);
}
return result;
};
}
// Override eval to log what gets executed
var origEval = eval;
eval = function(code) {
console.log("[FINALURL] Dynamic eval code: " + code);
try {
return origEval(code);
} catch (e) {
console.log("[ERROR] Eval execution failed: " + e);
return undefined;
}
};
'''
# Insert the override at the beginning of the script
result = eval_override + result
# Handle character mapping + find() execution pattern
elif ('String.fromCharCode(j[' in result or '.find(() =>' in result) and 'filter.constructor' in result:
print(f" [DEBUG] Detected character mapping + find() execution pattern, analyzing...")
# This pattern uses character mapping and Array.find() execution
# Add atob function and eval override BEFORE the original execution happens
eval_override = '''
// Add missing atob function for box-js compatibility
if(typeof atob === 'undefined') {
var atob = function(str) {
var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
var result = '';
var i = 0;
str = str.replace(/[^A-Za-z0-9+/]/g, '');
while (i < str.length) {
var a = chars.indexOf(str.charAt(i++));
var b = chars.indexOf(str.charAt(i++));
var c = chars.indexOf(str.charAt(i++));
var d = chars.indexOf(str.charAt(i++));
var bitmap = (a << 18) | (b << 12) | (c << 6) | d;
result += String.fromCharCode((bitmap >> 16) & 255);
if (c !== 64) result += String.fromCharCode((bitmap >> 8) & 255);
if (d !== 64) result += String.fromCharCode(bitmap & 255);
}
return result;
};
}
// Override eval to log what gets executed
var origEval = eval;
eval = function(code) {
console.log("[FINALURL] Character mapping eval code: " + code);
try {
return origEval(code);
} catch (e) {
console.log("[ERROR] Character mapping eval execution failed: " + e);
return undefined;
}
};
'''
# Insert the override at the beginning of the script
result = eval_override + result
# Handle arithmetic character code eval construction pattern
elif ('String.fromCharCode(' in result and 'Y.S +' in result) or ('Function("return this")' in result and 'parseInt(' in result):
print(f" [DEBUG] Detected arithmetic character code eval construction pattern, analyzing...")
# This pattern uses arithmetic to build character codes for "eval"
# Add atob function and eval override BEFORE the original execution happens
eval_override = '''
// Add missing atob function for box-js compatibility
if(typeof atob === 'undefined') {
var atob = function(str) {
var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
var result = '';
var i = 0;
str = str.replace(/[^A-Za-z0-9+/]/g, '');
while (i < str.length) {
var a = chars.indexOf(str.charAt(i++));
var b = chars.indexOf(str.charAt(i++));
var c = chars.indexOf(str.charAt(i++));
var d = chars.indexOf(str.charAt(i++));
var bitmap = (a << 18) | (b << 12) | (c << 6) | d;
result += String.fromCharCode((bitmap >> 16) & 255);
if (c !== 64) result += String.fromCharCode((bitmap >> 8) & 255);
if (d !== 64) result += String.fromCharCode(bitmap & 255);
}
return result;
};
}
// Override eval to log what gets executed
var origEval = eval;
eval = function(code) {
console.log("[FINALURL] Arithmetic eval code: " + code);
try {
return origEval(code);
} catch (e) {
console.log("[ERROR] Arithmetic eval execution failed: " + e);
return undefined;
}
};
'''
# Insert the override at the beginning of the script
result = eval_override + result
# Handle common obfuscation patterns (catch-all for variants)
elif any(pattern in result for pattern in [
'setTimeout(', 'setInterval(', 'Promise.resolve()', '.then(',
'new Function(', 'Function.constructor', 'eval.call(',
'(1,eval)', '(0,eval)', 'String.fromCharCode(',
'addEventListener(', 'dispatchEvent(', 'parseInt(',
'atob(', 'btoa(', 'decodeURI', 'unescape(',
'constructor("return', 'filter.constructor'
]) and any(suspicious in result for suspicious in [
'window.location', 'document.location', '.href =',
'charAt(', 'charCodeAt(', 'fromCharCode(',
'split(', 'join(', 'slice(', 'substr('
]):
print(f" [DEBUG] Detected common obfuscation pattern, adding safety overrides...")
# Add comprehensive overrides for any suspicious dynamic execution
safety_override = '''
// Add missing atob function for box-js compatibility
if(typeof atob === 'undefined') {
var atob = function(str) {
var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
var result = '';
var i = 0;
str = str.replace(/[^A-Za-z0-9+/]/g, '');
while (i < str.length) {
var a = chars.indexOf(str.charAt(i++));
var b = chars.indexOf(str.charAt(i++));
var c = chars.indexOf(str.charAt(i++));
var d = chars.indexOf(str.charAt(i++));
var bitmap = (a << 18) | (b << 12) | (c << 6) | d;
result += String.fromCharCode((bitmap >> 16) & 255);
if (c !== 64) result += String.fromCharCode((bitmap >> 8) & 255);
if (d !== 64) result += String.fromCharCode(bitmap & 255);
}
return result;
};
}
// Override eval and Function constructor
var origEval = eval;
eval = function(code) {
console.log("[FINALURL] Generic eval code: " + code);
try {
return origEval(code);
} catch (e) {
console.log("[ERROR] Generic eval execution failed: " + e);
return undefined;
}
};
var origFunction = Function;
Function = function() {
var code = arguments[arguments.length - 1];
console.log("[FINALURL] Generic Function code: " + code);
try {
return origFunction.apply(this, arguments);
} catch (e) {
console.log("[ERROR] Generic Function execution failed: " + e);
return function() {};
}
};
// Override setTimeout for delayed execution
if(typeof setTimeout !== 'undefined') {
var origSetTimeout = setTimeout;
setTimeout = function(func, delay) {
if(typeof func === 'string') {
console.log("[FINALURL] setTimeout eval code: " + func);
try {
return origSetTimeout(function() { origEval(func); }, delay);
} catch (e) {
console.log("[ERROR] setTimeout execution failed: " + e);
return 0;
}
}
return origSetTimeout.apply(this, arguments);
};
}
'''
# Insert the override at the beginning of the script
result = safety_override + result
# Handle XOR + Proxy eval pattern - add forced execution at the end
elif 'new Proxy(' in result and 'Symbol.toPrimitive' in result:
print(f" [DEBUG] Detected XOR + Proxy pattern, analyzing...")
# Look for the pattern where eval is hidden in a proxy
# Find the variable that contains the decoded URL (usually 'h')
# Find the variable that contains "eval" (usually constructed from array)
# Add direct execution at the end
url_var_match = re.search(r'(\w+)\s*\+=\s*"%"\s*\+[^;]+\.toString\(16\)', result)
eval_var_match = re.search(r'var\s+(\w+)\s*=\s*\[.*?\]\.join\(', result)
global_var_match = re.search(r'var\s+(\w+)\s*=\s*\[\]\.filter\.constructor\("return this"\)', result)
print(f" [DEBUG] URL var match: {url_var_match.group(1) if url_var_match else None}")
print(f" [DEBUG] Eval var match: {eval_var_match.group(1) if eval_var_match else None}")
print(f" [DEBUG] Global var match: {global_var_match.group(1) if global_var_match else None}")
if url_var_match and eval_var_match and global_var_match:
print(f" [DEBUG] All patterns matched, adding XOR execution code...")
url_var = url_var_match.group(1)
eval_var = eval_var_match.group(1)
global_var = global_var_match.group(1)
# Replace the proxy execution (N + "") with our direct execution
proxy_execution_pattern = r'(\w+)\s*\+\s*""\s*;'
def replace_proxy_execution(match):
return f'// Proxy execution replaced with direct XOR decode'
result = re.sub(proxy_execution_pattern, replace_proxy_execution, result)
# Add direct execution at the end with atob function
result += f'''
// Ensure atob is available for eval
if(typeof atob === 'undefined') {{
var atob = function(str) {{
var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
var result = '';
var i = 0;
str = str.replace(/[^A-Za-z0-9+/]/g, '');
while (i < str.length) {{
var a = chars.indexOf(str.charAt(i++));
var b = chars.indexOf(str.charAt(i++));
var c = chars.indexOf(str.charAt(i++));
var d = chars.indexOf(str.charAt(i++));
var bitmap = (a << 18) | (b << 12) | (c << 6) | d;
result += String.fromCharCode((bitmap >> 16) & 255);
if (c !== 64) result += String.fromCharCode((bitmap >> 8) & 255);
if (d !== 64) result += String.fromCharCode(bitmap & 255);
}}
return result;
}};
}}
try {{
console.log("[FINALURL] XOR decoded URL variable: " + {url_var});
console.log("[FINALURL] Eval variable: " + {eval_var});
var __decoded_url = decodeURIComponent({url_var});
console.log("[FINALURL] Decoded URL code: " + __decoded_url);
// Try to execute the decoded JavaScript to get the final URL
try {{
{global_var}[{eval_var}](__decoded_url);
}} catch (eval_error) {{
console.log("[ERROR] Eval failed, trying manual parsing: " + eval_error);
// Manual parsing - look for window.location.href = atob(...) + variable patterns
if(__decoded_url.indexOf('window.location.href') !== -1) {{
console.log("[FINALURL] Found window.location.href assignment, attempting manual decode");
// Extract the email variable (usually 'i')
var email_var = '';
if(__decoded_url.indexOf('+i') !== -1) email_var = i;
// Look for concatenated base64 strings in the decoded URL
// Pattern: atob("part1"+"part2"+...)+variable
var b64_parts = [];
var concat_pattern = /atob\s*\(\s*([^)]+)\s*\)/;
var atob_match = concat_pattern.exec(__decoded_url);
if (atob_match) {{
var atob_content = atob_match[1];
console.log("[FINALURL] Found atob content: " + atob_content);
// Extract individual base64 strings
var b64_pattern = /["']([^"']+)["']/g;
var b64_match;
var combined_b64 = '';
while ((b64_match = b64_pattern.exec(atob_content)) !== null) {{
combined_b64 += b64_match[1];
}}
if (combined_b64) {{
try {{
var decoded_url = atob(combined_b64);
console.log("[FINALURL] Decoded base URL: " + decoded_url);
if (email_var) {{
var final_url = decoded_url + email_var;
console.log("[FINALURL] " + final_url + " ;; manual_xor_decode");
}}
}} catch (decode_error) {{
console.log("[ERROR] Failed to decode combined base64: " + decode_error);
}}
}}
}}
}}
}}
}} catch (e) {{
console.log("[ERROR] XOR execution failed: " + e);
}}
'''
# Remove async/await syntax and convert to regular function
# Pattern: try {(async function() { ... })(); } catch (e) {}
async_pattern = r'try\s*\{\s*\(\s*async\s+function\s*\(\s*\)\s*\{\s*(.*?)\s*\}\s*\)\s*\(\s*\)\s*;\s*\}\s*catch\s*\(\s*\w+\s*\)\s*\{\s*\}'
def replace_async(match):
inner_code = match.group(1)
# Convert to regular try-catch with immediate function
return f'try {{ (function() {{ {inner_code} }})(); }} catch (e) {{}}'
result = re.sub(async_pattern, replace_async, result, flags=re.DOTALL)
# Add URL interception directly into the code (only if XOR pattern wasn't applied)
# Look for window.location.href assignments and add logging
if not ('new Proxy(' in result and 'Symbol.toPrimitive' in result):
location_pattern = r'window\.location\.href\s*=\s*([^;]+);?'
def replace_location(match):
url_expr = match.group(1)
# Add explicit console logging before the assignment
return f'''
try {{
var __final_url = {url_expr};
console.log("[FINALURL] " + __final_url + " ;; dynamic_url_construction");
window.location.href = __final_url;
}} catch (e) {{
console.log("[ERROR] Failed to construct URL: " + e);
}}'''
result = re.sub(location_pattern, replace_location, result)
# Final catch-all for any remaining JavaScript that might contain URLs
if not any([
'[FINALURL]' in result, # Already has our overrides
'console.log(' in result and '[FINALURL]' in result, # Already processed
result.strip().startswith('//') # Just comments
]) and any([
'location' in result, 'href' in result, 'atob(' in result,
'eval(' in result, 'Function(' in result, 'constructor(' in result
]):
print(f" [DEBUG] Adding minimal safety overrides for unrecognized pattern...")
minimal_override = '''
// Minimal safety overrides for unrecognized patterns
if(typeof atob === 'undefined') {
var atob = function(str) {
var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
var result = '';
var i = 0;
str = str.replace(/[^A-Za-z0-9+/]/g, '');
while (i < str.length) {
var a = chars.indexOf(str.charAt(i++));
var b = chars.indexOf(str.charAt(i++));
var c = chars.indexOf(str.charAt(i++));
var d = chars.indexOf(str.charAt(i++));
var bitmap = (a << 18) | (b << 12) | (c << 6) | d;
result += String.fromCharCode((bitmap >> 16) & 255);
if (c !== 64) result += String.fromCharCode((bitmap >> 8) & 255);
if (d !== 64) result += String.fromCharCode(bitmap & 255);
}
return result;
};
}
'''
result = minimal_override + result
return result
def write_temp_js(scripts, out_dir: Path, base_name: str) -> Path:
out_dir.mkdir(parents=True, exist_ok=True)
js_path = out_dir / f"{base_name}.boxed.js"
with js_path.open("wb") as f:
for i, s in enumerate(scripts):
if s.strip(): # Only write non-empty scripts
f.write(f"// ---- script boundary {i} ----\n".encode("utf-8"))
# Ensure each script ends with semicolon to prevent syntax issues
script_content = s.strip()
# Convert modern JS syntax to ES5 for box-js compatibility
script_content = convert_to_es5(script_content)
if script_content and not script_content.endswith((';', '}')):
script_content += ';'
f.write(script_content.encode("utf-8", errors="replace"))
f.write(b"\n\n")
return js_path
def write_prelude(out_dir: Path) -> Path:
prelude = out_dir / "prelude.ioc.js"
prelude.write_text(PRELUDE_JS, encoding="utf-8")
return prelude
def run_boxjs(js_path: Path, result_dir: Path, prelude_path: Path, timeout: int) -> Tuple[bool, str]:
result_dir.mkdir(parents=True, exist_ok=True)
flags = BOXJS_BASE_FLAGS + [f"--prepended-code={prelude_path}"]
cmd = [BOXJS_CMD] + flags + ["--output-dir", str(result_dir), str(js_path)]
try:
p = subprocess.run(cmd, capture_output=True, text=True, timeout=timeout)
(result_dir / "analysis.stdout.log").write_text(p.stdout + "\n\nSTDERR:\n" + p.stderr, encoding="utf-8")
return (p.returncode == 0), p.stdout + "\n\nSTDERR:\n" + p.stderr
except subprocess.TimeoutExpired:
(result_dir / "analysis.stdout.log").write_text("TIMEOUT (expired)\n", encoding="utf-8")
return False, "TIMEOUT"
except FileNotFoundError:
print("[!] 'box-js' not found. Install with: npm install -g box-js", file=sys.stderr)
sys.exit(3)
def gather_results(result_dir: Path, raw_emails: set = None) -> Tuple[Set[str], Set[str]]:
urls, emails = set(), set()
final_urls = set() # Track the final complete URLs
# Include emails from the raw SVG file
if raw_emails:
emails.update(raw_emails)
top = result_dir / "analysis.stdout.log"
if top.exists():
txt = top.read_text(encoding="utf-8", errors="ignore")
# Extract emails first (before parsing JS)
for em in EMAIL_RE.findall(txt):
emails.add(em)
# DEBUG: Show all box-js output
print(f" [DEBUG] Box-js stdout content:")
for i, line in enumerate(txt.splitlines()[:20], 1): # Show first 20 lines
print(f" {i:2}: {line}")
if len(txt.splitlines()) > 20:
print(f" ... and {len(txt.splitlines()) - 20} more lines")
print(f" [DEBUG] Emails found in box-js output: {emails}")
# First priority: Extract FINALURL markers (complete URLs)
finalurl_count = 0
for line in txt.splitlines():
if FINALURL_MARK in line:
finalurl_count += 1
print(f" [DEBUG] Found FINALURL marker: {line}")
try:
part = line.split(FINALURL_MARK, 1)[1].strip()
if part:
final_url = part.split(" ;;", 1)[0].strip()
if final_url and is_http_like(final_url):
final_urls.add(final_url)
print(f" [DEBUG] Added final URL: {final_url}")
elif "Decoded URL code:" in part: