Searching for “how to prevent cross site scripting in .NET” in Google produces a number of interesting results. The first link points to a MSDN article titled How To: Prevent Cross-Site Scripting in ASP.NET, but this article includes the following code snippet, which “uses HtmlEncode to ensure the inserted text is safe”, but this code is clearly vulnerable upon further inspection.

<%@ Page Language=“C#” AutoEventWireup=“true”%>

<html>
  <form id="form1" runat="server">
    <div>
      Color:&nbsp;<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
      <br />
      <asp:Button ID="Button1" runat="server" Text="Show color"
         OnClick="Button1_Click" /><br />
      <asp:Literal ID="Literal1" runat="server"></asp:Literal>
    </div>
  </form>
</html>

<script runat="server">
  private void Page_Load(Object Src, EventArgs e)
  {
    protected void Button1_Click(object sender, EventArgs e)
    {
      Literal1.Text = @"<span style=""color:"
        + Server.HtmlEncode(TextBox1.Text)
        + @""">Color example</span>";
    }
  }
</Script>

In this example, it is crucial to understand, which characters the Server.HtmlEncode function actually encodes, and understand the context in which the application injects the user input. The application accepts user input and uses the input to build an inline style for a span element. In this context, a malicious user could inject in JavaScript without the use of single quotes, or double quotes as demonstrated by the following examples.

<span style="color: expression(alert(3435849))">Color example</span>

Or the following…

<span style="color: \65\78\70\72\65\73\73\69\6f\6e(\u0061\u006C\u0065\u0072\u0074(3435849))">Color example</span>

While the MSDN article remains popular, Microsoft has chosen not to maintain this documentation, which is a shame because most of the content is fairly informative for developers attempting to secure their code. Anyways, don’t believe everything you read and please use the Anti-XSS library instead of the Server.HtmlEncode function.