Cloudflare WAF Security Rules

Web applications face an ever-increasing array of security threats, from sophisticated SQL injection attacks to devastating distributed denial-of-service (DDoS) campaigns. Organizations require robust defense mechanisms that can adapt to emerging threats while maintaining performance and usability. Enter Cloudflare’s Web Application Firewall (WAF), a cloud-based security solution that processes over 46 million HTTP requests per second[1].

Understanding how to effectively configure and optimize Cloudflare WAF security rules can mean the difference between a secure application and a compromised one. This comprehensive guide explores the architecture, configuration, and best practices for leveraging Cloudflare’s WAF to protect modern web applications.

Understanding Web Application Firewalls

A Web Application Firewall operates at the application layer (Layer 7) of the OSI model, examining HTTP/HTTPS traffic to identify and block malicious requests before they reach your origin server. Unlike traditional network firewalls that operate at lower layers, WAFs understand web protocols and can detect application-specific attacks[2].

Cloudflare’s WAF provides several key advantages:

  • Edge-based protection - Traffic is filtered at Cloudflare’s global network before reaching your infrastructure
  • Managed rule sets - Pre-configured rules maintained by security experts
  • Custom rule engine - Flexible rule creation using Cloudflare’s expression language
  • Real-time updates - Rapid deployment of rules to counter emerging threats
  • Performance optimization - Efficient rule matching with minimal latency impact

Web application security and firewall protection
Cloud-based web application firewall architecture

Cloudflare WAF Architecture

Cloudflare’s WAF operates as part of its edge computing platform, processing requests at over 300 data centers globally. When a request arrives at Cloudflare’s network, it passes through multiple security layers:

  1. DDoS mitigation - Volumetric attack filtering
  2. IP reputation - Known malicious IP blocking
  3. Bot management - Automated traffic analysis
  4. WAF rules - Application-level threat detection
  5. Rate limiting - Request frequency control
  6. Custom rules - Organization-specific logic

This layered approach ensures that different types of threats are handled by specialized systems optimized for that specific threat category.

Managed Rules: OWASP Core Ruleset

Cloudflare WAF’s Managed Rules provide protection against the OWASP Top 10 vulnerabilities and other common web application attacks. The OWASP ModSecurity Core Rule Set (CRS) serves as the foundation, offering comprehensive coverage of known attack patterns[3].

Key Managed Rule Categories

The managed rules are organized into logical categories:

SQL Injection Protection

  • Detects attempts to inject malicious SQL code
  • Blocks common SQL injection patterns
  • Validates input against SQL syntax patterns

Cross-Site Scripting (XSS) Prevention

  • Identifies JavaScript injection attempts
  • Blocks malicious script tags and event handlers
  • Sanitizes user input containing HTML/JavaScript

Command Injection Detection

  • Prevents OS command execution attempts
  • Blocks shell metacharacters in user input
  • Validates file path traversal attempts

Local File Inclusion (LFI) Protection

  • Detects attempts to access unauthorized files
  • Blocks directory traversal patterns
  • Validates file path parameters

Configuring Managed Rules

Managed rules can be configured through the Cloudflare dashboard or API:

# Example: Enable OWASP ruleset via API
curl -X PUT "https://api.cloudflare.com/client/v4/zones/{zone_id}/rulesets/phases/http_request_firewall_managed/entrypoint" \
  -H "Authorization: Bearer {api_token}" \
  -H "Content-Type: application/json" \
  --data '{
    "rules": [
      {
        "action": "execute",
        "action_parameters": {
          "id": "efb7b8c949ac4650a09736fc376e9aee",
          "overrides": {
            "enabled": true,
            "sensitivity_level": "high"
          }
        },
        "expression": "true",
        "description": "Enable OWASP Core Ruleset"
      }
    ]
  }'

Sensitivity Levels

Managed rules support different sensitivity levels that control the aggressiveness of detection:

  • Low - Fewer false positives, may miss some attacks
  • Medium - Balanced approach (default)
  • High - More aggressive detection, higher false positive rate
  • Off - Rule category disabled

Adjusting sensitivity requires careful testing to balance security and functionality. Applications with complex user input may need lower sensitivity to avoid blocking legitimate traffic.

Custom Firewall Rules

While managed rules provide broad protection, custom firewall rules enable organizations to implement application-specific security logic. Cloudflare’s rule engine uses a powerful expression language that can match on numerous request attributes.

Rule Expression Language

Custom rules use expressions to match traffic patterns. Key fields available for matching include:

# Request properties
http.request.uri.path         # URL path
http.request.uri.query        # Query string
http.request.method           # HTTP method (GET, POST, etc.)
http.request.headers          # Request headers
http.request.body             # Request body content

# Client properties
ip.src                        # Client IP address
ip.geoip.country              # Client country code
cf.threat_score              # Cloudflare threat score (0-100)
cf.bot_management.score      # Bot detection score

# SSL/TLS properties
ssl                          # SSL enabled
cf.tls_version              # TLS version
cf.tls_cipher               # Cipher suite

Example Custom Rules

Block Access from Specific Countries

(ip.geoip.country in {"CN" "RU" "KP"}) and not (ip.src in {1.2.3.4})

This rule blocks traffic from specific countries while allowing a trusted IP address.

Rate Limit API Endpoints

(http.request.uri.path contains "/api/") and 
(rate_limit(10, 60s)) # 10 requests per 60 seconds

Block SQL Injection Attempts in Query Parameters

(http.request.uri.query contains "union" and http.request.uri.query contains "select") or
(http.request.uri.query contains "1=1") or
(http.request.uri.query contains "drop table")

Require Strong TLS Versions

not ssl or cf.tls_version in {"TLSv1.0" "TLSv1.1"}

Protect Admin Panels

(http.request.uri.path contains "/admin" or 
 http.request.uri.path contains "/wp-admin") and
not (ip.src in {203.0.113.0/24})

This rule restricts admin panel access to a specific IP range.

Security operations center monitoring web traffic
Real-time security monitoring and threat detection

Rate Limiting Rules

Rate limiting prevents abuse by controlling how frequently clients can make requests. Cloudflare offers sophisticated rate limiting capabilities integrated with the WAF.

Basic Rate Limiting

# Example: Limit login attempts
curl -X POST "https://api.cloudflare.com/client/v4/zones/{zone_id}/rate_limits" \
  -H "Authorization: Bearer {api_token}" \
  -H "Content-Type: application/json" \
  --data '{
    "match": {
      "request": {
        "url": "https://example.com/login",
        "methods": ["POST"]
      }
    },
    "threshold": 5,
    "period": 60,
    "action": {
      "mode": "challenge",
      "timeout": 3600
    }
  }'

This configuration challenges users who make more than 5 POST requests to /login within 60 seconds.

Advanced Rate Limiting Strategies

Tiered Rate Limits

Different limits for different user types:

# API users: 1000 req/min
(http.request.uri.path contains "/api/") and 
(http.request.headers["Authorization"][0] exists)
→ 1000 requests per 60s

# Anonymous users: 100 req/min
(http.request.uri.path contains "/api/") and 
not (http.request.headers["Authorization"][0] exists)
→ 100 requests per 60s

Geographic Rate Limiting

Apply different limits based on geographic location:

# Strict limits for high-risk countries
(ip.geoip.country in {"XX" "YY"})
→ 50 requests per 60s

# Normal limits for other regions
→ 500 requests per 60s

Bot Management Integration

Cloudflare’s Bot Management system integrates with WAF rules to provide granular control over automated traffic. The system assigns bot scores (0-100) to each request, where lower scores indicate likely bot traffic[4].

Bot Score-Based Rules

# Block obvious bots
(cf.bot_management.score < 30)
→ Action: Block

# Challenge suspicious traffic
(cf.bot_management.score >= 30 and cf.bot_management.score < 50)
→ Action: JS Challenge

# Allow likely humans
(cf.bot_management.score >= 50)
→ Action: Allow

Verified Bots

Cloudflare maintains a list of verified good bots (Google, Bing, etc.). Rules can explicitly allow these:

cf.bot_management.verified_bot
→ Action: Allow

Security Level and Challenge Pages

Cloudflare provides Security Level settings that determine how aggressively it challenges visitors:

  • Essentially Off - Only challenge the most threatening visitors
  • Low - Challenge visitors with a threat score above 50
  • Medium - Challenge visitors with a threat score above 25 (default)
  • High - Challenge visitors with a threat score above 0
  • I’m Under Attack - Present JavaScript challenge to all visitors

Custom Challenge Pages

Organizations can customize challenge pages to match branding:

<!DOCTYPE html>
<html>
<head>
    <title>Security Check</title>
    <style>
        body { font-family: Arial, sans-serif; text-align: center; padding: 50px; }
        .logo { max-width: 200px; margin: 20px auto; }
    </style>
</head>
<body>
    <img class="logo" src="/logo.png" alt="Company Logo">
    <h1>Security Verification</h1>
    <p>Please complete this check to verify you're human.</p>
    <div id="cf-challenge-running"></div>
</body>
</html>

Rule Ordering and Priority

Rule evaluation order significantly impacts security effectiveness and performance. Cloudflare processes rules in a specific sequence:

  1. IP Access Rules - Allow/block by IP first
  2. Firewall Rules - Custom rules in configured order
  3. Managed Rules - OWASP and other managed rulesets
  4. Rate Limiting - Request frequency controls

Optimizing Rule Order

Place the most specific, high-impact rules first:

