| Tiago Coimbra
1. SQL Injection - SQLi
SQL Injection - SQLi
Category: #Execution-Attack
Attack
SQL Injection allows attackers to manipulate SQL queries by injecting malicious SQL code through user input fields.
Attack Code Example:
' OR 1=1; --
In this example, an attacker bypasses authentication by using a simple SQL injection in a login form. This query returns all rows from the database, effectively logging the attacker in without a password.
Vulnerable Code (Python with sqlite3):
import sqlite3
user_input = "' OR 1=1; --"
conn = sqlite3.connect('database.db')
query = f"SELECT * FROM users WHERE username = '{user_input}'"
conn.execute(query) # Vulnerable to SQL Injection
Remediation Steps:
- Use Parameterized Queries (Prepared Statements): Parameterized queries treat user input as data, not as executable code.
- Input Validation: Validate all user inputs.
- Use ORMs: Use Object-Relational Mappers (ORMs) to interact with the database instead of writing raw SQL queries.
Safe Code (Using parameterized queries in Python):
safe_query = "SELECT * FROM users WHERE username = ?"
conn.execute(safe_query, (user_input,))