Sql Hacks
What is SQL Injection?
SQL Injection is a code injection technique that exploits a vulnerability in an application's software by manipulating SQL queries. It occurs when user input is improperly sanitized, allowing an attacker to inject malicious SQL statements.
Common SQL Injection Examples
1. Basic SQL Injection
Input:
' OR '1'='1
Query:
SELECT * FROM users WHERE username = '' OR '1'='1' AND password = '';
This always returns true and may bypass authentication.
2. UNION-Based SQLi
Input:
' UNION SELECT null, username, password FROM users--
Query:
SELECT id, name FROM products WHERE id = '' UNION SELECT null, username, password FROM users--';
This can dump sensitive data from another table.
3. Blind SQL Injection
Blind SQLi does not show results directly. It relies on observing application behavior:
Input:
1' AND 1=1-- (returns true)
1' AND 1=2-- (returns false)
How to Prevent SQL Injection
Use Prepared Statements (Parameterized Queries)
In PHP (PDO):
$stmt = $pdo->prepare("SELECT * FROM users WHERE username = ? AND password = ?");
$stmt->execute([$username, $password]);
In Python (with SQLite or MySQL):
cursor.execute("SELECT * FROM users WHERE username = %s AND password = %s", (username, password))
Input Validation
Only allow expected input values (e.g., numbers for IDs).
Escape Inputs (as a fallback)
Use escaping functions, though not preferred over parameterization.
Use ORM Tools
Use frameworks like Laravel (Eloquent), Django ORM, SQLAlchemy, etc., which help avoid raw SQL.
Limit Database Privileges
Avoid using root users in production. Restrict DB user privileges.