Audit logging and cluster hardening

Advanced · 13 min

Recording who did what through the API server with an audit policy, reading audit events, and the control-plane settings that harden a cluster.

Before thisRBACAdmission control and policy

Kubesimplify · 13 min

Audit logging and cluster hardening

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by KubesimplifyReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • Every API request can produce an audit event with the user, impersonated user, verb, object, response code and RBAC decision. It's the record you need after an incident, and nothing is logged unless the API server is given a policy.
  • An audit policy is an ordered list of rules, and the first match sets the level: None, Metadata, Request or RequestResponse. Order rules from most specific to least.
  • Log Secrets, ConfigMaps and token requests at Metadata only. At Request or RequestResponse their contents would be copied into the log.
  • Rules match resources literally. deployments doesn't match deployments/status, and with per-controller credentials, controller traffic arrives as kube-system ServiceAccounts, not as system:kube-controller-manager.
  • Secrets sit in etcd as plain protobuf unless the API server has an EncryptionConfiguration, ideally with a KMS v2 provider. Anyone with etcd or its backups reads them all.
  • Hardening is mostly defaults you have to change: no anonymous API access beyond health checks, NodeRestriction admission, kubelet webhook authn and authz, a private API endpoint, encrypted etcd with TLS, and a CIS benchmark run (kube-bench) to find the rest.

After the incident, someone asks who did it

A Secret was read that shouldn’t have been. A Deployment’s image changed at 03:12 and nobody admits to it. A ClusterRoleBinding appeared granting cluster-admin to a ServiceAccount. RBAC and admission try to prevent these things. When they fail, or when someone with legitimate access misuses it, the questions are: who, what, when, from where, and was it allowed?

Every one of those actions went through the API server, so it’s the one place that can answer. Audit logging makes the API server write an event for each request. Nothing is logged by default. You have to give it a policy and a backend.

What an audit event contains

The lab API server runs with --audit-log-path and --audit-policy-file. Here is a real event from it, trimmed, for a Secret list attempted by an admin impersonating jane:

{
  "level": "Metadata",
  "stage": "ResponseComplete",
  "requestURI": "/api/v1/namespaces/shop/secrets?limit=500",
  "verb": "list",
  "user": {"username": "lab-admin", "groups": ["system:masters", "system:authenticated"]},
  "impersonatedUser": {"username": "jane", "groups": ["dev", "system:authenticated"]},
  "sourceIPs": ["127.0.0.1"],
  "objectRef": {"resource": "secrets", "namespace": "shop", "apiVersion": "v1"},
  "responseStatus": {"status": "Failure", "reason": "Forbidden", "code": 403,
    "message": "secrets is forbidden: User \"jane\" cannot list resource \"secrets\" in API group \"\" in the namespace \"shop\""},
  "requestReceivedTimestamp": "2026-11-28T18:23:49.343672Z",
  "annotations": {"authorization.k8s.io/decision": "forbid", "authorization.k8s.io/reason": ""}
}

Both identities are recorded: the real caller and who they claimed to be. The RBAC decision appears as an annotation. Admission adds annotations too, such as the Pod Security level and the CEL policy failures from the admission lesson.

Each request can produce events at several stages: RequestReceived, ResponseStarted (long-running requests such as watches), ResponseComplete and Panic. Most policies omit RequestReceived, since ResponseComplete has everything plus the outcome.

The policy

Each rule sets a level for the requests it matches:

  • None: don’t log.
  • Metadata: user, verb, resource, response code. No bodies.
  • Request: plus the request body.
  • RequestResponse: plus the response body.

Rules are checked in order and the first match wins. I restarted the lab API server with this policy:

apiVersion: audit.k8s.io/v1
kind: Policy
omitStages: ["RequestReceived"]
rules:
- level: None
  nonResourceURLs: ["/healthz*", "/livez*", "/readyz*", "/version"]
- level: None
  resources: [{group: "coordination.k8s.io", resources: ["leases"]}]
- level: None
  users: ["system:kube-controller-manager", "system:kube-scheduler", "system:apiserver"]
- level: None
  verbs: ["watch"]
- level: Metadata
  resources: [{group: "", resources: ["secrets", "configmaps", "serviceaccounts/token"]}]
- level: RequestResponse
  verbs: ["create", "update", "patch", "delete"]
  resources: [{group: "apps", resources: ["deployments"]}, {group: "rbac.authorization.k8s.io"}]
- level: Metadata

Then I created a Secret holding s3cr3t-value, created a Deployment, tried to read the Secret as jane, and listed Pods. The 14 events that followed, summarised:

Metadata         create  secrets      db              lab-admin                                        201
RequestResponse  create  deployments  api             lab-admin                                        201  (request+response bodies)
Metadata         create  replicasets  api-59b45c4f66  system:serviceaccount:kube-system:deployment-controller  201
Metadata         update  deployments  api             system:serviceaccount:kube-system:deployment-controller  200
Metadata         create  pods                         system:serviceaccount:kube-system:replicaset-controller  201
Metadata         get     secrets      db              lab-admin (as jane)                              403  forbid
...

