Search code examples
spring-bootrestcrlf-vulnerability

Spring Boot: CRLF - Securely log payload in REST API


I have a Spring Boot app which exposes a REST API. I need to log the payload to be able to find errors in the JSON in the API calls. I have ran a code analysis tools that reports the following security risk when I log the payload. https://find-sec-bugs.github.io/bugs.htm#CRLF_INJECTION_LOGS

How can I protect against code injection? I guess removing new lines only protect against fake log entries and will not protect against code injection?

REST API:

@PostMapping("/my/api")
public ResponseEntity<String> handleApi(@RequestBody Body body) {

Payload logging:

@Slf4j
public class CustomRequestLoggingFilter extends AbstractRequestLoggingFilter {
private static final int MAX_PAYLOAD_LENGTH = 64000;

public CustomRequestLoggingFilter() {
    this.setIncludeQueryString(true);
    this.setIncludePayload(true);
    this.setMaxPayloadLength(MAX_PAYLOAD_LENGTH);
}

@Override
public void afterRequest(HttpServletRequest request, String message) {
    if (request.getRequestURI().equals("/my/api")) {
        log.info(message); //This is the security risk
    }
}

Solution

  • You can try to use OWASP Json Sanitizer library (https://owasp.org/www-project-json-sanitizer/migrated_content) to clean and sanitize Json input prior logging it. If you are not concerned about adding additional 3rd party dependency to your project.

    NOTE: Last release of this library was in Jan 11, 2021

    Example:

    @Override
    public void afterRequest(HttpServletRequest request, String message) {
        if (request.getRequestURI().equals("/my/api")) {
            String sanitizedJson = JsonSanitizer.sanitize(message);
            log.info(sanitizedJson );
        }
    }