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.

usingSystem;usingSystem.Web;publicclassXSSHandler:IHttpHandler{publicvoidProcessRequest(HttpContextctx){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:

usingSystem;usingSystem.Web;usingSystem.Net;publicclassXSSHandler:IHttpHandler{publicvoidProcessRequest(HttpContextctx){stringpage=WebUtility.HtmlEncode(ctx.Request.QueryString["page"]);ctx.Response.Write("The page \""+page+"\" was not found.");}}

References

close