A SQL injection vulnerability can occur when a poorly-written program uses user-provided data in a database query without first validating the input. This is most-often found within web pages with dynamic content. There are some excellent tutorials and descriptive articles on this subject, as well as many vulnerability postings for different applications from full-disclosure websites.
A simple example of SQL injection is a basic HTML form login in which you provide a username and password:
<form method="post" action="process_login.php"> <input type="text" name="username"> <input type="password" name="password"> </form>
Given this snippet of HTML, one can deduce that the easiest (and worst) way for the script “process_login.php” to work would be for it to build and execute a database query that looks like this:
"SELECT id FROM logins WHERE username = '$username' and password = '$password'";
Under those circumstances, if the variables “$username” and “$password” are taken directly from the user’s input, the login script can easily be tricked into believing that a valid password has been provided by playing with the syntax of the SQL statement. Suppose the following string were provided as the password:
' or '' = '
and we gave “bob” as the username. Once the variables are interpolated, the query above would look like this:
"SELECT id FROM logins WHERE username = 'bob' and password = '' or '' = ''";
This query will return a row because the final clause:
... or '' = ''
will always evaluate to true (an empty string is always equal to an empty string).
Preventing SQL Injection Attacks
The most common methods to prevent this kind of SQL injection vunerability are to check the user’s input for dangerous characters like single-quotes; and using prepared statements, which tell the database exactly what to expect before any user-provided data is passed to it.