ASP.Net MVC Html.Raw with AntiXSS protection

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

As with all user generated content, I want to misinform them before going out.

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

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

      

Output for above:

J&#243;n

      

This is great because it protects me from users by putting <tags>

both <script>evilStuff</script>

in its names and playing silly games.

In the example above, I want sanity from villains, but I don't want HTML to UTF8 encoded valid characters that are not evil.

I want the result to read:

Jรณn

      

but I also want XSS protection to give me the encoding.

Outside of using a whitelist structure (like Microsoft.AntiXSS) is there a built in MVC feature that helps here?

UPDATE:

It looks like it looks like what it looks like to work:

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

      

Will it protect against the majority of all XSS attacks?

+2


source to share


1 answer


You will need to write your own coder or find another third party. The default encoders in ASP.NET tend to err on the more secure side, coding more than is necessary.

Having said that, please don't write your own encoder! Writing the correct HTML coding routines is a very difficult task and is only suitable for those with specific security knowledge.

My recommendation is to use what is built in because it is correct and safe enough. While it might seem like it produces non-standard HTML output, you're better off safe than sorry.




Now, notice that this code:

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

      

Wrong and unsafe because it is wrong to use JavaScript routing to render HTML markup.

+1


source







All Articles