Sunday, July 18, 2010

SQL Injection - Beginner's guide

So much has been told, discussed and written about SQL Injection. But still a variety of applications are vulnerable for such attack.

If you are a tester, and have no clue how to go about testing for SQL Injection vulnerability, here are few tips.

Do you have access to the application's code?

If yes, run a full project search for SQL key words like 'select' , 'insert', 'update' and 'Delete'
If search returns any positive results, study that part of the code.

Are those SQL queries a part of production code? or just a test code?
Are those SQL queries parameterized ?
Do those SQL queries take user input directly ? If yes, is user input sanitized ?
Can you trace back that query to a field in application ? Either in UI or in services ?

So, if you do find direct SQL queries which are part of production code, taking user input with out parameterizing and sanitizing, boy o boy, you are in for a treat!

Now, fire up your favorite SQL profiler. Observe the queries that get executed in DB.

For simplicity sake, lets say an input field like username is vulnerable for SQL Injection.

Assuming the application works fine for a normal input ie,

john

Try following input for the same field :

john'; DELETE from users;--

In Microsoft SQL server, single quotes are used to note the text input, Semi colon denotes end of a SQL query, two hyphens used for commenting.

So, in above input, we are tying to 'inject' a SQL query of our own.

This may or may not work. Data in users table may or may not get deleted.

There are quite a few reasons why it won't work:

Our input might go through field length validation and get truncated
users table might have foreign key constraints
Logged in user account for SQL DB may not have privileges to drop a table
So on ...

So, you would have to study the relevant SQL query that got run in DB, (DB profiler is your friend), use variations of above input to get it working. I'll leave that to your imagination. :-)

In case if you have no access to application code and DB, then blind SQL Injection is your friend. Conceptually, it's similar idea.

Before you try SQL Injection, few words of caution :

Make sure you are on a test system where you can afford to screw up your data.
Make sure you are not affecting your fellow testers' hard work.
Make sure you have a latest DB copy saved somewhere else.

Happy testing!



No comments:

Post a Comment

Your comments won't reflect immediately, might take 10 minutes or a day :)