PHP code snippet showing a vulnerable SQL query
PHP code snippet showing a vulnerable SQL query

Mastering SQL Injection Exploitation with Sqlmap: A Comprehensive Guide

SQL injection, a long-standing and notorious vulnerability, remains a significant threat in the cybersecurity landscape of 2024. It consistently appears in penetration testing reports and continues to be a major concern.

The prevalence of SQL injection is underscored by the fact that over 2159 CVEs were attributed to SQL injection vulnerabilities in 2023 alone, a noticeable increase from 2022. Furthermore, SQL injection holds the third position in the OWASP Top 10 list, highlighting its critical and widespread nature in web application security risks.

Exploiting SQL injection vulnerabilities to fully understand their impact can be a complex and time-consuming process. Fortunately, the open-source community has developed powerful tools like sqlmap to streamline and simplify this task.

This article aims to provide a detailed exploration of SQL injection principles and a comprehensive guide on utilizing sqlmap, complete with practical examples. For those searching for guidance on “Cara Setting Proxy Di Simple Sqli Dork Scanner” (a phrase which may relate to proxy configurations in security scanning), this article, while not directly addressing that specific Indonesian phrase, will provide valuable insights into using proxies within the context of SQL injection testing using a powerful tool like sqlmap.

Comprehensive Guide to Sqlmap

Understanding SQL Injections (SQLi): A Refresher

Let’s begin by defining SQL. Structured Query Language (SQL) is a specialized language designed for interacting with databases, enabling users to manage and manipulate data stored within them.

SQL is the backbone for data management in most web applications. However, vulnerabilities known as SQL injection (SQLi) can arise depending on how these applications are implemented and how they handle SQL queries.

Defining SQLi

SQL injection (SQLi) is a type of cyberattack that targets relational databases used by web applications, such as MySQL, Oracle Database, and Microsoft SQL Server. It’s important to distinguish this from NoSQL injections, which target non-relational databases like MongoDB or CouchDB.

Consider this example of PHP code:

In this code, the variable $id is directly assigned the value of the id parameter from the URL. Critically, this $id variable is then concatenated directly into the SQL query on the subsequent line.

Because the id parameter is user-controlled, a malicious actor can inject SQL code through the URL’s id parameter, allowing them to perform unauthorized actions on the web application’s database.

For instance, an attacker might inject a 5-second delay into the id parameter to test for SQL injection:

SQL injection example in the id parameter of the URL

On the server-side, the resulting SQL query would look like this:

This injection causes the server to pause for 5 seconds before responding, confirming the presence of an SQL injection vulnerability.

The Severity of SQLi Impact

SQL injection vulnerabilities often carry a critical risk level. If the database user permissions are sufficiently broad, which is frequently the case, a successful SQLi attack can enable an attacker to extract the entire database. In some scenarios, it can even lead to complete server compromise.

Types of SQLi and Prevention Strategies

SQL injection vulnerabilities manifest in various forms, depending on the injection point and the exploitation methods. Here are some common SQLi types:

  • UNION-based SQLi
  • Boolean-based blind SQLi
  • Error-based SQLi
  • Stacked queries SQLi
  • Time-based blind SQLi

The most effective defense against SQL injection attacks is the use of “prepared statements.” Prepared statements pre-define the structure of SQL queries before incorporating any variables. This approach ensures that even if an attacker controls a variable, they cannot inject malicious SQL code because the query’s structure is already fixed.

For a more in-depth understanding of SQL injection, including detailed case studies and best security practices, refer to our comprehensive article: SQL injections (SQLi): principles, impacts, exploitations and security best practices.

How Sqlmap Automates SQL Injection Exploitation

While manual exploitation of SQL injection vulnerabilities and database exfiltration is possible, it is significantly more efficient to utilize automated tools and scripts.

For those seeking efficiency and avoiding reinventing the wheel, sqlmap stands out as an invaluable tool.

What is Sqlmap?

Sqlmap is a powerful open-source tool designed to automate the processes of detecting and exploiting SQL injection vulnerabilities. It is a feature-rich tool offering a wide array of options, capable of even compromising the SQL server under specific conditions.

Important Note: Sqlmap can generate substantial network traffic. Using sqlmap for penetration testing without explicit authorization from the system owner is illegal.

Step-by-Step SQLi Exploitation with Sqlmap

In penetration testing engagements, sqlmap is typically employed after an SQL injection vulnerability has been initially identified. This approach minimizes unnecessary traffic generation. A standard sqlmap exploitation process involves several key steps.

Let’s break down these steps in detail.

Identifying a Suitable Payload for the SQLi Type

The initial step involves finding a payload that is appropriate for the specific type of SQL injection present. This payload will be crucial for subsequent database exfiltration.

Command:

The -r option instructs sqlmap to use the HTTP request contained within the specified file, which in this case is req.txt. This file holds the request containing the injection point. If the injection point is already known, as in this example, you can pinpoint it by adding an asterisk * at the precise location within the request where the SQL injection is to be injected.

