SQL injections

I'll try to explain it with a simple example.

Let's take a table named 'Users' which has two columns, 'Username' and 'Password'. In the 'Username' field, they store the username and in the 'Password' field they store passwords. For the simplicity, let's assume they are storing the password in plain text (Facebook surely don't store their password in plain text). Now let's look what it looks like the SQL query for a legal user. They will provide the username along with the correct password. So their query will looks like below.

SELECT * FROM Users WHERE Username = 'Ruchira' AND Password = '123'

Here I'm login to that site using my username 'Ruchira' and my password '123' which is the correct one. So now, the select query will return a one row. Now the system know I'm a legal user because it returns a record which matches both my password and username.

Now, let's see how SQL query for a hacker looks like. Hacker knows my Username but don't know my password. So he is TRYING to make a query like below.

SELECT * FROM Users WHERE Username = 'Ruchira' AND Password = 'none' OR 'x'='x'

Now the question is how can a hacker makes such a query.

He can pass the username as I do but problems occurs when he provide the password because he don't know it. Now what he is doing is he provides something which makes the second condition (i.e. Password='none'…. part) always evaluates to true no matter what he provides for the password. In the backend, the website have something likes this

SELECT * FROM Users WHERE Username = '+txtUserName.Text+' AND Password = '+txtPassword.Text+'

Where they are getting the username from txtUserName TextBox and password from txtPassword TextBox. So now, the hacker provides the following value for the txtPassword field

none' OR 'x'='x

So the final query he is sending looks like below

SELECT * FROM Users WHERE Username = '+txtUserName.Text+' AND Password = 'none' OR 'x'='x'

So what basically SQL injection preventions do is, they prevent/ignore users from inserting words such as OR in to the password fields or prevent users inserting special characters such as " ' or distinguish data from the SQL query so the data will not be used to build the query.

No comments: