Drop CSRF middleware from the settings template

217 views
Skip to first unread message

Ryan Hiebert

unread,
Apr 16, 2023, 6:33:04 PM4/16/23
to Django developers (Contributions to Django itself)
I've recently been working with other new frameworks, particularly Remix. Coming from Django, which has had excellent CSRF for many years, one of my first questions was how to handle CSRF protection. And the response I got lead me to the "Lax" SameSite cookie parameter, and that I really wouldn't need more than that for the session cookie.

It appears that Django has defaulted the session cookie to `Lax` since the SESSION_COOKIE_SAMESITE parameter was added in Django 2.1. All current browsers seem to have supported it since 2019. Is it time for us to remove the CSRF Middleware from the default settings template file?

Jacob Rief

unread,
Apr 17, 2023, 2:32:35 AM4/17/23
to Django developers (Contributions to Django itself)
Actually, I attempted to forge POST requests on Django with disabled CSRF protection – and failed.
Maybe I wasn't creative enough, but modern browsers do indeed have a good protection against this attack vector.
I therefore welcome this proposal, unless someone can show how to bypass this protection.
– Jacob

Curtis Maloney

unread,
Apr 17, 2023, 2:45:16 AM4/17/23
to 'Mike Hansen' via Django developers (Contributions to Django itself)
On Mon, 17 Apr 2023, at 04:25, 'Ryan Hiebert' via Django developers  (Contributions to Django itself) wrote:
I've recently been working with other new frameworks, particularly Remix. Coming from Django, which has had excellent CSRF for many years, one of my first questions was how to handle CSRF protection. And the response I got lead me to the "Lax" SameSite cookie parameter, and that I really wouldn't need more than that for the session cookie.

I think I missed a detail here.

What problem are you having with using CSRF?

What response did you get?



It appears that Django has defaulted the session cookie to `Lax` since the SESSION_COOKIE_SAMESITE parameter was added in Django 2.1. All current browsers seem to have supported it since 2019. Is it time for us to remove the CSRF Middleware from the default settings template file?

Are you implying that all CSRF attacks protected by Django's current machinery are entirely mitigated by SameSite=Lax on the _session_ cookiue?

--
Curtis

Jacob Rief

unread,
Apr 17, 2023, 3:24:19 AM4/17/23
to Django developers (Contributions to Django itself)
On Monday, April 17, 2023 at 8:45:16 AM UTC+2 Curtis Maloney wrote:
Are you implying that all CSRF attacks protected by Django's current machinery are entirely mitigated by SameSite=Lax on the _session_ cookiue?

Yes. Therefore imho, the CSRF protection is just some nasty legacy, developers have to fiddle with. It doesn't add any security benefit anymore.
That said, maybe there is still a possible attack vector on cross site request forgeries, but I was unable to exploit them with disabled CSRF protection.
Therefore it would be great, if someone with more hacking experience than myself, could try this.

– Jacob

Jure Erznožnik

unread,
Apr 17, 2023, 3:55:54 AM4/17/23
to django-d...@googlegroups.com

https://security.stackexchange.com/questions/262245/are-csrf-attacks-a-thing-of-the-past

Looks like lax will do the trick, but it's not like there aren't legit cases for same-site policy to be set to something less restrictive.

LP,
Jure

--
You received this message because you are subscribed to the Google Groups "Django developers (Contributions to Django itself)" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-develop...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-developers/18aaa4cf-4612-4373-bd91-90cfb3fd07b8n%40googlegroups.com.

Stratos Moros

unread,
Apr 18, 2023, 9:34:14 AM4/18/23
to django-d...@googlegroups.com

Hello Everyone,

Looks like lax will do the trick, but it's not like there aren't legit cases for same-site policy to be set to something less restrictive.

I agree. In my experience there are legitimate cases for setting SameSite=None, especially concerning iframes.

Specifically, when developing a web app intended to be embedded as an iframe by a different top-level origin, you can't really use cookies unless their SameSite attribute is None. This is the case even if you manage the cookies entirely inside the iframe and its origin.

In such cases, you really do need Django's current CSRF protection. Personally I wouldn't mind it being off by default, since SameSite=Lax seems to be enough for most cases, but this could be a footgun for some people.

