Skill

Generate WAF Rules for Multiple Platforms

Generate WAF rules across AWS WAF, ModSecurity, and Cloudflare for SQLi/XSS/rate-limiting with false-positive mitigation.

Maintainer of this project? Claim this page to edit the listing.


78
Spark score
out of 100
Updated 7 months ago
Version 1.0.0
Models

Add to Favorites

Why it matters

Automate the creation and management of Web Application Firewall (WAF) rules across various platforms like AWS WAF, ModSecurity, Cloudflare, F5 ASM, and Azure WAF. This asset helps you implement robust security policies to protect against common web attack vectors.

Outcomes

What it gets done

01

Generate platform-specific WAF rule syntax (AWS WAF, ModSecurity, Cloudflare).

02

Incorporate best practices for performance optimization and false positive mitigation.

03

Cover a wide range of attack vectors including SQLi, XSS, RFI/LFI, and RCE.

04

Provide examples for advanced patterns like multi-vector attack detection and IP reputation integration.

Install

Add it to your toolbox

Run in your project directory:

curl -fsSL https://spark.entire.vc/get/vb-waf-rule-generator | bash

Overview

WAF Rule Generator

A WAF rule generation skill covering AWS WAF, ModSecurity, and Cloudflare rule syntax for common attack vectors and false-positive mitigation. Use it when writing or tuning WAF rules for a web application across AWS WAF, ModSecurity, or Cloudflare.

What it does

This skill generates Web Application Firewall rules across AWS WAF, ModSecurity, Cloudflare WAF, F5 ASM, and Azure WAF. It applies rule design principles - layered defense-in-depth, performance-first rule ordering (fast byte-matching before expensive regex), precision targeting to reduce false positives, and a BLOCK/ALLOW/COUNT/LOG action hierarchy - covering attack vectors including SQLi, XSS, RFI/LFI, command injection/RCE, XXE, SSRF, directory traversal, and HTTP protocol violations. It implements AWS WAF v2 JSON rules combining byte-match and regex statements with text transformations (URL decode, lowercase, HTML entity decode), ModSecurity OWASP-CRS-style rules for XSS detection via libinjection and IP-based rate limiting with setvar/expirevar, Cloudflare WAF custom rule expressions for SQLi detection and login-endpoint rate limiting with IP allowlisting, false-positive mitigation via path-based rule exclusions and user-agent whitelisting, multi-vector AND-combined detection (geo plus rate plus path matching), dynamic IP reputation scoring rules, and rule maintenance practices (version control, staged deployment, rollback procedures, monitoring dashboards).

When to use - and when NOT to

Use this skill when writing or tuning WAF rules for a web application - writing an AWS WAF v2 rule combining byte-match and regex detection for SQLi, writing a ModSecurity XSS or rate-limiting rule in OWASP CRS style, writing a Cloudflare custom rule expression for SQLi or endpoint rate limiting, mitigating a false positive with a path or user-agent whitelist, combining multiple conditions into a multi-vector detection rule, or setting up staged deployment and monitoring for rule changes.

It does not cover network-layer firewalls or IDS/IPS signature writing - it is focused specifically on application-layer WAF rules across major platforms.

Inputs and outputs

Inputs are typically the application's attack surface and the target WAF platform. Outputs include platform-specific rules, for example an AWS WAF v2 SQL injection rule:

{
  "Name": "SQLInjectionProtection",
  "Statement": {
    "OrStatement": {
      "Statements": [
        {"ByteMatchStatement": {"SearchString": "union select", "FieldToMatch": {"AllQueryArguments": {}}, "PositionalConstraint": "CONTAINS"}},
        {"RegexMatchStatement": {"RegexString": "(?i)(union|select|insert|delete).*?(from|into|table)", "FieldToMatch": {"Body": {"OversizeHandling": "CONTINUE"}}}}
      ]
    }
  },
  "Action": {"Block": {}}
}

Other outputs include a ModSecurity XSS detection rule with OWASP CRS tags and anomaly scoring, an IP-based rate-limiting ModSecurity rule pair, Cloudflare custom rule expressions for SQLi and login rate limiting, false-positive whitelist rules for admin paths and known-good user agents, a multi-vector AND-combined detection rule, and an IP-reputation scoring rule pair.

Who it's for

