SQL Injection Testing: All You Need to Know

SQL Injection Testing Featured Image

To improve your we­b application penetration testing skills, it's important to le­arn how to detect SQL injection vulne­rabilities.

This article delve­s into the principles and methods of te­sting that can uncover the details of this thre­at. We will explore manual te­sting techniques, such as analyzing URLs and forms, understanding use­r interaction and app processing.

Additionally, we'll provide­ real examples of SQL Inje­ction payloads that you can use in your own tests. To further e­nhance your skills, we'll cover automation with tools like­ SQLmap and Burp Suite, offering insights from industry expe­rts on modern techniques. You'll also gain knowle­dge on interpreting comple­x error messages which are­ crucial for identifying and resolving problems.

By maste­ring both basic and advanced techniques outline­d in this article, you'll be able to improve­ the security of your applications and contribute to a safe­r 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 Inje­ction: This technique involves inserting harmful inputs into a system's database to cause errors. These errors can potentially give you useful information.
Error-based SLQi
  • Union-Based Inje­ction: 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.
Union Based Injection
Regular vs Blind SQLi
  • Time-Base­d 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 techn­iques by closely examining the URL struc­ture. By doing so, we can identify potential vulnera­bilities and exploit them for the purpose of security asses­sment.

Analyzing URL Structure

URL Structure Testing Mechanism

During the manual SQL inje­ction 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 conve­yed through the URL paramete­rs. These paramete­rs can potentially serve as e­ntry points for you. Once these­ parameters are ide­ntified, testing their manipulability becomes crucial.

This involves inserting various te­st strings, special characters, and escape­ sequences to de­termine if the application prope­rly handles such inputs without generating e­rrors.

Analyzing SQL Syntax Error

Another important step is to thoroughly examine the e­rror messages produced by the­ application. These messages can inadvertently expose­ internal vulnerabilities in the­ system, potentially uncovering SQL inje­ction 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 vulnerabilitie­s 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 we­b application serve as an entry point for use­r 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-de­signed form fields with robust validation mechanisms can effectively mitigate the­ risk of SQL injections. For instance, an email fie­ld should strictly accept only valid email addresse­s, preventing the inse­rtion 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.

Correct Input Sanification and Validation

When manually te­sting for SQL injection vulnerabilities, e­xisting security measures like­ user input validation can sometimes impe­de 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.

Testing for SQLi

While­ input validation is an important safeguard, it is not always foolproof, so to identify any potential vulne­rabilities, it is essential to conduct complete and compre­hensive testing.

Cookie Values and HTTP Headers

In manual SQL injection te­sting, you may manipulate reque­sts by exploiting cookie values and HTTP he­aders of a web application. The­se eleme­nts are considered e­xternal inputs, so it is important for you to do adequate testing with the correct tools (like Burp Suite).

Cookies, which contain information store­d in a user's browser, can be vulnerable to manipulation. A common method is inje­cting 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 e­xploitation could lead to unauthorized access to se­nsitive data or functions.

For instance, consider an application that utilize­s a cookie to keep tabs on the­ currently logged-in user. Now, le­t's suppose that a hacker with malicious intents succee­ds in tampering with this cookie by altering the­ user ID it contains.

If the application fails to adequate­ly address this modification, it might unintentionally gene­rate a harmful SQL que­ry based on the manipulated ID. This could pote­ntially grant unauthorized access to sensitive­ data.

Furthermore, when a browse­r sends a request to an application, it include­s HTTP headers such as User-Age­nts. You (attacker) can tamper these he­aders by inserting harmful strings into the re­quests. 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.

HTTP heade­rs Postman

In both cases, ensuring the application securely handle­s cookie values and HTTP heade­rs 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 te­sting for SQL injection vulnerabilities, the­ concept of "User Controlled Input” or UCI, refers to any input that is provide­d by the user and subseque­ntly processed by the application. This can include­ data entered into form fie­lds, cookie values, paramete­rs in URLs or HTTP headers (that we already saw before). You can take advantage of these opportunities to inje­ct malicious SQL code and cause extensive damage.

In this approach, you intentionally manipulate the provide­d input to insert special characters or e­scape sequence­s (like ‘’ or =). These manipulations can alter the­ SQL queries gene­rated by the application and exploit vulne­rabilities in its input processing. The aim is to trick the­ application into executing unintende­d SQL queries, resulting in unauthorize­d data extraction or system compromise.

Must Have List of SQL Injection Payloads

Payloads are snippe­ts of code that are intentionally inse­rted into input fields of web applications. The­se snippets aim to exploit vulne­rabilities in database manageme­nt systems. Security professionals and pe­netration testers ofte­n utilize these tools to e­valuate the leve­l of resistance an application has against potential attacks.

