Courses3 levels
Level 1 · Foundations11 courses
Level 2 · Core5 courses
Level 3 · Advanced5 courses
Labs8 topics
Library Practice exams AI Range Pricing Start free

Scenario test · 90 minutes

Review and fix a colleague's API

After this lesson you can
  • Find planted flaws in an unfamiliar API by reading its code and by sending requests
  • Fix each flaw and prove the fix with a request that fails before and passes after
  • Write a short review report that an employer can read
Lab files of this lesson (18)

The lab folder as it stands after this lesson. Unzip it in ~/krlab.

More

The zip holds every file that the course has printed up to here. To start this lesson with the files of the earlier lessons only, take the zip of the lesson before. Type the code yourself first: you learn more.

Scenario

A colleague wrote a small help-desk API in a hurry and asks you to review it before it goes to the test team. Support agents (alice and bob) keep tickets, search them, create new ones, list the files of an attachment folder and ask for a preview of a link. The code runs, and the demo worked. Nobody has looked at it with the eyes of an attacker.

The file below is helpdesk.py. The colleague uses the standard library only and keeps the data in memory, so every start gives the same five tickets. Ignore TLS (encryption) and rate limiting: a gateway (a front server) handles them. The file has several flaws: some of the kinds that lessons 4 to 9 teach, and some smaller faults that lesson 2 teaches. Find them all. Do not run it anywhere except on 127.0.0.1 of your own machine.

helpdesk.py

import hmac, json, sqlite3, subprocess, urllib.request
from http.server import BaseHTTPRequestHandler, HTTPServer
from urllib.parse import parse_qs, urlsplit

# API keys of the two support agents
KEYS = {"alice": "alice-key-7f3a91", "bob": "bob-key-c20e45"}

db = sqlite3.connect(":memory:")
db.execute("CREATE TABLE tickets (id INTEGER PRIMARY KEY, owner TEXT, title TEXT)")
db.executemany("INSERT INTO tickets (owner, title) VALUES (?, ?)", [
    ("alice", "printer jams on floor 2"),
    ("alice", "vpn drops every hour"),
    ("bob", "payroll export fails"),
    ("bob", "printer toner is empty"),
    ("alice", "new laptop request"),
])
db.commit()


class Handler(BaseHTTPRequestHandler):
    def reply(self, status, obj):
        data = json.dumps(obj).encode()
        self.send_response(status)
        self.send_header("Content-Type", "application/json")
        self.send_header("Content-Length", str(len(data)))
        origin = self.headers.get("Origin")
        if origin:
            self.send_header("Access-Control-Allow-Origin", origin)
        self.end_headers()
        self.wfile.write(data)

    def agent(self):
        key = self.headers.get("X-API-Key", "").encode()
        for name, known in KEYS.items():
            if hmac.compare_digest(key, known.encode()):
                return name

    def do_GET(self):
        agent = self.agent()
        if agent is None:
            return self.reply(401, {"error": "not authenticated"})
        url = urlsplit(self.path)
        query = parse_qs(url.query)

        if url.path == "/tickets":
            rows = db.execute("SELECT id, title FROM tickets WHERE owner = ?", (agent,))
            return self.reply(200, [{"id": i, "title": t} for i, t in rows])

        if url.path.startswith("/tickets/") and url.path[9:].isdecimal():
            row = db.execute("SELECT id, owner, title FROM tickets WHERE id = ?",
                             (int(url.path[9:]),)).fetchone()
            if row is None:
                return self.reply(404, {"error": "no such ticket"})
            return self.reply(200, {"id": row[0], "owner": row[1], "title": row[2]})

        if url.path == "/search":
            word = query.get("q", [""])[0]
            sql = ("SELECT id, title FROM tickets WHERE owner = '" + agent +
                   "' AND title LIKE '%" + word + "%'")
            try:
                rows = db.execute(sql).fetchall()
            except sqlite3.Error:
                return self.reply(400, {"error": "bad search"})
            return self.reply(200, [{"id": i, "title": t} for i, t in rows])

        if url.path == "/preview":
            target = query.get("url", [""])[0]
            try:
                page = urllib.request.urlopen(target, timeout=3).read(200)
            except Exception:
                return self.reply(502, {"error": "cannot fetch"})
            return self.reply(200, {"preview": page.decode("utf-8", "replace")})

        if url.path == "/attachments":
            folder = query.get("folder", ["docs"])[0]
            out = subprocess.run("ls " + folder, shell=True, capture_output=True, text=True).stdout
            return self.reply(200, {"files": out.split()})

        self.reply(404, {"error": "not found"})

    def do_POST(self):
        agent = self.agent()
        if agent is None:
            return self.reply(401, {"error": "not authenticated"})
        if self.path != "/tickets":
            return self.reply(404, {"error": "not found"})
        try:
            body = json.loads(self.rfile.read(int(self.headers["Content-Length"])))
            title = body["title"]
        except (ValueError, KeyError, TypeError):
            return self.reply(400, {"error": "send a JSON body with a title"})
        owner = body.get("owner", agent)
        cur = db.execute("INSERT INTO tickets (owner, title) VALUES (?, ?)", (owner, title))
        db.commit()
        self.reply(201, {"id": cur.lastrowid, "owner": owner, "title": title})