1. Allow trusted IPs (office, monitoring services)
2. Block known malicious IPs/countries
3. Rate limit sensitive endpoints
4. Application-specific protection rules
5. General managed rules

Monitoring and Analytics

Effective WAF configuration requires continuous monitoring and tuning. Cloudflare provides comprehensive analytics for security events.

Key Metrics to Monitor

Request Statistics

  • Total requests processed
  • Blocked requests by rule
  • Challenge presentations
  • False positive rates

Attack Patterns

  • Attack types (SQL injection, XSS, etc.)
  • Geographic distribution
  • Time-based patterns
  • User agent analysis

Firewall Events Log

The firewall events log provides detailed information about each security event:

# Fetch firewall events via API
curl -X GET "https://api.cloudflare.com/client/v4/zones/{zone_id}/firewall/events?per_page=50" \
  -H "Authorization: Bearer {api_token}" \
  -H "Content-Type: application/json"

Event data includes:

  • Timestamp and action taken
  • Rule that matched
  • Request details (IP, path, headers)
  • Threat indicators

Performance Optimization

While security is paramount, WAF rules must not significantly impact application performance. Best practices for optimization include:

Rule Efficiency

  • Use specific matches instead of regex where possible
  • Combine related conditions into single rules
  • Avoid overly complex expressions
  • Leverage caching for repeated checks

Expression Optimization

# Inefficient - multiple separate rules
Rule 1: (http.request.uri.path eq "/api/users")
Rule 2: (http.request.uri.path eq "/api/posts")
Rule 3: (http.request.uri.path eq "/api/comments")

# Efficient - single rule with OR conditions
(http.request.uri.path in {"/api/users" "/api/posts" "/api/comments"})

Testing and Validation

Before deploying rules to production:

  1. Test in Log mode - Rules don’t block, only log matches
  2. Analyze false positives - Review blocked legitimate requests
  3. Gradual rollout - Start with Challenge action, then Block
  4. A/B testing - Test rules on subset of traffic

Advanced WAF Techniques

Skip Rules for Trusted Traffic

Improve performance by skipping WAF evaluation for known good traffic:

# Skip WAF for authenticated API clients
(http.request.headers["X-API-Key"][0] in {"trusted_key_1" "trusted_key_2"})
→ Action: Skip - WAF Rules

Dynamic Response Actions

Use Page Rules to deliver custom responses:

# Custom error page for blocked requests
(cf.waf.action eq "block")
→ Return: Custom HTML with 403 status

Threat Intelligence Integration

Cloudflare constantly updates threat intelligence. Custom rules can leverage this:

# Block IPs with high threat scores
(cf.threat_score > 50)
→ Action: Challenge

# Block requests from Tor exit nodes
(cf.client.bot or ip.src in $tor_exit_nodes)
→ Action: Block

Compliance and Regulatory Considerations

WAF configurations often need to address regulatory requirements:

PCI DSS Compliance

  • Requirement 6.6 mandates WAF or code review
  • Log all security events
  • Regular rule updates and testing

GDPR Considerations

  • Log retention policies
  • Privacy-preserving logging
  • Right to access logs about specific users

HIPAA Requirements

  • Audit trail maintenance
  • Access controls to sensitive data
  • Encryption of logs

Conclusion

Cloudflare’s Web Application Firewall provides a powerful, flexible platform for protecting web applications against a wide array of threats. Success requires understanding not just individual features, but how they work together as part of a comprehensive security strategy.

Effective WAF configuration is an iterative process. Start with managed rules and basic custom rules, then refine based on your application’s specific needs and observed attack patterns. Regular monitoring, testing, and tuning ensure your WAF configuration evolves with your application and the threat landscape.

The key to successful WAF deployment lies in balancing security with usability. Overly aggressive rules create friction for legitimate users, while permissive configurations leave applications vulnerable. By following best practices, leveraging Cloudflare’s extensive analytics, and staying informed about emerging threats, organizations can achieve robust protection without compromising user experience.

References

[1] Cloudflare. (2024). Cloudflare Security Statistics. Available at: https://www.cloudflare.com/learning/security/ (Accessed: November 2025)

[2] OWASP Foundation. (2024). Web Application Firewall Guide. Available at: https://owasp.org/www-community/Web_Application_Firewall (Accessed: November 2025)

[3] OWASP Foundation. (2024). ModSecurity Core Rule Set. Available at: https://coreruleset.org/ (Accessed: November 2025)

[4] Cloudflare. (2024). Bot Management Documentation. Available at: https://developers.cloudflare.com/bots/ (Accessed: November 2025)

[5] PCI Security Standards Council. (2024). Payment Card Industry Data Security Standard. Available at: https://www.pcisecuritystandards.org/ (Accessed: November 2025)

Thank you for reading! If you have any feedback or comments, please send them to [email protected].