CODEDIGEST
Home » Articles
Search
 

Technologies
 

Sponsored links
 

CodeDigest Navigation
 

Technology News
No News Feeds available at this time.
 

Community News
No News Feeds available at this time.
 
What is SQL Injection Attack? How to prevent SQL Injection in ASP.Net?

By Bala Murugan
Posted On Nov 26, 2010
Article Rating:
Be first to rate
this article.
No of Comments: 0
Category: ASP.Net
Print this article.

What is SQL Injection Attack? How to prevent SQL Injection in ASP.Net?


SQL injection is an attack where an executable query is inserted or injected with the input data. The injected code will then gets executed with the application identity and hence causing the damage. For example, an attacker can take advantage of this vulnerability to gain access to restricted areas by injecting script to pass the user verification against DB or delete your database or tables very easily.

Moving forward, we will try to understand the SQL injection attack with an example code.

Consider the below code,

private void GetEmp()

    {

        SqlConnection con = new SqlConnection(ConfigurationManager.
ConnectionStrings["ConnectionString"].ConnectionString);

        SqlDataReader dr = null;

        try

        {           

            con.Open();

            SqlCommand com = new SqlCommand("Select * from Employee where EmpID =" + txtID.Text, con);

            dr = com.ExecuteReader();

            while (dr.Read())

            {

                txtAge.Text = dr["Age"].ToString();

                txtName.Text = dr["EmpName"].ToString();

            }

        }

        catch

        {

        }

        finally

        {

            dr.Close();

            con.Close();

        }

    }

In the above code, the SQL query is written inline and the parameter value is concatenated directly reading from TextBox.

See below,

"Select * from Employee where EmpID =" + txtID.Text


Now, consider you are giving the below string as input in the TextBox(txtID),

0;delete from employee; --


When executed, the above code will successfully delete the Employee table data as it is prone to SQL injection vulnerability.

Now, let’s see the above scenario in detail.

If you take a close look at the above input, the semicolon after the number 0 will complete the previous SQL statement. Then comes the disastrous delete statement and -- will make any statement after its occurrence void since it is a commenting operator.

On execution, final query that will be formed and executed will be like below.

Select * from Employee where EmpID =0;delete from employee; --


Now, let see an another example where a user can gain access to restricted sections by bye-passing the authentication logic that has SQL injection vulnerability. Consider the below sql statement which is used for login screen.

"Select count(login) from tblLogin where login = '+"txtLogin.Text"+' and password ='"+txtPass.Text+"' "


Now, a malicious user can give the below input to txtLogin TextBox to bye-pass the where condition.

' OR 1=1 ;--


The above input will produce a SQL query something like below and can produce count greater than 1 and thus achieving his aim.

Select count(login) from tblLogin where login = '' OR 1=1 ;-- and password ='test'


We will now move forward and will understand how to prevent SQL injection in ASP.Net.

1.      Clean input Validation

2.      Use Parameterized SQL query

3.      Using Stored Procedure

4.      Using ORM tools

 

Clean Input Validation

Always have a validation on user input in place. Choose white listing as opposed to blacklisting because we certainly know what is expected as input. But, doing this alone may not be sufficient at times. You need employ other techniques as well.


Use Parameterized Query

This is one way of preventing SQL injection attack. Never believe the user’s input and directly concatenate it with query like above. Instead, it is always advisable to have an input validation and use parameterized query. So the above code can be re-written as,

private void GetEmp(int empid)

    {

        SqlConnection con = new SqlConnection(ConfigurationManager.
ConnectionStrings["ConnectionString"].ConnectionString);

        SqlDataReader dr = null;

        try

        {           

            con.Open();          

            SqlCommand com = new SqlCommand("Select * from Employee where EmpID =@EmpID", con);

            com.Parameters.Add(new SqlParameter("@EmpID", empid));

            dr = com.ExecuteReader();

            while (dr.Read())

            {

                txtAge.Text = dr["Age"].ToString();

                txtName.Text = dr["EmpName"].ToString();

            }

        }

        catch

        {

        }

        finally

        {

            dr.Close();

            con.Close();

        }

    }





Using Stored Procedure

Using stored procedure is another way of preventing SQL injection attack. When using stored procedures, you are forced to use parameters through the parameter collection object of SqlCommand object. So, the above code can be re-written as,

private void GetEmp(int empid)

    {

        SqlConnection con = new SqlConnection(ConfigurationManager.
ConnectionStrings["ConnectionString"].ConnectionString);

        SqlDataReader dr = null;

        try

        {           

            con.Open();          

            SqlCommand com = new SqlCommand("PRC_GetEmployee", con);

           com.CommandType = CommandType.StoredProcedure;

            com.Parameters.Add(new SqlParameter("@EmpID", empid));

            dr = com.ExecuteReader();

            while (dr.Read())

            {

                txtAge.Text = dr["Age"].ToString();

                txtName.Text = dr["EmpName"].ToString();

            }

        }

        catch

        {

        }

        finally

        {

            dr.Close();

            con.Close();

        }

    }

The above code will prevent SQL injection attack.

Sometimes, when using dynamically constructed query in stored procedures it will still carry the vulnerability. Hence, make sure you are doing proper filtrations on the input to remove unwarranted characters (like ‘, ;, etc) from the user input.


Using ORM tools

When you use ORM tools like LINQ to SQL, LINQ to Entities or NHibernate for data access then the tool themselves will handle the SQL injection attacks for you. Since, these ORM tools will generate the query to execute against the DB we need not worry about the SQL injection attacks.


Things to Consider

Using Low Privileged account to execute SQL statement

In SQL injection attack, the injected code will run under the identity of the application. Hence, you can provide very least permission set for the application service account on the database. For example, provide only execute access on database. Again, using this method will not prevent SQL injection attack fully as the malicious user will be still able to execute some script and get some crucial data or bye pass some filtering conditions(as discussed above for login screens) to gain more access than designated.

 

Conclusion

It is really important to protect our web assets from malicious users or programs. SQL injection is one of the most common vulnerability (also, an easy way to take advantage) which can be easily addressed. Hence, your application should prevent this vulnerability at any cause. To recap,

1.      Filter user data or sanitize the data

2.      Use Parameterized query or Stored procedures or use ORM for data access.

3.      As an extra measure, always provide the least required permission for application service account.

Similar Articles
You can contribute to CodeDiget.Com:
Donate to CodeDigest.com
Article Feedback
Comments