How to render single quote in safe way - asp.net-mvc

I saw in a tutorial video that we should use Html.Encode in our views to prevent malicious injections. However, when the text that I'm encoding contains the ' character (for example Dog's) the output in the browser is Dog#39;s. I would have thought every potentially dangerous character would be remaped to some safe code that the browser would render correctly. Is this not the case? How can I get ' to show up in the browser but in an HTML safe way?

The # in Razor automatically encodes for you, meaning that you probably did a double encode.
Example:
#Html.Encode("This is \"safe\"")
is more or less the same as
#{Response.Write(Html.Encode(Html.Encode("This is \"safe\"")));}
Dunno if that last one works in Razor though.

If you are using ASP.NET MVC 2 <%: %> is already encoding the value for you
In Razor (MVC 3) # encodes the values for you so you do not need to wrap the output in Html.Encode
Make sure that you are not double encoding

Related

Html.Raw not decoding

Just a query, I have used #Html.Raw(Item.sometext) before and it decodes the html tags correctly, I'm getting some data from remore source which is in json format, but when displayed on the page I found Html.raw did not decodes html tags.
To fix the problem I used:
#Html.Raw(HttpUtility.HtmlDecode(Item.sometext))
So my question is, can anyone please tell me why that could be the case, as I'm curious as to the reason. Im using mvc4 and asp.net 4.5
Thanks
George
Here is my answer in an attempt to explain better what I mean (in the comments).
Your JSON is formatted for example (which you have supplied) like so:
<p><b>Location. <\/b> <br \/>...
However, this is not valid HTML. Notice the escape characters used for the slashes '/'. So if you pass this value to Html.Raw it will (should) output it, but it's not valid HTML so will unlikely display correctly (if it display anything at all).
This escape character issue can be fixed using Html.Decode which will effectively return the following:
<p><b>Location. </b> <br />...
This is valid HTML, and can therefore be passed to Html.Raw without any problems
NOTE: Html.Raw does not do any encoding/decoding, in fact it explicitly instructs that the supplied value should not be encoded as it is already raw HTML. This is confirmed here:
Use the Raw method when the specified text represents an actual HTML
fragment that should not be encoded and that you want to render as
markup to the HTTP response.

should I always use <%: instead of <%=

I know that <%: does the html.encode thing, but there are lots of situations when I'm sure that I don't need to encode, so why should I waste time on encoding stuff that I'm 100% sure it doesn't require to be encoded like for example <%:Url.Action("Index") %> or <%: Model.Id %> (is of type int)?
The : code nugget is part of the ASP.NET 4.0 web compiler and doesn't just call Html.Encode(). It works out whether or not the string is already encoded first (if the expression returns an IHtmlString then it probably won't get encoded).
This means it is safe to use it when inserting actual data or when inserting HTML from some type of helper method (if you write your own helper methods, they should always return IHtmlString as of MVC 2).
With regards to whether or not you always use it, of course you don't. But I'd rather not think about it too much and will be happier knowing I've gone some way towards fending off XSS attacks with little effort; therefore, I nearly always use it.
It also encourages you to make sure you return a MvcHtmlString from your HTML helper methods rather than a string.
One example where you would not want to use <%: is for strings that come from your resource file that include HTML escape characters. I don't think you can make a blanket statement that you should always use <%:.
Personally I use it only for stuff that I know that needs to be encoded. No need to use it for integer types <%: Model.Id %> but that's just a personal preference.
<%: model %> is equivalent of <%= Html.Encode(model)%>
using <%: saves keystrokes and improves your productivity,
but sometimes you will have a need to do <%= (not to encode whatever you are displaying on your page)
One of the advantages of encoding to HTML is that it makes the pages W3C Valid according to corresponding datatype. So why validate the document in the first place?
For the answer to that please check, please check: http://validator.w3.org/docs/why.html
Briefly validating HTML saves a lot of time later in the development cycle and its a good practice.
Its easier, if you use only one type, and makes the code more clean.
also, you never know, who will change the code, and makes out of a simple "100 %" statement, a not so 100% statement :-)
Normally, in a web environment, the performance on such things are not an issue.
i would suggest to only use "<%:" as a team development guideline. just to be on the safe side.

ASP.NET MVC: How to allow some HTML mark-up in Html Encoded content?

