SQL Injection-how to avoid problem in Python DB API

Photo by Jan Antonin Kolar on Unsplash

What is Python DB API?

What is SQL Injection?

# Define POST variables
username = request.POST['username']
password = request.POST['password']
# SQL query vulnerable to SQLi
sql = “SELECT id FROM users WHERE username=’” + username+ “’ AND password=’” + password+ “’”
# Execute the SQL statement
database.execute(sql)
SELECT id FROM users WHERE username='username' AND password='password' OR 1=1'
-- MySQL, MSSQL, Oracle, PostgreSQL, SQLite
' OR '1'='1' --
' OR '1'='1' /*
-- MySQL
' OR '1'='1' #
-- Access (using null characters)
' OR '1'='1' %00
' OR '1'='1' %16

Example of SQL Injection problem using Python DB API

Example with SQL Injection mistake
login: alice
password: xxx' OR 1 = 1 -- ]
[('alice', 'qwerty'), ('bob', 'secret')]
Access granted
Process finished with exit code 0
Example without SQL Injection mistake
login: alice
password: xxx' OR 1 = 1 -- ]
Access denied
Process finished with exit code 0

Conclusion

I’m a civil engineer at the beginning of my path to becoming a programmer and changing construction design to application design. I’m a Python enthusiast.