Archives
-
Secure ASP.NET MVC Applications
One of the greatest advantages of ASP.NET MVC is that it provides a "Close to the Metal" programming experience and you have full control over the HTML. It aslo means that you should care about the vulnerabilities regards with your HTML. In webform, server controls would be automatically HTML-encoded their outputs. While developing ASP.NET MVC apllications, you should filter your HTML to avoid XSS attacks. Use the following HTML helper methods to avoid vulnerabilities in your ASP.NET MVC applications.
Use Html.Encode to defense XSS
Use Html.Encode Helper method if you output user-supplied data.
Your search result for category : <%=Html.Encode(ViewData["Category"]) %>
Lets assume that if the user supplied "<script>alert('XSS')</script>" for input data , the Html.Encode will avoid to execute as a JavaScript function and will ensures to display that string as a literal text. When you using built-in Helper methods, It will automatically HTML-encode their outputs. As Rob Conery said, Html.Encode is not a silver bullet to avoid XSS
Use Html.AntiForgeryToken to defense Cross-Site Request Forgery (CSRF)
The Html.AntiForgeryToken helper method provides the support for detecting and defense CSRF attacks. This helper method available in Microsft ASP.NET MVC Futures assembly (Microsoft.Web.Mvc.dll). The assembly can download from http://www.codeplex.com/aspnet/Release/ProjectReleases.aspx?ReleaseId=18459 . Check the below example
<% Html.BeginForm("Save", "Category", FormMethod.Post); %>
<%= Html.AntiForgeryToken() %>
<% Html.EndForm(); %>
The AntiForgeryToken helper would generate a hiiden field named __MVC_AntiForgeryToken and gave a value that randomly generated for each user request. And at the same it gave cookie with name __MVC_AntiForgeryToken and the value would be constant for user session.
<form method="post" action="/Category/Save">
<input type="hidden" value="34/LV6nApPw0VWjxZkwY1imE8U8c+fAthll+ssF1fhbbK20HYA1EzXB6xaHqCHo4" name="__MVC_AntiForgeryToken"/>
</form>
The authorization filter atrribute [ValidateAntiForgeryToken] will check the all incoming request with form value __MVC_AntiForgeryToken and block the request if there is a invalid token is supplied. A CSRF attacker can't know the randomly generated value of AntiForgeryToken.
The below example used [ValidateAntiForgeryToken] in the controller action to validate the AntiForgeryToken.
[ValidateAntiForgeryToken]
public ActionResult Save(FormCollection form) {
} -
My UG Talk on ASP.NET MVC
I did an another UG presentation on the ASP.NET MVC Framework for K-Mug (Kerala Microsoft User Group) at Technopark, India. You can download the presentation material from here