javajdbcsql-injectionfortify

Fortify scan getting failed with reason data is used to dynamically construct a SQL query


Fortify scan failed for some of my java classes with reason The data is used to dynamically construct a SQL query. From the message I can able to understand this is related to SQL injection, before i was appending sql's with + operator now changed this to stringbuilder but fortify still shows the sql injection in the analysis report.

Here is my code sample

public int prepareSql(String queryType){
....
StringBuilder stringBuilder = new StringBuilder("Select username, password from loginDetails where "
if (queryType="id")
stringBuilder .append("id = 123")
else
stringBuilder .append("name = 'test'")

String selectQuery = stringBuilder.toString();
Connection connection = ***;
             PreparedStatement statement = connection.prepareStatement(selectQuery);
 /**scan failed on this line **/   ResultSet resultSet = statement.executeQuery(){
while (resultSet.next()) {
......
}
}

Solution

  • It make no difference how you append, it is the same from a security standpoint. Don't append strings to queries. Instead use different queries. Use the prepared statement to set parameters, not concatenation.