Panel Discussion: API Security in DevSecOps. Register Now

Panel Discussion: API Security in DevSecOps. Register Now

Panel Discussion: API Security in DevSecOps. Register Now

SQL Injection: A Comprehensive Guide to Understanding SQL Injection Risks

SQL Injection (SQLi) is a type of attack where an attacker injects malicious SQL code into a vulnerable application's database query.

Author Image

Medusa

10 mins read

SQL Inection
SQL Inection
SQL Inection

In 2008, Heartland Payment Systems experienced a significant data breach. The incident involved the exploitation of an SQL injection vulnerability by attackers, who were able to gain unauthorized access to the company's payment processing system. As a result, the attackers were able to steal millions of credit card numbers, which had a severe impact on the company's reputation and financial stability. The breach not only resulted in significant financial losses for Heartland and its customers but also served as a wake-up call for other organizations to take data security more seriously.

This blog covers the following topics related to SQL Injection:

  • Understanding SQL Injection

  • Types of SQL Injection attacks

  • Techniques used by attackers to perform SQL Injection

  • Demonstration of SQL Injection attack

  • SQL Prevention

What is SQL Injection?

SQL Injection is a type of attack where an attacker injects malicious SQL code into a vulnerable application's database query. This can result in unauthorized access to sensitive data, modification of data, or even complete loss of data. SQL Injection attacks are one of the most common types of attacks against web applications and can have serious consequences for organizations that fall victim to them.

"Key takeaway: In SQL Injection attacks, a communication channel means the way an attacker talks to a weak application's database to insert harmful SQL code. It could use the same way the application talks to the database normally, or the attacker might choose a different way like email or an external website to get the results of the injected code."

Types of SQL Injection

  • In-band SQL Injection: In-band SQL injection is a common way attackers inject malicious SQL code into a vulnerable application's database query. The attacker uses the same channel to perform the attack and gather results. There are two sub-types: error-based and union-based SQL injection.

    • Error-based SQL Injection

    • Union-based SQL Injection

  • Out-of-band SQL Injection: In this type of attack, the attacker uses a different communication channel to perform the attack and gather the results. This can be further divided into two sub-types:

    • Time-Based SQL Injection

  • Boolean-based SQL injection: Boolean-based SQL injection, also known as inferential SQL injection, is an attack that relies on sending SQL queries to the database that force the application to return a different result depending on whether the query returns a true or false result. This can be further divided into two sub-types:

    • Simple or Direct

    • Indirect or Complex

  • Time-based SQL Injection: This type of attack involves delaying the server's response to infer information about the database. For instance, an attacker might send a query like "SELECT SLEEP(5);" to delay the response for five seconds and confirm that the database is vulnerable.

SQL Injection examples:

If you are interested in a live practical demonstration, check out this YouTube video!

Attackers can use various techniques to perform SQL Injection attacks. Some of the most common examples include:

Manual SQL Injection:

This is the most basic technique and involves manually injecting SQL code into an input field or URL parameter. Attackers will often use tools such as SQLMap or Havij to automate this process. Example:

Suppose a website has a search bar that allows users to search for products by name. The search query might look something like this:

SELECT * FROM products WHERE name LIKE '%search_term%';

An attacker might enter the following into the search bar:

‘ OR 1=1;--

This would result in the following query:

SELECT * FROM products WHERE name LIKE '%' OR 1=1;--%';

The double dash -- at the end of the query is a comment in SQL and will cause the rest of the query to be ignored. The resulting query will return all products in the database since 1=1 is always true.

Error-based SQL Injection:

This technique involves injecting SQL code that causes the database to generate errors. The attacker can then use these errors to gather information about the database schema or even extract data.

Here is an example query for searching for products from a search bar.

SELECT * FROM products WHERE name LIKE '%search_term%';

An attacker might enter the following into the search bar:

' OR 1=1;SELECT * FROM nonexistent_table;--

This would result in the following query:

SELECT * FROM products WHERE name LIKE '%' OR 1=1;SELECT * FROM nonexistent_table;--%';

The query now includes a second SELECT statement that will cause an error since nonexistent_table does not exist. However, the attacker can still use this error to infer information about the database schema, such as the names of tables or columns.

Union-based SQL Injection:

This technique involves injecting SQL code that uses the UNION operator to combine the results of two or more SELECT statements. The attacker can then use this technique to extract data from the database.

An example of a union-based SQL Injection query might look something like this:

SELECT name, email, password FROM users WHERE id = 1 UNION SELECT cc_number, NULL, NULL FROM credit_cards LIMIT 1;

In this example, the attacker is attempting to extract credit card information from the database by using the UNION operator to combine the results of two SELECT statements. The first SELECT statement selects the user's name, email, and password, while the second SELECT statement selects the credit card number from the credit_cards table. The LIMIT 1 clause at the end of the query ensures that only one row is returned, since the attacker may not know how many rows are returned by the first SELECT statement.

The attacker can potentially extract sensitive information from the database by injecting this query into a vulnerable application's database query.

Blind SQL Injection:

This technique involves injecting SQL code that does not generate any visible output. The attacker can then use techniques such as time delays or boolean logic to infer information about the database.

SELECT * FROM users WHERE username = 'admin' AND SUBSTRING(password, 1, 1) = 'a';

In this example, the attacker is attempting to determine if the first character of the admin user's password is "a". If the database returns a result, the attacker knows that the first character of the password is "a". The attacker can continue this process, guessing one character at a time, until they have determined the entire password.

Second-order SQL Injection:

This technique involves injecting SQL code that is not executed immediately, but is stored in the database for later use. When the code is executed at a later time, it can be used to perform a SQL Injection attack.

