diff --git a/docs/kube-apiserver-audit-logging.md b/docs/kube-apiserver-audit-logging.md deleted file mode 100644 index cddc258..0000000 --- a/docs/kube-apiserver-audit-logging.md +++ /dev/null @@ -1,151 +0,0 @@ -# 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//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` **list, watch, update** | measured volume control, 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` get/create/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 | -| 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 `list`/`update` on secrets is Metadata and not RequestResponse - -First cut was `RequestResponse` for every secret verb. Measured on this cluster it cost -**22.8 GB/day** and would have rotated the whole retention window every ~2 hours: - -| verb | events/189 s | avg event | share | -|---|---|---|---| -| `list secrets` | 16 | **1.9 MiB** (every secret in the namespace) | 14 GB/day | -| `update secrets` | 90 | 170 KiB (flux `sh.helm.release.v1.*` blobs + prometheus-operator `tls-assets`) | 7 GB/day | -| `get secrets` | 151 | 6.8 KiB | 1 GB/day | - -Those two verbs are dominated by automation rewriting its own storage; the body is a copy of what -etcd already holds. They now record identity + namespace/name + status (Metadata), which is the -part that answers "who touched this secret". The single-object read path — the actual finding — -stays at `RequestResponse`. Total after the change: **~2.5 GB/day, ~1330 events/min**. - -## Sensitivity: the audit log is secret material - -At `RequestResponse`, a `get secret` audit event contains the secret's `data` in `responseObject`. -`/var/log/kubernetes/audit/` is therefore `0700 root` and the log `0600 root`, on the control-plane -node only. Treat any future log shipper as a **secrets pipeline**: no unauthenticated sink, no -plaintext off-node copy, and its own encryption/retention story. Nothing ships this log today. - -## Verify it is live - -```bash -# 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 captured 2026-11-27T05:18Z (final policy): - -``` -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) -rbac write kubernetes-admin create forgejo/audit-trail-probe (dryRun=All) code 201 RequestResponse -pods/exec kubernetes-admin get forgejo//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. - -## 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/`): - -```bash -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 - -```bash -sudo cp -a /root/kube-apiserver.yaml.bak- /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 (realistic on-disk after gzip is a few hundred MB, -since most records are small metadata JSON), so the ≥32 GiB floor is never at risk from audit. - -## 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). diff --git a/infrastructure/controlplane/audit/audit-policy.yaml b/infrastructure/controlplane/audit/audit-policy.yaml deleted file mode 100644 index aea8e77..0000000 --- a/infrastructure/controlplane/audit/audit-policy.yaml +++ /dev/null @@ -1,127 +0,0 @@ -apiVersion: audit.k8s.io/v1 -kind: Policy -# One record per request instead of two (RequestReceived + ResponseComplete). -# The completion record carries responseStatus and is the forensic one. -omitStages: - - RequestReceived -# server-managed noise, never evidence -omitManagedFields: true - -# Volume note (measured 2026-11-27 on this cluster): full bodies for EVERY secret -# verb cost 22.8 GB/day, because (a) flux helm-controller lists all secrets -# (1.9 MiB per list) and (b) it rewrites sh.helm.release.v1.* release blobs -# (~170 KiB each) every reconcile, plus prometheus-operator rewrites its -# tls-assets secrets. Rule 4 therefore keeps identity+object for those two -# verbs and reserves bodies for the single-object paths (rule 5) that actually -# answer "who read / who wrote this one secret". -rules: - # ---------------------------------------------------------------- 1. silence - # Liveness/version/discovery surface: polled by kubelet on every node every - # few seconds and carries no identity information. - - level: None - verbs: ["get"] - nonResourceURLs: - - /healthz - - /healthz/* - - /livez - - /livez/* - - /readyz - - /readyz/* - - /version - - /version/* - - /openapi/v2 - - /openapi/v3 - - /openapi/v3/* - - /metrics - - # Leader election / heartbeat / event spam. - - level: None - resources: - - group: coordination.k8s.io - resources: ["leases"] - - group: "" - resources: ["events"] - - group: events.k8s.io - resources: ["events"] - - # Informer watch subscriptions on high-volume, non-secret resources: recorded - # once at subscribe time and the payload never enters the record. secrets, - # RBAC and certificate objects are deliberately NOT here - a watch on those is - # itself worth a record (rules 4/6 keep it, minus the body). - - level: None - verbs: ["watch"] - resources: - - group: "" - resources: ["pods", "nodes", "services", "endpoints", "configmaps", - "persistentvolumes", "persistentvolumeclaims"] - - group: discovery.k8s.io - resources: ["endpointslices"] - - group: networking.k8s.io - resources: ["ingresses", "networkpolicies"] - - group: apiextensions.k8s.io - resources: ["customresourcedefinitions"] - - group: storage.k8s.io - resources: ["storageclasses"] - - # ------------------------------- 2. secrets: bulk enumeration / automation rewrite - # user + verb + namespace/name + responseStatus, no bodies. list secrets is - # 1.9 MiB of every secret in the namespace; update is the flux helm release - # churn. Losing the body here loses only a copy of what etcd already holds. - - level: Metadata - verbs: ["list", "watch", "update"] - resources: - - group: "" - resources: ["secrets"] - - # ------------------- 3. RBAC / certs enumeration: identity + request, no response - # list/watch of roles & bindings returns whole objects; the write paths are what - # matter and rule 6 keeps those at RequestResponse. - - level: Request - verbs: ["list", "watch"] - resources: - - group: rbac.authorization.k8s.io - resources: ["*"] - - group: certificates.k8s.io - resources: ["*"] - - # --------------------- 4. secrets: single-object read/write, full bodies - # THIS FILE IS SECRET MATERIAL from here on: get/read responses and - # create/patch requests carry live secret values. 0600 root, never shipped - # off-node over an unauthenticated path. - - level: RequestResponse - verbs: ["get", "create", "patch", "delete", "deletecollection"] - resources: - - group: "" - resources: ["secrets"] - - # -------------------------------- 5. everything privileged-but-authorized - - level: RequestResponse - resources: - - group: "" - resources: - - serviceaccounts/token - - pods/exec - - pods/attach - - pods/portforward - # every verb + subresource: create/update/patch/bind/escalate of a - # ClusterRoleBinding is a cluster takeover, not a config change - - group: rbac.authorization.k8s.io - resources: ["*"] - # CSR approval signs new client certs against the cluster CA - - group: certificates.k8s.io - resources: ["*"] - # acting as another identity - - level: RequestResponse - verbs: ["impersonate"] - - # Metadata + request body only: kubelet/API proxies can return multi-MB bodies - # (metrics, pprof, logs) and the response is the volume, not the evidence. - - level: Request - resources: - - group: "" - resources: ["pods/proxy", "nodes/proxy", "nodes/log", "nodes/metrics", - "nodes/spec", "nodes/stats"] - - # ------------------------------------------------------------------ 6. default - # who / what / when / from where / status code - no bodies. - - level: Metadata diff --git a/infrastructure/controlplane/audit/install-audit.sh b/infrastructure/controlplane/audit/install-audit.sh deleted file mode 100755 index 1f9926d..0000000 --- a/infrastructure/controlplane/audit/install-audit.sh +++ /dev/null @@ -1,147 +0,0 @@ -#!/usr/bin/env bash -# Enable kube-apiserver audit logging on a kubeadm control plane (host-side, NOT Flux). -# -# Why this script exists: /etc/kubernetes/manifests/kube-apiserver.yaml is owned by -# kubeadm, not by Flux. `kubeadm init`, `kubeadm upgrade apply` and a control-plane -# re-init all REGENERATE that file from kubeadm's own template, silently dropping every -# --audit-* flag and the two hostPath mounts added here. Audit logging then stops with -# no error anywhere: the API keeps serving, /var/log/kubernetes/audit just stops growing. -# Re-run this after any of those operations. -# -# sudo ./install-audit.sh # install policy + patch the static pod manifest -# sudo ./install-audit.sh --check # exit 0 only if policy + manifest are both applied -# sudo ./install-audit.sh --dry-run # show the diff, change nothing -# -# Idempotent: re-running on an already-patched manifest is a no-op. -# Patching the manifest makes kubelet restart the apiserver (~40 s of API downtime on a -# single-control-plane cluster). Back up the manifest first if you need a rollback: -# sudo cp -a /etc/kubernetes/manifests/kube-apiserver.yaml /root/kube-apiserver.yaml.bak-$(date -u +%Y%m%dT%H%M%SZ) -set -euo pipefail - -MANIFEST=${MANIFEST:-/etc/kubernetes/manifests/kube-apiserver.yaml} -AUDIT_DIR=${AUDIT_DIR:-/etc/kubernetes/audit} -LOG_DIR=${LOG_DIR:-/var/log/kubernetes/audit} -# staging dir for the atomic rename into the manifests dir; must be on the SAME fs as -# MANIFEST (both live on the root fs). NOT the manifests dir itself: kubelet would try -# to run a half-written second static pod. -STAGE_DIR=${STAGE_DIR:-/root} -POLICY_NAME=audit-policy.yaml -HERE=$(cd "$(dirname "$0")" && pwd) - -MODE=install -for a in "$@"; do - case "$a" in - --check) MODE=check ;; - --dry-run) MODE=dryrun ;; - -h|--help) sed -n '2,20p' "$0"; exit 0 ;; - *) echo "unknown argument: $a" >&2; exit 2 ;; - esac -done - -die() { echo "ERROR: $*" >&2; exit 1; } - -[ -f "$HERE/$POLICY_NAME" ] || die "policy not found next to script: $HERE/$POLICY_NAME" -[ -f "$MANIFEST" ] || die "manifest not found: $MANIFEST" - -patched=$(mktemp) -trap 'rm -f "$patched"' EXIT - -# Insert the audit flags, the two volumeMounts and the two hostPath volumes into a -# kubeadm-shaped manifest. Text insertion (not a YAML round-trip) keeps the diff to the -# lines we own, so a later kubeadm manifest stays byte-comparable. -MANIFEST="$MANIFEST" OUT="$patched" python3 - <<'PY' -import os, sys - -src, out = os.environ["MANIFEST"], os.environ["OUT"] -s = open(src).read() - -FLAGS = """ - --audit-log-compress - - --audit-log-format=json - - --audit-log-maxage=7 - - --audit-log-maxbackup=48 - - --audit-log-maxsize=100 - - --audit-log-path=/var/log/kubernetes/audit/audit.log - - --audit-policy-file=/etc/kubernetes/audit/audit-policy.yaml -""" -MOUNTS = """ - mountPath: /etc/kubernetes/audit - name: audit-policy - readOnly: true - - mountPath: /var/log/kubernetes/audit - name: audit-log -""" -VOLS = """ - hostPath: - path: /etc/kubernetes/audit - type: DirectoryOrCreate - name: audit-policy - - hostPath: - path: /var/log/kubernetes/audit - type: DirectoryOrCreate - name: audit-log -""" - -if "--audit-policy-file=" in s: - open(out, "w").write(s) - sys.exit(0) - -anchor = None -for cand in (" - --allow-privileged=true\n", " - kube-apiserver\n"): - if s.count(cand) == 1: - anchor = cand - break -if anchor is None: - sys.exit("cannot find a safe anchor for the audit flags") - -s = s.replace(anchor, anchor + FLAGS, 1) - -i = s.find(" volumeMounts:\n") -if i < 0: - sys.exit("no container volumeMounts block in manifest") -i += len(" volumeMounts:\n") -s = s[:i] + MOUNTS + s[i:] - -k = s.find("\n volumes:\n") -if k < 0: - sys.exit("no spec.volumes block in manifest") -k += len("\n volumes:\n") -s = s[:k] + VOLS + s[k:] - -open(out, "w").write(s) -PY - -manifest_ok=0 -cmp -s "$MANIFEST" "$patched" && manifest_ok=1 - -case "$MODE" in - check) - [ "$manifest_ok" = 1 ] || { echo "DRIFT: $MANIFEST has no audit flags/mounts (kubeadm upgrade? re-run ./install-audit.sh)"; exit 1; } - cmp -s "$HERE/$POLICY_NAME" "$AUDIT_DIR/$POLICY_NAME" || { echo "DRIFT: $AUDIT_DIR/$POLICY_NAME differs from $HERE/$POLICY_NAME"; exit 1; } - [ -d "$LOG_DIR" ] || { echo "DRIFT: $LOG_DIR missing"; exit 1; } - echo "OK: audit policy installed and manifest patched" - ;; - dryrun) - if [ "$manifest_ok" = 1 ]; then - echo "manifest already patched, nothing to do" - else - diff -u "$MANIFEST" "$patched" || true - fi - cmp -s "$HERE/$POLICY_NAME" "$AUDIT_DIR/$POLICY_NAME" || echo "policy would be (re)installed to $AUDIT_DIR/$POLICY_NAME" - ;; - install) - install -d -m 700 "$AUDIT_DIR" "$LOG_DIR" - install -m 600 "$HERE/$POLICY_NAME" "$AUDIT_DIR/.$POLICY_NAME.new" - if cmp -s "$AUDIT_DIR/.$POLICY_NAME.new" "$AUDIT_DIR/$POLICY_NAME"; then - rm -f "$AUDIT_DIR/.$POLICY_NAME.new" - echo "policy unchanged: $AUDIT_DIR/$POLICY_NAME" - else - mv "$AUDIT_DIR/.$POLICY_NAME.new" "$AUDIT_DIR/$POLICY_NAME" # same fs => atomic - echo "policy installed: $AUDIT_DIR/$POLICY_NAME (takes effect on the next apiserver start)" - fi - if [ "$manifest_ok" = 1 ]; then - echo "manifest already patched, nothing to do" - else - install -m 600 "$patched" "$STAGE_DIR/kube-apiserver.yaml.staged" - mv "$STAGE_DIR/kube-apiserver.yaml.staged" "$MANIFEST" # same fs => atomic rename, kubelet never sees a torn file - echo "manifest patched; kubelet restarts kube-apiserver within ~20 s" - fi - ;; -esac