What Is SQL Injection? How To Prevent SQLi Attacks
Web applications power our online experience day in and day out. We connect, interact, shop, and watch funny cat videos – all using web apps. They deliver vital business services and hold sensitive data, but the more we use something, the more prone it becomes to assaults.
One cyberattack to watch out for on apps that exploit vulnerabilities in structured query language (SQL) is the common and dangerous SQL injection.
What is SQL injection?
SQL injection (SQLi) is a harmful code injection technique cyber attackers use to exploit vulnerabilities in web applications. They leverage the weak spots to gain unauthorized access by adding a string of malicious code to a database query.
SQL injection attacks lead to improper data access, manipulation, identity theft, financial loss, reputation damage, and legal consequences. Developers and organizations have to understand its risks and implement full security measures. Tools like web application firewalls (WAF) software and digital forensics software are designed to guard against SQL injection attacks. Businesses can also depend on comprehensive website security suites to protect their apps.
Read this SQL injection cheat sheet to know how SQL attacks are executed with examples, their variations, and how to prevent such attacks.
Why are SQL injection attacks dangerous?
SQL injection has been in the Open Worldwide Application Security Project’s (OWASP) top 10 list of web application security risks for years. In 2022 alone, OWASP found 274,000+ occurrences of some form of injection in the apps they tested; SQL injection and cross-site scripting (XSS) were the most common.
Attackers can use SQl injections to cause:
- Errors in web applications by modifying or deleting information within a database.
- Data breaches if hackers get unauthorized access to sensitive data stored in databases, such as personal information, financial records, or passwords.
- Compromised systems by accessing additional, unauthorized systems that use the same shared databases. This allows attackers to escalate their strikes to other systems on the same network or perform distributed denial-of-service (DDoS).
These destructive actions irrevocably damage businesses. The offenses compromise privacy and data integrity, leading to a loss of customer trust and business reputation. It also adds a financial burden to the company dealing with the aftermath.
Real-life SQL injection attack examples
It’s been more than two decades since SQL injection first came on the scene. Twenty years later, it remains notorious, as evidenced by the following prominent SQL injection incidents.
- Heartland Payments Systems: In 2008, Heartland Payments Systems suffered what was one of the biggest data breaches in history, exposing over 130 million credit and debit card details through an SQLi attack. Heartland paid millions in fines.
- Yahoo: In 2012, an SQL injection attack compromised nearly 5 million Yahoo users’ account details, including email addresses and passwords.
- Freepik: Hackers stole the emails and passwords of 8.3 million Freepik and Flaticon users in 2020 during an SQL injection attack against the company’s Flaticon website.
- WooCommerce: The popular WordPress plugin fixed an SQL injection vulnerability that exposed 5 million sites to data theft.
- BillQuick: Cybercriminals exploited a blind SQL vulnerability in the popular billing platform to spread ransomware.
- MOVEit: In May 2023, the Cl0p ransomware gang used a SQL injection vulnerability in the managed file transfer software tool MOVEit, affecting over 1,000 organizations and at least 60 million individuals, making it the largest data breach in the year so far.
How does an SQL injection attack work?
Let’s look at the basics of databases and SQL queries we use in modern web applications. This will help us understand the inner workings of SQL injection better.
All websites use relational databases, also called SQL databases, to store data about their users and apps. It could be user info, login credentials, payment information, or anything else about the company. Take an e-commerce website, for instance. It stores product data, user accounts, order data, and payment information in its database.
The websites then take the data from these databases and deliver content or services specific to the users. This process happens thanks to SQL, a standardized programming language used for managing databases. Whenever you need to get something from an app, say your purchase history, you’re, in fact, making a request to the database using SQL queries, a command that instructs a database to perform a specific action.
In an attempt to make web interactions seamless, many websites let users enter data to make SQL queries. This can include things like search terms, usernames, or payment details.
Consider the e-commerce website’s example. A simple SQL query to display your order history from the database with “orders” table (o) and a “products” table (p) will be as follows:
SELECT o.order_id, o.order_date, p.product_name, p.price
FROM orders o
JOIN products p ON o.product_id = p.product_id
WHERE o.user_id = 12345;
This SQL code picks the order ID and date from the orders table, along with the product name and price from the product table for USER ID 12345 from the website database. Typically, the ID will be based on input from the user. Problems arise when the input isn’t properly checked and controlled. Attackers exploit this vulnerability to carry out an SQL injection attack.
Here’s how it typically unfolds.
SQL injection example
Consider a web application that uses a URL parameter to fetch product details based on a product ID, like this:
http://example.com/products?id=1
An attacker might try to inject malicious SQL code to cause an error and retrieve information like this: http://example.com/products?id=1′ OR 1=1; –
If the application fails to validate and sanitize user input adequately, the SQL query could be manipulated as follows:
SELECT * FROM products WHERE id = ‘1’ OR 1=1; – – ‘;
In this case, the original query was designed to retrieve a product with ID 1, but the attacker’s input modifies the query to return all products because of the addition of 1=1 and the appended double hyphen (- -). It nullifies the original closing single quote and leads to consequences displaying all product details or revealing error messages that attackers can exploit.
33%
of web application critical vulnerabilities in 2022 were due to SQL injections.
Source: Statista
The widespread prevalence of SQL vulnerabilities and the attraction of the web app database with all its business-critical data makes SQL injection one of the most persistent cyberattacks.
Source: Spiceworks
Types of SQL injection attacks
There are three major types of SQL injection attacks based on how attackers retrieve information or interact with the database:
- Classic or in-band SQLi
- Blind or inferential SQLi
- Out-of-the-band SQLi
1. Classic or in-band SQLi
In-band is the most common type of SQL injection attack. The classic hacker uses the same communication channel (in-band) to inject malicious SQL code and retrieve the results. The two main variations of in-band SQLi are:
Union-based in-band SQLi
This attack leverages the UNION SQL operator, used to combine data from the result of two or more SELECT statements. By doing this, attackers can retrieve data from tables they don’t have direct access to.
Error-based in-band SQLi
In this technique, an attacker intentionally triggers errors in an SQL query to exploit the error messages returned by the database. The errors can reveal valuable information about the database structure, table names, column names, and sometimes the data itself. Error-based SQLi can also be executed as out-of-the-band SQLi.
2. Inferential (blind) SQLi
In a blind SQLi, the attacker cannot directly see the results of their assault. Instead, they infer information by observing application behavior or error messages that respond to their queries. This type of attack is time-intensive as hackers have to make a series of SQL queries to find potential vulnerabilities to exploit. Two variations of blind SQLi are:
Time-based blind SQLi
Here, the attackers ask queries that make the database delay its response before it reacts. They infer information about the database by paying attention to response time.
Boolean blind SQLi
For Boolean blind SQLi, attackers take advantage of the way an application responds to true or false conditions in SQL queries. Based on the web application’s responses, they infer information about the database, even though no data from the database is returned.
3. Out-of-the-band SQLi
An out-of-the-band SQLi attack causes the application to send data to a remote endpoint controlled by the hackers. An attack like this requires the SQL servers to have certain features, like being able to initiate external network requests like Hypertext Transfer Protocol (HTTP) requests.
How to prevent SQL injection attacks: a cheat sheet
Preventing SQL injection requires a multi-layered approach involving secure coding practice and continuous monitoring. Here’s a cheat sheet with essential steps to help keep you safe from SQL injection attacks.
Use prepared statements
The primary defense against SQL injection attacks is prepared statements with parameterized queries. Prepared statements ensure user inputs are treated as data rather than executable code.
Developers compile SQL codes for queries in advance as templates with placeholders for input values from the user. At the query execution time, the prepared statements bind actual values instead of placeholders. This stops malicious code execution.
Prepared statements are favored over dynamic SQL statements. They write SQL queries during the execution time, which weakens them against injection attacks.
Prepared statements in popular programming languages:
Here are language-specific recommendations for using prepared statements (parameterized queries) in popular database programming:
- Java enterprise edition (EE): Use PreparedStatement class from the java.sql package. Bind parameters using methods like setString, setInt, etc.
- Python (SQLite3): Use placeholders (?) in queries. Bind parameters using a tuple or list.
- PHP: Use the PHP data objects (PDO) extension. Utilize prepared statements with placeholders (:). Bind parameters with bindValue or bindParam.
- .NET: Use MySqlCommand object. Bind parameters using Parameters.AddWithValue.
Another SQL injection prevention method is the use of stored procedures or a group of pre-compiled SQL codes that can be used again and again.
Practice input validation
Input validation involves checking user input to make sure it meets specific criteria before processing. An allow-list, also known as a white list, is a key aspect of input validation. Here, only predefined, safe values or patterns are accepted as part of SQL queries. Any input that doesn’t match the set criteria is rejected. This actively prevents malignant or unexpected input from entering the system.
Use object-relational mapping libraries
Object-relational mapping (ORM) libraries are valuable tools for developers working with relational databases. They let developers interact with databases using the programming language of their choice, and thereby reducing the need for writing raw SQL queries. ORM libraries provide built-in protection against SQL injection attacks.
Train the developers and IT teams on secure coding practices. Make sure to do regular security audits and penetration testing to find vulnerabilities.
Enforce the least privilege principle
The least privilege principle only gives database users the minimum permission required to do their jobs. Following this principle reduces the impact of potential SQL injection attacks, or any cyberattack, for that matter. Also, apply strict access control to your database.
Deploy a web application firewall (WAF)
A WAF monitors incoming network traffic of applications and blocks potential malicious traffic based on a list of well-known attack signatures.
A WAF employs predefined rules to detect suspicious patterns and anomalies in incoming traffic, like SQL keywords and malicious payloads. It sanitizes and validates user inputs and blocks or filters out harmful requests. This helps stop dangerous SQL queries as they enter the system.
Modern WAFs adapt to new attack methods using machine learning.
Other security tools to prevent SQL injection attack
In addition to WAF, several other security platforms impede SQL injection attacks.
Guard your data fortresses
SQL injection attacks pose a grave threat to web app security. Companies risk losing valuable data, user privacy, and their good reputations if the attacks succeed.
While no single solution guarantees absolute safety against SQL injection, combining the preventive measures we talked about here significantly reduces the chance of attacks. Web developers and database administrators should employ stringent defenses and fortify their web apps against potential exploitation.
Want a comprehensive solution to secure your website? Explore web security software and how it helps against cyber attacks that leads to data breaches.