Back

Defining SQL injection and prevention methods

Latest Update: 17/09/2024

Defining SQL injection and prevention methods

The OWASP Top 10 is an internationally recognized standard list of the most critical security risks to web applications. For nearly two decades, SQL injection has consistently ranked among the top vulnerabilities, highlighting its severity and the increasing sophistication of these attacks. The consequences of exploiting SQL injection vulnerabilities can be severe, ranging from sensitive data breaches to complete system compromises, resulting in significant financial and reputational damage. In this article, VNETWORK will delve deeper into this threat and explore effective prevention methods.

What is SQL injection?

SQL injection (SQLi) is a dangerous web application hacking technique that involves injecting malicious code to exploit security vulnerabilities. This vulnerability allows attackers to insert malicious code (usually SQL statements) to manipulate the original query, enabling them to extract data from a database. When a web application processes this input without proper validation and sanitization, the malicious code is executed directly on the database system, leading to SQL injection attacks.

Why is SQL injection dangerous?

SQL injection poses a significant threat to web applications and can result in various consequences:

  • Data theft: Attackers can extract sensitive information such as usernames, passwords, credit card numbers, and personal data from the database.
  • Data modification or deletion: Unauthorized modification or deletion of data can lead to data corruption or loss, affecting data integrity and reliability.
  • System takeover: By gaining administrative privileges, attackers can control the system, leading to further malicious activities such as escalation of privileges, malware installation, and system structure modification.
  • Financial loss: The costs of addressing SQL injection attacks can be substantial, including direct costs for system recovery and data restoration, as well as indirect losses from business disruption and revenue loss.
  • Regulatory and legal consequences: Organizations may face financial penalties or lawsuits due to data breaches, especially for those handling sensitive information such as financial or healthcare organizations.
  • Reputational damage: A successful attack can negatively impact a company's reputation, leading to long-term damage to growth and profitability.
  • Business disruption: Downtime caused by attacks can result in revenue loss and customer dissatisfaction, harming the company's image.

Additionally, attackers often combine SQL injection with other techniques such as authentication bypass, DNS spoofing, XSS, and DDoS attacks, which can exacerbate financial damage and lead to more severe system compromises.

Common types of SQL injection attacks

SQL injection attacks come in various forms, each with its own characteristics. Below are the three most common types of SQLi attacks.

common-types-of-sql-injection.png Common types of SQL injection

1. Error-Based SQLi attacks

Involve sending malicious SQL queries to trigger errors or confirm vulnerabilities in the application. Attackers use these errors to gather information about the database structure or other sensitive details.

Example of Error-Based SQLi attacks

Attackers may use SQL commands like single quotes, double quotes, or operators like AND, OR, and NOT to exploit errors.

For instance, entering http://example.vnetwork.vn/index.php?title=1' could produce an error message like:

“You have an error in your SQL syntax; check the manual corresponding to your MySQL server version for the right syntax to use near ‘‘VALUE’’.

The error message provides attackers with critical information such as:

  • The database in use is MySQL.
  • The syntax error involves double quotes.
  • The error occurs at the end of the parameter.

2. Union-Based SQLi attacks

In this type of SQL injection attack, the attacker exploits a vulnerability by using the "UNION" operator. The UNION operator is used to combine two tables or simultaneously perform two select queries. In UNION, duplicate rows or columns are eliminated, which is what the attacker tries to exploit.

Example of Union-Based SQLi attacks

Suppose a web application constructs an SQL query as follows:

SELECT name, email, phone FROM users WHERE name = '[user_input]'

If user input is not properly sanitized, attackers can inject malicious SQL code. For example, they might enter the following as a name:

' UNION SELECT password, NULL, NULL FROM users --

This will lead to the execution of the following SQL query:

SELECT name, email, phone FROM users WHERE name = '' UNION SELECT password, NULL, NULL FROM users --'

The '--' at the end of the string is a comment character, commenting out the rest of the original query. Thus, the resulting query is equivalent to:

SELECT name, email, phone FROM users WHERE name = ''

UNION SELECT password, NULL, NULL FROM users

This query will return a table containing the users' names, emails, and phone numbers, as well as a table with all the passwords in the users table. The attacker can then use this information to further compromise the system.

3. Blind SQLi attacks

Blind SQLi attacks occur when attackers cannot directly view the database content but can infer information based on the application's response. There are two main types of Blind SQLi attacks:

3.1. Boolean-Based SQLi attacks

In this type of SQL injection vulnerability exploitation, the attacker sends a series of SQL queries that evaluate to true or false, depending on whether the injected code is successfully executed. The attacker can then use the application's response to infer information about the database by crafting complex queries to probe specific details.

Example of Boolean-Based SQLi attacks

A typical SQL database query for an online store might look like this:

SELECT ItemName, ItemDescription FROM Item WHERE ItemNumber = ItemNumber

So, a product URL on the online store could be: http://www.example.vnetwork.vn/items/items.asp?itemid=999 or 1=1. The SQL query could be:

SELECT ItemName, ItemDescription FROM Items WHERE ItemNumber = 999 OR 1=1

Since the condition "1=1" always evaluates to true, the SQL query will return all item names and descriptions in the database, including items the attacker does not have access to.

3.2. Time-Based SQLi attacks

This SQL injection technique involves injecting a query to cause a delay in the application's response. By measuring the system's response time, attackers can infer whether data exists and gain insight into the database structure.

Example of Time-Based SQLi attacks

Suppose a login form on a web application uses an SQL query to check if a user's login credentials are valid. The query might look like this:

SELECT * FROM users WHERE username = 'admin' AND password = 'password123'

To execute a Time-based SQLi attack, an attacker might inject a query like this:

SELECT CASE WHEN (1=1) THEN pg_sleep(10) ELSE pg_sleep(0) END;

This query will cause the application to sleep for 10 seconds if the condition (1=1) is true. The attacker can determine whether the condition is true or false by measuring the time it takes for the application to respond to this query.

If the response takes 10 seconds, the attacker knows the condition is true, indicating the application is vulnerable to Time-based SQLi. Conversely, if the response is immediate, the attacker knows the condition is false.

Once attackers confirm the possibility of Time-based SQLi, they can begin injecting more complex queries to extract sensitive information from the database.

How Bot-Controlled SQL injection attacks work

SQL injection attacks can be automated using bots, which can scale up the attacks and make them more dangerous. Here is how bots can control SQL injection attacks:

  • Automated Attack Execution: Bots can be programmed to automatically send SQL injection payloads to web applications. They can test various input fields and try different injection types at high speed, something that humans cannot easily do manually.
  • Scalability: Bots can perform thousands of SQL injection attempts simultaneously on multiple websites or applications. This scalability increases the likelihood of finding vulnerabilities and makes it harder for organizations to defend against such attacks.
  • Advanced Techniques: Bots can use advanced techniques to avoid detection, such as IP rotation, using proxies, and employing encryption. They can also use complex SQL payloads to bypass standard security measures.
  • Data Extraction: Once a bot successfully injects malicious SQL code, it can automate the process of extracting sensitive data from the database.
  • Persistent Exploitation: Bots can continuously probe for vulnerabilities and exploit them over time. They can also adapt to changes in the application's structure or security measures, making this attack a persistent threat.

To combat bot-controlled SQL injection attacks, apply "rate limit" requests from individual IPs and block malicious IPs. Additionally, use bot detection tools such as CAPTCHA and behavior analysis to identify and mitigate bot traffic.

Top 4 ways to prevent SQL injection attacks

The easiest way to protect your website from SQL injection attacks is to keep all software and "third party" components up to date. However, several techniques can help prevent SQL injection vulnerabilities, as outlined below. ways-to-prevent-sql-injection-attacks.png Ways to prevent SQL injection attacks

1. Input data filtering

While input filtering cannot completely eliminate SQL injection attacks, it is a fundamental security measure to reduce the risk of SQL injection vulnerabilities. Attackers often exploit vulnerabilities in handling special characters to perform passive attacks, gather information about the database structure, and even execute malicious commands to gain unauthorized access or manipulate data.

Cleaning data and limiting special characters

Attackers exploit special characters to inject SQL code into the database, so data must be sanitized to prevent concatenation or recognizing user input as commands.

For example, in a login-oriented attack where an attacker attempts to log in using the password: password’ or 1=1

When an SQL database is not adequately secured, password verification commands become susceptible to exploitation. The attacker can alter the content of these commands to gain unauthorized access to the system.

password = ‘<insert user input here>’

When the database processes the attacker's string, it sees the command:

password = ‘password’ or 1=1’

This action injects a logic statement that is always true (1=1) into the query, causing the database to interpret that any password satisfies the condition, thus allowing the attacker unauthorized access.

Each programming language typically provides different functions and methods for handling and cleaning input data. Therefore, programmers need to thoroughly understand the appropriate functions for their language and use specialized SQL cleaning libraries.

2. Limiting database access code

In addition to filtering input, limiting database access code can enhance control and reduce the likelihood of attackers exploiting SQL injection vulnerabilities.

2.1. Minimizing available functionality

The attack surface in cybersecurity is the set of potential weaknesses that attackers can exploit to penetrate a system. In the context of SQL injection attacks, minimizing the attack surface requires disabling unnecessary database functionalities. For example, the "procedure" xp_cmdshell in Microsoft SQL Server allows the execution of operating system commands from within the database, creating a significant vulnerability if not tightly managed.

2.2. Using stored procedures

Using "stored procedures" can isolate the database from direct user interactions, significantly reducing the risk of exploitation. Instead of allowing users to execute SQL commands directly on the database, the application calls these procedures and receives only the processed results.

This method often includes parameter binding, a security technique that prevents SQL injection attacks. Stored procedures are typically contained within the database itself and are called from the web application. However, if dynamic SQL statements are still used within the procedure, they can still be targets for SQL injection attacks.

2.3. Using whitelists

Specifically, developers create a list of all permitted SQL statements. When users input data, the system compares it against this whitelist. Only matching data is processed; the rest is rejected. Using a whitelist significantly limits attackers' ability to exploit vulnerabilities and inject malicious code into the database.

2.4. Focusing on prepared statements & parameterization

To prevent SQL injection attacks, one of the basic security techniques is to use "prepared statements" combined with "parameterization." Instead of allowing users to directly input SQL commands into the system, a statement structure is pre-built, and only the data value portion is changed.

Specifically, developers create a template SQL statement where the values to be changed are marked with question marks (?). Then, as users input data, these values are inserted in place of the question marks. The database treats the data as a simple value, not part of the statement. This prevents attackers from exploiting vulnerabilities to inject malicious code into the SQL statement.

For example, instead of writing the statement:

“SELECT * FROM users WHERE username=” + “'” + username + “'”

It is better to write:

“SELECT * FROM users WHERE username = ?”

and pass the username value into the question mark.

3. Restricting database access

To mitigate damage from SQL injection attacks, we need to minimize database access as much as possible.

3.1. Use firewalls

A Web Application Firewall (WAF) is an indispensable security solution for any web application. WAFs operate by inspecting and filtering all incoming requests to the application, blocking attacks such as SQL injection, cross-site scripting (XSS), and other types of attacks. Additionally, a WAF serves as a shield, protecting against the exploitation of vulnerabilities and preventing SQL injection.

Hardware firewalls are a common network security solution employed by many enterprises. However, with the increasing complexity of cyberattacks, hardware devices may not suffice due to limitations in throughput and lack of flexibility in scalability. Consequently, to enhance system security, many companies are deploying additional Cloud WAF layers integrated with Content Delivery Network (CDN) infrastructure to optimize costs and improve filtering efficiency. Furthermore, some organizations are transitioning entirely to Cloud WAF solutions to optimize investment and operational costs.

