To improve your web application penetration testing skills, it's important to learn how to detect SQL injection vulnerabilities.
This article delves into the principles and methods of testing that can uncover the details of this threat. We will explore manual testing techniques, such as analyzing URLs and forms, understanding user interaction and app processing.
Additionally, we'll provide real examples of SQL Injection payloads that you can use in your own tests. To further enhance your skills, we'll cover automation with tools like SQLmap and Burp Suite, offering insights from industry experts on modern techniques. You'll also gain knowledge on interpreting complex error messages which are crucial for identifying and resolving problems.
By mastering both basic and advanced techniques outlined in this article, you'll be able to improve the security of your applications and contribute to a safer digital environment
Understanding SQL Injections
SQL Injections are a computer vulnerability that can affect web applications and databases that use the SQL language. These attacks take advantage of vulnerabilities in input forms and URLs within applications. They intentionally insert harmful SQL statements into server requests.
The main goal of an SQL Injection attack is to control how the database works. This allows unauthorized access to sensitive data by extracting, changing, or deleting it.
SQL injection attacks can be divided into several categories. The most known are:
- Error-Based Injection: This technique involves inserting harmful inputs into a system's database to cause errors. These errors can potentially give you useful information.
- Union-Based Injection: The UNION operator allows you to combine the results of a harmful query and a valid query. This lets them access data from other tables without permission.
- Blind Injection: In this type of attack, the perpetrator does not receive a direct response from the server. Instead, they infer information about the system's behavior to gather data. Learn more in our article “Blind SQL Injection: An Expert’s Guide to Detect and Exploit.”
- Time-Based Blind Injection: This technique involves intentionally adding delays to queries in order to check the accuracy of specific conditions. By analyzing the error messages, you can extract valuable information about the database, aiding in further exploitation, such as discovering table names or system details, without raising any alarms or suspicion.
Manual SQL Injection Testing
Let's now dive into manual SQL injection testing techniques by closely examining the URL structure. By doing so, we can identify potential vulnerabilities and exploit them for the purpose of security assessment.
Analyzing URL Structure
During the manual SQL injection testing process, a deep analysis of the URL structure is essential for identifying and assessing vulnerabilities in web applications. This approach involves identifying weaknesses in the application by intentionally injecting malicious SQL code through parameters found within URLs.
In order to analyze the vulnerability of a website to SQL injection attacks, it is important to identify any user input that is conveyed through the URL parameters. These parameters can potentially serve as entry points for you. Once these parameters are identified, testing their manipulability becomes crucial.
This involves inserting various test strings, special characters, and escape sequences to determine if the application properly handles such inputs without generating errors.
Another important step is to thoroughly examine the error messages produced by the application. These messages can inadvertently expose internal vulnerabilities in the system, potentially uncovering SQL injection weaknesses.
For example, in the above image, you can see an error generated by manipulating the user parameter in the URL, which helps us to identify the specific SQL query that is causing the error. This could then be used to try to exploit the vulnerability that is causing the error or launch a Denial of Service Attack (DoS) on the website by sending too many invalid SQL queries.
To go more in-depth with testing this kind of URL, you can try to identify where user input is inserted into the SQL query. This can be an input field, a variable in the URL, or any form of user input.
To get started, you can use a basic SQL payload like this:
' OR '1'='1
Insert this payload into the suspect input and see if the SQL error message disappears. If the error message disappears or different behavior occurs, it could be a sign that the site is vulnerable to an SQL injection attack.
If the basic payload does not produce significant results, you may want to experiment with more advanced SQL payloads such as UNION-based or time-based blind SQL injection. For example, a UNION-based payload you could try is:
' UNION SELECT null, username, password FROM users--
This kind of payload tries to extract information from the users table. However, be careful when using advanced payloads like this one, as they may negatively impact the site you’re testing, if not used correctly.
To summarize, analyzing the URL structure in manual SQL injection testing can help identify potential vulnerabilities and assess an application's ability to handle malicious inputs, giving you important data to continue with your pentest.
Form Fields and Validation Mechanisms
Form fields in a web application serve as an entry point for user input. You can exploit these fields through SQL injections, where you inject harmful SQL code. These form fields are commonly used to collect important user data, such as names, e-mail addresses, passwords, and more.
Combining well-designed form fields with robust validation mechanisms can effectively mitigate the risk of SQL injections. For instance, an email field should strictly accept only valid email addresses, preventing the insertion of special characters that could potentially manipulate SQL queries. This is not always the case, and is subject to abuse.
Testing to see if the form will accept special characters or non-typical input can indicate the potential to send malicious commands or requests to the database.
When manually testing for SQL injection vulnerabilities, existing security measures like user input validation can sometimes impede the injection process. In such cases, it is worth exploring basic payloads, such as inserting
'OR 1=1-- into the input field; this type of payloads are called bypass payloads, because they use a condition which is always true to manipulate a vulnerable input and bypass authentication, access unauthorized data, or execute malicious commands.
While input validation is an important safeguard, it is not always foolproof, so to identify any potential vulnerabilities, it is essential to conduct complete and comprehensive testing.
Cookie Values and HTTP Headers
In manual SQL injection testing, you may manipulate requests by exploiting cookie values and HTTP headers of a web application. These elements are considered external inputs, so it is important for you to do adequate testing with the correct tools (like Burp Suite).
Cookies, which contain information stored in a user's browser, can be vulnerable to manipulation. A common method is injecting harmful SQL code by altering the data within a cookie.
If a cookie is used, for example, to store a user ID in an application, you may try to modify that ID within the cookie itself. This type of exploitation could lead to unauthorized access to sensitive data or functions.
For instance, consider an application that utilizes a cookie to keep tabs on the currently logged-in user. Now, let's suppose that a hacker with malicious intents succeeds in tampering with this cookie by altering the user ID it contains.
If the application fails to adequately address this modification, it might unintentionally generate a harmful SQL query based on the manipulated ID. This could potentially grant unauthorized access to sensitive data.
Furthermore, when a browser sends a request to an application, it includes HTTP headers such as User-Agents. You (attacker) can tamper these headers by inserting harmful strings into the requests. For example, you could use the following payload:
'UNION SELECT null, username, password FROM users--
This payload is designed to extract data from a database's "users" table. Let's say you have an HTTP GET request that includes an "cat" parameter into which to place the payload.
In the "HTTP Request" tab of Burp Suite, change the "cat" parameter so that it contains the payload, for example:
cat=' UNION SELECT null, username, password FROM users--
Start sending the request and observe the response. If the site is vulnerable to a UNION-based SQL injection, you will get a response that includes information from the "users" table.
In both cases, ensuring the application securely handles cookie values and HTTP headers is essential. Manual testing involves analyzing the impact of such manipulations on application inputs and verifying its response to potential SQL injection attacks.
User Controlled Input (UCI) Processed by Application
When manually testing for SQL injection vulnerabilities, the concept of "User Controlled Input” or UCI, refers to any input that is provided by the user and subsequently processed by the application. This can include data entered into form fields, cookie values, parameters in URLs or HTTP headers (that we already saw before). You can take advantage of these opportunities to inject malicious SQL code and cause extensive damage.
In this approach, you intentionally manipulate the provided input to insert special characters or escape sequences (like
=). These manipulations can alter the SQL queries generated by the application and exploit vulnerabilities in its input processing. The aim is to trick the application into executing unintended SQL queries, resulting in unauthorized data extraction or system compromise.
Must Have List of SQL Injection Payloads
Payloads are snippets of code that are intentionally inserted into input fields of web applications. These snippets aim to exploit vulnerabilities in database management systems. Security professionals and penetration testers often utilize these tools to evaluate the level of resistance an application has against potential attacks.
- Basic SQL Injection payload:
' OR '1'='1(Used to bypass authentication by entering a condition that is always true.)
- Retrieving information:
' UNION SELECT null,username,password FROM users--(Used to extract sensitive data such as username and password from the database.)
- Query manipulation:
'; DROP TABLE users; --(Used to cause the deletion of the "users" table.)
- Get the table names:
' AND 1=0 UNION SELECT table_name, null FROM information_schema.tables--(Used to extract the names of the tables in the database.)
- Extract database name:
' AND 1=0 UNION SELECT null, database()--(Used to extract the name of the current database.)
- Using UNION to extract data:
' UNION SELECT username, password FROM users--(Used to extract sensitive data through a UNION operation.)
- Using comments to bypass:
admin' --(Uses a comment to bypass the rest of the input and log in as administrator.)
- Using Time-Based Blind SQLi:
' OR IF(1=1, SLEEP(5), 0)--(Delays server response to confirm SQL injection vulnerability).
- Using Error-Based SQLi:
' AND 1=CONVERT(int, (SELECT @@version))--(Forces a SQL error to reveal database information).
All these payloads can be used (and are the most effective) in vulnerable login forms, URLs (used as malicious queries) and requests (captured and modified by you with the correct payload).
Automated SQL Injection Testing
When it comes to information security, tools like SQLmap and Burp Suite are highly regarded in the field of SQL injection testing.
Tools Overview: SQLmap and Burp Suite
These tools are widely used by security professionals and provide effective automated solutions for detecting and exploiting SQL injection vulnerabilities in web applications.
While SQLmap specializes in advanced testing and automation, Burp Suite offers a complete ecosystem for analyzing application security. It allows experts to identify, evaluate, and address critical vulnerabilities, including those related to SQL injection attacks.
Now let's see in detail what these tools are for and why they are used:
- SQLmap: It’s a valuable open-source tool that automates SQL injection tests. It effectively detects vulnerabilities, extracts data, and compromises database systems using a variety of payloads and techniques. Penetration Testers, mostly rely on SQLmap to assess application security.
- Burp Suite: It’s an all-inclusive set of tools designed for web application security. Among its features, the tool includes a Web Application Security (WAS) module, which helps security specialists identify and address vulnerabilities in websites. This module can detect common security threats including, as you might expect, SQL injection attacks.
Running SQLmap to Find and Exploit SQL Injections
Now, let's use SQLmap to systematically uncover SQL Injection vulnerabilities on a purposely vulnerable website. Our target will be VulnWeb (http://testphp.vulnweb.com), a website designed specifically for Cyber Security students to learn by attacking and exploiting its vulnerabilities.
If you come across a web URL like, in this case, http://testphp.vulnweb.com/listproducts.php?cat=1, where the 'GET' parameter is highlighted, it could indicate that the website is susceptible to SQL injection attacks. In such cases, you may be able to access sensitive information from the database. It's known that SQLmap is the most effective in scenarios involving PHP-based websites.
Step 1: Assessment of the URL’s parameter
A straightforward way to determine if your website is vulnerable is by replacing the value in the get request parameter with an * (asterisk).
This kind of error, suggests that the website is vulnerable to some type of SQL Injection attacks.
Step 2: Checking the URL with SQLmap
We need to input the desired web URL that needs to be checked, using the
-u parameter. Usually, the main objective is to determine if it's possible to access a database, so we can utilize the
--dbs option for this purpose. By using
--dbs, we can obtain a list of all available databases.
The first command will be:
sqlmap -u http://testphp.vulnweb.com/listproducts.php?cat=1 --dbs
Step 3: Understanding the output
In the above output, you can see in yellow the parts where SQLmap found SQL Injection vulnerabilities, and in orange the best payloads, suggested by SQLmap, to use that specific kind of SQL Injection (for example, the first vulnerability found is a boolean-based blind SQL Injection and the suggested payload is:
cat-1 AND 1050-1050).
Let’s take, for example, the last part of the output, highlighted in yellow, which says: “GET parameter ‘cat’ is ‘Generic UNION query’.
This part of the output tells us that the parameter “cat” of a GET request (which is the type of web request that, in this case, SQLmap is using to test the URL) inside “http://testphp.vulnweb.com/listproducts.php?cat=1” is vulnerable to a Generic UNION query.
But what is a Generic UNION query?
It’s an attack that typically involves manipulating the SQL query to combine the results of 2 or more database tables, allowing you to get unauthorized access to sensitive data.
In summary, this SQLmap output suggests that further testing is needed to confirm if the 'cat' parameter is indeed vulnerable to a "Generic UNION query" SQL Injection attack. It's a signal to investigate and potentially exploit a vulnerability in the application's input validation (which is the part of the WebApp that checks and allows user’s input based on the query used).
And that’s why we can see, in the last piece of output highlighted in orange, that SQLmap suggests a specific payload, to manually test the vulnerable website for that type of SQL Injection Attack.
Analyzing Error Messages
During the process of error analysis in SQL injection testing, the errors generated by an application can offer important insights into the existence of vulnerabilities.
For instance, error messages that contain sensitive information like table names, blatant SQL syntax errors in the feedback from the application, and inconsistent responses such as missing or duplicate results can indicate potential query manipulation.
These error messages can offer valuable information about the internal workings of the system.
To trigger these messages, one can intentionally input malicious data that causes queries to fail.
In the above image, you can see a SQL Syntax Error (that we already mentioned before) that pops up following the changing of the cat parameter’s value from “1” to * (example of malicious input).
If you encounter SQL syntax errors, like the commonly seen "You have an error in your SQL syntax" (that we can see in the image), it typically signifies that the input is directly included in queries without proper verification. These kinds of errors often indicate internal system behavior and assist security experts in identifying possible weaknesses in applications.
To wrap up, SQL Injection testing is an essential tool for web application penetration testers. In this thorough exploration, we've dived into the fundamental principles and methodologies that allow us to uncover vulnerabilities. We've explored manual testing in detail, where a deep analysis of URLs, forms, and user interactions reveals potential weak spots.
When it comes to preventing SQL Injections, form fields and validation mechanisms are very important. However, sometimes these measures can hinder the testing process and skilled testers may need to use bypass payloads. Automated tools like SQLmap and Burp Suite prove invaluable in conducting thorough assessments.