Skip to content
SQL injection Write-up Advanced

Blind SQL Injection Behind a WAF: Bypassing Filters with a NOT IN

A numeric parameter was inserted into a SQL query without quoting or a prepared statement, and a WAF blocked the usual injection payloads. The author found a subquery construction the WAF did not match, turning the flaw into a timing oracle that allowed data to be extracted character by character.

Guilhermegh Follow

Published on medium.com

Sql Injection

Guilhermegh, on medium.com

The full write-up lives on its author's site

It belongs to its author, so we link to it rather than copy it. The other two tabs are our own rewrites, checked against it.

Written with AI from the full original report and checked against it passage by passage; anything it could not back up was removed or toned down. The original is the record. 5 min read.

Context

During a bug bounty programme I found a numeric parameter reflected into a SQL query without quotes and without a prepared statement. A WAF in front of the application blocked the classic payloads: UNION SELECT, AND/OR <n>, SLEEP(), and comments. The bypass that worked was a subquery of the form NOT IN (SELECT CASE WHEN <condition> THEN SLEEP(...) END), a construction the WAF does not sign. It turned the flaw into a stable temporal oracle and allowed extracting the whole database character by character through binary search over ASCII(SUBSTR(...)).

The affected route is /catalog/items, and the parameter is id. The report does not name the product or the programme.

Setup

The report describes no accounts, roles, tools or versions. The only precondition it states is the shape of the sink: a numeric value interpolated directly into the query, with no quotes and no prepared statement, behind a WAF.

Finding it

The id parameter of /catalog/items was interpolated directly into the query. The classic signals were all there:

  • ?id=444' returned a SQL error reflected on the page, with the syntax error near the end of the value. The error is returned to the user.
  • ?id= followed by a backtick around 444 produced Unknown column '444', which shows the value enters without quotes and becomes an identifier.
  • ?id=444%1 (MOD) returned an empty page, while ?id=444 DIV 1 returned results again, which shows the expression is evaluated in an executable numeric context.

The report shows these probes in a block that uses cat rather than id:

Text
?cat=444' -> SQLSTATE syntax error (refletido)
?cat=`444` -> Unknown column ‘444’ in ‘WHERE’
?cat=444%1 -> 0 resultados (444 MOD 1 = 0)
?cat=444 DIV 1 -> resultados (expressao avaliada)
?cat=444,445 -> sintaxe de lista aceita (multi-valor)

So a single quote breaks the syntax, a backtick turns the value into a column identifier, MOD evaluates to zero and empties the result set, DIV evaluates and returns results, and a comma-separated list is accepted as list syntax.

Exploitation

Step 1: map the WAF

Every attempt at classic extraction returned 403:

