Ubuntu - ModSecurity - Testing SQL Injection

Before going ahead with configuring rules, we will create a PHP script which is vulnerable to SQL injection and try it out. Please note that this is just a basic PHP login script with no session handling. Be sure to change the MySQL password in the script below so that it will connect to the database:

/var/www/login.php
<html>
<body>
<?php
  if(isset($_POST['login']))
  {
    $username = $_POST['username'];
    $password = $_POST['password'];
    $con = mysqli_connect('localhost','root','password','sample');
    $result = mysqli_query($con, "SELECT * FROM `users` WHERE username='$username' AND password='$password'");
    if(mysqli_num_rows($result) == 0)
        echo 'Invalid username or password';
    else
        echo '<h1>Logged in</h1><p>A Secret for you....</p>';
  }
  else
  {
?>
    <form action="" method="post">
      Username: <input type="text" name="username"/><br />
      Password: <input type="password" name="password"/><br />
      <input type="submit" name="login" value="Login"/>
    </form>
<?php
  }
?>
</body>
</html>

This script will display a login form. Entering the right credentials will display a message “A Secret for you.”

We need credentials in the database. Create a MySQL database and a table, then insert usernames and passwords.

mysql -u root -p

This will take you to the mysql> prompt

create database sample;
connect sample;
create table users(username VARCHAR(100),password VARCHAR(100));
insert into users values('john','pwd');
insert into users values('alice','secret');
quit;

Open your browser, navigate to http://yourwebsite.com/login.php and enter the right pair of credentials.

Username: john
Password: pwd

You'll see a message that indicates successful login. Now come back and enter a wrong pair of credentials– you'll see the message Invalid username or password.

We can confirm that the script works right. The next job is to try our hand with SQL injection to bypass the login page. Enter the following for the username field:

' or true -- 

NOTE: There should be a space after this injection won't work without that space. Leave the password field empty and hit the login button.

Voila! The script shows the message meant for authenticated users.