Skip to content
SQL injection Write-up Intermediate

How a Sort Parmeter Became Blind SQL Injection

The sort_by parameter of a WordPress REST API endpoint was concatenated directly into the SQL ORDER BY clause without validation, allowing an unauthenticated attacker to inject boolean expressions. By observing which of two orderings was returned, the attacker could extract database metadata and user counts character by character.

medium.com

Published on medium.com

Cybersecurity

Adem_Zayani, 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

The target was a web application in scope for a private bug bounty program. The feature under test was a REST API endpoint that returns a list of records, in this case counties. It is a simple "get all" endpoint that accepts two query parameters, sort_by and sort_dir, and returns the records in the requested order.

Nothing about the endpoint suggested anything interesting: it is a read-only listing with a sort parameter, the kind of thing that is usually written off as harmless. The researcher's starting point was simply wanting to know what the backend actually did with that parameter.

Setup

No accounts, roles or special tooling are described. The testing was done by sending requests with modified query parameters and observing the order of the returned records. The extraction was later scripted in Python and PowerShell so that the triage team could reproduce it without a wall of manual curl commands.

Finding it

The endpoint looked like this:

HTTP
GET https://[REDACTED].com/wp-json/counties/v1/all?sort_by=CountyName&sort_dir=asc

The path sits under wp-json, the WordPress REST API prefix, with a route for counties. The first step was to confirm that sort_by genuinely controlled the ordering of the response, using two legitimate column names:

Text
sort_by=CountyName  → first record: Appling County
sort_by=CountyID    → first record: Bartow County

Two different, predictable orderings came back. That told the researcher the value was being used directly to build the query, which raised the question of whether it was validated at all.

Exploitation

Step 1: confirm the parameter reaches the query

Sending sort_by=CountyName returned Appling County first, and sort_by=CountyID returned Bartow County first. The ordering changed with the parameter value, so the value was reaching the query logic.

Step 2: send a SQL expression instead of a column name

Instead of a real column name, the researcher sent a CASE WHEN expression:

SQL
sort_by=(CASE WHEN 1=1 THEN CountyName ELSE CountyID END)

The response came back ordered by CountyName.

Step 3: flip the condition

SQL
sort_by=(CASE WHEN 1=2 THEN CountyName ELSE CountyID END)

This time the response came back ordered by CountyID.

That was the confirmation. The database was evaluating the CASE WHEN expression directly, with no authentication and no sanitisation: raw SQL injection in the ORDER BY clause. The two orderings give a clean boolean oracle, because a true condition and a false condition each produce a known, distinguishable state in the response.

Step 4: extract data character by character

With a working boolean oracle, the database can be asked anything one true/false question at a time. Using LENGTH() and ASCII(SUBSTRING(...)) inside the same CASE WHEN, the researcher extracted real values character by character:

SQL
sort_by=(CASE WHEN (LENGTH(DATABASE())=14) THEN CountyName ELSE CountyID END)
sort_by=(CASE WHEN (ASCII(SUBSTRING(DATABASE(),1,1))=119) THEN CountyName ELSE CountyID END)

Repeating this for each position recovers the string one character at a time.

Using this technique, the researcher recovered:

Item Value
Database name [REDACTED]
Current DB user [REDACTED]@[redacted]
DB server hostname [REDACTED]
Total tables in schema 155
Users table wp_users (confirmed to exist)
User account count 71

All of it unauthenticated.

Step 5: automate

The whole extraction was scripted, in Python and PowerShell versions, so the triage team could reproduce the results themselves rather than trusting a long sequence of manual curl commands.

The attack flow, as the researcher lays it out:

Text
Send a normal request with a known sort_by value
        ↓
Confirm the ordering changes as expected
        ↓
Replace sort_by with a CASE WHEN boolean expression
        ↓
Observe which ordering comes back
        ↓
Use that as a true/false oracle
        ↓
Extract data character-by-character with LENGTH() / ASCII(SUBSTRING())
        ↓
