Careeroza
SQL Injection
What is SQL Injection?
SQL injection is one of the most common and dangerous web attacks. It happens when user input is pasted directly into a SQL string, so the input can change the meaning of the query.
// Vulnerable application code (JavaScript)
const sql = "SELECT * FROM Users WHERE Email = '" + email + "' AND Password = '" + password + "'";How the Attack Works
If an attacker types ' OR '1'='1 as the password, the query becomes:
SELECT * FROM Users
WHERE Email = '[email protected]' AND Password = '' OR '1'='1';'1'='1' is always true, so the attacker logs in without a password. Other inputs can read every table (UNION SELECT ...) or destroy data (; DROP TABLE Users; --).
See It Happen
Example
The injected condition returns every user:
CREATE TABLE Users (ID INT, Email TEXT, Password TEXT);
INSERT INTO Users VALUES (1, '[email protected]', 'S3cret!'), (2, '[email protected]', 'pa55');
-- what the vulnerable code builds when password = ' OR '1'='1
SELECT * FROM Users
WHERE Email = '[email protected]' AND Password = '' OR '1'='1';Result: 2 rows
| ID | Password | |
|---|---|---|
| 1 | [email protected] | S3cret! |
| 2 | [email protected] | pa55 |