An example of a second-order SQL Injection query might look something like this:

Suppose a vulnerable web application allows users to submit feedback, and the feedback is stored in a database table called "feedback". The application also has a feature that allows users to view their own feedback by entering their email addresse. The query for retrieving the feedback might look something like this:

SELECT * FROM feedback WHERE email = 'user@example.com';

An attacker might submit feedback containing malicious SQL code that is not executed immediately but is stored in the "feedback" table for later use. For example:

' OR 1=1; INSERT INTO users (username, password) VALUES ('attacker', 'p@ssw0rd');--

This SQL code will create a new user with the username "attacker" and the password "p@ssw0rd" when a user with the email address "user@example.com" views their feedback. The attacker can then use this account to perform further attacks.

Check out this SQL Injection cheat sheet and SQL payloads.

Test for SQL Injection using the best proactive API Security product

Our customers love us for our proactive approach and world class API Security test templates. Try Akto's test library yourself in your testing playground. Play with the default test or add your own.

Test for SQL Injection using the best proactive API Security product

Our customers love us for our proactive approach and world class API Security test templates. Try Akto's test library yourself in your testing playground. Play with the default test or add your own.

Test for SQL Injection using the best proactive API Security product

Our customers love us for our proactive approach and world class API Security test templates. Try Akto's test library yourself in your testing playground. Play with the default test or add your own.

SQL Injection example with Practical Demonstration

I have imported an API collection into Postman for testing.

SQL Injection example

As shown in the screenshot above, there is an API endpoint that allows users to log in, and the server provides an authentication token.

There is an additional API endpoint that allows users to retrieve information about their accounts. This endpoint uses the username as an identifier in the URL path and provides the information in JSON format.

endpoint uses name as identifier

Additionally, you may notice that the endpoint path uses :username instead of an actual username. That's the path variable, which will be replaced with a different value when we send the request. In this case, the value of the username variable is "name1", which you can view in the path variables section.

In Postman, path variables are variables that are used in the URL path of a request. They are denoted by a colon followed by the variable name.

The server returns the username and email of the authenticated user who requested it in the response.

Testing SQL Injection

To check if the system is vulnerable to SQL Injection, inject a single quote after the value of "name1" in the "path variable" section or directly in the endpoint if you don't have a path variable set.

Why quote?

The reason is that SQL queries are often constructed by concatenating strings of text. If an attacker can inject a single quote into one of these strings, they can break out of the string and inject their own SQL code. By injecting a single quote, the attacker can test whether the application is vulnerable to SQL Injection attacks.

test SQL Inection

Interesting! The response contains an error that appears to be related to SQLite, possibly due to an incorrect query.

Automation Using SQLMap

SQLMap is an open-source tool that automates the process of identifying and exploiting SQL Injection vulnerabilities in web applications. It can be used to perform a wide range of tasks, including identifying the type of database being used by a vulnerable application, extracting data from a database, and even taking control of a vulnerable system. SQLMap is highly configurable and can be used to perform attacks against a wide range of database systems, including MySQL, Oracle, and Microsoft SQL Server. It is one of the most popular tools used by penetration testers and ethical hackers to test the security of web applications.

Automate using SQL map

The command above simply takes the target URL and tries to find if it’s vulnerable or not.

  • -risk option specifies the risk level of the tests to perform. It is a value between 1 and 3, with 1 being the least aggressive and 3 being the most aggressive.

  • -level option specifies the level of tests to perform. It is a value between 1 and 5, with 1 being the least aggressive and 5 being the most aggressive. The higher the level, the more types of tests SQLMap will perform.

Based on the results, we can confirm that the database being used is SQLite and that it is vulnerable to SQL injection. The type of SQL injection vulnerability is boolean-based blind.

Results

Again with the same command, but running with an additional option: --dbms with a value of SQLite, and then --dump-all. This will dump all the table and their entries on the terminal.

dumped all the tables

There are two tables: users and books. The users table contains the email, username, and password of all registered users. As you can see, retrieving all of this sensitive information was not very difficult.

You can also use Akto to automate SQL Injection testing. For your custom cases, you can write YAML tests using Akto's test editor.

SQL Injection Prevention

By taking these steps, developers can significantly reduce the risk of SQL Injection attacks and protect their applications and databases from malicious actors.

  • Use parameterized queries or prepared statements instead of constructing SQL queries by concatenating strings of text.

  • Use an ORM (Object-Relational Mapping) library that can sanitize user input and protect against SQL Injection attacks.

  • Validate and sanitize all user input to ensure that it conforms to expected formats and does not contain malicious code.

  • Keep software and frameworks up to date with the latest security patches.

  • Regularly update your application's software, frameworks, and libraries to benefit from security patches and bug fixes. SQL Injection vulnerabilities discovered in older versions are often addressed in newer releases.

  • Implement a web application firewall (WAF) that can detect and block SQL Injection attacks.

In conclusion, understanding SQL Injection vulnerabilities is crucial for safeguarding the integrity of databases. By implementing strict input validation and using prepared statements, we can prevent potential attacks. Thank you for reading, your awesome support is truly appreciated. Keep up the great work in safeguarding valuable data!

Want to ask something?

Our community offers a network of support and resources. You can ask any question there and will get a reply in 24 hours.

Want to ask something?

Our community offers a network of support and resources. You can ask any question there and will get a reply in 24 hours.

Want to ask something?

Our community offers a network of support and resources. You can ask any question there and will get a reply in 24 hours.

Follow us for more updates

Experience enterprise-grade API Security solution