A Web Application Firewall (WAF) protects applications from malicious traffic and common web attacks. This guide covers WAF concepts, rules, and deployment.
Understanding WAF
What WAF Protects Against
owasp_top_10:
- "A01:2021 - Broken Access Control"
- "A02:2021 - Cryptographic Failures"
- "A03:2021 - Injection"
- "A04:2021 - Insecure Design"
- "A05:2021 - Security Misconfiguration"
- "A06:2021 - Vulnerable Components"
- "A07:2021 - Auth Failures"
- "A08:2021 - Data Integrity Failures"
- "A09:2021 - Logging Failures"
- "A10:2021 - SSRF"
common_attacks:
- "SQL Injection"
- "Cross-Site Scripting (XSS)"
- "Cross-Site Request Forgery (CSRF)"
- "Path Traversal"
- "Command Injection"
- "LDAP Injection"
- "XML External Entity (XXE)"
WAF Deployment Modes
deployment_modes:
- name: "Block Mode"
description: "Threats are blocked completely"
- name: "Monitor Mode"
description: "Threats are logged but allowed"
- name: "Learning Mode"
description: "Traffic patterns are analyzed to create rules"
WAF Rules
Rule Types
rule_types:
- name: "Signature-based"
description: "Match known attack patterns"
- name: "Behavioral"
description: "Detect anomalies in traffic patterns"
- name: "Rate-based"
description: "Limit request frequency"
- name: "Geo-blocking"
description: "Block traffic from specific regions"
- name: "IP Reputation"
description: "Block known malicious IPs"
Custom Rules Example
# AWS WAF custom rules
rules:
- name: "Block SQL Injection"
statement:
sqliMatchStatement:
fieldToMatch:
body:
oversizeHandling: MATCH
samplingPriority: NORMAL
action:
block:
visibilityConfig:
sampledRequestsEnabled: true
- name: "Rate Limit"
statement:
rateBasedStatement:
limit: 1000
aggregateKeyType: IP
action:
block:
- name: "Block XSS"
statement:
xssMatchStatement:
fieldToMatch:
queryString: {}
samplingPriority: NORMAL
action:
block:
ModSecurity Rules
# ModSecurity rules
# Block SQL Injection
SecRule REQUEST_URI|ARGS "@rx (?i)(\b(SELECT|INSERT|UPDATE|DELETE|DROP|UNION|ALTER|CREATE|TRUNCATE)\b)" \
"id:1001,phase:1,deny,status:403,msg:'SQL Injection Attempt'"
# Block XSS
SecRule REQUEST_URI|ARGS|REQUEST_HEADERS "@rx (?i)<script[^>]*>.*?</script>" \
"id:1002,phase:1,deny,status:403,msg:'XSS Attempt'"
# Block path traversal
SecRule REQUEST_URI "@rx \.\.(\/|\\)" \
"id:1003,phase:1,deny,status:403,msg:'Path Traversal Attempt'"
# Rate limiting
SecRuleEngine On
SecRequestBodyAccess On
SecPcreMatchLimit 1000
SecPcreMatchLimitRecursion 1000
Implementation Examples
Cloudflare WAF
# Cloudflare WAF via API
import requests
class CloudflareWAF:
def __init__(self, api_token, zone_id):
self.base_url = "https://api.cloudflare.com/client/v4"
self.headers = {
"Authorization": f"Bearer {api_token}",
"Content-Type": "application/json"
}
self.zone_id = zone_id
def create_firewall_rule(self, name, action, expression):
"""Create WAF rule"""
url = f"{self.base_url}/zones/{self.zone_id}/firewall/rules"
data = {
"filter": {
"expression": expression
},
"action": action,
"priority": 1
}
response = requests.post(url, json=data, headers=self.headers)
return response.json()
def block_ip(self, ip):
"""Block specific IP"""
return self.create_firewall_rule(
name=f"Block {ip}",
action="block",
expression=f"ip.src == {ip}"
)
def allow_bot(self):
"""Allow known bots"""
return self.create_firewall_rule(
name="Allow Good Bots",
action="allow",
expression="cf.client.bot"
)
AWS WAF
# AWS WAF via boto3
import boto3
class AWSWAF:
def __init__(self, region):
self.client = boto3.client('wafv2', region_name=region)
self.scope = "CLOUDFRONT" # or REGIONAL
def create_ip_set(self, name, addresses):
"""Create IP set for blocking/allowing"""
response = self.client.create_ip_set(
Name=name,
Scope=self.scope,
Description=f"IP set for {name}",
Addresses=addresses,
Tags=[{'Key': 'Environment', 'Value': 'Production'}]
)
return response
def create_rule(self, name, statement, action):
"""Create WAF rule"""
response = self.client.create_rule(
Name=name,
Scope=self.scope,
Rules=[{
'Name': name,
'Priority': 0,
'Statement': statement,
'Action': {'Block': {}},
'VisibilityConfig': {
'SampledRequestsEnabled': True,
'CloudWatchMetricsEnabled': True,
'MetricName': name
}
}]
)
return response
WAF Best Practices
# WAF best practices
deployment:
- "Start in learning/monitor mode"
- "Tune rules to reduce false positives"
- "Use managed rule groups when possible"
- "Keep rules updated"
monitoring:
- "Review blocked requests regularly"
- "Set up alerts for spikes"
- "Track false positive rates"
- "Monitor performance impact"
rules:
- "Start with OWASP Core Rules"
- "Add custom rules for specific needs"
- "Review and update regularly"
- "Test rules before deploying"
Conclusion
WAF is essential for web application security:
- Deploy in stages: Start with monitoring, then block
- Tune continuously: Reduce false positives
- Layer with other security: WAF is one layer of defense
Use managed rules from Cloudflare, AWS, Azure for best protection.
Comments