简体   繁体   中英

Java Veracode Scan - False Positive on SQL Injection

We get an "CWE-89: Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')" in the Java code:

    private static void doSomethingWithDB(int queryFetchSize, String sql, Object... params)
        try {
            Connection connection = ...

            PreparedStatement statement = connection.prepareStatement(sql);
            statement.setFetchSize(queryFetchSize);
            for (int i = 0; i < params.length; i++) {
                statement.setObject(i + 1, params[i]);
            }
            ResultSet resultSet = statement.executeQuery(); //this is where Veracode reports error
        ....

passing SQL from outside is not a best design practice but it is OK in this particular case (method is private, SQL queries are under our control).

How can I make Veracode less paranoid in this case?

In this scenario one workaround would be to pass the sql's identifier (eg enum) to the method instead of the sql itself, and then map this identifier to the actual sql inside the method body. So the example code would like something like this:

 private static void doSomethingWithDB(int queryFetchSize, SqlName sqlName, Object... params)
    try {
        Connection connection = ...

        PreparedStatement statement = connection.prepareStatement(SqlMap.get(sqlName));
        statement.setFetchSize(queryFetchSize);
        for (int i = 0; i < params.length; i++) {
            statement.setObject(i + 1, params[i]);
        }
        ResultSet resultSet = statement.executeQuery();
    ....

SqlName is the enum representing your predefined sqls and SqlMap is the enum-keyed map definied somewhere else, containing actual sqls. With this solution, Veracode stops complaining about sql injection, which make sense to me as now you cannot use any sql in your method, only one you recognize.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM