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

Asp.net web application Security Review: Do's & Don't

By , 19 Dec 2011
Rate this:
Please Sign up or sign in to vote.
This is an old version of the currently published article.

Table of Contents

  1. Overview
  2. Avoid Click Jack Attack:Use X-Frame-Options[Deny]
  3. Restrict Exposed HTTP Method- URL SCAN TOOL
  4. Disabled Directory Listing and Directory Traversal: HTTP Error 403 Vs. 404
  5. Encrypt Connection string in web.config file
  6. Always Set Custom Error Page
  7. Always Pass Secure Cookie
  8. Web Farm Security Norms
  9. Miscellaneous
  10. Addendum :Security Hardening In IIS 6.0 Vs IIS 7.0
  11. Conclusion

1. Overview

This article helps you to build and enable robust web applications with respect to various aspects of securities that needs to be taken care while designing the system. The system that are design without considering the security assessment  leads to non compliance and may come under security threats such systems are vulnerable to harmful attacks. The guide below will foster the strengthening of applications and mitigate a risk of probable attacks and reduce unathourised activities. The problem,scenario and solution statement stated here are .net centric. I tried to cover most essential security review items that causes maximum issues and non compliance.

2. Avoid Click Jack Attack:Use X-Frame-Options[Deny]

In nutshell click of website can be hijacked by any website using click jacking technique. The basic idea behind this concept is making use of z-index property of DIV and IFrame Tag in html page. One can harm the transactions of actual website with dummy website placed just above the actual one. What happens here ? The malicious website will load the actual website page in its html IFrame and put the actual website in the background with transparency set to 'False'. Using this mechanism, dummy website will replicate/simulate the real website with all non -virtual buttons placed exactly above the real website and helping online users to perform the actions on actual website with information provided by dummy website with fraudulent motive.

Click Jacking Technique

Two steps Implementation

  1. Keep the target website under low level Z-INDEX say 5 and AllowTransparency="false"
  2. Keep the dummy website at high level Z-INDEX say 10
<html>
<body>
<iframe src="http://www.microsoft.com" allowtransparency="false" style="float; position: absolute;
        left: -5px; top: 12px; width: 731px; background: white; height: 259px; z-index: 5;
        margin-top: 0px;" border="0" frameborder="0" scrolling="no"/>

<div style="position:absolute; left:0px; top:0px; width: 250px; height: 200px; background:white; z-index:10">

<h1>Click Jacking</h1>

</div>
</body>
</html>

The concept is pretty simple .The phishing website will be placed exactly just above the target website such that whatever action is performed on dummy website will trigger the events of actual website. This is how the foul play will lead to invalid transactions to take place and target website is vulnerable to click –jacking.

Real Time Scenario

Assume there is E-Commerce site where one can purchase the book online. There will be another website with exact replica but with few changes such that users are motivated to transact. A scenario where E-Commerce Site will have button with BUY caption and malicious site will have screen with masked non –event button ‘Donate’ just placed above it. Moment user clicks on masked non-event button ‘Donate’ in reality it will trigger the low level z-index Buy button. This is how hacker can misuse your website for their purpose.

Solution for Click Jacking Website

The below solution is strickely .net centric and every technology will have its own solution for this problem. The x-frame-options is the one area where we can restrict our website from being misused using click jack.

Three solutions to tackle this

Solution 1

Add below code in Global.axa file of your web application solution

void Application_BeginRequest(object sender, EventArgs e)
{
  this.Response.Headers["X-FRAME-OPTIONS"] = "DENY";
}

Point to be noted here. This will indeed throws error such as "Error:This operation requires IIS integrated pipeline mode”

Solution 2: This works absolutely fine for all authentication mode.
void Application_BeginRequest(object sender, EventArgs e)
{
    HttpContext.Current.Response.AddHeader("x-frame-options", "DENY");
}
Solution 3: We can directly set this restriction by adding custom X-Frame-options

