SQL Injection is one of the those common application layer security vulnerabilities. Every course or hacking tutorials out there, starts with SQL injection.

Prerequisites

  • SQL
  • PHP (since this post is written based on PHP)

SQL injection aims to inject SQL query in user input which causes the application to misbehave or reveal data. Consider a application with the following PHP code

$username = $_POST["username"];
$password = $_POST["password"];
$sql = "select * from login where username='$username' and password='$password'";
$result = $conn->query($sql);

The user inputs from the username and password fields are concatenated into the SQL query. A intended user input like

' OR '1=1

will result in a query like

select * from login where username='' OR '1=1' AND password='' OR '1=1'

Now the above query has a condition like username should be empty or 1 should be equal to 1. The latter will be always true. The same applies for the condition after AND. Thus the condition will result in true always and thus the query returns every row in the table. So the attacker will be able to login as the first user in the table without knowing the credentials.

Even Worse

The above example allows the attacker to gain unintended access to the application. Since the SQL injection allows the attacker to directly run SQL queries in the database, this can end up worse than the above. Consider the below input in the password field.

'; DELETE login where '1=1

will result in a query like

select * from login where username='' OR '1=1' AND password=''; DELETE login where '1=1'

The ; ends the SQL query and thus the attacker can give the next query which even can alter the database. where '1=1' will be true for all rows, and thus every tuple in login table will be deleted.

Not a doddle

In a real attack, the attacker won't have the knowledge of the apllication code (PHP code here). Thus he needs to try different possible inputs to analyse the application, which is defnitely not a cakewalk.

How to protect

SQL has something called prepared statements.
Learn more about Prepared statements in PHP
The prepared statements works by executing the query without substituting user input and thus creating a statement (see it's prepared :P). Later the user input can be given to the statement to get back the results.

Sample Code can be found here on Github