SQL Injection em ORDER BY sem autenticação: contornando o WAF com CASE WHEN e subqueries em uma corretora de investimentos.
An unauthenticated rankings API concatenated the sort parameter directly into the SQL ORDER BY clause, so arbitrary SQL expressions were evaluated by the database. The author confirmed SQL function execution, CASE WHEN evaluation, scalar subqueries against system tables and column-position enumeration, which could allow data extraction by conditional inference across millions of accounts.
Bug Bounty
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.
Context
The target was a public investment platform, and the feature in question was a rankings API. The endpoint returns JSON with ranking data for a given period, and the client controls the ordering through a single GET parameter called sort. The endpoint was public: no token, no cookie, and no perceptible rate limit. According to the author, the data behind it covered millions of user accounts.
All identifying details (domain, endpoint names) were censored in the write-up to respect the disclosure policy. The author also notes that an earlier IDOR had let them identify and deduce user IDs, which made it possible to develop and chain the SQL injection; that part is left for a separate article.
Setup
There were no accounts, roles or special tooling described. The only precondition was network access to the public endpoint. The request shape given in the report is:
GET https://[REDACTED]/api/[...]/rankings/?period=OneYearAgo&sort=<PAYLOAD>&pagesize=5
period selects the time window, sort is the injection point, and pagesize limits the number of rows returned. Nothing else was needed to reach the vulnerable code path.
Finding it
The sort parameter is concatenated directly into the ORDER BY clause of the SQL query. Instead of validating the value against a fixed enum of allowed columns, the backend builds the query as:
SELECT … FROM … ORDER BY <valor_do_parametro>
That means any valid SQL expression supplied in sort is evaluated in the database context. The author's reasoning was straightforward: if the backend ignored invalid values, every malformed or unexpected input would fall back to the default ordering. Distinct orderings for distinct expressions would prove the expressions were being evaluated by SQL.
Exploitation
Step 1: SQL functions in ORDER BY
Replacing sort with SQL functions produced different and consistent orderings across requests:
REVERSE(UserName): reverse ordering of names;LOWER(UserName): case-insensitive ordering;LEFT(UserName, 3): ordering by the first three characters.
If the backend discarded invalid values, all three would have returned the default ordering. The different results show the functions are evaluated by the database.
Step 2: Conditional CASE WHEN expressions
The decisive test used two expressions:
CASE WHEN 1=1 THEN UserName ELSE CustomerId END
CASE WHEN 1=2 THEN 1 ELSE 2 END
The second one, CASE WHEN 1=2 THEN 1 ELSE 2 END, produced exactly the same ordering as sort=2. That proves three things at once: the CASE WHEN expression is evaluated by SQL, its result is used as a column index in ORDER BY, and boolean logic works (1=1 true, 1=2 false).
This opens the path to extraction by conditional inference. A payload of the form CASE WHEN SUBSTRING(secret,1,1)='a' THEN 1 ELSE 2 END lets you compare the resulting ordering with the baseline and recover each character, bit by bit.
Step 3: Scalar subqueries against system tables
The next batch of payloads used subqueries:
sort=(SELECT 1)
sort=(SELECT 1 FROM pg_class)
sort=(SELECT 1 FROM information_schema.tables)
sort=(SELECT 1 FROM sys.tables)
sort=(SELECT 1 FROM DUAL)
These cover PostgreSQL (pg_class), ANSI (information_schema.tables), MSSQL (sys.tables) and Oracle (DUAL). All returned HTTP 200, so the backend accepts scalar subqueries inside ORDER BY, including references to system tables. For the author this is proof that there is no whitelist parser: real SQL is being executed.
Step 4: Column enumeration by position
Values from sort=1 through sort=10 produced distinct orderings, confirming that numeric values are interpreted as SQL column indices, the classic position-based ORDER BY n. An application without injection would only accept a fixed enum.
Step 5: System functions and variables
@@version, VERSION(), CURRENT_USER, NOW() and RAND() were all accepted with HTTP 200, which enriched the database fingerprint.
The author also mapped which expressions the WAF blocked through repeated attempts and used that to infer a bypass. The specific bypass technique is deliberately omitted from the write-up.
Why direct extraction was not possible
The backend wrapped the query in an error-handling block that silences every exception:
CAST(UserName AS INTEGER)produced a type error that was silenced;CASE WHEN 1=1 THEN 1/0 ELSE 1 ENDproduced a division by zero that was silenced;INVALID()produced a missing-function error that was silenced.
As a result, error-based SQL injection was not viable. Extraction would have had to go through one of three routes:
- Boolean-based: comparing the ordering of
CASE WHEN condição THEN 1 ELSE 2 ENDagainst the baseline (sort=1), which the author considered the most promising; - Heavy query / time-based: differential latency, observed at roughly 6x higher with
FROM DUAL; - OOB: exfiltration through an external channel.

