Be careful outputting strings in ASP.NET MVC
Wednesday, January 09 2008 5 Comments
During my presentation at Alamo Coders last night, someon mentioned that it is unsafe to output user-entered strings like this:
<
h2><%= college.Name %></h2>The reason is, of course, that the user could be malicious and enter in a string such as this:
“<script>alert(‘I am evil’);</script>”
And it would evaluated on the page and all of your users would get an alert box. This is leaving your door wide-open to clever attacks known as Cross Site Scripting and is very dangerous.
Instead, we should escape these strings so that they aren’t rendered as HTML or javascript, but rather textual characters. That means that < will be translated to < and so on.
To do that, the Html helpers that ship with the framework give you an Encode method, letting you do something like:
<
h2><%= Html.Encode(college.Name) %></h2>But the syntax is a bit cumbersome for every outputted value on a page. I prefer the way Rails handles it… like this:
<
h2><%= h(college.Name) %></h2>And it turns out that you can add this extension method somewhere and be done with it:
And that’s it! Just remember to take this precaution, or you’ll regret it later.
public static string h(this ViewPage page, string input){ return new HtmlHelper(page.ViewContext).Encode(input);}


Sean Chambers
1.09.2008
10:46 PM
This raises the question as to whether one should be stripping these values from the input before you insert it into your database. It takes a little bit of extra processing and if you are already performing some type of validation it isn't that much more difficult.Although, I've heard people discuss it either way to no end on newsgroups before so I won't say for one way or the other. Even if you are stripping nasty values before insertion into the database, this is an added bonus to be positive that you are not outputting anything nasty.