If you have
ever taken raw user input and inserted it into a MySQL database there's a
chance that you have left yourself wide open for a security issue known as SQL Injection.
SQL injection
refers to the act of someone inserting a MySQL statement to be run on your database without your
knowledge. Injection usually occurs when you
ask a user for
input, like their name, and instead of a name they give you a MySQL statement
that you will unknowingly run on your database.
Below is a sample string
that has been gathered from a normal user and a bad user trying to use SQL
Injection. We asked the users for their login, which will be used to run a
SELECT statement to get their information.
MySQL & PHP Code:
// a good user's name
$name = "timmy";
$query = "SELECT * FROM
customers WHERE username = '$name'";
echo "Normal: " .
$query . "<br />";
// user input that uses SQL
Injection
$name_bad = "' OR 1'";
// our MySQL query builder,
however, not a very safe one
$query_bad = "SELECT *
FROM customers WHERE username = '$name_bad'";
// display what the new query
will look like, with injection
echo "Injection: " .
$query_bad;
Display:
Normal: SELECT
* FROM customers WHERE username = 'timmy'
Injection: SELECT * FROM customers WHERE username = '' OR 1''
Injection: SELECT * FROM customers WHERE username = '' OR 1''
The normal query is no
problem, as our MySQL statement will just select everything from customers that
has a username equal to timmy.
However, the injection attack has actually made our
query behave differently than we intended. By using a single quote (') they
have ended the string part of our MySQL query
- username = ' '
and then added on to our
WHERE statement with an OR clause of 1 (always true).
- username = ' ' OR
1
This OR clause of 1 will
always be true and so every single entry in the "customers" table would be selected by this
statement!
No comments:
Post a Comment