DotNetPanel S&M Blog

Cross-Site Scripting in ASP.NET

Cross-site scripting attacks exploit vulnerabilities in Web page validation by injecting client-side script code. The script code embeds itself in response data, which is sent back to an unsuspecting user. The user's browser then runs the script code. Because the browser downloads the script code from a trusted site, the browser has no way of recognizing that the code is not legitimate, and Microsoft Internet Explorer security zones provide no defense. Cross-site scripting attacks also work over HTTP and HTTPS (SSL) connections.

One of the most serious examples of a cross-site scripting attack occurs when an attacker writes script to retrieve the authentication cookie that provides access to a trusted site and then posts the cookie to a Web address known to the attacker. This enables the attacker to spoof the legitimate user's identity and gain illicit access to the Web site.

Common vulnerabilities that make your Web application susceptible to cross-site scripting attacks include:

  • Failing to constrain and validate input.
  • Failing to encode output.
  • Trusting data retrieved from a shared database.

Guidelines

The two most important countermeasures to prevent cross-site scripting attacks are to:

  • Constrain input.
  • Encode output.

Constrain Input

Start by assuming that all input is malicious. Validate input type, length, format, and range.

  • To constrain input supplied through server controls, use ASP.NET validator controls such as RegularExpressionValidator and RangeValidator.
  • To constrain input supplied through client-side HTML input controls or input from other sources such as query strings or cookies, use the System.Text.RegularExpressions.Regex class in your server-side code to check for expected using regular expressions.
  • To validate types such as integers, doubles, dates, and currency amounts, convert the input data to the equivalent .NET Framework data type and handle any resulting conversion errors.

For more information about and examples of how to constrain input, see .

Encode Output

Use the HttpUtility.HtmlEncode method to encode output if it contains input from the user or from other sources such as databases. HtmlEncode replaces characters that have special meaning in HTML-to-HTML variables that represent those characters. For example, < is replaced with &lt; and " is replaced with &quot;. Encoded data does not cause the browser to execute code. Instead, the data is rendered as harmless HTML.

Similarly, use HttpUtility.UrlEncode to encode output URLs if they are constructed from input.

Summary of Steps

To prevent cross-site scripting, perform the following steps:

<system.web>


<pages buffer="true" validateRequest="true" />
</system.web>

You can disable request validation on a page-by-page basis. Check that your pages do not disable this feature unless necessary. For example, you may need to disable this feature for a page if it contains a free-format, rich-text entry field designed to accept a range of HTML characters as input. For more information about how to safely handle this type of page.

