Saturday, May 19, 2012

JavaScript Injection: Dealing with Java Scripts supplied through QueryString in URL while requesting for an ASP.NET or MVC webpage.

QueryStrings are very common in websites.
But they are very much prone to JavaScript injection. And if they are not handled properly, they can easily temper your webpage/ data.

For example, you have a label in your webpage, and you are setting it's text property according to a particular QueryString supplied (say, querystring UserName).

Now, if a user requests following URL in a browser:
http://myWebsite/myPage.aspx?UserName=Sample<script type="text/Javascript">alert('a')</script>

In this case, if you have not taken handled QueryString properly in your page, it will execute this javascript. Though, alert is a harmless script, but a user can really pass some dangerous javascripts and they will get executed.

Following is what we need to avoid this -

1. If your page has ValidateRequest attribute is set to True (which is a default value), it will anyway not allow such querystrings to be processed. Instead it will show user Browser's error page indicating potentially dangerous request.

2. But if you do not want to display Browser's error page (Browser's error page does not give good impression to user) or if you absolutely had to set ValidateRequest to False according to your requirements, then you need to do an HTML encoding of supplied querystring.

lblQueryString.Text = HttpUtility.HtmlEncode(Request.QueryString["UserName"].ToString());

This will treat the querystring as plain text (no execution of any script at all)!

Also, if you are using .NET v4.0, it will show you browser's error page even if you have "ValidateRequest" to False in your page. To avoid that, add following line under "<system.web>" section within your web.config file.

<httpRuntime requestValidationMode="2.0"/>





1 comment:

  1. This article is very informative and easy to understand. Thank you for sharing!


    ReplyDelete

Thanks for visiting my blog.
However, if this helped you in any way, please take a moment to write a comment.

Thanks
Nirman