Take the 2-minute tour ×
Information Security Stack Exchange is a question and answer site for Information security professionals. It's 100% free, no registration required.

I've created a test site in order to learn about SQLi and then protect against it. I may be misunderstanding how it is supposed to behave but at present I'm not getting the results I expect.

The page:

<!DOCTYPE html>
<html><body>

<h1>SQL Injection Test Site</h1>
<h2>Login Form</h2>

<form action="" method="post">
Username: <input type="text" name="username">
Password: <input type="text" name="password">
<input type="submit"></form>

<?php
$db = mysql_connect(***, ***, ***); 
if(!$db){ 
    die('Could not connect: ' . mysql_error()); 
}else{
    mysql_select_db(***);  
}

if(isset($_POST["username"]) && isset($_POST["password"])){
    $username = $_POST["username"];
    $password = $_POST["password"];
    $result = mysql_query("SELECT * FROM customer_data 
                            WHERE username = '$username' 
                               AND password = '$password'");
    $result = mysql_fetch_assoc($result);
    //we would now process the login if details matched
    echo "Logged in: " . $result['username'];
    var_dump($result);
}
?>

</body></html>

The table in the database:

http://imgur.com/FvIbCuz

The input:

username: admin
password: ' OR '1'='1

My expectation is that it would find the admin user and then accept the input from the password field as '1'='1 should evaluate to true. It actually returns the result for the first entry in the table, username JBloggs. This is the bit I don't understand.

Can anyone point out a fault in the code or logic that is causing this behaviour?

share|improve this question

1 Answer 1

up vote 2 down vote accepted

There is no fault in the code. You are using the OR condition. For the first row having the data of the user JBloggs, the username is not admin but 1=1 is true for the first record. Since the two conditions have an OR between them, any single true condition will make the whole statement true that is why you are getting the record of the first row.

share|improve this answer
    
Thanks, now I understand. So is there any way to target the query at the admin user only? I can't see how if the query passes over each row and will pass on the OR true. A lot of tutorials online seem to suggest you can output the contents of a table but I've yet to be successful in trying. –  Scott Helme Jul 21 '13 at 12:34
2  
' OR ('1'='1' AND username=admin)-- should give you the data for admin user –  void_in Jul 21 '13 at 13:36
2  
Thanks. I managed to get it with ' OR username = 'admin –  Scott Helme Jul 21 '13 at 13:53

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.