CodeQL documentation

Cross-site scripting

ID: cs/web/xss
Kind: path-problem
Security severity: 6.1
Severity: error
Precision: high
Tags:
   - security
   - external/cwe/cwe-079
   - external/cwe/cwe-116
Query suites:
   - csharp-code-scanning.qls
   - csharp-security-extended.qls
   - csharp-security-and-quality.qls

Click to see the query in the CodeQL repository

Directly writing user input (for example, an HTTP request parameter) to a webpage, without properly sanitizing the input first, allows for a cross-site scripting vulnerability.

Recommendation

To guard against cross-site scripting, consider using a library that provides suitable encoding functionality, such as the System.Net.WebUtility class, to sanitize the untrusted input before writing it to the page. For other possible solutions, see the references.

Example

The following example shows the page parameter being written directly to the server error page, leaving the website vulnerable to cross-site scripting.

using System;
using System.Web;

public class XSSHandler : IHttpHandler
{
    public void ProcessRequest(HttpContext ctx)
    {
        ctx.Response.Write(
            "The page \"" + ctx.Request.QueryString["page"] + "\" was not found.");
    }
}

Sanitizing the user-controlled data using the WebUtility.HtmlEncode method prevents the vulnerability:

using System;
using System.Web;
using System.Net;

public class XSSHandler : IHttpHandler
{
    public void ProcessRequest(HttpContext ctx)
    {
        string page = WebUtility.HtmlEncode(ctx.Request.QueryString["page"]);
        ctx.Response.Write(
            "The page \"" + page + "\" was not found.");
    }
}

References

  • © GitHub, Inc.
  • Terms
  • Privacy