Payload Response
444' UNION SELECT 1 — - 403
444 AND 1=1 / OR 1=1 403
SLEEP(3), IF(..), BENCHMARK(..), GET_LOCK(..) 403
EXTRACTVALUE(..), UPDATEXML(..) 403
—, /*, )#, &&, || 403
subquery (SELECT after an operator or a comma 403
version(), database() outside a string 403

One curiosity helped map the filter: the same keywords inside SQL strings passed. The filter tokenises and ignores strings, so the game became finding a construction where the payload does not fall into any signed pattern.

Step 2: find the construction the WAF does not sign

While testing subqueries, one specific construction was not blocked:

Text
?id=444 NOT IN (SELECT CASE WHEN <cond> THEN SLEEP(0.0001) END)

Inside the CASE WHEN, the filter let through what it blocked outside: SLEEP(), ASCII(), SUBSTR(), LENGTH(), and subqueries against information_schema, all of them.

The oracle became dichotomous and stable:

Condition Response time
true ~5 s
false ~0.3 s

The SLEEP does not run once. The subquery is re-evaluated once per row scanned by the outer query, so even SLEEP(0.0001) becomes about 5 s, an amplification of roughly 29,000 times. That suits the attacker: tiny sleeps still produce a strong signal.

Step 3: extract data with binary search

With the oracle in place, any SQL expression becomes an extractable string:

  1. Length: LENGTH(<expr>) > N (binary search).
  2. Each character: ASCII(SUBSTR(<expr>, <pos>, 1)) < <mid> (binary search over 33 to 126).
  3. Databases: (SELECT schema_name FROM information_schema.schemata ORDER BY schema_name LIMIT n,1) compared by equality.

Typical cost: about 7 requests per character, averaging about 2 to 3 s each.

The expressions and example results shown in the report:

Text
Expressão: @@version -> “10.x.x-****-log” (exemplo)
Expressão: database() -> “wp_<redacted>” (exemplo)
Expressão: @@hostname -> host interno (IP privado)
Expressão: current_user -> user@host (privilegios limitados a 2 schemas)
Databases visiveis -> information_schema, ****_<redacted>

The report lists these expressions with example results: the version string, the current database name, the internal hostname (a private IP), and the current user with its host. The database user's privileges were limited to two schemas, and the visible databases were information_schema and one other.

Root cause

The id value is concatenated into the SQL text without quotes and without a prepared statement, so the database parses it as an expression rather than as data. The WAF is a signature filter: it tokenises the request and ignores string contents, and it blocks the well-known keywords and operators listed above. It does not recognise the NOT IN (SELECT CASE WHEN ... THEN SLEEP(...) END) shape, and once the payload sits inside that shape, the keywords it would otherwise block pass through. The defences did not stop the attack because the filter matches patterns rather than enforcing parameterisation, and the application had no parameterised query behind it.

Impact

An attacker who can reach /catalog/items with a crafted id can turn the injection into a timing oracle and extract arbitrary SQL expressions character by character. In this case that covered the database version, the current database name, the internal hostname, the current user, and the list of visible schemas. The database user's privileges were limited to two schemas, which bounds what could be read with that account. The report does not describe write access, authentication bypass, or access to other systems.

Fix

The fix the finding calls for is to stop concatenating the value into the query and use a prepared statement with a bound parameter, so the value is treated as data regardless of what it contains. A WAF rule for the NOT IN (SELECT CASE WHEN ...) shape would only be a stopgap, since the filter already showed it can be bypassed by constructions it does not sign.

Variants to test

  • Numeric context without quotes: send a single quote and a backtick around the value, then MOD and DIV expressions. A positive result is a reflected syntax error, an Unknown column error for the backticked value, an empty page for MOD, and results for DIV.
  • Keyword filter that ignores strings: place a blocked keyword inside a SQL string and see whether it passes. A positive result is that the keyword inside a string passes while the same keyword outside a string returns 403.
  • Subquery after NOT IN: try NOT IN (SELECT CASE WHEN <cond> THEN SLEEP(<small>) END) with a true and a false condition. A positive result is a clear timing difference, here about 5 s against about 0.3 s.
  • Amplified sleep: use a very small sleep such as SLEEP(0.0001) and measure. A positive result is a delay far larger than the sleep value, caused by re-evaluation per row scanned.
  • Binary search extraction: compare LENGTH(<expr>) > N and ASCII(SUBSTR(<expr>, <pos>, 1)) < <mid>. A positive result is a consistent true/false timing split that lets you reconstruct a known string such as @@version.
  • Schema enumeration: compare (SELECT schema_name FROM information_schema.schemata ORDER BY schema_name LIMIT n,1) by equality. A positive result is a stable timing signal per candidate name.

Written with AI from the full original report and checked against it passage by passage; anything it could not back up was removed or toned down. The original is the record. 16 min read.

What happened, in plain words

A security researcher was taking part in a bug bounty programme, which is a scheme where companies invite people to look for security holes in their systems and pay for the ones that are reported responsibly. While testing a website, the researcher found a place where the site took a number from the address bar and pasted it straight into a database command. That is dangerous because a database command is a piece of text that tells the database what to do, and if a visitor can add their own words to that text, they can change what the database does.

The site had a WAF in front of it. A WAF, or web application firewall, is a filter that sits between visitors and the website and tries to block requests that look like attacks. It blocked all the usual tricks. The researcher then found a different way of writing the attack that the WAF did not recognise. It made the database pause for a few seconds when a condition was true, and answer quickly when it was false. By asking yes/no questions and watching the clock, the researcher could read the database one character at a time, including its version, its name, the internal hostname, the current user and the list of databases.

This article walks through that story from the beginning, explaining each idea as it appears.

1. The discovery (error-based)

The affected route was /catalog/items, and the parameter was id. A route is the part of a web address that points to a page or a feature, like a street address for a page. A parameter is a named value added to the address after a question mark, such as ?id=444, which the site reads and uses. Here the site took the value of id and put it directly into a database query, which is the instruction sent to the database. There were no quotes around it and no prepared statement. A prepared statement is a way of sending a query where the database is told in advance which parts are instructions and which parts are just data, so data can never be mistaken for an instruction. Without that, the value becomes part of the instruction itself.

The researcher looked for classic signs that the value was being treated as part of the query:

  • ?id=444' returned a SQL error reflected on the page, with the syntax error near the end of the value. The error is returned to the user. A SQL error is the database complaining that the command it received is not valid. Seeing that error on the page is a strong hint that the input reached the database.
  • ?id= followed by a backtick around 444 produced Unknown column '444', which shows the value enters without quotes and becomes an identifier. An identifier is a name, such as a column name or a table name, rather than a piece of text. Backticks are used in some databases to mark a name.
  • ?id=444%1 (MOD) returned an empty page, while ?id=444 DIV 1 returned results again, which shows the expression is evaluated in an executable numeric context. MOD gives the remainder of a division, and DIV gives the whole-number result of a division. If the site calculates them, the value is being treated as a mathematical expression, not as plain text.

The report shows these probes in a block that uses cat rather than id:

Text
?cat=444' -> SQLSTATE syntax error (refletido)
?cat=`444` -> Unknown column ‘444’ in ‘WHERE’
?cat=444%1 -> 0 resultados (444 MOD 1 = 0)
?cat=444 DIV 1 -> resultados (expressao avaliada)
?cat=444,445 -> sintaxe de lista aceita (multi-valor)

Line by line:

  • ?cat=444' sends a value ending in a single quote. The database sees an unfinished piece of text and reports a syntax error, which the page shows back. The word refletido means reflected: the error comes back to the person who sent the request.
  • ?cat=444`` wraps the number in backticks. The database treats it as a name, looks for a column called 444, does not find it, and says Unknown column. That tells the researcher the value is not inside quotes.
  • ?cat=444%1 uses % as the modulo operator, which gives the remainder of a division. 444 divided by 1 leaves no remainder, so the condition is false and the page comes back empty. The text 0 resultados means zero results.
  • ?cat=444 DIV 1 uses DIV, which divides and keeps the whole-number part. 444 divided by 1 is 444, so the page returns results again. The text expressao avaliada means the expression was evaluated.
  • ?cat=444,445 sends two values separated by a comma. The database accepts the list syntax, which means the value can be part of a list of values. The text multi-valor means multi-value.

Why this step matters: before attacking, the researcher needed to confirm that the input really reaches the database and how it is treated. Each probe answers a small question: does a quote break the query, does a backtick turn the value into a name, does arithmetic get calculated, and is a list accepted? Together they show a numeric context without quotes, which is exactly the kind of place where a crafted value can change the query.

2. The WAF

Every attempt at classic extraction returned 403. The number 403 is an HTTP status code meaning forbidden: the server, or the filter in front of it, refused the request. The table lists what was tried and what came back:

Payload Response
444' UNION SELECT 1 — - 403
444 AND 1=1 / OR 1=1 403
SLEEP(3), IF(..), BENCHMARK(..), GET_LOCK(..) 403
EXTRACTVALUE(..), UPDATEXML(..) 403
—, /*, )#, &&, || 403
subquery (SELECT after an operator or a comma 403
version(), database() outside a string 403

What each row means:

  • 444' UNION SELECT 1 — - is a classic attempt to append a second query with UNION SELECT, which combines the results of two queries. The — - is a comment marker that tells the database to ignore the rest of the original query. The WAF blocked it.
  • 444 AND 1=1 and OR 1=1 are simple conditions that are always true. Attackers use them to test whether their input changes the logic of the query. The WAF blocked them too.
  • SLEEP(3) asks the database to pause for three seconds. IF(..), BENCHMARK(..) and GET_LOCK(..) are other functions that can be used to cause delays or side effects. All were blocked.
  • EXTRACTVALUE(..) and UPDATEXML(..) are functions that can produce error messages containing data. They were blocked.
  • —, /*, )#, && and || are comment markers and logical operators often used to stitch payloads together. They were blocked.
  • A subquery, which is a query inside another query, written as (SELECT after an operator or a comma, was blocked.
  • version() and database() are functions that return the database version and the current database name. Outside a string, they were blocked.

One curiosity helped map the filter: the same keywords inside SQL strings passed. The filter tokenises and ignores strings, so the game became finding a construction where the payload does not fall into any signed pattern. To tokenise means to split the request into small pieces, called tokens, and inspect each one. If the filter skips anything inside quotes, then a blocked word placed inside a string is not seen as a keyword. A signed pattern is a known shape the filter recognises and blocks. The researcher's goal was therefore to find a shape that does the same job but does not match any pattern the filter knows.

Why this step matters: knowing exactly what is blocked tells you what you cannot use. It also reveals the filter's blind spot: it looks at tokens and ignores strings, so the attack has to be built from pieces that do not look like the blocked keywords when the filter reads them.

3. The bypass: NOT IN (SELECT CASE WHEN … )

While testing subqueries, one specific construction was not blocked:

Text
?id=444 NOT IN (SELECT CASE WHEN <cond> THEN SLEEP(0.0001) END)

Line by line:

  • ?id=444 is the normal parameter with a number.
  • NOT IN (...) is an operator that checks whether the value on the left is absent from a list or a set of results. The database has to work out the set on the right before it can answer.
  • (SELECT ...) is a subquery: a query inside the parentheses that produces that set.
  • CASE WHEN <cond> THEN SLEEP(0.0001) END is a conditional expression. <cond> stands for a condition the researcher chooses. If the condition is true, the expression evaluates to the result of SLEEP(0.0001), which asks the database to pause for a tiny fraction of a second. If the condition is false, it evaluates to nothing.

Inside the CASE WHEN, the filter let through what it blocked outside: SLEEP(), ASCII(), SUBSTR(), LENGTH(), and subqueries against information_schema, all of them. ASCII() returns the numeric code of a character, SUBSTR() takes a piece of a string, LENGTH() counts characters, and information_schema is a built-in catalogue of the database's own structure, such as the names of its databases and tables. The filter did not recognise this shape, so the keywords inside it were not matched.

The oracle became dichotomous and stable. An oracle, in security, is any observable behaviour that answers a yes/no question about the database. Here the answer is the response time:

Condition Response time
true ~5 s
false ~0.3 s

The SLEEP does not run once. The subquery is re-evaluated once per row scanned by the outer query, so even SLEEP(0.0001) becomes about 5 s, an amplification of roughly 29,000 times. That suits the attacker: tiny sleeps still produce a strong signal. In everyday terms, imagine asking a clerk to check a list of a thousand items and to pause for a moment each time an item matches. Even a very short pause, repeated a thousand times, becomes a long wait. The attacker measures the total wait, not the individual pause.

Why this step matters: the WAF blocked the obvious words, but it did not block this particular arrangement. By hiding the useful functions inside a CASE WHEN inside a NOT IN subquery, the researcher got the database to perform the delay while the filter saw nothing it recognised. The delay then becomes a channel for asking questions.

4. Extracting data with binary search

With the oracle in place, any SQL expression becomes an extractable string. An expression is a piece of SQL that produces a value, such as a version number or a name. Binary search is a way of finding a value by repeatedly halving the possibilities. Instead of trying every character from A to Z, you ask whether the answer is above or below the middle of the range, then repeat on the half that remains. Each answer removes half of the remaining options, so a small number of questions is enough.

The steps were:

  1. Length: LENGTH(<expr>) > N (binary search). First find how many characters the value has. Ask whether the length is greater than a number, adjust the number up or down depending on the timing, and repeat until the exact length is known.
  2. Each character: ASCII(SUBSTR(<expr>, <pos>, 1)) < <mid> (binary search over 33 to 126). Then take one character at a time. SUBSTR picks the character at position <pos>, ASCII turns it into a number, and the comparison asks whether that number is below a midpoint. The range 33 to 126 covers printable characters, from punctuation and digits to upper and lower case letters.
  3. Databases: (SELECT schema_name FROM information_schema.schemata ORDER BY schema_name LIMIT n,1) compared by equality. A schema is a container for tables inside a database. This subquery picks one schema name at a time from the built-in catalogue, in alphabetical order, and the equality comparison asks whether it matches a guess.

Typical cost: about 7 requests per character, averaging about 2 to 3 s each. Seven requests per character is what binary search over a range of about 94 printable characters looks like: each request halves the possibilities.

The expressions and example results shown in the report:

Text
Expressão: @@version -> “10.x.x-****-log” (exemplo)
Expressão: database() -> “wp_<redacted>” (exemplo)
Expressão: @@hostname -> host interno (IP privado)
Expressão: current_user -> user@host (privilegios limitados a 2 schemas)
Databases visiveis -> information_schema, ****_<redacted>

Line by line:

  • Expressão: @@version means the expression tested was @@version, which returns the database version. The result shown is a version string ending in -log, with part of it masked. The word exemplo means example.
  • database() returns the name of the current database. The result shown starts with wp_ and the rest is masked.
  • @@hostname returns the name of the machine the database runs on. The example result was an internal host, described as a private IP address. A private IP address is one used only inside a local network, not reachable directly from the internet.
  • current_user returns the database account in use, in the form user@host. The example result showed the account and its host, with a note that its privileges were limited to two schemas. Privileges are the permissions an account has.
  • Databases visiveis means visible databases. The example list contained information_schema and one other database whose name is masked.

Why this step matters: once a yes/no timing signal exists, any question that can be phrased in SQL can be answered. The researcher did not need to see data on the page. The clock did the talking. Binary search keeps the number of questions small, and the amplified sleep keeps each answer clear even when the individual pause is tiny.

Root cause

The id value is concatenated into the SQL text without quotes and without a prepared statement, so the database parses it as an expression rather than as data. Concatenated means joined together as text. Because the value is not quoted, the database cannot tell where the data ends and the instruction begins. The WAF is a signature filter: it tokenises the request and ignores string contents, and it blocks the well-known keywords and operators listed above. It does not recognise the NOT IN (SELECT CASE WHEN ... THEN SLEEP(...) END) shape, and once the payload sits inside that shape, the keywords it would otherwise block pass through. The defences did not stop the attack because the filter matches patterns rather than enforcing parameterisation, and the application had no parameterised query behind it. Parameterisation is the practice of sending values separately from the query text so they can only ever be data.

Impact

An attacker who can reach /catalog/items with a crafted id can turn the injection into a timing oracle and extract arbitrary SQL expressions character by character. In this case that covered the database version, the current database name, the internal hostname, the current user, and the list of visible schemas. The database user's privileges were limited to two schemas, which bounds what could be read with that account. The report does not describe write access, authentication bypass, or access to other systems.

Fix

The report does not state what was changed. The fix the finding calls for is to stop concatenating the value into the query and use a prepared statement with a bound parameter, so the value is treated as data regardless of what it contains. A bound parameter is a placeholder in the query that is filled with the value at run time, separately from the query text. A WAF rule for the NOT IN (SELECT CASE WHEN ...) shape would only be a stopgap, since the filter already showed it can be bypassed by constructions it does not sign.

Variants to test

These are the checks that follow from the techniques described. Each one describes what to send and what a positive result looks like.

  • Numeric context without quotes: send a single quote and a backtick around the value, then MOD and DIV expressions. A positive result is a reflected syntax error, an Unknown column error for the backticked value, an empty page for MOD, and results for DIV.
  • Keyword filter that ignores strings: place a blocked keyword inside a SQL string and see whether it passes. A positive result is that the keyword inside a string passes while the same keyword outside a string returns 403.
  • Subquery after NOT IN: try NOT IN (SELECT CASE WHEN <cond> THEN SLEEP(<small>) END) with a true and a false condition. A positive result is a clear timing difference, here about 5 s against about 0.3 s.
  • Amplified sleep: use a very small sleep such as SLEEP(0.0001) and measure. A positive result is a delay far larger than the sleep value, caused by re-evaluation per row scanned.
  • Binary search extraction: compare LENGTH(<expr>) > N and ASCII(SUBSTR(<expr>, <pos>, 1)) < <mid>. A positive result is a consistent true/false timing split that lets you reconstruct a known string such as @@version.
  • Schema enumeration: compare (SELECT schema_name FROM information_schema.schemata ORDER BY schema_name LIMIT n,1) by equality. A positive result is a stable timing signal per candidate name. Enumeration means listing items one by one.

Glossary

  • API: a defined way for one piece of software to ask another for data or actions, like a service counter with a fixed set of requests.
  • Authentication bypass: getting into an account or system without the correct credentials.
  • Binary search: a method of finding a value by repeatedly halving the range of possibilities, asking each time whether the answer is above or below the middle.
  • Bound parameter: a placeholder in a query that is filled with a value at run time, kept separate from the query text so the value cannot change the query's structure.
  • Bug bounty programme: a scheme where an organisation invites researchers to find and report security problems, often with a reward.
  • Concatenation: joining pieces of text together end to end.
  • Cookie: a small piece of data a website stores in the browser, often used to remember who you are between requests.
  • Database: an organised store of data that can be searched and changed with queries.
  • DIV: an operator that divides two numbers and keeps the whole-number part of the result.
  • Error-based: a technique that learns about a system by causing it to return error messages.
  • Expression: a piece of SQL that produces a value, such as a number, a string or a true/false result.
  • HTTP status code: a three-digit number in a web response that says how the request went, such as 200 for success and 403 for forbidden.
  • Identifier: a name used in a query, such as a column or table name, as opposed to a piece of text data.
  • information_schema: a built-in catalogue in many databases that describes the database's own structure, including database and table names.
  • Injection: inserting crafted input into a system so that it is interpreted as instructions rather than data.
  • MOD: an operator that gives the remainder after dividing one number by another.
  • Oracle: in security, any observable behaviour that answers a yes/no question about a system, such as a delay or an error.
  • Parameter: a named value passed in a web address, usually after a question mark, that the site reads and uses.
  • Parameterisation: sending values separately from query text so they are always treated as data.
  • Payload: the crafted input sent to a system to test or exploit it.
  • Prepared statement: a query sent to a database with placeholders for values, so the database knows in advance which parts are instructions and which are data.
  • Privileges: the permissions an account has, such as which databases it can read.
  • Private IP address: an address used only inside a local network, not directly reachable from the internet.
  • Query: an instruction sent to a database to read or change data.
  • Reflected: returned back to the person who sent the request, as opposed to stored and shown later to someone else.
  • Route: the part of a web address that points to a page or feature.
  • Schema: a container for tables inside a database.
  • Signature filter: a filter that blocks requests matching known patterns, rather than understanding what the request does.
  • SQL: the language used to talk to relational databases.
  • SQL error: a message from the database saying the query it received is not valid.
  • Subquery: a query written inside another query.
  • Tokenise: split a piece of text into small pieces, called tokens, for inspection.
  • UNION SELECT: a SQL construct that combines the results of two queries into one result set.
  • WAF (web application firewall): a filter placed in front of a website that inspects requests and blocks ones that look like attacks.

More by Guilhermegh

View all

1 more disclosed report, best first.

Similar reports

View all

Same bug class and techniques, clearest first.

SQL injection

The lesson behind this report.

Input reaches a database query as code, letting an attacker read or change data the application never meant to expose.