2

In ASP.NET MVC views, it is typical to bind model values using Razor's syntax:

@Html.DisplayFor(m => m.Name)

We know that Razor will html encode the value by default. But imagine a malicious user inputting scripts in a textbox and submitting it:

<script>alert('Executing evil script')</script>

Now if we do not use the [ValidateInput(false)] or [AllowHtml] attributes, we will be hit with a HttpRequestValidationException which means this exception have to be caught every time a user submits a form.

From the answer in another stackoverflow question, I know we can disable request validation on an application level but many are suggesting this is a bad practice.

My question is, given we have Razor to escape all &gt; and &lt;, can we assume the site will still be secure if we turn off request validation?

Community
  • 1
  • 1
rexcfnghk
  • 14,435
  • 1
  • 30
  • 57
  • Given there is `Html.Raw` I'm not sure how Razor is important part of the decision to use or not request validation... It was never required, but useful if you don't expect "evil script" as inputs. – Alexei Levenkov Jan 05 '15 at 04:14

1 Answers1

0

No, relying only HTML encoding during Razor page generation and switching off request validation is not a good strategy to combat XSS attacks:

  • Request Validation prevents bad user input from getting into your database / storage / other user screens in the first place.
  • Html encoding (sanitization) is there as a backup strategy, e.g. where the attacker has already got through the door.
  • Considering that an App can serve more than just Html - e.g. Xml and REST services, which will not be subject to the encoding by the Html helpers. (e.g. attacker might find a way to put a malicious payload in an Xml CDATA section)
  • Also, consider running regular Sql / NoSql queries against your database looking for signs that your site request validation has been compromised.
StuartLC
  • 104,537
  • 17
  • 209
  • 285
  • Then how can I allow users to enter `<` and `>` in textboxes safely without the application crashing with a `HttpRequestValidationException`? – rexcfnghk Jan 05 '15 at 04:28
  • You allow just that one field for Html, use a mainstream Html editor like *CKEditor or TinyMCE etc, and [configure](http://www.tinymce.com/wiki.php/Configuration:valid_elements) your Html editor control just to allow specific Html tags. No scripts. And not all Html, otherwise an attacker can still deface your site. – StuartLC Jan 05 '15 at 04:31
  • 1
    @StuartLC: Configuring a *client side editor* does nothing to protect your server from malicious HTML. You need to validate everything on the server side. And that's very difficult to do correctly. – Matti Virkkunen Mar 21 '17 at 22:19