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 · 40 minutes

Decide who may do what with roles and permissions

After this lesson you can
  • Tell authorisation from authentication and apply least privilege and deny by default
  • Write and test a role-based access check in Python
  • Use Linux file permissions to give read-only access to a file
Lab files of this lesson (8)

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 medical clinic has one shared login for the whole staff, so the receptionist can open prescriptions and the nurse can sign her own notes. The clinic is moving to a new system and asks you to write the access rules first. You get the list of roles and the first ten requests that the new system must judge. Your job is to build the check, test it, and say which requests it must refuse.

Recall

Lesson 2: what does the mode 600 mean, and for whom?

The owner may read (4) and write (2). The group and everyone else get nothing.

Lesson 3: what is the difference between identification and authentication?

Identification is the claim ("I am alice"). Authentication is the proof of the claim (a password, a code, a key). Authorisation, the subject of this lesson, comes after both.

The idea

Authentication proves an identity (lesson 3). Authorisation decides what that identity may do. A system can authenticate you perfectly and still let you do too much.

Five rules guide a good design:

RuleMeaning
Least privilegeGive each person or program only the access that the task needs, and no more.
Deny by defaultWithout a rule that says yes, the answer is no. Unknown users, unknown actions and errors all end in no.
Role-based access control (RBAC)Give permissions to roles, and give roles to people. When a person changes job, you change the role, not fifty permissions.
Separation of dutiesOne person cannot finish a risky task alone. The one who writes a payment cannot approve it.
Defence in depthUse several layers, so that one failed control does not open everything. A password, a second factor, a role check and a log are four layers.

The rules apply to logs too: only the logging system may add a line, nobody may edit or delete one, and an auditor may read. Enforce every rule on the server. A button that is hidden in the browser is not a control, because the user can send the request without the button.

A permission is one allowed action on one kind of thing, such as report:read. A role is a named set of permissions, such as analyst.

Every request passes the same steps, and any "no" ends the decision:

One access decision
RequestKnow the userFind the rolesCheck permissionCheck dutiesAllowwho is it? (lesson 3)known user (unknown: deny)a role exists (none: deny)a role lists the action (no: deny)not the author (author: deny)RequestKnow the userFind the rolesCheck permissionCheck dutiesAllow12345
  1. Request → Know the user: who is it? (lesson 3)
  2. Know the user → Find the roles: known user (unknown: deny)
  3. Find the roles → Check permission: a role exists (none: deny)
  4. Check permission → Check duties: a role lists the action (no: deny)
  5. Check duties → Allow: not the author (author: deny)
Who can reach the reports
UsersServerAnaBoEveAccess checkReports1234UsersServerAnaBoEveAccess checkReports1234
  1. Ana → Access check: read a report: her role allows it
  2. Bo → Access check: create a report: his role allows it
  3. Eve → Access check (blocked): no user, no role
  4. Access check → Reports: only a yes passes through

Worked example

1. Make a folder

mkdir -p ~/krlab/security-basics/rbac
cd ~/krlab/security-basics/rbac

2. Write the access check

Write rbac.py. A dictionary ({...}) maps a key to a value, and a set (also {...}) holds values with no order and no repeats. ROLES maps each role to a set of permissions, and USERS maps each user to a set of roles. .get(key, default) reads a key and gives the default when the key is missing: that is how an unknown user becomes an empty set.

The function allowed says yes only when a role of the user lists the permission. Every other path returns False.

rbac.py

ROLES = {
    "viewer": {"report:read"},
    "analyst": {"report:read", "report:create"},
    "approver": {"report:read", "report:approve"},
    "admin": {"report:read", "report:create", "report:approve", "user:manage"},
}

USERS = {"ana": {"viewer"}, "bo": {"analyst"}, "cy": {"approver"}, "di": {"admin"}}


def allowed(user, permission):
    """Deny by default: only a role that lists the permission opens the door."""
    for role in USERS.get(user, set()):
        if permission in ROLES.get(role, set()):
            return True
    return False


def approve(user, report):
    """Separation of duties: nobody approves a report that they wrote."""
    return allowed(user, "report:approve") and report["author"] != user

3. Write the tests

A rule that you have not tested is a rule that you hope for. unittest is the test module of the standard library. A class is a named group of functions. RbacTest groups the five tests, and unittest runs each function in it whose name starts with test (a function inside a class is called a method). Write self and the first line of the class as shown: you need no more about classes now. assertTrue and assertFalse fail the test when the value is not what they expect. Write test_rbac.py.

test_rbac.py

import unittest

from rbac import allowed, approve


class RbacTest(unittest.TestCase):
    def test_role_grants_its_permission(self):
        self.assertTrue(allowed("bo", "report:create"))

    def test_least_privilege(self):
        self.assertFalse(allowed("ana", "report:create"))
        self.assertFalse(allowed("bo", "user:manage"))

    def test_unknown_user_is_denied(self):
        self.assertFalse(allowed("eve", "report:read"))

    def test_unknown_permission_is_denied(self):
        self.assertFalse(allowed("di", "server:shutdown"))

    def test_author_cannot_approve_own_report(self):
        report = {"author": "di"}
        self.assertFalse(approve("di", report))
        self.assertTrue(approve("cy", report))


