An attacker who has gained a foothold in a Kubernetes cluster does not stay dependent on the vulnerability that let them in: they leave behind an object that gives them access back, even if the vulnerability is fixed and the original Pod deleted. This is persistence. This lesson shows which Kubernetes objects serve for that, how to spot them with kubectl and the audit log, in which order to delete them without touching the legitimate application, and how to check that the access does not come back. It is aimed at readers who already know RBAC and CronJobs, and prepares the "Persistence" objective of the "Kubernetes Threat Model" domain of the KCSA certification.
What you will learn
- Define persistence and tell it apart from initial access and execution.
- Name the persistence mechanisms possible in a cluster.
- List the objects that can serve as persistence and read the events and the audit log to spot what is new.
- Record, then delete, the object that recreates the access, without removing the legitimate application.
- Check that the access does not come back, and name the controls that prevent or reveal persistence.
Prerequisites
- Have followed the lesson Attack scenarios in a cluster, which describes the first three stages of an attack: execution, privilege escalation, network.
- Know how to create a CronJob and read a DaemonSet, the two objects that start Pods without anyone restarting them by hand.
- Know RBAC bindings: a
ClusterRoleBindinggives a role to a service account across the whole cluster.
What is persistence in a cluster?
Persistence is the attacker's ability to stay in the cluster after losing their initial access. It comes after two other stages that need to be told apart. Initial access is the vulnerability or the stolen token that let them in. Execution is the code they run once inside. Persistence is what they leave in place so that this code comes back by itself.
In a cluster, this persistence object has an advantage for the attacker: Kubernetes recreates what you ask it to maintain. A deleted Pod is restarted by its Deployment, a Job is created again by its CronJob. A malicious workload declared in one of these objects benefits from the same machinery as the legitimate application. The page Phase 5 - Installation (in French) describes the general principle of the kill chain (the sequence of stages of an intrusion): hijacking a legitimate mechanism so that it restarts the implant in place of the attacker.
Which objects serve as persistence in Kubernetes?
Several mechanisms come up again and again. The table says for each one how it works and where to look for it. Read it as a checklist: each row is a command to run on a cluster you suspect.
| Mechanism | What it does | Where to look |
|---|---|---|
| CronJob | Starts a Pod at a fixed interval, at most once a minute | kubectl get cronjobs -A |
| DaemonSet | Keeps a Pod on every node, including nodes added later | kubectl get daemonsets -A |
| Added ServiceAccount and RBAC binding | Gives the attacker an account and rights that look legitimate | kubectl get serviceaccounts -A, kubectl get clusterrolebindings and kubectl get rolebindings -A (bindings limited to one namespace, kube-system included) |
| Client certificate signed through a CSR | Stays valid until it expires and cannot be revoked | kubectl get csr (an approved request is deleted one hour after its last state change, so the list can be empty) |
| Long-lived service account token | A Secret of type kubernetes.io/service-account-token stays valid as long as it exists | kubectl get secrets -A --field-selector type=kubernetes.io/service-account-token |
| Malicious admission webhook | Hooks into the creation of every object, for example to add a container to every Pod | kubectl get validatingwebhookconfigurations,mutatingwebhookconfigurations |
| Static Pod or host mount | A manifest dropped in the node's static Pod directory is restarted by the kubelet, without going through the API | On the node, /etc/kubernetes/manifests with kubeadm |
A static Pod is hard to see from the API: the kubelet starts it from a file on the node, and the API only keeps a read-only copy. To plant one, the attacker already needs access to the node: a Pod that mounts hostPath with write access is enough. This is why the lesson on the Pod Security Standards refuses this mount at the Baseline level.
A booby-trapped image is a case apart: the attacker pushes a modified version of an image used by a Deployment, and every recreated Pod carries the backdoor. It leaves no suspicious object in the cluster. Only comparing the image digest with the one your build chain produced reveals it, which is what the lesson Supply Chain Security teaches.
Why is deleting the account or the Pod not enough?
Deleting the object you can see, the account or the Pod, leaves in place the one that recreates it. The trap comes from two linked objects: a service account and its binding that give a strong right, and a scheduled workload, CronJob or DaemonSet, that recreates them if you delete them.
The diagram shows the loop. Look at the two dotted arrows: deleting the account and its binding alone only has an effect until the next run of the scheduled workload, whereas deleting the scheduled workload first breaks the loop.
In the course labs (Kubernetes 1.37.2), a service account and its binding deleted alone come back with the right to list the cluster Secrets. The workload of the end-of-module challenge (next lesson) recreates the access within seconds, and the CronJob of this lesson's guided lab recreates it every minute. These rhythms depend on the workload that recreates, not on Kubernetes: an attacker picks their own, from a few seconds to several hours. This is why the check, further down, waits longer than the longest delay.
How do you spot what was added?
To spot persistence, look for what did not exist yesterday. Compare the current state of the cluster with a reference you know: the content of the Git repository that deploys the cluster, or the list taken on a day when everything was healthy. Without a reference, one more object among hundreds goes unnoticed.
Start with the workloads that restart by themselves, in all namespaces:
kubectl get cronjobs,daemonsets -ALook at the AGE column and the name of each object. A recent object, in a namespace where nobody deployed anything, with a name that imitates a system component, deserves a closer look. Then move on to the rights:
kubectl get serviceaccounts -A --sort-by=.metadata.creationTimestampkubectl get clusterrolebindings -o wideThe first sort puts the most recent accounts at the bottom of the list. In the second, the SERVICEACCOUNTS column says to which service accounts each binding gives its role. A binding to cluster-admin, or to a role that reads Secrets, given to an unknown account, is a strong signal.
To know what an account can really do, ask the cluster rather than reading the roles by hand. The next command assumes you have the right to impersonate an identity, which an administrator has. Replace app-prod with the namespace of the account and compte-suspect with its name:
kubectl auth can-i list secrets --all-namespaces \ --as=system:serviceaccount:app-prod:compte-suspectThe answer is yes or no. A yes on an account that no application uses points to an access that someone created in order to use it. Finish with the entry points of the cluster, which the first two commands do not see:
kubectl get validatingwebhookconfigurations,mutatingwebhookconfigurationskubectl get secrets -A --field-selector type=kubernetes.io/service-account-tokenkubectl get events -A --sort-by=.metadata.creationTimestampThe webhooks installed by your tools (cert-manager, a policy engine) are expected; any other one needs a look. A Secret of type kubernetes.io/service-account-token is no longer created automatically: everything the command lists was requested by hand, or inherited from an old cluster, and every token must have a known owner. Events show the Jobs and Pods created recently, but they only last about an hour by default: for an older investigation, the audit log takes over, provided the cluster has enabled it.
How do you date and attribute a creation with the audit log?
The audit log says who created the suspicious object and when. Each line of the file is a JSON event: user.username says who acted, verb says what, objectRef says on which resource. You only need these three fields here.
This log is not active by default, neither with kubeadm nor with kind: it only exists if the API server runs with the --audit-policy-file and --audit-log-path options. The lesson Audit logs, in the "Harden the cluster" module, shows how to write the policy that produces it. On a managed cluster, it is read at the provider. Otherwise, it sits at the path given by --audit-log-path, on the control plane node with kubeadm. The next command requires jq to be installed. For persistence, filter the creations of sensitive objects:
cat audit.log | jq 'select(.verb=="create" and (.objectRef.resource=="cronjobs" or .objectRef.resource=="daemonsets" or .objectRef.resource=="clusterrolebindings")) | {time: .stageTimestamp, user: .user.username, resource: .objectRef.resource, name: .objectRef.name}'Look at user.username. If the creations come from a human user, for example kubernetes-admin, the administrator account that kubeadm creates, a person made them with that certificate. If they come from a service account (system:serviceaccount:namespace:name), a workload in the cluster is creating them: you have found the compromised account, and you can see at what rhythm it recreates. That rhythm confirms the loop: if the same binding is created every minute, a CronJob recreates it.
How do you remove persistence without breaking the application?
To remove persistence, delete first the object that recreates, then what it was recreating, after recording the state. The order matters: the reverse leaves the loop running. Here is the procedure, with an example where a nettoyage-cache workload in the app-prod namespace recreates an agent-sauvegarde account and its binding.
-
Record the object before any deletion. Export it from the live cluster, not from a file you wrote: it is the trace of what the attacker left, with its
creationTimestampandserviceAccountNamefields.Terminal window kubectl get cronjob nettoyage-cache -n app-prod -o yaml > constat-persistance.yaml -
Trace Pods back to their owner if you start from a suspicious Pod. The
ownerReferencesfield of the Pod names the Job or the ReplicaSet that created it, and the Job in turn names the CronJob.Terminal window kubectl get pod <pod> -n app-prod \-o jsonpath='{.metadata.ownerReferences[0].kind}/{.metadata.ownerReferences[0].name}{"\n"}' -
Delete the scheduled workload. Its Jobs and Pods go with it, because they depend on it.
Terminal window kubectl delete cronjob nettoyage-cache -n app-prod -
Then delete the service account and the binding it was recreating. Without the workload, they no longer come back.
Terminal window kubectl delete clusterrolebinding agent-sauvegardekubectl delete serviceaccount agent-sauvegarde -n app-prod -
Consider as compromised everything the account could read. A right to list Secrets is a right to copy them: change the passwords and keys these Secrets contain, because deleting the account no longer protects them.
To avoid removing the legitimate application, delete only what the recording identified, by its name, and never run a mass deletion on a namespace. The application's CronJobs, accounts and bindings have their own names: compare them with your reference before each delete. The same procedure applies to a DaemonSet or a webhook, replacing the object name in step 3.
How do you check that the access does not come back?
To check the removal, wait longer than the longest recreation delay, then ask the cluster again. A CronJob scheduled every minute recreates the access within a minute at most: two minutes of waiting are then enough. If the deleted workload had a slower rhythm, wait longer still. Also delete the original Pod, the one where the attacker had run their code, to be sure nothing relies on it:
kubectl delete pod <original-pod> -n app-prodAfter the two minutes of waiting, ask the cluster again what exists and what the account can still do:
kubectl get cronjobs,daemonsets -Akubectl get serviceaccount agent-sauvegarde -n app-prodkubectl auth can-i list secrets --all-namespaces \ --as=system:serviceaccount:app-prod:agent-sauvegardeThe expected result: no more suspicious workload, NotFound for the account, and no for the right to list Secrets. Finally check that the legitimate application is intact with kubectl get deployments -n app-prod: all its replicas must be available. If the account comes back, another workload recreates it: resume the search, on DaemonSets and webhooks in particular.
Which controls prevent or reveal persistence?
Four controls of the course act on persistence, each at a different place. The table says for each one whether it prevents or detects.
| Control | Role | What it does against persistence | Lesson |
|---|---|---|---|
| Minimal RBAC | Prevents | Without the right to create CronJobs, DaemonSets, bindings or webhooks, the attacker cannot settle in | RBAC |
| Admission control | Prevents | A policy refuses hostPath, or the binding of an account to cluster-admin | Admission controllers |
| Audit log | Detects | Once enabled, keeps the trace of who created what, and makes it possible to date the persistence | Audit logs |
| Falco | Detects | Alerts on an opened shell, and on sensitive audit events if you plug it into the log | Falco |
Minimal RBAC acts before the installation: it removes the attacker's ability to anchor themselves. Kubernetes adds a protection: an account cannot create a binding that gives more rights than it has, unless it holds the bind verb (binding a role it does not own itself) or escalate (creating or modifying a role with more rights than it has). Do not give these verbs to anyone for convenience. The controls that detect remove nothing: a Falco alert or an audit line does not replace deleting the object.
Which mistakes should you avoid?
A persistence cleanup rarely fails for lack of commands. It fails because you remove what you can see instead of what recreates it, or because you delete before keeping a trace. Three mistakes come up again and again, and each has a consequence you can observe: access reappears, the investigation becomes impossible, or the attacker keeps secrets already copied.
- Deleting the visible account or Pod first. The scheduled workload recreates it, and you wrongly believe the cluster is clean.
- Deleting without recording. Without the export of the live object, you lose what lets you understand the attack, date the compromise and look for twin objects.
- Forgetting the Secrets already read. Removing the access does not undo what the attacker copied, and only rotating the secrets does.
Put it into practice
This guided lab follows the demonstration of this lesson. A namespace contains a scheduled workload that silently recreates an attacker's access, next to a legitimate billing application. You list what is scheduled, who holds which rights and what changed recently, you record the guilty object before deleting it, then you remove the access. The validation covers the state of the cluster: the object is recorded, the scheduled workload and the attacker's identities are gone, the access does not come back after the original Pod is deleted, and the legitimate application stays intact.
Key takeaways
- Persistence is what the attacker leaves to keep access once the vulnerability is fixed and the original Pod deleted; it differs from initial access and execution.
- The objects that serve as persistence are CronJobs, DaemonSets, service accounts and their bindings, long-lived tokens, admission webhooks and static Pods.
- Deleting the visible account or Pod is not enough: the scheduled workload that recreates it brings it back on its next run, within seconds or at the next minute in the lesson's labs.
- You spot what is new by comparing the cluster with a reference, with
kubectl get cronjobs,daemonsets -A,kubectl get clusterrolebindings -o wideandkubectl auth can-i, then you date the creation in the audit log, if it is enabled. - The removal order is fixed: record the object, delete the workload that recreates, then the account and the binding, then change the secrets the account could read.
- You check by waiting longer than the recreation delay, deleting the original Pod and asking the cluster for the right again.
- Minimal RBAC and admission prevent; the audit log and Falco detect, without removing anything.
Knowledge check
Check that you have mastered the essentials of this guide. The questions only cover what has just been explained here.
Knowledge check
Check what you have learned with this interactive quiz
How it works
- The timer starts when you click Start
- Multiple choice, true/false and short answer questions
- You can move between questions
- Detailed results are shown at the end
Starts the quiz and the timer
Review
(0/0)Result saved on this device. It will be sent to your account at the next sync. Sync now
Score by domain
A domain groups several guides and gets several questions, so its score is more reliable than a per-topic score, which often rests on a single question.
Summary
Strengths
No topic passed at 80% on at least two questions yet.
Weak areas
No topic below the pass mark.
Recommended next
Hints before you try again?
Continue the course: Denial of service: exhausting a cluster
A new full quiz with random questions
Work again only on the questions you missed