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

Free lesson

Detecting misuse from the audit log

After this lesson: I can detect misuse of a cluster from its API server audit log.

70 min lesson10 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

Who made themselves cluster-admin?

On Monday a service account holds cluster-admin. Nobody on the team remembers giving it.

Somebody also ran commands inside a pod over the weekend. Without a record of each request to the cluster, nobody can say who, when or what.

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 detect misuse of a cluster from its API server audit log.

Key words

WordWhat it meansExample
Audit loga record of each request to the API server
Audit policyrules for what goes in the audit log
Audit levelhow much of a request is writtenMetadata
Impersonationacting as another account with --as
Alert rulea test that flags a record worth a look

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

Every change goes through one door

kubectl, pipelines and controllers all talk to the API server. So the API server is where a record of who did what can be kept.

An audit policy says what to write. Each rule gives a level: None, Metadata (who, what, the answer), Request (the object sent too) or RequestResponse (both).

The policy you will write

RequestsLevelWhy
From nodesNoneConstant and routine
Secrets, exec, attachMetadataWho touched them, never the secret itself
Changes to pods and bindingsRequestTo see privileged: true or the role given
Everything elseNoneKeep the log small

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

Try it: one alert rule

Code: python
records = [
    {"user": "system:admin", "verb": "get", "resource": "pods/exec", "code": 101},
    {"user": "system:serviceaccount:ops:ci", "verb": "list", "resource": "secrets", "code": 403},
    {"user": "system:kube-scheduler", "verb": "list", "resource": "pods", "code": 200},
]
for r in records:
    if r["resource"] in ["pods/exec", "secrets"]:
        print("ALERT", r["resource"], r["verb"], "by", r["user"], "answer", r["code"])
# Add "nodes" to the watched list. Does the scheduler's line become an alert?

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

Turn the audit log on in your cluster

Your cluster keeps no audit log yet. You write the policy, then give the API server two flags in k3s's config file: where the policy is and where to write.

k3s reads that file when it starts, so you restart it. The pods keep running through the restart.

Write the audit policy

Command
mkdir -p ~/ch && printf '%s\n' 'apiVersion: audit.k8s.io/v1' 'kind: Policy' 'omitStages: ["RequestReceived", "ResponseStarted"]' 'rules:' '  - level: None' '    userGroups: ["system:nodes"]' '  - level: Metadata' '    resources:' '      - group: ""' '        resources: ["secrets", "pods/exec", "pods/attach"]' '  - level: Request' '    verbs: ["create", "update", "patch", "delete"]' '    resources:' '      - group: ""' '        resources: ["pods"]' '      - group: "rbac.authorization.k8s.io"' '  - level: None' > ~/ch/audit.yaml

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

Give the API server the two flags

Command
sudo cp ~/ch/audit.yaml /etc/rancher/k3s/audit.yaml && (grep -q audit-policy-file /etc/rancher/k3s/config.yaml || printf "%s\n" "kube-apiserver-arg:" "  - audit-policy-file=/etc/rancher/k3s/audit.yaml" "  - audit-log-path=/var/lib/rancher/k3s/server/logs/audit.log" "  - audit-log-maxage=7" | sudo tee -a /etc/rancher/k3s/config.yaml)

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

Restart k3s and wait until it answers

Command
sudo systemctl restart k3s; for i in $(seq 1 60); do kubectl get --raw /readyz >/dev/null 2>&1 && break; sleep 2; done; kubectl get --raw /readyz; echo

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

Make ops, an account and a pod

Command
kubectl create namespace ops; kubectl create serviceaccount ci -n ops; kubectl run tool -n ops --image=busybox:1.37.0 -- sleep 3600; kubectl wait -n ops --for=condition=Ready pod/tool --timeout=120s

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

Stage four misuses in your own cluster

Command
kubectl get secrets -n kube-system --as=system:serviceaccount:ops:ci; kubectl exec -n ops tool -- cat /etc/hostname; kubectl run miner -n ops --image=busybox:1.37.0 --privileged -- sleep 3600; kubectl create clusterrolebinding ci-admin --clusterrole=cluster-admin --serviceaccount=ops:ci

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

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

Write the alert rules, part 1

Command
mkdir -p ~/ch && printf '%s\n' 'import json' 'import sys' '' 'POWERFUL = ["cluster-admin", "admin", "edit"]' '' '' 'def who(event):' '    user = event["user"]["username"]' '    acted = event.get("impersonatedUser", {}).get("username")' '    return acted + " (as " + user + ")" if acted else user' '' '' 'def control_plane(event):' '    user = event.get("impersonatedUser", event["user"])["username"]' '    if user.startswith("system:serviceaccount:kube-system:"):' '        return True' '    return user.startswith("system:") and not user.startswith("system:serviceaccount:") and not user == "system:admin"' '' '' 'def privileged(pod):' '    for box in pod.get("spec", {}).get("containers", []):' '        if box.get("securityContext", {}).get("privileged"):' '            return True' '    return False' '' '' 'alerts = 0' 'events = [json.loads(line) for line in open(sys.argv[1])]' 'for event in events:' '    if control_plane(event):' '        continue' > ~/ch/detect.py

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

Write the alert rules, part 2

Command
printf '%s\n' '    ref = event.get("objectRef", {})' '    what = ref.get("resource", "") + "/" + ref.get("subresource", "")' '    place = ref.get("namespace", "") + "/" + ref.get("name", "")' '    code = event.get("responseStatus", {}).get("code")' '    body = event.get("requestObject") or {}' '    found = ""' '    if ref.get("resource") == "secrets":' '        found = "secrets " + event["verb"] + " in " + ref.get("namespace", "every namespace")' '    elif what == "pods/exec":' '        found = "a command run inside " + place' '    elif what == "pods/" and event["verb"] == "create" and privileged(body):' '        found = "a privileged pod " + place' '    elif ref.get("resource", "").endswith("rolebindings") and event["verb"] == "create":' '        role = body.get("roleRef", {}).get("name", "")' '        if role in POWERFUL:' '            found = role + " given by binding " + ref.get("name", "")' '    if found:' >> ~/ch/detect.py

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

Write the alert rules, part 3

Command
printf '%s\n' '        print("ALERT", found, "by", who(event), "answer", code)' '        alerts = alerts + 1' 'print(alerts, "alerts in", len(events), "records")' >> ~/ch/detect.py

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

Run the alert rules over the audit log

Command
sudo python3 ~/ch/detect.py /var/lib/rancher/k3s/server/logs/audit.log

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

A common mistake

Warning

Many people think logging everything at RequestResponse is the safe choice. For Secrets it writes the secret values into the log, which becomes a store of secrets itself. Log Secrets at Metadata, and keep the log where few can read it.

Undo the misuse, and keep watching

Each alert is a question for a person. Here the answers are clear: remove the binding and the privileged pod, and label ops restricted as in lesson 4.

In a real cluster the log goes to a central store and the rules run every few minutes. A tool such as Falco also watches calls inside pods, but it is not in your lab.

Remove the binding and pod, lock ops

Command
kubectl delete clusterrolebinding ci-admin; kubectl delete pod miner -n ops --now; kubectl label --overwrite namespace ops pod-security.kubernetes.io/enforce=restricted; kubectl auth can-i get secrets -n kube-system --as=system:serviceaccount:ops:ci

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

Assignment: alert rules

Write alert rules over audit records.

actor(event) gives the impersonated user if there is one, otherwise the user. control_plane(name) is True for kube-system service accounts and system: users, except other service accounts and system:admin. alerts(events) gives one line for each pods/exec, each Secrets request, and each created binding to cluster-admin, admin or edit, skipping the control plane.

Code: python
def actor(event):
    # The user who acted: impersonatedUser's username if present, else user's.
    return ""


def control_plane(name):
    # True for kube-system service accounts and for "system:" users,
    # except other service accounts and "system:admin".
    return False


def alerts(events):
    # One line per event that is not the control plane's:
    # "exec NAMESPACE/NAME by ACTOR" for pods/exec,
    # "secrets VERB by ACTOR" for secrets,
    # "binding ROLE by ACTOR" for a created binding to cluster-admin, admin or edit.
    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.