Question

Let's say we have such SQL sentence (running MySQL 5.6):

SELECT * FROM order WHERE orderid = 12345 LIMIT 0, 1

Let's say an orderid is supplied by a user (taken from a request url). We have this "LIMIT 0, 1" part which normaly would return only 1 row of results, but attacker could make orderid be something like "12345 OR 1=1"

SELECT * FROM order WHERE orderid = 12345 OR 1=1 LIMIT 0, 1

Now this would again return only 1 row. Now attacker adds inline comment to the orderid variable "12345 OR 1=1 -- "

SELECT * FROM order WHERE orderid = 12345 OR 1=1 -- LIMIT 0, 1

This time the attacker receives records of every order, because he commented out the "LIMIT 0, 1" part.

However, if proper formatting would be used like this:

 SELECT * 
 FROM   order
 WHERE  orderid = 12345
 LIMIT 0, 1

Inline comments (--) would not comment out "LIMIT 0, 1" as it is on a new line.

Can the attacker somehow remove the 'LIMIT 0, 1" part even with formatting like above?

Was it helpful?

Solution 2

No it won't stop it, the injector could just write:

12345 OR 1 = 1; SELECT * FROM `order`;

Making the full SQL:

 SELECT * 
 FROM   `order`
 WHERE  orderid = 12345 OR 1 = 1; SELECT * FROM `order`
 LIMIT 0, 1;

Which will still return all orders in the first result set, as shown here.

Don't try and reinvent the wheel, parameterised queries and prepared statements are there for a reason!

One of the best websites on this is Bobby-tables.com

OTHER TIPS

Changing a query to be multi-line (on any other kind of formatting) is not a "real" security measure.

You should always check your input before putting it in your query, and input verification should be done according to the input type. If the expected input is a number make sure the input is all digits (no letters, no spaces) and that its size is limited. If the expected input is textual, escape all characters that should be escaped in SQL, and again verify the size of the input is reasonable. These measures will solve the general case.

I recommend a quick Google search on protecting from SQL injection for more such insights.

At least the attacker can select a different row by injecting

 OR orderid = 1 ORDER BY orderid

I prepared an example on sqlfiddle. Btw. your example code is not correct. You used a reserved word (order) as a table name. I had to modify your code regarding this.

Nevertheless I don't think it is a very good idea to use code formatting as a measure against code injection. I suggest to first sanitize the user input and then use bind variables.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top