ASP.NET Cross Site Scripting Validation Control

Cross Site Scripting, or XSS for short, is a form of HTML injection exploit where an attacker will attempt to embed malicious JavaScript, Java (Applets) or ActiveX code in HTML tags like <script>, <form>, <applet>, <iframe> and <object>. These HTML tags are usually injected into form fields such as text boxes or text areas. A vulnerable website will typically collect and save the contents of a form submission and redisplay the data at a later time allowing the offending HTML embedded code to execute if the appropriate precautions are not taken.

There are two ways to defend against cross site scripting attacks:

  • Validate form fields against XSS by ensuring that they do not contain an HTML tags. An XSS validator is presented in this post.
  • HTML encode all user generated text and HTML content.

XSS Validation

By default ASP.NET automatically parsed form fields, cookies and query string values and throws a server error if it finds specific patterns such as an angled bracket followed by non-whitespace or an ampersand. This is done using the page directive <% @Page ValidateRequest="true" %> which can also be set in the web.config on the <pages validateRequest="true" /> element globally.

However, if you want to provide a friendly error message or have to turn off request validation for some reason you will need to implement cross site scripting validation.

HTML Encoding

By encoding user generated text and HTML content, characters such as "<" and ">" are replaced with harmless entities &lt; and &gt; you can avoid user generated content like blog comment submissions from leading to cross site scripting attacks.

Use HttpUtility.HtmlEncode() or a server control that can encode its content such as <asp:Literal runat="server" Mode="Encode"> to achieve this.

Cross Site Scripting Validation Control

The following cross site scripting validator uses our free LINQ to HTML library in conjunction with a custom ASP.NET validator control to validate against XSS attacks on specific form fields.

public class CrossSiteScriptingValidator : BaseValidator
{
   protected override bool EvaluateIsValid()
   {
      string value = GetControlValidationValue(ControlToValidate);

      HDocument document = HDocument.Parse(value);

      if (document.Declaration != null)
      {
          return false;
      }

      return !document.DescendantNodes().Any(node => !(node is HText) && !(node is HEntity));
   }

   protected override void RegisterValidatorDeclaration()
   {
   }
}

Using the Cross Site Scripting Validation Control

<asp:TextBox runat="server" ID="CommentTextBox" />

<ssc:CrossSiteScriptingValidator runat="server" ControlToValidate="CommentTextBox" Text="*" />

Note that you'll need to register the tag prefix "ja" in the web.config.