Automate it

Root cause

The sort_by value was concatenated straight into the SQL ORDER BY clause with no allowlist and no validation. The application effectively trusted:

Text
sort_by=<anything the client sends>

instead of checking whether the value is one of the columns the application actually allows sorting by.

Prepared statements do not help here: a value can be parameterised, but a column name or expression cannot. Without an explicit allowlist of permitted sort columns, anything the client sends is accepted, and in this case it was evaluated by the database as SQL.

Impact

This gave an unauthenticated attacker a reliable SQL injection primitive against the production database, with no rate limiting slowing it down. In practice that meant:

  • Extraction of database and server metadata.
  • Confirmation of internal table structure.
  • Ability to query user account counts from the wp_users table.
  • A clear path toward extracting further data, limited only by the permissions of the database user.

No login, no session and no prior access were required: just the endpoint and a query string.

Fix

The report does not describe the code change that was made. It states that the vulnerability was reported through HackerOne to the responsible program, validated, escalated to Critical severity, and that the fix was later confirmed via retest, with the report now closed as Resolved.

From the original on medium.com

The general remedy follows from the root cause: validate sort_by against an explicit allowlist of sortable columns and map the request to a known column rather than concatenating the client value into the query. Prepared statements alone are not sufficient for this position in the query.

Variants to test

  • Other sort parameters on listing endpoints. Look for sort, order_by, sort_by, sort_dir and similar parameters on REST, GraphQL and classic endpoints. A positive result is the same as here: two legitimate values produce two predictable orderings, and a CASE WHEN expression flips the ordering between them.
  • WordPress REST namespaces with custom routes. A positive result is a route that accepts a column name and reflects it in the ordering of the response.
  • Boolean oracles through ordering. Any endpoint where a true and false condition produce two distinguishable, stable responses can be used the same way. A positive result is a reliable flip between two known states when the condition changes.
  • Length and character tests. Once an oracle exists, LENGTH() and ASCII(SUBSTRING(...)) inside the same expression confirm that arbitrary data can be read. A positive result is a length test that matches and a character test that matches for a known string.
  • Rate limiting checks. Send the oracle requests repeatedly and observe whether responses are throttled.
From the original on medium.com

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. 13 min read.

What happened, in plain words

A security researcher was testing a website that was part of a private bug bounty program. A bug bounty program is an arrangement where a company invites outside testers to look for security problems in its systems and report them, usually in exchange for a reward and recognition. "Private" means only invited people can take part.

The researcher found a page on the site that returns a list of counties. The endpoint had a parameter that chose how the list is sorted, for example by county name or by county ID. That setting was passed to the database without being checked, and the database ran whatever was put there as part of its query. By putting a small question into that setting, the researcher could make the database answer yes or no, and by asking many such questions they could read information out of the database: its name, the user it runs as, the server hostname, how many tables it has, and how many user accounts exist. No login was needed.

The researcher reported it through HackerOne, a platform where bug bounty reports are submitted and tracked. The report was accepted, raised to Critical severity, and the fix was confirmed by testing again. The report is now closed as Resolved.

This article walks through the same steps for someone who has never done security testing before. The requests and payloads below are as they appear in the write-up.

Background: the pieces involved

Before the steps, a few ideas that come up constantly.

  • Web page versus API. When you open a site in a browser, you get a page with text, buttons and pictures. An API is a different door into the same system: it is meant for programs rather than people. You send it a request in a fixed format and it sends back data, often in a structured form such as JSON (a text format for labelled values). A browser can open an API address too, and you will see the raw data instead of a designed page.
  • Endpoint. An endpoint is one specific address on a server that does one specific job. Think of a restaurant: the building is the server, and each counter (drinks, hot food, desserts) is an endpoint. You go to the right counter for what you want.
  • Query string and query parameters. The part of a web address after a question mark is the query string. It carries small labelled values called query parameters, written as name=value and joined with &. They are like the options you tick on an order form: "size: large, colour: blue". The server reads them and adjusts what it sends back.
  • REST API. A common style for building APIs where each address represents a thing (here, counties) and the type of request (GET means "give me data") says what to do with it.
  • WordPress and wp-json. WordPress is a very popular system for building websites. It has a built-in API whose addresses start with wp-json. Plugins (add-on pieces of software) can add their own sections under it, which is why you see a custom name like counties in the address.
  • Database, table, column, row. A database is an organised store of data. Inside it, data sits in tables, which look like spreadsheets: columns are the headings (for example CountyName, CountyID) and rows are the individual records (one county each).
  • SQL and the ORDER BY clause. SQL is the language used to ask a database for data. A query is one such request. ORDER BY is the part of a query that says how to sort the results. If the sort choice is pasted into the query as text, whatever is pasted becomes part of the instruction the database follows.
  • SQL injection. This is the vulnerability class here: when a program takes input from a user and puts it straight into a database instruction without checking it, the user's input can change the instruction itself. It is like a form that says "write your name here" and someone writes "name, and also open the safe".
  • Authentication and unauthenticated. Authentication is proving who you are, usually by logging in. Unauthenticated means no login at all: anyone who knows the address can send the request.
  • Sanitisation and allowlist. Sanitisation means cleaning or checking input before using it. An allowlist is a list of the only values that are accepted; anything not on the list is refused. It is the difference between a bouncer with a guest list and a bouncer who lets in anyone who says a word.
  • Boolean oracle. A boolean is a yes/no value. An oracle is something that gives you an answer you can use. A boolean oracle is a way of asking the system a yes/no question and telling the two answers apart from the outside, even when the system never says "yes" or "no" in words.
  • Blind. Blind injection means you cannot see the database's output directly. You only see a side effect, here the order of the list, and you infer the answer from it.
  • Rate limiting. A limit on how many requests a server will answer in a period of time. Without it, a program can ask thousands of questions quickly.

The endpoint that was tested

While testing a web application in scope for a private program, the researcher came across a REST API endpoint that returns a list of records, counties in this case. It is a simple "get all" endpoint with two query parameters:

HTTP
GET https://[REDACTED].com/wp-json/counties/v1/all?sort_by=CountyName&sort_dir=asc

Line by line:

  • GET is the type of request. It means "send me data" and does not change anything on the server.
  • https://[REDACTED].com is the site's address. The real domain is hidden here.
  • /wp-json/counties/v1/all is the path to the endpoint. wp-json shows it belongs to WordPress's API, and the rest of the path names the route.
  • ? starts the query string.
  • sort_by=CountyName says which column to sort on.
  • & separates the next parameter.
  • sort_dir=asc says the direction: ascending, meaning A to Z or smallest to largest.

At first glance it looked completely harmless, just a sort parameter. But the researcher wanted to see what the backend actually did with it. That is the right instinct: a setting that only chooses a sort order still has to be read by the server, and the question is whether the server checks it first.

From the original on medium.com

Finding the injection

The first step was to confirm that sort_by genuinely controlled the ordering of the response, using two legitimate values:

Text
sort_by=CountyName  → first record: Appling County
sort_by=CountyID    → first record: Bartow County

What this shows:

  • The first line asks for sorting by county name. The first record returned is Appling County.
  • The second line asks for sorting by county ID. The first record returned is Bartow County.
  • The arrow means "and the result was".

Two different, predictable orderings. That told the researcher the value was being used directly to build the query, which made them want to test whether it was validated at all. The reasoning is simple: the order changed in a way that matches the column names, so the value was reaching the query. It did change, so the value was reaching the query.

So instead of a real column name, the researcher sent a SQL expression:

SQL
sort_by=(CASE WHEN 1=1 THEN CountyName ELSE CountyID END)

What each part means:

  • CASE WHEN ... THEN ... ELSE ... END is SQL's way of writing an if/else. If the condition is true, use the first choice; otherwise use the second.
  • 1=1 is a condition that is always true.
  • THEN CountyName means: if true, sort by county name.
  • ELSE CountyID means: if false, sort by county ID.
  • END closes the expression.

The response came back ordered by CountyName. That is exactly what the true branch asks for.

Then the researcher flipped the condition:

SQL
sort_by=(CASE WHEN 1=2 THEN CountyName ELSE CountyID END)

Here 1=2 is always false, so the expression should choose the ELSE branch. This time the response came back ordered by CountyID.

That was the confirmation. The database was evaluating the CASE WHEN expression directly, with no authentication and no sanitisation: raw SQL injection in the ORDER BY clause. In plain terms, the sort setting was not a setting at all; it was a slot where the server pasted text into its database instruction, and the database obeyed whatever was pasted.

From oracle to data extraction

At this point there was a working boolean oracle: depending on whether the condition was true or false, the response ordering flipped between two known states. That is enough to ask the database anything, one true/false question at a time. It is like playing twenty questions with someone who will only answer "warmer" or "colder": you cannot see the answer, but you can narrow it down.

Using LENGTH() and ASCII(SUBSTRING(...)) inside the same CASE WHEN, the researcher extracted real values character by character:

SQL
sort_by=(CASE WHEN (LENGTH(DATABASE())=14) THEN CountyName ELSE CountyID END)
sort_by=(CASE WHEN (ASCII(SUBSTRING(DATABASE(),1,1))=119) THEN CountyName ELSE CountyID END)

Breaking these down:

  • DATABASE() asks the database for the name of the database currently in use.
  • LENGTH(...) returns how many characters that name has.
  • =14 is the guess being tested: is the name 14 characters long? If yes, the list comes back sorted by county name; if no, by county ID.
  • SUBSTRING(DATABASE(),1,1) takes the first character of the database name. The first number is the starting position, the second is how many characters to take.
  • ASCII(...) turns that character into a number, its character code. Every character has one; for example, the code 119 corresponds to the letter w.
  • =119 is the guess: is the first character's code 119? Again, the sort order tells you yes or no.

Repeating this for each position recovers the string one character at a time. First find the length, then test each position until the answer is yes, then move to the next position. It is slow by hand, which is why the next step matters.

Using this technique, the researcher recovered:

Item Value
Database name [REDACTED]
Current DB user [REDACTED]@[redacted]
DB server hostname [REDACTED]
Total tables in schema 155
Users table wp_users (confirmed to exist)
User account count 71

A schema here means the collection of tables in the database. wp_users was confirmed to exist in the database. All of it was obtained unauthenticated, meaning without logging in at all.

Why was this possible?

The root cause was simple: the sort_by value was being concatenated straight into the SQL ORDER BY clause with no allowlist and no validation. Concatenated means joined together as text, like gluing words into a sentence. The application effectively trusted:

Text
sort_by=<anything the client sends>

instead of checking:

Text
Is this one of the columns we actually allow sorting by?

The first line means the server accepted whatever text arrived in that parameter. The second line is the check that was missing: a short list of permitted column names, with everything else refused.

Prepared statements do not help here. A prepared statement keeps data values separate from the query's structure, but a column name or expression is part of that structure. That works for a value, such as a name or a number you are searching for, but not for a column name or an expression, because those are part of the query's structure. Without an explicit allowlist, anything goes.

The attack flow

The researcher laid out the whole process as a sequence:

Text
Send a normal request with a known sort_by value
        ↓
Confirm the ordering changes as expected
        ↓
Replace sort_by with a CASE WHEN boolean expression
        ↓
Observe which ordering comes back
        ↓
Use that as a true/false oracle
        ↓
Extract data character-by-character with LENGTH() / ASCII(SUBSTRING())
        ↓
Automate it

Each arrow means "then". The first step establishes what normal looks like. The second proves the parameter has an effect. The third and fourth turn that effect into a yes/no signal. The fifth and sixth turn the signal into readable data. The last step makes it practical at scale.

The researcher ended up scripting the whole extraction, in Python and PowerShell versions, so the triage team could reproduce it themselves without trusting a wall of manual curl commands. The script was written so the triage team could reproduce the extraction themselves.

Impact

This gave an unauthenticated attacker a reliable SQL injection primitive against the production database, with no rate limiting slowing it down. A primitive here means a basic capability that can be built on. Production means the live system, not a test copy. In practice that meant:

  • Extraction of database and server metadata. Metadata is information about the system itself, such as names.
  • Confirmation of internal table structure.
  • Ability to query user account counts from the wp_users table.
  • A clear path toward extracting further data, limited only by the permissions of the database user.

No login, no session, no prior access required: just the endpoint and a query string. A session is the state a site keeps after you log in so it remembers you; here there was none to begin with.

Disclosure

The researcher reported the vulnerability through HackerOne to the responsible program. It was validated, escalated to Critical severity, and the fix was later confirmed via retest. The report is now closed as Resolved.

From the original on medium.com

The write-up was shared for educational purposes, to show how something as small and overlooked as a sort parameter can turn into a full unauthenticated database extraction primitive when input is not validated against an allowlist.

Glossary

  • API: a way for programs to talk to a system, sending requests and receiving data rather than web pages.
  • Allowlist: a list of the only values that are accepted; anything else is refused.
  • ASCII: a numbering scheme that gives every character a number, used here to compare characters as numbers.
  • Authentication: proving who you are, usually by logging in.
  • Blind injection: an injection where you cannot see the database's output directly and must infer answers from a side effect.
  • Boolean: a yes/no value.
  • Boolean oracle: a way of asking a yes/no question and telling the two answers apart from outside the system.
  • Bug bounty program: an arrangement where a company invites outside testers to find and report security problems.
  • CASE WHEN: SQL's if/else expression, choosing one result when a condition is true and another when it is false.
  • Column: a heading in a database table, such as CountyName.
  • Concatenation: joining pieces of text together into one string.
  • Critical severity: the highest level in a common severity scale for security issues.
  • curl: a command-line tool for sending web requests.
  • Database: an organised store of data, made of tables.
  • Endpoint: one specific address on a server that performs one specific job.
  • GET: the request type that asks a server to send data without changing anything.
  • HackerOne: a platform where bug bounty reports are submitted and tracked.
  • JSON: a text format for labelled values, commonly used by APIs.
  • LENGTH(): a SQL function that returns how many characters a string has.
  • Metadata: information about the system itself, such as names and versions.
  • ORDER BY: the part of a SQL query that says how to sort results.
  • Parameter (query parameter): a labelled value in a web address after the question mark, written name=value.
  • Prepared statement: a way of sending a query where data values are kept separate from the query's structure.
  • Primitive: a basic capability that can be built on.
  • Production: the live system used by real people, as opposed to a test copy.
  • Query: a request to a database, written in SQL.
  • Query string: the part of a web address after the question mark that carries parameters.
  • REST API: a common style of API where each address represents a thing and the request type says what to do.
  • Row: one record in a database table.
  • Sanitisation: cleaning or checking input before using it.
  • Schema: the collection of tables in a database.
  • Session: the state a site keeps after you log in so it remembers you.
  • Severity: how serious a security issue is judged to be.
  • SQL: the language used to ask a database for data.
  • SQL injection: putting unchecked user input into a database instruction so that the input changes the instruction.
  • SUBSTRING(): a SQL function that takes part of a string, given a starting position and a length.
  • Table: a set of data in a database, arranged in columns and rows.
  • Triage: the first review a security report receives.
  • Unauthenticated: done without logging in.
  • Validation: checking that input is acceptable before using it.
  • WordPress: a popular system for building websites, with a built-in API under wp-json.
  • wp_users: the standard WordPress table that stores user accounts.

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.