How do I log into django? (Rant warning) - django

Given:
A default-configured django service, and;
A default-configured django rest framework:
How do I log in?
By "default-configured", I mean that I followed the suggested tutorials of both websites.
However, neither django nor the django rest framework discusses how to use the authentication system as a user. They often seem to discuss authentication from the point of view of the python code running within the django framework.
Where can I read concise, clear documentation that tells me how the user requests the website with correct authentication?
I know that my DEFAULT_PERMISSION_CLASSES in 'REST_FRAMEWORK' is set to: rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly
Which implies that I am probably using whatever authentication is set in the django webservice by default.
And I know that my django instance has "Authenticationmiddleware" and "CsrfViewMiddleware" and the like, whatever they mean. (Ok, CSRF is easy to google, but that's besides the point)
The relevant django documentation seems to be https://docs.djangoproject.com/en/1.5/topics/auth/default/
However, that doesn't tell me how to actually log INTO the website so that I can POST some data.
Where can I find simple, concise instructions that tell me how to:
GET some data as a particular user, and.
POST some data as a particular user.
In the mean time, I will continue perusing the documentation.
So far I have attempted to do:
Obtain the csrf cookie by using GET /api-auth/login/
Perform the login by using POST /api-auth/login/ and providing the cookie obtained in the previous step.
However, Django still detects forgery.

Here is how to do it:
django-rest-framework provides a login page for you if you follow the documentation at http://django-rest-framework.org/
django by default, at least in version 1.5, uses CSRF tokens for security.
In order to login, you need to:
Obtain the cookies by visiting the login page, at /api-auth/login/, including the csrftoken and sessionid. This will be something like: csrftoken=123411231234123; sessionid=143212341234123412
Send the login page as a http POST using the above cookies, and setting the POST as a form with username, password, and csrfmiddlewaretoken as the form elements.
** The value of the csrfmiddleware should be that of the csrftoken value.
So, to re-iterate, the following must be set:
All the original cookies must be set in the POST headers.
The username in the POST form.
The password in the POST form.
The csrfmiddlewaretoken in the POST form.

Related

Why does Django/Django REST Framework not validate CSRF tokens in-depth, even with enforce-CSRF?

I am trying to enforce CSRF for a Django Rest API which is open to anonymous users.
For that matter, I've tried two different approaches:
Extending the selected API views from one CSRFAPIView base view, which has an #ensure_csrf_cookie annotation on the dispatch method.
Using a custom Authentication class based on SessionAuthentication, which applies enforce_csrf() regardless of whether the user is logged in or not.
In both approaches the CSRF check seems to work superficially. In case the CSRF token is missing from the cookie or in case the length of the token is incorrect, the endpoint returns a 403 - Forbidden.
However, if I edit the value of the CSRF token in the cookie, the request is accepted without issue. So I can use a random value for CSRF, as long as it's the correct length.
This behaviour seems to deviate from the regular Django login view, in which the contents of the CSRF do matter. I am testing in local setup with debug/test_environment flags on.
What could be the reason my custom CSRF checks in DRF are not validated in-depth?
Code fragment of the custom Authentication:
class RestCsrfAuthentication(SessionAuthentication):
def authenticate(self, request):
self.enforce_csrf(request)
rotate_token(request)
return None
And in settings:
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
'csrfexample.authentication.RestCsrfAuthentication',
]
}
The specific contents of CSRF tokens in Django never matter, actually.
This reply by a Django security team member to a question similar to yours says this:
The way our CSRF tokens work is pretty simple. Each form contains a CSRF token, which matches the CSRF cookie. Before we process the protected form, we make sure that the submitted token matches the cookie. This is a server-side check, but it's not validating against a stored server-side value. Since a remote attacker should not be able to read or set arbitrary cookies on your domain, this protects you.
Since we're just matching the cookie with the posted token, the data is not sensitive (in fact it's completely arbitrary - a cookie of "zzzz" works just fine), and so the rotation/expiration recommendations don't make any difference. If an attacker can read or set arbitrary cookies on your domain, all forms of cookie-based CSRF protection are broken, full stop.
(Actually "zzzz" won't work because of length requirements, but more on that later.) I recommend reading the entire mailing list message for a fuller understanding. There are explanations there about how Django is peculiar among frameworks because CSRF protections are independent of sessions.
I found that mailing list message via this FAQ item on the Django docs:
Is posting an arbitrary CSRF token pair (cookie and POST data) a vulnerability?
No, this is by design. Without a man-in-the-middle attack, there is no way for an attacker to send a CSRF token cookie to a victim’s browser, so a successful attack would need to obtain the victim’s browser’s cookie via XSS or similar, in which case an attacker usually doesn’t need CSRF attacks.
Some security audit tools flag this as a problem but as mentioned before, an attacker cannot steal a user’s browser’s CSRF cookie. “Stealing” or modifying your own token using Firebug, Chrome dev tools, etc. isn’t a vulnerability.
(Emphasis mine.)
The message is from 2011, but it's still valid, and to prove it let's look at the code. Both Django REST Framework's SessionAuthentication and the ensure_csrf_cookie decorator use core Django's CsrfViewMiddleware (source). In that middleware class's process_view() method, you'll see that it fetches the CSRF cookie (a cookie named csrftoken by default), and then the posted CSRF token (part of the POSTed data, with a fallback to reading the X-CSRFToken header). After that, it runs _sanitize_token() on the POSTed/X-CSRFToken value. This sanitization step is where the check for the correct token length happens; this is why you're getting 403s as expected when you provide shorter or longer tokens.
After that, the method proceeds to compare the two values using the function _compare_salted_tokens(). If you read that function, and all the further calls that it makes, you'll see that it boils down to checking if the two strings match, basically without regard to the values of the strings.
This behaviour seems to deviate from the regular Django login view, in which the contents of the CSRF do matter.
No, it doesn't matter even in the built-in login views. I ran this curl command (Windows cmd format) against a mostly default Django project:
curl -v
-H "Cookie: csrftoken=abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijkl"
-H "X-CSRFToken: abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijkl"
-F "username=admin" -F "password=1234" http://localhost:8000/admin/login/
and Django returned a session cookie (plus a CSRF cookie, of course).
Just a note on the way you're overriding SessionAuthentication.authenticate(): you probably already know this, but according to the DRF docs that method should return a (User, auth) tuple instead of None if the request has session data, i.e. if the request is from a logged-in user. Also, I think rotate_token() is unnecessary, because this code only checks for authentication status, and is not concerned with actually authenticating users. (The Django source says rotate_token() “should be done on login”.)

Is it okay to disable CSRF for slack slash command api mad in Django?

Is it disabling CSRF functionality the best practice for Slack slash command server?
I want to call an API view function in Django by a Slack slash command, for example, /test.
When I call the URL for the view function with any browser (so it is a GET request), it works as expected.
However, when I run /test in Slack, I got 403_client_error in slack, and Forbidden (CSRF cookie not set) in the Django shell.
I believe this is because Slack sends a POST request, and Django requires CSRF token for any POST requests.
My question is whether I should disable CSRF checking for this view. Will there be a significant risk? Or is there any workaround?
Short Answer:
Yes, it's fine for an API endpoint.
Longer Answer:
Cross-Site Request Forgery (CSRF) Tokens are a means of preventing CSRF Attacks. These attacks basically work by placing some malicious code on another site that runs when the user visits that site. Upon loading the malicious site, some JavaScript code runs and submits a POST request to a site that the victim is already authenticated at. Since the user is already authenticated, the server for the other site—a bank, for example—thinks that the user is actually making this request—send the attacker $100, for example—and goes ahead and processes the request. Here is a really good description of CSRF Attacks and Tokens: https://stackoverflow.com/a/33829607/8068625
The way that CSRF Tokens prevent this is by putting a token somewhere on any page that contains a form and that token gets submitted as an additional field on the form when submitted. This way the page must actually be visited (which the attacker should not be able to accomplish) in order to submit the page.
So, as long as this page you are removing the CSRF protection from does not have a form on it that you would not like submitted by an attacker, it is fine to add #csrf_exempt to the view. It seems that this is the case since the endpoint exists solely as an API endpoint for a Slack Slash Command.
You might consider adding some other form of authentication for your API endpoints (note that CSRF is not for use in APIs) like, for example, JSON Web Tokens. But that is up to you.

Is this how Django's CSRF protection works?

Being a beginner at cookies, CSRF and Django (using 1.4), from what I can make out this is how it works, please correct me where I go wrong...
The following applies where django.middleware.csrf.CsrfViewMiddleware is included in the MIDDLEWARE_CLASSES tuple.
Where a POST form includes the csrf_token tag, and the view concerned passes RequestContext to the template, requesting the page means Django includes a hidden form field which contains an alphanumeric string. Django also returns to the browser a cookie with the name set to csrftoken and value set to the same alphanumeric string.
When receiving the form submission, Django checks that the alphanumeric string value from the hidden form field matches and the csrftoken cookie received from the browser. If they don't match a 403 response is issued.
A CSRF attack might come in the form of a malicious web site that includes an iframe. The iframe includes a POST form and some JavaScript. The form's action attribute points to my Django site. The form is designed to do something nasty at my site, and the JS submits the form when the iframe is loaded.
The browser would include the csrftoken cookie in the header of the form submission. However, the form would not include the hidden field with the matching alphanumeric string, so a 403 is returned and the attack fails. If the iframe JS tried to access the cookie, so as to create the correct hiddden form field, the browser would prevent it from doing so.
Is this correct?
I would say that you are right. You will find here my own formulation of it.
To summarize:
The CSRF token is sent from the code, which means that the malicious code must know it.
The CSRF token is stored in a cookie and sent by the browser.
The attacker cannot access the cookie because of the same-origin policy.
The server can simply verify that the "safe" value coming from the cookie is the same as the one coming from the code.
I think what you want is described here in the official Django Documentation.
https://docs.djangoproject.com/en/dev/ref/contrib/csrf/#how-it-works
Above link was broken when I tried, but for version 1.7 this works:
https://docs.djangoproject.com/en/1.7/ref/contrib/csrf/

django REST facebook authentication

I have a site that allows Facebook authentication using django-social-auth
Now I also need to authenticate using a non-cookie-based API. My idea is to include a "sessionid=" as a POST field (it will be using HTTPS). So far I managed to "fool" django to access this sessionid as if it were a cookie (I basically do something like request.COOKIES['sessionid'] = request.POST['sessionid'] in a middleware).
My problem is how to give the sessionid to the user right after he authenticated.
From what I could find out, facebook gives the user an "access token" which is then sent to /complete/facebook/ , which is processed by django-social-auth and returns a "Set-cookie" header containing the "sessionid" key. But instead of that, I'd need it to return the sessionid key as a json in the page content (the API client can't read http response header).
Seems like a challenge. But perhaps you can make use of a save signal that fires a Comet event with the required JSON. As a starting point an old version of the django-social-auth doc seems to mention signals.
https://django-social-auth.readthedocs.org/en/v0.7.1/signals.html
However a better approach may be to skip django-social-auth all together and go for a python social auth. The documentation itselfs says:
"NOTE: THIS LIBRARY IS DEPRECATED IN FAVOR OF python-social-auth."