Here, the attacker is aware that an SQL injection is likely within the value of the TrackingId cookie.

Alternatively, the -u option can be used to directly specify a URL if the SQL injection vulnerability is located within a URL parameter.

Result:

After conducting various payload tests, sqlmap successfully identifies the type of SQL injection:

The identified SQL injection type is “stacked query time-based blind.” This indicates that data exfiltration will rely on time delays, as direct retrieval of SQL injection results is not possible. The “stacked query” designation means the injection involves adding a new query after the original one.

Simultaneously, sqlmap also determines the database management system (DBMS) in use, which is PostgreSQL. With this critical information, sqlmap can now tailor its payloads to match both the injection type and the specific DBMS for efficient data exfiltration.

Database Name Enumeration

The next step involves enumerating the database names. To save time, this step can often be performed concurrently with the initial payload identification.

Command:

To list database names, append the -dbs option to the sqlmap command.

Result:

In this instance, only one database, named “public,” is discovered.

Table Name Listing

With the database name (“public”) identified, the third step is to list the table names within this database.

Command:

The -D option specifies the target database, “public” in this case, and the -tables option instructs sqlmap to enumerate the table names within the “public” database.

Result:

Two tables are found: “tracking” and “users.” The “users” table appears to be particularly interesting, potentially containing user-related data.

Selecting a Table for Column Enumeration

The fourth step involves choosing a table to investigate further. To understand the table’s structure, we list its columns.

Command:

The -T option specifies the target table, “users,” and the -columns option is used to list the column names within the “users” table.

Result:

Data Extraction from the Table

The fifth and final step is to extract the data from the chosen table. Having examined the columns of the “users” table, we can decide to dump all data from the table or focus on specific columns. In this example, we choose to extract data from the “username” and “password” columns.

Command:

The -C option allows us to specify the columns we want to extract, separated by commas (in this case, “username,password”). The -dump option initiates the data exfiltration process.

Result:

Through these steps, we successfully extracted usernames and passwords for all users on the platform using sqlmap.

Retrieving System Information with Sqlmap

To gain a deeper understanding of the compromised environment, it is beneficial to retrieve system-level information related to the database system. Sqlmap provides options to retrieve:

  • The current database system user
  • DBA (Database Administrator) role status for the current user
  • Hostname of the database server
  • List of all database system users
  • Privileges of all database system users

Below are the sqlmap commands and their results for retrieving this information:

Current Database System User

Command:

Result:

Is Current User DBA?

Command:

Result:

Hostname

Command:

Result:

List of Database System Users

Command:

Result:

Privileges of Database System Users

Command:

Result:

Sources for labs on Portswigger

Exploiting Blind SQL Injections with Sqlmap

In blind SQL injection scenarios, the results of the SQL injection are often not directly visible in the application’s response. So, how does sqlmap manage to extract data in such situations?

Blind SQL injections rely on identifying conditions that produce different server responses based on whether the injected condition is true or false. For example, in Boolean-based blind SQLi, the server response will vary depending on the truthiness of a Boolean condition within the injected query:

If the server response differs based on the condition’s truth value, this difference can be exploited to extract data character by character. This process involves iteratively determining each character of database names, tables, columns, and finally, the data itself.

Consider this example of a Boolean-based blind SQLi:

Boolean-based blind SQLi example

The complete server-side query would be:

Because the password indeed starts with “5,” the server responds differently compared to if another character or number was used.

We can then proceed to determine subsequent characters by incrementing the second parameter of the SQL SUBSTRING() function. This method is effective because we know the DBMS is PostgreSQL and the injection type is Boolean-based blind.

Sqlmap’s strength lies in its ability to automate and handle a wide range of SQL injection scenarios. It is a versatile tool capable of exploiting many SQL injection types beyond just blind injections. The following section explores some of sqlmap’s advanced options and the concept of “tamper” scripts.

Sqlmap Advanced Options

It’s not an exaggeration to call sqlmap a comprehensive SQLi tool. Running sqlmap -hh to display the full help documentation will quickly demonstrate the breadth and depth of its capabilities.

This section highlights some particularly useful options for penetration testing, but exploring the full range of sqlmap’s features is highly recommended.

--proxy=

To gain a detailed understanding of sqlmap’s interactions with the target application, you can route all sqlmap traffic through a proxy. This allows you to inspect each request and response. A popular tool for this purpose is Burp Suite.

Using a proxy, as in “cara setting proxy di simple sqli dork scanner” scenarios where proxy configuration might be crucial, helps in troubleshooting unexpected sqlmap behavior by directly observing server responses to sqlmap’s requests. To set up a proxy in sqlmap, use the --proxy option followed by the proxy URL (e.g., --proxy="http://127.0.0.1:8080").

--delay=

Web applications often implement rate limiting to protect against abuse.

Sqlmap’s traffic intensity can trigger rate limiting mechanisms, leading to blocked requests. To circumvent this, the --delay option introduces a pause in seconds between each request sent by sqlmap.

