Skip to content
Tutorials Center
My learning

Topics

Lesson 76 of 80 ยท Practice and Review

Practice: Web Application Security

Six web security exercises with runnable solutions in Python: fix SQL injection, escape output, block CSRF, validate paths and uploads, audit headers, stop mass assignment.

Most web vulnerabilities come from a few repeated mistakes: building a command out of untrusted text, trusting a request because it carries a cookie, and trusting input because "the form only allows that". The fastest way to make the defenses automatic is to write them. In these six exercises you attack a small fake application (all in memory, nothing real) and then fix it.

Each exercise has a task, a hint and a runnable solution. Try the task first; then read the solution and change it: add another attack string, remove a check, and see which case now gets through. If an exercise feels shaky, the matching lesson is linked in the hint.

flowchart LR
    A["Untrusted input"] --> B{"Where does it go?"}
    B -->|"database query"| C["Parameterized query"]
    B -->|"HTML page"| D["Output encoding"]
    B -->|"state-changing request"| E["CSRF token + SameSite"]
    B -->|"file path or upload"| F["Allow-list + canonical path"]
    B -->|"object update"| G["Allow-listed fields"]
    H["Every response"] --> I["Security headers"]

Each exercise below handles one of these destinations. The right defense depends on where the data lands.

Exercise 1: close the SQL injection

Task. The function find_unsafe(name) builds its SQL with an f-string. Show three inputs against a fake in-memory SQLite database: a normal name, x' OR '1'='1 (returns every user) and a UNION that steals the secret column. Then write find_safe(name) with a parameterized query and show that the same inputs return nothing. Finally, look up the name O'Brien in both versions.

Hint. The database must receive the SQL text and the values separately: execute("... WHERE name = ?", (name,)). See SQL Injection and Parameterized Queries.

Python Solution 1: injection and the fix

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The last case matters: O'Brien is a perfectly honest customer, and the unsafe version crashes on them. Injection is as much a correctness bug as a security hole. Parameters fix both, because the value is never parsed as SQL. Remember that you cannot parameterize an identifier such as a column name; for those, map user choices to an allow-list of known names.

Exercise 2: encode output for its context

Task. Write comment_html(text) that shows a user comment safely in a paragraph, and link_html(label, url) that builds an anchor. The link must refuse javascript: URLs (allow only http, https and relative links) and must stay safe when the label or URL contains quotes or angle brackets. Test with a script tag, an attribute break-out and a javascript: link.

Hint. html.escape(text, quote=True) for text and attributes; check the URL scheme with an allow-list because escaping alone does not make javascript: harmless. See Cross-Site Scripting and Output Encoding.

Python Solution 2: context-aware output

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Read the last two lines carefully: the quote characters become ", so the attacker's text stays inside the attribute value and cannot start a new attribute. Escaping is only correct for the context it was written for. HTML text, attribute values, URLs, JavaScript strings and CSS each need their own rules. Better still, let a template engine escape by default and add a Content Security Policy as a second layer.

Exercise 3: stop the forged request

Task. Model a bank's transfer endpoint. A request is a dictionary with a method, cookies, headers and form data. The server must reject a transfer unless it uses POST, carries a valid session cookie, comes from an allowed Origin, and contains the correct anti-CSRF token for that session. Test a genuine request, a forged cross-site one (the browser attaches the cookie, but the attacker's page cannot know the token), a request with no token and a GET. Then write a tiny function that says whether the browser would attach a cookie to a cross-site POST for SameSite=None, Lax and Strict.

Hint. Derive the token from the session with an HMAC, so the server needs no extra storage, and compare it in constant time. See CSRF, SameSite and CORS.

Python Solution 3: CSRF defenses

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

No single layer carries the whole defense here: the request with a stripped Origin header is refused because a missing origin is not on the allow-list, the same request would still fail on its token if you removed the origin check, and a leaked token would still meet the origin check and SameSite. Also notice rule one: a GET request must never change state, because links and images trigger GET freely.

