Sensitive cookies without Secure

Sensitive cookies without the Secure attribute

Description

Without Secure, the browser may send a sensitive cookie in an unencrypted HTTP request. Anyone who can observe that traffic may read its value.

Potential impact

An intercepted cookie may disclose sensitive data or, if it is a session cookie, allow someone to impersonate the user. Altered cookie values can also affect application data if the application trusts them.

Remediation

Restrict cookie transmission to HTTPS using the setting for your framework.

  • In Django, set SESSION_COOKIE_SECURE and CSRF_COOKIE_SECURE to True.
  • For Flask session cookies, set SESSION_COOKIE_SECURE=True.
  • In FastAPI, pass secure=True to set_cookie when issuing a sensitive cookie.

Examples

Before

python
# Django cookie settings without the flag
SESSION_COOKIE_SECURE = False
CSRF_COOKIE_SECURE = False

After

python
# Django cookie settings with the flag
SESSION_COOKIE_SECURE = True
CSRF_COOKIE_SECURE = True

Before

python
# Flask cookie settings without the flag
from flask import Flask

app = Flask(__name__)
app.config.update(
    SESSION_COOKIE_SECURE=False,
)

After

python
# Flask cookie settings with the flag
from flask import Flask

app = Flask(__name__)
app.config.update(
    SESSION_COOKIE_SECURE=True,
)

Before

python
# FastAPI cookie settings without the flag
from fastapi import FastAPI, Response
import secrets

app = FastAPI()

@app.post("/set-cookie")
async def set_cookie(response: Response):
    session_id = secrets.token_urlsafe(32)  # An unpredictable session value issued by the server
    response.set_cookie(
        key="session",
        value=session_id,
        secure=False,
        httponly=True,
        samesite="lax",
    )
    return {"message": "Cookie set"}

After

python
# FastAPI cookie settings with the flag
from fastapi import FastAPI, Response
import secrets

app = FastAPI()

@app.post("/set-cookie")
async def set_cookie(response: Response):
    session_id = secrets.token_urlsafe(32)  # An unpredictable session value issued by the server
    response.set_cookie(
        key="session",
        value=session_id,
        secure=True,
        httponly=True,
        samesite="lax",
    )
    return {"message": "Cookie set"}

Explanation

  • Before: Without Secure, the cookie may be sent over HTTP.
  • After: Secure restricts transmission to HTTPS. HttpOnly separately prevents JavaScript from reading the cookie.

References