Project Hub: WSHawk v4.0.0
WSHawk is an open-source websocket security testing and web application penetration testing toolkit. Designed for authorized security assessments, bug bounty hunters, and offensive security engineers, WSHawk shifts the focus from stateless HTTP scanning to stateful, bidirectional protocol analysis.
Modern web applications—such as trading interfaces, collaboration platforms, and internal dashboards—rely heavily on WebSockets for real-time data streaming. Traditional HTTP scanners fail to assess these connections because they do not persist state, handle asynchronous race conditions, or interpret binary and JSON-framed WebSocket protocols. WSHawk bridges this gap by combining a full-duplex WebSocket interceptor with a Smart Payload Engine (SPE) and Playwright-assisted DOM mutation evidence collection.
Technical Features
1. Smart Payload Evolution (SPE)
Source File: wshawk/smart_payloads/payload_evolver.py
Relevant Class: PayloadEvolver
CLI Command: wshawk-advanced ws://target.com --smart-payloads
The payload evolver uses genetic algorithms to bypass Web Application Firewalls (WAFs) and input filters.
- Mutation Strategies: Implements 10 distinct mutation categories including
char_swap,encoding_wrap(Base64, Hex, ROT13),null_padding, andcase_tricks. - WAF Bypass Injection: Automatically injects SQL comments (
/**/), HTML breaks (<![CDATA[), and string concatenation breakers ('+') into payloads that trigger initial WAF blocks. - Crossover Breeding: Combines successful payloads using
split,interleave,wrap, andinjectrecombination strategies to create novel bypasses not found in standard wordlists.
1.1 Deep Dive: Genetic Recombination
When the PayloadEvolver detects that two separate payloads successfully bypassed a WAF but failed to exploit the target, it breeds them.
Split Crossover Example:
def _crossover_split(self, parent1: str, parent2: str) -> str:
"""Split each parent and swap halves."""
mid1 = len(parent1) // 2
mid2 = len(parent2) // 2
if random.random() < 0.5:
return parent1[:mid1] + parent2[mid2:]
else:
return parent2[:mid2] + parent1[mid1:]
If Parent 1 is <script>alert(1)</script> and Parent 2 is <img src=x onerror=alert(1)>, a split crossover might produce <script>alert(1 onerror=alert(1)>, breaking regex signatures while potentially remaining syntactically valid in permissive HTML parsers.
2. Headless Browser XSS Verifier
Source File: wshawk/headless_xss_verifier.py
Relevant Class: HeadlessBrowserXSSVerifier
CLI Command: wshawk-advanced ws://target.com --playwright
To eliminate false positives in Cross-Site Scripting (XSS) detection, WSHawk uses a Chromium Playwright instance to execute payloads in a sandboxed DOM environment.
- Execution Beacons: Overrides the native
window.alertfunction to trap execution beacons and verifies execution state by readingwindow.xssExecuted. - DOM Mutation Tracking: Checks for injected
<script>tags and dynamically added event handlers (onmouseover,onerror) bypassing the need for static regex matches.
2.1 Playwright Integration Architecture
WSHawk wraps Playwright in an asynchronous task pool. When a suspected reflection is detected on the socket, it is queued for browser verification.
async def verify_xss_execution(self, html_content: str, payload: str, timeout: int = 5) -> Tuple[bool, str]:
page = await self.browser.new_page()
# Set up alert handler
alert_detected = False
alert_message = ""
async def handle_dialog(dialog):
nonlocal alert_detected, alert_message
alert_detected = True
alert_message = dialog.message
await dialog.dismiss()
page.on("dialog", handle_dialog)
# ... DOM evaluation logic continues
3. Full-Duplex WebSocket Interceptor (MitM)
Source File: wshawk/wshawk-bridge.spec (Desktop Build)
The Electron desktop application includes a real-time interceptor proxy that sits between the client and the target server.
- Frame-by-Frame Control: Allows operators to drop, forward, or edit text and binary WebSocket frames in transit.
- Identity-Aware Replay: Captures authorization headers and session tokens during the HTTP upgrade handshake, enabling replay of specific WebSocket sequences under different user identities to test for vertical and horizontal privilege escalation (IDOR/BOLA).
- Binary Frame Unmasking: Automatically XOR-unmasks client-to-server traffic, providing plaintext visibility into proprietary protocol streams.
The 22 Web Pentest Modules
WSHawk integrates 22 built-in Web Pentest tools to orchestrate a complete attack chain. These modules are accessible via the Python API or the wshawk-advanced CLI.
Reconnaissance & Discovery
-
Web Crawler (
web_pentest/crawler.py)- Implements a Breadth-First Search (BFS) spider.
- Extracts forms, API endpoints, and parses
robots.txtandsitemap.xml. - Asynchronous execution ensures high throughput.
-
Subdomain Finder (
web_pentest/subdomain_finder.py)- Passive enumeration via
crt.sh(Certificate Transparency). - Queries AlienVault OTX.
- Active DNS brute-forcing with concurrent
dnspythonresolution validation.
- Passive enumeration via
-
Technology Fingerprinter (
web_pentest/tech_fingerprint.py)- Identifies 35+ technologies (Nginx, Apache, WordPress, React, Cloudflare, AWS WAF, etc.).
- Analyzes HTTP headers, Set-Cookie structures, and DOM fingerprints.
-
DNS / WHOIS Lookup (
web_pentest/dns_lookup.py)- Full record enumeration (A, AAAA, MX, NS, TXT, CNAME, SOA, SRV, CAA).
- Integrates WHOIS registration data extraction.
-
TCP Port Scanner (
web_pentest/port_scanner.py)- Async connect scanner utilizing non-blocking sockets.
- Service identification and banner grabbing.
- Preset port lists (top-100, common-web, database, full 65535).
Vulnerability Scanning
-
HTTP Fuzzer (
web_pentest/fuzzer.py)- Parameter fuzzing utilizing
§FUZZ§placeholder markers. - Built-in wordlists optimized for discovery.
- Encoding options (URL, Base64, Hex) applied per-payload.
- Parameter fuzzing utilizing
-
Directory Scanner (
web_pentest/dir_scanner.py)- Path brute-forcing with extension permutation (
.php,.aspx,.json). - Recursive scanning for identified directories.
- WAF-evasion throttling (dynamic delay injection upon
429responses).
- Path brute-forcing with extension permutation (
-
Automated Vulnerability Scanner (
web_pentest/vuln_scanner.py)- Multi-phase orchestrator.
- Pipeline: Crawl Header Analysis Directory Scan Fuzz Sensitive Data Scan.
- Auto-escalation logic (e.g., attempting LFI chaining if a local inclusion vulnerability is identified).
-
Security Header Analyzer (
web_pentest/header_analyzer.py)- Evaluates
Strict-Transport-Security,Content-Security-Policy,X-Frame-Options. - Assigns risk ratings based on missing or misconfigured directives.
- Evaluates
-
Sensitive Data Finder (
web_pentest/sensitive_finder.py)- Regex detection engine for 30+ secret types.
- Detects AWS keys, Google API keys, JWTs, GitHub tokens, database connection strings, and internal IP address leaks within HTML comments or JS bundles.
Offensive Security Tools
-
WAF Detector (
web_pentest/waf_detector.py)- Passive and active fingerprinting of 15+ WAFs.
- Signatures for Cloudflare, AWS WAF, Akamai, Imperva, Sucuri, ModSecurity, and F5 BIG-IP.
-
CORS Misconfiguration Tester (
web_pentest/cors_tester.py)- Probes 6 distinct attack patterns.
- Tests wildcard origins, null origins, subdomain suffix attacks, domain prefix injections, and HTTP downgrade (
https://tohttp://).
-
SSL/TLS Analyzer (
web_pentest/ssl_analyzer.py)- Certificate inspection using the
cryptographylibrary. - Protocol version testing (TLS 1.0–1.3).
- Weak cipher detection, expiry validation, and self-signed certificate checks.
- Certificate inspection using the
-
SSRF Prober (
web_pentest/ssrf_prober.py)- Executes 40+ payloads targeting cloud metadata endpoints.
- Targets AWS (
169.254.169.254), GCP, Azure. - Tests DNS rebinding vectors and URL parser confusion.
-
Open Redirect Scanner (
web_pentest/redirect_scanner.py)- 25+ bypass techniques (e.g.,
//evil.com,https:evil.com). - Auto-detection of 20+ common redirect parameter names (
next,url,target,return_to).
- 25+ bypass techniques (e.g.,
-
Prototype Pollution Tester (
web_pentest/proto_polluter.py)- Targets Node.js and client-side JavaScript environments.
- Injects
__proto__andconstructor.prototypevia URL query parameters and nested JSON bodies. - Detects pollution by monitoring global scope escalation.
Exploit Generation & Attack Chaining
-
CSRF Exploit Forge (
web_pentest/csrf_forge.py)- Generates standalone HTML Proof-of-Concept (PoC) files.
- Supports auto-submitting standard POST forms, Fetch API XHR requests, and multipart form data.
- Auto-detects CSRF token presence to warn the operator.
-
Attack Chainer (
web_pentest/attack_chainer.py)- Multi-step HTTP attack sequencing.
- Regex-based value extraction from Step 1 response.
{{variable}}templating to inject extracted values into Step 2 requests (useful for exploiting multi-step authentication or checkout flows).
-
Proxy CA Generator (
web_pentest/proxy_ca.py)- Generates a Root Certificate Authority (RSA 4096-bit, 10-year validity).
- Handles per-host certificate signing for seamless HTTPS interception.
-
HTTP Request Forge (
web_pentest/http_proxy.py)- Manual HTTP request builder supporting all standard verbs (
GET,POST,PUT,DELETE,PATCH,HEAD,OPTIONS). - Requests are routed through the Python daemon to bypass restrictive browser CORS policies.
- Manual HTTP request builder supporting all standard verbs (
-
Report Generator (
web_pentest/report_gen.py)- Compiles findings into professional HTML reports.
- Includes executive summaries, severity charts, and remediation guidance.
- Exports to JSON, PDF, CSV, and SARIF 2.1.0 formats.
-
Out-Of-Band (OAST) Provider (
oast_provider.py)- Injects tracking domains to detect blind vulnerabilities.
- Polls external DNS resolvers to confirm out-of-band execution.
Comprehensive CLI Reference
WSHawk provides four separate CLI entry points for different operational modes.
1. wshawk (Standard Scanner)
The standard CLI initiates the heuristic vulnerability scanner against a target WebSocket URI.
Syntax:
wshawk [OPTIONS] <TARGET_URI>
Key Parameters:
--headers <JSON>: Pass custom HTTP headers (e.g.,{"Authorization": "Bearer token"}).--timeout <INT>: Timeout for socket connections (default: 10).--concurrency <INT>: Number of concurrent async payload tasks (default: 50).--format <STRING>: Output format (json,html,csv,sarif).--out <FILE>: Output file path.
Example:
wshawk wss://api.target.com/chat --headers '{"Cookie": "session=xyz"}' --format sarif --out results.sarif
2. wshawk-advanced (Deep Auditing)
The advanced CLI enables computationally expensive features like the Smart Payload Engine and Headless Verifier.
Syntax:
wshawk-advanced [OPTIONS] <TARGET_URI>
Key Parameters:
--smart-payloads: Enables the genetic algorithm payload evolver.--playwright: Enables the headless Chromium XSS verifier.--oast: Enables Out-Of-Band (OAST) callback detection for blind SSRF.--generations <INT>: Number of evolution generations to process (default: 10).--population <INT>: Size of the payload population pool (default: 50).--full: Enables all advanced checks simultaneously.
Example:
wshawk-advanced wss://api.target.com/data --smart-payloads --playwright --oast
3. wshawk-interactive (REPL Mode)
Starts a Read-Eval-Print Loop (REPL) for manual, frame-by-frame interaction with a WebSocket endpoint without utilizing the Electron GUI.
Example Session:
$ wshawk-interactive
> connect wss://target.com/ws
[+] Connected to wss://target.com/ws
> send {"action": "ping"}
[<] {"status": "pong", "timestamp": 1690000000}
> fuzz {"action": "view_user", "id": §FUZZ§} --type sqli
[!] Fuzzing initiated. Check wshawk.log for results.
4. wshawk-defensive (Blue Team Validation)
Designed for defensive engineering teams to validate the effectiveness of their security controls.
Key Parameters:
--test-cswsh: Tests origin header validation.--test-tls: Validates cipher suites and TLS protocol versions.--test-bot-evasion: Simulates headless browser bot traffic to test WAF bot-protection mechanisms.
Configuration Schema (wshawk.yaml)
WSHawk utilizes a comprehensive YAML configuration file to manage environment-specific variables, integration tokens, and tuning parameters.
To generate the default configuration template:
python3 -m wshawk.config --generate
Breakdown of wshawk.yaml
version: 4.0.0
core:
# The local port for the Python Bridge (used by Electron UI)
bridge_port: 8080
# Maximum memory to allocate for SQLite WAL mode cache
db_cache_size_mb: 256
# Maximum concurrent websocket connections per target
max_connections: 50
scanner:
# Default timeout in seconds for socket reads
read_timeout: 15
# The user-agent string presented during the HTTP upgrade
user_agent: "Mozilla/5.0 (Windows NT 10.0; Win64; x64; WSHawk/4.0)"
# Comma separated list of domains to bypass proxy settings
no_proxy: "localhost,127.0.0.1"
advanced_features:
playwright:
# Set to false to see the Chromium window during testing (useful for debugging)
headless: true
# Maximum time to wait for DOM mutation or alert beacon (ms)
timeout_ms: 2000
payload_evolver:
mutation_rate: 0.3
crossover_rate: 0.5
# The minimum fitness score required to enter the Hall of Fame
elite_threshold: 0.7
integrations:
jira:
# Use the 'env:' prefix to pull from environment variables securely
api_token: "env:JIRA_TOKEN"
url: "https://your-org.atlassian.net"
project_key: "SEC"
issue_type: "Vulnerability"
defectdojo:
api_key: "env:DD_API_KEY"
url: "https://defectdojo.your-org.com"
webhook:
# Receive POST payloads when critical vulnerabilities are found
url: "https://hooks.slack.com/services/T0000/B0000/XXXX"
Comprehensive Installation Guide
WSHawk is distributed across multiple package managers to support diverse operating environments.
1. Docker Deployment (Recommended)
Docker provides a zero-setup environment, packaging the Python daemon, the Playwright Chromium binaries, and all dependencies.
# Pull the latest image
docker pull rothackers/wshawk:latest
# Run a basic scan
docker run --rm rothackers/wshawk ws://target.com
# Run an advanced scan mounting a local directory for reports
docker run --rm -v $(pwd)/reports:/reports rothackers/wshawk \
wshawk-advanced ws://target.com --playwright --out /reports/results.html
2. Python Package Index (pip)
For users who prefer managing their own Python virtual environments. Python 3.8+ is required.
# Create and activate a virtual environment
python3 -m venv wshawk-env
source wshawk-env/bin/activate
# Install the core scanner
pip install wshawk
# Optional: Install Playwright binaries for headless verification
playwright install chromium
3. Arch Linux (AUR)
Arch users can utilize the Arch User Repository for native system integration.
# Install via yay
yay -S wshawk
4. Kali Linux / Debian APT
We maintain an official Debian package repository signed with the WSHawk GPG key.
# Add the WSHawk GPG key to your keyring
curl -sSL https://regaan.github.io/wshawk-repo/wshawk_repo.gpg.key | \
sudo gpg --dearmor -o /usr/share/keyrings/wshawk-archive-keyring.gpg
# Add the WSHawk APT repository list
echo "deb [signed-by=/usr/share/keyrings/wshawk-archive-keyring.gpg] https://regaan.github.io/wshawk-repo stable main" | \
sudo tee /etc/apt/sources.list.d/wshawk.list
# Update package cache and install
sudo apt update && sudo apt install wshawk
5. macOS (Homebrew)
macOS users can install the CLI and the Electron Desktop Application via our custom Homebrew Tap.
# Register the WSHawk tap
brew tap regaan/tap
# Install the cask (includes the Electron Desktop App)
brew install --cask wshawk
Python API Integration
WSHawk is designed to be highly modular. You can import the core engines directly into your own custom Python scripts to build highly specialized testing harnesses.
Example: Custom Heuristic Scan
import asyncio
from wshawk.scanner_v2 import WSHawkV2
async def custom_scan():
# Initialize the scanner targeting an authenticated endpoint
scanner = WSHawkV2("wss://api.target.com/stream")
# Set HTTP Upgrade headers
scanner.set_headers({
"Authorization": "Bearer eyJhbGciOiJIUzI1NiIsInR5c...",
"Origin": "https://target.com"
})
# Enable advanced verification modules
scanner.use_headless_browser = True
scanner.use_oast = True
print("[*] Starting heuristic scan...")
results = await scanner.run_heuristic_scan()
# Process findings
for finding in results.vulnerabilities:
print(f"[!] Found {finding.type} - Severity: {finding.cvss_score}")
print(f" Evidence: {finding.evidence}")
if __name__ == "__main__":
asyncio.run(custom_scan())
Example: Utilizing the Payload Evolver Standalone
from wshawk.smart_payloads.payload_evolver import PayloadEvolver
# Initialize the genetic algorithm engine
evolver = PayloadEvolver(population_size=20, mutation_rate=0.4, crossover_rate=0.6)
# Seed the population with payloads that bypassed a WAF
initial_seeds = [
"<script>alert(1)</script>",
"<img src=x onerror=alert(1)>"
]
evolver.seed(initial_seeds, initial_fitness=0.6)
# Generate the next generation of mutated payloads
print("[*] Evolving payloads...")
generation_2 = evolver.evolve(count=5)
for payload in generation_2:
print(f"Mutated Payload: {payload}")
Threat Model & Scope Definitions
WSHawk operates under a strictly defined threat model. It is designed to evaluate specific Web Application and API vulnerabilities within the application layer (OSI Layer 7).
Assumptions
- Authorization: The operator executing WSHawk possesses explicit, documented authorization to perform penetration testing against the target infrastructure.
- Network Reachability: The host running WSHawk can establish a TCP connection to the target server and successfully negotiate the HTTP
Connection: Upgradehandshake. - Protocol Support: The target application relies on standard HTTP or WebSocket protocols.
In Scope (Supported Attack Vectors)
- Cross-Site WebSocket Hijacking (CSWSH): Bypassing Origin, CORS, and CSRF token restrictions during the initial HTTP handshake phase.
- DOM-based & Reflected XSS: Exploiting unsafe client-side rendering (e.g.,
innerHTML) of data pushed via WebSocket frames. - Blind SSRF & OAST: Triggering out-of-band network calls from backend workers processing message queues fed by WebSocket data.
- SQL & NoSQL Injection: Exploiting backend database queries triggered by specific JSON properties within the WebSocket payload envelope.
- Command Injection: Exploiting blind execution contexts using time-based payloads (e.g.,
sleep 10) or asynchronous callback markers. - Vertical & Horizontal Privilege Escalation (IDOR/BOLA): Tested via Identity-Aware Replay of WebSocket state sequences.
Out of Scope (Unsupported / Prevented Vectors)
- Layer 3 / Layer 4 DDoS Attacks: WSHawk does not perform SYN floods, UDP amplification, or volumetric bandwidth exhaustion attacks. (Note: Highly aggressive fuzzing may inadvertently cause application-level DoS).
- Supply-Chain Dependency Exploits: WSHawk does not scan the target’s node_modules or Python dependencies for known CVEs.
- Physical Security Penetration: Beyond the scope of network assessment.
- Social Engineering / Phishing: WSHawk does not generate phishing templates or credential harvesting infrastructure.
- Zero-Click OS Exploitation: WSHawk focuses on application-layer logic flaws, not binary buffer overflows or kernel exploitation.
System Architecture
WSHawk decouples its execution context between a local background daemon (Python) and a frontend dashboard (Electron or Flask). This allows long-running asynchronous scans to persist state regardless of the user interface.
Detailed Data Flow
graph TD
A[User Interface: Electron Desktop / CLI] -->|REST/WS| B(Python Daemon Bridge)
B --> C{Operation Mode}
C -->|Automated Scan| D[Scanner Engine v2]
C -->|Manual Intercept| E[MitM Proxy Port]
D --> F[Smart Payload Evolver]
D --> G[Playwright DOM Verifier]
D --> L[OAST Provider]
F --> H[AsyncIO Websocket Client]
L -.-> H
G -.-> H
E --> H
H -->|TLS / TCP| I[Target WSS Endpoint]
I -->|Masked/Unmasked Frames| H
H --> J[SQLite WAL Store & Evidence Collector]
J --> K[SARIF / HTML / JSON Exporter]
K --> M[CI/CD Pipeline Integration]
Validation Labs
WSHawk includes local validation lab environments designed to train offensive engineers on stateful WebSocket exploitation. These labs are containerized and can be launched locally.
full_stack_realtime_saas: A vulnerable trading dashboard demonstrating delayed asynchronous SQL injection and Race Conditions in bid processing.socketio_saas: A chat application demonstrating blind XSS, DOM-based XSS, and Server-Side Request Forgery via profile image URLs.graphql_subscriptions_lab: A complex GraphQL endpoint utilizing WebSockets for real-time subscription updates, vulnerable to deep object property Prototype Pollution and NoSQL injection.
Security Warning & Responsible Use
[!CAUTION] WSHawk generates aggressive fuzzing traffic and exploit payloads that can disrupt services, alter backend databases, and trigger incident response alerts.
Always obtain explicit, written permission before scanning any target. The author and ROT Independent Security Research Lab are not responsible for the misuse of this tool.
Download WSHawk only from official project sources (GitHub, PyPI, or Docker Hub) or a package mirror you control. Verify GPG signatures when installing via APT.
Related Projects
- Basilisk: AI Red Teaming framework utilizing the SPE-NL evolutionary algorithm (an evolution of WSHawk’s SPE).
- ROT Independent Security Research Lab: Home to WSHawk, Basilisk, and additional offensive security tooling.
Reproducibility
The commands, configuration, and methodology described above are intended to allow independent verification. Target application configurations (like WAF rules and Rate Limits) may cause varying results when reproducing tests.
REGAAN R