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.
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.
0 of the 10 are handled right now. Turn defences on one at a time. In real life one defence can help against more than one attack; here each is paired with one to keep it readable. It all happens in this picture's toy shop
A login form pastes the typed name straight into its SQL, and someone types admin' --. What happens, and what's the fix?
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.
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.
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
| Attack | The fix | Deeper |
|---|---|---|
| SQL injection | parameterized queries | – |
| XSS | escaping + CSP | Browser security |
| CSRF | SameSite + CSRF token | Cookies and sessions |
| DDoS | CDN + rate limits | – |
| Man-in-the-middle | HTTPS + HSTS | – |
| Phishing | passkeys | – |
| Path traversal | path checks | – |
| Session hijacking | HttpOnly + Secure + new id | Cookies and sessions |
| Clickjacking | frame-ancestors | Browser security |
| Brute force | rate limits + MFA | API 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
# 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)}")
python3 login.pyIt printed: name "admin' --": string-built query logs in as admin · parameterized query: NoneA 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.
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.