Search code examples
javaspring-bootsanitizationcheckmarxsecure-coding

HOw to fix checkmarx error for sanitizing payload


I have a spring boot service (2.4.5) that shows a checkmarx error, that we need to sanitize the request payload. How do we sanitize the request payload?

 @ApiOperation(value = "Executes new report. The response contains the new job id.")
@PostMapping(value = "/execute")
public ResponseEntity<MyResponse<Object, Void>> execute(
        @RequestBody final MyInput input) {.......}

I am getting the following checkmarx error message for "@RequestBody final MyInput input":

The application's executeNewReport method executes an SQL query with input, at line 82 of src\main\java\com\gayathri\controllers\JobController.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. This apparent database access is seemingly encapsulated in an external component or API. Thus, it seems that the attacker might be able to inject arbitrary data into the SQL query, by altering the user input input, which is read by the execute method, at line 75 of src\main\java\com\gayathri\controllers\JobController.java. This input then flows through the code to the external API, and from there to a database server, apparently without sanitization. This may enable an SQL Injection attack, based on heuristic analysis.

I would like to sanitize my payload. Or is there no other option than to use a DTO , and then transform it to my database entity


Solution

  • Based on the description of the vulnerability, I'm assuming the exact vulnerability detected by Checkmarx is "Heuristic SQL Injection". It would be nice to see where the sink is (where the vulnerability is propagates) and not just the source ("@RequestBody final MyInput input").

    The first approach is to use parameterization or prepared statements, and here is a link to a cheatsheet from OWASP that can be useful for you

    What I think Checkmarx also looks out for is the use for the encodeForSQL function which will require you to use the OWASP Enterprise Security API library

    If you're using MySQL:

    input = ESAPI.encoder().encodeForSQL(new MySQLCodec(), input);
    

    or change the database codec appropriately