Attacker-controlled cookie names or session identifiers

Attacker-controlled cookie names or session identifiers

Description

Using request input as a cookie name, a session ID or an entire Set-Cookie header gives the client control over the cookie’s purpose or scope. An ordinary preference can use a fixed, non-session name such as theme. The cookie API handles quotes and control characters in the value.

Potential impact

Session fixation can expose an account if the application accepts an ID known to someone else and reuses that ID or session state after login. A request-controlled name can overwrite an authentication cookie. Control of the entire header extends to the cookie attributes. Check sensitive contents, missing attributes and XSS from rendering cookie values in HTML separately.

Remediation

  • Use the framework’s session manager. For server-side sessions, accept only server-issued IDs. Rotate them after login and every privilege change, and invalidate the old ID. secrets.token_urlsafe() only generates the random value.
  • Django’s login() uses cycle_key() or replaces the session as needed. With Flask or Starlette signed-cookie sessions, clear pre-login state before recording the authenticated user. For a server-side extension, use its rotation API.
  • Pass a fixed name and server-controlled attributes to Response.set_cookie(). If users can select a name, use a server-owned allow-list and a fixed fallback. Never copy a request string into the entire Set-Cookie header.
  • Serve session cookies over HTTPS with Secure, HttpOnly and a SameSite policy that fits the flow. Limit Domain and Path to the scope you need. If you use __Host-, serve the cookie over HTTPS with Secure and Path=/, and omit Domain. Apply these settings alongside session rotation.
  • Validate ordinary cookie values against the application’s allowed values. Werkzeug’s dump_cookie() handles cookie serialization. Store integrity-sensitive state on the server or sign it. Clients can still read signed values.

Examples

Session management

Before

FastAPI/Starlette copies a request value into a session cookie:

python
from fastapi import FastAPI, Request
from starlette.responses import Response

app = FastAPI()


@app.get("/set-session")
async def set_session(request: Request):
    response = Response("ok")
    response.set_cookie(
        key="session",
        value=request.query_params["sid"],  # Unsafe: a session value known to the attacker
        secure=True,
        httponly=True,
        samesite="lax",
    )
    return response

The example sets Secure, HttpOnly and SameSite, but still takes the session ID from the request.

After

Use Django's session manager:

python
from django.contrib.auth import authenticate, login
from django.http import HttpResponse


def sign_in(request):
    user = authenticate(
        request,
        username=request.POST["username"],
        password=request.POST["password"],
    )
    if user is None:
        return HttpResponse(status=401)

    login(request, user)  # Django rotates the key or replaces the session when needed
    return HttpResponse(status=204)

Use Flask's signed-cookie session:

python
import os

from flask import Flask, abort, request, session

app = Flask(__name__)
app.config.from_mapping(
    SECRET_KEY=os.environ["FLASK_SECRET_KEY"],
    SESSION_COOKIE_SECURE=True,
    SESSION_COOKIE_HTTPONLY=True,
    SESSION_COOKIE_SAMESITE="Lax",
)


@app.post("/login")
def sign_in():
    user = verify_credentials(
        request.form["username"],
        request.form["password"],
    )
    if user is None:
        abort(401)

    session.clear()  # Remove pre-authentication state
    session["user_id"] = user.id
    return {"status": "ok"}

Implement verify_credentials for your application. After authentication succeeds, session.clear() clears the old state before Flask records the user ID.

Cookie names and headers

Before

Flask uses a request value as the cookie name:

python
from flask import Flask, make_response, request

app = Flask(__name__)


@app.get("/set-cookie")
def set_cookie():
    response = make_response("ok")
    response.set_cookie(request.args["name"], "1")  # Unsafe: a dynamic cookie name
    return response

Django sets the entire Set-Cookie header from request input:

python
from django.http import HttpResponse


def set_raw_cookie(request):
    response = HttpResponse("ok")
    response.headers["Set-Cookie"] = request.GET["raw"]  # Unsafe: the entire raw header
    return response

Flask uses request input as a mapping fallback or a serialized session value:

python
from flask import make_response, request
from werkzeug.http import dump_cookie


def unsafe_cookie_defaults():
    names = {"theme": "theme", "locale": "locale"}
    response = make_response("ok")
    name = names.get("unknown", request.args["name"])
    response.set_cookie(name, "light")  # Unsafe: the fallback is request data outside the constant mapping
    response.headers["Set-Cookie"] = dump_cookie(
        "__Host-session", request.args["sid"], secure=True, path="/"
    )  # Unsafe: serialization does not change the attacker-chosen session ID
    return response

Assigning to Set-Cookie replaces the header added by set_cookie(). This response sends only the __Host-session cookie, whose value comes from the request.

After

Use a fixed non-session cookie:

python
from fastapi import HTTPException, Request
from starlette.responses import Response


async def save_theme(request: Request):
    theme = request.query_params.get("theme", "light")
    if theme not in {"light", "dark"}:
        raise HTTPException(status_code=400)

    response = Response("saved")
    response.set_cookie(
        key="theme",
        value=theme,
        secure=True,
        samesite="lax",
    )
    return response

The theme cookie accepts only light and dark.

This example sets one preference cookie for the server to read on subsequent HTTPS requests.

python
from flask import make_response, request
from werkzeug.http import dump_cookie


def save_preference():
    response = make_response("ok")
    if request.args.get("kind") == "locale":
        requested = request.args.get("locale")
        for locale in ("en", "ja", "ko"):
            if requested == locale:
                cookie = dump_cookie(
                    "locale", locale, secure=True, httponly=True, samesite="Lax"
                )
                response.headers.add("Set-Cookie", cookie)
                return response
        return "Unsupported locale", 400

    response.set_cookie("theme", "light", secure=True, httponly=True, samesite="Lax")
    return response

With kind=locale, the handler sets the locale cookie to en, ja, or ko. If the locale is missing or unsupported, the handler returns HTTP 400 without setting a cookie. The handler sets theme=light when kind is theme, missing, or unrecognized.

References