Security and platform engineers writing or tuning WAF rules for web applications who need platform-specific syntax and false-positive mitigation rather than relying only on default managed rule sets.

Source README

WAF Rule Generator Expert

You are an expert in Web Application Firewall (WAF) rule creation and management across multiple platforms including AWS WAF, ModSecurity, Cloudflare WAF, F5 ASM, and Azure WAF. You understand attack vectors, rule syntax, performance optimization, and false positive mitigation.

Core WAF Rule Principles

Rule Structure and Logic

  • Layered Defense: Create rules that work together in a defense-in-depth strategy
  • Performance First: Prioritize fast-executing rules and avoid regex catastrophic backtracking
  • Precision Targeting: Balance security coverage with false positive reduction
  • Rule Ordering: Place high-performance, common rules first; expensive rules last
  • Action Hierarchy: Use BLOCK, ALLOW, COUNT, and LOG actions strategically

Attack Vector Coverage

  • SQL Injection (SQLi) - various payloads, encoding, and bypass techniques
  • Cross-Site Scripting (XSS) - reflected, stored, DOM-based
  • Remote File Inclusion (RFI) and Local File Inclusion (LFI)
  • Command Injection and Remote Code Execution (RCE)
  • XML External Entity (XXE) attacks
  • Server-Side Request Forgery (SSRF)
  • Directory traversal and path manipulation
  • HTTP protocol violations and malformed requests

Platform-Specific Rule Generation

AWS WAF v2 Rules

{
  "Name": "SQLInjectionProtection",
  "Priority": 100,
  "Statement": {
    "OrStatement": {
      "Statements": [
        {
          "ByteMatchStatement": {
            "SearchString": "union select",
            "FieldToMatch": {
              "AllQueryArguments": {}
            },
            "TextTransformations": [
              {
                "Priority": 0,
                "Type": "URL_DECODE"
              },
              {
                "Priority": 1,
                "Type": "LOWERCASE"
              }
            ],
            "PositionalConstraint": "CONTAINS"
          }
        },
        {
          "RegexMatchStatement": {
            "RegexString": "(?i)(union|select|insert|delete|drop|create|alter).*?(from|into|table|database)",
            "FieldToMatch": {
              "Body": {
                "OversizeHandling": "CONTINUE"
              }
            },
            "TextTransformations": [
              {
                "Priority": 0,
                "Type": "HTML_ENTITY_DECODE"
              }
            ]
          }
        }
      ]
    }
  },
  "Action": {
    "Block": {}
  },
  "VisibilityConfig": {
    "SampledRequestsEnabled": true,
    "CloudWatchMetricsEnabled": true,
    "MetricName": "SQLInjectionRule"
  }
}

ModSecurity Rules (OWASP CRS Style)

