This code directly incorporates user input into an XPath query, allowing injection of malicious XPath.
Fixed Code:
phpCopy<?php$xpath =newDOMXPath($xml);$query ="//user[username/text()=? and password/text()=?]";$nodes = $xpath->query($query,array($_POST['username'], $_POST['password']));?>
Reason for Fix:
The fixed code uses parameterized queries to separate the XPath query from user input.
C# Example
Vulnerable Code:
csharpCopyusing System.Xml.XPath;publicstringGetUserRole(string username,string password){XPathNavigator nav =xmlDoc.CreateNavigator();string query =$"string(//user[username='{username}' and password='{password}']/role)";returnnav.Evaluate(query).ToString();}
Reason for Vulnerability:
This code directly incorporates user input into an XPath query, allowing injection of malicious XPath.
Fixed Code:
csharpCopyusing System.Xml.XPath;publicstringGetUserRole(string username,string password){XPathNavigator nav =xmlDoc.CreateNavigator();XPathExpression expr =nav.Compile("string(//user[username=@u and password=@p]/role)");expr.SetContext(newXPathContext { {"u", username}, {"p", password} });returnnav.Evaluate(expr).ToString();}
Reason for Fix:
The fixed code uses parameterized XPath queries to separate the query from user input.