Notably, Cloud-WAF offers outstanding advantages such as easy integration and rapid deployment, minimizing service downtime and ensuring continuous business operations.

3.2. Minimize imation disclosure in error messages

Detailed error messages can disclose too much critical information about the database's structure and operations, facilitating SQL injection attacks. To prevent the leakage of sensitive information, organizations should: Simplify Error Messages: Only display the most necessary information to the user, avoiding details about the database.

Use customErrors Mode: Configure customErrors mode to "RemoteOnly" (or equivalent) to show generic error messages to external users while providing more detailed information to administrators for easier troubleshooting.

3.3. Implement the principle of least privilege

To protect SQL database data, it is crucial to apply the principle of least privilege. This means granting users or applications only the permissions necessary to perform their tasks. For instance, if a web application only needs to read data from the database, it should be granted SELECT permissions only, without any additional INSERT, UPDATE, or DELETE permissions.

3.4. Encryption: Protect sensitive information

To protect sensitive information like passwords, credit card numbers, or personal data, encryption is an essential solution. By converting data into an encrypted format, we can ensure that even if the database is compromised, the data remains secure.

3.5. Avoid shared databases & accounts

Sharing databases among multiple websites or applications can lead to severe consequences. The same applies to user accounts with access to multiple web applications. While shared access may provide flexibility for organizations or administrators, it also inadvertently increases security risks if an application or user credentials are compromised.

Ideally, any connected servers, Storage Area Networks (SANs), or cloud data buckets should have minimal access to the target server, with strictly limited permissions for critical data. All associated assets should have separate login credentials, avoiding shared access with other processes on the server.

4. Prioritize vulnerability detection & remediation

Timely detection and response to security vulnerabilities are crucial to protecting web applications and databases. By continuously monitoring database activities and using behavior analysis tools, we can identify unusual activities and prevent SQL injection attacks before they cause damage.

All components of a web application must be monitored and updated, including database server software, frameworks, libraries, plugins, APIs, and web server software. For organizations struggling with continuous patching and updating, a WAF solution is worth investing in to reduce the burden on development and IT teams during vulnerability management.

VNIS - Effective solution against SQL injection attacks

vnis-comprehensive-security-solution.png VNIS - Comprehensive security solution

VNIS offers a comprehensive security solution for Web/App/API against DDoS attacks on layers 3, 4, and 7, with infrastructure availability up to 2,600 Tbps combined with a Multi-CDN system, ensuring web application stability under high traffic or attacks. Moreover, this article highlights its ability to detect and automatically block all critical security vulnerabilities listed by OWASP (Top 10 OWASP) such as SQL injection, XSS injection, Broken access control, Cryptographic failures, etc., ensuring the continuous protection of corporate websites. With over 2000 security rules continuously updated, VNIS not only detects but also acts as a strong shield against all exploitation attempts, providing peace of mind for businesses regarding website security.

For SQL injection prevention, one of the most sophisticated and large-scale attack methods due to the use of bots, VNIS's rate limit feature can limit the number of requests, detect and filter malicious SQL queries, and utilize CAPTCHA to restrict bot access. Built on a Cloud platform, VNIS ensures high load capacity and flexible scalability to maintain stable business operations. Additionally, VNIS leverages Cloud technology to optimize costs and simplify deployment, allowing businesses to integrate into existing systems quickly without disrupting business activities. VNIS's intuitive management interface allows businesses to flexibly configure security rules, monitor attack activities in real-time, accurately identify which IP addresses are exploiting vulnerabilities, or which URLs are being attacked/taken over, enabling timely patching of vulnerabilities.

Moreover, VNETWORK's SOC experts are always ready to support 24/7, helping businesses effectively respond to unexpected attacks. As a result, VNIS provides comprehensive protection for Web/App/API, enabling businesses to focus on their core activities.

Don't let your business become the next victim of SQL injection attacks. Contact VNETWORK now for a free consultation on VNIS solutions and protect your business's systems from all attacks through hotline: +84 (028) 7306 8789 or email: contact@vnetwork.vn.

Sitemap HTML