Exercise 4: validate names, paths and uploads

Task. Write three validators: valid_username (3 to 16 characters, lowercase letters, digits and underscores, starting with a letter), safe_path(base, user_path) that returns a path inside a base directory or raises an error for ../ tricks, absolute paths and null bytes, and upload_ok(filename, content) that accepts only .png files whose first bytes match the PNG signature, whatever the claimed name.

Hint. Use an allow-list with re.fullmatch, normalize the path before checking the prefix, and check the content, not only the extension. See Input Validation and Sanitization.

Python Solution 4: validators

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The username check uses fullmatch, so the trailing newline in "ok_user\n" does not slip through (a classic bug with $ anchors in some regex flavors). Even after passing these checks, uploaded files should be stored under a name you generate, outside the web root, and never executed.

Exercise 5: audit the security headers

Task. Write audit(headers) that takes a response's headers (any capitalization) and returns a list of findings. Check for: Strict-Transport-Security with a max-age of at least 15,552,000 seconds (180 days); a Content-Security-Policy without unsafe-inline; X-Content-Type-Options: nosniff; clickjacking protection (frame-ancestors in the CSP, or X-Frame-Options); a Referrer-Policy; a Server header that reveals a version number; and cookies missing Secure, HttpOnly or SameSite. Run it on a weak and on a strong sample response.

Hint. Lowercase the header names first. See HTTP Security Headers.

Python Solution 5: header audit

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

An auditor like this is easy to run in a build pipeline, so a missing header fails the build instead of being discovered in production. Treat it as a floor, not a score: a perfect header grade does not mean the application is safe.

Exercise 6: block mass assignment

Task. A profile update endpoint copies every field of the request into the user record. An attacker adds "role": "admin" and "balance": 1000000. Write update_profile(user, data) that applies only the fields the user is allowed to change (display_name and bio), checks their types and lengths, and returns the list of rejected fields so they can be logged.

Hint. An allow-list of fields, never a deny-list. See API Security.

Python Solution 6: allow-listed updates

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The server, not the client, decides which fields exist as inputs. When the same model holds both harmless and privileged fields, split the input shape from the stored shape, with separate input classes (often called DTOs or form objects) for each endpoint.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why does a parameterized query stop SQL injection?

    The database compiles the statement first and treats parameters strictly as data. Removing quotes is fragile and incomplete, which is why it is not the defense.
  2. 2. A comment is placed inside an HTML attribute value. Which statement is correct?

    An unescaped quote lets the input close the attribute and add new ones. In URL attributes a javascript: scheme must be rejected on top of escaping.
  3. 3. In the CSRF exercise, why can the attacker's page not simply include the correct token?

    The same-origin policy stops the attacker's page from reading the bank's responses, so it cannot learn the token. The browser still attaches the cookie, which is exactly why the cookie alone proves nothing.
  4. 4. Why validate the upload's content as well as its extension?

    A name is just text chosen by the sender. Checking the bytes (and storing the file under a server-chosen name) removes that trust.
  5. 5. What makes an allow-list better than a deny-list for editable fields?

    With an allow-list, anything not named is refused. With a deny-list, every field you forget to name is open to attack.

Summary

  • Keep code and data apart: parameterized queries for SQL, context-aware encoding for HTML, and allow-listed schemes for URLs.
  • A cookie proves only that the browser is signed in. State-changing requests need a CSRF token, an Origin check and sensible SameSite cookies, and must never use GET.
  • Validate with allow-lists and fullmatch, normalize paths before comparing them, and check the content of uploads, not only the name.
  • A header audit in your pipeline turns forgotten headers into failed builds.
  • Accept only the fields an endpoint is meant to change, and log what you reject.

Next: Practice: Detection and Response, where you'll analyze logs, build an incident timeline and rank vulnerabilities with CVSS.