Go to DotNetFunda.com
 Online : 5606 |  Welcome, Guest!   Login
 
Home > Articles > ASP.NET > Introduction to SQL Injection in ASP.NET

Submit Article | Articles Home | Search Articles |

Introduction to SQL Injection in ASP.NET

 Posted on: 3/25/2009 7:02:59 AM by Vuyiswamb | Views: 1272 | Category: ASP.NET | Level: Beginner | Print Article
Every time I get involve in a new project that I happen to inherit, I always come across sql code in the pages and input that is not trapped. Well some of this applications are used internally and some go to clients externaly. One programmer argued about how dangerous it is to write your sql statement in the pages. In this short article am going explain the reasons why is it not a good programming practice or dangerous to your users if you don’t trap the input or if you write your sql on your pages. It is because it leads to sql injection. What is SQl Injection?

.NET Training Videos!
Buy online comprehensive training video pack just for $35.00 only, see what's inside it.

Background

Wikipedia says SQL injection is a code injection technique that exploits a security vulnerability occurring in the database layer of an application. The vulnerability is present when user input is either incorrectly filtered for string literal escape characters embedded in SQL statements or user input is not strongly typed and thereby unexpectedly executed. It is an instance of a more general class of vulnerabilities that can occur whenever one programming or scripting language is embedded inside another. SQL injection attacks are also known as SQL insertion attacks.[1]

Using the code

We are going to use multiple comments in our article and we are going to use C# as our language.

Start

Let us take an example of a code that i came across in some online catalogue, that was for online shooping application for a client. The code look like this and the page ware written too close to something like this.

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Data;

using System.Data.SqlClient;

using System.Web.Configuration;

 

public partial class _Default : System.Web.UI.Page

{

    protected void Page_Load(object sender, EventArgs e)

    {

 

    }

 

    protected void  Show_Data(String strssearch)

    {

        String strcon = WebConfigurationManager.ConnectionStrings["MYSTRING"].ConnectionString;

 

        SqlConnection con = new SqlConnection(strcon);

 

        String tsql = "select * from dbo.memyself where fname = '" + strssearch + "'";

 

        SqlCommand cmd = new SqlCommand(tsql, con);

 

        con.Open();

 

        SqlDataReader reader = cmd.ExecuteReader();

       

        GridView1.DataSource = reader;

       

        GridView1.DataBind();

 

        reader.Close();

 

        con.Close();

 

    }

 

    protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)

    {

 

    }

    protected void Button1_Click(object sender, EventArgs e)

    {

       

        Show_Data(txtsearch.Text);

    }

}

 

And the aspx page like this

 

 

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

 

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

    <title>SQL Injection Example</title>

</head>

<body>

    <form id="form1" runat="server">

    <div>

   

    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;

        <asp:TextBox ID="txtsearch" runat="server"></asp:TextBox>

&nbsp;

        <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Search" />

        <br />

   

    </div>

    <asp:GridView ID="GridView1" runat="server" Height="169px"

        onselectedindexchanged="GridView1_SelectedIndexChanged" Width="396px">

    </asp:GridView>

    </form>

</body>

</html>

 

And when you run the application,it should show you something like this

 

Now maybe the programmer was happy when he saw that he can search for me :), but now this was a dangerous way of doing things. Let us inject the above application.

 

SQL Injection Begins

 

In the above example a bad user(Hacker) might try to temper with the Sql statement. Often, the main reason for a bad user is to get an error message that will expose the name of the tables and the database. Now as you saw above code;the error handling has not been done and the low level message will show and that info will be used to execute other malicious statements against your database and if it’s an online shopping site;the clients credits card info might be exposed. Now let us inject the above. Enter the Following text:

 

 “Vuyiswa' OR '1' = '1”

 

