Tuesday, December 21, 2010

Sql Injection

Sql Injection

Most of Developers used to write sql queries. But the problem here is "sql injection".

What is Sql Injection

SQL Injection happens when a developer accepts user input that is directly placed into a SQL Statement.
This can allow an attacker to not only steal data from your database, but also modify and delete it.

How Sql Injection works

For example you want to check USER ID and PASSWORD from database and you write the query as follows

select userid from tablename where userid='"+txtUser.Text+"' and password='"+txtPwd "'"

This is called dynamic query building,

suppose i enter values

txtUser -- kartheek

txtPwd -- chkartheek

query becomes

select userid from tablename where userid='kartheek' and password='chkartheek'

and gives output perfectly but the problem is...

suppose an attacker want to login into ur account he enters the text into the userid as follows..

txtUser -- yy' or 'a'='a'--

txtPwd -- xxxxx

then the query becomes as follows

select userid from tablename where userid='yy' or 'a'='a'-- 'and password='kranthikumar'

see the query once here the query checks the condition " userid ='yy' or 'a'='a' " and after the " -- " will be commented

so condition works perfectly and attacker can loggin to your account.

This is what we called SQL INJECTION

How to avoid Sql injection

* Use parameterized queries (SqlCommand with SqlParameter) and put user input into parameters.

* Don't build SQL strings out of unchecked user input.

* Use stored procedures to encapsulate database operations.

SqlCommand cmd = new SqlCommand("select userid from tablename where userid=@userid and password=@password", con);

cmd.Parameters.AddWithValue("@userid", txtUserid.Text);

cmd.Parameters.AddWithValue("@password", txtPwd.Text);

This solves the sql injection.

No comments:

Post a Comment