10 web attacks

Ten attacks you'll hear about, each fired at the same toy shop. With nothing in the way they walk right in; switch on the right defence and they hit a wall.

Level: BasicWatch: 20 steps · ~100 secondsSwitch defences on and offRecall: 3 questions · 8 cardsCompare 4 setupsPython · TypeScript · nginx

What you'll take away

  • Spot the one mistake behind SQL injection and XSS: user input run as code
  • Tell XSS from CSRF, and why a CSRF token can't help once there's XSS
  • Know why defences are stacked: some attacks, like a DDoS, can only be made smaller
  • Set up the minimum a login site needs, from HTTPS and cookie flags to frame-ancestors

The 1-minute version

Tap a point and the picture below plays that step.

4Compare them all
SQL injectionno defence yet
you
your browserbrowser
café Wi-FiWi-Fi
shop.example
DB · filesDB
attacker
' OR '1'='1 → …
Step 1 / 20 · step by step
browserComes in at
DB · filesAims at
serverStopped at
offparameterized queries
0/10Defences up

The picture: the toy shop's street in the city. The shop, with its database and files next door, stands at the top of the avenue; you and your browser live in the yard at the front, behind the café's Wi-Fi on the corner; the attacker has a red building of their own. Each step is one attempt, a red light on the streets: first with nothing in the way, then against its own defence, a wall across the street (a gate, for the CDN). Defences already up stay as gold slabs on the roof of what they guard. The shop is a toy that lives only in this picture and in the code below, run on our own machine.

Step 4 · Every option at once, on one clock

Compare them all: Web attacks

The same ten attacks against the toy shop set up four ways, each adding to the one before. See which holes are still open.

1/10 · SQL injection
Nothinga site rushed outgot in 0 of 0

Use it when No site should be like this, not even a test one on the internet

Skip it when Always

A model: each attack is paired with its main defence to keep it readable; in real life one defence helps against several, and nothing stops a DDoS completely. The shop is a toy, nobody's real site. Press any tile to see it large above, with when it fits.

All ten on one page

AttackThe fixDeeper
SQL injectionparameterized queries–
XSSescaping + CSPBrowser security
CSRFSameSite + CSRF tokenCookies and sessions
DDoSCDN + rate limits–
Man-in-the-middleHTTPS + HSTS–
Phishingpasskeys–
Path traversalpath checks–
Session hijackingHttpOnly + Secure + new idCookies and sessions
Clickjackingframe-ancestorsBrowser security
Brute forcerate limits + MFAAPI security

Most fixes are one habit

Several of these are the same mistake: something a user sent is treated as code or as a path. A value in SQL, a comment in HTML, a file name on disk. Keep what users send as data all the way through: parameters, escaping, ids instead of names.

Try it only on what's yours

Practise on your own machine, on code you wrote, like the files below. Testing someone else's site without their permission is against the law in many countries, Thailand included.

In real code

login.py
# SQL injection on a toy login: the same typed text, two ways to build the query. In-memory SQLite, nothing else.
import hashlib
import sqlite3

db = sqlite3.connect(":memory:")
db.execute("CREATE TABLE users (name TEXT PRIMARY KEY, password_sha256 TEXT NOT NULL)")
db.execute("INSERT INTO users VALUES ('admin', ?)", (hashlib.sha256(b"a long secret nobody knows").hexdigest(),))


def login_unsafe(name: str, password: str):
    digest = hashlib.sha256(password.encode()).hexdigest()
    # the typed name is pasted into the SQL text: whatever it says becomes part of the statement
    sql = f"SELECT name FROM users WHERE name = '{name}' AND password_sha256 = '{digest}'"
    return db.execute(sql).fetchone()


def login_safe(name: str, password: str):
    digest = hashlib.sha256(password.encode()).hexdigest()
    # placeholders: the database gets the statement and the values apart, so a value is never code
    return db.execute("SELECT name FROM users WHERE name = ? AND password_sha256 = ?", (name, digest)).fetchone()


typed = ("admin' --", "any password")  # -- starts a comment, so the password check is gone
assert login_unsafe(*typed) == ("admin",)
assert login_safe(*typed) is None
assert login_safe("admin", "a long secret nobody knows") == ("admin",)
print(f"name {typed[0]!r}: string-built query logs in as {login_unsafe(*typed)[0]} · parameterized query: {login_safe(*typed)}")
Run: python3 login.pyIt printed: name "admin' --": string-built query logs in as admin · parameterized query: None

A toy login on an in-memory SQLite: the same typed name, admin' --, through a query built as a string (it logs in as admin) and a parameterized one (it doesn't). Really run; below is what it printed.

Common questions

How are XSS and CSRF different?

In XSS the attacker's script runs inside your page and can do anything the user can. In CSRF another site gets the browser to send you a request with the user's cookie. Once there's XSS, a CSRF token won't help: the script can read it from the page.

Doesn't HTTPS already protect me from these?

HTTPS stops someone in the middle from reading or changing traffic. SQL injection, XSS and CSRF ride inside HTTPS just fine: the request is perfectly valid, it just carries something bad.

Can't I just strip out quotes instead of using parameterized queries?

No. A number field needs no quote to be injected, and there are many ways around a filter. A parameterized query passes the value as data, apart from the statement, so whatever it looks like it never becomes SQL.

If I escape everything, why do I still need a CSP?

Because one day some spot will miss its escaping. A CSP tells the browser where scripts may come from; without 'unsafe-inline', an injected inline script won't run. It's a second wall, not a replacement for escaping.

We send SMS codes. Can phishing still get through?

Yes. The fake page asks for the code right after the password, and the attacker uses both on the real site at once. Passkeys hold up better: the browser ties each one to the real domain, so a look-alike domain can't use it.

Can a DDoS be stopped completely?

No. It comes from a great many machines at once, more than one app can take. A CDN or a DDoS protection service in front, plus rate limits, takes most of it, but nothing stops all of it every time.

What should every site with a login have, at the least?

At least the "browser side" setup in Compare: HTTPS, parameterized queries, escaping with a CSP, HttpOnly + Secure + SameSite cookies, a CSRF token and frame-ancestors. Rate limits and MFA, against guessed passwords, come next.

Table: all ten on one page

Can I try these against a real site?

Only on what's yours: your own machine and code you wrote. Testing someone else's site without permission is against the law in many countries, Thailand included. Bug bounty programs are the exception, within their rules.

Next lesson

Cookies and sessionsLevel: Intermediate

CSRF and session hijacking both ride on your login cookie; next, the cookie flags and server rules that stop each.