A note pushed under the door
Somebody pushes a note under your door: "Please give the bearer your bike. Signed, Mum." The writing looks a bit like hers.
Would you hand the bike over? You would want proof the note really came from her.
Web apps face the same trick. Another website can send a form to our app, as if you pressed the button yourself.
Key words
| Word | What it means |
|---|---|
| CSRF | Cross-site request forgery: another site sending a form as you. |
| Token | A long random secret that proves a form came from our page. |
| Security header | An instruction to the browser to be stricter with a page. |
| Cookie | A small piece of data the browser sends back with every request. |
| Personal data | Any information about a person who can be identified. |
| Privacy notice | A page telling people what happens to their data. |
The cells students fill in are left blank in this preview.
By the end of this lesson
Note
I can protect every form in the app from forged requests.
Starter: what you already know
Have a go
Starter: what you already know
3 questionsSprint 4, step 14: the goal and stories
| Part | For this step |
|---|---|
| Sprint (a short block of work) | Sprint 4: reports, accessibility (use by everyone) and security. |
| E6.5 | As Netheret, I want forms and accounts protected, so that nobody can act as someone else. |
| E6.6 | As any user, I want a privacy notice, so that I know how my data is used. |
The cells students fill in are left blank in this preview.
A secret token proves the form is ours
In a CSRF attack, another website hides a form that posts to our app. Your browser sends our session cookie with it, so the app thinks you pressed the button.
The fix: keep a random token in the session, and put it in a hidden field in every form we make. Before any POST, the app checks the token. The other site cannot read our pages, so it cannot know the token. No token, or a wrong one, means error 400.
Step 14: the CSRF check, by hand
# helpdesk/security.py (part)
def csrf_token():
"""The session's CSRF token, made the first time a form needs it."""
if "csrf_token" not in session:
session["csrf_token"] = secrets.token_hex(32)
return session["csrf_token"]
def check_csrf():
"""Runs before every request and refuses a POST without the right token."""
if request.method != "POST":
return
expected = session.get("csrf_token")
sent = request.form.get("csrf_token")
# compare_digest takes the same time whether the first letter or the
# last is wrong, so timing cannot give the token away.
if not expected or not sent or not secrets.compare_digest(expected, sent):
abort(400)
Make a free account to save your work and track your progress.
Try it: a token and a guess
import secrets
# The app makes a long random token and keeps it in the session.
token = secrets.token_hex(32)
print("Token in the session:", token)
# Our own form sends the same token back in a hidden field.
sent_by_our_form = token
# A form on another website cannot read our pages, so it can only guess.
sent_by_another_site = "1234abcd"
print("Our form allowed?", secrets.compare_digest(token, sent_by_our_form))
print("Other site allowed?", secrets.compare_digest(token, sent_by_another_site))
# Press Run twice. Does the token change each time?
Make a free account to save your work and track your progress.
Check: CSRF tokens
Have a go
Check: CSRF tokens
3 questionsStep 14: the hidden field in each form
{# In every form the app makes, for example signin.html #}
<form method="post" action="{{ url_for('auth.signin') }}">
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
...
</form>
Headers and cookies add more locks
Security headers go out with every page. One says scripts may only come from our own site. One stops other sites showing our pages in a frame.
The session cookie is HttpOnly, so scripts cannot read it, and SameSite=Lax, so other sites' forms do not get it. On a real server with HTTPS it is also Secure.
Two older defences were here all along. Jinja turns < into harmless text. The library builds every lookup safely. The puzzle below shows what each one stops.
Step 14: headers and cookie settings
# helpdesk/security.py (part)
def add_security_headers(response):
"""Headers that tell the browser to be stricter with our pages."""
# Only run scripts, styles and images from our own site.
response.headers["Content-Security-Policy"] = (
"default-src 'self'; frame-ancestors 'none'; form-action 'self'; base-uri 'self'"
)
# Do not let other sites show our pages inside a frame (clickjacking).
response.headers["X-Frame-Options"] = "DENY"
# Do not guess file types: a .txt file is never run as a script.
response.headers["X-Content-Type-Options"] = "nosniff"
return response
# helpdesk/__init__.py (part)
app.config["SESSION_COOKIE_SAMESITE"] = "Lax"
app.config["SESSION_COOKIE_SECURE"] = os.environ.get("SESSION_COOKIE_SECURE") == "1"
Make a free account to save your work and track your progress.
Match each control to the attack it stops
Have a go
Loading…
Your answers are marked here and are not kept. A college account keeps every student’s marks.
A common mistake
Warning
Many students think signing in is enough security. A signed-in user's browser can still be tricked into sending a form. Security is layers: sign in, roles, company checks, tokens, headers and safe cookies. Each layer stops a different attack.
Worked example: the three aims of security
| Aim | What it means | Where the app does it |
|---|---|---|
| Confidentiality | Only the right people see data | Roles, company checks, internal notes left out |
| Integrity | Data is only changed on purpose, by the right people | CSRF tokens, server-side checks, the timeline |
| Availability | The app works when people need it | Bad input is ignored or refused, never a crash |
The cells students fill in are left blank in this preview.
The law: tell people about their data
The app holds personal data: names, work emails and what people write. The UK GDPR (the UK's data protection law) and the Data Protection Act 2018 say people must be told what happens to it.
So a privacy notice is linked from every footer. It says who holds the data, what is kept, why, who sees it, how long it is kept, and people's rights.
The only cookie is the session cookie, which is strictly needed. So the app does not need to ask before setting it.
Check: security and the law
Have a go
Check: security and the law
3 questionsBuild it yourself: step 14
Build step 14. 1. Write security.py with csrf_token, check_csrf run before every request, and add_security_headers run after it. 2. Add the hidden token to every POST form, including sign out. 3. Set the session cookie to SameSite=Lax, and Secure when an environment setting says so. 4. Write a privacy notice for your app and link it from the footer. 5. Test by hand: send a form with the token removed in the browser's tools, then look at the response headers. 6. Commit and write the change log row, and a short Sprint 4 review.
A teacher marks this in a college. Nothing you write here is kept: it goes when you leave the page.
Make a free account to save your work, or press Start lab to work through the whole lesson.
Compare with the step 14 code
Tip
Compare yours with the step 14 code on GitHub. Search every template for method="post" and check each form has the hidden token.
Change log entry for step 14
| Date | Version and files | What changed | Why |
|---|---|---|---|
| 20 March | step-14: security.py, __init__.py, main.py, privacy.html, every template with a form | A CSRF token on every POST form, security headers, safer cookie settings, a privacy notice | To protect accounts and data, and to meet the UK GDPR duty to inform people |
The cells students fill in are left blank in this preview.
Sprint 4 done. Next: the review
Every feature is built. The review sprint starts in step 15. You test the whole app by hand against its acceptance criteria (the pass or fail checks from Task 1). You record every test in the test log, and fix what fails.
Exit quiz
Have a go