Tuesday, January 27, 2009

Why you should not use ‘OR 1=1’ when testing for SQL injection (part 2)

In my previous post, I explained why testing for SQL injection using ‘OR 1=1’ can lead to data loss. In this article, I will describe an alternative and safer approach.

I like to use ‘AND 1=0’ instead of ‘OR 1=1’. This does not increase the number of items affected by a query, but (in most cases) results in the query returning 0 rows (as 1=0 is never true ?). In our previous example of a site displaying articles, no article would have been displayed. The resulting query would become:

SELECT title,text,hitcount FROM articles WHERE id=1234 AND 1=0

That query would return 0 rows. So now what? We’re looking at the site we’re testing and no article is displayed, so what? It doesn’t mean there’s SQL injection. Well, now we enter ‘AND 1=1’ after the articleID and the following query is executed:

SELECT title,text,hitcount FROM articles WHERE id=1234 AND 1=1

Now the ‘AND 1=1’ does not affect the original query, and article 1234 is displayed. At this point I am pretty sure I have SQL injection and could try a UNION SELECT to extract more information from the database.

Of course, this is not the only solution to this problem, but it’s one of the safest to use (unless the application displays SQL errors). For bypassing authentication I still sometimes use the OR approach, but in most cases you do not have to take the risk.

No comments: