Suppose user is logged in a website www.example.com, there’s a malicious site www.attacker.com and the user’s browser allows cross domain access of cookies. For a successful CSRF attack the hacker needs the users cookies (may contain both session cookie and csrf cookie) and a csrf token in the html form page. On example.com, when user sends a GET request to get html form page containing the template tag {% csrf_token %}, django context processor calls get_token(request) method which does two things:
ref: django/csrf.py at main · django/django · GitHub
-
If request has ‘CSRF-COOKIE’ containing csrftoken then it just refreshes the token with the same secret key,. And when response is processed by csrf middleware, this token is added as a new ‘CSRF-COOKIE’.
-
It returns another token using the same secret key to be used in the html form.
Token in the CSRF-COOKIE and in the html form will be different, but it will have same secret key when decrypted. This is what is checked by django for CSRF protection.
Now as a hacker, I already can access the CSRF-COOKIE as we assumed that browser shall share the cross origin cookies. I just need csrf token present in the form.
So can’t I just make an AJAX get request when user visits attacker.com to get the html form containing CSRF token and make a automatic AJAX post request by prefilling it with malicious data?