A search of the whole audit log for s3cr3t found nothing. The Secret was logged at Metadata. The Deployment event carried its full spec as the server decoded it, with defaults such as imagePullPolicy: IfNotPresent already filled in.

Two surprises are worth knowing:

  • Subresources match separately. The controller’s Deployment updates were logged at Metadata, not RequestResponse, because they were updates to deployments/status. The rule named deployments only. Use deployments/* or list subresources explicitly.
  • Controllers aren’t who you think. The rule silencing system:kube-controller-manager silenced nothing here, because the controller manager runs with --use-service-account-credentials and each controller calls as its own ServiceAccount. Most of the 14 events were controller chatter. Filter on system:serviceaccount:kube-system:* controllers if you want them gone.

Backends and volume

The log backend writes JSON lines to a file, rotated with --audit-log-maxage, --audit-log-maxbackup and --audit-log-maxsize. The webhook backend posts batches to a collector. Either way, ship events off the control plane promptly, since an attacker with cluster-admin can’t edit what’s already in your SIEM. Audit volume is large. Dropping watches, leases and health checks, and keeping bodies only for the writes you care about, is the difference between useful and unaffordable. Managed clusters expose audit logs through the provider’s logging service with a fixed policy.

Secrets in etcd

Audit logs protect against misuse through the API. They don’t help if someone reads etcd directly. The lab API server runs without an encryption config, so I read the Secret’s key straight from etcd over its HTTP gateway:

b'k8s\x00' 232
b':{}}B\x00\x12\x18\n\x08password\x12\x0cs3cr3t-value\x1a\x06Opaque'

The k8s\x00 prefix marks Kubernetes’ protobuf encoding. The password is right there, unencrypted. An EncryptionConfiguration (--encryption-provider-config) fixes that. Use a KMS v2 provider so the key-encryption key lives in a cloud KMS or HSM, not on the control-plane disk, then rewrite existing Secrets so they’re re-encrypted. The Secrets lesson covers what else Secrets don’t protect.

A hardening checklist

From the Kubernetes security checklist and the CIS Kubernetes Benchmark:

  • API server: private endpoint or an IP allowlist. Anonymous auth limited to health endpoints. NodeRestriction in --enable-admission-plugins. Audit logging on. Encryption at rest on.
  • etcd: TLS for clients and peers, reachable only from the API servers, backups encrypted.
  • Kubelet: --anonymous-auth=false, --authorization-mode=Webhook, read-only port off, certificate rotation on.
  • Identity: no shared admin certificates. Human access via OIDC or cloud IAM, system:masters credentials kept offline.
  • Workloads: Pod Security baseline everywhere and restricted where possible, network policies with a default deny, per-workload ServiceAccounts.
  • Verify: run kube-bench against the CIS benchmark on self-managed clusters, and keep the control plane within supported versions.

About the video

The embed is Kubesimplify’s “CKS Certification: Kubernetes Audit Logging Explained”, October 2024, 13 minutes. Its chapters cover audit stages, policy levels, backends, batching modes, writing a policy that logs Secrets and ConfigMaps at Metadata and Deployments at RequestResponse (close to the one above), applying it to the API server, and checking the log. It covers audit only, not the wider hardening list. I judged it from chapters and description only, since transcripts couldn’t be fetched. English was judged from its “English (US) original” audio track. Shay Berkovich’s fwd:cloudsec talk in deeper is about what goes wrong once you try to build detection on audit logs.

What was run: both audit policies were loaded by a local Kubernetes v1.37.3 API server whose nodes run no containers, and the events, the empty search for the secret value, the subresource and ServiceAccount surprises, and the plaintext Secret read from etcd 3.6’s gateway are real. kube-bench, KMS providers and kubelet settings weren’t run. They’re from the auditing, encryption-at-rest and security-checklist docs, checked 2026-11-29.

Where this fits

That closes security. Next is packaging what you deploy, starting with Helm charts in depth.

Check yourself

  1. 01An audit policy has a catch-all Metadata rule first and a RequestResponse rule for Deployments second. What gets logged for a Deployment update?

    Metadata only. Rules are evaluated in order and the first match wins, so the catch-all shadows every rule after it. Put specific rules first and the catch-all last.

  2. 02Why must Secrets never be logged at Request or RequestResponse level?

    Those levels copy the request and response bodies into the audit log, so every Secret's data, base64-encoded but not encrypted, would end up in log files and the log pipeline, readable by anyone with log access.

  3. 03During an incident you see a Secret read in the audit log by lab-admin with impersonatedUser jane. Who did it?

    The authenticated caller, lab-admin, acting as jane through impersonation. The event records both identities. Authorization was checked against jane, and the impersonation itself was authorized for lab-admin.

  4. 04Your etcd backups go to a shared bucket. Why does that make API server encryption at rest important?

    Without an EncryptionConfiguration, Secrets are stored in etcd as unencrypted protobuf, so the backup files contain every password and token in readable form. With encryption (ideally a KMS v2 provider holding the key outside the cluster), the backup holds ciphertext.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark