Knowledge Base Hub

Browse through our helpful how-to guides to get the fastest solutions to your technical issues.

Home  >  Firewall  >  How to Block SQL Injection Using a WAF | Setup Guide

How to Block SQL Injection Using a WAF | Setup Guide

 8 min

SQL Injection (SQLi) is one of the oldest and most dangerous vulnerabilities in web applications. This happens when an attacker injects malicious SQL code into an input field (such as a login box or search bar), which prompts the back-end database to execute commands it wasn’t designed to execute.

A Web Application Firewall (WAF) sits between your users and your web application, examining incoming HTTP/HTTPS traffic. It can detect and block SQL injection attacks before they reach your application/database.

This article describes what SQL injection is, how a WAF prevents it, and guides you through the configuration of SQLi protection step by step.

Useful Read: A Complete Guide to SQL Injection

What is SQL Injection?

SQL injection is when a user-supplied input is concatenated into a SQL query without proper validation or sanitization. 

Example of a vulnerable query:

SELECT * FROM users WHERE username = '$username' AND password = '$password';

Malicious input:

username = admin' --

Resulting query:

SELECT * FROM users WHERE username = 'admin' -- 'AND password = '';

Here, — starts a SQL comment, causing the database to ignore the rest of the query. As a result, the password check is bypassed, potentially allowing the attacker to log in as the admin user without knowing the password.

Popular SQLi attack types:

  1. Classic/In-band SQLi: The attacker can directly see the results (e.g., error messages, page content).
  2. Blind SQLi: The attacker infers data from true/false or timing responses.
  3. Union-based SQLi: Combination of results from another table using the UNION operator.
  4. Out-of-band SQLi: Data is leaked via DNS or HTTP requests.

What is a WAF and How Does it Prevent SQLi?

A WAF operates at Layer 7, the application layer. It looks at each request that comes in—headers, cookies, query strings, form data, and JSON bodies and matches it to a set of rules or patterns.

Useful Read: What Is A Web Application Firewall?

For SQL injection specifically, a WAF utilizes the following:

  1. Signature-based detection: Matches known SQLi patterns (e.g., UNION SELECT, OR 1=1, –, xp_cmdshell).
  2. Anomaly scoring: Assigns risk scores to suspicious tokens (e.g., too many quotes, SQL keywords) and blocks requests if a threshold is exceeded.
  3. Regular expressions / grammar-based parsing: Some modern WAFs parse the input as if it were SQL to more accurately detect injection attempts than simple regex.
  4. Rate-based and behavioral rules: Repeated probing attempts typical of automated SQLi scanners, such as sqlmap, are flagged.

WAF can do the following when a request matches a rule:

  • 403 Forbidden (Block the request)
  • Log it for review.
  • Challenge the request (e.g., CAPTCHA).
  • Rate limit source IP

Before You Start: Prerequisites

Before you start to block SQL injection using WAF, ensure you have the following setup ready. 

  • Access to the WAF admin interface (cloud or self-hosted)
  • A staging/test environment (preferred before applying rules to production)
  • Understanding of your application’s traffic patterns (to prevent false positives)
  • Your list of public-facing endpoints and forms that take user input

Enable SQL Injection Protection: A Step-by-Step Guide

Here are the configuration steps you can follow for the most popular WAF platforms. Choose the one that fits your environment.

Option A: AWS WAF

  • To get started, open the AWS WAF & Shield Console.
  • Create a new Web ACL or use an existing one, and associate it with your resource (CloudFront, ALB, API Gateway, or AppSync).
  • Under Rules, choose Add rules > Add managed rule groups.
  • Enable the AWS Managed Rules – SQL Database (SQLi) rule group (AWSManagedRulesSQLiRuleSet).
  • Change the rule group action to Block.
  • (Optional) You can use the SqliMatchStatement to define a custom rule to inspect specific fields, such as the body, query string, or custom headers.
  • Save and deploy the web ACL.

Before moving to Block mode, review CloudWatch metrics and sampled requests over a few days in Count mode to catch false positives.

Option B: Cloudflare WAF (Web Application Firewall)

  • Log in to the Cloudflare dashboard and choose your domain.

Security -> WAF -> Managed Rules

  • Activate the Cloudflare Managed Ruleset. It comes with rules for detecting SQL injection.
  • Set the SQLi-related rules’ sensitivity/action to Block (Cloudflare allows per-rule action overrides).
  • (Optional) Create a Custom Rule:
    • Field: URI query string, body, or specific form field
    • Operator: Use or include the built-in SQLi detection expression:
    • (cf.waf.score.sqli < 30)
    • Action: Block
  • Deploy first in log mode, review the Security Events dashboard, then switch to block.

Testing Your WAF Rules

Once you configure your WAF protection, testing is essential. It ensures all the steps are correctly executed to protect you.

  • Safe payloads to use only in testing environments:
' OR '1'='1
1; DROP TABLE users--
' UNION SELECT null, null--
admin'--
  • How to test:
  1. Submit the payloads through login forms, search boxes, or URL parameters in a non-operational environment. 
  2. Ensure that your WAF returns a 403 Forbidden (or whatever block response you have configured) instead of a normal application response. 
  3. Check your WAF logs to see if SQLI was flagged.
  4. Optionally, you can test using an automated scanner like sqlmap:
sqlmap -u "https://staging.example.com/login" --data="username=test&password=test" --batch

The WAF should prevent or exert a great deal of control over sqlmap’s probing behavior. Never conduct these tests on production systems or systems not owned by you.

Best Practices to Block SQL Injection

A Web Application Firewall (WAF) is most effective when used as part of a layered security strategy rather than as the only line of defense. Follow these recommended practices to strengthen your protection against SQL injection attacks:

  • WAF must function as a supplementary measure and not as the sole protective mechanism. Ensure that when creating code, prepared statements or parameterized queries and ORM are in place so the WAF simply adds to them.
  • Always start operating in detection/logging mode and only after that transition to blocking mode to ensure that legitimate traffic remains unaffected (avoiding false positives).
  • Gradually adjust the paranoia/sensitivity degrees. High sensitivity is likely to catch more attacks, but it will also increase false positives.
  • If you have a field where SQL-like text is legitimate, whitelist specific patterns using rule exceptions instead of disabling SQL injection protection entirely.
  • Keep managed rule sets updated regularly, as SQL injection techniques continue to evolve and security vendors frequently release improved protection rules.
  • Monitor WAF logs continuously because repeated SQL injection attempts from the same IP address may indicate a larger attack campaign.
  • Apply the principle of least privilege to database accounts so that even if an attack succeeds, its impact remains limited.
For our Knowledge Base visitors only
Get 10% OFF on Hosting
Special Offer!
30
MINS
59
SECS
Claim the discount before it’s too late. Use the coupon code:
STORYSAVER
Note: Copy the coupon code and apply it on checkout.