Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL-injection - is this (oneliner) safe?

PHP:

$SQL = "SELECT goodies FROM stash WHERE secret='" .  
    str_replace("'",'',$_POST['secret']) .  
"'";  

Could an evil genius hacker inject SQL into my SELECT - How ?

like image 371
T4NK3R Avatar asked Aug 14 '10 20:08

T4NK3R


2 Answers

Why won't you use mysql_real_escape_string() or even better - prepared statements? Your solution seems silly.

like image 52
hanse Avatar answered Oct 05 '22 16:10

hanse


I've had a think about this for a while and I can't see any way to inject SQL into this statement.

An SQL string that starts with a single quotes terminates at the next single quote unless it is escaped with a backslash or another quote (\' or ''). Since you are removing all single quotes there cannot be a doubled quote. If you escape the closing quote you will get an error, but no SQL injection.

However this method has a number of drawbacks:

  • Single quotes in the input are ignored.
  • Backslashes in the input aren't handled correctly - they will be treated as escape codes.
  • You get an error if the last character is a backslash.
  • If you later extend the query to add a second parameter, it would allow an SQL injection attack.

For example:

$SQL = "SELECT goodies FROM stash WHERE secret='" .  
    str_replace("'",'',$_POST['secret']) .  
"' AND secret2 = '" .
    str_replace("'",'',$_POST['secret2']) .  
"'";  

When called with parameters \ and OR 1 = 1 -- would result in:

SELECT goodies FROM stash WHERE secret='\' AND secret2=' OR 1 = 1 -- '

Which MySQL would see as something like this:

SELECT goodies FROM stash WHERE secret='...' OR 1 = 1

Even if it's impossible to cause an injection in this case the drawbacks make this unsuitable for a general purpose way to avoid SQL injection.

The solution, as already pointed out, is to use a prepared statement. This is the most reliable way to prevent SQL injection attacks.

like image 29
Mark Byers Avatar answered Oct 05 '22 16:10

Mark Byers