Foundations / Web applications and APIs
Web applications and APIs cheat sheet
Call a server
| Task | Command |
|---|---|
| Show response headers | curl -si http://127.0.0.1:8300/ |
| Show both directions | curl -sv http://127.0.0.1:8300/api/hello 2>&1 | grep -E '^[<>]' |
| Print only the status | curl -s -o /dev/null -w '%{http_code} %{content_type}\n' http://127.0.0.1:8300/nothing |
| Save the address | H=http://127.0.0.1:8300 |
| Create a note | curl -si -X POST $H/notes -H 'Content-Type: application/json' -d '{"text":"buy milk"}' |
| Delete a note | curl -s -w '[%{http_code}]\n' -X DELETE $H/notes/1 |
| Accept only digits in an id | re.fullmatch(r"/notes(?:/([0-9]{1,9}))?", self.path) |
| Refuse bad text | if not isinstance(text, str) or not 1 <= len(text) <= 200 |
Read status codes
| Term | Meaning |
|---|---|
201 | Created. 204 is deleted, no body |
400 | Bad request. 415 is wrong content type |
401 | Not authenticated |
403 | Authenticated, but not allowed |
404 | Not found, or not yours |
405 | Method not allowed on this path |
409 | Conflict with the current state, for example a quota |
413 | Body too large |
429 | Too Many Requests |
502 | Bad gateway: a fetch to another server failed |
Log in
| Task | Command |
|---|---|
| Make a key | export API_KEY=$(python3 -c "import secrets; print(secrets.token_urlsafe(32))") |
| Compare a key | hmac.compare_digest(key.encode(), API_KEY.encode()) |
| Hash a password | hashlib.scrypt(password.encode(), salt=SALT, n=2**14, r=8, p=1) (demo cost; OWASP advises Argon2id, or scrypt with n=2**17) |
| Hash for an unknown user too | hmac.compare_digest(hash_pw(password), USERS.get(user, DUMMY)), so the time is equal |
| Make a session id | secrets.token_urlsafe(32) |
| Set the cookie | f"sid={sid}; HttpOnly; SameSite=Strict; Path=/" |
| Log in, save cookie | curl -si -c jar.txt -X POST $H/login -d '{"user":"alice","password":"alice-pass"}' |
| Send the cookie | curl -s -b jar.txt $H/me |
| Send the key | curl -s -H "X-API-Key: $API_KEY" $H/api/data |
Control access
| Task | Command |
|---|---|
| Test another user's note | curl -s -H "X-API-Key: $ALICE_KEY" $H/notes/2 |
| Check owner in the query | WHERE id = ? AND owner = ? |
| Choose 404 or 403 | Use 404, so a missing note and a note that is not yours look the same |
def find_note(user, note_id):
note = NOTES.get(note_id)
if note is not None and note["owner"] == user:
return note
return NoneStop injection
| Task | Command |
|---|---|
| Test a flawed query | x' OR 1=1 -- |
| Parameterise a query | db.execute("SELECT text FROM notes WHERE owner = ? AND public = 1", (owner,)) |
| Escape text for HTML | html.escape(note) |
| Sort by a column name | Check the name against a fixed list. ? cannot hold a name |
Stop unsafe fetches
| Task | Command |
|---|---|
| List allowed hosts | ALLOWED_HOSTS = {"127.0.0.1:8303"} |
| Check scheme and host | parts.scheme not in ("http", "https") or parts.netloc not in ALLOWED_HOSTS |
| Refuse redirects | opener = urllib.request.build_opener(NoRedirect) |
| Test a fetcher | curl -s -G --data-urlencode "url=$u" $F |
Limit, log and test
| Task | Command |
|---|---|
| Protect a .env file | chmod 600 .env |
| Ignore it in Git | echo ".env" >> .gitignore |
| Limit requests | TokenBucket(rate=1, burst=3) |
| Cap the cost of a key | spent[key] = spent.get(key, 0) + 1 and refuse with 429 above DAILY_MAX |
| Refuse a bad length | if not 0 <= size <= MAX_BODY: after int(...) in try, except ValueError: size = -1 |
| Log without secrets | self.log_message("%s %s %s", self.command, self.path.split("?")[0], code) |
| Rotate a key | Write a new key to .env, restart, and expect 401 for the old key |
| Run the tests | bash test_api.sh |
Refuse in this order: key (401), rate (429), size (413, 400), route (404), input (415, 400), owner (404), method (405).
Close token and cross-site gaps
| Task | Command |
|---|---|
| Read a bearer token | auth = self.headers.get("Authorization", ""), then auth[7:] after Bearer |
| Check a signed token | header["alg"] != "HS256", hmac.compare_digest(sig, sign(...)), claims["exp"] < time.time(); any error returns None |
| Send a bearer token | curl -s -H "Authorization: Bearer $TOKEN" $H/me |
| Send CORS only to a list | if origin in ORIGINS: then send Access-Control-Allow-Origin |
| Refuse a cross-site POST | if origin and origin not in ORIGINS: answer 403 |
| Test that a text is absent | curl -si ... and case "$out" in *"$2"*) (the without function) |
Close shell and field gaps
| Task | Command |
|---|---|
| Run a program with no shell | subprocess.run(["ls", "--", name], capture_output=True, text=True) after re.fullmatch(r"[a-z]{1,20}", name) |
| Pick the fields of an object | {"owner": user, "text": text}, never note.update(body) |
| Send text in the query string | curl -s -G --data-urlencode "dir=docs; echo pwned" $H/list |
Shell helpers
| Task | Command |
|---|---|
| Remove a variable | unset API_KEY |
| Read the exit code of the last command | echo $? |
| Pass on the arguments from the third | "${@:3}" |
Search a file for plain text, even a text that starts with - | grep -qF -- "$KEY" server.log |
| Run a server in the background, then stop it | python3 notes_api.py 2> server.log &, then SERVER=$! and later kill $SERVER |
| List the ports in use | ss -ltn (Linux) or lsof -iTCP -sTCP:LISTEN -n -P (macOS) |
| Put the output of a command into a variable | API_KEY=$(python3 -c "import secrets; print(secrets.token_urlsafe(32))") |
| Set a variable for one command | DAILY_MAX=3 python3 limits.py |
| Create an empty file | touch docs/a.txt |
Read the value after = in a file | cut -d= -f2 .env |
| Wait for some seconds | sleep 3 |
| Count from 1 to N | seq 40 |
| Make a file of N letters | head -c 2000 /dev/zero | tr '\0' a |
| Copy a file with one text changed | sed 's/old/new/' in.py > out.py |
Stop curl after some seconds | curl -m 3 ... |
| Add 1 to a shell number | n=$((n+1)) |
Safety habits
- Treat the request line, headers and body as untrusted. Allow known good values and refuse the rest.
- Keep credentials out of URLs, logs and source code. Store passwords with a slow hash such as scrypt and a random salt for each user.
- Check the owner in one function or in the SQL query, and test it with user A and user B's id.
- Use parameterised queries first. Escape for the place where the text lands.
- Limit size, rate, time and cost. Send errors in one fixed shape, with no stack trace.
- Use TLS in production, and alert on bursts of 401, 413 and 429.
- Read the claims of a signed token as public. The server chooses the algorithm and checks the signature and the expiry.
- On a cookie route, check
Origin. Send CORS headers only to a list. Never hand client text to a shell, and never copy every field of a body into an object.