K8S默认禁用审计
开启/关闭 k8s 审计日志
默认 Kubernetes 集群不会输出审计日志信息。通过以下配置,可以开启 Kubernetes 的审计日志功能。
- 准备审计日志的 Policy 文件
- 配置 API 服务器,开启审计日志
- 重启并验证
准备审计日志 Policy 文件
apiVersion: audit.k8s.io/v1
kind: Policy
rules:
- level: Metadata
omitStages:
- RequestReceived
- ResponseStarted
resources:
- group: ""
resources: ["pods", "services", "deployments"]
verbs: ["create", "update", "delete", "patch"]
将以上审计日志文件放到 /etc/kubernetes/audit-policy/
文件夹下,并取名为 apiserver-audit-policy.yaml
。
配置 API 服务器
⚠️只有一个控制平面节点禁止操作,此操作会引起api-server重启,但一旦挂掉,就很难恢复,也就是说,一个控制平面节点不能开启审计,除非集群初始化就指定⚠️
打开 API 服务器的配置文件 kube-apiserver.yaml,一般会在 /etc/kubernetes/manifests/
文件夹下,并添加以下配置信息:
这一步操作前请备份 kube-apiserver.yaml,并且备份的文件不能放在 /etc/kubernetes/manifests/
下,建议放在 /etc/kubernetes/tmp
。
-
在
spec.containers.command
下添加命令:--audit-log-maxage=30 --audit-log-maxbackup=1 --audit-log-maxsize=100 --audit-log-path=/var/log/audit/kube-apiserver-audit.log --audit-policy-file=/etc/kubernetes/audit-policy/apiserver-audit-policy.yaml
-
在
spec.containers.volumeMounts
下添加:- mountPath: /var/log/audit name: audit-logs - mountPath: /etc/kubernetes/audit-policy name: audit-policy
-
在
spec.volumes
下添加:- hostPath: path: /var/log/kubernetes/audit type: "" name: audit-logs - hostPath: path: /etc/kubernetes/audit-policy type: "" name: audit-policy
测试并验证
稍等一会,API 服务器会自动重启,执行以下命令查看/var/log/kubernetes/audit
目录下是否有审计日志生成,若有,则表示 k8s 审计日志成功开启。
ls /var/log/kubernetes/audit
审计日志样例
{"kind":"Event","apiVersion":"audit.k8s.io/v1","level":"Metadata","auditID":"0d3e03f1-2c7b-4c55-a457-8153ca3053c7","stage":"ResponseComplete","requestURI":"/api/v1/namespaces/kube-system/pods","verb":"create","user":{"username":"system:node:test3","groups":["system:nodes","system:authenticated"],"extra":{"authentication.kubernetes.io/credential-id":["X509SHA256=f624d02c9b496b091c035973fdebaa49445bc661126811e9e3e0d5254f6a61b5"]}},"sourceIPs":["10.0.2.18"],"userAgent":"kubelet/v1.32.0 (linux/amd64) kubernetes/70d3cc9","objectRef":{"resource":"pods","namespace":"kube-system","name":"etcd-test3","uid":"37d309b452af10f21285eec4372382b6","apiVersion":"v1"},"responseStatus":{"metadata":{},"status":"Failure","message":"pods \"etcd-test3\" already exists","reason":"AlreadyExists","details":{"name":"etcd-test3","kind":"pods"},"code":409},"requestReceivedTimestamp":"2025-01-15T03:04:00.960498Z","stageTimestamp":"2025-01-15T03:04:01.014779Z","annotations":{"authorization.k8s.io/decision":"allow","authorization.k8s.io/reason":"","pod-security.kubernetes.io/enforce-policy":"privileged:latest"}}
如果想关闭,去掉 spec.containers.command
中的相关命令即可。