HTTPServer(("127.0.0.1", 8300), Handler).serve_forever()

You also need the two small services of lesson 6: run services.py in a second terminal. Port 8302 plays an internal service with a secret, and port 8303 plays a public site. If you no longer have the file, write it again from lesson 6.

The lab of the review
AgentsHelp deskLab servicesalice and bobhelpdesk.pyPublic site 8303Internal service 8302123AgentsHelp deskLab servicesalice and bobhelpdesk.pyPublic site 8303Internal service 8302123
  1. alice and bob → helpdesk.py: requests with X-API-Key
  2. helpdesk.py → Public site 8303: /preview of the public site
  3. helpdesk.py → Internal service 8302: what can /preview reach?

Your tasks

Work in ~/krlab/web-apis. Save the file above as helpdesk.py. There are no commands here: you know them from the lessons.

  1. Start helpdesk.py. Its keys are in the source: alice-key-7f3a91 and bob-key-c20e45. Read the code from top to bottom and write down every place where you think a control from lessons 2 to 9 is missing.
  2. Before you send the probes of this task, make sure that your list from task 1 is your own: the probes are a second look, not the list. Prove each suspicion with requests to your own copy, as alice. Read ticket 3. Run a search that uses the text zzz' OR 1=1 --, on a fresh start of the server. Create a ticket with a title of 5,000 letters a. Create a ticket with the title ok and the body field owner set to bob. Ask /preview for http://127.0.0.1:8302/secret. Try a file:// URL for a file that you make yourself. Ask /attachments for the folder docs; echo pwned (make the folder docs with two empty files if you have none). List your tickets with the header Origin: http://evil.example and read the headers of the answer. For each, write down what the server answered.
  1. Copy the file to helpdesk_fixed.py and fix every flaw that you found. The goals:
    • The keys are not in the source. They come from the variables ALICE_KEY and BOB_KEY, and the program refuses to start when one is missing.
    • A ticket belongs to its owner. Another agent cannot tell it from a ticket that does not exist.
    • The user's text never becomes part of the SQL.
    • A request body has a size limit of 1,024 bytes, as in lesson 10. It works before the body is read, answers 413 when the body is too large, and a bad Content-Length never makes the server wait.
    • A new ticket always belongs to the agent who sends it. A field owner in the body is ignored.
    • A title is accepted only when it is a text of sensible length.
    • A folder name for /attachments is accepted only when it is 1 to 20 lowercase letters, and the program starts no shell. A bad name gets 400.
    • A preview fetches only from the one public site of the lab, 127.0.0.1:8303. A URL that is not allowed gets 403. A redirect is never followed: it counts as a failed fetch, and a failed fetch gets 502.
    • The help desk has no web page of its own yet, so no answer carries a CORS header.
  2. Start helpdesk_fixed.py with two keys that you make with secrets.token_urlsafe. Export them in the terminal where you start the server, and use the same two values in your requests (a new terminal has no variables; copy the values with echo). Repeat every request of task 2 with alice's new key (restart the server before the search). Then check that the normal use still works: alice reads her own ticket 1, alice searches for printer, alice lists the folder docs, and alice asks for a preview of http://127.0.0.1:8303/. Last, ask for a preview of http://127.0.0.1:8303/go, which redirects.
  3. Start the fixed file in a terminal where the key variables are not set, and read its exit code.

