简体   繁体   中英

What is the best way to avoid XPath Injection attack in Java?

I am using XPath to retrieve values from XML. My code scanner break the build because of the following reason:

invokes an XPath query built using unvalidated input. This call could allow an attacker to modify the statement's meaning or to

This is my code:

private String myMethod(String XPath, OMElement input) {
  String elementText = null;
  AXIOMXPath xpathToElement = null;
  try {
    xpathToElement = new AXIOMXPath(XPath);
    xpathToElement.addNamespace(xxx,yyy);
    elementText = ((OMElement) xpathToElementnode.selectSingleNode(input)).getText();

  } catch (JaxenException e) {
    e.printStackTrace();
    fail(e.getMessage());
  ...

Here is the code where I call above method:

key = myMethod(myAttribute.getAttributeValue(), input);

input is OMelement which contains XML. Attribute is getting from XML attribute.

How can I avoid XPathInjection? Could please share a code snippet?

You're taking an entire XPath from user input or other external source?

Recommendation: Do not take in a full XPath expression an unsecured source. Use precompiled XPaths. If you have to parameterize your XPath based on user input, isolate the user-based parts to string-only parameters, and then use your XPath library's parameterization mechanism.

You're using Java and Axiom, which is based on Jaxen, so use SimpleVariableContext and setVariableContext() for XPath parameterization. See Charles Duffy's answer here for more details on safely parameterizing XPaths when using Axiom.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM