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

Lesson 04 · 35 minutes

Find and fix a broken access check

After this lesson you can
  • Explain the difference between authentication and authorisation
  • Read another user's note by changing an id, on your own server
  • Fix the flaw with an owner check on every request that denies by default
Lab files of this lesson (5)

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 customer writes to your support desk: "I changed the number in the address bar and I saw somebody else's note." Your team runs a notes API like the one you built, with a key for each user. Your task is to reproduce the report on your own machine with two users, fix the server, and then add a new route that must be safe from the first minute.

Recall

Lesson 3. The API key must never be in a URL. Name one place where the URL ends up.

The server log (the default log prints the whole request line), the browser history, proxy logs and the Referer header. A key in any of them is a leaked key.

Lesson 2. A client asks for /notes/abc. Which status does your notes API give, and which check decides it?

404. The function route accepts an id only when it matches one to nine digits, so abc is not a valid route and never reaches the note code.

The idea

Authentication asks "who are you?". Authorisation, also called access control, asks "what may you do?". Lesson 3 gave you the first. A valid key proves identity; it says nothing about which notes that person may read.

The flaw in this lesson is broken object-level authorisation (BOLA): the server finds an object by the id in the request and never asks whether this user owns it. Ids in a URL are chosen by the client, so the server must check each one.

Three rules fix it:

  1. Check on every request. Each route that touches a note runs the same check, on the server.
  2. Check the object, not only the user. "Is this user logged in?" is not enough. Ask "does this user own this note?".
  3. Deny by default. The code returns data only when a rule says yes. A missing rule, an unknown user or an unexpected case ends in a refusal.
Alice asks for the note of bob
AliceServerNotes storeGET /notes/2 with alice's keythe key is valid, user is alicefind note 2note 2, owner is bob200 and the private text of bobAliceServerNotes store12345
  1. Alice → Server: GET /notes/2 with alice's key
  2. Server: the key is valid, user is alice
  3. Server → Notes store: find note 2
  4. Notes store → Server: note 2, owner is bob
  5. Server → Alice: 200 and the private text of bob

The server did the check "who is it?" and skipped the check "may this user see this note?". The fix puts the second check between the lookup and the answer.

Worked example

1. Make two users and write the flawed server

Each user has a key from the environment (lesson 3). Create bola.py. Two notes exist: note 1 belongs to alice and note 2 to bob. Both read and delete go through handle_note, which calls find_note. Four things in the code are known or new:

  • re.fullmatch(r"/notes/([0-9]{1,9})", self.path) is the strict path check of lesson 2. match[1] holds the digits, and match is None for any other path.
  • A if c else B gives A when c is true and B when not, so find_note(...) if match else None looks for a note only when the path matched.
  • NOTES.get(note_id) returns the note, or None when the id is unknown.
  • del NOTES[id] removes a note.
  • KEYS.items() gives each key and its value of a dictionary as a pair, so for known, name in KEYS.items() visits every key together with its user name.
cd ~/krlab/web-apis
export ALICE_KEY=$(python3 -c "import secrets; print(secrets.token_urlsafe(16))")
export BOB_KEY=$(python3 -c "import secrets; print(secrets.token_urlsafe(16))")

bola.py

import hmac, json, os, re
from http.server import BaseHTTPRequestHandler, HTTPServer

KEYS = {os.environ["ALICE_KEY"]: "alice", os.environ["BOB_KEY"]: "bob"}
NOTES = {1: {"owner": "alice", "text": "alice: my private plan"},
         2: {"owner": "bob", "text": "bob: my private plan"}}

def find_note(user, note_id):
    return NOTES.get(note_id)               # the flaw: user is never used

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)))
        self.end_headers()
        self.wfile.write(data)

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

    def handle_note(self, action):
        user = self.user()
        if user is None:
            return self.reply(401, {"error": "not authenticated"})
        match = re.fullmatch(r"/notes/([0-9]{1,9})", self.path)
        note = find_note(user, int(match[1])) if match else None
        if note is None:
            return self.reply(404, {"error": "no such note"})
        if action == "delete":
            del NOTES[int(match[1])]
        self.reply(200, note)

    def do_GET(self):    self.handle_note("read")
    def do_DELETE(self): self.handle_note("delete")

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

Start it with python3 bola.py. A new terminal starts in your home folder (type cd ~/krlab/web-apis) and does not have the two variables, and typing the export lines again would make different keys. In the first terminal type echo $ALICE_KEY and echo $BOB_KEY. In the second terminal type export ALICE_KEY= and export BOB_KEY=, each followed by its own value, pasted after the sign.

2. Read your own note, and then another user's

Alice asks for note 1 and for note 2. The header -H "X-API-Key: ..." carries her key.

Alice's request for note 2
GETmethod: read/notes/2the id, chosen by the clientX-API-Key: <alice key>only says who alice isGETmethod: read/notes/2the id, chosen by the clientX-API-Key: <alice key>only says who alice is
H=http://127.0.0.1:8300
curl -s -H "X-API-Key: $ALICE_KEY" $H/notes/1
curl -s -H "X-API-Key: $ALICE_KEY" $H/notes/2
{"owner": "alice", "text": "alice: my private plan"}
{"owner": "bob", "text": "bob: my private plan"}

The second line is the flaw. Alice is logged in, and the server gave her bob's note. A request with no key gets 401, so authentication works. Authorisation does not exist.

3. Fix it in one place

Stop the server. Replace the function find_note in bola.py with this one. It returns a note only when the owner matches the user.

def find_note(user, note_id):
    note = NOTES.get(note_id)
    if note is not None and note["owner"] == user:   # deny unless the user owns it
        return note
    return None

Every route calls find_note, so one change protects read and delete. Start the server again.

4. Try the attack again

Alice tries to read and then delete bob's note. The option -X DELETE sets the method. Bob reads his own.

curl -s -H "X-API-Key: $ALICE_KEY" $H/notes/2
curl -s -X DELETE -H "X-API-Key: $ALICE_KEY" $H/notes/2
curl -s -H "X-API-Key: $BOB_KEY" $H/notes/2
{"error": "no such note"}
{"error": "no such note"}
{"owner": "bob", "text": "bob: my private plan"}

Alice cannot read or delete note 2, and bob still can. Stop the server with Ctrl+C.

The same request after the fix
AliceServerNotes storeGET /notes/2 with alice's keyfind note 2 owned by alicenothing found404 and no private textAliceServerNotes store1234
  1. Alice → Server: GET /notes/2 with alice's key
  2. Server → Notes store: find note 2 owned by alice
  3. Notes store → Server: nothing found
  4. Server → Alice: 404 and no private text

5. Read what the refusal says

The server answers 404 (not found), not 403 (forbidden), for a note that is not yours. A 403 would tell the attacker that note 2 exists. With 404, a note that does not exist and a note that is not yours look the same. Either choice is correct if you choose it on purpose and use it everywhere.

6. The finished file

This is the whole file as it stands after the steps above. The lab files of the course hold it.

The finished file: bola.py

bola.py

import hmac, json, os, re
from http.server import BaseHTTPRequestHandler, HTTPServer

KEYS = {os.environ["ALICE_KEY"]: "alice", os.environ["BOB_KEY"]: "bob"}
NOTES = {1: {"owner": "alice", "text": "alice: my private plan"},
         2: {"owner": "bob", "text": "bob: my private plan"}}

def find_note(user, note_id):
    note = NOTES.get(note_id)
    if note is not None and note["owner"] == user:   # deny unless the user owns it
        return note
    return None

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)))
        self.end_headers()
        self.wfile.write(data)

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

    def handle_note(self, action):
        user = self.user()
        if user is None:
            return self.reply(401, {"error": "not authenticated"})
        match = re.fullmatch(r"/notes/([0-9]{1,9})", self.path)
        note = find_note(user, int(match[1])) if match else None
        if note is None:
            return self.reply(404, {"error": "no such note"})
        if action == "delete":
            del NOTES[int(match[1])]
        self.reply(200, note)

    def do_GET(self):    self.handle_note("read")
    def do_DELETE(self): self.handle_note("delete")

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

Your turn

Now add a list route to the fixed server. There are no steps here: use the rules of the lesson.

  1. In bola.py give the notes four entries: keep notes 1 and 2, add note 3 for alice and note 4 for bob (any text).
  2. Add the route GET /notes (the path /notes has no id, so test self.path == "/notes" before the other code). It answers 200 with a JSON list of the ids of the notes that the calling user owns, and nothing else. With no key or a wrong key it answers 401.
  3. Restart the server. Call GET /notes with no key, then as bob. Ask for note 4 as alice. Delete note 3 as alice, then list alice's notes.

Last, list the notes as bob again. The list must not have changed.

Check yourself

The notes use ids 1, 2, 3. Would random ids such as 9f3c... remove the flaw?

No. Random ids make guessing hard, but ids leak (in logs, links, shared screens). The flaw is the missing owner check. Use random ids as an extra layer, never instead of the check.

Why is a check in the web page ("hide the Delete button") not access control?

The page runs on the client. A person can call the API directly with curl and any id. The server must refuse the request itself.

You add a new route that lists notes. What must it do first?

Return only the notes whose owner is the current user, or refuse. A new route has no protection until you write it. Deny by default means you start from a refusal and add what is allowed.

Field notes

  • BOLA is the first item of the OWASP API Security Top 10: "Broken Object Level Authorization". In the OWASP Top 10 web list the same family is "Broken Access Control", the top category.
  • Put the check in one function that every route uses, as you did, or in the query itself (WHERE id = ? AND owner = ?). Checks copied into each route are forgotten in the next route.
  • Test for it. For every route, write a test where user A uses user B's id and expect a refusal. Lesson 10 does this.
  • Authorisation also applies to functions, not only to objects. "Broken Function Level Authorization" is a separate API category: a normal user who calls an admin route such as /admin/delete.
  • Do not let the client send fields that set its own rights, such as "owner": "bob" or "role": "admin". Take the owner from the session or the key, never from the body. OWASP calls this "Broken Object Property Level Authorization". Lesson 9 builds the fix and its test.