CSRF token in page source

Viewed 660

If the token is visible in the page source (I.e. hidden input field) wouldn’t this defeat the purpose? The token can just be grabbed from the page source. Maybe I’m overthinking this, but shouldn’t a CSRF token only be generated on successful login?

3 Answers

CSRF tokens in the page are compared to CSRF tokens that are associated with a browser (e.g. via a cookie or session).

So consider this attack:

  1. Attacker makes a request to the Good Site and gets a CSRF token
  2. Attacker injects that token into a form on their Evil™ Site
  3. The Victim visits the Evil™ Site and JS on the page immediately submits the form to Good Site
  4. The Good Site compares the CSRF token in the form data with the one associated with the Victim's browser. They don't match because the attacker didn't grab the token from the page source that was delivered to the Victim; they had to make their own request.

Victim and Good Site are safe.

CSRF tokens should be generated after a session has been established with a client, not necessarily only after authentication. Malicious sites could still get a CSRF token from your site by scraping the page source, as you suggested, but the CSRF token they receive won't be valid for the target user's session.

Another advantage to using CSRF tokens at the session-level is because you could then protect your authentication forms against CSRF attacks as well. You'd need to create a session pre-authentication for this to work.

CSRF tokens are not directly related to authentication, they can be used on any form. The purpose of a CSRF token is to correlate two things:

  • The user that requested a form.
  • The user that submits the form.

The general approach is this:

  • When you display a form, you associate the token with the user by sending it in a cookie, or associating it with an existing session cookie. You also include it as a hidden field in the form.
  • When you receive a form submission, you look at the CSRF token from the hidden field, and compare it against the token in the cookie or session. If they don't match, it's not the same user.

The reason this check matters is that a malicious user can look at a form on your site, copy and manipulate it, and then trick a user into submitting it. To your server, this looks like the user submitted the real form, so without a CSRF check, you would accept the instructions as coming from the victim, rather than the attacker.

Related