Thursday, June 3, 2010

SQL Injection Exposed

Structured Query Language (SQL) is the nearly universal language of databases that allows the storage, manipulation, and retrieval of data. An SQL query comprises one or more SQL commands, such as SELECT, UPDATE or INSERT. SQL injection is currently the most common form of web site attack. In that web forms are very common, they are often not coded properly and the hacking tools that can be used to find weaknesses and take advantage of them are commonly available online.

Example of SQL Injection:

SELECT queries, has a clause by which it returns data. Suppose for any website my username is "arpit" and password is also "arpit". I entered a username "arpit" and password "arpit" in the form, then I would be logged in. The query that runs behind would look something like this:

SELECT userId FROM Users WHERE userName='arpit' AND userPass='arpit';

but what about if I entered a username "arpit" and a password " ' or 1=1 --" .

[All inputs are without double quotes]

The resultant query would now look like this:

SELECT userId FROM Users WHERE userName='arpit' AND userPass=' 'or 1=1 --'

The query now only checks for any user with a username "arpit" with empty password, or the conditional equation of 1=1. This means that if the password field is empty OR 1 equals 1 (which it does), then a valid row has been found in the users table. Last quote is commented out with a single-line comment delimiter (--). This stops returning an error about any unclosed quotations. Doing the same thing to the username field, like this:

Username: ' or 1=1 ---

Password: [Empty]


This would execute the following query against the users table:

SELECT userId FROM Users WHERE userName=' ' or 1=1 --' AND userPass='[Anything] '

Then we would also be logged in as a user that has the first entry in users table. For more information about SQL Injection visit http://www.unixwiz.net/techtips/sql-injection.html and search on google about it.

Preventing SQL Injection Attacks

If you design your scripts and applications with care, SQL injection attacks can be avoided most of the time. There are a number of things that we as developers can do to reduce our site's susceptibility to attack.

1. Replacing quotes : Majority of injection attacks require single quotes to terminate an expression. By using a simple replace function and converting all single quotes to two single quotes, you're greatly reducing the chance of an injection attack succeeding.

2. Limit the Length of User Input

3. Remove Culprit Characters/Character Sequences

No comments:

Post a Comment