0

I currently have this PHP code right now for authentication and I would like to figure out if it's vulnerable to a MySQL injection. Specifically if someone can return fake data with an UNION or other attack and therefore fake the login. I am currently using mysqli_real_escape_string to try to prevent trivial attacks and also attempt to sanitize the request. However, is this code perfectly safe due to the use of mysqli_real_escape_string or is there a security flaw?

$email = mysqli_real_escape_string($database_connection, $_POST["email"]);
$pass = mysqli_real_escape_string($database_connection, $_POST["pass"]);
$query = "SELECT * FROM auths WHERE email='$email' AND pass='$pass'";
$query_result = mysqli_query($database_connection, $query);

if(mysqli_num_rows($query_result) === 1) 
{
    // User is logged in.
}
else
{
    die("Unauthorized");
}
user4819
  • 53
  • 6
  • 7
    [Mysqli prepared statements](http://php.net/manual/en/mysqli.prepare.php) If you're accepting user data, do not use anything else. Period. – Ohgodwhy Nov 03 '14 at 19:45
  • 1
    It's perfectly safe, but it's best if you use [prepared statements](http://php.net/manual/en/mysqli.quickstart.prepared-statements.php). Then you can just simply forget about escaping the data. – Amal Murali Nov 03 '14 at 19:46
  • 1
    Ohgodwhy: How would the injection attack work in this case? What would be an example of bad input? – user4819 Nov 03 '14 at 19:46
  • Example here. **Do not** use mysqli_real_escape_string to protect against SQL injection. http://stackoverflow.com/questions/5741187/sql-injection-that-gets-around-mysql-real-escape-string – Svein Fidjestøl Nov 03 '14 at 19:48
  • @user4819 Just have a look at the thread that was linked by Svein for an example. There are other examples on the web as well. It is not an end all to be all protection measure, and it should not be purported as such. – Ohgodwhy Nov 03 '14 at 19:50
  • Please read http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php – Andy Lester Nov 03 '14 at 20:02
  • **DO NOT** use plain-text passwords. Always follow [proper password hashing procedures](http://www.phptherightway.com/#password_hashing). Additionally, can people stop writing their own terrible authentication systems when any modern [development framework](http://codegeekz.com/best-php-frameworks-for-developers/) like [Laravel](http://laravel.com/) comes with a very good [authentication system](http://laravel.com/docs/security) built-in? – tadman Nov 03 '14 at 20:32

1 Answers1

3

Forget mysqli_real_escape_string. Simply use prepared statements

$conn = new mysqli('host', 'user', 'pass', 'database');        
$stmt = $conn->prepare('select * from auths where email=? and pass=?');
$stmt->bind_param('ss', $_POST['email'], $_POST['pass']);
$stmt->execute();
if($stmt->num_rows > 0):
    //user is logged in
else:
    die('Unauthorized');
endif;
tadman
  • 208,517
  • 23
  • 234
  • 262
Ohgodwhy
  • 49,779
  • 11
  • 80
  • 110