Doug
Doug

Reputation: 6518

ASP.Net MVC Html.Raw with AntiXSS protection

I want to display user content in a java script variable.

As with all user generated content, I want to sanitize it before outputting.

ASP.Net MVC does a great job of this by default:

@{
  var name = "Jón"; 
}
<script> var name ='@name';</script>

The output for the above is:

J&#243;n

This is great as it protects me from users putting <tags> and <script>evilStuff</script> in their names and playing silly games.

In the above example,I want sanity from evil doers but I don't want to HTML encode UTF8 valid characters that aren't evil.

I want the output to read:

Jón

but I also want the XSS protection that encoding gives me.

Outside of using a white listing framework (ie Microsoft.AntiXSS) is there any built in MVC function that helps here?

UPDATE:

It looks like this appears to achieve something that looks like it does the job:

@{
  var name = "Jón"; 
}
<script> var name ='@Html.Raw(HttpUtility.JavaScriptStringEncode(name))';

Will this protect against most all XSS attacks?

Upvotes: 2

Views: 2746

Answers (1)

Eilon
Eilon

Reputation: 25704

You'd have to write your own encoder or find another 3rd party one. The default encoders in ASP.NET tend to err on the side of being more secure by encoding more than what might necessarily be needed.

Having said that, please don't write your own encoder! Writing correct HTML encoding routines is a very difficult job that is appropriate only for those who have specific advanced security expertise.

My recommendation is to use what's built-in because it is correct, and quite secure. While it might appear to produce less-than-ideal HTML output, you're better safe than sorry.


Now, please note that this code:

@Html.Raw(HttpUtility.JavaScriptStringEncode(name))

Is not correct and is not secure because it is invalid to use a JavaScript encoding routing to render HTML markup.

Upvotes: 1

Related Questions