published on in php security
tags: security mongodb database mysql

(No SQL Inject) or (NoSQL Inject)

SQL Injection? What is it?

I can’t believe you don’t know what is it… But here is a simple example:

$query = "SELECT *
  FROM users
  WHERE Username = '%s'
    and Password = '%s'
  LIMIT 1;";
$res = mysql_query(sprintf(

Ok. This is a very-very simple PHP code to handle User Login. Where is the problem?

$_POST['username'] = "admin' or '1' = '1";
$_POST['password'] = '123';

What the query will be?

  FROM users
  WHERE Username = 'admin' or '1' = '1'
    and Password = '202cb962ac59075b964b07152d234b70'
  LIMIT 1;

And the result will be the admin user.

I use MongoDB… Am I safe?

No. I read somewhere a comment in which he wrote ‘this is more secure’. But not. Let’s see an example:

$user = $mongo_user_collection->findOne(array(
  'username' => $_POST['username'],
  'password' => $_POST['password']

Ok, it’s easy (and ugly) but what happens if I visit your site? I’m not a potential unit-radius user. I’m an attacker and if I know you use MongoDB as database then I will try this:

$_POST['username'] = 'admin';
$_POST['password'] = array('$ne' => '');

Wow… You execute this query:

  "username": "admin",
  "password": { $ne: "" }

Whatever you use… Always pay attention. A simple (or complex) database won’t save your ass.