Applications that execute XQuery commands should neutralize any externally-provided values used in those commands. Failure to do so could allow an attacker to include input that executes unintended commands, or exposes sensitive data.


This rule checks that method parameters are not unconditionally used directly in XQuery commands.


== Noncompliant Code Example

----
public User getUser(String user) {
  OXQDataSource ds = new OXQDataSource();
  XQConnection con = ds.getConnection();
  String query = "doc(\"users.xml\")/userlist/user[uname=\"" 
          + user + "\"]";  // Parameter concatenated directly into string
  XQPreparedExpression expr = con.prepareExpression(query); // Noncompliant
  XQSequence result = expr.executeQuery();
  // ...
----


== Compliant Solution

----
public User getUser(String user) {
  OXQDataSource ds = new OXQDataSource();
  XQConnection con = ds.getConnection();
  String query = "doc(\"users.xml\")/userlist/user[uname=\"" 
          + scrubUser(user) + "\"]";  // Method presumably sanitizes parameter
  XQPreparedExpression expr = con.prepareExpression(query);
  XQSequence result = expr.executeQuery();
  // ...
----
or

----
public User getUser(String user) {
  if (! user.matches(USERNAME_ALLOWED_CHARS)) {
    return null;
  }

  OXQDataSource ds = new OXQDataSource();
  XQConnection con = ds.getConnection();
  String query = "doc(\"users.xml\")/userlist/user[uname=\"" + user + "\"]"; 
  XQPreparedExpression expr = con.prepareExpression(query); // Compliant; value used conditionally
  XQSequence result = expr.executeQuery();
    // ...
----
or

----
public User getUser(String user) {
  String cleanUser = user.replaceAll("[^a-zA-Z0-9]", "");

  OXQDataSource ds = new OXQDataSource();
  XQConnection con = ds.getConnection();
  String query = "doc(\"users.xml\")/userlist/user[uname=\"" 
          + cleanUser + "\"]"; // Parameter not used directly in string
  XQPreparedExpression expr = con.prepareExpression(query); 
  XQSequence result = expr.executeQuery();
  // ...
----


== See

* https://www.owasp.org/index.php/Top_10-2017_A1-Injection[OWASP Top 10 2017 Category A1] - Injection
* http://cwe.mitre.org/data/definitions/652[MITRE, CWE-652] - Improper Neutralization of Data within XQuery Expressions

