Easier to read with cream paper, a tint, more contrast or larger text? Choose your colours and text, once, for every page.

Free lesson

Least privilege with Kubernetes RBAC

After this lesson: I can find an over-broad RoleBinding and narrow it to what the job needs.

65 min lesson8 commandsKubernetes lab: a one-node k3s cluster for each student on a private Ubuntu VM

A quick check that you are not a bot, then your own lab opens on the interactive lesson.

Already have an account? Sign in

A deploy account that could read everything

A pipeline needs to update one Deployment. To get it working on a Friday, its account was given the built-in edit role across the whole cluster.

Months later its token leaks from a build log. Whoever holds it can read every Secret in every namespace.

The one rule

Warning

Everything in this module happens in the cluster of your own lab. Testing a cluster you do not own needs the owner's written permission. In the UK, without it, it can break the Computer Misuse Act 1990.

Quick check: the rule

Have a go

Quick check: the rule

3 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

By the end of this lesson

Note

I can find an over-broad RoleBinding and narrow it to what the job needs.

Key words

WordWhat it meansExample
Service accountan identity a program in the cluster uses
Rolea list of allowed verbs on resources, in one namespace
ClusterRolea Role that can be used in any namespace
RoleBindinggives a role to someone in one namespace
ClusterRoleBindinggives a role to someone in every namespace
Verbwhat is done to a resourceget, patch, delete

The cells students fill in are left blank in this preview.

Starter

Have a go

Starter

3 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

The binding decides where a role applies

A role lists verbs and resources, and allows nothing until it is bound. A RoleBinding gives it to someone in one namespace. A ClusterRoleBinding gives it in every namespace.

Kubernetes ships ClusterRoles such as view, edit, admin and cluster-admin. Edit sounds modest, but it can read Secrets and run commands in pods.

Where a role applies

RoleBound byApplies in
Role in shopRoleBinding in shopshop only
ClusterRole editRoleBinding in shopshop only
ClusterRole editClusterRoleBindingEvery namespace

The cells students fill in are left blank in this preview.

Try it: rules and questions

Code: python
rules = [{"verbs": ["get", "list"], "resources": ["pods"]},
         {"verbs": ["*"], "resources": ["deployments"]}]
asks = [("get", "pods"), ("delete", "pods"), ("patch", "deployments"), ("get", "secrets")]
for verb, resource in asks:
    ok = any((verb in r["verbs"] or "*" in r["verbs"]) and resource in r["resources"] for r in rules)
    print(verb, resource, "yes" if ok else "no")
# Add {"verbs": ["get"], "resources": ["secrets"]} to rules. What changes?

Make a free account to save your work and track your progress.

Check

Have a go

Check

3 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

Ask what an account may do

You make the deploy account and give it edit across the cluster, as the pipeline team did. Then you ask the API server about it with kubectl auth can-i.

Your own account is the cluster's admin, so --as lets you ask as the deploy account. No token leaves the cluster.

Make the deploy account and its wide binding

Command
kubectl create namespace shop; kubectl create serviceaccount deployer -n shop; kubectl create clusterrolebinding deployer-edit --clusterrole=edit --serviceaccount=shop:deployer

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Ask four questions as the deploy account

Command
for q in "get secrets -n kube-system" "create pods/exec -n kube-system" "patch deployments -n shop" "create rolebindings -n shop"; do echo "$q: $(kubectl auth can-i $q --as=system:serviceaccount:shop:deployer)"; done

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Write the binding check, part 1

Command
mkdir -p ~/ch && printf '%s\n' 'import json' 'import sys' '' 'POWERFUL = ["cluster-admin", "admin", "edit"]' '' '' 'def ours(subject):' '    if subject["kind"] == "ServiceAccount":' '        return not subject.get("namespace") == "kube-system"' '    return not subject["name"].startswith("system:")' '' '' 'found = 0' 'for binding in json.load(sys.stdin)["items"]:' '    where = binding["metadata"].get("namespace", "the whole cluster")' '    role = binding["roleRef"]["name"]' '    for subject in binding.get("subjects") or []:' '        if not ours(subject):' '            continue' '        who = subject["kind"] + " " + subject.get("namespace", "") + "/" + subject["name"]' '        if role in POWERFUL:' '            print("FAIL", binding["metadata"]["name"], ":", who, "gets", role, "in", where)' '            found = found + 1' '        elif binding["kind"] == "ClusterRoleBinding" and subject["kind"] == "ServiceAccount":' > ~/ch/rbacscan.py

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Write the binding check, part 2

Command
printf '%s\n' '            print("FAIL", binding["metadata"]["name"], ":", who, "gets", role, "in the whole cluster")' '            found = found + 1' 'print(found, "over-broad bindings")' >> ~/ch/rbacscan.py

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Check every binding in the cluster

Command
kubectl get clusterrolebindings,rolebindings -A -o json | python3 ~/ch/rbacscan.py

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

A common mistake

Warning

Many people think edit is safe because it is not admin. Edit can read every Secret and run commands in pods wherever it is bound. Write a Role with only the verbs the job uses, and bind it in one namespace.

Check

Have a go

Check

3 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

One Role, one namespace

The pipeline only reads and updates Deployments in shop. So the fix is a Role in shop with get, list, watch, patch and update on deployments, and a RoleBinding in shop.

Then the wide binding goes. Ask the same questions again and check the answers changed.

Replace the wide binding with a narrow one

Command
kubectl delete clusterrolebinding deployer-edit && kubectl create role deploy-shop -n shop --verb=get,list,watch,patch,update --resource=deployments && kubectl create rolebinding deployer-deploy -n shop --role=deploy-shop --serviceaccount=shop:deployer

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Ask the four questions again

Command
for q in "get secrets -n kube-system" "create pods/exec -n kube-system" "patch deployments -n shop" "create rolebindings -n shop"; do echo "$q: $(kubectl auth can-i $q --as=system:serviceaccount:shop:deployer)"; done

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Check the bindings and list what is left

Command
kubectl get clusterrolebindings,rolebindings -A -o json | python3 ~/ch/rbacscan.py && kubectl auth can-i --list -n shop --as=system:serviceaccount:shop:deployer | grep -E "^Resources|deployments"

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Catch wide bindings again later

Run the binding check on a schedule and on every change to the cluster's files. Wide bindings come back in a hurry.

Lesson 6 turns on the API server's audit log, which records who made a binding, and who was refused a Secret.

Assignment: decide like RBAC

Write the pieces of a small RBAC checker.

rule_allows(rule, verb, resource) is True when the rule lists the verb and the resource, where "*" matches anything. allowed(rules, verb, resource) is True when any rule allows it. risky(bindings) gives, sorted, the names of bindings that give cluster-admin, admin or edit, or that are a ClusterRoleBinding to a ServiceAccount.

Code: python
POWERFUL = ["cluster-admin", "admin", "edit"]


def rule_allows(rule, verb, resource):
    # rule: {"verbs": [...], "resources": [...]}. "*" in either list matches anything.
    return False


def allowed(rules, verb, resource):
    # True when any rule allows it.
    return False


def risky(bindings):
    # Sorted names of bindings that give a POWERFUL role,
    # or that are a ClusterRoleBinding to a ServiceAccount.
    return []

Make a free account to save your work and track your progress.

Exit quiz

Have a go

Exit quiz

5 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

Teaching a class? Set this module for your students with a teacher guide, marked assignments and a lab for every student.