Hypertext Transfer Protocol (HTTP) header injection can only occur when user-supplied unsanitized data is copied into a response header. If an attacker can inject a carriage return and line feed (CRLF) into the response header, they can add new HTTP headers and/or any arbitrary content into the application’s response. This can lead to a large number of exploits including HTTP response splitting, session fixation, cross-site scripting, and malicious redirect attacks.

Impact of Header Injection

Header Injection can lead to many exploits by manipulating the header via user input and injecting additional content, control not only the headers of the HTTP but also session and content manipulation within the response. Listed below are some exploits that can occur from header injection.

  • Cross-site scripting attack, which can lead to session hijacking
  • Session fixation attacks by setting new cookies
  • Poisoning the cache of any proxy server and/or browser

Fixes for Header Injection in Java

In general, replacing all occurrences of “\n” might still not be enough. It is best practice to remove both “\n” and “\r” with “” (nothing) when transferring from user input into a response header for CRLF attacks. For HTTP attributes stripping ” “, “”” and “;” can also be used based upon context.

Vulnerable Code:

protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
  String value = req.getParameter("value");
  resp.addHeader("X-Header", value); // Noncompliant
  // ...
}

Sanitizing User-data:

protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
  String value = req.getParameter("value");

  // Allow only alphanumeric characters
  if (!value.matches("[a-zA-Z0-9]++"))
    throw new IOException();

  resp.addHeader("X-Header", value);
  // ...
}

Want to check your projects for free?

References

OWASP: HTTP Response Splitting
CWE-113: Improper Neutralization of CRLF Sequences in HTTP Headers (‘HTTP Response Splitting’)