Adjusting the delay can help bypass rate limiting, although it will increase the overall time required for data exfiltration.

--force-ssl

If a server exclusively accepts HTTPS and you are using a request file specified with -r, the --force-ssl option ensures that sqlmap uses HTTPS for all requests.

This simple yet critical option is essential for secure data exfiltration when HTTPS is required.

--threads=

When you are confident that the target server can handle substantial traffic, increasing the number of threads with the --threads option can accelerate data retrieval. However, use this option cautiously, as excessive threads can potentially overload and crash the SQL server.

--dbms=

For optimization, if you already know the database management system (DBMS) used by the target SQL server, specifying it with --dbms can significantly reduce the time needed for SQL injection type detection. Sqlmap will then focus its payload testing on those relevant to the specified DBMS.

--level=

The --level option controls the thoroughness of sqlmap’s tests. It ranges from 1 to 5 (default is 1). Higher levels trigger a broader range of payload testing.

This option is useful for complex SQL injection scenarios. If initial attempts with sqlmap are unsuccessful, increasing the --level value is often a good next step.

--risk=

Similar to --level, the --risk option defines the accepted risk level, from 1 to 3. Higher risk levels involve more aggressive payloads, increasing both the chances of detection and the potential for unintended consequences.

Depending on the injection point’s location within the original SQL query, higher risk levels could lead to data modification. The default risk level is 1.

--string=

In Boolean-based SQL injection cases, the --string option allows you to specify a string that sqlmap should look for in the server’s response when the injected condition is true.

As mentioned earlier, Boolean-based blind SQLi relies on server response variations based on the injected condition’s truth value. The difference might be as subtle as the presence of a specific string in the response, making --string a valuable option for accurate detection.

--technique=

The --technique option gives you control over the types of payloads sqlmap tests and their order. An SQL injection can sometimes belong to multiple types simultaneously (e.g., both Boolean-based blind and time-based blind).

However, Boolean-based blind exploitation is typically faster than time-based blind. Using --technique, you can instruct sqlmap to prioritize specific SQLi types.

The possible values for --technique are:

  • B: Boolean-based blind
  • E: Error-based
  • U: Union query-based
  • S: Stacked queries
  • T: Time-based blind
  • Q: Inline queries

You can specify a single technique or a combination in a preferred order, which sqlmap will follow. The default order is BEUSTQ.

--file-read=

On certain DBMS like MySQL, PostgreSQL, or Microsoft SQL Server, the database user might have permissions to read files on the server’s file system. The --file-read option allows you to specify the path of a file to retrieve.

--os-cmd=

Similar to --file-read, the --os-cmd option enables executing operating system commands on the SQL server. This option is applicable to MySQL, PostgreSQL, and Microsoft SQL Server, and requires sufficient database user privileges.

--flush-session

By default, sqlmap maintains a session for each target, storing relevant information in memory.

This session allows sqlmap to resume exploitation quickly if the same query is repeated, as it retains payload details, database structure information, etc., avoiding the need to restart from scratch.

If you want sqlmap to start fresh on a target, use --flush-session once to clear the saved session data.

--tamper=

The --tamper option significantly enhances sqlmap’s flexibility. It allows you to specify one or more “tamper scripts” that modify payloads before they are sent to the target.

The following section delves into tamper scripts and provides practical examples.

For comprehensive information on all sqlmap options, consult the official wiki.

Sqlmap Tamper Scripts

Tamper scripts are designed to modify sqlmap payloads to bypass application filters or Web Application Firewalls (WAFs). For instance, a web application might restrict spaces in user inputs.

If a penetration tester identifies an SQL injection in such an input field, they need to bypass this space restriction to exploit the vulnerability. Tamper scripts address this. Sqlmap provides pre-built tamper scripts, and users can also create custom scripts for unique filtering scenarios.

To list available tamper scripts, use the command:

Command to list tamper scripts

Among the numerous pre-built tamper scripts, some notable examples include:

space2comment.py

This script replaces all spaces in a payload with comment sequences like /**/. Some database systems interpret these comments as spaces. This script can bypass basic “anti-SQLi” filters that simply block spaces in user inputs.

randomcase.py

The randomcase.py script randomizes the case of SQL keywords (e.g., SELECT, WHERE). SELECT might become SelEcT. Some filters or WAFs check for SQL keywords in user inputs to prevent SQL injection. However, poorly implemented filters might be bypassed by case randomization.

equaltolike.py

This script replaces all equals signs (=) in payloads with LIKE to bypass filters that disallow the equals sign in user inputs.

Multiple tamper scripts can be combined to bypass complex filter combinations.

Conclusion

Sqlmap is an indispensable tool for anyone involved in SQL injection detection and exploitation. Its extensive features cater to both basic and advanced needs, making it a powerful and essential asset for penetration testers. For individuals interested in “cara setting proxy di simple sqli dork scanner” and related security practices, understanding tools like sqlmap and their proxy configurations is a crucial step in mastering web application security testing.

Author: Lorenzo CARTE – Pentester @Vaadata

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *