Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

This guideline is a specific example of the broadly scoped IDS51-JG. Prevent code injection.

XML Path Injection Example

Consider the following XML schema:

...

The passwords are hashed in compliance with 13. MSC66-JG. Store passwords using a hash function.

...

Code Block
bgColor#FFcccc
private boolean doLogin(String userName, char[] password)
  throws ParserConfigurationException, SAXException, IOException, XPathExpressionException {

  DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
  domFactory.setNamespaceAware(true);
  DocumentBuilder builder = domFactory.newDocumentBuilder();
  Document doc = builder.parse("users.xml");
  String pwd = hashPassword( password);

  XPathFactory factory = XPathFactory.newInstance();
  XPath xpath = factory.newXPath();
  XPathExpression expr = xpath.compile("//users/user[username/text()='" +
       userName + "' and password/text()='" + pwd + "' ]");
  Object result = expr.evaluate(doc, XPathConstants.NODESET);
  NodeList nodes = (NodeList) result;

  // Print first names to the console
  for (int i = 0; i < nodes.getLength(); i++) {
    Node node = nodes.item(i).getChildNodes().item(1).getChildNodes().item(0);
    System.out.println( "Authenticated: " + node.getNodeValue());
  }

  return (nodes.getLength() >= 1);
}

Compliant Solution (XQuery)

XPath injection can be prevented by adopting defenses similar to those used to prevent SQL injection:

...

Using this method, the data specified in the userName and password fields cannot be interpreted as executable content at runtime.

Applicability

Failure to validate user input may result in information disclosure and execution of unprivileged code.

...

[Prevention of XPath injection] requires the following characters to be removed (ie, prohibited) or properly escaped:

  • < > / ' = " to prevent straight parameter injection
  • XPath queries should not contain any meta characters (such as ' = * ? // or similar)
  • XSLT expansions should not contain any user input, or if they do, [you should] comprehensively test the existence of the file, and ensure that the files are within the bounds set by the Java 2 Security Policy

Bibliography

...