Resolve SQL Injection Error from Checkmarx using NamedParameterJdbcTemplate reading parameterized query from a file

Viewed 35

The query is read from a file in the resources folder of the java spring boot application. How do I prevent this Sql Injection error from Checkmarx in the code below?

@Repository
public class ItemRepository {

  @Autowired
  NamedParameterJdbcTemplate jdbcTemplate;

  public List<Item> getData(String action) {
    String sql = IOUtils.toString(getClass().getResourceAsStream("queries/query.sql"));
    MapSqlParameterSource parameters = new MapSqlParameterSource();
    parameters.addValue("action", action, Types.VARCHAR);

    try {
      List<Item> items = jdbcTemplate.query(sql, parameters, new ItemMapper());
      return items;
    } catch (EmptyResultDataAccessException ex) {
      return new ArrayList<>();
    }
  }
}

Error message:

The application's getData method executes an SQL query with query, at line 13 of ItemRepository.java. The application constructs this SQL query by embedding an untrusted string into the query without proper sanitization. The concatenated string is submitted to the database, where it is parsed and executed accordingly.
An attacker would be able to inject arbitrary syntax and data into the SQL query, by crafting a malicious payload and providing it via the input toString; this input is then read by the getData method at line 8 of ItemRepository.java. This input then flows through the code, into a query and to the database server - without sanitization.
This may enable an SQL Injection attack.

1 Answers

Checkmarx is likely complaining about the SQL string coming via a stream. In this specific case it's coming from a resource file in a jar, which is probably a trusted source in your application. If so, this is a false positive and you should mark it Not Exploitable (with the appropriate reasoning).

Related