Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Hack Proof Your ASP.NET Applications From SQL Injection

0.00/5 (No votes)
7 Jun 2013 1  
This article descirbes what SQL injection is and how to prevent from SQL injection.

Introduction

A developer never wants to get hacked his own web application .But intruder , malicious persons are more than developers, and I used to be one of them and then turned into a developer .As i have walk in both the shoes , so i have decided to write a series of articles which will definitely help to hack proofing a web application .

A developer should always concerned about hack attempts in their applications ,and its a developer duty as well. Lots of online tools, spoofing tools, sniffers tool, etc., are available on the internet .so even a normal internet user can turned into a hacker . i hope everybody knows the consequences of being hacked , so by not describing them , i better do write my article.

lets gets start understanding of some hacks and how a developer can prevent them .in this first article i will start by sql injections.

SQL Injection

SQL injection is an attack in which one or more commands are inserted into a query to form a danger query which may retrieve , damage , manipulate your existed data channel. This almost always occurs when dynamic SQL is being used and when you’re concatenating strings in your code (C#,VB,J#,F#) to form SQL statements. SQL injection can occur in your Microsoft .NET Framework code if you’re forming a query or procedure call, and it can occur in your server-side T-SQL code as well, such as in the case of dynamic SQL in stored procedures.

SQL injection was number one attack in 2010 .And legacy coded applications are still vulnerable to sql injections. let me describe it more clearly or we can say in simple language , it happens when commands(or other sql queries) are inserted where we were supposed to send the DATA into sql .We can divide a whole query into two channel control channel (query) and data channel (user inputs). A attacker usually do not care about your control channel (query) , he just do care ,how he can insert malicious query in your data channel.

There are other ways too to inject sql injection : -

  • String truncations from SQL functions
  • Automated tools

Except being hijacked of any individual or group accounts , sql injection can help to do virtually anything on the system that permissions allow : -

  • Install backdoors
  • Can copy database over port 80
  • Port scan (can scan your whole network)
  • Many more !!

How is it Exploited -

Generally attacker inject the sql Injection directly from the web page or by manipulating sql statements .

In the above code we are concatenating the string with user input data and forming a sql statement .and we supposed to work our query like in the following image -

But a hacker thinks differently , he will manipulate the query as in the following image -

SQL Injection Used in the above example -

' union select username , password ,'1' from [User] --' 

Above is just a example, there are many sql injections which a hacker can try on a application.Hacker can get the passwords , install the backdoor . hacker can manipulate the query to get the data from sysobject for all the database detail .

How to prevent SQL Injections -

  1. Validate user input (Using Regex or anything else)
  2. Using Parameterized query
  3. Use Stored procedure
  4. Use an ORM

1.Validate user input

The simplest way is that we can validate the user input using Regular Expression and replace the danger character by blank

//Validate the user input
string userinput = TextBox1.Text;
 
//only accept the alphabets and numbers , rest will be replaced by blank    
userinput = Regex.Replace(userinput, "[^A-Za-z0-9$]", ""); 

But but this is not the best way to prevent application from sql injection .Because SQL Injection does not only contains "-" or " ' " . There are many sql injections which consists legal code too.

2.Using Parameterized Query -

if we want to use inline SQL ,then to stop SQL injection we can pass the parameter in sql query and can add SQL Parameter in the query .this way we can prevent sql injection .there is nothing wrong in using sql statement inline.

string connectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
//add the parameter in query
string query = string.Format(@"select Username ,Age,Department from " + 
       @"[User] where Username like '%+@Username+%'", TextBox1.Text);

using (SqlConnection con = new SqlConnection(connectionString))
{
    //
    // Open the SqlConnection.
    //
    con.Open();
    //
    // The following code uses an SqlCommand based on the SqlConnection.
    //
    using (SqlDataAdapter da = new SqlDataAdapter())
    {
        using (SqlCommand command = new SqlCommand(query, con))
        {
            //pass the parameter
            command.Parameters.Add(new SqlParameter("@Username",TextBox1.Text)) ;
            DataSet ds = new DataSet();
            da.SelectCommand = command;
            da.Fill(ds, "test");
            GridView1.DataSource = ds;
            GridView1.DataBind();
        }
    }
}

parameterized query tell to the SQL server that data passed into any parameter will remain in the data channel thats how sql server prevent the SQL injection. But still its not the best way as we are writing business logic inline .every time i have to write again this query .

3.Using SQL Procedure -

The best way to prevent from SQL injection is use stored procedure . As business logic are hidden , Its provide better performance , reusability . Now you will have to just protect the table and stored procedure by using permissions .

string connectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
//add the stored procedure name 
string query = "dbo.GetUsername";

using (SqlConnection con = new SqlConnection(connectionString))
{
    //
    // Open the SqlConnection.
    //
    con.Open();
    //
    // The following code uses an SqlCommand based on the SqlConnection.
    //
    using (SqlDataAdapter da = new SqlDataAdapter())
    {
        using (SqlCommand command = new SqlCommand(query, con))
        {
            //pass the parameter
            command.Parameters.Add(new SqlParameter("@param1", TextBox1.Text));
            command.CommandType = CommandType.StoredProcedure;
            DataSet ds = new DataSet();
            da.SelectCommand = command;
            da.Fill(ds, "test");
            GridView1.DataSource = ds;
            GridView1.DataBind();
        }
    }
} 

4.Use an ORM -

We can use any ORM (Entity framework , Nhibernate ,etc ) .ORM makes query parameterized behind the scene so using ORM we can also prevent SQL Injection.

References

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here