Oops it gave more than it should have. This brought Dave’s info and it should have brought only vuyiswa. Now my point is that the user can add sql statements on your textbox and return more that what was intended to be seen by clients and that might be someone else’s credit card info. It does not end here, the malicious user might even insert comments and run extra code. In Oracle database comments are done with a (;) and MySql with a (#) code. Or he can use a Batch command to execute an sql command.

Let look at this one. Enter the following

Vuyiswa' ; truncate table dbo.Customers --


 

What happened here? The data in the Table is deleted , I mean all of it. Let us look at it in detail.

 

Vuyiswa' ; truncate table dbo.memyself --

 

With the “;” you start an other line. All this will be executed. Now if you check your table, you will not find any data.

Solution

 

To overcome this problem a Parametrized stored procedure and more input validation like this. A Stored Procedure can be created like this


CREATE PROC prc_search
(
@FNAME varchar(20)
)
AS
SELECT * FROM DBO.MEMYSELF WHERE FNAME = @FNAME

And our function should look like this

protected void Show_Data(String strssearch)

{

String strcon = WebConfigurationManager.ConnectionStrings["MYSTRING"].ConnectionString;

SqlConnection con = new SqlConnection(strcon);

SqlCommand cmd = new SqlCommand();

cmd.CommandText = "dbo.prc_search";

cmd.Parameters.Add("@FNAME", SqlDbType.VarChar, 20).Value = strssearch;

cmd.CommandTimeout = 0;

cmd.CommandType = CommandType.StoredProcedure;

cmd.Connection = con;

SqlDataReader reader = null;

 

try

{

con.Open();

reader = cmd.ExecuteReader();

}

catch (SqlException ex)

{

lblMessage.Text = ex.Message.ToString();

}

if (reader.HasRows)

{

GridView1.DataSource = reader;

GridView1.DataBind();

reader.Close();

con.Close();

}

else

{

lblMessage.Text = "There are no Records Available";

}

}



Now if you go and test the injection again , you will see that the user cannot run sql commands again. i have added a label to show trapped exceptions and named it lblMessage. 

Conclusion
I only truncated the table. I don’t know what the malicious user would do with the data. If it is an online shopping site I don’t know. There are thousands of sites build with this vulnerability and believe me there are malicious users hunt this sites every day.

Thank you

Ngiyabonga


If you like this article, subscribe to our RSS Feed. You can also subscribe via email to our Interview Questions, Codes and Forums section.

Interesting?   Share and Bookmark this kick it on DotNetKicks.com


Experience:8 year(s)
Home page:http://www.VuyiswaMaseko.com
Member since:Sunday, July 06, 2008
Level:HonoraryPlatinum
Status: [Member] [Administrator]
Biography:Vuyiswa Junius Maseko is a programmer for ITS abacus and a moderator in ".NetFunda. Vuyiswa has been developing for 8 years now. his major strength are C# 1.1,2.0,3.0,3.5 and vb.net and sql and his interest are in asp.net, c#, smart clients, Robot Programming(embedded programming).He has been doing a lot of windows development and web development, but lately his projects are web based projects. He has been using .net since the beta version of it. Currently he works on 2.0 but has some project running on 3.5. Thanks to people like Chris Maunder (codeproject), Colin Angus Mackay (codeproject), Dave Kreskowiak (Codeproject), Sheo Narayan (.Netfunda).They have made vuyiswa what he is today.
 Latest post(s) from Vuyiswamb

   ◘ Introduction to DeepZoom Silverlight 3 posted on 3/15/2010 4:15:18 PM
   ◘ How to make your Control Always Available While Scrolling in ASP.NET AJAX posted on 3/11/2010 3:39:02 AM
   ◘ How to Write a Simple login page in Asp.net posted on 3/5/2010 5:53:22 PM
   ◘ How to Execute SSIS Packages in C# ASP.NET Part II posted on 2/24/2010 1:35:03 AM
   ◘ How to Execute SSIS Packages in C# ASP.NET - Part I posted on 2/12/2010 3:05:27 AM


 Responses
Posted by: Thulanekhz | Posted on: 25 Mar 2009 07:30:33 AM

even though we have diverted from what we do. i am glad that there are people like you who keep on enlighting us and passing your knowledge to fundi's(learner) like us.

this is a very vital topic that we tend to overlook.

thank you Vuyiswa!

Kubonga thina (Zulu, we thank you)

Submit Article

About Us | The Team | Advertise | Contact Us | Feedback | Privacy Policy | Terms of Use | Link Exchange | Members | Go Top
General Notice: If you found copied contents on this page, please let us know the original source along with your correct email id (to communicate) for further action.
All rights reserved to DotNetFunda.Com. Logos, company names used here if any are only for reference purposes and they may be respective owner's right or trademarks.
(Best viewed in IE 6.0+ or Firefox 2.0+ at 1024 * 768 or higher)