Skip to main content

Preventing SQL Injection in ASP.NET

What is SQL Injection?

An SQL query comprises one or more SQL commands, such as SELECT, UPDATE or INSERT. For SELECT queries, each query typically has a clause by which it returns data, It’s these types of queries that make the SQL language so popular and flexible… it’s also what makes it open to SQL injection attacks. As the name suggests, an SQL injection attack "injects" or manipulates SQL code. By adding unexpected SQL to a query, it is possible to manipulate a database in many unanticipated ways.

One of the most popular ways to validate a user on a Website is to provide them with an HTML form through which they can enter their username and password. Let’s assume that we have the following simple HTML form:

With the blow example we will understand the SQL Injection You enter the ID of the users, you want to search and click the Search users button. If a match is found in the database, we show the users record in the GridView.

SQL-Server

create table users

(

userId int identity(1,1) not null,

userName varchar(50) not null,

userPass varchar(20) not null

)

insert into users(userName, userPass) values('abc', 'a')

insert into users(userName, userPass) values('pqr', 'p')

insert into users(userName, userPass) values('xyz', 'x')

HTML

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

<head runat="server">

<title>Untitled Pagetitle>

head>

<body>

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

<div>

User ID:<asp:TextBox ID="TextBox1" runat="server">asp:TextBox>

<br>

<br>

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

<br />

<br />

<asp:GridView ID="GridView1" runat="server">

</asp:GridView>

</div>

</form>

</body>

</html>

Code Behind

protected void Button1_Click(object sender, EventArgs e)

{

SqlConnection Objcon = new SqlConnection("Data Source=localhost;Initial Catalog=myDB;integrated security=SSPI");

SqlCommand Objcmd = new SqlCommand();

DataSet Objds = new DataSet();

Objcmd.Connection = Objcon;

Objcmd.CommandType = CommandType.Text;

Objcmd.CommandText = "select * from users where userid='" + TextBox1.Text.ToString() + "'";

SqlDataAdapter Objda = new SqlDataAdapter();

Objda.SelectCommand = Objcmd;

Objda.Fill(Objds);

GridView1.DataSource = Objds.Tables[0];

GridView1.DataBind();

}


The Button1_Click event handler has the required ADO.NET code to get data from the database. This code is highly susceptible to sql injection attack and I will never ever have code like this in production environment. The second line in Button1_Click event handler, dynamically builds the sql query by concatenating the user ID that we typed into the TextBox.

So, for example, if we had typed 3 into the user ID textbox, we will have a SQL query as shown below.

Select * from users where userid=’3’


If a malicious user, types something like ‘3 OR 1=1-- into the TextBox, then we will have a SQL query as shown below.


Select * from users where userid=’’ OR 1=1 –‘

When this query is executed, it shows all the data in the users table. This is SQL Injection Attack, as the user of the application is able to inject SQL and get it executed against the database.

It is very easy to avoid SQL Injection attacks by using either parameterized queries or using stored procedures.


SQL-SERVER

CREATE PROCEDURE sp_getUsers

@Id VARCHAR(255)

AS

BEGIN

SELECT * FROM users WHERE userid=@Id

END

GO

CODE Behind

protected void Button1_Click(object sender, EventArgs e)

{

SqlConnection Objcon = new SqlConnection("Data Source=localhost;Initial Catalog=myDB;integrated security=SSPI");

SqlCommand Objcmd = new SqlCommand();

DataSet Objds = new DataSet();

Objcmd.Connection = Objcon;

Objcmd.CommandType = CommandType.StoredProcedure;

Objcmd.Parameters.Add("@Id", SqlDbType.VarChar, 255, "userid").Value = TextBox1.Text.ToString();

Objcmd.CommandText = "sp_GetUsers";

SqlDataAdapter Objda = new SqlDataAdapter();

Objda.SelectCommand = Objcmd;

Objda.Fill(Objds);

GridView1.DataSource = Objds.Tables[0];

GridView1.DataBind();

}

Now types something like ‘3 OR 1=1-- into the TextBox, then it will thrown an exception



Comments

Popular posts from this blog

Connected and disconnected architecture in ADO.Net with Example

Connected Architecture of ADO.NET The architecture of ADO.net, in which connection must be opened to access the data retrieved from database is called as connected architecture. Connected architecture was built on the classes connection, command, datareader and transaction.  Connected architecture is when you constantly make trips to the database for any CRUD (Create, Read, Update and Delete) operation you wish to do. This creates more traffic to the database but is normally much faster as you should be doing smaller transactions. Disconnected Architecture in ADO.NET The architecture of ADO.net in which data retrieved from database can be accessed even when connection to database was closed is called as disconnected architecture. Disconnected architecture of ADO.net was built on classes connection, dataadapter, commandbuilder and dataset and dataview. Disconnected architecture is a method of retrieving a recor

HTTPHandler and HTTPModule in ASP.NET

If you want to implement pre-processing logic before a request hits the IIS resources. For instance you would like to apply security mechanism, URL rewriting, filter something in the request, etc. ASP.NET has provided two types of interception HttpModule and HttpHandler .   The web server examines the file name extension of the requested file, and determines which ISAPI extension should handle the request. Then the request is passed to the appropriate ISAPI extension.  For Example When an .aspx page is requested it is passed to ASP.Net page handler. Then Application domain is created and after that different ASP.Net objects like Httpcontext, HttpRequest, HttpResponse. HTTPModule: -    It's just like a filter. The Modules are called before and after the handler executes . -    HTTP Modules are objects which also participate the pipeline but they work before and after the HTTP Handler does its job, and produce additional services within the pipeline -  

ASP.NET Page Life Cycle with example

In this article, we are going to discuss the different methods and order they are executed during the load of an .aspx web page. Methods Description Page_PreInit Before page Initialization Page_Init Page Initialization LoadViewState View State Loading LoadPostData Postback Data Processing Page_Load Page Loading RaisePostDataChangedEvent PostBack Change Notification RaisePostBackEvent PostBack Event Handling Page_PreRender Page Pre Rendering Phase SaveViewState View State Saving Page_Render Page Rendering Page_Unload Page Unloading PreInit : The entry point of the page life cycle is the pre-initialization phase called “PreInit”. You can dynamically set the values of master pages and themes in this event. You can also dynamically create controls in this event.  Init : This event fires after each control h