Data Browser - Viewing Site  Sector 23 Code Bank Logged in as:  Guest  


XSS Attack on HyperLinkField
In general, unless you have countermeasures, data in a database could have come from anywhere, and there is no guarantee that it does not contain javascript/html type XSS injection attack code.
Even if it was entered by trusted users, they could enter text like "Bob&Ampie" or "a<b" which should not be rendered straight out in .NET, as it will be converted to "Bob&ie" or an HTML error.
In general, a fix is to use the Microsoft anti-XSS library or HttpUtility.HtmlEncode to convert the text to HTML-safe text before setting it to a 'Text' property on a label or other .NET control.
Or, you can use a Literal control with mode = Encode.
(some suggest encoding before putting in database, but who wants HTML in their database fields? It won't render on all non-html output. Also you cannot assume every developer remembered to encode the data (on bulk import, on edit, on add, from SSIS, from scripts, etc). Although you still should make a good faith effort to block obvious attacks such as with Page.ValidateRequest.

However, there are some controls that appear to be just plain broken in .NET!

Today's example is the HyperLinkField in a gridview. It is supposed to make it easy to bind hyperlinks in a grid. However, unless your "DataTextField" is known to contain HTML that you have already sanitized and not plain text, you will need to HtmlEncode the text.
However, the field contains no property to automatically encode the text! You must fall back to a manual workaround such as using a TemplateField with HyperLink or similar fix.

This is one of many examples, including the fact that by default a Label renders HTML instead of sanitized text, that makes it very easy for developers to completely forget about XSS protection when building .NET sites. It seems like all of these controls should assume text first, and require the developer to pass a flag if they want the HTML/javascript rendered and executed.

Anyway, enough complaining. Here's the fix! You can use this field instead of the default one. (to get this override to show up in intellisense see google, there is a simple hack).

/// <summary>
/// field for my grid
/// </summary>
public class HyperLinkField : System.Web.UI.WebControls.HyperLinkField
public bool HtmlEncode
if (ViewState["vsEH"] == null)
return false;
return (bool)ViewState["vsEH"];
ViewState["vsEH"] = value;

protected override string FormatDataTextValue(object dataTextValue)
if (dataTextValue == DBNull.Value || dataTextValue == null || !HtmlEncode)
return base.FormatDataTextValue(dataTextValue);
return base.FormatDataTextValue(HttpUtility.HtmlEncode(dataTextValue));

Created By: amos 11/14/2014 11:25:57 AM
Updated: 11/14/2014 11:41:36 AM