Root cause
The mistake is in how sort is handled: the value is concatenated into the ORDER BY clause instead of being validated against a fixed enum of columns. Because ORDER BY accepts expressions, not just column names, the concatenation gives the attacker the full SQL expression grammar: functions, CASE WHEN, scalar subqueries and system variables all work.
The existing defences did not stop it. The WAF blocked some expressions, but the author mapped the blocks and found a bypass (technique not disclosed). The error-handling wrapper silenced exceptions, which removed error-based extraction but did nothing to prevent the injection itself. The absence of authentication on the endpoint meant there was no session or privilege boundary to cross either.
Impact
The author rated the issue CVSS 3.1: 7.5 (High), with Attack Vector Network, Privileges Required None, and Confidentiality High, given that data from 3.6M+ accounts was within reach, including through conditional inference.
Confirmed during testing:
- execution of SQL functions in
ORDER BY; CASE WHENexpressions evaluated;- subqueries against system tables;
- column enumeration by position.
Potential, as described by the author:
- extraction of data character by character through conditional inference on the ordering;
- full database fingerprint via
@@version,VERSION()andCURRENT_USER.
The vulnerability was a duplicate when reported.
Fix
The report does not describe a fix or a change made by the platform. The measure implied by the root cause is to stop concatenating sort into the query and validate it against a fixed enum of allowed columns, so that only known column names can reach ORDER BY.
Variants to test
- Function calls in
sort: sendREVERSE(column),LOWER(column)orLEFT(column, 3). A positive result is an ordering that differs from the default and stays consistent across repeated requests. - Conditional expressions: send
CASE WHEN 1=2 THEN 1 ELSE 2 ENDand compare withsort=2. A positive result is an identical ordering, which shows the expression is evaluated and its result used as a column index. - Scalar subqueries: send
(SELECT 1),(SELECT 1 FROM pg_class),(SELECT 1 FROM information_schema.tables),(SELECT 1 FROM sys.tables)and(SELECT 1 FROM DUAL). A positive result is HTTP 200 for the variants that match the backend's database engine. - Position-based enumeration: send
sort=1throughsort=10. A positive result is distinct orderings for the different numbers. - System variables: send
@@version,VERSION(),CURRENT_USER,NOW()andRAND(). A positive result is HTTP 200, which also helps fingerprint the engine. - Error silencing check: send
CAST(column AS INTEGER),CASE WHEN 1=1 THEN 1/0 ELSE 1 ENDandINVALID(). If all errors are swallowed, plan for boolean-based, time-based or OOB extraction rather than error-based. - WAF mapping: repeat blocked and allowed expressions to find which patterns the filter catches. A positive result is a set of expressions that pass while still being evaluated by SQL.
What happened, in plain words
A security researcher was testing a public investment platform, the kind of website where people hold accounts, see their balances and compare how their investments are doing. One of the site's features was a rankings page: it shows a list of users ordered in some way, for example by performance over a chosen period. That list was not drawn by the website itself in the browser; it was fetched from a small web service behind the scenes, and that service had a serious flaw.
The flaw let anyone who could reach that service slip pieces of database instructions into the request, and the database would run them. The researcher used this to prove that the database was executing their instructions, and to show that data belonging to millions of user accounts was within reach. The site had a protective filter in front of it (a WAF), but the researcher found a way around it. The report does not describe the exact bypass technique; the author deliberately leaves it out.
When the researcher reported the issue, it turned out someone else had already reported the same problem, so it was marked as a duplicate. The write-up exists to explain the thinking and the method.
A few words before we start, because they come up constantly:
- An API is a way for one piece of software to talk to another. When your browser loads a rankings page, the page's code often asks a separate service for the data, and that service answers in a compact format such as JSON. Think of it as a waiter: you do not walk into the kitchen, you tell the waiter what you want and the waiter brings it.
- JSON is just a text format for structured data, made of names and values in curly braces and square brackets. It is what the waiter hands back.
- A GET parameter is a value attached to the end of a web address after a question mark, like
?period=OneYearAgo. It is how you tell the API what you want, and it is visible in the address bar. - A cookie is a small piece of data your browser stores for a site and sends back with each request, usually to remember who you are. A token is similar: a string that proves you are logged in. Neither was needed here, which is the point.
- SQL is the language used to ask a database questions. A database is the place where the site keeps its records, in tables that look like spreadsheets: rows are records, columns are fields such as a username or a customer ID.
- SQL injection is what happens when a program builds a database question by gluing together text from the user, so that the user's text is treated as part of the instruction rather than as plain data. It is like a form that says "write your name here" and someone writes "name, and also open the safe".
- A WAF (web application firewall) is a filter that sits in front of a site and tries to block requests that look malicious, a bit like a bouncer checking bags at the door.
The target
The feature was a rankings API. It returns ranking data for a chosen period, and the person calling it decides how the list is ordered through one single GET parameter called sort. The endpoint was public: no token, no cookie, and no noticeable rate limit (a rate limit is a cap on how many requests you can make in a given time, like a shop limiting how many items one person can buy). According to the author, the data behind it covered millions of user accounts.
All identifying details, such as the domain and the endpoint names, were censored in the write-up to respect the disclosure policy. The author also mentions that an earlier IDOR had let them identify and deduce user IDs, which made it possible to develop and chain the SQL injection. IDOR stands for Insecure Direct Object Reference: a flaw where a site lets you reach someone else's record simply by changing an identifier in a request, for example swapping a number for another number. That earlier finding is left for a separate article.
Setup
There were no accounts, roles or special tools described. The only precondition was network access to the public endpoint, meaning an ordinary internet connection and the ability to send a request to that address. The request shape given in the report is:
GET https://[REDACTED]/api/[...]/rankings/?period=OneYearAgo&sort=<PAYLOAD>&pagesize=5
Line by line:
GETis the type of request. It means "give me something", as opposed to sending data to be stored.https://[REDACTED]/api/[...]/rankings/is the address of the service. The parts in brackets were removed from the write-up so the target cannot be identified.period=OneYearAgotells the API which time window to use for the ranking.sort=<PAYLOAD>is the parameter under attack.<PAYLOAD>is a placeholder: this is where the researcher puts the text they want the database to process.pagesize=5limits how many rows come back, here five.
Nothing else was needed to reach the vulnerable code path, meaning the part of the program where the mistake lives.
Finding it
The sort parameter is concatenated directly into the ORDER BY clause of the SQL query. ORDER BY is the part of a SQL question that says how to sort the results, for example by username or by score. Concatenated means glued in as raw text. Instead of checking the value against a fixed list of allowed columns, the backend builds the query like this:
SELECT … FROM … ORDER BY <valor_do_parametro>
Line by line:
SELECT … FROM …is the skeleton of a database question: pick some fields from some table. The dots stand for parts the report does not show.ORDER BY <valor_do_parametro>is where the sort choice goes.<valor_do_parametro>means "the value of the parameter", in other words whatever the caller typed intosort, pasted in as-is.
Because of that, any valid SQL expression supplied in sort is evaluated in the database context. An expression is a piece of SQL that produces a value, such as a function call or a comparison. The author's reasoning was simple: if the backend ignored invalid values, every malformed or unexpected input would fall back to the default ordering. If different expressions produced different orderings, that would prove the expressions were being evaluated by SQL. This is the core idea of the whole article: compare what you send with what comes back, and let the difference tell you what the server did.
Exploitation
Step 1: SQL functions in ORDER BY
Replacing sort with SQL functions produced different and consistent orderings across requests:
REVERSE(UserName): reverse ordering of names;LOWER(UserName): case-insensitive ordering;LEFT(UserName, 3): ordering by the first three characters.
What these mean:
REVERSE(UserName)takes each username and flips its characters, then sorts by the flipped text. The resulting order differs from sorting by the normal name.LOWER(UserName)turns each username to lowercase before sorting, so uppercase and lowercase letters are treated the same.LEFT(UserName, 3)keeps only the first three characters of each username and sorts by those.
If the backend discarded invalid values, all three would have returned the default ordering. The different results show the functions are evaluated by the database. In everyday terms: you asked the waiter for three different dishes and got three different plates, so the kitchen really is reading your order.
Step 2: Conditional CASE WHEN expressions
The decisive test used two expressions:
CASE WHEN 1=1 THEN UserName ELSE CustomerId END
CASE WHEN 1=2 THEN 1 ELSE 2 END
Line by line:
CASE WHEN ... THEN ... ELSE ... ENDis SQL's way of saying "if this condition is true, use this value, otherwise use that value". It is the same idea as an if/else in any program.1=1is always true, so the first expression always sorts byUserName.1=2is always false, so the second expression always produces the value2.
The second one, CASE WHEN 1=2 THEN 1 ELSE 2 END, produced exactly the same ordering as sort=2. That proves three things at once: the CASE WHEN expression is evaluated by SQL, its result is used as a column index in ORDER BY (a column index is a number that means "the first column, the second column" and so on), and boolean logic works, meaning true and false conditions behave as expected.
This opens the path to extraction by conditional inference. Inference means working something out indirectly, from clues, rather than reading it directly. A payload of the form CASE WHEN SUBSTRING(secret,1,1)='a' THEN 1 ELSE 2 END lets you compare the resulting ordering with the baseline and recover each character, bit by bit. SUBSTRING(secret,1,1) takes one character from a piece of text at a given position. The baseline is the normal result you compare against, here sort=1. If the ordering matches the baseline, the condition was true; if it matches the other branch, it was false. Ask enough yes/no questions and you can spell out a secret one character at a time, like playing twenty questions with a database.
Step 3: Scalar subqueries against system tables
The next batch of payloads used subqueries:
sort=(SELECT 1)
sort=(SELECT 1 FROM pg_class)
sort=(SELECT 1 FROM information_schema.tables)
sort=(SELECT 1 FROM sys.tables)
sort=(SELECT 1 FROM DUAL)
Line by line:
- A subquery is a query inside another query, like a question asked within a question. A scalar subquery is one that returns a single value.
(SELECT 1)asks the database for the number 1. If that is accepted, the database is running your nested query.(SELECT 1 FROM pg_class)asks for 1 frompg_class, a system table in PostgreSQL that lists the database's own tables. A system table is a built-in table the database keeps about itself, like an index at the back of a book.(SELECT 1 FROM information_schema.tables)does the same using the standard, ANSI-style catalogue of tables.(SELECT 1 FROM sys.tables)uses the equivalent in MSSQL, Microsoft's database.(SELECT 1 FROM DUAL)usesDUAL, a special one-row table in Oracle.
These cover PostgreSQL, ANSI, MSSQL and Oracle. All returned HTTP 200, the standard "OK" response code, so the backend accepts scalar subqueries inside ORDER BY, including references to system tables. For the author this is proof that there is no whitelist parser: a whitelist is a list of allowed values, and a parser here would be code that checks the input against that list. Real SQL is being executed.
Step 4: Column enumeration by position
Values from sort=1 through sort=10 produced distinct orderings, confirming that numeric values are interpreted as SQL column indices, the classic position-based ORDER BY n. In plain words, ORDER BY 1 means "sort by the first column", ORDER BY 2 means "sort by the second column", and so on. An application without injection would only accept a fixed list of allowed values, so a bare number would not change anything.
Step 5: System functions and variables
@@version, VERSION(), CURRENT_USER, NOW() and RAND() were all accepted with HTTP 200, which enriched the database fingerprint. A fingerprint here means the clues that tell you which database product and version you are talking to. @@version and VERSION() report the database version, CURRENT_USER reports the account the database is running as, NOW() gives the current time and RAND() gives a random number.
The author also mapped which expressions the WAF blocked through repeated attempts and used that to infer a bypass. The specific bypass technique is deliberately omitted from the write-up.
Why direct extraction was not possible
The backend wrapped the query in an error-handling block that silences every exception. An exception is an error the program raises when something goes wrong; silencing it means the program catches the error and returns a normal-looking answer instead of an error message.
CAST(UserName AS INTEGER)produced a type error that was silenced.CASTtries to convert a value from one type to another, here text to a whole number, which fails for a name like "alice".CASE WHEN 1=1 THEN 1/0 ELSE 1 ENDproduced a division by zero that was silenced. Dividing by zero is an error in SQL, and this payload forces it whenever the condition is true.INVALID()produced a missing-function error that was silenced, because no such function exists.
As a result, error-based SQL injection was not viable. Error-based injection is a technique where you deliberately cause an error and read the database's complaint, which often contains the data you want. Here the complaints never reached the researcher. Extraction would have had to go through one of three routes:
- Boolean-based: comparing the ordering of
CASE WHEN condição THEN 1 ELSE 2 ENDagainst the baseline (sort=1), which the author considered the most promising. Boolean means yes/no: each request answers one true-or-false question. - Heavy query / time-based: differential latency, observed at roughly 6x higher with
FROM DUAL. Latency is how long a response takes. If a payload that makes the database work harder takes noticeably longer, the delay itself becomes the yes/no signal. - OOB: exfiltration through an external channel. OOB stands for out-of-band: instead of reading the answer in the response, you make the database send the data somewhere you can watch, such as a server you control.

