Java Reference
In-Depth Information
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.
Treat all user input as untrusted, and perform appropriate sanitization.
When sanitizing user input, verify the correctness of the data type, length, format,
and content. For example, use a regular expression that checks for XML tags and
special characters in user input. This practice corresponds to input sanitization.
See Guideline 7 , “ Prevent code injection , ” for additional details.
In a client-server application, perform validation at both the client and the server
sides.
Search WWH ::




Custom Search