tags:

views:

112

answers:

3

Does anybody knows if it is necessary to sanitize the contents of the HtmlControl.Attributes? MSDN is silent in that:

http://msdn.microsoft.com/en-us/library/system.web.ui.htmlcontrols.htmlcontrol.attributes.aspx

In other words, which of this is correct:

HtmlGenericControl control = new HtmlGenericControl();
/*Option 1*/ control.Attributes["value"] = HttpUtility.HtmlAttributeEncode(unsafestring);
/*Option 2*/ control.Attributes["value"] = unsafestring;
A: 

ASPX:

<div id="div" runat="server">test</div>

Codebehind:

protected void Page_Load(object sender, EventArgs e)
{
    div.Attributes["title"] = "this is unsafe~~~\">"; 
}

Rendered HTML:

<div id="div" title="this is unsafe~~~&quot;>">test</div>

Guess Framework did the cleaning up for us!

UPDATE:
Using HttpUtility.HtmlAttributeEncode rendered this output:

<div id="div" title="this is unsafe~~~&amp;quot;>">test</div>

Guess there's a difference after all, I've yet to find any documented reference for this.

o.k.w
A test is nice, but does one has a reference to a spec that says it?
David Reis
Unfortunately I can't find any. I've edited my test result further, do take a look.
o.k.w
A: 

There is no MSDN documentation on HTML-encoding details at this level. If you're willing to do a bit of Reflector spelunking, you'll discover that HtmlAttributeEncode is automatically applied to most attribute values by default at rendering, but this is a behaviour that can easily be overridden by a control implementer.

In other words, it's not a great idea to assume that automatic encoding will either be performed or not for any given attribute. Unless you're willing to develop your own controls that following a single guiding principle wrt automatic encoding, you may want to consider creating a set of unit tests that verify that the attributes that you use are applying the encoding behaviour you expect. This will help you guard against potential future changes to encoding behaviour as well as confirming the current encoding behaviour.

Nicole Calinoiu
A: 

It seems that MSDN docs does not clearly state that HtmlEncoding is occuring but from the following reference of AttributeCollection.Add method it seems evident. I do not see an overload for the method that can bypass it either.

Roma