Best,
Stratos

Jacob Rief

unread,
Apr 18, 2023, 9:58:32 AM4/18/23
to Django developers (Contributions to Django itself)

In such cases, you really do need Django's current CSRF protection. Personally I wouldn't mind it being off by default, since SameSite=Lax seems to be enough for most cases, but this could be a footgun for some people.


This could be handled by the configuration checker, which runs after reading the setup. Whenever CSRF_COOKIE_SAMESITE=None but 'django.middleware.csrf.CsrfViewMiddleware' is missing in the MIDDLEWARE setting, a warning shall be issued.

– Jacob
 

Ryan Hiebert

unread,
Apr 18, 2023, 11:51:08 AM4/18/23
to Django developers (Contributions to Django itself)


On Tuesday, April 18, 2023 at 8:34:14 AM UTC-5 Stratos Moros wrote:

[...] In my experience there are legitimate cases for setting SameSite=None, especially concerning iframes.

Specifically, when developing a web app intended to be embedded as an iframe by a different top-level origin, you can't really use cookies unless their SameSite attribute is None. This is the case even if you manage the cookies entirely inside the iframe and its origin.

In my experience, even SameSite None is not sufficient to use cookies in cross-site iframes. Safari doesn't allow those cookies to be sent unless you visit the site directly first. I've heard movements for Firefox and/or Chrome having similar behavior, but I haven't been working with iframes recently enough to know the current state of that.

In such cases, you really do need Django's current CSRF protection. Personally I wouldn't mind it being off by default, since SameSite=Lax seems to be enough for most cases, but this could be a footgun for some people.

There certainly are legitimate use-cases. I like Jacob's following suggestion for a check that might help alleviate a misconfiguration concern, if they did change SameSite to none without activating CSRF protection. If it were possible to identify other places where there might be a sharp-edge misconfiguration because of the cross-domain difference of meaning between samesite and what CSRF needs, that could be good as well. And those checks would, I think, be worthwhile even without changing the default, since they are currently possible configurations.

I think what we want to weigh is whether the footgun of *not* having CSRF by default is bigger than the significant complexity overhead of managing the CSRF projection in a new project. It's marking all views, adding tags to all form templates, and I think it can be easy to underestimate the attention it requires. If we can eliminate this overhead, especially for beginners starting out with Django and web development, that sounds like a great benefit. Lowering the barrier to entry is worth a lot.

Stratos Moros

unread,
Apr 18, 2023, 1:53:17 PM4/18/23
to Django developers (Contributions to Django itself)

In my experience, even SameSite None is not sufficient to use cookies in cross-site iframes. Safari doesn't allow those cookies to be sent unless you visit the site directly first. I've heard movements for Firefox and/or Chrome having similar behavior, but I haven't been working with iframes recently enough to know the current state of that.

You are correct about this and I've been bitten by this in the past. (Un)fortunately, I am currently involved with enterprise™ projects where Safari is a distant afterthought.

There certainly are legitimate use-cases. I like Jacob's following suggestion for a check that might help alleviate a misconfiguration concern, if they did change SameSite to none without activating CSRF protection. If it were possible to identify other places where there might be a sharp-edge misconfiguration because of the cross-domain difference of meaning between samesite and what CSRF needs, that could be good as well. And those checks would, I think, be worthwhile even without changing the default, since they are currently possible configurations.

If CSRF is turned off by default, adding such a check would be a good idea. It should definitely check for SESSION_COOKIE_SAMESITE's value, since the session cookie is usually the one that needs protection from CSRF, but I haven't thought deeply about theotherthe cookies. This could have implications regarding HttpResponse.set_cookie, since it can't be checked by a system check.

I think what we want to weigh is whether the footgun of *not* having CSRF by default is bigger than the significant complexity overhead of managing the CSRF projection in a new project. It's marking all views, adding tags to all form templates, and I think it can be easy to underestimate the attention it requires. If we can eliminate this overhead, especially for beginners starting out with Django and web development, that sounds like a great benefit. Lowering the barrier to entry is worth a lot.