Hand in

Hand in three files. They are the proof of your work that you can show to an employer.

  1. helpdesk_fixed.py, the fixed program.
  2. test_helpdesk.sh, a regression test: the check function of lessons 8 to 10 and at least five requests that fail on helpdesk.py and pass on helpdesk_fixed.py. Run it on both and keep the two outputs.
  3. report.md, a short review report. Write one block for each flaw, with the four headings below. Put the date at the top. Add a first line with the number of flaws and one sentence with your overall judgement. Order the blocks by risk, the worst first, and add one last line that says what you did not test.
HeadingWhat to write
FindingThe flaw in one sentence, the place in the code, and the kind of flaw (the lesson and, when you know it, the OWASP name).
EvidenceThe exact request that shows it and the answer that you got, copied from your terminal.
FixWhat you changed, in one or two sentences, with the changed lines.
How verifiedThe same request after the fix, the new answer, and one request that shows that normal use still works.

Keep the report to one page. A reader who has never seen the code must be able to repeat your evidence.

Review your work

Compare your report with the model findings. Your wording will differ; findings 1 to 6, 8 and 9, and their proofs, must match. Finding 7 is a smaller fault, and a careful reader may find more such faults: that is good, if each has its own evidence.

The flaws, the evidence and the fix
#FindingEvidence (before)FixVerified (after)
1Broken object-level authorisation: /tickets/<id> looks up the ticket by id only (lesson 4, OWASP API Security "Broken Object Level Authorization").alice asks for ticket 3, status 200, and the answer shows bob's ticket.Add AND owner = ? to the query and pass the agent.Status 404. Ticket 1 still gives 200.
2SQL injection: /search joins the text into the query (lesson 5, OWASP Top 10 "Injection").The text zzz' OR 1=1 -- returns 5 rows, including the tickets of bob.Use ? marks and pass "%" + word + "%" as a value.0 rows. The search for printer returns 1 row.
3Secrets in the source: both API keys are written in the file (lesson 7).Read the first lines of the file. Anyone who can read the repository has the keys.Read the keys from ALICE_KEY and BOB_KEY, and let the program stop if one is missing.Without the variables the program stops with exit code 1. With new keys the old key gives 401.
4No size limit: the body is read without a check (lesson 7, OWASP API Security "Unrestricted Resource Consumption").A title of 5,000 letters is stored, status 201. A Content-Length of -1 makes the server wait until you stop curl.Refuse a Content-Length of more than 1,024 before the read, and refuse a negative or non-numeric one with 400. Read only that many bytes.Status 413 for 5,000 letters, 400 for -1, 201 for a normal title.
5Server-side request forgery: /preview fetches any URL (lesson 6, OWASP API Security "Server Side Request Forgery").The internal URL on port 8302 gives status 200 and the secret. A file:// URL gives the local file.Allow only the schemes http and https, only the host 127.0.0.1:8303, and use an opener that does not follow redirects.Status 403 for port 8302 and for file://. Status 200 for port 8303. Status 502 for the redirect.
6Mass assignment: POST /tickets takes the owner from the body (lesson 9, OWASP API Security "Broken Object Property Level Authorization").alice sends {"title":"ok","owner":"bob"}: the answer names bob as owner, status 201, and bob's list now holds the ticket.Ignore the body field and use the agent from the key.The answer names alice, and bob's list is unchanged.
7No validation of the title: any JSON value is stored (lesson 2).{"title":""} gives 201. {"title":["x"]} makes SQLite raise an error, and curl gets no answer.Accept only isinstance(title, str) and 1 <= len(title) <= 200, and answer 400.Status 400 for both bodies. {"title":"ok"} still gives 201.
8OS command injection: /attachments joins the folder name into a shell command (lesson 9, OWASP Top 10 "Injection").The folder docs; echo pwned gives status 200, and the file list holds pwned: the shell ran the second command.Accept only [a-z]{1,20} with re.fullmatch, answer 400 otherwise, and run ls with a list of arguments and no shell.Status 400 for the same name. The folder docs still gives 200.
9Any origin may read the answers: reply copies the Origin header into Access-Control-Allow-Origin (lesson 8, OWASP API Security "Security Misconfiguration"). The risk is low today: a foreign page cannot add X-API-Key without a preflight, which the server does not answer.A request with Origin: http://evil.example gets Access-Control-Allow-Origin: http://evil.example.Remove the three lines. The help desk has no web page; when it gets one, send the header only to a listed origin.No Access-Control-Allow-Origin header for evil.example. Normal requests still give 200.

