Review code for XPath injection vulnerabilities
Review code for XPath injection vulnerabilities
Microsoft docsDescription
When working with untrusted input, be mindful of XPath injection attacks. Constructing XPath queries using untrusted input may allow an attacker to maliciously manipulate the query to return an unintended result, and possibly disclose the contents of the queried XML.
This rule attempts to find input from HTTP requests reaching an XPath expression. 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 performs an XPath query, 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 an XPath query.
By default, this rule analyzes the entire codebase, but this is configurable.
How to fix violations
Some approaches to fixing XPath injection vulnerabilities include:
- Don't construct XPath queries from user input.
- Validate that the input only contains a safe set of characters.
- Escape quotation marks.
Example
using System;
using System.Xml.XPath;
public partial class WebForm : System.Web.UI.Page
{
public XPathNavigator AuthorizedOperations { get; set; }
protected void Page_Load(object sender, EventArgs e)
{
string operation = Request.Form["operation"];
// If an attacker uses this for input:
// ' or 'a' = 'a
// Then the XPath query will be:
// authorizedOperation[@username = 'anonymous' and @operationName = '' or 'a' = 'a']
// and it will return any authorizedOperation node.
XPathNavigator node = AuthorizedOperations.SelectSingleNode(
"//authorizedOperation[@username = 'anonymous' and @operationName = '" + operation + "']");
}
}When to suppress
If you know you've validated the input to be safe, it's okay to suppress this warning.