All rules
CA3002Security Enabled by default: No

Review code for XSS vulnerabilities

Review code for XSS vulnerabilities

Microsoft docs

Description

When working with untrusted input from web requests, be mindful of cross-site scripting (XSS) attacks. An XSS attack injects untrusted input into raw HTML output, allowing the attacker to execute malicious scripts or maliciously modify content in your web page. A typical technique is putting <script> elements with malicious code in input. For more information, see OWASP's XSS.

This rule attempts to find input from HTTP requests reaching raw HTML output. This rule can't track data across assemblies. For example, if one assembly reads the HTTP request input and then passes it to another assembly that outputs raw HTML, this rule won't produce a warning. There is a configurable limit to how deep this rule will analyze data flow across method calls. See Analyzer Configuration for how to configure the limit in an EditorConfig file.

Cause

Potentially untrusted HTTP request input reaches raw HTML output.

By default, this rule analyzes the entire codebase, but this is configurable.

How to fix violations

  • Instead of outputting raw HTML, use a method or property that first HTML-encodes its input.
  • HTML-encode untrusted data before outputting raw HTML.

Example

using System;

public partial class WebForm : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        string input = Request.Form["in"];
        Response.Write("<HTML>" + input + "</HTML>");
    }
}

using System;

public partial class WebForm : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        string input = Request.Form["in"];

        // Example usage of System.Web.HttpServerUtility.HtmlEncode().
        Response.Write("<HTML>" + Server.HtmlEncode(input) + "</HTML>");
    }
}

When to suppress

It's safe to suppress a warning from this rule if:

  • You know that the input is validated against a known safe set of characters not containing HTML.
  • You know the data is HTML-encoded in a way not detected by this rule.

This rule may report false positives for some methods or properties that HTML-encode their input.

Group results
0 yes 0 no
ConsensusNone (disabled)
Severity preference (yes voters)
Suggestion0
Warning0
Error0