sadok-f
sadok-f

Reputation: 1447

PHP: Understand SQL Injection

I'm working on old website and I found this error in log files:

 Invalid SQL: SELECT COUNT(*) AS color_count FROM colors WHERE id IN (on,on) ;

  mysql error: You have an error in your SQL syntax; check the manual that corresponds to
  your MySQL server version for the right syntax to use near
  'on,on) ' at line 1

The code php is like that :

$query  = "SELECT COUNT(*) AS color_count FROM colors WHERE id IN ";
$ids    = implode("','", $_GET['id_color']);
$query  .= "('".$ids."') ";

I resolved this error by adding mysql_real_escape_string.

But I want to understand how an SQL injection can modify the query and remove the simple quotes ' from the query?

Upvotes: 0

Views: 96

Answers (3)

Bill Karwin
Bill Karwin

Reputation: 562230

SQL injection can only add characters, it cannot remove characters from your SQL string. In other words, it's not "SQL suction". :-)

I can think of these possibilities:

  • The error in the log occurred on a date in the past, before your code did quoting. Perhaps it was originally designed to handle only integers, which aren't required to be quoted.

    I recommend noting the date/time of the error in the log, then retrieve the version of code from your source control corresponding to that date.

  • The error was generated by a similar SQL query in another part of your code, where the code fails to quote the values.

    I recommend searching all of your code for similar SQL queries.

  • Your code (or your framework) strips single-quotes out of the SQL string. I can't guess why it would do this, but in theory it's a possibility.

Upvotes: 2

BalticMusicFan
BalticMusicFan

Reputation: 663

It can be ' or '1'='1 if you want to break single quotes (http://en.wikipedia.org/wiki/SQL_injection).

Upvotes: 0

Marshall Tigerus
Marshall Tigerus

Reputation: 3764

SQL injection is a danger (among other cases) anywhere you allow user input to be put directly into the statement. This is why bound statements are more secure and preferred.

The gist of it is, if I can tack on input to the end of your statement, there's nothing to stop me from adding a semicolon to end your current statement, and then a new statement in the same variable. So my string could be:

"11;Drop colors if exists cascade" which a naive execute would execute two statements, one of which completes as you expect, then the malicious one which deletes your table.

Now, a checkbox isn't likely to be a victim of injection, but it should always be a concern.

Do some more research on SQL injection, and really understand it. Then you can start building and modifying code to better combat it.

http://en.wikipedia.org/wiki/SQL_injection

Upvotes: 0

Related Questions