The complete change, as a diff:

@@ -1,9 +1,18 @@
-import hmac, json, sqlite3, subprocess, urllib.request
+import hmac, json, os, re, sqlite3, subprocess, urllib.request
 from http.server import BaseHTTPRequestHandler, HTTPServer
 from urllib.parse import parse_qs, urlsplit
 
-# API keys of the two support agents
-KEYS = {"alice": "alice-key-7f3a91", "bob": "bob-key-c20e45"}
+KEYS = {"alice": os.environ["ALICE_KEY"], "bob": os.environ["BOB_KEY"]}
+MAX_BODY = 1024
+ALLOWED_HOSTS = {"127.0.0.1:8303"}
+
+
+class NoRedirect(urllib.request.HTTPRedirectHandler):
+    def redirect_request(self, *args, **kwargs):
+        return None
+
+
+opener = urllib.request.build_opener(NoRedirect)
 
 db = sqlite3.connect(":memory:")
 db.execute("CREATE TABLE tickets (id INTEGER PRIMARY KEY, owner TEXT, title TEXT)")
@@ -23,9 +32,6 @@
         self.send_response(status)
         self.send_header("Content-Type", "application/json")
         self.send_header("Content-Length", str(len(data)))
-        origin = self.headers.get("Origin")
-        if origin:
-            self.send_header("Access-Control-Allow-Origin", origin)
         self.end_headers()
         self.wfile.write(data)
 
@@ -47,33 +53,34 @@
             return self.reply(200, [{"id": i, "title": t} for i, t in rows])
 
         if url.path.startswith("/tickets/") and url.path[9:].isdecimal():
-            row = db.execute("SELECT id, owner, title FROM tickets WHERE id = ?",
-                             (int(url.path[9:]),)).fetchone()
+            row = db.execute("SELECT id, owner, title FROM tickets WHERE id = ? AND owner = ?",
+                             (int(url.path[9:]), agent)).fetchone()
             if row is None:
                 return self.reply(404, {"error": "no such ticket"})
             return self.reply(200, {"id": row[0], "owner": row[1], "title": row[2]})
 
         if url.path == "/search":
             word = query.get("q", [""])[0]
-            sql = ("SELECT id, title FROM tickets WHERE owner = '" + agent +
-                   "' AND title LIKE '%" + word + "%'")
-            try:
-                rows = db.execute(sql).fetchall()
-            except sqlite3.Error:
-                return self.reply(400, {"error": "bad search"})
+            rows = db.execute("SELECT id, title FROM tickets WHERE owner = ? AND title LIKE ?",
+                              (agent, "%" + word + "%")).fetchall()
             return self.reply(200, [{"id": i, "title": t} for i, t in rows])
 
         if url.path == "/preview":
             target = query.get("url", [""])[0]
+            parts = urlsplit(target)
+            if parts.scheme not in ("http", "https") or parts.netloc not in ALLOWED_HOSTS:
+                return self.reply(403, {"error": "url not allowed"})
             try:
