0

After performing Vera code scan on my code, a flaw was reported saying " Improper Neutralization of CRLF Sequences in HTTP Headers ('HTTP Response Splitting - CWE ID 113') on the below code. How can I fix this code.

public void writeCookies() {
            for (final Cookie cookie : cookies) {
                super.addCookie(cookie);
            }

Here I am trying to add the Cookie on HttpServletResponseWrapper object. The flaw code reported is super.addCookie(cookie). How to get rid of this finding. Please help.

Nicolas
  • 554
  • 2
  • 11
  • 27
  • 1
    You should remove `'\r'` and `'\n'` from `cookie`. See [How to fix “Improper Neutralization of CRLF Sequences in HTTP Headers ('HTTP Response Splitting')”](https://stackoverflow.com/questions/21993290/how-to-fix-improper-neutralization-of-crlf-sequences-in-http-headers-http-res) –  Apr 30 '18 at 20:58

1 Answers1

0

To prevent HTTP response splitting attacks, you can use the OWASP Encoder library to sanitize the cookie values in your code. First, add the following package to your Gradle project:

implementation 'org.owasp.encoder:encoder:1.2.3'

If you are using Maven, add the following dependency to your pom.xml file:

<dependency>
    <groupId>org.owasp.encoder</groupId>
    <artifactId>encoder</artifactId>
    <version>1.2.3</version>
</dependency>

Then, in your Java code, import the forJava() method from the org.owasp.encoder.Encode class:

import org.owasp.encoder.Encode.forJava;

Next, use the following code to sanitize your cookie values before adding them to the response:

public void writeCookies() {
    for (final Cookie cookie : cookies) {
        // Sanitize the cookie value to remove CRLF characters
        String sanitizedValue = forJava(cookie.getValue());

        // Create a new cookie with the sanitized value
        Cookie sanitizedCookie = new Cookie(cookie.getName(), sanitizedValue);
        sanitizedCookie.setPath(cookie.getPath());
        sanitizedCookie.setDomain(cookie.getDomain());
        sanitizedCookie.setMaxAge(cookie.getMaxAge());
        sanitizedCookie.setSecure(cookie.getSecure());
        sanitizedCookie.setHttpOnly(cookie.isHttpOnly());

        super.addCookie(sanitizedCookie);
    }
}

This code loops through each cookie, sanitizes the value using the forJava() method, and creates a new cookie with the sanitized value. The new cookie is then added to the response using super.addCookie().

Sabesan
  • 654
  • 1
  • 10
  • 17