Dynamically building SQL query strings can result in broken SQL syntax and open SQL injection attacks.

Why is this an issue?

When SQL queries are constructed by concatenating or formatting user-supplied values directly into the query string, the structure of the query itself can be altered by a malicious input. This rule flags calls to SQL execution functions where the query string is built using string concatenation or format operators rather than parameterized queries or prepared statements. Unlike rule {rule:javasecurity:S3649}, this rule does not perform taint analysis — it flags all dynamically formatted SQL queries as a potential risk regardless of the data source.

What is the potential impact?

SQL injection

If any part of a dynamically formatted query string originates from untrusted input, an attacker can manipulate the query to read, modify, or delete data they should not have access to, bypass authentication checks, or in some configurations execute operating system commands.

How to fix it

Code examples

The following code builds a SQL query by concatenating a value directly into the query string.

Noncompliant code example

public User getUser(Connection con, String user) throws SQLException {

  Statement stmt1 = null;
  Statement stmt2 = null;
  PreparedStatement pstmt;
  try {
    stmt1 = con.createStatement();
    ResultSet rs1 = stmt1.executeQuery("GETDATE()"); // No issue; hardcoded query

    stmt2 = con.createStatement();
    ResultSet rs2 = stmt2.executeQuery("select FNAME, LNAME, SSN " +
                 "from USERS where UNAME=" + user);  // Noncompliant

    pstmt = con.prepareStatement("select FNAME, LNAME, SSN " +
                 "from USERS where UNAME=" + user);  // Noncompliant
    ResultSet rs3 = pstmt.executeQuery();

    //...
}

public User getUserHibernate(org.hibernate.Session session, String data) {

  org.hibernate.Query query = session.createQuery(
            "FROM students where fname = " + data);  // Noncompliant
  // ...
}

Compliant solution

public User getUser(Connection con, String user) throws SQLException {

  Statement stmt1 = null;
  PreparedStatement pstmt = null;
  String query = "select FNAME, LNAME, SSN " +
                 "from USERS where UNAME=?"
  try {
    stmt1 = con.createStatement();
    ResultSet rs1 = stmt1.executeQuery("GETDATE()");

    pstmt = con.prepareStatement(query);
    pstmt.setString(1, user);
    ResultSet rs2 = pstmt.executeQuery();

    //...
  }
}

public User getUserHibernate(org.hibernate.Session session, String data) {

  org.hibernate.Query query =  session.createQuery("FROM students where fname = ?");
  query = query.setParameter(0,data);  // Good; Parameter binding escapes all input

Resources

Articles & blog posts

Standards