Skip to content

Lesson 4 of 4

CSRF defences

Listen to an AI summary of CSRF defences

0:00 / 0:33

The attack the defences stop

At sign-in the sports shop gives Sam's browser a cookie. The browser sends the cookie even when a page on another website starts the request. The attack is called cross-site request forgery, or CSRF (the lesson before).

A defence asks for more than the cookie, or stops the browser sending the cookie.

What is a CSRF token

A CSRF token is a random value in a form that the server checks. A page on another website cannot read the token.

The server makes a token for Sam's session, the time after sign-in during which the server remembers Sam. The server keeps one copy of the token and writes a second copy into each form sent to Sam.

The token goes in a hidden field, a form field that the page does not show. The second form is the forged form on the attacker's page at evil.example.

  1. <form action="/account/address" method="post"><!-- the shop's address form -->
  2. <input type="hidden" name="csrf_token" value="q7Zp4kV9mX2c"><!-- a hidden field that holds the CSRF token -->
  3. <input name="line1"><!-- the form field where Sam types the first line of the address -->
  4. </form><!-- the end of the shop's form -->
  5. <form action="https://shop.example/account/address" method="post"><!-- the forged form, which sends a request to the shop -->
  6. <input type="hidden" name="line1" value="PO Box 1198"><!-- a hidden field that holds the attacker's address -->
  7. </form><!-- the end of the forged form, with no CSRF token -->
The shop's address form has a CSRF token. The forged form has no CSRF token.

A request from the forged form has Sam's cookie and the attacker's address, and no token.

Why the attacker's page cannot supply the token

The same origin policy stops a page on one website reading the pages of another. The attacker's page cannot read the shop's form, so the attacker's page cannot copy the token. The token is long and random, so the attacker cannot guess the token.

How the server checks the token

The shop's server runs the Python code when a request arrives to change the address. Look at the two values the if statement compares.

sent = request.form.get("csrf_token", "")  # the token in the request
kept = session["csrf_token"]               # the copy the server kept for Sam
if not hmac.compare_digest(sent, kept):
    return "Request refused"
save_address(request.form["line1"])

request.form.get reads one form field from the request, and gives an empty string when the field is missing. hmac.compare_digest compares the two values in constant time (Hashing and salts). session holds what the server remembers about Sam, including the server's copy of the token. The forged request has no token, so sent and kept differ and the server refuses the request. A token from the attacker's own account differs from Sam's token as well.

A token never goes in a URL. The browser's history and the server's log, a list of what happened, both keep each URL.

Django, Rails, Laravel and Spring Security are frameworks that check a CSRF token unless the code turns the check off. Express is a framework with no CSRF check of its own.

SameSite cookies

The cookie setting SameSite (Sessions) tells the browser whether to send the cookie with requests started by other websites. A form that changes something uses the method POST, the first word of the request. Following a link uses the method GET, which asks to read a page.

SameSite=Strict
No cookie with any request another website starts, even a link Sam follows.
SameSite=Lax
No cookie with a POST from another website. The cookie goes when Sam follows a link from another website.
SameSite=None
The cookie goes with both.

A forged POST with no cookie changes nothing, because the shop does not know the request is Sam's. With SameSite=Lax a link on the attacker's page still sends Sam's cookie when Sam follows the link. A shop that empties the basket on a GET to /basket/empty can still be attacked with a link. A state-changing request, a request that changes something on the server, belongs on a POST.

The Origin header

An origin is three parts of a URL. The parts are the scheme (https), the host name (shop.example) and the port, a number that picks one program on a server. The shop's origin is https://shop.example, with the usual port left out.

The Origin header is a header that the browser adds to say which origin started a request.

The browser adds the Origin header to every POST, and a page cannot change the header. The forged request from the attacker's page has the header Origin: https://evil.example. The server compares the header with the shop's own origin, and refuses a state-changing request when the two differ.

Checking the Origin header with a URL parser

Each piece of Python checks the Origin header of a request. Look at what each if statement compares.

origin = request.headers.get("Origin", "")    # the header, or empty text when the header is missing

# Weakness: checks only the start of the text
if not origin.startswith("https://shop.example"):
    return "Request refused"

# Safer: a URL parser finds the host name, and the code compares the whole host name
if urlparse(origin).hostname != "shop.example":
    return "Request refused"
# A full check compares the scheme and the port as well

The vulnerable check uses startswith, which is true when the text begins with https://shop.example.

https://shop.example.evil.example

  1. httpsthe scheme, which says how the browser talks to the server
  2. shop.example.evil.examplethe host name, the name of the computer the website runs on
An origin the weak check accepts. The host name ends in evil.example, a website the attacker owns.

A URL parser is a function that splits a URL into parts, such as the scheme and the host name. urlparse is the URL parser that Python provides, and .hostname is the host name the URL parser found. The safer check compares the whole host name with shop.example, so the attacker's host name fails. A request with no Origin header has no host name and fails as well.

Asking for the password again

For a change of password or email address, the shop can ask Sam to type the password again. The shop can also ask for a code sent to Sam's phone. The attacker's page knows neither the password nor the code, so the forged request fails.

Examples of defences that do not work

Accepting only POST
The forged form on the attacker's page already sends a POST. The rule stops a forged GET, such as a link, and no other forged request.
Several steps
A change that takes three requests is forged with three requests.
A CAPTCHA
A CAPTCHA is a puzzle that shows a person is present. A CAPTCHA does not show which website started the request.

Cross-site scripting

Cross-site scripting, also called XSS, is an attacker's script running inside a page of the shop (the lesson on XSS). The script can read the CSRF token from the shop's form. A request the script sends starts from the shop's own origin, so the Origin check passes.

Examples of what to look for

  • A form that changes something, such as an address, with no hidden field for a CSRF token.
  • Code that checks a token is in the request and does not compare the token with the server's copy.
  • A line that turns the framework's CSRF check off for one page, such as @csrf_exempt in Django.
  • A CSRF token in a URL, or code that changes something on a GET.
  • A session cookie set with no SameSite setting, or with SameSite=None.
  • An Origin check that matches part of the text, such as startswith, or that passes a missing Origin header.
  • A change of password or email address that does not ask for the password again.
  • A comment that names POST, several steps or a CAPTCHA as the CSRF defence.

Check your understanding

  1. State what a CSRF token is and where the token goes in a form.

    Show the answer

    A CSRF token is a random value that the server checks. The token goes in a hidden field of the form.

  2. The sports shop sets Sam's cookie with SameSite=Lax. Which request from the attacker's page still has Sam's cookie?

    Show the answer

    A GET from a link on the attacker's page that Sam follows. A POST from the forged form has no cookie.

  3. Give one reason why the attacker's page cannot supply Sam's CSRF token.

    Show the answer

    The same origin policy stops the attacker's page reading the shop's form, so the attacker's page cannot copy the token.

Practise it

Challenges with a weakness this lesson teaches.