Bruno Bruno - 6 months ago 28
SQL Question

SQL inject - BadStore.net

I'm studying some topics of software security and I found this site :
http://teachcryptography.blogspot.com.br/2015/03/badstore-funway-of-exploiting-web.html

I'm trying to leak data using SQL inject in Quick Item Search form.
Here is the query :

"SELECT itemnum, sdesc, ldesc, price FROM itemdb WHERE '$squery' IN
(itemnum,sdesc,ldesc)";


I got the right answer with this input :
1=1'/*
but the input
'-'
is also right. Could someone explain to me why?

Answer

The string '-' (single-quote, hyphen, single-quote) works because of the integer to string casting behavior of some RDBMS. Since what you posted looks like PHP code, I will make the assumption that the database involved is MySQL.

In MySQL, a non-numeric string cast to an integer will result in zero. Further, attempting an arithmetic operation on two strings will first cause them to be cast to integers. So let's look at the string after the value is substituted:

WHERE ''-'' IN (itemnum, sdesc,ldesc)

MySQL will attempt to do subtraction of the two empty strings '', so literally: '' minus ''. To accomplish that, they must first be cast to integers, which are zero (0-0=0). Now it looks like:

WHERE 0 IN (itemnum, sdesc,ldesc)

For the same reason that the non-numeric string casts to zero, this time MySQL will cast the varchar columns sdesc, ldesc to an integer. Unless they begin with numbers, the result of that cast is zero. The 0 from ''-'' then works because the IN() will match any of the listed columns and the varchar have all been cast to equivalent 0.

Here's MySQL attempting arithmetic on the strings:

> select ''-'';
+-------+
| ''-'' |
+-------+
|     0 |
+-------+

Here's MySQL casting the empty string to 0:

 > select CAST('' AS SIGNED);
+--------------------+
| CAST('' AS SIGNED) |
+--------------------+
|                  0 |
+--------------------+

Finally, here's MySQL returning TRUE because integer 0 matches string values:

> SELECT 0 IN (123, 'abc', 'def');
+--------------------------+
| 0 IN (123, 'abc', 'def') |
+--------------------------+
|                        1 |
+--------------------------+