-                page = urllib.request.urlopen(target, timeout=3).read(200)
+                page = opener.open(target, timeout=3).read(200)
             except Exception:
                 return self.reply(502, {"error": "cannot fetch"})
             return self.reply(200, {"preview": page.decode("utf-8", "replace")})
 
         if url.path == "/attachments":
             folder = query.get("folder", ["docs"])[0]
-            out = subprocess.run("ls " + folder, shell=True, capture_output=True, text=True).stdout
+            if not re.fullmatch(r"[a-z]{1,20}", folder):
+                return self.reply(400, {"error": "bad folder name"})
+            out = subprocess.run(["ls", "--", folder], capture_output=True, text=True).stdout
             return self.reply(200, {"files": out.split()})
 
         self.reply(404, {"error": "not found"})
@@ -85,14 +92,20 @@
         if self.path != "/tickets":
             return self.reply(404, {"error": "not found"})
         try:
-            body = json.loads(self.rfile.read(int(self.headers["Content-Length"])))
-            title = body["title"]
+            size = int(self.headers.get("Content-Length") or 0)
+        except ValueError:
+            size = -1
+        if not 0 <= size <= MAX_BODY:
+            return self.reply(413 if size > MAX_BODY else 400, {"error": "bad or large Content-Length"})
+        try:
+            title = json.loads(self.rfile.read(size))["title"]
         except (ValueError, KeyError, TypeError):
             return self.reply(400, {"error": "send a JSON body with a title"})
-        owner = body.get("owner", agent)
-        cur = db.execute("INSERT INTO tickets (owner, title) VALUES (?, ?)", (owner, title))
+        if not isinstance(title, str) or not 1 <= len(title) <= 200:
+            return self.reply(400, {"error": "title must be 1 to 200 characters"})
+        cur = db.execute("INSERT INTO tickets (owner, title) VALUES (?, ?)", (agent, title))
         db.commit()
-        self.reply(201, {"id": cur.lastrowid, "owner": owner, "title": title})
+        self.reply(201, {"id": cur.lastrowid, "owner": agent, "title": title})
 
 
 HTTPServer(("127.0.0.1", 8300), Handler).serve_forever()

Three notes for the report. The file does not check Content-Type either (lesson 2 answers 415); the model fix leaves that out, and a reader who adds it does well. The fix for flaw 1 answers 404 and not 403, so that a missing ticket and a ticket of another agent look the same (lesson 4). The search still lets a user type % as a wildcard in the pattern; that returns only the user's own tickets, so it is not a leak.

If one of findings 1 to 6, 8 or 9 is missing, read the file again with the list of lessons 4 to 9 beside you and ask for each lesson: "Where does this code do what the lesson warned about?"

Mark your report

You mark this yourself, or you ask a colleague or a mentor to mark it. The page checks the numbers above; it cannot read your report.

CriterionNot yetMeets the standardStrong
FindingsOne of 1 to 6, 8 or 9 is missing, or two share a block.Findings 1 to 6, 8 and 9, one block each.Also finding 7 or another fault, with evidence.
EvidenceA claim with no request.The exact request and answer, copied from the terminal.Another person repeats each request from the report alone.
JudgementCode order; no limits named.Count first; risk order, with a reason each.Also names what was not tested, and why 9 is low risk.
FixChanges more than the flaw, or blocks normal use.Names the changed lines; the request now gets the new answer.Also shows one normal request that still works.
Regression testNone, or it passes on helpdesk.py.Five requests that fail before and pass after, both outputs kept.Has normal-use lines too.
WritingOver a page, or blames the colleague.One page, dated; the first lines say what to do.A non-specialist knows which fix comes first.

Meets the standard in every row: you can show this report as a work sample. Remove names and data that are not yours to share.

The report shows your work on this scenario, done on your own machine without a proctor.

Get a result link

When all 19 answers above are right, the server can check them again and give you a signed link. You can put the link in a CV or send it to a manager: it opens a page that shows the course, the test, the date and the name you give here. No account, and nothing is stored: keep the link.