Back to blog
Mar 17, 2024
2 min read

SQL Injection: An Introduction to the Simplest Code

Understanding the basics of one of the most common web vulnerabilities and how it can be exploited with simple inputs.

SQL Injection is a code injection technique used to attack data-driven applications, in which malicious SQL statements are inserted into an entry field for execution. This article will show a basic example of how it works.

A Vulnerable Query

Imagine a website uses the following SQL query to find a user’s details based on their username and password.

SELECT * FROM users WHERE username = '$username' AND password = '$password';

The $username and $password variables are replaced with whatever the user types into a login form.

The Injection Payload

An attacker can bypass this login by entering a specific string into the username field.

// Username field input

' OR '1'='1' --

The ' character closes the username field, the OR '1'='1' statement is always true, and the final -- comments out the rest of the original query, effectively ignoring the password check.

The resulting query that the database receives becomes:

SELECT * FROM users WHERE username = '' OR '1'='1' -- ' AND password = '$password';

Since '1'='1' is always true, the database will return all users, and the attacker gains access.

Explanation of the Payload

PartDescription
'Closes the single quote for the username field.
ORA logical operator that combines conditions.
'1'='1'A condition that is always true, granting access without a valid username.
--A comment operator in SQL that ignores everything that follows in the query.