SQL (Structured Query Language) is a language that allows us to interact with databases. Modern web applications use databases to manage data and display dynamic content to readers.
SQL injection, or SQLi, is an attack on a web application by compromising its database through malicious SQL statements.
As it’s a common attack, let’s try to learn more about what it is, how it happens, and how to defend yourself from it.
Ready? Let’s dive in!
What is SQL Injection?
SQL injection, or SQLi, is a type of attack on a web application that enables an attacker to insert malicious SQL statements into the web application, potentially gaining access to sensitive data in the database or destroying this data.SQL injection was first discovered by Jeff Forristal in 1998.
In the two decades since its discovery, SQL injection has consistently been the top priority of web developers when designing applications.
Barclaycard estimated in 2012 that 97% of data breaches initiate with an SQL injection attack. An SQL injection is prevalent even today and the severity of injection attacks in a web application is recognized widely. It is one of the top ten most critical web application security risks by OWASP.
How Does the SQL Injection Vulnerability Work?
An SQL injection vulnerability gives an attacker complete access to your application’s database through the use of malicious SQL statements.
In this section, we share an example of how a vulnerable application looks like.
Imagine the workflow of a typical web application that involves database requests through user inputs. You take the user input through a form, say a login form. You then query your database with the fields submitted by the user to authenticate them. The structure of the query to your database is something like this:
select * from user_table where username = 'sdaityari' and password = 'mypassword';
For simplicity, let’s assume you are storing your passwords as clear text. It is, however, a good practice to salt your passwords and then hashing them. Moving on, if you have received the username and password from the form, you may define the query in PHP as follows:
// Connect to SQL database $db_query = "select * from user_table where username = '".$user."' AND password = '".$password."';"; // Execute query
If someone enters the value “admin’;–” in the username field, the resulting SQL query that the variable $db_query generates will be as follows:
select * from user_table where username = 'admin';--' and password = 'mypassword'
What does this query do?
A comment in SQL starts with double dashes (–). The resultant query filters only by the username without taking into consideration the password. If there was no security in place to avoid this, you would simply be granted administrative access to the web application just by using this trick.
This article was written by Shaunik Daityari and originally published on Blog – Kinsta Managed WordPress Hosting.