homek8s/docs/kube-apiserver-audit-logging.md
Lance Walters 723462f390 docs(audit): record the read/write split evidence and the pre-split purge
Live proof from the fresh audit.log after the apiserver reload (policy 9f07d333):
263 read verbs all Metadata with 0 responseObject/0 data, 76 write verbs all
RequestResponse with requestObject; plus the throwaway-probe create/patch/update/
delete ladder. Documents the purge: pre-split files (39 MB .gz + 15 MB moved live
file) deleted, oldest remaining file is the fresh audit.log.
2026-11-27 00:58:12 -05:00

13 KiB
Raw Blame History

kube-apiserver audit logging (control-plane, host-applied)

Status: live and verified 2026-11-27 on siriussec (kubeadm v1.36.4, single control plane). Owner: devops. Finding: F1 of the 2026-11-27 cluster network-security audit.

Why

The apiserver ran with no audit configuration at all. Every privileged-but-authorized API call — reading a Secret, pods/exec, RBAC writes, ServiceAccount token minting — completed with no record anywhere on the cluster. That is the gap that makes every other detector partially blind: there is nothing to alert on, nothing to reconstruct after an incident, and no way to answer "who read forgejo-pg-app last Tuesday".

What is installed

Piece Path / value
Audit policy /etc/kubernetes/audit/audit-policy.yaml (0600 root, in this repo)
Audit log /var/log/kubernetes/audit/audit.log (0600 root, JSON, one event per line)
Static pod patch /etc/kubernetes/manifests/kube-apiserver.yaml (kubeadm-owned — see Drift)
Staged volumes hostPath /etc/kubernetes/audit (ro) and hostPath /var/log/kubernetes/audit