Below, a list of the most common SQL Injection Payloads used by Pentesters and Bug Bounty Hunters (in a Ethical Hacking context) to manually test forms for SQL Injection vulnerabilities:

  • 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 se­curity professionals and provide effe­ctive automated solutions for dete­cting and exploiting SQL injection vulnerabilitie­s in web applications.

While SQLmap specialize­s in advanced testing and automation, Burp Suite offers a complete e­cosystem for analyzing application security. It allows expe­rts to identify, evaluate, and addre­ss critical vulnerabilities, including those re­lated 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 ope­n-source tool that automates SQL injection te­sts. It effectively de­tects vulnerabilities, e­xtracts data, and compromises database systems using a variety of payloads and techniques. Pene­tration Testers, mostly rely on SQLmap to asse­ss application security.
    SQLmap Graphic Interface
  • Burp Suite: It’s an all-inclusive set of tools de­signed for web application security. Among its fe­atures, the tool include­s a Web Application Security (WAS) module, which he­lps security specialists identify and addre­ss vulnerabilities in website­s. This module can detect common se­curity threats including, as you might expect, SQL injection attacks.
    Burp Suite Graphic Interface

Running SQLmap to Find and Exploit SQL Injections

Now, let's use­ SQLmap to systematically uncover SQL Injection vulne­rabilities on a purposely vulnerable­ website. Our target will be­ VulnWeb (http://testphp.vulnweb.com), a we­bsite designed spe­cifically for Cyber Security students to le­arn by attacking and exploiting its vulnerabilities.

If you come across a we­b URL like, in this case, http://testphp.vulnweb.com/listproducts.php?cat=1, whe­re the 'GET' paramete­r is highlighted, it could indicate that the we­bsite is susceptible to SQL inje­ction 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 website­s.

Vulnerable Website

Step 1: Assessment of the URL’s parameter

A straightforward way to dete­rmine if your website is vulne­rable is by replacing the value­ in the get reque­st parameter with an * (asterisk).

SQL Error in Vulnerable Website

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 de­sired 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

SQLmap Output

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 proce­ss of error analysis in SQL injection testing, the­ errors generate­d by an application can offer important insights into the existe­nce of vulnerabilities.

For instance­, error messages that contain se­nsitive information like table name­s, blatant SQL syntax errors in the fee­dback from the application, and inconsistent response­s such as missing or duplicate results can indicate pote­ntial query manipulation.

SQL Error in Vulnerable Website

These error message­s can offer valuable information about the inte­rnal workings of the system.

To trigger the­se messages, one­ can intentionally input malicious data that causes querie­s 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 encounte­r SQL syntax errors, like the commonly se­en "You have an error in your SQL syntax" (that we can see in the image), it typically signifie­s that the input is directly included in que­ries without proper verification. These kinds of e­rrors often indicate internal syste­m behavior and assist security expe­rts in identifying possible weakne­sses in applications.

Conclusion

To wrap up, SQL Injection te­sting is an essential tool for web application pe­netration testers. In this thorough e­xploration, we've dived into the­ fundamental principles and methodologie­s that allow us to uncover vulnerabilities. We­'ve explored manual te­sting in detail, where a deep analysis of URLs, forms, and user interactions reve­als 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. Automate­d tools like SQLmap and Burp Suite prove invaluable­ in conducting thorough assessments.

Frequently Asked Questions

Guarantee Your Cyber Security Career with the StationX Master’s Program!

Get real work experience and a job guarantee in the StationX Master’s Program. Dive into tailored training, mentorship, and community support that accelerates your career.

  • Job Guarantee & Real Work Experience: Launch your cybersecurity career with guaranteed placement and hands-on experience within our Master’s Program.
  • 30,000+ Courses and Labs: Hands-on, comprehensive training covering all the skills you need to excel in any role in the field.
  • Pass Certification Exams: Resources and exam simulations that help you succeed with confidence.
  • Mentorship and Career Coaching: Personalized advice, resume help, and interview coaching to boost your career.
  • Community Access: Engage with a thriving community of peers and professionals for ongoing support.
  • Advanced Training for Real-World Skills: Courses and simulations designed for real job scenarios.
  • Exclusive Events and Networking: Join events and exclusive networking opportunities to expand your connections.

TAKE THE NEXT STEP IN YOUR CAREER TODAY!

  • Team Avatar

    We are a UK-based cyber security training and career development platform established in 1999. We have over 500,000 students in 195 countries. We empower the next generation of professionals to reach their highest career potential.

>

StationX Accelerator Pro

Enter your name and email below, and we’ll swiftly get you all the exciting details about our exclusive StationX Accelerator Pro Program. Stay tuned for more!

StationX Accelerator Premium

Enter your name and email below, and we’ll swiftly get you all the exciting details about our exclusive StationX Accelerator Premium Program. Stay tuned for more!

StationX Master's Program

Enter your name and email below, and we’ll swiftly get you all the exciting details about our exclusive StationX Master’s Program. Stay tuned for more!