Search code examples
c#razorxsswebmatrixhtml-encode

Does using razor in WebMatrix mitigate an XSS threat?


I have purposfully (for testing) assigned the following variable in WebMatrix C#:

string val = "<script type='text/javascript'>alert('XSS Vector')</script>";

Later in the page I have used razor to write that value directly to the page.

<p>
    @val
</p>

It writes the text, but in a safe manner (i.e., no alert scripts run)

This, coupled with the fact that if 'val' contains an html entity (e.g., &lt;) it also writes exactly "&lt;" and not "<" as I would expect the page to render.

Is this because C# runs first, then html is rendered?

More importantly, is using razor in this fashion a suitable replacement for html encoding, when used like this?


Solution

  • The @Variable syntax will HtmlEncode any text you pass to it; hence you seeing literally what you set to the string value. You are correct in that this is for XSS protection. It is part of Razor that does this; the @Variable syntax itself.

    So basically, using the @Variable syntax is not so much a 'replacement' for Html Encoding; it is HTML encoding.

    Related: If you ever want some string to render the HTML, you would use this syntax in Razor:

    @Html.Raw(Variable)
    

    That causes the Html Encoding not to be done. Obviously, this is dangerous to do with user-supplied input.