The websites are vulnerable to click-jacking which can allow an attacker using Cross Site Scripting (XSS) to trick a user into clicking a malicious link Procedure to send out the X-Frame-Option Header Using IIS.

  1. Open IIS (by run inetmgr command)
  2. Go to the Website folder and right click on your website, & go to the Properties.
  3. Go to the HTTP Header Tab.
  4. Go to Custom Header section.
  5. click on Add
  6. Custom Header Name: X-Frame-Options Custom Header Value: "DENY" (without the quotes). or "SAMEORIGIN"
  7. if any subdirectory website is there then IIS will ask you to override this to subdirectory website.
  8. Ok and restart IIS by run iisreset command

Note: Ensure you either add DENY or SAMEORIGIN.Each one has its own significance. If one wants to apply at application level ,the simple solution is add below line of code in Global.asax file under following event.

Reference: Anti Click Jack:http://blogs.msdn.com/b/sdl/archive/2009/02/05/clickjacking-defense-in-ie8.aspx

 What is X-frameoptions DENY ,SAMEORIGIN or NONE http://blogs.msdn.com/b/ieinternals/archive/2010/03/30/combating-clickjacking-with-x-frame-options.aspx

http://technet.microsoft.com/en-us/security/cc242650

http://blogs.msdn.com/b/ieinternals/archive/2010/03/30/combating-clickjacking-with-x-frame-options.aspx

http://msdn.microsoft.com/en-us/library/wce3kxhd.aspx

http://blogs.msdn.com/b/sdl/archive/2009/02/05/clickjacking-defense-in-ie8.aspx

https://www.owasp.org/index.php/Clickjacking

http://blogs.msdn.com/b/ie/archive/2009/01/27/ie8-security-part-vii-clickjacking-defenses.aspx

http://www.syfuhs.net/category/IIS.aspx

3. Restrict Vulnerable HTTP Method- URL SCAN TOOL

HTTP Methods that can be exploited are enabled.The OPTIONS HTTP method is enabled. The OPTIONS method can be used in foot printing/profiling the application/server. the answer to this problem is URL Scan tool.

Download URL SCAN TOOL

Why URL Scan?

UrlScan tool is a security tool that scans and restricts incoming HTTP requests that are processed by IIS. By blocking specific HTTP requests, UrlScan helps prevent potentially harmful requests from being processed by web applications on the server.This tool enables options to apply security rules and policies that are must when http request is passed to or process by IIS. Its bit confusing for first time to understand a URL scan concept for any novice learner. Basically this tool provides a configuration template which helps us define our own rules or can use the existing rules as is if applicable to application and business requirement.

Advantage

It helps avoid running malicious code, requests that coming to IIS and which can be threat and harmful for overall website functioning.

What does it do?

The rules basically monitors and act as inspectors to restrict harmful incoming request send to IIS. But to make this work we need to install URLscan in web server where IIS is a hosting platform. Now this URL scan comes with default configuration settings. We can modify these configurations as per our requirement and leverage its benefits.

Define Rules and Policy

  • Rules to block SQL Injections
  • Rules to set URL Format
  • Limit Length of header Values
  • Limit Max length of URL
  • Limit Max Length of Query string in URL
  • Limit Request’s Content Length
  • HTTP Method –Get POST,Head,trace

For more deep dive check this out http://learn.iis.net/page.aspx/476/common-urlscan-scenarios/

Where do we configure above ruleset?

All the above rules are presents in UrlScan.ini configuration and as per our business requirement or compliance we can reconfigure or add custom configurations in it. The sample configuration settings are given below.

Alternative to URL SCAN

URLScan applies rules to overall website at IIS level. If we want security norms to be applied to specific website and a module then one must look into Security code access options in .net. There are three essential practices that can help us apply security to specific files,directory(URL) and file type. Each of this comes with specification and requirement of its own.

1)FileAuthorizationModule

This basically works with respect to ACL list of file related to .aspx or .asmx. If we rely on IIS for authentication then we need asp.net impersonation. This impersonation works with windows Identity and it’s based on identity token passed to IIS. This is all about impersonation. I won’t take much time explaining all this for now. I just want reader to focus on security code access and spend time understanding the concepts and theory behind it. Mostly we face security enablement issues in MOSS and PPS installation where we need to setup environment right in first time and then all it goes with codes and deliverables.