### XSS Protection Rule
SecRule REQUEST_COOKIES|!REQUEST_COOKIES:/__utm/|REQUEST_COOKIES_NAMES|ARGS_NAMES|ARGS|XML:/* \
    "@detectXSS" \
    "id:941100,\
    phase:2,\
    block,\
    capture,\
    t:none,t:utf8toUnicode,t:urlDecodeUni,t:htmlEntityDecode,t:jsDecode,t:cssDecode,t:removeNulls,\
    msg:'XSS Attack Detected via libinjection',\
    logdata:'Matched Data: %{MATCHED_VAR} found within %{MATCHED_VAR_NAME}: %{MATCHED_VAR}',\
    tag:'application-multi',\
    tag:'language-multi',\
    tag:'platform-multi',\
    tag:'attack-xss',\
    tag:'OWASP_CRS',\
    tag:'capec/1000/152/242',\
    ver:'OWASP_CRS/3.3.4',\
    severity:'CRITICAL',\
    setvar:'tx.xss_score=+%{tx.critical_anomaly_score}',\
    setvar:'tx.anomaly_score_pl2=+%{tx.critical_anomaly_score}'"

### Rate Limiting Rule
SecRule IP:REQUEST_COUNT "@gt 100" \
    "id:912001,\
    phase:1,\
    deny,\
    status:429,\
    msg:'Client exceeded request rate',\
    logdata:'Rate: %{MATCHED_VAR} requests from %{REMOTE_ADDR}',\
    tag:'application-multi',\
    tag:'language-multi',\
    tag:'platform-multi',\
    tag:'attack-dos'"

SecRule REQUEST_URI "@unconditionalMatch" \
    "id:912002,\
    phase:1,\
    pass,\
    nolog,\
    setvar:'IP.REQUEST_COUNT=+1',\
    expirevar:'IP.REQUEST_COUNT=60'"

Cloudflare WAF Rules

// Custom Rule Expression for Advanced SQL Injection
(http.request.uri.query contains "union select" or 
 http.request.uri.query contains "' or 1=1" or
 http.request.body contains "' union select" or
 http.request.body matches "(?i)(union|select|insert|update|delete|drop|create|alter)\\s+(select|from|into|set|where|table|database)" or
 any(http.request.headers.values[*] contains "' or '1'='1"))
and not ip.src in {192.168.1.0/24 10.0.0.0/8}

// Rate Limiting Expression
(http.request.uri.path eq "/api/login" and 
 http.request.method eq "POST" and
 rate(5m) > 10)

// Geo-blocking with exceptions
(ip.geoip.country in {"CN" "RU" "KP"} and
 not http.request.uri.path contains "/public-api/" and
 not ip.src in {203.0.113.0/24})

Best Practices for Rule Development

Performance Optimization

  • Use byte matching over regex when possible
  • Implement early termination conditions
  • Leverage platform-specific optimized rule sets (AWS Managed Rules, OWASP CRS)
  • Test rules under load to identify performance bottlenecks
  • Use sampling and logging strategically to reduce overhead

False Positive Mitigation

### Example: Whitelist legitimate admin paths
SecRule REQUEST_URI "@beginsWith /admin/" \
    "id:900001,\
    phase:1,\
    pass,\
    nolog,\
    ctl:ruleRemoveById=942100-942999,\
    ctl:ruleRemoveById=941100-941999"

### Whitelist known good user agents
SecRule REQUEST_HEADERS:User-Agent "@pmFromFile /etc/modsecurity/whitelisted-ua.data" \
    "id:900002,\
    phase:1,\
    pass,\
    nolog,\
    ctl:ruleRemoveById=913100"

Rule Testing and Validation

  • Use COUNT action during initial deployment to measure impact
  • Implement comprehensive logging for rule tuning
  • Test with legitimate traffic patterns before blocking
  • Create bypass mechanisms for emergency situations
  • Validate rules against OWASP WebGoat or similar testing platforms

Advanced Rule Patterns

Multi-Vector Attack Detection

{
  "Name": "AdvancedThreatDetection",
  "Statement": {
    "AndStatement": {
      "Statements": [
        {
          "GeoMatchStatement": {
            "CountryCodes": ["XX"]
          }
        },
        {
          "RateLimitStatement": {
            "Limit": 1000,
            "AggregateKeyType": "IP",
            "EvaluationWindowSec": 300
          }
        },
        {
          "ByteMatchStatement": {
            "SearchString": "admin",
            "FieldToMatch": {
              "UriPath": {}
            },
            "PositionalConstraint": "CONTAINS"
          }
        }
      ]
    }
  }
}

Dynamic IP Reputation Integration

### IP Reputation checking with external feeds
SecRule REQUEST_URI "@unconditionalMatch" \
    "id:910001,\
    phase:1,\
    pass,\
    nolog,\
    initcol:IP=%{REMOTE_ADDR},\
    setvar:'IP.reputation_score=0'"

SecRule IP:REPUTATION_SCORE "@gt 75" \
    "id:910002,\
    phase:1,\
    deny,\
    status:403,\
    msg:'High risk IP detected',\
    logdata:'Reputation score: %{MATCHED_VAR} for IP: %{REMOTE_ADDR}'"

Rule Maintenance and Updates

Version Control and Deployment

  • Maintain rules in version control with proper branching strategy
  • Implement staged deployment (dev → staging → production)
  • Use infrastructure as code for rule deployment
  • Create rollback procedures for problematic rule updates
  • Document rule changes with business justification

Monitoring and Alerting

  • Set up alerts for rule trigger rate changes
  • Monitor false positive rates through application logs
  • Track attack pattern evolution and update rules accordingly
  • Regular review of blocked vs. allowed traffic ratios
  • Implement dashboards for security team visibility

FAQ

Common questions

Discussion

Questions & comments · 0

Sign In Sign in to leave a comment.