Description
A cookie (Cookie) without Secure, or with the attribute explicitly disabled, may be sent over HTTP and exposed to an attacker observing network traffic. HTTPS applications should set Secure so cookies are sent over encrypted connections.
Potential impact
Exposure requires the cookie to be sent over HTTP on a path the attacker can observe. The consequences depend on the stored value and session permissions.
- Session hijacking through intercepted session cookies
- Disclosure of authentication tokens or personal information
- Unauthorized account access using a stolen session
Remediation
- Use
cookie.setSecure(true)in Java, orcookie.secure = trueorcookie.setSecure(true)in Kotlin. - Centralize cookie creation and response handling to enforce
Secure=trueby default. - Operate the service over HTTPS and redirect HTTP requests. A redirect alone cannot protect a cookie already sent in the initial HTTP request.
- Apply
HttpOnlyto sensitive cookies that do not need JavaScript access, and set an appropriateSameSitepolicy through a supported API or theSet-Cookieheader.
Examples
These ordinary preference cookies demonstrate only the transport attribute. Assess sensitivity from the values and their use, not the names alone.
Java
Before
java
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
void addPreferenceCookie(HttpServletResponse response, String value) {
Cookie cookie = new Cookie("theme", value);
cookie.setSecure(false);
response.addCookie(cookie);
}
After
java
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
void addPreferenceCookie(HttpServletResponse response, String value) {
Cookie cookie = new Cookie("theme", value);
cookie.setSecure(true);
response.addCookie(cookie);
}
Kotlin
Before
kotlin
import jakarta.servlet.http.Cookie
import jakarta.servlet.http.HttpServletResponse
fun addPreferenceCookie(response: HttpServletResponse, value: String) {
val cookie = Cookie("preferences", value)
cookie.secure = false
response.addCookie(cookie)
}
After
kotlin
import jakarta.servlet.http.Cookie
import jakarta.servlet.http.HttpServletResponse
fun addPreferenceCookie(response: HttpServletResponse, value: String) {
val cookie = Cookie("preferences", value)
cookie.secure = true
response.addCookie(cookie)
}