Apiserver flags added (verified in the live container's /proc/<pid>/cmdline, not just the pod object):

--audit-policy-file=/etc/kubernetes/audit/audit-policy.yaml
--audit-log-path=/var/log/kubernetes/audit/audit.log
--audit-log-format=json
--audit-log-maxsize=100     # MiB per file, then rotate
--audit-log-maxbackup=48    # hard cap: 4.8 GiB raw before compression
--audit-log-maxage=7        # days
--audit-log-compress        # rotated files are gzipped

Rotation and retention are the apiserver's own (lumberjack) rotation, not logrotate. Do not add a logrotate rule for this path: the apiserver holds the file descriptor, so an external rotate produces a stale fd and silent loss.

Policy design

omitStages: [RequestReceived] — one record per request instead of two (the completion record is the one carrying responseStatus). omitManagedFields: true drops server-managed field blobs.

# Level Scope Rationale
1 None /healthz* /livez* /readyz* /version /openapi* /metrics, GET kubelet polls these every few seconds per node
2 None coordination.k8s.io/leases, events leader election / heartbeat / event spam
3 None watch on pods, nodes, services, endpoints, configmaps, PV/PVC, endpointslices, ingresses, netpols, CRDs, storageclasses a watch is recorded once at subscribe time and its payload never enters the record. secrets/RBAC/certs are deliberately not listed — a watch on those is itself worth a record
4 Metadata secrets get, list, watch reads: a corpus dump (list) or one live credential (get); objectRef is the whole signal, see below
5 Request rbac.authorization.k8s.io/*, certificates.k8s.io/* list, watch whole-object listings; the write paths stay at rule 6
6 RequestResponse secrets create/update/patch/delete/deletecollection, serviceaccounts/token, pods/exec, pods/attach, pods/portforward, rbac.authorization.k8s.io/*, certificates.k8s.io/*, verb impersonate the privileged-but-authorized calls: full request+response bodies. For secrets this is the write path only — the body is the tampering evidence
7 Request pods/proxy, nodes/proxy, nodes/log, nodes/metrics, nodes/spec, nodes/stats who proxied to which kubelet; the multi-MB response body is volume, not evidence
8 Metadata everything else who / what / when / from where / status code

Why secret reads are Metadata and secret writes are not

The first cut logged full bodies for every secret verb. During a flux reconcile storm (which happens after every apiserver restart and every full reconcile) that measured 22.8 GB/day, i.e. it would have rotated the entire retention window every couple of hours and buried the useful records:

verb events/189 s avg event burst rate
list secrets 16 1.9 MiB (every secret in the namespace) 14 GB/day
update secrets 90 170 KiB (flux sh.helm.release.v1.* + prometheus-operator tls-assets) 7 GB/day
get secrets 151 6.8 KiB 1 GB/day

A list body is a corpus dump scaled by how many secrets the cluster holds — it grows with the cluster, and the security signal ("who enumerated every secret") is fully captured by the metadata. That verb pair (list, watch) was therefore the first to go Metadata.

get was the second half of the same problem, and it was not a volume issue. Measured on the live log 2026-11-27: of 3,527 secret events, 1,606 were get and 2,574 carried .data in responseObject — the audit log was a second plaintext copy of every secret that had been read (kubernetes-admin, kustomize-controller, source-controller, sirius-growth:portal, …). That copy is root-only on the control-plane node, so reading it produces no audit event, which inverts the purpose of the log. A get is fully described by objectRef + user + sourceIPs + responseStatus.

Secret writes are the opposite case and keep full request/response bodies: an attacker filling a secret with their own SSH key or rewriting a dockerconfigjson is exactly the record you want, and a write body is evidence rather than a credential that was already in the cluster. Verbs are enumerated (create/update/patch/delete/deletecollection) so an unrecognised verb falls through to Metadata instead of silently acquiring a body.

Steady state with this split is 0.79 GB/day, ~420 events/min (secret traffic ~0.25 GB/day); the storm burst is bounded and absorbed by rotation. Retention numbers below account for it.

Sensitivity: the audit log still holds secret material

Secret reads are Metadata since 2026-11-27, so a get/list/watch record carries no data. Secret writes still do: at RequestResponse a create/update/patch record carries the object in requestObject (and the server's answer in responseObject). /var/log/kubernetes/audit/ therefore stays 0700 root with the log 0600 root, on the control-plane node only.

Files written before that date also held every secret that had been read; they were deleted as part of the change rather than left to age out (see "Purge" below). Treat any log shipper that touches this path as a secrets pipeline: no unauthenticated sink, no plaintext off-node copy, and its own encryption/retention story. The Loki/Alloy stack in infrastructure/logging/ does not mount this directory today (/var/log/pods + /var/log/journal only) — keep it that way unless the pipeline has an encryption story.

Purge: files written before the split (2026-11-27)

The bodies already on disk were upstream of the policy fix, so they were cut rather than left to age out. truncate -s 0 is wrong here — the apiserver keeps writing at its own offset and the file stays sparse — so the live file was moved aside while the apiserver still held its fd (no bytes lost), the container was restarted so the new process created a fresh audit.log instead of appending, and the superseded files were then deleted:

/var/log/kubernetes/audit before:  audit-2026-11-27T05-45-22.804.log.gz  39,423,475
                                   audit-pre-readfix-20261127T055416Z.log 15,037,570   (the moved live file)
                                   audit.log                               7,440,332   (fresh, post-change)
after:                             audit.log                               7,440,332   age ~1 min

Summary of what those files held, extracted before deletion (the only part worth keeping):

secret events 3,527 (get 1,606, patch 899, watch 721, update 196, delete 49, list 43, create 13)
with responseObject 2,753 | with responseObject.data 2,574
readers: kubernetes-admin, kustomize-controller, source-controller, kube-prometheus-stack-grafana,
         sirius-growth:portal, cert-manager, cnpg-manager, and per-node kubelet identities

Rotation later in the run only replaces files that were written under the split, so nothing with a read body can reappear. The throwaway-probe values from the write-path proof are the only secret values in the fresh log, and that secret no longer exists.

Verify it is live

# 1. flags are in the running container (authoritative: the live process, not the pod object)
CID=$(sudo crictl ps -q --name kube-apiserver | head -1)
PID=$(sudo crictl inspect "$CID" | python3 -c 'import json,sys;print(json.load(sys.stdin)["info"]["pid"])')
sudo tr '\0' '\n' < "/proc/$PID/cmdline" | grep -- --audit-
# (the mirror pod also carries them, but it can lag the container by a few seconds)
kubectl -n kube-system get pod kube-apiserver-siriussec \
  -o jsonpath='{.spec.containers[0].command}' | tr ',' '\n' | grep -- --audit-

# 2. the sink grows and the log is 0600
sudo ls -la /var/log/kubernetes/audit/

# 3. make a record and find it (name only — never print secret data)
kubectl -n forgejo get secret forgejo-pg-app -o name
sudo grep -c forgejo-pg-app /var/log/kubernetes/audit/audit.log

Live proof — read/write split, captured 2026-11-27T05:57Z (policy merged as 9f07d333, apiserver restarted to reload it, one fresh audit.log):

verb   level            secret                      code  body
get    Metadata         forgejo/forgejo-pg-app       200   none — no requestObject, no responseObject, no `data` substring
create RequestResponse  audit-probe/throwaway-probe  201   requestObject.data = {key}
patch  RequestResponse  audit-probe/throwaway-probe  200   requestObject = {"stringData":{"added":…}}  (the patch document)
update RequestResponse  audit-probe/throwaway-probe  200   requestObject.data = {added, key, replaced}
delete RequestResponse  audit-probe/throwaway-probe  200   DeleteOptions, no object body
get    Metadata         audit-probe/throwaway-probe  404   objectRef + responseStatus only (post-delete read still recorded)

Whole-file check over the first 339 secret events of the fresh log: 263 read verbs (get/list/watch), all Metadata, 0 with responseObject, 0 with data; 76 write verbs, all RequestResponse carrying requestObject. A merge patch's requestObject is the patch document itself, which is exactly the tampering evidence (an attacker's key appears verbatim in stringData).

Earlier proof, 2026-11-27T05:18Z (pre-split policy), kept for the pods/exec shape:

secret 404   kubernetes-admin get forgejo/pg-superuser      code 404   RequestResponse   (the audit card's literal command; the secret is named forgejo-pg-app)
secret get   kubernetes-admin get forgejo/forgejo-pg-app    code 200   request+response  (responseObject carries .data — PRE-SPLIT; now Metadata with no body)
rbac write   kubernetes-admin create forgejo/audit-trail-probe (dryRun=All) code 201     RequestResponse
pods/exec    kubernetes-admin get   forgejo/<pod>/exec     code 101   full command line  ResponseStarted + ResponseComplete

pods/exec produces two records per session (ResponseStarted, ResponseComplete) — the first is what makes an interactive session visible while it is still running. Write-path fidelity re-checked after the final policy revision: create secret (server dry-run) records requestObject.data.

Drift: a kubeadm upgrade silently resets this

/etc/kubernetes/manifests/kube-apiserver.yaml is generated by kubeadm, and Flux does not reconcile it. kubeadm init, kubeadm upgrade apply and a control-plane re-init regenerate the file from kubeadm's template and drop every --audit-* flag and both mounts. The failure is silent: the API keeps serving, /var/log/kubernetes/audit just stops growing.

Recover with the installer in this directory (also staged on the node at /root/audit-recovery/):

sudo infrastructure/controlplane/audit/install-audit.sh --check   # exit 1 = drift
sudo infrastructure/controlplane/audit/install-audit.sh           # policy + manifest patch

The installer is idempotent and was verified to reproduce the live manifest byte-for-byte; a second run is a no-op. Patching the manifest makes kubelet restart the apiserver (~40 s of API downtime on a single-control-plane cluster).

Other drift triggers: moving the API/advertise address (a rewrite of the same manifest), kubeadm reset + re-init.

Rollback

sudo cp -a /root/kube-apiserver.yaml.bak-<stamp> /root/.kube-apiserver.rollback
sudo mv /root/.kube-apiserver.rollback /etc/kubernetes/manifests/kube-apiserver.yaml

Dropping the flags stops the audit backend; the policy file and log directory can stay (inert). Never edit the manifest in place with a non-atomic write: kubelet parses the directory, so a torn file makes it remove the static pod and take the API down.

Disk headroom

siriussec had 102 GiB free of 214 GiB when this landed. Retention is bounded at 48 × 100 MiB = 4.8 GiB raw before compression, which at the measured 0.79 GB/day is ~6 days of history; realistic on-disk after gzip is several hundred MB. The ≥32 GiB floor is never at risk.

Not covered here

  • No shipping/alerting on audit events (no log store yet) — separate work.
  • No kubelet-level audit (--audit-* on kubelet), pods' auditPolicy, or OPA/admission policy.
  • Audit records for list secrets are metadata-only by design (see above).