Secure coding techniques in ASP.NET - Part 1

balaji
By balaji

December 17, 2009

A number of applications today are developed with a web interface, and if the Operating System in use is Microsoft Windows then ASP.NET seems to be the ideal choice. Microsoft has taken great initiative in ensuring the ASP.NET framework has some built-in security features that help programmers to develop secure web applications. In this 3 part series, we will be talking about the different components of ASP.NET that programmers can leverage to develop secure web applications.

A number of applications today are developed with a web interface, and if the Operating System in use is Microsoft Windows then ASP.NET seems to be the ideal choice. Microsoft has taken great initiative in ensuring the ASP.NET framework has some built-in security features that help programmers to develop secure web applications. In this 3 part series, we will be talking about the different components of ASP.NET that programmers can leverage to develop secure web applications.

We will look at how ASP.NET helps defend against some of the commonly known vulnerabilities like SQL injection, Cross Site Scripting(XSS) and Cross Site Request Forgery (XSRF).

SQL injection

Probably the most notorious attack on applications, that relies on manipulating SQL statements constructed by the application. This vulnerability is caused as a result of usage of concatenated SQL statements as the one shown below

Select * from User_table where username = "  + txtuser + " and
password = " + txtpassword + ''";

Above is a SQL query used to login to the database. A few highlights on this, is that SQL query is constructed using string concatenation. User input is directly fed into the strings. The number of rows returned will determine whether the user is able successfully login.

A SQL injection string like ' OR 1=1# in the username field will result in the following query.

Select * from User_table where username = '' OR 1=1# ' and
password = 'blah'
;

The above query when sent to the database will return all rows in the user_table table. The # will comment out rest of the SQL query.

Thus the attacker injected a SQL fragment that altered the SQL query. This way an attacker could potentially execute stored procedures, drop tables or shutdown databases.

To prevent such attacks, ASP.NET provides ADO.NET components to help developers construct a parameterized SQL statement as opposed to the above concatenated SQL statement.

Steps to create a parameterized statement in ADO.NET

  1. Create the database connection
    • SqlConnection myConnection = new SqlConnection();
    • myConnection.ConnectionString = "Data Source=localhostSQLEXPRESS Initial Catalog=Pubs;Integrated Security=SSPI";
    • myconnection.open()
  2. Create the SQL command
    • SqlCommand myCommand = new SqlCommand();
    • myCommand.Connection = myConnection;
    • mycommand.CommandText = "SELECT * FROM User_Table where username = @uname and password = @pwd"
    • myCommand.Parameters.AddWithValue("@name",txtuser);
    • myCommand.Parameters.AddWithValue("@pwd",txtpassword);

Thus the user input is now passed as parameters to the SQL query and not as concatenate strings. Now any input passed by the attacker will be taken has a value to the above SQL query and not as part of the SQL query.

Cross Site Scripting

This is one of the top 5 web application vulnerabilities that attackers use to propagate worms and trojans on the internet. In this attack the victim is tricked into running a Javascript that executes on the browser. Using Javascript an attacker can write code to - download a Trojan, steal session tokens from victim’s machine. This is possible in applications that typically allow one user’s input to be viewed by other users of the application. Typical examples of such applications are blogs, forums and social networking site, any webpage that takes in user input from one user and reflects it to another user. This happens because the attacker enters HTML tags like <FRAME>, <SCRIPT>, <a href> etc. These tags are standard HTML tags and will interpreted by the browser as client side HTML or Javascript code.

The standard defense against cross site scripting is to sanitize all "<" and ">" elements in the user input. This will ensure that the when this input is reflected back in the application, the browser will not interpret them as HTML or Javascript tags.

ASP.NET framework provides an XSS filter default to all webpages, which protects against any input that contains HTML or Javascript code. This is the standard .NET XSS filter, and is part of the 'RequestValidation' routine for the page. The attribute ValidateRequest, which is set to ON by default, is responsible for this protection mechanism. It is set to true in the machine.config file and applies to all websites.

In addition to this, ASP.NET also provides utilities that are useful specifically for sanitizing user input or any data that is sent back to the user.

The HTTPUtility class in ASP.NET supports the HTMLEncode and URLEncode methods that help in sanitizing HTML tags and URLs sent back to the user.

Here is a sample code that encodes input retrieved from the database before displaying to the user.

SqlDataReader reader = cmd.ExecuteReader();
Response.Write(Httputility.HTMLEncode(reader.GetString(1)));

Cross Site Request Forgery

This is a much talked about vulnerability and especially affects applications that perform sensitive transactions. Dwayne C Litzenberger, explains in his blog, "when a website is able to fool a user into doing things on another website that the user wouldn't actually want to do." This vulnerability is explained well in an article written by Sapna Satish, sometime back.

The solution is to introduce a random and unique token that is not known to the attacker, so that attacker cannot forge the HTTP request. Without the presence of the token the application will not accept the HTTP request and perform an action. This token can be called as an Anti-CSRF token sent along with every GET/POST HTTP request. This token should be always be validated at the server.

Codeplex.com have come up with an Anti-CSRF token, developed in C#. It is implemented as a HTTP module and consists of a DLL file that can be copied onto the bin folder of the website. The HTTP module configuration should be done in the Web.Config file.

The following settings need to be configured in the Web.Config file to ensure that the CSRF token is associated with every HTTP request.

  • Configure HTTP module
<httpModules>
<add name="AntiCSRF" type="Idunno.AntiCsrf.AntiCsrfModule,
Idunno.AntiCsrf"/>
</httpModules>
  • In the <configuration> section of the web.config file, configure the following settings to ensure that CSRF token is added as a hidden field in every HTML form.
<section name="csrfSettings"
type="Idunno.AntiCsrf.Configuration.CsrfSettings, Idunno.AntiCsrf" />
<csrfSettings cookieName="__CSRFCOOKIE" formFieldName="__CSRFTOKEN"
detectionResult="RaiseException" errorPage="error.html" />

This module only supports inclusion of the CSRFToken as a hidden field in a HTML form. Ensure that the application developed uses HTML forms and POST requests only to update or modify data in the application.

In the next article, we will talk about the use of HTTP modules and global.asax file to perform centralized input validation for a web application.


Tags: Best Practices

About

balaji