Root cause
The mistake is in how sort is handled: the value is concatenated into the ORDER BY clause instead of being validated against a fixed list of columns. Because ORDER BY accepts expressions, not just column names, the concatenation gives the attacker the full SQL expression grammar: functions, CASE WHEN, scalar subqueries and system variables all work.
The existing defences did not stop it. The WAF blocked some expressions, but the author mapped the blocks and found a bypass, technique not disclosed. The error-handling wrapper silenced exceptions, which removed error-based extraction but did nothing to prevent the injection itself. The absence of authentication on the endpoint meant there was no session or privilege boundary to cross either. Authentication means proving who you are, and a privilege boundary is the line between what a logged-in user may do and what an anonymous visitor may do. With no login required, there was no line to cross.
Impact
The author rated the issue CVSS 3.1: 7.5 (High). CVSS is a standard scoring system for the severity of a security flaw, where a higher number means more serious. The components given are Attack Vector Network, meaning it can be done remotely over the internet; Privileges Required None, meaning no account is needed; and Confidentiality High, meaning a lot of secret data could be read, given that data from 3.6M+ accounts was within reach, including through conditional inference.
Confirmed during testing:
- execution of SQL functions in
ORDER BY; CASE WHENexpressions evaluated;- subqueries against system tables;
- column enumeration by position.
Potential, as described by the author:
- extraction of data character by character through conditional inference on the ordering;
- full database fingerprint via
@@version,VERSION()andCURRENT_USER.
The vulnerability was a duplicate when reported. A bounty is the reward a company pays for a valid report; a duplicate means the same issue had already been reported by someone else.
Fix
The measure implied by the root cause is to stop concatenating sort into the query and validate it against a fixed list of allowed columns, so that only known column names can reach ORDER BY. In everyday terms: instead of letting the customer write anything on the order slip, give them a menu and only accept items from it.
Variants to test
These are the checks the author describes, written so you can repeat them on a system you are authorised to test. Each one lists what a positive result looks like.
- Function calls in
sort: sendREVERSE(column),LOWER(column)orLEFT(column, 3). A positive result is an ordering that differs from the default and stays consistent across repeated requests. - Conditional expressions: send
CASE WHEN 1=2 THEN 1 ELSE 2 ENDand compare withsort=2. A positive result is an identical ordering, which shows the expression is evaluated and its result used as a column index. - Scalar subqueries: send
(SELECT 1),(SELECT 1 FROM pg_class),(SELECT 1 FROM information_schema.tables),(SELECT 1 FROM sys.tables)and(SELECT 1 FROM DUAL). A positive result is HTTP 200 for the variants that match the backend's database engine. - Position-based enumeration: send
sort=1throughsort=10. A positive result is distinct orderings for the different numbers. - System variables: send
@@version,VERSION(),CURRENT_USER,NOW()andRAND(). A positive result is HTTP 200, which also helps fingerprint the engine. - Error silencing check: send
CAST(column AS INTEGER),CASE WHEN 1=1 THEN 1/0 ELSE 1 ENDandINVALID(). If all errors are swallowed, plan for boolean-based, time-based or OOB extraction rather than error-based. - WAF mapping: repeat blocked and allowed expressions to find which patterns the filter catches. A positive result is a set of expressions that pass while still being evaluated by SQL.
Glossary
- API: a service that one piece of software calls to get data or perform an action, usually over the internet.
- Authentication: the process of proving who you are, typically by logging in.
- Baseline: the normal, known result you compare a test result against.
- Boolean-based injection: a technique where each request answers one true-or-false question, and the answers are combined to recover data.
- Bounty: a reward paid by a company for a valid security report.
- CASE WHEN: SQL's if/else construct, choosing one value or another depending on a condition.
- CAST: a SQL operation that converts a value from one data type to another.
- Column index: a number referring to a column's position in a result, as used in
ORDER BY 1,ORDER BY 2. - Concatenation: gluing pieces of text together into one string.
- Cookie: a small piece of data a browser stores for a site and sends back with requests, often used to remember a session.
- CVSS: a standard scoring system for the severity of a security flaw.
- Database: the system that stores a site's records in tables of rows and columns.
- Duplicate: a report describing an issue that has already been reported.
- Error-based injection: a technique that deliberately triggers database errors and reads the error messages to obtain data.
- Exception: an error raised by a program when something goes wrong.
- Expression: a piece of SQL that produces a value, such as a function call or a comparison.
- Fingerprint: the set of clues that identify which database product and version is running.
- GET parameter: a value attached to a web address after a question mark, used to tell a service what you want.
- Heavy query / time-based injection: a technique that infers answers from how long the server takes to respond.
- HTTP 200: the standard response code meaning the request succeeded.
- IDOR: Insecure Direct Object Reference, a flaw where changing an identifier in a request gives access to someone else's record.
- Inference: working something out indirectly from clues rather than reading it directly.
- JSON: a text format for structured data, made of names and values.
- Latency: how long a response takes to arrive.
- OOB (out-of-band): sending data out through a separate channel, such as an external server, instead of reading it in the response.
- ORDER BY: the part of a SQL query that decides how results are sorted.
- Parser: code that reads and checks input, here against a list of allowed values.
- Payload: the text an attacker sends in a request to trigger or test a flaw.
- Privilege boundary: the line between what one kind of user may do and what another may do.
- Rate limit: a cap on how many requests can be made in a given time.
- Scalar subquery: a query nested inside another query that returns a single value.
- SQL: the language used to ask a database questions.
- Subquery: a query inside another query.
- System table: a built-in table a database keeps about itself, listing its own tables and similar metadata.
- Token: a string that proves you are logged in, sent with requests instead of or alongside a cookie.
- WAF: web application firewall, a filter in front of a site that tries to block malicious requests.
- Whitelist: a list of values that are explicitly allowed, with everything else rejected.