unittest.main()
python3 test_rbac.py
.....
----------------------------------------------------------------------
Ran 5 tests in 0.000s

OK

Notice that di, the admin, holds report:approve and still cannot approve their own report. Separation of duties is a rule on top of the role.

4. Break deny by default and watch the tests catch it

Change the last line of allowed from return False to return True. This is the classic mistake: a check that fails open. In the command below, 2>&1 joins the error output to the normal output, and grep -E keeps only the lines that match the pattern. In the sed pattern, ^ is the start of a line and $ is the end, so only a line of exactly four spaces and return False changes. In the grep pattern, (FAIL:|Ran) means one of the two words.

sed -i 's/^    return False$/    return True/' rbac.py
python3 test_rbac.py 2>&1 | grep -E "^(FAIL:|Ran)"
FAIL: test_least_privilege (__main__.RbacTest.test_least_privilege)
FAIL: test_unknown_permission_is_denied (__main__.RbacTest.test_unknown_permission_is_denied)
FAIL: test_unknown_user_is_denied (__main__.RbacTest.test_unknown_user_is_denied)
Ran 5 tests in 0.002s

Put it back, and check that the tests pass again. tail -1 prints the last line only.

sed -i 's/^    return True$/    return False/' rbac.py
python3 test_rbac.py 2>&1 | tail -1
OK

5. Do the same with Linux permissions

The owner is the admin, the group is the readers, and others get nothing. You met chmod and umask in Part 1 of the Linux course, lesson 10. Here they work as security controls. A new file starts from the mode 666, and a new folder from 777. The umask is a mask that takes permission bits away: under umask 027, 666 loses 027 and becomes 640. Under umask 077 it becomes 600. In a subshell (commands in round brackets), umask 077 makes new files private from the start, so there is no moment in which they are open.

What umask 027 does to a new file
666new file027umask640resultrw-r-----owner, group, others666new file027umask640resultrw-r-----owner, group, others
mkdir reports
cd reports
(umask 077; echo "q3 findings" > report.txt)
ls -l report.txt
-rw------- 1 you you 12 Nov 21 08:36 report.txt

Give the group read access, with chmod 640. Then make the file read-only for everyone, as a viewer would see it, and try to write. The sign >> adds text to the end of a file, and cat prints the file.

chmod 640 report.txt
ls -l report.txt
chmod 440 report.txt
echo "edit" >> report.txt
cat report.txt
-rw-r----- 1 you you 12 Nov 21 08:36 report.txt
bash: report.txt: Permission denied
q3 findings

The write was denied and the read worked: report:read without report:create. If you run as root, the write is not denied, because root ignores modes. Use a normal user. A directory has its own rule: x lets you enter it. chmod 750 . stops others from even listing the folder.

Your turn

Write the rules of the clinic. There are no steps here: change the data and the separation rule in rbac.py, and add your own tests. These are the roles:

RolePermissions
receptionpatient:read, appointment:create
nursepatient:read, note:create
doctorpatient:read, note:create, note:sign, prescription:create
auditorpatient:read, log:read
managerstaff:manage, report:read

The staff: kim is reception, lee is a nurse, max is a doctor, ola is an auditor, pat is the manager. The separation rule: nobody signs a note that they wrote. Judge these ten requests. The last column is the author of the note, for the signing requests.

No.UserPermissionAuthor
1kimpatient:read
2kimnote:create
3leenote:create
4leenote:signlee
5maxnote:signlee
6maxnote:signmax
7olalog:read
8patpatient:read
9sampatient:read
10patstaff:manage

Then write one sentence for the clinic: which request shows least privilege at work, and which shows separation of duties?

Compare with this

Request 8 shows least privilege: the manager runs the staff, and no role of the manager lists patient:read, so the manager cannot read patient records. Request 6 shows separation of duties: max is a doctor and holds note:sign, yet he cannot sign a note that he wrote.

Check yourself

A user is signed in and changes the number in the URL from /invoice/101 to /invoice/102. They see another customer's invoice. Which control failed?

Authorisation. The user was authenticated, but the server did not check that the invoice belongs to them. Check the owner of the object on every request.

Why is a role called "superuser" for a nightly backup job a poor choice?

The job needs to read the data and write a copy, and no more. A superuser role gives it every other right too, so a flaw in the job becomes a full takeover. Make a role with only the two permissions.

The permission store is unreachable and the code catches the error. Should it allow the request or deny it?

Deny. A failure must close the door (fail closed). Allowing on error means that an attacker who can cause the error gets every permission.

Field notes

  • The broken-access-control class is first in the OWASP Top 10 in both the 2021 and the 2025 edition (A01 in each), and OWASP names "insecure direct object reference" as the example in the invoice question. Test it by trying one user's identifiers with another user's session.
  • Enforce the check on the server, in one place that every route passes through. A button that is hidden in the browser is not a control.
  • NIST SP 800-53 has the controls AC-5 (separation of duties) and AC-6 (least privilege). RBAC itself has a NIST model in ANSI INCITS 359.
  • RBAC grows roles without end in a large company. Attribute-based access control (ABAC, NIST SP 800-162) decides from attributes, such as department, time and data class, and fits cases where roles are too coarse.
  • Review who holds what on a schedule. Permissions collect over the years, and a person who has moved teams often still holds the rights of the old team.