9 Tips for Writing Secure Applications in ASP.NET

Security is one of the most important aspects of any application and when we talk about security, particularly in ASP.NET applications, it is not limited to development. A secure app involves multiple layers of security in the configuration, framework, web server, database server, and more. In this post, we’ll take a look at the top nine tips for writing secure applications in ASP.NET… Read complete post on Infragistics blog

IIS7 and Higher : system.webServer element ApplicationHost.config vs Web.config

Hi All,

This is another post on Authentication for ASP.NET applications. In one of my last posts, I talked about setting up authentication mode as Windows in web.config and Enabling/Disabling windows authentication at IIS. You can access that post from the below link.

Looking into Windows authentication at Web.config and at IIS
Continue reading

Authentication and Session timeout – Session expired message on clicking the login button

In my starting phase of Career, My client reported me a peculiar issue. They said that they get redirected to session expired page even before they actually Login.

In that application, We developed a generic methodology, then whenever a user clicks on any action that requires a post back, it first checks whether session is expired or not and if expired then redirects to a custom session expired page. Later, user can click on login link and redirected to Login page.

[As asked by one of my blog readers, There could be many ways for the generic methodology. I have seen people place common code at several place like Master Page,  some put in base class that further worked as base class for all the web pages. I used it in a base class. In my view there are other places like Global.asax and methods could be Application_PreRequestHandlerExecute, Application_AcquireRequestState .]

I analyzed that Issue and found that users used to open the website first page which is obviously the Login page and some of them left the page for a while around 15 or more minutes and after that they when they again back to system, used to enter the credentials and click on login button, it redirects them to session expired page.

It left them annoying and even me too. I have myself seen to many application where I open the Login page and after sometime when I enter my Login details but it redirects me to session expired page.

Some of my colleagues was saying, how a session can expire even before successfully login. I have also found many other developers have same question. So I thought of writing a blog post on it.

So first let me explain, how session works

Session_Life_Cycle

So as you can see above, as soon as user accesses the site and the first page gets opened, the countdown of the session timeout starts. So it does not matter whether you Login or not, session will be expired after the specified amount of time. So if your website does not have a check on session expiration before Login then it wont be visible to your user and even if user Logins after the specified amount of time, A new session will be created.

But so many people get confused about authentication and session. Session start and expire does not have any connection with authentication start and authentication timeout. Authentication works separately.

As you know, A user request any Page, It goes through many HTTPModules and lastly served by a HTTPHandler. We can show it pictorially as

ASP.NET Request Proessing

As you can see, An asp.net request goes through many HTTPModules and finally served by a HTTPHandler. Many features of ASP.NET are developed as HTTP Module. Session and Authentication are also developed as HTTPModules . For session handling we have SessionStateModule which is available under the namespace System.Web.SessionState and various Authentication mechanism in ASP.NET like Form Authentication is also available via a HTTPModule FormsAuthenticationModule which is under the namespace System.Web.Security.  So these two are separate modules and works independently.

Normally in our application, as soon as user clicks on sign out, we used to kill session. Normally, we set authentication time out and session timeout same but what may happen if we have

<forms timeout="15" loginUrl="Login.aspx" name=".ASPXFORMSAUTH">

and

<sessionState timeout="10">

What could happen

user's browsing history

As you can see in the above scenario, I have set session time out is less than authentication timeout. After browsing for 5 mins, I left it for around 12 mins and my session got timeout.  As my session time out is 10 mins while my authentication time out is 15 mins. But I’ll be still authenticated and able to browse application even my session expired and got recreated and my existing session data will be lost.

So normally we put the authentication time out and same time out as same. This is just first step to avoid the discrepancy between the timeout of Authentication and Session.

But at certain browsers, it behaves differently. Like Session gets time out if the last request made was 10 (in my example session timeout is 10 minutes) or more minutes and on every request the counter get resets for 10 minutes but Authentication timeout does not work in same ways in different browsers. Like if have authentication timeout for 10 minutes, the authentication timeout counter does not get reset on every request to 10 minutes. Sometimes there are some performance improvement has been done which resets on the counter only at certain points say if after 5 or 7 minutes as to reset the authentication timeout on very request is costly. And this may lead to discrepancy.

Other scenario, If some how IIS gets reset the sessions of the users connected to that web server will become invalid while the user authentication will still be valid.

To avoid any unprecedented event like above, I put a check for an authentication and session on every page, So that user cannot continue further if session or authentication is not valid. Also if we found user is not authenticated any more then used to clear and abandon the session and redirects the user to login page. Similarly, if session is not available then the remove the user the authentication as well.

Also, at the time of user clicking on Logoff, one should clear and abandon the session. So that same session is not available after Logoff.

So as you can see, that session and authentication works separately and they work parallely and independently.

So for the problem stated earlier in this post, I suggested a solution to avoid the issue but you can yourself can put your own logic to prevent the issue.

Hope you all have enjoyed this post. Please share your valuable feedback.

Cheers,
Brij

Request Validation with ASP.NET 4.5 : A deep dive

DownLoad Sample

Security is always the one of the greatest concerns of Applications and when it comes to web applications, they are more prone to security breach. All the web technologies provides many features that are used to write secured web applications.

Here In this post, I am going to discuss Request Validation feature, mainly focusing ASP.NET 4.5 version.

Request validation introduced since ASP.NET 1.1 is available. By default it is enabled and it prevents to accept un-encoded HTML/XML etc from Client to server. It validates all the data that is passed from client to server. It can be any form like

  • Cookies
  • Form Collection
  • Querystring
  • Server variables

This helps to avoid script injection attacks. So it is always recommended to validate all the data that is passed from client to server because it can be malicious code and can be harmful the application.

Although, if we are sure that this situation would not arise, it can be disabled at application level or page level so no request will get validated. But this is not the case every time. On some occasions, we may need to allow users to enter some html, xml etc.. data . In this case, we need to partially validate the request.

There are several scenarios where we need to turn off the request validation just because of some specific data we don’t need to get validated. It leads us to write less secure code because we are the whole request goes to unvalidated. There are scenarios like in blog sites where we normally allow the user to write html , xml etc as input

Till ASP.NET 4.0, we have option to disable the request validation in the entire application or can be done page by page. But till now we did not have option to partially validate the page. ASP.NET 4.5 enables us to validate some specific part of the request.

ASP.NET 4.5 provides us two features.

  • Selectively un-validate the request
  • Deferred or lazy validation

How to allow partially unvalidated request in asp.net 4.5

(Note : I have VS11 beta version for this post)

I have created a sample application and have two textboxes – txtValidate and txtunValidate, with a submit button.

Let’s have a use case that I want to validate txtValidate but not txtunValidate. You must remember that this was not possible with earlier version of ASP.NET.I’ll also discuss it in detail later. To use this feature , you must set requestValidationMode as 4.5 in web.config like

            <httpruntime requestvalidationmode="4.5" />
 

Apart from this, ASP.NET 4.5 added one more property ValidateRequestMode with input controls. And it can have the following values

  • Enabled: Request validation is enabled for the control. Bydefault it is enabled
  • Disabled: Input values for this control would not be validated
  • Inherit: Property value will be inherited from parent

So let’s proceed with sample, and as I don’t want to validate txtunValidate so I need to set ValidateRequestMode attribute as disabled like

Sample aspx code

Now Let’s run the code.

sample runningAnd as you can see I’ve put some script tag in txtunValidate and it worked fine. But let us remove the requestValidationMode from web.config and try to submit the same input again.

Request Validation error

and see it gave the HttpRequestValidationException exception and got the above screen. Now lets again put the attribute requestValidationMode in web.config and try to put some script in txtValidate and submit. It’ll show you the same exception again as expected. So here you can see, ASP.NET 4.5 enables us to selectively validate the request.

Deferred or lazy validation

This is also introduced in asp.net 4.5 and I’ll say that above feature is just a corollary of this feature.

To provide these features, Microsoft has done some major changes in the way Request Validation feature got implemented in earlier version of ASP.NET. As we know, to process a request, ASP.NET creates an instance of HTTPContext which holds the instance of HTTPRequest and HTTPResponse with other required data. All the input data that is passed from client to server, it is posted in form collection, querystring etc.. ASP.NET validates every data that is passed from client to server.

Actually in ASP.NET 4.5, whenever the data is accessed from the request it gets validated. Like when we access the form collection to some input as Request.Form[uniqueId] the validation triggers. To provide selective validation, Microsoft has introduced a new collection property named as Unvalidated in the HTTPRequest class. This contains all the data that is passed from client to server like cookies, form collection, querystring etc as

UnValidated collection

Now the same data is available at two places. In UnValidated collection and normal in HTTPRequest. When we set the ValidateRequestMode is disabled, the data is accessed from UnValidated collection else normal request. UnValidated collection don’t trigger any validation while other one triggers. I’ll show you a demo later.

In earlier version of ASP.NET 1.1/2.0/3.5, Request validation is done at earlier level of page processing. There were also some good amount of changes took place in ASP.NET 4.0, which provides us the feature to validate the non-ASP.NET resources as well which was not available earlier.

Under the hood

I have the same application and I have removed the requestValidationMode attribute from web.config and putting some html tags as I did above example and pressed submit. So I got the HttpRequestValidationException as

Validation exception in earlier versions of ASP.NET

Now let’s put the requestValidationMode as 4.5 and try the same as above. I have removed the disable attribute. Again I got the same exception as below

Validation error in ASP.NET 4.5

But if we examine the circled part of the stacktrace, we can easily Identify that in 4.5, the validation exception got thrown from TextBox’s LoadPostData method.

Let’s do some experiment to examine this. I have made two case studies for this.

Case Study 1

As we all know the ASP.NET Page LifeCycle as

ASP.NET page life cycleAs you can see, here LoadPostData is a part of PageLife Cycle and comes after LoadViewState. All of the Input control’s data don’t get wiped off during postback even if viewstate is not enabled for that control. I have written a post on it. You can view this here.

So this is the LoadPostData method that is responsible to get the data from Form collection and assign it to the control. As I said, Now asp.net 4.5, validates the input only when you access the data from form collection. That’s why if you look the stacktrace then it is visible that the exception is thrown from LoadPostData method only and page life cycle is the last stage of ASP.NET Request Processing.

Now lets try to have an clarification using a demo. As I mentioned, in ASP.NET 4.5, the validation triggers only when the data is accessed and the data is accessed at LoadPostData for input controls. So lets create a custom textbox. For this I’ll override LoadPostData method and will do nothing in that. It means that the data would not be accessed for the customTextBox at LoadPostData. So even if the ValidationMode is enabled for the CustomtextBox, it wont be fired. Lets see this

I have created a CustomtestBox and overridden the LoadPostData method as

   public class CustomTextBox : System.Web.UI.WebControls.TextBox
    {
        protected override bool LoadPostData(string postDataKey, NameValueCollection postCollection)
        {
            return false;
        }
    }
 

You can see, I have just returned false in the LoadPostData method. Now I have used my CustomTextBox at my aspx page as

CustomtextboxNow set the requestValidationMode as 4.5 in web.config and enter some script tag and submit.

You would not get any error even RequestValidation is enabled. This proves the validation fires only when data is accessed from the form collection.

Case Study 2

Here I’ll also try to prove the same as above. I have already shown above that How the new UnValidated property of Context holds all the data including form collection, querystring, cookies etc. So whenever the data is accessed from the UnValidated collection, the validation is not fired. But when it is accessed from the normal form collection, validation gets fired.

So here I am going to use again the earlier sample. In that example I had two textboxes and a submit button. Here the change is that at server side, instead of accessing the data form txtValidate.Text, I’ll be accessing the data from FormCollection. So I’ll set the the ValidateRequestMode as disabled for both the textbox and will try to get the data one will be form normal Form Collection and another is from Unvalidated’s form collection as

   protected void Button1_Click(object sender, EventArgs e)
    {
        string textValidated = this.Context.Request.Unvalidated.Form[txtValidate.UniqueID];
        string textUnValidated = this.Context.Request.Form[txtunValidate.UniqueID];
    }
 

Now lets enter some html tags in both the textboxes and submit the page using debugger as

Exception using debuggerOh!! see even we have disabled the validation, even in that situation when data is accessed from normal Form collection the validation is fired.

This again proves the validation is fired only when the data is acessed and when the ValidateRequestMode is set as disabled it is accessed from the UnValidated property.

Hope you all have enjoyed the post. Do share your precious feedback.

Cheers,
Brij

Limiting the accessibility- Another way of Friend Assemblies

In my last post, I discussed, how to access internal class of one assembly in another assembly and that is easily achieved with the help of a C# feature called Friend Assemblies. It allows us to call the internal methods of another assembly. It is very much required at several occasions like the one I discussed in my last post, Unit Testing. It is often required to test the internal classes of the assembly in another project of Unit testing and It can be done easily via Friend Assembly.

To see my last post Please click here How to access internal class of one assembly to other assembly

But in some other scenarios Friend assemblies solution may not work. Like if you have two assemblies and one assembly accesses other assembly using Friend assembly. It’ll be fine as long as both assembly are compatible and shipped at same point of time. And if it does not happen on regular basis or in every release/update of assembly this may be hazardous.

To avoid it, we should implement it in another way. Here we declare the method as public but will limit to its accessibility to some specific assembly. It can be achieved by using LinkCommand with StrongNameIdentityPermission.

Continue reading