8.18. SQL Injection

8.18.1. Rationale

Warning

This is to demonstrate a serious problem. Do not that statements in your code!

8.18.2. Scenario

Ask user for credentials:

>>> username = input('Username: ')
>>> password = input('Password: ')

System uses SQL query with variable substitution:

>>> SQL_QUERY = f"""
...     SELECT * FROM users
...     WHERE username='{username}'
...     AND password='{password}';
... """

System executes query on database:

>>> print(SQL_QUERY)

    SELECT * FROM users
    WHERE username='' OR 1=1; DROP TABLE users --'
    AND password='whatever';

Exploited SQL injection, will SELECT all users with their data and then DROP all data from table users!

Why this happened? Because user input:

>>> print(username)
' OR 1=1; DROP TABLE users --
>>>
>>> print(password)
whatever

Warning

This is to demonstrate a serious problem. Do not that statements in your code!

../_images/sql-injection.jpg