SQL injection is a simple mechanism that might destroy the entire database! Simple usage of SQL injection is that the hacker can gain access to others' accounts without knowing the username or password.
Following query is used to validate the user credentials of an account.
select * from users where username = 'abc' and password = 'abc123'
Username (abc) and password (abc123) are passed as parameters from the text boxes entered by the user. The query will return data if and only if the username and password entered by the user matching with the username and password in the database.
- Since it uses and statement in the query, both sides should be true in order to return true.
X | Y | Output |
F | F | F |
F | T | F |
T | F | F |
T | T | T |
- Username: test' or '1' = '1
- Password: test' or '1' = '1
Then the query will be likely as follows.
select * from users where username = 'test' or '1' = '1' and password = 'test' or '1' = '1'
(Username and password will be replaced by abc and abc123)
Analyze the query now!
select * from users where username = 'test' or '1' = '1' and password = 'test' or '1' = '1'
Is '1'='1' true? Yes, exactly! Therefore both left-hand side and right-hand side of the and operator will return TRUE! So query will return true irrespective of the username and password.
Solutions:
- Use of prepared statements (With parameterized queries)
- Use of stored procedures Refer: https://www.owasp.org/index.php/SQL_Injection_Prevention_Cheat_Sheet