审计

本指南介绍如何在 kind 集群上启用 Kubernetes API 审计

概述 🔗︎

Kubernetes 审计提供了一个安全相关的、按时间顺序排列的记录集,记录了集群中操作的顺序。审计需要一个文件来定义 审计策略,以及一个后端配置来存储记录的事件。审计支持两种类型的后端:日志(文件)和 Webhook。以下练习使用日志后端。

步骤

设置 🔗︎

创建一个 audit-policy.yaml 文件 🔗︎

审计策略 定义了 Kubernetes API 服务器输出的粒度级别。以下示例记录了“元数据”级别的所有请求。有关更多示例,请参阅 审计策略 文档。

cat <<EOF > audit-policy.yaml
apiVersion: audit.k8s.io/v1
kind: Policy
rules:
- level: Metadata
EOF

创建一个 kind-config.yaml 文件。 🔗︎

要启用审计日志记录,请使用 kind 的 配置文件 传递其他设置说明。kind 使用 kubeadm 来配置集群,配置文件能够传递 kubeadmConfigPatches 以进行进一步的自定义。

cat <<EOF > kind-config.yaml
kind: Cluster
apiVersion: kind.x-k8s.io/v1alpha4
nodes:
- role: control-plane
  kubeadmConfigPatches:
  - |
    kind: ClusterConfiguration
    apiServer:
        # enable auditing flags on the API server
        extraArgs:
          audit-log-path: /var/log/kubernetes/kube-apiserver-audit.log
          audit-policy-file: /etc/kubernetes/policies/audit-policy.yaml
        # mount new files / directories on the control plane
        extraVolumes:
          - name: audit-policies
            hostPath: /etc/kubernetes/policies
            mountPath: /etc/kubernetes/policies
            readOnly: true
            pathType: "DirectoryOrCreate"
          - name: "audit-logs"
            hostPath: "/var/log/kubernetes"
            mountPath: "/var/log/kubernetes"
            readOnly: false
            pathType: DirectoryOrCreate
  # mount the local file on the control plane
  extraMounts:
  - hostPath: ./audit-policy.yaml
    containerPath: /etc/kubernetes/policies/audit-policy.yaml
    readOnly: true
EOF

启动一个新集群 🔗︎

kind create cluster --config kind-config.yaml

查看审计日志 🔗︎

集群运行后,在控制平面的 /var/log/kubernetes/kube-apiserver-audit.log 中查看日志文件。

docker exec kind-control-plane cat /var/log/kubernetes/kube-apiserver-audit.log

故障排除 🔗︎

如果日志不存在,请确保以下几点。

本地审计策略文件是否已挂载到控制平面? 🔗︎

docker exec kind-control-plane ls /etc/kubernetes/policies

预期输出

audit-policy.yaml

API 服务器是否包含挂载和参数? 🔗︎

docker exec kind-control-plane cat /etc/kubernetes/manifests/kube-apiserver.yaml | grep audit

预期输出

    - --audit-log-path=/var/log/kubernetes/kube-apiserver-audit.log
    - --audit-policy-file=/etc/kubernetes/policies/audit-policy.yaml
      name: audit-logs
      name: audit-policies
    name: audit-logs
    name: audit-policies

如果控制平面需要进一步调试,请使用 docker exec -it kind-control-plane bash 启动与容器的交互式终端会话。