homek8s/infrastructure/controlplane/audit/install-audit.sh

147 lines
5.4 KiB
Shell
Raw Normal View History

#!/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