1

I am trying to learn about PHP and SQL Injections, so I have created a login form where users introduce their username and password and click the Login button. Later in the server I get the passed parameters using $_POST global variable.

This is the code used to check if user credentials are valid:

$email = $_POST['u_email'];
$password = $_POST['u_password'];

$query = "SELECT * FROM User WHERE EMAIL='$email' AND PASSWORD='$password'";
$result = $mysqli->query($query);
$counter = mysqli_num_rows($result);

if($counter == 1)//Correct Login

The problem is that I think that if a user enters the following text in the username and password fields, the login should be done (although they are not valid values because they do not exist in the DB).

Username: xxx' OR '1'='1/*
Password: */

I think so because that would be translated to:

$query = "SELECT * FROM User WHERE EMAIL='xxx' OR '1'='1/*' AND PASSWORD='*/'";

In other words:

$query = "SELECT * FROM User WHERE EMAIL='xxx' OR '1'='1'";

But the SQL Injection is not working, why?

My DBMS is MySQL.

6

It's not working because of this:

if($counter == 1)

The injected OR '1'='1' is valid for every single row, and if there are multiple rows in the table, that $counter check will fail.

To get around that, you could do something like this (if I remember my SQL correctly), with anything in $email and this in $password:

' UNION SELECT * FROM User LIMIT 1 --

Nothing will be returned from the first part, but the injected second half of the UNION will get a single arbitrary row.

  • Don't forget you can select a row at random and just keep repeating the query with ever growing exceptions of user IDs to find as much user information as possible over time. – Robert Mennell Jul 7 '16 at 17:42
2

A more common and easy way to comment for SQL injection is to use -- because you have not to close the comment. It also requires only 1 input instead of 2.

In this case, an easy injection will look like :

Username : xxx' OR 1=1;--
Password : not that important

The SQL query will be : SELECT * FROM User WHERE EMAIL='' OR 1=1;-- ' AND PASSWORD='not that important'. Without the comment : SELECT * FROM User WHERE EMAIL='' OR 1=1;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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