Hire a web Developer and Designer to upgrade and boost your online presence with cutting edge Technologies

Wednesday, September 2, 2015

Cross Site Scripting Attack Prevention

Last week I discussed what cross site scripting attack is. In today's blog post I am going to discuss some measures which can help prevent cross site scripting attack in MVC applications.

How to Prevent

Encoding the content is the best way to prevent XSS attack. We need to encode both HTML and Javascript content. Let's discuss each of these one by one.

Encode HTML

The output on the pages should be HTML encoded or HTML attribute encoded. In Web Forms, we could use Html.Encode like this:

<% Html.Encode(Model.DataToEncode) %>

 Or shorthand like this:

<%: Model.DataToEncode %>

The Razor View Engine HTML encodes output by default. So a Model property on the View like this:

@Model.LastName

will be automatically encoded.
If we want to access raw data with no encoding then we need to use Html.Raw like this:

@Html.Raw(Model.LastName)

One should be extremely careful while using Html.Raw() as it opens doors for many security vulnerabilities.

Encode Javascript

Similarly, if we need to display user input in Javascript, we should do Javascript encoding like this:

@Ajax.JavaScriptStringEncode(ViewBag.UserName)

In the example, that I gave in my previous blog post, if the attacker tries to provide malicious input like this:

\x3cscript\x3e%20alert(\x27EVIL\x27)%20\x3c/script\x3e
 
 and the input is Javascript encoded then it will be rendered.

Conclusion

In order to prevent cross site scripting attack, we should not trust user input. We should always HTML encode/ Javascript encode the data.
For future updates to my weekly blog, please subscribe to the blog.

No comments:

Post a Comment