Is there some magic existing code in MVC 2 to Html.Encode() strings and allow certain html markup, like paragraph marks and breaks? (coming from a Linq to SQL database field)
A horrible code example to achieve the effect:
Html.Encode(Model.fieldName).Replace("<br />", "<br />")
What would be really nice is to overload something and pass to it an array (or object) full of allowed html tags.
It's not a good idea to create your own whitelist based on regular expressions because you'll likely inadvertently open a security hole for XSS.
From Sanderson's book "Pro ASP.NET MVC3 Framework": "...The only viable mitigation is strict, whitelist-based filtering: use a library like the HTML Agility Pack to ensure the user-supplied markup contains only the tags that you explicitly allow."
Sanderson goes on to supply a link to a site that demonstrates a broad range of XSS techniques that you'd have to test for if you use the regex approach. Check out http://ha.ckers.org/xss.html
There is nothing built in to ASP.NET or MVC for this, but it's not that hard to write your own whitelist-based one with regular expressions and so on. Here's one that Jeff wrote, though it's pretty rough around the edges...
I can't think of anything off the bat but I guess you could write an extension method that allows you to add a paremeter/list of items to allow.
Html.Encode(Mode.fieldName, List<items> Myitems);
It could modify the allowable tags into < etc and then encodes the rest like normal.

Better way to implement an Html Helper method?

I created an html helper
Html.BreadCrumb(IDictionary<string, string> crumbs)
Where the first string is the label and the second string is the URL.
The helper creates the html required (an unordered list, some classes for first element, current element, last element, dead element and separators etc)
All working nice, but I do this by creating a stringbuilder, pumping all the html in it and returning the stringbuilder's content as a string.
I figure in this example it doesn't matter all that much, but what if an Html helper is churning out a big load of html? Isn't there a way to push it to Response.Write instead of a stringbuilder?
Or any other issues/improvements you have?
BTW we have a naming pattern in ASP.NET MVC for the various rendering techniques.
Helpers that return a string of what they are should be named what they are. For example, Url.Action() and Html.TextBox() return those exact items. Thus, these helpers should be used with the <%= %> syntax.
Helpers that render directly to the output stream should start with Render. For example, Html.RenderPartial(). These are used with the <% %> syntax.
Helpers that use the IDisposable pattern should be named with Begin/End. For example, Html.BeginForm() and Html.EndForm(). These should also be used with the <% %> syntax.
Thanks,
Eilon
It certainly is possible to use Response.Write instead of returning a string; see the source for System.Web.Mvc.Ajax.Form (in AjaxExtensions.cs) in the MVC source for an example.
You then call the helper with <% instead of <%=.
Will it be any faster? I doubt it, but it's easy to test.
I don't think you will have any performance problems as long as the size of the HTML pages you produce is reasonable. And when you really start to create pages of megabytes in size, then you should ask yourself, why are you creating such huge HTML files?

How do I bypass the HTML encoding when using Html.ActionLink in Mvc?

Whenever I use Html.ActionLink it always Html encodes my display string. For instance I want my link to look like this:
More…
it outputs like this: More…
&hellip is "..." incase you were wondering.
However the actionlink outputs the actual text "…" as the link text. I have the same problem with if I want to output this:
<em>My-Post-Title-Here</em>
I wind up with:
<em>My-Post-Title-Here</em>
Any idea how to do this?
It looks like ActionLink always uses calls HttpUtility.Encode on the link text. You could use UrlHelper to generate the href and build the anchor tag yourself.
<a href='#Url.Action("Posts", ...)'>More…</a>
Alternatively you can "decode" the string you pass to ActionLink. Constructing the link in HTML seems to be slightly more readable (to me) - especially in Razor. Below is the equivalent for comparison.
#Html.ActionLink(HttpUtility.HtmlDecode("More…"), "Posts", ...)
The answer given by Sam is actually correct and I used it in my solution so I have therefore tried it myself.
You may want to remove the extra parenthesis so it becomes something like this:
#Html.ActionLink(HttpUtility.HtmlDecode("&"), "Index", "Home")
Alternatively, just use a plain Unicode ellipsis character \u2026 and let MVC worry about how to encode it. Unless there's some particularly compelling reason you'd specifically need a hellip entity reference as opposed to a character reference or just including the character as simple UTF-8 bytes.
Alternative alternatively: just use three periods. The ellipsis (U+2026) is a compatibility character, only included to round-trip to pre-Unicode encodings. It gets you very little compared to simple dots.
Check out this:
<p>Some text #(new HtmlString(stringToPaste)) </p>
Decode it before passing the value in. Just had this same issue (different characters) and it works fine:
Eg:
#Html.ActionLink(HttpUtility.HtmlDecode(_("&")), "Index", "Home")
Annoying though

Resources