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
getDatamethod executes an SQL query withquery, at line 13 ofItemRepository.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 inputtoString; this input is then read by thegetDatamethod at line 8 ofItemRepository.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.