Description
Without Secure, a session cookie issued over HTTPS can travel in plaintext on a later HTTP request.
Potential impact
Anyone able to read that traffic could see identifiers or permission data in the cookie. An exposed, valid session ID can give someone access to the account with the user’s permissions.
Remediation
- Set
Secure: trueon every session and authentication cookie. Use HTTPS throughout the service. A redirect to HTTPS takes effect after the first HTTP request. - Set
HttpOnly: trueto prevent JavaScript from reading the value. Address XSS separately. - Apply these attributes in shared creation and deletion helpers. Use
Secureby default for other cookies where possible. When deleting a cookie, match its original name,DomainandPath.
Examples
Before
go
package main
import (
"net/http"
)
// Before: missing Secure flag
func setSessionCookie(w http.ResponseWriter, sessionID string) {
// Login session cookie without Secure or HttpOnly
cookie := http.Cookie{
Name: "SESSIONID",
Value: sessionID,
Path: "/",
// Secure defaults to false
// HttpOnly defaults to false
}
// This cookie may also be sent in HTTP requests
http.SetCookie(w, &cookie)
}
After
go
package main
import (
"net/http"
"time"
)
// After: explicitly set Secure and HttpOnly
func setSessionCookie(w http.ResponseWriter, sessionID string) {
cookie := http.Cookie{
Name: "SESSIONID",
Value: sessionID,
Path: "/",
Secure: true, // Send only over HTTPS
HttpOnly: true, // Not readable by JavaScript
SameSite: http.SameSiteLaxMode,
Expires: time.Now().Add(30 * time.Minute),
}
http.SetCookie(w, &cookie)
}
// Retain Secure/HttpOnly when deleting the cookie
func deleteSessionCookie(w http.ResponseWriter) {
cookie := http.Cookie{
Name: "SESSIONID",
Value: "",
Path: "/",
Secure: true,
HttpOnly: true,
Expires: time.Unix(0, 0),
MaxAge: -1,
}
http.SetCookie(w, &cookie)
}
Both helpers use SESSIONID and Path: "/" and omit Domain. The response that deletes this host-only cookie must come from the same host that issued it.