Can you protect against SQLi without using prepared statements?



  • I am learning about SQLi (SQL injection) and I know that the solution to avoid them is prepared statements. However, does this mean that without them we are sure that we can get hacked? Are prepared statements the only solution? I was thinking about that and I have decided to write a piece of code that I think is safe without using prepared statements. The code is the following.

    $username = escapeSimple($_POST['username']);
    $password = $_POST['password'];
    $sql= "SELECT user_id, username, password
                FROM users WHERE username='".$username."'";
    $result = mysql_query($sql);
    $row = mysql_fetch_array($result);
    if ($username == escapeSimple($row["username"])) {
       if (md5($password) == escapeSimple($row["password"])) {
             //Log in
       }
    }
    

    As you can see in users table I save the passwords using md5.

    I think that this is safe. Am I missing something? Are there some vulnerabilities that I do not see?



  • Not sure what escapeSimple does exactly, but if it behaves like mysqli_real_escape_string then it's ok, as long as you are not using some weird character encoding or forget to set it correctly (UTF8 should be ok by default, as far as I know).

    Remember that using MD5 or any other simple hashing function is considered bad practice today, and you should use better functions which take more resources to compute (and with salts), for example bcrypt, argon2, etc.

    I also don't like that == in the comparison, you should always use === unless you have a good reason to want type juggling. Otherwise you are going to get into trouble and something like this might happen: https://stackoverflow.com/questions/22140204/why-md5240610708-is-equal-to-md5qnkcdzo By the way, there might also be timing attacks to consider (see Alexander O'Mara's comment below).

    That said, your question was about avoiding SQL injection without prepared statements. Yes, it's definitely possible to avoid it, if you are very careful and make sure every statement is correctly constructed and its parts correctly escaped. However in some cases it might be tricky, and to avoid any mistakes of course prepared statements are the way to go.


Log in to reply
 

Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2