Click here to Skip to main content
15,868,340 members
Articles / Web Development / ASP.NET

Hack Proof Your ASP.NET Applications From SQL Injection

Rate me:
Please Sign up or sign in to vote.
4.85/5 (65 votes)
7 Jun 2013CPOL4 min read 132.7K   2.4K   81   39
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 -

C#
' 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

C#
//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.

C#
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 .

C#
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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
India India
I do believe life is to help others ... So here i am .. in my spare time i learn new things of programming and try to help people with my knowledge .
I'm an energetic, self-motivated and hard-working Developer and Information Technology Professional with experience in projects, website design and development.

Visit My Technical Blog

Comments and Discussions

 
GeneralMy vote of 5 Pin
Afzaal Ahmad Zeeshan13-Dec-14 4:39
professionalAfzaal Ahmad Zeeshan13-Dec-14 4:39 
GeneralRe: My vote of 5 Pin
Sarvesh Kushwaha29-Dec-14 23:27
Sarvesh Kushwaha29-Dec-14 23:27 
QuestionPrevent SQL injection Pin
Member 1106722514-Oct-14 17:14
Member 1106722514-Oct-14 17:14 
QuestionI need help!!! Pin
Member 1114811512-Oct-14 16:47
Member 1114811512-Oct-14 16:47 
AnswerRe: I need help!!! Pin
Sarvesh Kushwaha13-Oct-14 6:41
Sarvesh Kushwaha13-Oct-14 6:41 
GeneralMy vote of 5 Pin
Sibeesh KV21-Sep-14 22:35
professionalSibeesh KV21-Sep-14 22:35 
GeneralRe: My vote of 5 Pin
Sarvesh Kushwaha22-Sep-14 5:55
Sarvesh Kushwaha22-Sep-14 5:55 
GeneralRe: My vote of 5 Pin
Sibeesh KV22-Sep-14 6:24
professionalSibeesh KV22-Sep-14 6:24 
GeneralMy vote 5 Pin
Member 1100920112-Aug-14 17:56
Member 1100920112-Aug-14 17:56 
GeneralMy vote of 5 Pin
Humayun Kabir Mamun20-Jun-14 3:45
Humayun Kabir Mamun20-Jun-14 3:45 
GeneralRe: My vote of 5 Pin
Sarvesh Kushwaha20-Jun-14 15:30
Sarvesh Kushwaha20-Jun-14 15:30 
GeneralMy vote of 5 Pin
ravithejag17-Apr-14 23:38
ravithejag17-Apr-14 23:38 
GeneralRe: My vote of 5 Pin
Sarvesh Kushwaha17-Apr-14 23:39
Sarvesh Kushwaha17-Apr-14 23:39 
GeneralMy vote of 5 Pin
csharpbd23-Feb-14 8:47
professionalcsharpbd23-Feb-14 8:47 
GeneralRe: My vote of 5 Pin
Sarvesh Kushwaha23-Feb-14 17:21
Sarvesh Kushwaha23-Feb-14 17:21 
Generaltest Pin
Deep Hemant Gabra25-Jan-14 7:41
Deep Hemant Gabra25-Jan-14 7:41 
GeneralRe: test Pin
Deep Hemant Gabra25-Jan-14 7:42
Deep Hemant Gabra25-Jan-14 7:42 
GeneralRe: test Pin
Sarvesh Kushwaha29-Jan-14 18:49
Sarvesh Kushwaha29-Jan-14 18:49 
GeneralMy vote of 5 Pin
Renju Vinod23-Jan-14 1:31
professionalRenju Vinod23-Jan-14 1:31 
GeneralMy vote of 5 Pin
Ștefan-Mihai MOGA13-Jul-13 20:55
professionalȘtefan-Mihai MOGA13-Jul-13 20:55 
GeneralRe: My vote of 5 Pin
Sarvesh Kushwaha14-Jul-13 19:40
Sarvesh Kushwaha14-Jul-13 19:40 
GeneralMy vote of 5 Pin
Prasad Khandekar9-Jul-13 20:55
professionalPrasad Khandekar9-Jul-13 20:55 
Nice and well explained article.
GeneralRe: My vote of 5 Pin
Sarvesh Kushwaha9-Jul-13 21:09
Sarvesh Kushwaha9-Jul-13 21:09 
GeneralRe: My vote of 5 Pin
Sarvesh Kushwaha9-Jul-13 21:21
Sarvesh Kushwaha9-Jul-13 21:21 
GeneralEmbedded Dynamic Sql is just asking for trouble Pin
John B Oliver30-Jun-13 12:35
John B Oliver30-Jun-13 12:35 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.