简体   繁体   English

在 Java 中避免 XPath 注入攻击的最佳方法是什么?

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

I am using XPath to retrieve values from XML.我正在使用 XPath 从 XML 检索值。 My code scanner break the build because of the following reason:由于以下原因,我的代码扫描器破坏了构建:

invokes an XPath query built using unvalidated input.调用使用未经验证的输入构建的 XPath 查询。 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. input是包含 XML 的OMelement Attribute is getting from XML attribute.属性是从 XML 属性获取的。

How can I avoid XPathInjection?如何避免 XPathInjection? Could please share a code snippet?可以分享一个代码片段吗?

You're taking an entire XPath from user input or other external source?您是从用户输入或其他外部来源获取整个XPath 吗?

Recommendation: Do not take in a full XPath expression an unsecured source.建议:不要将完整的 XPath 表达式视为不安全的源。 Use precompiled XPaths.使用预编译的 XPath。 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.如果必须根据用户输入参数化 XPath,请将基于用户的部分隔离为仅字符串参数,然后使用 XPath 库的参数化机制。

You're using Java and Axiom, which is based on Jaxen, so use SimpleVariableContext and setVariableContext() for XPath parameterization.您正在使用 Java 和基于 Jaxen 的 Axiom,因此使用SimpleVariableContextsetVariableContext()进行 XPath 参数化。 See Charles Duffy's answer here for more details on safely parameterizing XPaths when using Axiom.见查尔斯·达菲的答案在这里使用公理时,详细了解安全参数化的XPath。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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