SQL Injection(SQLi)

1. What it is

Definition

SQL Injection (SQLi), or SQL code injection, is a web security vulnerability that allows an attacker to interfere with the queries an application makes to its database. The attack involves injecting malicious SQL code through user-supplied input into SQL queries executed by the web application.

Essence of the Vulnerability

The essence of SQLi lies in the web application incorrectly processing or failing to validate user input, which is then directly concatenated with an SQL query. Instead of treating the entered data as ordinary values, the database interprets it as part of the SQL code, altering the original query logic. This happens when developers construct SQL queries by concatenating strings rather than using parameterized queries or prepared statements.

Why it is Dangerous

SQLi attacks are extremely dangerous because they provide an attacker with direct access to the database, which can lead to:

  • Unauthorized Data Access: Reading, modifying, or deleting sensitive information from the database, such as user credentials, financial data, personal information.

  • Authentication Bypass: An attacker can log in as any user, including an administrator, without knowing the password.

  • Complete System Compromise: In some cases, especially when using advanced SQLi techniques (e.g., SQLi using operating system functions), an attacker can execute commands on the server, potentially leading to full control over the system.

  • Data Integrity Violation: Modifying or deleting data in the database, which can cause serious business problems.

  • Disclosure of Internal Database Structure: An attacker can obtain information about tables, columns, and data types in the database.

Where it is Most Commonly Found

SQLi vulnerabilities are most commonly found in web applications that:

  • Use dynamically generated SQL queries: Applications that build SQL queries by concatenating strings that include user input.

  • Accept user input: Any input fields where a user can enter data that is then used in SQL queries (e.g., login fields, search, filtering, sorting, comments, feedback forms).

  • Insufficiently validate input: Applications that do not check or incorrectly check user input for special SQL characters.

  • Use outdated or misconfigured libraries/frameworks: Some older versions of ORMs or database libraries may be vulnerable if secure methods are not used.

  • In API endpoints: REST or SOAP APIs that accept parameters and use them in SQL queries without proper sanitization.

2. Types of Attack (Classification)

SQL Injection attacks are classified by the method an attacker uses to retrieve query results and interact with the database. There are three main categories:

Main Types

  • In-band SQLi (Classic SQLi): This is the most common and straightforward type of SQLi, where the attacker uses the same communication channel to inject malicious SQL code and retrieve results. Database responses are displayed directly in the web application.

    • Subtypes:

      • Error-based SQLi: The attacker causes database errors that contain information about the database structure or data. These error messages are then displayed in the web application's response.

      • Union-based SQLi: The attacker uses the UNION operator to combine the results of their malicious query with the results of a legitimate query. This allows extracting data from other database tables and displaying it on the page.

  • Inferential SQLi (Blind SQLi): In this type of attack, data is not directly transferred through the web application. Instead, the attacker sends SQL queries that cause the database to respond differently depending on the truth or falsity of a condition. The attacker infers the structure and content of the database by analyzing the web application's responses (e.g., response time or changes in page content).

    • Subtypes:

      • Boolean-based Blind SQLi: The attacker sends queries that return either TRUE or FALSE. Depending on the result, the web application either displays the page normally or shows an error/blank page. This allows the attacker to guess data character by character.

      • Time-based Blind SQLi: The attacker sends queries that cause the database to delay its response for a specific number of seconds if a condition is true. This allows the attacker to determine the truth of conditions based on the server's response time.

  • Out-of-band SQLi: This type of attack is less common and is used when the attacker cannot use the same channel for injection and result retrieval. Instead, it forces the database to send data to an external server controlled by the attacker, using database functions that can initiate external network requests (e.g., DNS requests or HTTP requests).

    • Implementation Features: Requires the database to have the ability to make outbound requests, which is not always possible due to security settings. Often used in conjunction with other techniques.

3. Mechanism of Operation

The mechanism of SQL Injection is based on manipulating SQL queries that a web application sends to the database. The attacker exploits vulnerabilities in user input processing to alter the logic of these queries.

How the Attack Occurs

  1. Identify Input Point: The attacker finds a web application that accepts user input (e.g., login fields, search, URL parameters) and uses it to form SQL queries.

  2. Inject Malicious SQL Code: Instead of expected data, the attacker enters a specially crafted string containing SQL syntax. This string is "injected" into the query.

  3. Change Query Logic: The web application, without proper validation or escaping, concatenates the user input with part of its SQL query. As a result, the database executes the modified query, which can perform actions not intended by the developer.

  4. Retrieve Results: Depending on the type of SQLi, the attacker can obtain attack results in various ways: directly in the web application's response (In-band), by analyzing application behavior (Inferential), or by initiating external network requests (Out-of-band).

What the Vulnerability is Based On

The SQLi vulnerability is based on a fundamental violation of the separation of data and code. When user input is directly concatenated with an SQL query, without adequate processing, it becomes part of the executable SQL code. The main reasons are:

  • Dynamic Query Formation: Using string concatenation to build SQL queries, instead of parameterized queries or prepared statements.

  • Insufficient Input Validation: The application does not check or incorrectly checks data coming from the user, allowing the injection of special SQL characters (e.g., single quotes ', double quotes ", comment characters --).

  • Lack of Special Character Escaping: Characters that have special meaning in SQL syntax are not properly escaped, allowing them to alter the query structure.

How Web Applications Process This Data

In vulnerable web applications, data is processed as follows:

  1. The user enters data into a form (e.g., username admin).

  2. The application takes this input and inserts it directly into an SQL query, for example: SELECT * FROM users WHERE username = 'admin';

  3. If the attacker enters admin' OR '1'='1, the query becomes: SELECT * FROM users WHERE username = 'admin' OR '1'='1'; This query will always be true, allowing authentication bypass.

In secure applications, before using user input in SQL queries, the following methods should be applied:

  • Parameterized Queries (Prepared Statements): This is the primary and most effective defense method. In this case, the SQL query is defined in advance, and then parameter values are passed separately. The database distinguishes code from data, preventing injections.

  • Escaping: If parameterized queries cannot be used, all special characters in user input must be escaped so that they are interpreted as data, not as part of the SQL code.

  • Input Validation: Checking user input against the expected format and data type.

Impact of User Input

User input is the primary vector for SQLi attacks. The attacker manipulates the input so that it contains not only data but also executable SQL code. This can be:

  • Form Fields: Login, password, search fields, comments, feedback forms.

  • URL Parameters: Query parameters in GET requests that are then used in SQL queries.

  • HTTP Headers: In rare cases, if the application uses the content of HTTP headers (e.g., User-Agent, Referer) in SQL queries without escaping.

  • Cookies: Data stored in cookies that is then processed and used in SQL queries without escaping.

4. Requirements for Exploitation

For successful exploitation of an SQL Injection vulnerability, certain conditions related to how the web application interacts with the database and processes user input must be met.

Conditions Under Which an Attack is Possible

  • Dynamic SQL Query Formation: The primary condition. The application must construct SQL queries by concatenating strings that include user input, instead of using secure methods like parameterized queries.

  • Absence or Incorrect Input Validation: The web application does not check or incorrectly checks user input for special SQL characters that can alter the query structure.

  • Display of Database Errors: In the case of Error-based SQLi, the application must display database error messages that contain useful information for the attacker.

  • Database Accessibility: The web application must be able to interact with the database, and the vulnerable code must be part of this interaction.

Technology Stack, Configurations, Developer Errors

  • Technology Stack: SQLi vulnerabilities do not depend on a specific DBMS (MySQL, PostgreSQL, Oracle, SQL Server) or programming language (PHP, Python, Java, Node.js, ASP.NET). The vulnerability arises from insecure coding practices. However, the syntax of payloads may differ depending on the DBMS used.

  • Configurations: Incorrect configurations of the database or web server that grant the application excessive privileges or do not disable functions potentially dangerous for Out-of-band SQLi (e.g., the ability to make outbound network requests) can contribute to attacks.

  • Developer Errors: The most common cause of SQLi. This can include:

    • Using string concatenation to build SQL queries.

    • Insufficient understanding of secure database practices.

    • Lack of server-side input validation.

    • Using outdated or insecure APIs for database interaction.

Entry Points and Targets (form, URL, headers, API, etc.)

An attacker looks for entry points through which they can inject their malicious SQL code. These include:

  • Form Fields: Any text fields where a user can enter data that is then used in SQL queries (e.g., login fields, search, comments, feedback forms).

  • URL Parameters: Query parameters in GET requests that are then used to form SQL queries (e.g., http://example.com/products?category=1).

  • HTTP Headers: In rare cases, if the application uses the content of HTTP headers (e.g., User-Agent, Referer, Cookie) in SQL queries without escaping.

  • API Endpoints: Input data for REST or SOAP APIs that can be used to inject SQL code if they are directly used in database queries.

  • Cookies: Data stored in cookies that is then processed and used in SQL queries without escaping.

5. Examples of Attacks

Let's look at a few examples of SQL Injection attacks, from the simplest to more advanced, with explanations of the payloads.

Simplest Example (Authentication Bypass)

Suppose we have a login form that uses the following SQL query to verify credentials:

SELECT * FROM users WHERE username = '[username]' AND password = '[password]';

Step-by-step exploitation:

  1. Attacker Input: In the username field, the attacker enters admin' OR '1'='1.

  2. Modified Query: The SQL query becomes:

    SELECT * FROM users WHERE username = 'admin' OR '1'='1' AND password = '[any_password]';

    Since the condition '1'='1' is always true, the query will return all rows where username is admin OR 1 is 1. This effectively bypasses password verification and allows logging in as the first user (often an administrator) in the users table.

Payload explanation:

  • ' OR '1'='1': This payload closes the single quote opened in the original query, adds the logical condition OR '1'='1' (which is always true), and then comments out the rest of the original query (e.g., AND password = '[password]') using -- (for MySQL/PostgreSQL) or /* (for SQL Server). In this example, if the password is not mandatory, comments might not be needed.

Advanced Example (Union-based SQLi - Data Extraction)

Suppose we have a page that displays products by categories, using the id parameter in the URL:

products.php?id=1

And the internal query looks like this:

SELECT name, description FROM products WHERE category_id = [id];

Step-by-step exploitation:

  1. Determine Number of Columns: First, the attacker must determine the number of columns in the original query using ORDER BY or UNION SELECT NULL, NULL, .... products.php?id=1 ORDER BY 3-- (if it throws an error, decrease the number until it stops; if not, increase) Assume the query has 2 columns.

  2. Data Extraction: The attacker uses UNION SELECT to combine their malicious query with the original one to extract data from other tables. products.php?id=-1 UNION SELECT username, password FROM users--

    • id=-1: Makes the original query false so that only the UNION SELECT results are displayed.

    • UNION SELECT username, password FROM users: Extracts usernames and passwords from the users table.

Payload explanation:

  • UNION SELECT: The UNION operator combines the results of two or more SELECT statements. The number of columns and their data types must match.

  • --: SQL comment characters, ignoring the rest of the query.

Example (Error-based SQLi - Information Extraction via Errors)

This method is used when query results are not displayed directly, but database errors are output to the page. An attacker can force the database to generate errors containing the desired information.

Step-by-step exploitation:

  1. Payload Injection: The attacker injects a payload that causes an error containing data. For example, for MySQL, using the EXTRACTVALUE function: products.php?id=1 AND (SELECT EXTRACTVALUE(1,CONCAT(0x5c, (SELECT DATABASE()))))--

  2. Error Analysis: The web application will output an error containing the name of the current database. XPATH syntax error: '\[database_name]'

Payload explanation:

  • EXTRACTVALUE(1,CONCAT(0x5c, (SELECT DATABASE()))): The EXTRACTVALUE function expects an XML path. If an incorrect path is passed to it (e.g., starting with 0x5c - a backslash), it will throw an error that will display the string passed as the path. SELECT DATABASE() returns the name of the current database.

Example (Time-based Blind SQLi - Data Extraction by Time)

Step-by-step exploitation:

  1. Condition Check: The attacker sends a request that causes the server to delay its response if a certain condition is true. For example, for MySQL, to check if the username admin starts with the letter a: products.php?id=1 AND IF(SUBSTRING((SELECT username FROM users WHERE id=1),1,1)='a', SLEEP(5), 0)--

  2. Response Time Analysis: If the page loads with a 5-second delay, it means that the first character of the username admin is indeed a. By repeating this process for each character and for different positions, all information can be extracted.

Payload explanation:

  • IF(condition, true_value, false_value): MySQL's IF function. If condition is true, true_value is executed; otherwise, false_value.

  • SLEEP(5): Causes the database to pause execution for 5 seconds.

  • SUBSTRING((SELECT username FROM users WHERE id=1),1,1): Extracts the first character of the username with id=1.

6. Tools and Techniques

Various tools and techniques are used to detect and exploit SQL Injection vulnerabilities, both for manual and automated testing.

Tools for Manual/Automated Attack

  • sqlmap: This is one of the most powerful and popular open-source tools for automatic detection and exploitation of SQL Injection vulnerabilities. sqlmap supports a wide range of SQLi techniques (Error-based, Union-based, Blind, Time-based) and various DBMS (MySQL, PostgreSQL, Oracle, SQL Server, and others). It can automate the process of data extraction, file system access, and operating system command execution.

  • Burp Suite: A comprehensive tool for web application security testing. Burp Suite allows intercepting, analyzing, and modifying HTTP requests, which is extremely useful for manual SQLi testing. The Intruder and Repeater functions are used for fuzzing parameters and testing various SQLi payloads.

  • OWASP ZAP (Zed Attack Proxy): A free and open-source web application security scanner. It can automatically scan web applications for SQLi and other vulnerabilities, and also provides tools for manual testing.

  • cURL/Wget: Command-line utilities for interacting with web servers. They can be used to send specially crafted HTTP requests with SQLi payloads and analyze server responses, especially when testing Blind SQLi.

Libraries and Utilities

Command Examples, One-liners

  • sqlmap - basic scan:

    sqlmap -u "http://example.com/products.php?id=1" --batch

    This command runs sqlmap to scan the URL for SQLi and automatically selects default parameters.

  • sqlmap - database extraction:

    sqlmap -u "http://example.com/products.php?id=1" --dbs

    Extracts a list of all databases.

  • sqlmap - table extraction from a specific database:

    sqlmap -u "http://example.com/products.php?id=1" -D [database_name] --tables

    Replaces [database_name] with the name of the target database.

  • sqlmap - column extraction from a specific table:

    sqlmap -u "http://example.com/products.php?id=1" -D [database_name] -T [table_name] --columns

    Replaces [database_name] and [table_name].

  • sqlmap - data dump:

    sqlmap -u "http://example.com/products.php?id=1" -D [database_name] -T [table_name] -C "username,password" --dump

    Dumps data from the username and password columns of the specified table.

Debugging via Burp Suite / cURL / browser

  • Burp Suite Repeater: Allows sending modified requests with various SQLi payloads and analyzing server responses. This is especially useful for manual Blind SQLi testing, where careful monitoring of changes in HTTP responses or response times is required.

  • cURL: Can be used to send GET/POST requests with SQLi payloads and analyze the HTML response for errors or changes indicating a vulnerability. Example for checking Error-based SQLi: curl "http://example.com/products.php?id=1%27" (adding a single quote often causes an SQL error)

  • Browser: When testing In-band SQLi, attack results (e.g., extracted data or error messages) can be displayed directly in the browser. Browser developer tools can help analyze responses and debug.

7. Bypassing Defenses and Filtering

Bypassing defenses and filtering is a key aspect of SQL Injection exploitation, as many web applications use various mechanisms to prevent the injection of malicious SQL queries, such as WAF (Web Application Firewall) and input validation systems.

Methods for Bypassing WAF, Input Validation

  • Encoding: Attackers use various encoding schemes to obfuscate malicious SQL code so that it is not detected by filters. Examples include URL encoding (%27 instead of '), Unicode encoding, or HTML entity encoding.

  • Obfuscation: Using alternative SQL syntaxes or adding unnecessary characters to change the appearance of the payload while maintaining its functionality. For example, using comments (/* */), spaces, newline characters (%0a), or tabs (%09) within or between keywords.

    • Example: SELECT/**/column/**/FROM/**/table instead of SELECT column FROM table.

  • String Concatenation: Splitting SQL strings into multiple parts that are then combined by the database. For example, SELECT 'user' || 'name' FROM users.

  • Using Alternative Operators and Functions: Some filters may block common operators or functions. Attackers can use less common but equivalent functions or operators.

    • Example: CHAR() or CONCAT() instead of direct string usage.

  • Injecting Newline/Tab Characters: Inserting newline (%0a) or tab (%09) characters into the payload can disrupt some regular expressions used by filters.

  • Comments: Using various types of comments (--, /* */, #) to bypass filters or to terminate the original query to add one's own.

  • Inline Comments: Inserting comments within keywords or functions to bypass filters that look for exact matches.

    • Example: SEL/**/ECT instead of SELECT.

Bypass Techniques

  • WAF Bypass: Bypassing WAF often involves finding "blind spots" in its rules. This can include using non-standard HTTP headers, changing HTTP methods, fragmenting requests, using different encodings that the WAF does not process correctly, or exploiting errors in the WAF's logic.

    • HTTP Parameter Pollution (HPP): Using multiple parameters with the same name in an HTTP request to bypass filters that only process the first or last parameter.

    • JSON-based SQLi: If the application processes JSON data and uses it in SQL queries, JSON parsing peculiarities can be used to bypass WAF.

  • Blacklist Bypass: If a filter is based on a blacklist of forbidden words or patterns, an attacker can use synonyms, typos, or insert special characters between forbidden words to "break" the pattern. For example, UNI/**/ON instead of UNION.

  • Context-Dependent Bypass: Understanding the SQL context in which the payload is injected (e.g., in a string literal, numeric field, table name) allows choosing the most effective bypass technique.

  • Using DBMS Functions: Some DBMS have specific functions that can be used to bypass filters. For example, in MySQL, /*!*/ can be used to execute code that is ignored by other DBMS.

8. Methods of Protection

Protecting against SQL Injection attacks requires a comprehensive approach based on secure development practices and strict control over the application's interaction with the database.

Secure Development Practices

  • Parameterized Queries (Prepared Statements): This is the most effective and recommended method for preventing SQLi. Parameterized queries separate SQL code from user data. The query is defined in advance, and then parameter values are passed separately. The database treats them as data, not as part of executable code, which completely eliminates the possibility of injection.

  • Using ORM (Object-Relational Mapping): Many ORM frameworks (e.g., Hibernate for Java, SQLAlchemy for Python, Entity Framework for .NET) use parameterized queries by default, significantly reducing the risk of SQLi. However, it is important to ensure that the ORM is used correctly and does not allow developers to manually form insecure queries.

  • Principle of Least Privilege: Database accounts used by the web application should have the minimum necessary privileges. For example, an account used for reading data should not have rights to write, modify, or delete tables.

Input Sanitization and Validation

  • Strict Input Validation: Always check and validate all user input against the expected format, data type, length, and allowed characters. Use whitelisting of allowed characters and values, rather than blacklisting. Validation must be performed server-side.

  • Escaping: If for some reason parameterized queries cannot be used, all special characters in user input must be carefully escaped before being included in an SQL query. Escaping functions depend on the specific DBMS (e.g., mysql_real_escape_string() for MySQL, pg_escape_string() for PostgreSQL). However, this method is less reliable than parameterized queries and prone to errors.

Server Settings, Sandboxing, Permissions

  • Web Application Firewall (WAF): A WAF can help detect and block known SQLi attacks, acting as an additional layer of defense. However, a WAF is not a panacea and does not replace secure coding practices, as it can be bypassed.

  • Disabling Error Display: In a production environment, detailed database error messages should be disabled from being displayed to users, as they can contain valuable information for an attacker.

  • Regular Software Updates: Update all web application components (operating system, web server, DBMS, frameworks, libraries) to the latest versions to eliminate known vulnerabilities.

  • Monitoring and Logging: Implement monitoring and logging systems to track suspicious activity and attempted SQLi attacks.

9. Known Cases and CVEs

The history of cybersecurity contains many examples of SQL Injection vulnerabilities that have led to serious incidents, demonstrating the real consequences of these attacks.

Real Vulnerabilities (with CVEs and descriptions)

  • Heartland Payment Systems (2008): One of the largest data breaches related to SQL Injection. Attackers used SQLi to inject malware into Heartland's payment processing systems, leading to the theft of data from over 130 million credit and debit cards. This was one of the largest payment card data theft cases in history.

    • Lesson Learned: This incident highlighted the critical importance of protecting databases containing sensitive financial information and the need to use parameterized queries to prevent SQLi.

  • Sony Pictures (2011): The hacker group LulzSec used SQL Injection to breach the Sony Pictures website, gaining access to data of over 1 million users, including names, passwords, email addresses, and birth dates. The attack was carried out through a vulnerability in one of the company's public websites.

    • Lesson Learned: Showed that even large corporations with seemingly robust security can be vulnerable to SQLi, and that the consequences can be significant, including personal data leaks and reputational damage.

  • CVE-2025-1094 (PostgreSQL psql SQL injection): In February 2025, a highly critical SQL Injection vulnerability was discovered and fixed in the interactive psql tool for PostgreSQL. This vulnerability allowed an attacker to execute arbitrary SQL code.

    • Lesson Learned: Even in well-maintained and widely used tools, critical vulnerabilities can be found, and it is important to update software promptly.

  • CVE-2024-23119 (Centreon SQL Injection): In September 2024, a critical SQL Injection vulnerability was identified in Centreon (an infrastructure monitoring system). The vulnerability affected Centreon Web versions up to 22.10.17, 23.04.13, and 23.10.5 and allowed arbitrary SQL code execution.

    • Lesson Learned: Emphasizes the importance of regular security audits of third-party software and timely application of patches.

  • WikiLeaks (2008): WikiLeaks suffered an SQL Injection attack that resulted in data theft, although the details of the incident are less public than other major breaches.

What Each Attack Taught

Each of these incidents underscores that SQL Injection remains one of the most serious threats to web applications. They demonstrate that SQLi can lead to:

  • Massive Data Theft: From personal data to financial information.

  • Complete System Compromise: Up to and including command execution on the server.

  • Significant Reputational and Financial Damage: For companies that fall victim to attacks.

These cases constantly remind us of the need to implement strict security measures, such as parameterized queries, input validation, and regular software updates, to protect against SQL Injection.

10. Conclusion

SQL Injection remains one of the most common and critical web application vulnerabilities, capable of leading to serious consequences such as data theft, authentication bypass, and complete system compromise. Its danger lies in its direct impact on the database, which stores the most valuable information.

Why it is Important to Know/Prevent: Understanding the mechanisms of SQLi and its exploitation methods is critically important for both developers and security professionals. Developers must apply secure coding practices, primarily using parameterized queries and strict input validation, to prevent these vulnerabilities from arising. Security professionals must be able to detect and test applications for SQLi to protect data and infrastructure. Only a comprehensive approach, including secure development, regular testing, and continuous system updates, can effectively counter the threat of SQL Injection.

Last updated

Was this helpful?