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 questionsBy the end of this lesson
Note
I can detect misuse of a cluster from its API server audit log.
Key words
| Word | What it means | Example |
|---|---|---|
| Audit log | a record of each request to the API server | |
| Audit policy | rules for what goes in the audit log | |
| Audit level | how much of a request is written | Metadata |
| Impersonation | acting as another account with --as | |
| Alert rule | a 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 questionsEvery 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
| Requests | Level | Why |
|---|---|---|
| From nodes | None | Constant and routine |
| Secrets, exec, attach | Metadata | Who touched them, never the secret itself |
| Changes to pods and bindings | Request | To see privileged: true or the role given |
| Everything else | None | Keep the log small |
The cells students fill in are left blank in this preview.
Try it: one alert rule
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 questionsTurn 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
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.yamlShown here, not run. Press Start lab to type it into your own lab’s terminal.
Give the API server the two flags
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
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; echoShown here, not run. Press Start lab to type it into your own lab’s terminal.
Make ops, an account and a pod
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=120sShown here, not run. Press Start lab to type it into your own lab’s terminal.
Stage four misuses in your own cluster
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:ciShown here, not run. Press Start lab to type it into your own lab’s terminal.
Check
Have a go
Check
3 questionsWrite the alert rules, part 1
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.pyShown here, not run. Press Start lab to type it into your own lab’s terminal.
Write the alert rules, part 2
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.pyShown here, not run. Press Start lab to type it into your own lab’s terminal.
Write the alert rules, part 3
printf '%s\n' ' print("ALERT", found, "by", who(event), "answer", code)' ' alerts = alerts + 1' 'print(alerts, "alerts in", len(events), "records")' >> ~/ch/detect.pyShown here, not run. Press Start lab to type it into your own lab’s terminal.
Run the alert rules over the audit log
sudo python3 ~/ch/detect.py /var/lib/rancher/k3s/server/logs/audit.logShown 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
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:ciShown 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.
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