Web Application Firewalls: Configuring and Tuning WAF Rules | SoniNow Blog

Limited TimeLearn More

wafweb application firewallsecurityrulesprotection

Web Application Firewalls: Configuring and Tuning WAF Rules

Published

2026-06-23

Read Time

6 mins

Web Application Firewalls: Configuring and Tuning WAF Rules

A Web Application Firewall sits between your users and your application, inspecting every request for malicious patterns. When properly configured, a WAF blocks SQL injection, XSS, path traversal, and other application-layer attacks before they reach your code. When poorly configured, it either lets attacks through or blocks legitimate traffic.

Managed vs Self-Hosted WAF

The first architectural decision is whether to use a managed WAF service (Cloudflare, AWS WAF, Azure WAF, Fastly) or a self-hosted solution (ModSecurity with OWASP CRS, NAXSI, Coraza).

Managed WAFs offload infrastructure management and provide automatic updates to rule sets. They are the right choice for most applications. Self-hosted WAFs offer complete control over rules and inspection depth, which is valuable for applications with unusual traffic patterns or compliance requirements.

# ModSecurity with OWASP Core Rule Set (self-hosted)
# Install ModSecurity Nginx connector
apt-get install libmodsecurity3 nginx-mod-modsecurity

# Configure ModSecurity
cat > /etc/nginx/modsecurity/main.conf << EOF
SecRuleEngine On
SecRequestBodyAccess On
SecResponseBodyAccess On
SecResponseBodyMimeType text/plain text/html text/xml application/json
SecDefaultAction "phase:1,pass,log,noauditlog"
Include /etc/nginx/modsecurity/coreruleset/crs-setup.conf
Include /etc/nginx/modsecurity/coreruleset/rules/*.conf
EOF

OWASP Core Rule Set Deployment

The OWASP Core Rule Set (CRS) is the most widely used WAF rule set, containing hundreds of rules organized by attack category. Deploying CRS involves selecting the appropriate paranoia level — higher levels provide stronger protection but increase false positive rates.

# CRS configuration — paranoia level tuning
# /etc/modsecurity/coreruleset/crs-setup.conf

# Start with Paranoia Level 1 for production
# Blocks obvious attacks with low false positive rate
SecAction \
  "id:900000,\
   phase:1,\
   nolog,\
   pass,\
   t:none,\
   setvar:tx.paranoia_level=1"

# Experimental detection (Paranoia Level 2)
# Adds rules for less common attack patterns
# Test in detection-only mode before enforcing
SecAction \
  "id:900001,\
   phase:1,\
   nolog,\
   pass,\
   t:none,\
   setvar:tx.paranoia_level=2"

Begin deployment in detection-only mode (SecRuleEngine DetectionOnly) for one week to collect baseline data. Review logs for blocked requests that should have been allowed, then adjust exclusions before switching to enforcement mode.

Anomaly Scoring and Thresholds

CRS uses anomaly scoring rather than single-rule blocking. Each rule violation adds a score, and the request is blocked only when the cumulative score exceeds a threshold. This reduces false positives from individual rules while maintaining strong protection.

# Anomaly score thresholds
# Inbound anomaly score limit (per request)
SecAction \
  "id:900400,\
   phase:1,\
   nolog,\
   pass,\
   t:none,\
   setvar:tx.inbound_anomaly_score_threshold=5"

# Outbound anomaly score limit (per response)
SecAction \
  "id:900410,\
   phase:1,\
   nolog,\
   pass,\
   t:none,\
   setvar:tx.outbound_anomaly_score_threshold=4"

A threshold of 5 for inbound traffic is suitable for most applications. Lower thresholds (3-4) for financial or healthcare applications. Monitor the score distribution in logs and adjust — if most legitimate requests have scores of 0-2 and most attacks score 8+, the threshold is well-positioned.

Custom Rule Creation

Managed WAFs allow custom rules for application-specific patterns. These rules augment the base rule set with knowledge of your application's expected traffic.

// AWS WAF custom rule: Block requests without User-Agent
{
  "Name": "block-no-user-agent",
  "Priority": 5,
  "Statement": {
    "NotStatement": {
      "Statement": {
        "RegexPatternSetReferenceStatement": {
          "ARN": "arn:aws:wafv2:us-east-1:...:regex/regex-set/user-agent",
          "FieldToMatch": {
            "SingleHeader": {
              "Name": "user-agent"
            }
          }
        }
      }
    }
  },
  "Action": { "Block": {} }
}
# Cloudflare WAF custom rule
name: "Block requests to admin from non-VPN IPs"
description: "Admin panel should only be accessible through VPN"
expression: |
  (http.request.uri.path contains "/admin") and
  not ip.src in {10.0.0.0/8 172.16.0.0/12 192.168.0.0/16}
action: block

False Positive Reduction

False positives — legitimate requests incorrectly blocked — are the primary operational challenge of WAF deployment. The most common causes are:

  • Body inspection of large payloads: Disable request body inspection for endpoints that handle binary data or large file uploads.
  • API endpoints with unusual payloads: Create rule exclusions for API endpoints that accept JSON payloads containing characters that trigger XSS rules.
  • Legacy clients with non-standard headers: Whitelist known legitimate clients that send unusual headers.
# Cloudflare WAF rule exclusion for API endpoints
# Skip body inspection for file upload endpoints
rulesets:
  - id: cloudflare_managed
    actions:
      - "skip"
    expression: |
      (http.request.uri.path contains "/api/upload") or
      (http.request.uri.path contains "/api/webhook")

Implement a WAF log review workflow. When a false positive is identified, create a targeted rule exclusion rather than disabling the entire rule ID. Document the rationale for each exclusion and set quarterly review reminders.

Rate Limiting and Bot Detection

Modern WAFs integrate rate limiting and bot detection alongside signature-based filtering. The combination catches both known attack patterns and novel abuse scenarios.

# Cloudflare: Super Bot Fight Mode
# Block identified bots and challenge疑似 bots
curl -X PATCH "https://api.cloudflare.com/client/v4/zones/ZONE_ID/settings/bot_management" \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  --data '{
    "enable_js": true,
    "fight_mode": true,
    "sbfm_definitely_automated": "block",
    "sbfm_verified_bots": "allow",
    "sbfm_static_resource_protection": false
  }'

Bot detection interacts closely with WAF rules. A request from a blocked bot should not also trigger WAF inspection — the bot score check should precede WAF evaluation in the request pipeline.

WAF Monitoring and Alerting

A WAF is only effective if its alerts are monitored. Configure real-time notifications for blocked traffic spikes, rule disablement events, and configuration changes.

// WAF alert handler
import { CloudWatch } from '@aws-sdk/client-cloudwatch';

async function monitorWafBlockedRequests() {
  const cloudwatch = new CloudWatch({ region: 'us-east-1' });

  // Alert if blocked requests exceed 5% of traffic in any 5-minute window
  const alarm = await cloudwatch.putMetricAlarm({
    AlarmName: 'WAF-Blocked-Traffic-Spike',
    MetricName: 'BlockedRequests',
    Namespace: 'AWS/WAFV2',
    Statistic: 'Sum',
    Period: 300,
    Threshold: 1000,
    ComparisonOperator: 'GreaterThanThreshold',
    AlarmActions: ['arn:aws:sns:us-east-1:...:ops-team'],
  });
}

Set up dashboards showing top blocked IPs, blocked rule IDs, and geographic distribution of blocked traffic. Review these weekly to identify trends and tune rules.

Testing WAF Rules

Test WAF rules against your application before enforcing them in production. Most managed WAFs support a count mode that logs what would have been blocked without actually blocking.

# AWS WAF: Test mode for rule evaluation
aws wafv2 update-rule-group \
  --name "core-rule-set" \
  --scope REGIONAL \
  --rules file://rules-test.json \
  --visibility-config SampledRequestsEnabled=true,CloudWatchMetricsEnabled=true,MetricName=test

Use tools like waf-tester or custom test suites that send benign requests (simulating normal usage) and malicious requests (OWASP benchmark payloads) to verify both protection and compatibility.

A properly tuned WAF is a critical component of application defense. Our <a href="/services/devops-server-management">devops and infrastructure services</a> include WAF deployment, tuning, and ongoing management. Contact SoniNow to configure a WAF that protects without interfering with legitimate traffic.