Easier to read with cream paper, a tint, more contrast or larger text? Choose your colours and text, once, for every page.

Free lesson

Cross-site request forgery (CSRF) and its fixes

After this lesson: I can protect a state-changing request from cross-site request forgery.

60 min lesson7 commandsDVWA lab: practise SQL injection and XSS on the Damn Vulnerable Web Application

A quick check that you are not a bot, then your own lab opens on the interactive lesson.

Already have an account? Sign in

A cat picture that changed a password

Cross-site request forgery, or CSRF, is when another website makes your browser send a request to a site where you are signed in. The site sees your cookie and obeys.

Sam is signed in to a club website in one tab. In another tab, Sam opens a page of cat pictures. One picture is really a link to the club site that changes Sam's password. Sam never clicked anything.

The one rule

Warning

This lab is a website that is insecure on purpose. Attack your own private copy and nothing else; it has no way out to the internet. A real system needs the owner's written permission first. Without it, in the UK, this is a crime under the Computer Misuse Act 1990.

By the end of this lesson

Note

I can protect a state-changing request from cross-site request forgery.

Quick check: the rule

Have a go

Quick check: the rule

3 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

Key words

WordWhat it meansExample
Cross-site request forgeryanother site making your browser send a request you did not mean
Session cookiethe value that tells a site who you are
State-changing requesta request that changes data, not one that only reads
CSRF tokena secret value in the form that another site cannot read
SameSitea cookie flag that limits sending it from other sitesSameSite=Lax
Origin headerthe site a request came from, added by the browser

The cells students fill in are left blank in this preview.

Starter

Have a go

Starter

3 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

The browser adds the cookie by itself

A browser attaches a site's cookies to every request it sends there. It does this whichever page started the request.

So a page on another site can hold a form or an image that points at your club. When the browser loads it, the club receives your cookie and believes you sent it. The attacker never sees the cookie. They only need the site to act.

Worked example: one forged request

sequenceDiagram
  participant B as Sam's browser
  participant C as cats.example
  participant S as club.example
  B->>C: open the cat page
  C-->>B: page with a hidden form to club.example
  B->>S: POST /password with Sam's cookie
  S-->>B: password changed

Check

Have a go

Check

3 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

A browser deciding whether to send a cookie

Code: python
# A tiny model of a browser. Change samesite to "Lax", then "Strict", and press Run.
samesite = "None"
requests = [
    ("club.example", "GET", "same site"),
    ("cats.example", "POST", "cross site, hidden form"),
    ("cats.example", "GET", "cross site, link clicked"),
]
for page, method, how in requests:
    send = True
    if how != "same site" and samesite == "Strict":
        send = False
    if how != "same site" and samesite == "Lax" and method != "GET":
        send = False
    print(how.ljust(26), method.ljust(5), "cookie sent" if send else "no cookie")

Make a free account to save your work and track your progress.

Look at the password form in your lab

Your lab runs DVWA, a website with flaws on purpose. Start it, then run these in order. The first two sign in as the lab's own admin and keep the session in a file called jar. The third prints the form on the CSRF page. The last three print lines of the page's PHP code at the low, medium and impossible levels.

Read the sign-in form's token

Command
T=$(curl -s -c jar http://dvwa/login.php | sed -n "s/.*name=.user_token. value=.\([a-f0-9]*\).*/\1/p"); echo ${#T}

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Sign in as the lab's admin

Command
curl -s -b jar -c jar -d "username=admin&password=password&Login=Login&user_token=$T" -o /dev/null -w "%{http_code} %{redirect_url}\n" http://dvwa/login.php

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

The form on the CSRF page

Command
curl -s -b jar http://dvwa/vulnerabilities/csrf/ | grep -o "<form[^>]*>\|user_token"

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Where the low level reads the password

Command
docker exec dvwa grep -n "_GET\|token" /var/www/html/vulnerabilities/csrf/source/low.php

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

What the medium level checks

Command
docker exec dvwa grep -n "HTTP_REFERER" /var/www/html/vulnerabilities/csrf/source/medium.php

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

What the impossible level checks first

Command
docker exec dvwa grep -n "checkToken\|password_current" /var/www/html/vulnerabilities/csrf/source/impossible.php

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

What the answers tell you

The first prints 32, the length of the sign-in token. The second prints 302 http://dvwa/index.php: you are in. The third prints <form action="#" method="GET"> and nothing more. The form carries no token, and the new password travels in the address.

Low reads the new password from $_GET on lines 5 and 6 and checks nothing. Medium only asks whether the Referer contains the server's name, which dvwa.cats.example would pass. Impossible calls checkToken on line 5 and reads password_current on line 8.

A common mistake

Warning

Many people think using POST instead of GET stops CSRF. It does not: a hidden form on another site can send a POST by itself when the page loads. POST keeps changes out of links and logs, which helps. The defence is a token the other site cannot read.

The fix: a token, SameSite and Origin

Give each session a random CSRF token and put it in every form as a hidden field. On each change, compare the form's token with the session's. Another site cannot read your page, so it cannot know the token.

Add two more layers. Set session cookies SameSite=Lax or Strict. Refuse a request whose Origin header names another site. For a password, also ask for the current one.

Checking a token on the server

Code: python
import hmac
import secrets

session_token = secrets.token_hex(16)   # made once, kept with the session
page_token = session_token              # written into the form as a hidden field
# Change form_token to "guess" to see a forged form refused.
form_token = page_token
if hmac.compare_digest(form_token, session_token):
    print("token matches: change the password")
else:
    print("refused: the form did not come from this site")

Make a free account to save your work and track your progress.

Check

Have a go

Check

3 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

How to detect a forgery attempt

Log every state-changing request with its Origin and Referer headers. A change whose Origin is another site, or a burst of refused tokens, is worth an alert.

Your lab writes an access log line for every request. The Run below prints your last visit to the CSRF page. The "-" before "curl/..." is the Referer: empty here. A password change by GET is a warning sign by itself, as the new password sits in every log the address passed.

Your visit in the access log

Command
docker logs dvwa 2>&1 | grep "GET /vulnerabilities/csrf/" | tail -1

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Match each defence to what it does

Have a go

Loading…

Your answers are marked here and are not kept. An account keeps your marks.

Assignment: a CSRF guard

Write two functions. allow_change(request, session_token, allowed) checks a request, a dictionary with "method", "origin" and "token". Return "use POST" if the method is not POST, "wrong origin" if the origin is not empty and not in allowed, "bad token" if the token is empty or differs from the session's, and otherwise "ok", checking in that order. missing_flags(set_cookie) takes a Set-Cookie value and returns which of "HttpOnly", "Secure" and "SameSite" it lacks, in that order. Only SameSite=Lax or SameSite=Strict counts, in any case.

Code: python
import hmac


def allow_change(request, session_token, allowed):
    # Return "use POST", "wrong origin", "bad token" or "ok", checked in that order.
    return "ok"


def missing_flags(set_cookie):
    # Return the names among HttpOnly, Secure and SameSite that the cookie does not set.
    return []

Make a free account to save your work and track your progress.

Exit quiz

Have a go

Exit quiz

5 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

Teaching a class? Set this module for your students with a teacher guide, marked assignments and a lab for every student.