Prompt
How to build a website WAF rule set for SQL injection and XSS
Latest observation
To build a website WAF rule set for SQL injection and XSS, the best approach is to use layered, normalized, behavior-aware rules rather than only blocking a few keywords. A good WAF rule set should:
- Normalize input first
- Detect common attack patterns
- Inspect all relevant inputs
- Log and tune aggressively
- Avoid breaking legitimate traffic
Here’s a practical way to build it.
1) Start with a baseline strategy
Use these rule categories:
A. Request normalization
Before inspection, normalize:
- URL decoding
- HTML entity decoding
- Unicode normalization
- Lowercasing where appropriate
- Remove comments and duplicate separators
- Collapse whitespace
- Handle double-encoding
This helps detect payloads like:
%27%20OR%201%3D1'UN/**/ION%2527(double-encoded)
2) SQL injection rule set
What to inspect
Check:
- Query parameters
- POST bodies
- JSON fields
- Cookies
- Headers if your app uses them
- GraphQL variables
- File names and multipart fields if relevant
High-value SQLi indicators
Look for patterns such as:
- SQL operators and logic:
or 1=1and 1=1union selectsleep(benchmark(
- Comment markers:
--#/* ... */
- String-breaking characters:
'"
- DB metadata access:
information_schema@@versionsysobjects
- Suspicious function usage:
cast(convert(substring(char(concat(
- Time-based payloads:
sleep(5)waitfor delay
- Error-based patterns:
extractvalue(updatexml(
Example SQLi detection rules
Use a mix of regex and behavioral rules.
Rule 1: Union-based injection
Match normalized input containing:
unionfollowed by optional whitespace/comments- then
select
Example regex idea:
(?i)\bunion\b(?:\s|/\*.*?\*/)+\bselect\b
Rule 2: Boolean-based injection
Match suspicious boolean tautologies:
(?i)(['"]\s*)?(or|and)\s+(\d+)\s*=\s*\3
Rule 3: Comment-based query truncation
(?i)(--\s|#|/\*)
Rule 4: Time-based SQLi
(?i)\b(sleep|benchmark|waitfor\s+delay)\s*\(
Rule 5: DB metadata enumeration
(?i)\b(information_schema|@@version|sysobjects|pg_catalog)\b
Recommended SQLi blocking approach
Instead of blocking all quotes, block only when:
- quotes appear with SQL keywords
- input contains SQL syntax outside expected fields
- there is unusual query structure for that endpoint
For example:
- On a login form,
"admin'--"is high risk - On a comment field, a single quote alone may be normal
3) XSS rule set
What to inspect
Inspect all user-controlled input rendered in:
- HTML content
- HTML attributes
- JavaScript context
- URLs
- SVG/XML
- Markdown if converted to HTML
High-value XSS indicators
Look for:
- Script tags:
<script
- Event handlers:
onerror=onload=onclick=
- JavaScript URLs:
javascript:
- HTML injection:
<img<svg<iframe<object
- Dangerous DOM sinks if reflected in client-side rendering:
document.writeinnerHTML
- Encoded variants:
<script- mixed case
- broken-up strings
Example XSS detection rules
Rule 1: Script tag
(?i)<\s*script\b
Rule 2: Event handler attributes
(?i)\bon\w+\s*=
Rule 3: JavaScript URI
(?i)\bjavascript\s*:
Rule 4: Common HTML injection tags
(?i)<\s*(img|svg|iframe|object|embed|link|style|math)\b
Rule 5: Dangerous DOM scripting patterns
If the WAF inspects request content for reflected payloads:
(?i)(document\.write|innerHTML|outerHTML|eval\s*\()
Recommended XSS blocking approach
Don’t just block < and > everywhere. Instead:
- Block when those characters appear in contexts that should be plain text
- Apply context-aware output encoding in the app
- Use Content Security Policy (CSP) as a second layer
- Treat inline event handlers and script URLs as high confidence
4) Add context-aware rules
A good WAF set depends on the endpoint.
Examples
- Login/search forms: stricter SQLi rules
- Comment/profile fields: stricter XSS rules
- API JSON endpoints: inspect nested values, but avoid false positives on legitimate strings
- Admin endpoints: more aggressive blocking
- File upload endpoints: inspect filenames, MIME types, and metadata
You can assign different thresholds:
- Low-risk fields: alert only
- Medium-risk: challenge or log
- High-risk: block immediately
5) Use positive security rules where possible
For each parameter, define:
- expected type:
integer,email,slug,text,uuid - allowed length
- allowed characters
- allowed format
Examples:
userIdshould be numericpageshould be an integersortshould be one of a known setemailshould match an email regex
This is often more effective than trying to detect every malicious payload.
6) Practical WAF tuning process
Phase 1: Detection mode
- Log all matches
- Do not block yet
- Review false positives
Phase 2: Soft enforcement
- Block only high-confidence patterns
- Challenge suspicious requests
- Rate limit repeated triggers
Phase 3: Full enforcement
- Block confirmed malicious patterns
- Maintain exceptions for legitimate business cases
Monitor:
- false positive rate
- top matched rules
- top offending endpoints
- repeated attack sources
7) Combine with application-side defenses
A WAF is not enough. Also do:
- Use parameterized queries for all SQL
- Use prepared statements
- Escape output based on context
- Validate and sanitize input
- Use CSP
- Disable inline scripts where possible
- Use secure frameworks/templates that auto-escape
- Keep dependencies patched
8) Example rule structure
A simple ruleset can be organized like this:
SQLi rules
- Detect union/select patterns
- Detect boolean tautologies
- Detect comments in suspicious contexts
- Detect time-based functions
- Detect DB metadata enumeration
XSS rules
- Detect script tags
- Detect event handlers
- Detect javascript: URLs
- Detect dangerous HTML tags
- Detect encoded/broken-up tag variants
Severity tiers
- High: block
- Medium: challenge/log
- Low: log only
9) Example pseudo-policy
If normalized request contains:
- "<script" OR "javascript:" OR "onload=" OR "onerror="
=> BLOCK
If normalized request contains:
- "union select" OR "or 1=1" OR "sleep(" OR "information_schema"
=> BLOCK
If request contains:
- SQL/XSS markers but field is expected to be free text
=> LOG or CHALLENGE
10) Best practice: use existing rule sets as a base
If you’re not starting from scratch, use a mature rule engine:
- OWASP ModSecurity Core Rule Set (CRS)
- Cloud WAF managed rules from your CDN/cloud provider
Then tune:
- exclusions for known-safe fields
- custom rules for your application
- score thresholds
If you want, I can also give you:
- a ModSecurity CRS-style rule set for SQLi/XSS, or
- a Cloudflare/AWS WAF-style JSON rule example.