Asp.net Required ACL List

public sealed class FileAuthorizationModule : IHttpModule

2) UrlAuthorizationModule

Usually we have three main line item for URL authorization. It needs role based security module in place where we can have domain groups with role assigned to users for specific business requirement. Coming to Verbs, this is HTTP Method type that can be GET-POST-HEAD-OPTIONS-TRACE-FIND and so on. This is what we saw in URL SCAN TOOL. Based upon our server environment we can set this HTTP Method type. Say for example we may enable TRACE and Options in test and development environment whereas we don’t want this to be there in production as it may harm performance and leak information related to server or configurations that are in place.

USER-ROLE-VERBS.

  • User *(All authenticated users/? Anonymous users/Or defined deterministic users)
  • Role(Domain/Admin- Domain/BusinesUser- so On)
  • VERBS-HTTP MEHTOD-GET,POST,HEAD,OPTIONS,FIND ,TRACE etc
 <authorization>
  <[allow|deny] users roles verbs />
</authorization>
<authorization>
  <allow verbs="GET" users="*"/>
  <allow verbs="POST" users="xyz"/>
  <deny verbs="POST" users="*"/>
</authorization>

HttpForbiddenHandler: Exclude Unnecessary Unsed File Extension

Disable remoting, batch files, executable on internet facing web servers.(.rem,.soap,.bat,.exe). Additionally if we know a given set of extension files are not been used in our application we can assigned it under HttpForbiddenHandler. Ref: Implement HttpForbiddenHandler In IIS Ref: Securing Web Server

<system.web>
    <httpHandlers>
         <add verb="*" path="*.mdb" type="System.Web.HttpForbiddenHandler" />
         <add verb="*" path="*.csv" type="System.Web.HttpForbiddenHandler" />
         <add verb="*" path="*.private" type="System.Web.HttpForbiddenHandler" />
	<add verb="*" path="*.rem" type="System.Web.HttpForbiddenHandler"/>
	<add verb="*" path="*.soap" type="System.Web.HttpForbiddenHandler"/>
	<add verb="*" path="*.asmx" type="System.Web.HttpForbiddenHandler"/>
    </httpHandlers>
</system.web>

4. Disabled Directory Listing and Directory Traversal: HTTP Error 403 Vs. 404

The application has directory listing enabled allowing users to see internal view of application and all pages available.Say for example- You've website NewBee-Website with directory listing such as Website/Image, Website/Script, Website/UI

Normally user will browse application pointing to this source website https://NewBee.com. The site will work as expected.

Senario1- If ignorantly one type url address such as https://Newbee.com/UI then in such case it will list all files under that directory/folder . Doing this your site is vulnerable to security threat. You allow user to guess the directory structure.

Scenario2- Suppose if directory listing is prohibited and http request error code 403 is enabled then user will get message directory browsing is forbidden. That means the UI-folder directory is valid and UI named folder exist in some form. This provides one step accessibility options to hacker so as to educate one about directory structure and files placement.

Remediation and workaround

  1. Disabled directory listing- Check for Custom Error 403 is set
  2. Configure web server to display a HTTP 404 error page in the cases when a user tries to perform a directory traversal. Display an HTTP 404 error instead of HTTP 403 error as a malicious user can use the HTTP 403 error to map the applications structure.

How to configure HTTP 404 Error in place of HTTP 403?

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
 
namespace MyNameSpace 
{ 
    public class NoAccessHandler: IHttpHandler 
    { 
 
        #region IHttpHandler Members 
 
        public bool IsReusable 
        { 
            get { return true; } 
        } 
 
        public void ProcessRequest(HttpContext context) 
        { 
            context.Response.StatusCode = 404; 
        } 
 
        #endregion 
    } 
}
<httpHandlers>
      <add verb="*" path="UI/*" validate="false" type="MyNameSpace.NoAccessHandler"/>
</httpHandlers>
<system.webServer>
        <handlers>
      <add name="NoAccess" verb="*" path="UI/*"  preCondition="integratedMode" type="MyNameSpace.NoAccessHandler"/>
    </handlers>
</system.webServer> 

5. Encrypt Connectionstring in web.config file

Never ever keep clear plain connectionstring in web.config file. The risk and consequences of this is self expalanatory.All you need to do is follow below steps and you are through with this.

Steps to be followed.

  1. Go to Visual Studio Command prompt in the “C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\”path.
  2. Install ASP.NET using aspnet_regiis –I command
  3. Encrypt Web.Config connectionStrings using below command;
  4. aspnet_regiis -pef "connectionStrings" path of the physical folder where web.config resides (e.g. aspnet_regiis -pef "connectionStrings" D:\Apps\NewBeeWebsite)
  5. You will get the message “Encrypting configuration section... Succeeded!”
  6. Run Following Commands;
  7. aspnet_regiis -pa "NetFrameworkConfigurationKey" "ASPNET"
  8. aspnet_regiis -pa "NetFrameworkConfigurationKey" "NETWORK SERVICE"
  9. aspnet_regiis -pa "NetFrameworkConfigurationKey" "NT AUTHORITY\NETWORK SERVICE"
  10. Restart IIS

6. Always Set Custom Error Page

Why Custom error message?Enable customerror page option in web.config file Never ever reveal the source level error message to end users. This will help users to understand the symantics of your code and flow. For any application level exception it is good practice to display custom error page. 

<customErrors mode="On" defaultRedirect="ErrorPage.aspx" /> 

7. Always Pass Secure Cookie

This secure cookies attribute prevents the cookie from being sent to HTTP traffic.Set the SECURE flag on all cookies: Whenever the server sets a cookie, arrange for it to set the SECURE flag on the cookie. The SECURE flag tells the user's browser to only send back this cookie over SSL-secure HTTPS connections; the browser will never send a SECURE cookie over an unencrypted HTTP connection. The simplest step is to set this flag on every cookie your site uses.

<httpCookies httpOnlyCookies="true" requireSSL="true" /> 

8. Web Farm Security Norms

Secure Viewstate and safeguard its Integrity

In form based authentication it is important to safeguard view state especially when it there are web servers in load balanced mode in web farm. In such scenario requests from client to servers are unknown and it may hit request onto server as per given threshold user load and it is non deterministic. The hacker may temper your viewstate and integrity of viewstate is hampered. In order protect viewstate from getting damage while at transmit from client to server and vice-versa we must apply <% @ Page enableViewStateMac=true >. This will generate machine authentication code for viewstate generated at page level. This will keep page level viewstate intact. But again we need to tighten this security when we have Wed farm environment. Here we again have to maintain another level of integrity.

  1. Level 1: At page level integrity :<% @ Page enableViewStateMac=true >
  2. Level 2: If webserver is in web farm mode then apply common encryption and decyption across all webserver

In all webserver’s machine.config we need to keep the machinekey consistent and same so that it has same encryption and decryption key.

<machineKey validationKey="AutoGenerate "
            decryptionKey="AutoGenerate"
            validation="SHA1"/>

Session State Management

As I said earlier in web farm environment. The consecutive/successive requests from same logged in users may hit different web servers in web farm. In such case integrity of session having user credential may lost and user session across web server is not maintained and information is lost. This may results in invalid session for each successive request. The only workaround is to store session SQL state management (Out of process state management).

Reference : http://msdn.microsoft.com/en-us/library/ff649337.aspx

9. Miscellaneous

Application Hardening- Few hard facts that are prerequsites and first level security based application hardening that are must and one has to take care.

  1. Handle SQL injection. URL scan also help prevent sql injection. Handle sql injection in sql script as well as in front end level. What is required is, deterministic client side validation. Try to use as much as client side validation and use server side only when it required most.
  2. Always encrypt querystring if used in your application. The querystring expose the application data and helps user gather more information to hack the site.
  3. Try using less hidden field in application.
  4. Encrypt viewstate. Ref http://msdn.microsoft.com/en-us/library/aa479501.aspx
  5. Never keep highly confidential data in cookies.
  6. IMPORTANT: INSTALL SSLSCAN.exe tool to verify weak cipher suites and it shouldn't be below 128 bit.For E.g Preferred Server Cipher(s) SSLv3 256 bits.
  7. Disable application trace and debug mode [false]

Addendum :Security Hardening In IIS 6.0 Vs IIS 7.0

IIS 6.0 vs. IIS 7.5

The above content are more in line with what we used to have in existing infrastructure setup and most of the applications in production is still in IIS 6.0 and window server 2003. As per the demand and ongoing migrations the above security aspects are really taken care in IIS7. To make this article more useful and better, I’ve added few contexts on IIS7.5 with respect to radical changes it underwent since the inception of IIS7.0.

IIS 6.0 Architecture

Internals of IIS 7

Sr. No

IIS 6

IIS 7

1

 IIS6.0- it has its own authentication and Authorization and asp.net has its own authentication and authorization mode. There is isolation in terms of Authentication and authorization.

IIS 7.5 has only authentication option with asp.net having only authorization mode enabled.

IIS 7.5 has two mode Classic(which apt IIS 6.0) and Integrated mode where authentication lies on IIS whereas authorization lies in Asp.net

 

2

IIS 6.0 it has anonymous access that exist in users and Guest group IIS_WPG

IIS 7.5 it has anonymous access assigned to new windows built- in user IUSR that exist in user group – IIS_IUSRS. This replaces IIS 6.0 IIS_WPG with IIS_IURS. This group does not require user id/password.

There is an option to include Application pool Identity as a anonymous user.

3

IIS6.0 There is web service Extensions to enable non static such as asp.net ,webdav, server side includes etc.

IIS7.5 these feature is available directly and enabled by default. That is part of CGI and ISAPI.dll restriction that can be set accordingly

4

IIS6.0 we can use URL scan to set rules to apply restrictions on URL Request filtering.

IIS7.5 it is built in feature Request Filtering.

Query strings

Header

File Name Extension

HTTP Verbs

Rules- e.g SQL Injection

URL

5

IIS 6.0 wild card script mapping available

IIS7.5  wild card mapping available with classic IIS6.0 and integrated pipeline mode IIS7

Just look for <modules runAllManagedModulesForAllRequests="true">

http://weblogs.asp.net/scottgu/archive/2007/02/26/tip-trick-url-rewriting-with-asp-net.aspx

 

http://haacked.com/archive/2010/12/22/asp-net-mvc-3-extensionless-urls-on-iis-6.aspx

 

http://learn.iis.net/page.aspx/508/wildcard-script-mapping-and-iis-integrated-pipeline/

 

 

IIS 7 Application Pool- Integrated & Classic Mode with Asp.net Framework option

IIS 7 Request Filtering: Alternative to URL Scan

This is just an overview of IIS and there are lot more information available online for reference. This will give pointer to reader to delve more into IIS to understand security implications if not handled or configure properly.

10. Conclusion

It’s good to incorporate the necessary key security best practices during design phase thus ensuring system is not at risk and at the same time it is hack-resilient.The references given in this article is really very informative and I insist the reader should take some time going through this. I hope I justified the reader's expectation and it must have helped them in a good way.

Reference

Secure Web Server

Building Secure Asp.net Pages and Control

MSDN SQL injection 1

MSDN SQL injection 2

SQL injection 3

Document Version

**Added Reference for Viewstate Encyption Dated 30th Nov 2011

**Added Reference for SQL Injection Dated 1st Dec 2011

**Added Reference for web farm security considerations Dated 5th Dec 2011

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

santosh poojari
Technical Lead
India India
Whatsup-->Exploring--> MVC/HTML5/Javascript & Virtualization.......!
www.santoshpoojari.blogspot.com

Comments and Discussions


Discussions posted for the Published version of this article. Posting a message here will take you to the publicly available article in order to continue your conversation in public.
 
QuestionMy vote of 4. Pinmembersucram29-Nov-11 3:57 
AnswerRe: My vote of 4. Pinmembersantosh poojari1-Dec-11 17:24 

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 | Mobile
Web04 | 2.8.140415.2 | Last Updated 20 Dec 2011
Article Copyright 2011 by santosh poojari
Everything else Copyright © CodeProject, 1999-2014
Terms of Use
Layout: fixed | fluid