This error is detected when unchecked user input is used as an XPath expression.

Mitigation and prevention

The prevention of XPath injection attacks can be achieved by validating any and all input from outside the application (user input, file input, system parameters, etc.). The best way to filter user data is with a blacklist regular expression that includes only the type of characters that are allowed; all other characters should be escaped.

Klocwork security vulnerability (SV) checkers identify calls that create potentially dangerous data; these calls are considered unsafe sources. An unsafe source can be any data provided by the user, since the user could be an attacker or has the potential for introducing human error.

Example 1

24  protected void doGet(HttpServletRequest httpServletRequest,
25          HttpServletResponse httpServletResponse) throws ServletException, IOException {
26     super.doGet(httpServletRequest, httpServletResponse);
27     String userName = httpServletRequest.getParameter("");
28     String userDescr = httpServletRequest.getParameter("user.descr");
29     CompiledExpression compiledExpression = JXPathContext.compile("string(//user[name/text()='" + userName + "']/account/text())");
30     compiledExpression.setValue(context, userDescr);
31     httpServletResponse.getOutputStream().println("User info updated");
32  }

SV.XPATH is reported for the snippet twice:

  • user data is stored in 'userName' on line 27 and later is used for the construction of an XPath expression on line 29
  • user data is stored in 'userDescr' on line 28 and later is passed to 'setValue(...)' on line 30


This checker can be extended through the Klocwork knowledge base. See Tuning Java analysis for more information.