Monday, June 29, 2009

SQL Injection: Tutorial Part 1

SQL Injection
What? What is SQL ? SQL stands for Structured Query Language, It is the most widely used database querying language. Before reading on I must say that this is an old technique and I dint want this to be posted because most sites have patched up this hole. I am posting this for the few websites I came across that had this vulnerability. If you have a website or planning to build one or administrates one please read on and fix the security holes.

Warning: The following methods may be illegal, given for illustration purpose only.

Most dynamic websites use a database server such as SQL Server from Microsoft, MySQL, etc. To demonstrate what SQL injection is, let us see a piece of code that is used as a login script. Most ASP websites use a code like this:

<%
user = Request.Form("user")
pass = Request.Form("pass")
SQL = "SELECT * FROM users WHERE username='" & user & _
"' AND password='" & pass & "'"
' Execute the SQL ...
%>


This is an example of a poor code which is vulnerable to SQL injection. In this example we can see that the user input of user and pass is directly included in the SQL query.

A legitimate user enters his details, say
user=digitalpbk
pass=password

The SQL query would be constructed as based on the code as
SELECT * FROM users WHERE user='digitalpbk' 
AND pass='password'


Now in order to demonstrate or find if there is an SQL injection hole, all an user has to do is add a ' (single quote) to the username and/or password fields, say
user=digitalpbk
pass=password'

Now the SQL query would be constructed as
SELECT * FROM users WHERE user='digitalpbk'
AND pass='password''


This will throw up an invalid SQL and if the errors are not supressed you will get a screen as shown below:



So if we modify the user input field pass such that
user=digitalpbk
pass=password' OR '1'='1,

the constructed SQL query would be
SELECT * FROM users WHERE user='digitalpbk'
AND pass='password' OR '1'='1'


Which is a valid query and it would always return true.

This validates the user and logs him in without even checking the username or password.

Prevention/Security Measures
Always escape or filter user input fields. It takes lesser time to do user input filtering (than posting about cyberlaws ). This type of vulnerability is because of the poor codes on the server which practically hands over you the control.

The method demonstrated here is just the teaser, you can do much more sinister things with SQL injection like dropping tables (which is not a good thing)

to be continued...

In case you find a website with such a vulnerability, please inform the webmaster of the condition and refer this page (in case they are ignorant).

Be ethical
Happy Browsing...

1 comments:

alok said...

keep the thread going on