SQL Injections
SQL Injections
5.6. SQLMap
The above code queries the database, asking for the name and the
description of a record in the products table. In this
example, the selected record will have id value equal 9.
Web Application Penetration Testing 3.0 – Caendra Inc. © 2018
In order to better understand SQLi, you need to know the basic
syntax of a SELECT statement:
https://www.w3schools.com/sql/sql_intro.asp
Example:
> SELECT Name, Description FROM Products WHERE ID='3' UNION SELECT
'Example', 'Data';
To perform the same tasks from within a web application, the application
must:
• Connect to the database
• Submit the query to the database
• Retrieve the results
$dbhostname='1.2.3.4';
Configuration
$dbuser='username';
$dbpassword='password'; Connection
$dbname='database';
Usage Submit
$id = $_GET['id'];
' OR 'a'='a
While the first condition is not met, the SQL engine will consider the
second condition of the OR. This second condition is crafted as an always
true condition.
In other words, this tells the database to select all the items in the
Products table!
This is not always the case; however, we will see later on that the
more powerful the DBMS, the more advanced the SQL is, and the
greater the capabilities of an attacker after an exploitation.
Example:
During and in-band attack the penetration tester finds a way to ask
the the web application for the desired information.
Error
Management
Error
Management
Example:
Even within the same DBMS, error messages change according to the
specific function the web application uses to interact with it.
Example:
You have an error in your SQL syntax. Check the manual that
corresponds to your MySQL server version for the right syntax to
use near [query snippet]
This is not always the case; sometimes you have to have educated
guesses in order to understand if a web app is vulnerable or not.
In the following slides, you will see how this approach cannot
defend a vulnerable application from SQL injection attacks.
The idea behind this process is simple yet clever, trying to craft
payloads which transform the web application queries into
True/False conditions. The penetration tester can then infer the
results of the queries by looking at how the application behavior
changes with different True/False conditions.
To demonstrate a Boolean
based SQLi detection, we
created a website hosting an
image gallery.
You will see how to use Boolean logic injections to test vulnerable
parameters and use SQLMap to perform basic SQLi exploitation.
We will also see, in detail, how to use SQL later in this module.
Example:
SELECT <field list> FROM <table> UNION SELECT <field list> FROM <another table>;
Users
user_id (int) Cc_num (int) CVS(int)
1 0000 1111 2222 3333 123
2 0123 4567 8901 2345 321
Users
user_id (int) Cc_num (int) CVS(int)
1 0000 1111 2222 3333 123
2 0123 4567 8901 2345 321
<?php
$rs=mysql_query("SELECT real_name FROM users WHERE id=".$_GET['id'].";");
$row=mysql_fetch_assoc($rs);
echo $row['real_name'];
?> SQL injection!
As you can see, there is a clear SQL injection in the id field of the
SQL query.
Note the use of the ALL operator. We used it to avoid the effect of
an eventual DISTINCT clause in the original web application query.
• MySQL error:
The used SELECT statements have a different number of columns
MS SQL error:
All queries in an SQL statement containing a UNION operator
must have an equal number of expressions in their target
lists
ERROR: each UNION query must have the same number of columns
• Oracle error:
SELECT field1, field2 FROM table where id='1138' UNION SELECT null, null; -- -
<remainder of the original query>
Example:
In the next example, we will try to find the data types used in a
query.
Web Application Penetration Testing 3.0 – Caendra Inc. © 2018
Example:
• To:
This time, we’ll retrieve database names, schemas, and data from
the errors themselves. We will see some MS SQL Server specific
payloads and then introduce some attack vectors for other DBMSs.
The basic principle is the same across any DBMS.
This is the part of the SQL that will trigger the error.
Example:
Different MS SQL Server versions have different default column names in
the master database.
We can still dump all the databases to which user has access to.
So, the next step is enumerating the databases that user can
access.
• xtype='U'
• Means that we are only interested in user-defined tables
• name NOT IN ('<known table list>')
• name is a column of the "sysobjects" special table. Every time
we find a new table we will append it to the NOT IN list. This is
needed because the error displays only the first table name
You will see different ways to trigger errors, some applied payload
examples. Moreover, you will see how to submit your payload via
the browser and a command line utility.
So, we can try to trigger an always true condition and see what
happens.
Let’s see a way to find the current database user by using Boolean
based blind SQL injections.
In the SQLMap chapter, you will see how to automate the dumping
phase.
We will have to find text in the web page code that will only
appear for the correct guess; this will let us tell a match from a
mismatch.
We will have made a correct guess when the string Nokia will be
met in the output.
The charset will be our iteration space, so the smaller it is, the
sooner we will retrieve the correct value.
However, when building your own BSQLi shell scripts, you need to
keep the process as fast as possible.
ASCII(UPPER(SUBSTRING((<query>),<position>, 1)))=
ASCII(SUBSTRING((<query>), <position>, 1))
Example:
ASCII(LOWER(SUBSTRING((<query>),<position>, 1)))=
ASCII(SUBSTRING((<query>), <position>, 1))
If the SQL condition is TRUE, the DBMS will delay for 6 seconds.
You will also see how to write some scripts to automate the
exploitation.
We will first take a look at its basic features; then, we will move on
to advanced settings.
This tells SQLMap to test the id parameter of the GET request for
view.php. Moreover, it tells SQLMap to use a UNION based SQL
injection technique.
You can write the POST string by yourself or copy it from a request
intercepted with Burp Proxy.
You can also copy the POST string from a request intercepted with
Burp Proxy.
You will see how to use Boolean logic injections to test vulnerable
parameters and use SQLMap to perform basic SQLi exploitation.
To get around that, you can use the --string and --not-
string command line switches:
• Append to --string a string which is always present in
true output pages or
• Append to --not-string a string which is always present
in false output pages
Please note that the use of the -p switch bypasses the Level. This
means that by manually setting the parameter to test, you can
perform a more accurate, stealthy and in-depth exploitation.
In the following slides, you will see some mitigation strategies you
can propose to a client in your report.
Example:
if (!preg_match(|'^[a-z\s-]$|i', $name)) {
die('Please enter a valid name');
}
Users like dbo are not usually privileged enough to perform these
commands.
Once we have the SHA-1 hash of the password, we can crack it and
access the database in the same manner as a legitimate database
administrator.
So, we test it first and note the execution time. We then try with
another host.
• If errors are hidden, and the port is closed, the connection will
timeout according to the <connection timeout in
seconds> value.
The victim server will connect to our SQL server, read the exe file
from the table and recreate it remotely.
create table temptable (id int not null identity (1,1), output
nvarchar(4096) null);--
As you will see in the next step, we need to convert the command
string of the command we want to run into an ASCII
representation.
And then insert a double zero after every character of the string.
0x640069007200200063003a005c00
You can use the id field of the temptable table to choose which
command result you want to retrieve.
https://dev.mysql.com/doc/refman/5.1/en/privileges-provided.html#priv_file
By using this method, you can convert any binary file to a long hex
string that you can use to steal any data from the server.
Example:
+--------------------------------------------------------------------------------+
| output |
+--------------------------------------------------------------------------------+
| root:x:0:0:root:/root:/bin/bash |
| daemon:x:1:1:daemon:/usr/sbin:/bin/sh |
| bin:x:2:2:bin:/bin:/bin/sh |
| sys:x:3:3:sys:/dev:/bin/sh |
| sync:x:4:65534:sync:/bin:/bin/sync |
| games:x:5:60:games:/usr/games:/bin/sh |
| . . . |
+--------------------------------------------------------------------------------+
But, how can you load a binary file into a table via SQL injections?
You have to convert it into an hex-string.
Example:
mysql> LOAD DATA INFILE '/tmp/ls.dmp' INTO TABLE mytable FIELDS TERMINATED BY 'sOmErandOM'
LINES TERMINATED BY 'oTHerRnD' (data);
Query OK, 1 row affected (0.01 sec)
Records: 1 Deleted: 0 Skipped: 0 Warnings: 0
You need to split the DUMPFILE you created into chunks of 1024
bytes and then insert them into a table field.
First, you have to perform an insert with the first chunk. Next, you
have to update the field by adding the other chunks.
SELECT <victim field> FROM <victim table> WHERE <optional conditions> INTO
DUMPFILE '<output path>';
You can find the source code of those functions here. Moreover,
you can find the compiled versions on the SQLMap repository.
http://www.mysqludf.org/
https://github.com/sqlmapproject/sqlmap/tree/master/udf/mysql
Web Application Penetration Testing 3.0 – Caendra Inc. © 2018
After uploading the files to the target system, running a command
is just a matter of performing a SELECT:
SELECT sys_eval('<command>');
SELECT sys_exec('<command>');
http://pentestmonkey.net/cheat-sheet/sql- http://www.amazon.com/The-Web-Application-
injection/mssql-sql-injection-cheat-sheet Hackers-Handbook/dp/1118026470