The code fails to sanitize the username and password, allowing them to be used directly in the SQL query, creating a vulnerability. An attacker could exploit this by crafting a malicious URL targeting the domain.
/login?username=admin&password=password’ OR ‘1’=’1 |
The password variable is manipulated to include SQL characters, causing the SQL query to return a row, even without knowing the correct password. The resulting SQL query would be:
SELECT * FROM userTable WHERE username = ‘admin’ AND password = ‘password’ OR ‘1’=’1′ |
Parameterized queries are the recommended solution to prevent SQL injection by defining input values and types, ensuring secure query execution. Here’s an example from the previous code:
$username = getUserName(); $pw = getPassword(); $parameterizedQuery = prepare_query(“SELECT * FROM userTable where username = ? and password = ?”); $parameterizedQuery.setString(1, $username) $parameterizedQuery.setString(2, $password) $user = parameterizedQuery.execute(); if ($user) { $loggedIn = True; } else { $loggedIn = False; } |