I recently noticed that I had a big hole in my application because I had done something like:
<input type="text" value="<%= value%>" />
I know that I should have used
Html.Encode, but is there any way to do that for all values, without having to do it explicitly?
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
There’s a few ways:
- Use the
<%: %>syntax in ASP.NET MVC2 / .NET 4.0. (Which is just syntactic sugar for
- Follow the directions laid out by Phil Haack where it details using the Anti-XSS library as the ‘default’ encoding engine for ASP.NET.
Watch this video from Scott Hanselman and Phil Haack. They cover XSS, CSRF, JSON Hijacking specifically with ASP.Net MVC.
In ASP.Net 4.0 or later, always use <%: … %> instead of <%= … %> … it does the HTML encoding for you.
Having done that, it’s fairly straightforward to grep your code for <%= regularly as a security precaution.
Also, are you using the Microsoft Anti-XSS library?
Syntax for HTML encoding
- <%: model.something %> syntax in WebForms
It is automatic in Razor i.e. @model.something will auto encode automatically no
need to do anything to encode.
- MVC3 HTML Helper methods return the encoded string automatically. e.g. Html.Label will return the encoded string
More about cross site scripting
Potentially Dangerous HTML Tags:
While not an exhaustive list, the following commonly used HTML tags could allow a malicious user to inject script code:
<applet> <body> <embed> <frame> <script> <frameset> <html> <iframe> <img> <style> <layer> <link> <ilayer> <meta> <object>
An attacker can use HTML attributes such as src, lowsrc, style, and href in conjunction with the preceding tags to inject cross-site scripting. For example, the src attribute of the tag can be a source of injection, as shown in the following examples.
An attacker can also use the tag to inject a script by changing the MIME type as shown in the following.