To test that ASP.NET request validation is enabled

  1. Create an ASP.NET page that disables request validation. To do this, set ValidateRequest="false", as shown in the following code example.

    <%@ Page Language="C#" ValidateRequest="false" %>
    
    <html>
    <script runat="server">
    void btnSubmit_Click(Object sender, EventArgs e)
    {
    // If ValidateRequest is false, then 'hello' is displayed
    // If ValidateRequest is true, then ASP.NET returns an exception
    Response.Write(txtString.Text);
    }
    </script>
    <body>
    <form id="form1" runat="server">

    <asp:TextBox id="txtString" runat="server"
    Text="<script>alert('hello');</script>" />
    <asp:Button id="btnSubmit" runat="server"
    OnClick="btnSubmit_Click"
    Text="Submit" />
    </form>
    </body>
    </html>

  2. Run the page. It displays Hello in a message box because the script in txtString is passed through and rendered as client-side script in your browser.
  3. Set ValidateRequest="true" or remove the ValidateRequest page attribute and browse to the page again. Verify that the following error message is displayed.

    A potentially dangerous Request.Form value was detected from the client (txtString="<script>alert('hello...").
    

    This indicates that ASP.NET request validation is active and has rejected the input because it includes potentially dangerous HTML characters.

    Response.Write
    

    <% =

    Search your pages to locate where HTML and URL output is returned to the client.

    Step 3. Determine Whether HTML Output Includes Input Parameters

    Analyze your design and your page code to determine whether the output includes any input parameters. These parameters can come from a variety of sources. The following list includes common input sources:

    • Form fields, such as the following.
      Response.Write(name.Text);
      
      Response.Write(Request.Form["name"]);
      Query Strings
      Response.Write(Request.QueryString["name"]);
    • Query strings, such as the following:

      Response.Write(Request.QueryString["username"]);
      
    • Databases and data access methods, such as the following:
      SqlDataReader reader = cmd.ExecuteReader();
      
      Response.Write(reader.GetString(1));

      Be particularly careful with data read from a database if it is shared by other applications.

    • Cookie collection, such as the following:
      Response.Write(
      
      Request.Cookies["name"].Values["name"]);
    • Session and application variables, such as the following:

      Response.Write(Session["name"]);
      
      Response.Write(Application["name"]);
      <%@ 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>

      Potentially Dangerous HTML Tags

      While not an exhaustive list, the following commonly used HTML tags could allow a malicious user to inject script code:

      <img src="BLOCKED SCRIPTalert('hello');">
      

      <img src="java&#010;script:alert('hello');">
      <img src="java&#X0A;script:alert('hello');">
      <style TYPE="text/javascript">
      

      alert('hello');
      </style>

      When you find ASP.NET code that generates HTML using some input, you need to evaluate appropriate countermeasures for your specific application. Countermeasures include:

      Response.Write(HttpUtility.HtmlEncode(Request.Form["name"]));
      
      Response.Write(HttpUtility.UrlEncode(urlString));
      
      <%@ Page Language="C#" ValidateRequest="false"%>
      

      <script runat="server">

      void submitBtn_Click(object sender, EventArgs e)
      {
      // Encode the string input
      StringBuilder sb = new StringBuilder(
      HttpUtility.HtmlEncode(htmlInputTxt.Text));
      // Selectively allow <b> and <i>
      sb.Replace("&lt;b&gt;", "<b>");

      sb.Replace("&lt;/b&gt;", "");
      sb.Replace("&lt;i&gt;", "<i>");
      sb.Replace("&lt;/i&gt;", "");
      Response.Write(sb.ToString());
      }
      </script>

      <html>
      <body>

      <form id="form1" runat="server">
      <div>
      <asp:TextBox ID="htmlInputTxt" Runat="server"
      TextMode="MultiLine" Width="318px"
      Height="168px"></asp:TextBox>
      <asp:Button ID="submitBtn" Runat="server"
      Text="Submit" OnClick="submitBtn_Click" />
      </div>
      </form>

      </body>
      </html>

Comments

Cross Site Scripting » Blog Archive » Cross -Site Scripting in Asp.Net - Dotnetpanel S&M Blog said:

Pingback from  Cross Site Scripting  &raquo; Blog Archive   &raquo; Cross -Site Scripting in Asp.Net - Dotnetpanel S&amp;M Blog

# February 15, 2009 2:55 PM

Mediumcube.com Web Hosting Blog » SQL Security Vulnerability in Poorly Designed Applications said:

Pingback from  Mediumcube.com Web Hosting Blog &raquo; SQL Security Vulnerability in Poorly Designed Applications

# February 26, 2009 6:23 PM

Jeep Comanche Cars For Sale, 1986 Jeep Comanche Parts Brake Pads said:

Pingback from  Jeep Comanche Cars For Sale, 1986 Jeep Comanche Parts Brake Pads

# May 20, 2010 12:11 PM

2002 Honda 400ex Atv, Sony Str 2400es Year Old said:

Pingback from  2002 Honda 400ex Atv, Sony Str 2400es Year Old

# May 20, 2010 2:17 PM

Fairlane Torino Ford Ranchero, Torino France said:

Pingback from  Fairlane Torino Ford Ranchero, Torino France

# May 20, 2010 4:45 PM

Auction Infiniti Fx35 Raleigh Used Cars, Fx35 Auction 2007 Infiniti said:

Pingback from  Auction Infiniti Fx35 Raleigh Used Cars, Fx35 Auction 2007 Infiniti

# May 20, 2010 8:14 PM

Buy Bonneville T100 Big Bike, F 100 Fighter North American Cockpit said:

Pingback from  Buy Bonneville T100 Big Bike, F 100 Fighter North American Cockpit

# May 20, 2010 11:52 PM

Rising Action Part Brave New World, Fusion Energy News said:

Pingback from  Rising Action Part Brave New World, Fusion Energy News

# May 21, 2010 4:43 AM

Used 2008 Wrangler, Aev Wrangler Bumper said:

Pingback from  Used 2008 Wrangler, Aev Wrangler Bumper

# May 21, 2010 3:37 PM

Insight Communications Discount, Bee Insight B M3 said:

Pingback from  Insight Communications Discount, Bee Insight B M3

# May 21, 2010 4:38 PM

T100 Supercharger Used Toyota 4runner, 4runner Alternative Subject said:

Pingback from  T100 Supercharger Used Toyota 4runner, 4runner Alternative Subject

# May 21, 2010 8:48 PM

1968 Volkswagen Squareback Anatomy, Vw 411 Squareback said:

Pingback from  1968 Volkswagen Squareback Anatomy, Vw 411 Squareback

# May 21, 2010 9:13 PM

1993 Acura Nsx Sale, Nsx Discount Oem Acura Mdx Parts said:

Pingback from  1993 Acura Nsx Sale, Nsx Discount Oem Acura Mdx Parts

# May 22, 2010 3:57 AM

Toyota L300 2 2nd Hand, Buy Saturn L300 1 Turn Signal Side Marker said:

Pingback from  Toyota L300 2 2nd Hand, Buy Saturn L300 1 Turn Signal Side Marker

# May 22, 2010 6:43 AM

Magentis 2003, Magentis Upgrade said:

Pingback from  Magentis 2003, Magentis Upgrade

# May 22, 2010 10:44 AM

K15 K1500 Pickup Sale Tire, K14 K1500 Pickup Buy Used Gmc said:

Pingback from  K15 K1500 Pickup Sale Tire, K14 K1500 Pickup Buy Used Gmc

# May 22, 2010 2:05 PM

Mitsubishi Outlander Sell Used Car, Outlander Radiator Vent Visor said:

Pingback from  Mitsubishi Outlander Sell Used Car, Outlander Radiator Vent Visor

# May 22, 2010 4:19 PM

76 Vw Super Beetle For Sale, New Volkswagen Beetle Alloy Wheels said:

Pingback from  76 Vw Super Beetle For Sale, New Volkswagen Beetle Alloy Wheels

# May 22, 2010 5:22 PM

Chrysler Lhs Interior Lights, Headlight Chrysler Fifth Avenue Parts Shock Absorber Power Steering Pump said:

Pingback from  Chrysler Lhs Interior Lights, Headlight Chrysler Fifth Avenue Parts Shock Absorber Power Steering Pump

# May 22, 2010 7:10 PM

300sel Seats Clinton Township, 1969 Mercedes Benz 300sel Sale Leather Interior - 350.luna-atra.net said:

Pingback from  300sel Seats Clinton Township, 1969 Mercedes Benz 300sel Sale Leather Interior - 350.luna-atra.net

# May 23, 2010 12:06 AM

2001 Honda Shadow Spirit 750 Sale Ads, Spirit Mars Rover Gusev Crater - 175.tvshowzone.com said:

Pingback from  2001 Honda Shadow Spirit 750 Sale Ads, Spirit Mars Rover Gusev Crater - 175.tvshowzone.com

# May 23, 2010 5:24 AM

2000 Dodge Stratus Check Engine Light Spark Plugs, D150 Discount Sprinter 3500 Dodge Stratus - 358.1fh.org said:

Pingback from  2000 Dodge Stratus Check Engine Light Spark Plugs, D150 Discount Sprinter 3500 Dodge Stratus - 358.1fh.org

# May 24, 2010 5:29 AM

Supreme Commander Tipps, Commander 112a For Sale - 492.rkwrh.com said:

Pingback from  Supreme Commander Tipps, Commander 112a For Sale - 492.rkwrh.com

# May 24, 2010 6:46 AM

Dynasty Sale Repair, Dynasty Radiator Product Description Oem - 75.tvshowzone.com said:

Pingback from  Dynasty Sale Repair, Dynasty Radiator Product Description Oem - 75.tvshowzone.com

# May 24, 2010 2:06 PM

Rx330 Wholesale, Lexus Rx330 Replacement Master Keys - 490.an74.com said:

Pingback from  Rx330 Wholesale, Lexus Rx330 Replacement Master Keys - 490.an74.com

# May 25, 2010 5:43 AM

D150 Used Pickup Box Ramcharger Dodge Salvage Yards, Programming Remote Keyless Entry Fob - 290.cmanager.org said:

