SQLi not detected when using StringBuilder for query

We are not getting any alert about SQLi for the below snippet. But if it is written using naive string concatenation (using ‘+’) we do get a finding (finding title: Make sure using a dynamically formatted SQL query is safe here.).

private static void undetectedVulnerability(String username, String password) {
    StringBuilder sb = new StringBuilder();
    sb.append("SELECT * FROM db_user WHERE username = '");
    sb.append(username);
    sb.append("' AND PASSWORD = '");
    sb.append(password);
    sb.append("'");
    String sql = sb.toString();

    try (Connection connection = DriverManager.getConnection(URL);
         Statement statement = connection.createStatement();
         ResultSet resultSet = statement.executeQuery(sql)) {

        if (!resultSet.next()) {
            throw new SecurityException("User name or password incorrect");
        }
    } catch (SecurityException | SQLException e) {
        Logger.getGlobal().info(e.getLocalizedMessage());
    }
}

The assumption is that the above code should generate a warning about unsafe construction of SQL query.

SonarQube ID information (Developer edition)
Server ID: 66DB2678-AXXX6IM635Wu8RZgK1OC
Version: 8.9.1.44547
Date: 2021-07-09

Hello,

SonarQube Developer Edition+ will raise an issue in such code only if the username or the password variables are controlled by a user.
If you just analyze this snippet of code, nothing will be raised and this is expected because there is no input from external user here.
On the other hand if username is coming from request.getParam("paramName"), then a SQL Injection issue will be raised.

Here is what I get on my side when there is really an execution flow from a source (the user input) and the sink (the execution of the SQL query):

So there is no problem with StringBuilder here, the engine is working as expected and don’t raise when there is no SQL Injection.

Alex

Okey, got it, so how do figure out which sources are counted as externally controlled in the developer version? So our actual problem that sonar cube is not detecting is much more complex, and the code I attached is just a synthetic example.

Basically we would like to understand if our problem is due to our data source not being counted as controlled by the user, or if the problem is due to the fact that the data flow is so complex that Sonarcube cannot follow it

Hello,

The best here is to share the original source code with us so we can review, analyze it on our side and determine if there is a problem or not. I’ll start a private thread so we can exchange about that.

Alex

Sounds good!

Hey, will you start the private thread?
Thanks

Yes. I created one. Looks like you did not receive the notification so trying another time.
Just in case, you need to go in your Profile (Summary), then Messages, Inbox.