Audit logging and runtime security
The audit log records who asked the API server to do what; runtime detection records what processes did after admission. Write a policy that keeps the right events, investigate with them, and respond without destroying evidence.
Shows the lesson one block at a time. Arrow keys step, number keys jump to a scene, and Escape returns to the page where you were.
RBAC and admission decide what may happen. They keep no record of what did happen, and they see nothing after a pod starts. Two other systems fill those gaps. The API server’s audit logA chronological record, written by kube-apiserver, of the requests it handled: who sent each one, what it asked for and how it was answered. records every request in the order it arrived. Runtime detection watches what processes on the nodes do, which no API request reveals. Together they answer the two questions of an incident: who did this through the API, and what is running that should not be.
Reconcile, in 7 scenes
Audit stages
The API server can emit an event at four points in a request’s life:
- RequestReceived, as soon as the request arrives, before any handling.
- ResponseStarted, once response headers are sent and before the body. Only long-running requests such as
watchreach this stage. - ResponseComplete, when the response is finished. This is the event that carries the result.
- Panic, when the handler panicked.
The events of one request share an auditID. Most policies drop RequestReceived with omitStages, since ResponseComplete repeats everything in it and adds the outcome.
Audit levels
Each event is written at one of four levels:
| Level | Records |
|---|---|
None | Nothing |
Metadata | User, verb, resource, namespace, name, source IPs, timestamps and response code; no bodies |
Request | Metadata plus the request body |
RequestResponse | Metadata plus request and response bodies |
Request and RequestResponse add nothing for non-resource requests such as /healthz.
Policy rules
The API server audits nothing unless --audit-policy-file names a policy. The policy is a file on the control plane nodes, read by kube-apiserver at startup, not a ConfigMap; on kubeadm clusters you mount it into the API server’s static pod with a hostPath volume. A policy with no rules is invalid.
The API server compares each request with the rules in order, and the first rule that matches sets the level. A request no rule matches is not logged. Order is the whole design: specific rules first, broad rules last.
apiVersion: audit.k8s.io/v1
kind: Policy
omitStages: ["RequestReceived"]
rules:
- level: Metadata
resources:
- group: ""
resources: ["secrets", "configmaps"]
- group: "authentication.k8s.io"
resources: ["tokenreviews"]
- level: RequestResponse
verbs: ["create", "update", "patch", "delete", "deletecollection"]
resources:
- group: "rbac.authorization.k8s.io"
resources: ["roles", "rolebindings", "clusterroles", "clusterrolebindings"]
- level: Metadata
resources:
- group: ""
resources: ["pods/exec", "pods/attach", "pods/portforward"]
- level: None
userGroups: ["system:nodes"]
verbs: ["get", "update", "patch"]
resources:
- group: "coordination.k8s.io"
resources: ["leases"]
- group: ""
resources: ["nodes/status"]
- level: None
nonResourceURLs: ["/healthz*", "/livez*", "/readyz*"]
- level: None
verbs: ["get", "list", "watch"]
- level: Request
verbs: ["create", "update", "patch", "delete", "deletecollection"]
- level: Metadata
Read it top to bottom. Secrets, ConfigMaps and token reviews are logged at Metadata for every verb, including the list that dumps a namespace’s Secrets, because that rule comes before the rule that drops reads. RBAC writes are logged in full, so an investigation can see exactly which permissions a binding granted. The exec rule sets no verbs, so it covers every way a client connects, and at Metadata the command is still visible because it travels in requestURI, as in /api/v1/namespaces/shop/pods/web-7d9f/exec?command=sh&container=web. Node heartbeats and health checks, the bulk of the volume, are dropped. Remaining reads are dropped, remaining writes are logged with their bodies, and the final catch-all keeps metadata for anything else.
Two rule fields trip people up. users matches exact usernames with no wildcards; to cover every service account in kube-system, use userGroups: ["system:serviceaccounts:kube-system"]. And a resource entry for pods does not match subresources: pods/exec and pods/log need their own entries, or pods/*.
Backends
The policy decides what to record; a backend decides where it goes. Two are built in.
The log backend writes one JSON event per line to --audit-log-path, or to standard output when the path is -. --audit-log-maxage, --audit-log-maxbackup and --audit-log-maxsize rotate the files. Its default mode is blocking: the API server writes each event before responding.
The webhook backend POSTs batches of events to a service described by --audit-webhook-config-file, a file in kubeconfig format. Its default mode is batch, which buffers up to 10,000 events and sends a batch when 400 have collected or 30 seconds have passed. Events that overflow the buffer are dropped. blocking-strict, available for both backends, fails the request itself if the RequestReceived event cannot be recorded.
Watch apiserver_audit_event_total and apiserver_audit_error_total on the API server’s metrics endpoint; a rising error count means events are being lost.
Get events off the control plane quickly. An attacker with cluster-admin can often reach the nodes, and a log that lives only beside the API server can be edited or deleted along with the evidence. A node agent such as Fluent Bit or Vector tailing the log file, or a webhook to a collector, ships events to storage the cluster’s own credentials cannot modify. Retention is a compliance question as much as a technical one: PCI DSS requires 12 months of audit history with the most recent 3 months immediately available. HIPAA’s six-year retention rule applies to policy documentation, not specifically to audit logs.
Investigating
Every event answers the same questions through the same fields:
{
"kind": "Event",
"apiVersion": "audit.k8s.io/v1",
"level": "Metadata",
"auditID": "4d2f6c1e-8b7a-4e39-9a51-0c7f3e2b9d14",
"stage": "ResponseComplete",
"requestURI": "/apis/apps/v1/namespaces/shop/deployments/web",
"verb": "delete",
"user": {
"username": "system:serviceaccount:ci:deployer",
"groups": ["system:serviceaccounts", "system:serviceaccounts:ci", "system:authenticated"]
},
"sourceIPs": ["10.244.2.17"],
"userAgent": "kubectl/v1.37.0 (linux/amd64) kubernetes/5f2c1a0",
"objectRef": {"resource": "deployments", "namespace": "shop", "name": "web", "apiGroup": "apps", "apiVersion": "v1"},
"responseStatus": {"metadata": {}, "status": "Success", "code": 200},
"requestReceivedTimestamp": "2026-11-19T09:14:02.511204Z",
"stageTimestamp": "2026-11-19T09:14:02.538977Z",
"annotations": {
"authorization.k8s.io/decision": "allow",
"authorization.k8s.io/reason": "RBAC: allowed by RoleBinding \"ci-deployer/shop\" of ClusterRole \"edit\" to ServiceAccount \"deployer/ci\""
}
}
useris the authenticated identity, from the certificate or token. If the client impersonated someone with--as,impersonatedUserholds the identity it acted as anduserthe one that authenticated.verbandobjectRefsay what was done to which object. Alisthas anobjectRefwith noname, and a non-resource request such as/healthzhas none.sourceIPslistsX-Forwarded-Foraddresses first and the connection’s address last. Every address but the last can be set by the client.userAgentis whatever the client sent. It is a hint, never evidence.responseStatus.codesays how it ended. A 401 is a failed authentication, the signature of someone trying stolen or expired tokens. A 403 withauthorization.k8s.io/decision: forbidis RBAC refusing. A 403 or 422 after anallowdecision is admission refusing; a ValidatingAdmissionPolicy’s default reason,Invalid, returns 422.
To find who deleted web, filter the log:
jq -c 'select(.verb == "delete" and .objectRef.resource == "deployments"
and .objectRef.namespace == "shop" and .objectRef.name == "web")
| {at: .stageTimestamp, user: .user.username, ips: .sourceIPs, code: .responseStatus.code}' audit.log
For changes, swap the verb for update and patch. Where the policy logs writes at Request level, requestObject holds what the client sent; compare it with the object’s state before the change to see what moved. The authorization reason annotation names the binding that allowed the request, which is the binding to fix.
Runtime detection
Admission sees a pod spec once, at creation. The audit log sees API requests. Neither sees what happens inside a running container: a shell spawned by an exploited web server, a credential file read, an outbound connection to an unknown host. Those are syscalls on the node, and that is where FalcoA CNCF runtime security tool that evaluates rules against a stream of kernel syscalls, and other event sources, and raises alerts when one matches. watches.
Falco runs as a DaemonSet. On each node its modern eBPF probe, bundled in the Falco binary and portable across kernels through CO-RE, streams syscall events to the rules engine. The modern probe has been the default since Falco 0.38; the legacy eBPF probe was deprecated in 0.43 and removed in 0.44.0, and the kernel module remains the other option. This section describes Falco 0.45.2. The probe needs CAP_SYS_ADMIN, or CAP_BPF and CAP_PERFMON on kernels that support them, plus CAP_SYS_RESOURCE and CAP_SYS_PTRACE, which makes the Falco DaemonSet one of the most privileged workloads in the cluster.
A rule is a condition over event fields, an output and a priority:
- rule: Package manager in container
desc: A package manager ran inside a running container
condition: >
spawned_process and container and
proc.name in (apt, apt-get, apk, dnf, yum, microdnf)
output: >
Package manager in container | command=%proc.cmdline user=%user.name
image=%container.image.repository ns=%k8s.ns.name pod=%k8s.pod.name
priority: WARNING
spawned_process and container are macros from the default rules. Only rules marked stable ship in falco_rules.yaml; incubating and sandbox rules are separate files you opt into. Container and pod metadata, such as container.image.repository and k8s.pod.name, comes from the container plugin. The stable rule Terminal shell in container catches an interactive kubectl exec ... -- sh; it uses the container_entrypoint macro rather than matching a parent named runc, which breaks across runtimes.
Change a shipped rule in a local file with override, available from Falco 0.37.0:
- rule: Terminal shell in container
priority: CRITICAL
override:
priority: replace
append: true is deprecated and applies only to conditions, exceptions and lists. Rules have no rate field; deduplicate and throttle alerts downstream. Falco exports its own metrics, including falcosecurity_falco_rules_matches_total per rule.
Falco’s alerts go nowhere until you route them. Set json_output: true and point http_output at Falcosidekick on port 2801, which fans each event out to Slack, Loki, a SIEM or a queue; its outputs take the destination as a URL that includes the scheme, such as http://loki.monitoring:3100. Send audit events to the same place, so one search covers both.
Response
When an alert fires, the instinct is to delete the pod. Deleting it destroys the container’s filesystem, its memory and the process tree an investigator needs, and the ReplicaSet starts a fresh copy that hides what happened. Contain first, capture, then remove.
- Cordon the node, so replacements and any other pods the scheduler places land elsewhere. Cordoning evicts nothing.
- Isolate the pod. A NetworkPolicy that selects a quarantine label and allows nothing cuts its traffic in both directions, provided no other policy that selects the pod allows traffic: policies only add allowances, so a namespace-wide policy with an empty
podSelectorstill applies. Changing the pod’sapplabel at the same time takes it out of its Service’s endpoints and out of its ReplicaSet’s selector: the ReplicaSet releases it and starts a replacement, and the suspect pod keeps running, unowned, for inspection. - Capture state before anything is deleted: the pod’s YAML, its logs, its events, the image digest it runs, and the audit events for its ServiceAccount.
- Revoke what it could reach. Treat the ServiceAccount token and every Secret mounted in the pod as exposed. A stolen copy of the pod’s projected token keeps working until the token expires or the pod is deleted, so remove the role bindings that give the ServiceAccount its permissions while the pod is kept for inspection, and rotate every mounted Secret.
The quarantine policy has a selector and no rules:
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: quarantine
namespace: shop
spec:
podSelector:
matchLabels:
quarantine: "true"
policyTypes:
- Ingress
- Egress
kubectl create namespace shop
namespace/shop created
kubectl -n shop create deployment web --image=ghcr.io/kx-labs/web:1.0 --replicas=2
deployment.apps/web created
kubectl -n shop rollout status deployment/web
Waiting for deployment "web" rollout to finish: 0 of 2 updated replicas are available... deployment "web" successfully rolled out
kubectl get pods -n shop -o wide
NAME READY STATUS RESTARTS AGE IP NODE NOMINATED NODE READINESS GATES web-5bf6f8859d-2cv2c 1/1 Running 0 20s 10.244.2.2 kx-worker2 <none> <none> web-5bf6f8859d-tfgs5 1/1 Running 0 20s 10.244.3.2 kx-worker3 <none> <none>
kubectl cordon kx-worker3
node/kx-worker3 cordoned
kubectl apply -f quarantine.yaml
networkpolicy.networking.k8s.io/quarantine created
kubectl label pod web-5bf6f8859d-tfgs5 -n shop app=quarantined quarantine=true --overwrite
pod/web-5bf6f8859d-tfgs5 labeled
kubectl get pods -n shop -o wide -L app
NAME READY STATUS RESTARTS AGE IP NODE NOMINATED NODE READINESS GATES APP web-5bf6f8859d-2cv2c 1/1 Running 0 30s 10.244.2.2 kx-worker2 <none> <none> web web-5bf6f8859d-tfgs5 1/1 Running 0 30s 10.244.3.2 kx-worker3 <none> <none> quarantined web-5bf6f8859d-w8nfw 1/1 Running 0 10s 10.244.1.3 kx-worker <none> <none> web
kubectl get pod web-5bf6f8859d-tfgs5 -n shop -o jsonpath='{.status.containerStatuses[0].imageID}'
ghcr.io/kx-labs/web@sha256:36e47e5c22574d24dc11ac25f7a0f8f58dd945c0480323f446c98129b159d545
The replacement web-5bf6f8859d-w8nfw landed on kx-worker because kx-worker3 was cordoned first, so the Deployment is back to two pods behind its selector while the quarantined pod stays on its node with its process, files and memory intact. The image digest ties the incident to an exact build and its scan results.
Automation can do the first steps. Falco Talon reacts to Falco events with actions defined in its own rules file, - action: entries naming an actionner and - rule: entries that match Falco rules:
- action: Quarantine label
actionner: kubernetes:label
parameters:
level: pod
labels:
quarantine: "true"
- rule: Contain terminal shells
match:
rules:
- Terminal shell in container
actions:
- action: Quarantine label
Automated containment is only as good as its rules: a noisy rule that labels pods in production becomes an outage. Start with notification, then contain automatically for the few rules that never fire on legitimate work.
kubectl --context kind-kx create namespace shopkubectl --context kind-kx -n shop create deployment web --image=nginx:1.31 --replicas=2kubectl --context kind-kx -n shop rollout status deployment/webPOD=$(kubectl --context kind-kx -n shop get pods -l app=web -o jsonpath='{.items[0].metadata.name}'); NODE=$(kubectl --context kind-kx -n shop get pod $POD -o jsonpath='{.spec.nodeName}'); echo $POD on $NODEkubectl --context kind-kx cordon $NODEkubectl --context kind-kx apply -f quarantine.yamlkubectl --context kind-kx -n shop label pod $POD app=quarantined quarantine=true --overwritekubectl --context kind-kx -n shop get pods -o wide -L appkubectl --context kind-kx -n shop get pod $POD -o yamlkubectl --context kind-kx uncordon $NODEkubectl --context kind-kx delete namespace shop
For your own kind cluster kx: copy a command and paste it into your terminal. Run in the simulator runs the same command in this page's simulated cluster instead; nothing on this page touches your machine. Save the quarantine policy above as quarantine.yaml first, and run the commands in one shell so POD and NODE carry over. After the relabel, the Deployment starts a replacement on another node, and the quarantined pod keeps running with no ownerReferences in its YAML.
Actual state
Check your understanding
Your first answer to each check is the one that counts. After a miss you can answer again; passing every check reconciles the lesson.
Lesson not yet reconciled
Desired: 4 objectives, 0 metReconciled: 4 of 4 objectives met
- Write an audit policy that records what you need at the right level. (not yet met)
- Find who changed or deleted an object from audit events. (not yet met)
- Explain what runtime detection with Falco sees that admission cannot. (not yet met)
- Route audit and runtime events to where responders look. (not yet met)
Pass every check above to reconcile this lesson.
Every check has passed, so the desired state is met. First-try accuracy: 0 of 5. This lesson's review cards are in your queue.
Changed since the notes
This lesson draws on an earlier set of study notes. Where the documentation contradicts a claim in them, qualifies it or has moved past it, the claim is listed here with the corrected statement and the source it was checked against.
Show 23 corrections
The notes saidEvents are retained for up to 7 years (CloudTrail Lake)
CorrectedCloudTrail Lake event data stores offer one-year extendable retention (default 366 days, up to 3,653 days, about 10 years) or seven-year retention (2,557 days). Since May 31, 2026, CloudTrail Lake is closed to new customers; existing customers get only critical fixes, and AWS points to CloudWatch as the alternative.
The notes saidManagement events are logged by default in every trail
CorrectedTrails log management events by default, but no trail is needed to see them: Event history shows the last 90 days of management events per Region at no cost. A trail's first copy of management events is free; additional copies are charged.
The notes saidTrail and Lake feature set
CorrectedTrails can also log network activity events for VPC endpoints and deliver aggregated data events (5-minute summaries), both charged. CloudTrail Lake is closed to new customers since May 31, 2026.
The notes saidEKS log types are misdescribed (api vs audit)
CorrectedConfirmed. EKS control plane log types are: api (kube-apiserver component logs); audit (a record of every API request, who made it and what it changed, including the authorization decision); authenticator (IAM authentication); controllerManager; and scheduler.
Sourcedocs.aws.amazon.com/eks/latest/userguide/control-plane-logs.html
The notes saidCalls CloudTrail cost minimal without noting only the first copy of management events is free
CorrectedConfirmed. A trail's first copy of management events is free. Additional trails that deliver the same management events, and all data, network activity and Insights events, are charged.
The notes saidFalco driver.kind=ebpf is the modern driver
Correctedmodern_ebpf has been the default since 0.38. The legacy eBPF probe was deprecated in 0.43 and removed in 0.44.0. Falco is at 0.45.2.
The notes saidMetrics falco_events_total and falco_rules_matched_total
CorrectedThe native metric is falcosecurity_falco_rules_matches_total.
The notes saidChange rule priority with append: true
CorrectedUse override: {priority: replace} (0.37.0+). append is deprecated and applies only to condition, exceptions and lists.
The notes saidDefault rules detect many threats
CorrectedOnly stable rules ship in falco_rules.yaml. Container metadata comes from the container plugin.
The notes saidFalco Talon example syntax
CorrectedTalon uses '- action:' with 'actionner:' and '- rule:' with 'match:'. The note's example was not confirmed.
The notes saidk8saudit plugin webhook on EKS
CorrectedEKS does not expose an audit webhook. Use the k8saudit-eks plugin (CloudWatch) with the json plugin.
Sourcegithub.com/falcosecurity/plugins/tree/main/plugins/k8saudit-eks
The notes saidRule field rate: 1/60
CorrectedFalco rules have no rate field.
The notes saidFalcosidekick hostport without a scheme
Correctedhostport must be a URL that includes the scheme.
The notes saidDetect container entry with proc.pname=runc
CorrectedThat check is fragile. Use the container_entrypoint macro.
Sourcegithub.com/falcosecurity/rules/blob/main/rules/falco_rules.yaml
The notes saidCustom audit policy and --audit-* flags on EKS
CorrectedEKS uses a fixed audit policy. You can only enable or disable the audit log type.
Sourcedocs.aws.amazon.com/eks/latest/best-practices/auditing-and-logging.html
The notes saidExample userAgent kubectl/v1.28.0
CorrectedKubernetes is at 1.37.
Sourcekubernetes.io/releases
The notes saidRetention: PCI 1 year, HIPAA 6 years for audit logs
CorrectedPCI DSS requires 12 months, with 3 immediately available. HIPAA's six-year rule covers policy documentation, not audit logs specifically.
Sourceecfr.gov/current/title-45/subtitle-A/subchapter-C/part-164/subpart-C/section-164.316
The notes saidAudit policy users wildcard for kube-system service accounts
Correctedusers does not take wildcards. Use userGroups: ["system:serviceaccounts:kube-system"].
The notes saidlist/watch level None rule placed before the secrets rule
CorrectedThe first matching rule wins, so the secrets rule never fires for those verbs.
The notes saidAudit policy delivered as a ConfigMap
CorrectedThe audit policy is a control-plane file, not a ConfigMap.
The notes saidS3 Object Lock must be enabled at bucket creation
CorrectedYou can enable Object Lock on existing versioned buckets. GOVERNANCE mode can be bypassed; COMPLIANCE mode cannot.
Sourcedocs.aws.amazon.com/AmazonS3/latest/userguide/object-lock-configure.html
The notes saidFirehose subscription filter without role_arn
Correctedrole_arn is required for Firehose destinations.
Sourcedocs.aws.amazon.com/AmazonCloudWatch/latest/logs/SubscriptionFilters.html
The notes saidTokenReview events indicate failed authentication
CorrectedFailed logins appear as 401 responses.
Sourcedocs.aws.amazon.com/eks/latest/best-practices/auditing-and-logging.html
Every correction across the guide, by note and topic.
Sources
Checked against kubernetes.io and AWS documentation for Kubernetes 1.37 on .
- kubernetes.io/docs/tasks/debug/debug-cluster/audit
- kubernetes.io/docs/reference/config-api/apiserver-audit.v1
- kubernetes.io/docs/concepts/services-networking/network-policies
- kubernetes.io/docs/reference/kubectl/generated/kubectl_cordon
- falco.org/docs/concepts/event-sources/kernel
- falco.org/docs/concepts/rules/basic-elements
- falco.org/docs/concepts/rules/overriding
- falco.org/blog/falco-0-44-0
- github.com/falcosecurity/rules/blob/main/rules/falco_rules.yaml
- github.com/falcosecurity/falcosidekick
- falco-talon.github.io/docs/rules
- github.com/falcosecurity/plugins/tree/main/plugins/k8saudit-eks
- docs.aws.amazon.com/eks/latest/userguide/control-plane-logs.html
- docs.aws.amazon.com/eks/latest/best-practices/auditing-and-logging.html
- docs.aws.amazon.com/eks/latest/userguide/logging-using-cloudtrail.html
- docs.aws.amazon.com/eks/latest/userguide/access-entries.html
- docs.aws.amazon.com/awscloudtrail/latest/userguide/view-cloudtrail-events.html
- docs.aws.amazon.com/awscloudtrail/latest/userguide/cloudtrail-lake.html
- aws.amazon.com/cloudtrail/pricing
- docs.aws.amazon.com/AmazonCloudWatch/latest/logs/SubscriptionFilters.html
- docs.aws.amazon.com/AmazonS3/latest/userguide/object-lock.html
- docs.aws.amazon.com/guardduty/latest/ug/kubernetes-protection.html
- docs.aws.amazon.com/guardduty/latest/ug/runtime-monitoring.html
- docs.aws.amazon.com/guardduty/latest/ug/how-runtime-monitoring-works-eks.html
Audit logging and runtime security
↓ ↑ step, 1 to 7 scene, Esc leave