Pingback from  D150 Used Pickup Box Ramcharger Dodge Salvage Yards, Programming Remote Keyless Entry Fob - 290.cmanager.org

# May 25, 2010 6:13 PM

1981 - 1984 @ F 250 Pickup Used Atv, 100 Watt Light Bulb Lava Lamp Reflector - 109.tijuanareader.com said:

Pingback from  1981 - 1984 @ F 250 Pickup Used Atv, 100 Watt Light Bulb Lava Lamp Reflector - 109.tijuanareader.com

# May 30, 2010 6:38 PM

2002 - 1980 @ Mercedes Benz R63 Aftermarket Cls63 Ml63 Amg, Cls500 Used Mercedes Benz Clk Cls63 Amg - 425.unlockiphone30.net said:

Pingback from  2002 - 1980 @ Mercedes Benz R63 Aftermarket Cls63 Ml63 Amg, Cls500 Used Mercedes Benz Clk Cls63 Amg - 425.unlockiphone30.net

# May 30, 2010 7:29 PM

1990 - 1986 @ Howloscream Passport Discount Busch Gardens Tampa Bay, My Passport Hard Drive 320gb - 13.1fh.org said:

Pingback from  1990 - 1986 @ Howloscream Passport Discount Busch Gardens Tampa Bay, My Passport Hard Drive 320gb - 13.1fh.org

# May 30, 2010 8:38 PM

1989 - 2008 @ Executive Limousine Bulb Mechanical, Executive Limousine Radiator Value - 392.binggreen.com said:

Pingback from  1989 - 2008 @ Executive Limousine Bulb Mechanical, Executive Limousine Radiator Value - 392.binggreen.com

# May 30, 2010 9:09 PM

1981 - 1980 @ 533i Cooling System Fan, 533i Cooling System Radiator Drain Plug - 428.dlmreza.net said:

Pingback from  1981 - 1980 @ 533i Cooling System Fan, 533i Cooling System Radiator Drain Plug - 428.dlmreza.net

# May 30, 2010 9:29 PM

1990 - 2007 @ 380se Area, 380se Sale Trucks 1970 Mercedes Benz - 393.cmanager.org said:

Pingback from  1990 - 2007 @ 380se Area, 380se Sale Trucks 1970 Mercedes Benz - 393.cmanager.org

# May 31, 2010 12:43 AM

1999 - 1980 @ Volvo V40 Break 2001, V40 Nikon Ni Mh - 181.binggreen.com said:

Pingback from  1999 - 1980 @ Volvo V40 Break 2001, V40 Nikon Ni Mh - 181.binggreen.com

# May 31, 2010 12:50 AM

1992 - 2001 @ Galant Pt Floor Mats, Starion Cheap Mitsubishi Galant - 320.rkwrh.com said:

Pingback from  1992 - 2001 @ Galant Pt Floor Mats, Starion Cheap Mitsubishi Galant - 320.rkwrh.com

# May 31, 2010 1:37 PM

1995 - 1997 @ Rx400h 450h Research Lexus Rx 400h, E450 Cutaway Radiator Trailer Towing Capacity - 405.1fh.org said:

Pingback from  1995 - 1997 @ Rx400h 450h Research Lexus Rx 400h, E450 Cutaway Radiator Trailer Towing Capacity - 405.1fh.org

# May 31, 2010 1:42 PM

Alabama weddings - Alabama reception - Alabama mobile wedding said:

Pingback from  Alabama weddings - Alabama reception - Alabama mobile wedding

# August 14, 2010 10:22 PM

Hotel island long radisson - Long island - Island hotel said:

Pingback from  Hotel island long radisson - Long island - Island hotel

# September 7, 2010 9:12 PM

Las brisas florida - Guardalavaca las - Las brisas said:

Pingback from  Las brisas florida - Guardalavaca las - Las brisas

# September 14, 2010 5:03 AM

Cool t shirt design said:

Pingback from  Cool t shirt design

# February 26, 2011 5:59 PM

horoscope said:

Pingback from  horoscope

# December 23, 2011 5:17 PM

horoscope said:

Pingback from  horoscope

# December 23, 2011 5:17 PM

horoscopes said:

Pingback from  horoscopes

# December 23, 2011 7:11 PM