Can I use HTTP Basic Authentication with Django?

We have a website running on Apache, access to which has a number of static pages protected via HTTP Basic authentication.
I've written a new part of the site with Django using Django's built in support for user management.
The problem I have is that users have to log in once via the HTTP Basic authentication and then again using a Django login form. This both clumsy and very confusing for users.
I was wondering if anyone had found a way to make Django log a user in using the HTTP Basic authentication information.
I not expecting to pass a password to Django, but rather if a user dave has been authenticated by Apache then they should be automatically logged into Django as dave too.
(One option would be to make Apache and Django share a user store to ensure common usernames and passwords but this would still involve two login prompts which is what I'm trying to avoid.)
For just supporting basic auth on some requests (and not mucking with the web server -- which is how someone might interpret your question title), you will want to look here:
http://www.djangosnippets.org/snippets/243/
This has been added to the Django 1.3 release. See more current documentation for this here:
http://docs.djangoproject.com/en/dev/howto/auth-remote-user/
Do check out Oli's links. You basically see the authenticated username as verified by Basic HTTP Authentication in Django by looking at request.META['REMOTE_USER'].
Update: Tested the proposed patch for ticket #689, which is available up-to-date in telenieko's git repository here. It applies cleanly at least on revision 9084 of Django.
Activate the remote user authentication backend by
adding the RemoteUserAuthMiddleware after AuthenticationMiddleware
adding the setting AUTHENTICATION_BACKENDS = ('django.contrib.auth.backends.RemoteUserAuthBackend',)
If you use lighttpd and FastCGI like I do, activate mod_auth, create credentials for a test user (I called it testuser and set 123 as the password) and configure the Django site to require basic authentication.
The following urls.py can be used to test the setup:
from django.conf.urls.defaults import *
from django.http import HttpResponse
from django.contrib.auth.models import User
urlpatterns = patterns('',
url(regex='^$',
view=lambda request: HttpResponse(repr(request), 'text/plain')),
url(regex='^user/$',
view=lambda request: HttpResponse(repr(request.user), 'text/plain')),
url(regex='^users/$',
view=lambda request: HttpResponse(
','.join(u.username for u in User.objects.all()),
'text/plain')),
)
After reloading lighty and the Django FCGI server, loading the root of the site now asks for authentication and accepts the testuser credentials, and then outputs a dump of the request object. In request.META these new properties should be present:
'AUTH_TYPE': 'Basic'
'HTTP_AUTHORIZATION': 'Basic dGVzdHVzZXI6MTIz'
'REMOTE_USER': 'testuser'
The /user/ URL can be used to check that you're indeed logged in as testuser:
<User: testuser>
And the /users/ URL now lists the automatically added testuser (here the admin user I had created when doing syncdb is also shown):
admin,testuser
If you don't want to patch Django, it's trivial to detach the RemoteUserAuthBackend and RemoteUserAuthMiddleware classes into a separate module and refer to that in the Django settings.
Yes you can use basic autorization with django as something similar:
def post(self, request):
auth_header = request.META.get('HTTP_AUTHORIZATION', '')
token_type, _, credentials = auth_header.partition(' ')
import base64
expected = base64.b64encode(b'<username>:<password>').decode()
if token_type != 'Basic' or credentials != expected:
return HttpResponse(status=401)
authorization success flow code ...
request.META contains key HTTP_AUTHORIZATION in which your Autorization is present.
In case if you are using apache with modWSGI, the key HTTP_AUTHORIZATION might not be present. You need to add below line in your WSGI config
WSGIPassAuthorization On
Refer this detailed answer:
Passing apache2 digest authentication information to a wsgi script run by mod_wsgi
Hope it is useful for someone who is wondering why HTTP_AUTHORIZATION key is not present
There is httpauth.py. I'm still a complete newb with Django so I've no idea how it fits in exactly, but it should do what you're looking for.
Edit: here's a longer bug thread on the subject.
Because django can be run in several ways, and only modpython gives you close integration with Apache, I don't believe there is a way for django to log you in basic on Apache's basic auth. Authentication should really be done at the application level as it'll give you much more control and will be simpler. You really don't want the hassle of sharing a userdata between Python and Apache.
If you don't mind using a patched version of Django then there is a patch at http://www.djangosnippets.org/snippets/56/ which will give you some middleware to support basic auth.
Basic auth is really quite simple - if the user isn't logged in you return a 401 authentication required status code. This prompts the browser to display a login box. The browser will then supply the username and password as bas64 encoded strings. The wikipedia entry http://en.wikipedia.org/wiki/Basic_access_authentication is pretty good.
If the patch doesn't do what you want then you could implement basic auth yourself quite quickly.
This seems to be a task for custom AuthenticationBackend - see Django documentation on this subject, djangosnippets.org has some real-life examples of such code (see 1 or 2) (and this is not really a hard thing).
AuthenticationBackend subclasses have to have only 2 methods defined and their code is pretty straightforward: one has to return User object for user ID, the second has to perform credentials check and return User object if the credentials are valid.