If at first you don't succeed, call it version 1.0

Contact Me

Sarvesh Kushwaha
Email : sarveshkushwaha@outlook.com

Total Pageviews

Powered by Blogger.

Google+ Followers

Thursday, 6 June 2013

Hack Proof Your Asp.Net Applications- PART-1 (SQL Injection)


Ahhhh 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(desi) 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 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 : -

  1. String truncations from sql functions
  2. 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 : -
  1. Install backdoors
  2. Can copy database over port 80
  3. Port scan (can scan your whole network)
  4. Many more !! 
How hacker use Sql Injection - THIS is the link of attached vulnerable project .
Following is the vulnerable code .



















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 Example -


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

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 - 
  • Validate user input (Using Regex or anything else)
  • Using Parameterized query 
  • Use Stored procedure

Validate user input -

we will validate the user input using Regular Expression and replace the danger character by blank .

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

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 SqlParemeter in the query .this way we can prevent sql injection .

Code Example - 


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
 .

Using SQL Procedure - 

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

Code by example - 


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();
                    }
                }
            }

So there are many ways to protect the SQL injection but i do think Using stored procedure is the best way and i always prefer using them for my applications.you can download the project and can test it . LINK
Reactions:

0 comments:

Post a Comment