Skip to main content

Potential XPath injection with XmlDocument

Back to rules list


The dynamic value passed to the XPath query should be validated.

Risk

If the user input is not properly filtered, a malicious user could extend the XPath query.

Vulnerable Code

XmlDocument doc = new XmlDocument();
doc.Load("/config.xml");
var results = doc.SelectNodes("/Config/Devices/Device[id='" + input + "']");

Solution

Regex rgx = new Regex(@"^[a-zA-Z0-9]+$");
if(rgx.IsMatch(input)) { //Additionnal validation
    XmlDocument doc = new XmlDocument();
    doc.Load("/config.xml");
    var results = doc.SelectNodes("/Config/Devices/Device[id='" + input + "']");
}

References

CWE-643: Improper Neutralization of Data within XPath Expressions ('XPath Injection')
CERT: IDS09-J. Prevent XPath Injection (archive)
Black Hat Europe 2012: Hacking XPath 2.0
Balisage: XQuery Injection
WASC-39: XPath Injection
OWASP: Top 10 2013-A1-Injection