I got a “XPath Injection” issue from Fortify scan for below code,
string username = string.Empty;
string password = string.Empty;
string officePrefix = "";
if (!String.IsNullOrEmpty(securityNode.Prefix))
{
officePrefix = securityNode.Prefix + ":";
ns.AddNamespace(securityNode.Prefix, securityNode.Namespace);
}
var regexPattern =
ConfigurationManager.AppSettings["xxx"];
var regexItem = new Regex(regexPattern, RegexOptions.None);
if(regexItem.IsMatch(officePrefix ))
{
//wsse:UsernameToken
XmlNode usernameTokenNode = securityNode.SelectSingleNode(officePrefix +
"UsernameTkn", ns);
username = usernameTokenNode.SelectSingleNode(officePrefix + "name", ns).InnerText;
password = usernameTokenNode.SelectSingleNode(officePrefix + "Pwd", ns).InnerText;
above code i am getting issue from ( XmlNode usernameTokenNode = securityNode.SelectSingleNode(officePrefix + "UsernameToken", ns);) this line of code. So, I tried to use regex and as you can see in the code. Even though the xpath injection issue still persists. Can any one kindly give a solution for the xpath injection issue.
You don't need to re-use the namespace alias from the actual XML. you can use your own. The only thing is that the actual namespace must be the same
string username = string.Empty;
string password = string.Empty;
const string officePrefix = "myPrefix";
bool hasPrefix = !string.IsNullOrEmpty(securityNode.Namespace);
if (hasPrefix)
{
ns.AddNamespace(officePrefix, securityNode.Namespace);
}
XmlNode usernameTokenNode = securityNode.SelectSingleNode(hasPrefix ? officePrefix + ":UsernameTkn" : "UsernameTkn", ns);
username = usernameTokenNode.SelectSingleNode(hasPrefix ? officePrefix + ":name" : "name", ns).InnerText;
password = usernameTokenNode.SelectSingleNode(hasPrefix ? officePrefix + ":Pwd" : "Pwd", ns).InnerText;
I note that XName
and XNode
are newer and much easier to use, they are in the System.Xml.Linq
library.