Click here to Skip to main content
Click here to Skip to main content

Hack Proof Your ASP.NET Applications From SQL Injection

, 7 Jun 2013 CPOL
Rate this:
Please Sign up or sign in to vote.
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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Sarvesh Kushwaha
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
Follow on   Twitter   Google+   LinkedIn

Comments and Discussions

 
GeneralMy vote of 5 PinprofessionalAfzaal Ahmad Zeeshan13-Dec-14 5:39 
QuestionPrevent SQL injection PinmemberMember 1106722514-Oct-14 18:14 
QuestionI need help!!! PinmemberMember 1114811512-Oct-14 17:47 
AnswerRe: I need help!!! PinmemberSarvesh Kushwaha13-Oct-14 7:41 
GeneralMy vote of 5 PinprofessionalSibeesh KV21-Sep-14 23:35 
GeneralRe: My vote of 5 PinmemberSarvesh Kushwaha22-Sep-14 6:55 
GeneralRe: My vote of 5 PinprofessionalSibeesh KV22-Sep-14 7:24 
GeneralMy vote 5 PinmemberMember 1100920112-Aug-14 18:56 
GeneralMy vote of 5 PinmemberHumayun Kabir Mamun20-Jun-14 4:45 
GeneralRe: My vote of 5 PinmemberSarvesh Kushwaha20-Jun-14 16:30 
GeneralMy vote of 5 Pinmemberravithejag18-Apr-14 0:38 
GeneralRe: My vote of 5 PinmemberSarvesh Kushwaha18-Apr-14 0:39 
GeneralMy vote of 5 Pinmembercsharpbd23-Feb-14 9:47 
GeneralRe: My vote of 5 PinmemberSarvesh Kushwaha23-Feb-14 18:21 
Generaltest PinmemberDeep Hemant Gabra25-Jan-14 8:41 
GeneralRe: test PinmemberDeep Hemant Gabra25-Jan-14 8:42 
GeneralRe: test PinmemberSarvesh Kushwaha29-Jan-14 19:49 
GeneralMy vote of 5 PinprofessionalRenju Vinod23-Jan-14 2:31 
GeneralMy vote of 5 PinprofessionalMihai MOGA13-Jul-13 21:55 
GeneralRe: My vote of 5 PinmemberSarvesh Kushwaha14-Jul-13 20:40 
GeneralMy vote of 5 PinprofessionalPrasad Khandekar9-Jul-13 21:55 
GeneralRe: My vote of 5 PinmemberSarvesh Kushwaha9-Jul-13 22:09 
Thanks Smile | :)
GeneralRe: My vote of 5 PinmemberSarvesh Kushwaha9-Jul-13 22:21 
GeneralEmbedded Dynamic Sql is just asking for trouble PinmemberJohn B Oliver30-Jun-13 13:35 
GeneralRe: Embedded Dynamic Sql is just asking for trouble Pinmembermidnight_21-Jul-13 21:00 

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

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

| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.141223.1 | Last Updated 8 Jun 2013
Article Copyright 2013 by Sarvesh Kushwaha
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid