#34465 closed Bug (needsinfo)

Handle malformed CSRF cookie

Reported by: Miha Sedej Owned by: nobody
Component: CSRF Version: 4.1
Severity: Normal Keywords: csrf, 500 error
Cc: Ruchir Harbhajanka Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

If the CSRF cookie contains invalid characters then CsrfViewMiddleware middleware raises a 500 internal server error at each request.

https://github.com/django/django/blob/main/django/middleware/csrf.py#L65 can't handle invalid characters and raises ValueError: substring not found exception.

Some clients like https://github.com/pjperez/httping send malformed CSRF cookie value. See the example:

"\"HpgYRzmZcUTBq8HW5Ms1ZpCcoKX2SLRa Max-Age=43200 Path=/ SameSite=Lax\\054stmpdid=zdfUYW3e0iLhc4_VfBHhoOGTidnz6mkYVU4yuvIx8ID9biwIrPVyFUdfcsbhZpZw0BteEJ7rXXZVKcaoshDtLe4 Max-Age=220752000 Path=/ SameSite=Lax\" Max-Age=43200 Path=/ SameSite=Lax\054stmpdid=OedsyDX-7s_guDKt1gZymYrTike8rzoZTmXpCeIMlGhPhR6LhfDh3Io3BlkdC3JoBuH4udHybYkC0LPy4_M9lpI Max-Age=220752000 Path=/ SameSite=Lax" Max-Age=43200 Path=/ SameSite=Lax,stmpdid=nj7BSEFLimv_-VSAxllXPYtBSiTNpeK3ht6lrc9hKS92EW0vE4zPuP5-R5NNbsDBkNB7seF6Q2i06rrU2mSVZIA Max-Age=220752000 Path=/ SameSite=Lax

I recommend returning a 400 response code instead of raising a 500 internal server error.

Change History (2)

comment:1 by Ruchir Harbhajanka, 20 months ago

Cc: Ruchir Harbhajanka added

comment:2 by Mariusz Felisiak, 20 months ago

Resolution: needsinfo
Status: newclosed

CsrfViewMiddleware already rejects tokens with invalid length or characters. Can you provide a small reproducible scenario?

Note: See TracTickets for help on using tickets.
Back to Top