Sensitive cookies without HttpOnly

Sensitive cookies without the HttpOnly flag

Description

Page scripts can read sensitive cookies that lack HttpOnly. An XSS flaw may therefore expose the values stored in those cookies.

Potential impact

A cookie can disclose any sensitive data it contains. If a session cookie is stolen, someone may be able to impersonate the user.

Remediation

  • For Django and Flask session cookies, set SESSION_COOKIE_HTTPONLY=True. In FastAPI, pass httponly=True to set_cookie when issuing a sensitive cookie.
  • Address XSS separately by validating input and encoding output for its destination.

Django’s CSRF cookie has a different purpose. CSRF_COOKIE_HTTPONLY=False is not a vulnerability by itself. Choose the setting based on how JavaScript obtains the CSRF token.

Examples

Before

python
# Django cookie settings without the flag
SESSION_COOKIE_HTTPONLY = False

After

python
# Django cookie settings with the flag
SESSION_COOKIE_HTTPONLY = True

Before

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

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

After

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

app = Flask(__name__)
app.config.update(
    SESSION_COOKIE_HTTPONLY=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,
        httponly=False,
        secure=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,
        httponly=True,
        secure=True,
        samesite="lax",
    )
    return {"message": "Cookie set"}

Explanation

  • Before: Without HttpOnly, JavaScript can read the cookie.
  • After: HttpOnly prevents JavaScript from reading the cookie.

References