views:

350

answers:

3

If the name of a link is pulled from the database, should you be calling the Html.Encode method to clean the name?

For example:

Html.ActionLink(Model.PersonFromDB.FirstName,
                "Action",
                "Controller",
                new RouteValueDictionary { { "id", Model.PersonFromDB.Id } },
                null)

or:

Html.ActionLink(Html.Encode(Model.PersonFromDB.FirstName),
                "Action",
                "Controller",
                new RouteValueDictionary { { "id", Model.PersonFromDB.Id } },
                null)

It would make sense that you would want to do this to ensure that there are no dangerous strings injected into the page between <a> and </a> tags, but are scripts and such executable between anchor tags?

A: 

Yes, absolutely. As a general rule, for any HTML that you are going to output that was originally obtained from an untrusted source, assuming the format wasn't HTML already (and sufficiently vetted), you should always HTML encode the string to protect against injection attacks.

casperOne
No. See http://stackoverflow.com/questions/2283920/should-html-encode-be-called-when-building-actionlinks-in-asp-net-mvc/2284022#2284022
bzlm
A: 

It's certainly a good idea, but you should probably be preventing users from entering in potentially malicious strings as their first name.

Kevin Pang
ASP.NET MVC has a feature that checks all input to see if you are attempting to input script or malicious text, so that's already in place.
Chris F
I generally agree, but keep in mind that "potentially malicious" depends a lot on where the data will be _displayed_. For instance, "</form>" is not at all damaging when displayed on a paper report or a raw DB report, it's only an issue when displayed in HTML. Thus, it's ultimately the job of the _presentation layer_ to format the data according to its specific needs.
Seth Petry-Johnson
+5  A: 

No, since according to this thread on SO HtmlAction.Link() already HTML encodes values, so you'd end up doing it twice.

Dan Diplo
Correct; see `GenerateLinkInternal` in HtmlHelper.cs in the MVC 2 source code.
Craig Stuntz