Guarding against SQL injection: Techniques to enhance code security
Learn how to avoid these common vulnerabilities in your applications with our SQL injection attack examples.
Table of Contents
Structured Query Language (SQL) is a high-level language that interacts with relational databases like MySQL or Microsoft’s SQL Server. It was designed to simplify the process of reading, writing, updating, and deleting data stored in these databases.
A simple query to retrieve all of the users from a user table for example would be something like the following:
SELECT user_id, username, last_name, first_name, email_address from users where username = "user1234";All programming languages provide ways to create SQL queries, submit them to the database, and then handle the response.
When writing an interactive application, you would take the input from a user and use that to carry out an operation on the database using SQL that is constructed using that input.
For example, a user who is searching for a new computer may filter the search by asking to show only “Gaming PCs”. In a PHP application, the code to do this would look like:
$query = "SELECT * from products where type = '$GET['computer_type']'"; $result = $pdo->query( $query );The great thing about SQL is that it is an intuitive, easy-to-learn, and applied language.
Constructing queries is also very simple, you just create a string combining the SQL syntax with the parameters you received from the user.
Unfortunately, it is in this simplicity that the problem of SQL injection lies.
So what is SQL injection?
So, you can create an SQL query easily by combining user input with other text using SQL syntax.
However, if you don’t check the user input, an attacker can potentially manipulate the final SQL query by crafting the input to alter what the SQL query does.
So, instead of just returning the details of a specific user “user1234” as in the example above, the attacker can modify the query to return all of the users in the user table.
We will cover this in more detail, with examples, but it is important to realize how big of a problem this type of vulnerability can be. Not only can attackers read data that they shouldn’t have access to, but they can also modify data and even run operating system commands on some systems.
Learn SQL injection fundamentals with Hack The Box

-
Learn the basics of SQL and MySQL.
-
Discover what SQL injections are, and how can we use them.
-
Use SQL injections to subvert the web application logic and bypass authentication.
-
Use SQL injections to read files of the back-end server.
-
Use SQL injections to write a web shell on the back-end server and gain remote control over it.
-
Learn how to mitigate such SQL injections and patch your code.
SQL injection is still a big problem
Bleeping Computer has a long list of all recent breaches and discovered vulnerabilities that involve SQL injection. A vulnerability in a WordPress plugin called LayerSlider exposed over a million sites to SQL injection (CVE-2024-2879).
In a campaign orchestrated by a group calling themselves ResumeLooters, the personal data of over 2 million job seekers was stolen from SQL injection and cross-site scripting (XSS) attacks on 65 different job listing and retail sites.
The problem is still so bad that it has prompted the US agency CISA (Cybersecurity and Infrastructure Security Agency) and the FBI to issue an appeal in early 2024 for developers to review and fix SQL injection vulnerabilities in their code.
Having stressed the importance of SQL injection vulnerabilities, let us look at how these vulnerabilities can be exploited in practice.
Common code vulnerabilities that lead to SQLi
SQL injections happen when a developer creates queries by combining user input, and the code is not checking directly with other text to create an SQL statement.
In the following PHP code example, the query is constructed using unsanitized inputs:
$query = "SELECT id from users where username = '$_GET['username']'"; $result = $pdo->query( $query );If the inputted username was “alice” then the query would be:
SELECT id from users where username = 'alice'If the attacker now passes in
anyone' or '1'='1The resulting query would be
SELECT id from users where username = 'anyone' or '1'='1'Which would always return a result. In the case where the username ‘anyone’ does not exist, it would return all rows in the table.
💡Recommended read: Secure coding practices: A busy dev's guide to bulletproof app security.
Common vulnerabilities and how they are exploited
Injection vulnerabilities are still common as they made the top 3 in the OWASP Top 10 vulnerabilities in 2021. There were a large number of critical SQL injection CVEs still being published in 2024.
Many of these are PHP applications or plugins but other languages appear in these CVEs.
Language frameworks like Django for example, use an object-relational mapping that hides the actual SQL used on the database. For greater flexibility, Django allows direct manipulation of the SQL to execute queries, and this is where the vulnerabilities can appear.
The most important thing to remember is that the underlying root cause in SQL injection is failing to validate inputs and creating dynamic SQL statements by combining that input with other text.
For example, CVE-2024-0610. The Piraeus Bank WooCommerce Payment Gateway plugin for WordPress (listed as having over 4000 active installs), was found to be vulnerable to time-based blind SQL injection attacks.
The PHP code illustrates the problem:
$ttquery = 'SELECT trans_ticket FROM `' . $wpdb->prefix . 'piraeusbank_transactions` WHERE `merch_ref` = ' . $order_id . ' ;';In this case, the variable $order_id is just filtered using the PHP function filter_var
$order_id = filter_var($_REQUEST['MerchantReference'], FILTER_SANITIZE_STRING);The function filter_var with the option FILTER_SANITIZE_STRING only removes HTML tags and HTML encodes quote marks. This will not remove SQL statements, so the attacker's input can still pass through to be executed.
What made this CVE particularly bad was that it allowed unauthenticated attackers to exploit it. This means that if you could find the right URL that accesses this function, you didn’t need to be logged in as a valid user to exploit it!
Types of SQL injection attack
Having looked at the basics of how an attacker can modify the input to a SQL statement to carry out a SQL injection attack, there is another problem that the attacker needs to deal with: how to get and process the response from that modified SQL.
From an attacker’s perspective, it would be convenient if the response from the query was simply displayed on a web page for them to read. That only happens in some situations and in others, the attacker has to resort to other techniques to access responses from the SQL query to extract useful information.
The names given to these different types of SQL injection attacks are technical but are useful to know because tools like sqlmap refer to them (as we will see later).
|
Author bio: David Glance (CyberMnemosyne), Senior Research Fellow, University of Western Australia Dr. David Glance is a cybersecurity consultant and Adjunct Senior Research Fellow at the University of Western Australia. He has taught and carried out research in the areas of cybersecurity, privacy, and electronic health. Dr. Glance has also worked in the finance and software industries for several years and has consulted in the areas of eHealth, cybersecurity and privacy for the OECD and WHO. He is the author of articles and books on cybersecurity. Feel free to connect with him on LinkedIn. |

