Reputation: 132
I'd like to note first that this is an education attempt on my own database to better understand MySQL injections to protect my own code.
I need to work out a couple of examples of how a MySQL injection can be constructed against the following code. It's a basic user login system where I'm accepting the username and password without any escaping
$user = (!empty($_POST['user'])) ? $_POST['user'] : '';
$pass = (!empty($_POST['pass'])) ? $_POST['pass'] : '';
The MySQL query then tries to find the entered username and password in my table called users, as follows:
$res = mysql_query("SELECT * from users where user='{$user}' AND pass='{$pass}'");
This is un-escaped input, and I'm trying to come up with MySQL injections to:
I've tried a couple of MySQL injection examples from Wikipedia, but I'm guessing the {}
in my query is preventing the injection, so I would appreciate some help from those who are confident with this, and thank you to all.
Upvotes: 5
Views: 9025
Reputation: 11
$user = (!empty($_POST['user'])) ? $_POST['user'] : '';
$pass = (!empty($_POST['pass'])) ? $_POST['pass'] : '';
$user = mysql_real_escape_string($user);
$pass = msyql_real_escape_string($pass);
$res = mysql_query("SELECT * from users where user='{$user}' AND pass='{$pass}'");
That will protect code for you.
Anyone will not be able to DROP
the table.
Upvotes: 1
Reputation: 37065
Try this one out and see if it dumps the entire table:
For both username and password, I enter:
' OR 1=1 AND '}' '=
This of course assumes that I know you are using the curly brace to wrap the data values.
I'm really not sure how MySQL handles mixed logic like that, since it's not enclosed in parenthesis, so let me know if it works!
Upvotes: 0
Reputation: 525
You will not be able to DROP
the table because using mysql_query
you can't send multiple queries.
Upvotes: 3
Reputation: 321698
Something like this should do:
This will make your query look like
$res = mysql_query("SELECT * from users where user='foo' -- ' AND pass=''");
The "-- " means the rest of the line is commented out
This will make your query look like:
$res = mysql_query("SELECT * from users where user='foo' OR (DROP TABLE users) -- ' AND pass=''");
might not accept that though - I think subqueries can only SELECT.
The mysql_query function will only run one query - others would let you do this:
$res = mysql_query("SELECT * from users where user='foo'; DROP TABLE users -- ' AND pass=''");
Upvotes: 5
Reputation: 9121
{} are not the reason. It might be that php's Magic Quotes (now deprecated) protect you from rather simplistic attacks.
However, you can switch them off and then test again.
Upvotes: 0
Reputation: 13972
Here's a long list.
http://ha.ckers.org/sqlinjection/
Your code will obviously fail almost all the test as it is totally unprotected.
Upvotes: 1