I mostly wanted to argue against the removal of the current CSRF machinery altogether, since it is still necessary for certain use cases.

Removing it from the default template is a harder question. I completely understand the complexity point, since I've lost track of how many times I've had to explain what a CSRF error is and why you should care. Still, I'm not sure if removing it from the default template would be OK, since it would trade off security for convenience (even if only for marginal cases).

Best,
Stratos

jure.er...@gmail.com

unread,
Apr 18, 2023, 4:57:55 PM4/18/23
to django-d...@googlegroups.com

Well, TBH, I've just completed dealing with CSRF form in my projects. I ended up exempting the particular view from CSRF because I didn't know how to get the stuff to work. The problem was that django parsed the body payload, which was JSON and thus rejected its contents (because it wasn't form payload type – POST method). As a result, DRF then had no payload to work with… I shouldn't go into too much detail as it's irrelevant to the point.

 

But, I've been considering I need a modernised CSRF: currently it works by generating a new token every page served. But we have switched our front-end to SPA and that doesn't make much sense any more since CSRF token itself doesn't change at all, since Django template system only ever serves one page. AFAIK, DRF doesn't ganerate new tokens in its pipelines.

 

Takeaway: I don't think having CSRF enabled causes any significant downsides, even with a simpler, more modern handling. It does its thing regardless and doesn't interfere if it thinks everything is ok. Otherwise, it just saved your a** 😉

 

LP,

Jure

--

You received this message because you are subscribed to the Google Groups "Django developers (Contributions to Django itself)" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-develop...@googlegroups.com.

Florian Apolloner

unread,
Apr 20, 2023, 5:51:41 AM4/20/23
to Django developers (Contributions to Django itself)
Hi,

On Tuesday, April 18, 2023 at 10:57:55 PM UTC+2 jure.er...@gmail.com wrote:

Well, TBH, I've just completed dealing with CSRF form in my projects. I ended up exempting the particular view from CSRF because I didn't know how to get the stuff to work. The problem was that django parsed the body payload, which was JSON and thus rejected its contents (because it wasn't form payload type – POST method). As a result, DRF then had no payload to work with… I shouldn't go into too much detail as it's irrelevant to the point.


I do not think this is true. Django only parses the POST data if the content-type is a form type, so if you are sending JSON properly Django will not parse the data and DRF can handle it just fine.
 

 But, I've been considering I need a modernised CSRF: currently it works by generating a new token every page served. But we have switched our front-end to SPA and that doesn't make much sense any more since CSRF token itself doesn't change at all, since Django template system only ever serves one page. AFAIK, DRF doesn't ganerate new tokens in its pipelines.


That is not accurate either. The token does not change for every page served, only it's visual representation does. That means that you can keep using the same CSRF token even though it looks like it is different (note: This assume that you are not triggering a codepath that is rotating the token).

Cheers,
Florian

Jure Erznožnik

unread,
Apr 20, 2023, 7:00:05 AM4/20/23
to django-d...@googlegroups.com

OK, I'll bite:

For the first issue, my problem revolved around this code:

@property def POST(self): # Ensure that request.POST uses our request parsing. if not _hasattr(self, '_data'): self._load_data_and_files() if is_form_media_type(self.content_type): return self._data return QueryDict('', encoding=self._request._encoding)

The second `if` asks whether the payload is form media type, and, if so, returns the parsed content, otherwise it returns a blank QueryDict. In my case, the content-type was set to application/json. It parsed successfully and self._data was still populated when the code reached the second if. However, the second if rejected the content and skipped to returning the empty QueryDict, which then resulted in payload consequently being served as the empty QueryDict also for DRF. I can't really say where the actual request._data got reset because of this, but I did (get reset). I'm guessing DRF tries to parse the data from scratch, but the stream was consumed already or some such. I didn't nearly debug this enough to KNOW what went wrong.

I was unable to find the actual culprit for this behaviour, so I ultimately just exempt the view. But the circumstances of the actual issue were very unclear: I have a commit where CSRF middleware chose this path and a commit where it did not. I was unable to find the culprit by being unable to find the condition that made the middleware go into the check at all - contrary to the commit before where it did not. Needless to say, the commits did not deal with anything I perceived as anything near CSRF or AJAX. They were super small too...

This is the actual section of the code that triggers the POST processing in the middleware:

if request.method == "POST": try: request_csrf_token = request.POST.get('csrfmiddlewaretoken', '') except OSError:

IIUC, this code tries to match the token received from the headers with one that's supposed to be in the form data payload. The code is allowed to fail just fine, but in this case it has the side-effect mentioned: the form payload will have been parsed and cannot be parsed again - while at the same time rejecting the parsed data because it is not form payload type.

As for the second issue, I must admit I don't understand your reply at all. I'm a pretty bad n00b while you're one of the Django đombas (tough big guys) and it's entirely possible I am misinterpreting what I'm seeing here. I just stated my observation that Django now only serves the index.html for me, generating a CSRF token along the way and then I use that CSRF token for all subsequent AJAX requests. I don't even understand the "visual representation changes" and "looks like it's different". So, sorry, I'm afraid I can't be of assistance here.

What I was trying to say with that paragraph was that I'd like to actually figure out a way to START doing token rotation because my observation is that it's currently NOT rotating and is therefore a lot less useful as a security measure.

Now I have bit my chunk off and I'm chewing. Hopefully no hooks in there ;)

LP,
Jure
--
You received this message because you are subscribed to the Google Groups "Django developers (Contributions to Django itself)" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-develop...@googlegroups.com.

Florian Apolloner

unread,
Apr 20, 2023, 8:48:18 AM4/20/23
to Django developers (Contributions to Django itself)
On Thursday, April 20, 2023 at 1:00:05 PM UTC+2 Jure Erznožnik wrote:

OK, I'll bite:

For the first issue, my problem revolved around this code:

@property def POST(self): # Ensure that request.POST uses our request parsing. if not _hasattr(self, '_data'): self._load_data_and_files() if is_form_media_type(self.content_type): return self._data
return QueryDict('', encoding=self._request._encoding)


That code looks correct. I cannot tell you why self._data would be lost, but the empty QueryDict for request.POST makes sense. Please note that my comments only apply to the Django codebase itself, I don't really know what DRF does aside from that

IIUC, this code tries to match the token received from the headers with one that's supposed to be in the form data payload. The code is allowed to fail just fine, but in this case it has the side-effect mentioned: the form payload will have been parsed and cannot be parsed again - while at the same time rejecting the parsed data because it is not form payload type.

It compares the value from the cookie with either the value from the header or the form payload. There is no need to parse it again, _load_data_and_files from above does this and sets it: https://github.com/encode/django-rest-framework/blob/38a74b42da10576857d6bf8bd82a73b15d12a7ed/rest_framework/request.py#L283 If you use application/json you need to access request.data in DRF, request.POST will always be empty.
 
What I was trying to say with that paragraph was that I'd like to actually figure out a way to START doing token rotation because my observation is that it's currently NOT rotating and is therefore a lot less useful as a security measure.

Oh then I did misread you. It is not neccessary to rotate the token every request, reusing the token that you obtain once is just fine.

Cheers,
Florian

Ryan Hiebert

unread,
May 5, 2023, 9:25:38 AM5/5/23
to Django developers (Contributions to Django itself)
I've been working on setting up a new project that's never going to see the light of production, so I went down the road of just disabling CSRF for that purpose. I notably found that the Django admin still requires CSRF, even when the middleware has been removed from the MIDDLEWARE setting. I found this because the development environment I was working in, Codespaces, forwards and redirects to a browser via a public address rather than localhost, and that difference means that CSRF checks were enforced in that environment, though I had no trouble with localhost. There's likely some details I'm missing in laying out this scenario, but it felt interesting enough to mention in the context of this conversation.

Deepak Sain

unread,
Jun 2, 2023, 10:02:41 AM6/2/23
to Django developers (Contributions to Django itself)
hello everyone i am deepak kumar sain new to tensorflow also new to opensource contributiuons , i am an student , i want to start my open source contribution journey can anyone helpme how can i contribute and what can i contribute am learning DSA in c++ and Flutter currently . thank you
Reply all
Reply to author
Forward
0 new messages