Ravindra BagaleCourses & study guides

29. OWASP Top 10 Web Vulnerabilities

29.2 A03 Injection: SQL Injection

SQL injection (SQLi) tevha hoto jevha user cha input thet SQL query madhe jato, ani attacker to query badalto. Chapter 21 madhe aapan sqlmap ne he baghitla; aata concept ani fix.

Vulnerable code (never do this):

// user input goes straight into the query
$id = $_GET['id'];
$sql = "SELECT * FROM users WHERE id = '$id'";

If the attacker sends id = 1' OR '1'='1, the query becomes ... WHERE id = '1' OR '1'='1' – which is always true and returns every row. Worse: 1'; DROP TABLE users;--.

The fix – prepared statements (parameterised queries):

// PDO: the input can never change the query structure
$stmt = $pdo->prepare("SELECT * FROM users WHERE id = ?");
$stmt->execute([$_GET['id']]);
$rows = $stmt->fetchAll();

The database treats the input strictly as data, never as SQL. This is exactly the approach you used in the Chapter 16 reels app. Also apply least-privilege DB users (Chapter 11) so a compromised app cannot drop tables.

Ravindra Bagale's Tip

"Remove quotes from the input (escaping)" is an old, incomplete fix. Prepared statements are the only correct fix – they keep the query and the data separate. We did exactly this in Chapter 16. Never join user input directly into a query.

Lab

In DVWA (SQL Injection, security = low), use 1' OR '1'='1 to dump all users. Then set security to "high" and try again – it fails. Open your reels app code and confirm every query uses prepared statements; fix any that do not.