콘텐츠로 이동

Kubernetes 감사 로그 수집

Kubernetes 감사(Audit)는 보안과 관련된 시계열 작업 기록을 제공합니다. 여기에는 시간, 출처, 작업 결과, 작업을 시작한 사용자, 작업 대상 리소스, 요청/응답의 상세 정보 등이 포함됩니다.

구성

사전 조건

감사 로그 정책 활성화

❗이미 활성화되어 있으면 무시하세요

Kubernetes 1.24를 예로 들어 감사 로그 정책을 활성화합니다

  • 마스터 노드 서버에 로그인

cd /etc/kubernetes

  • audit-policy.yml 추가
audit-policy.yml
# Copyright © 2022 sealos.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

apiVersion: audit.k8s.io/v1 # This is required.
kind: Policy
# Don't generate audit events for all requests in RequestReceived stage.
omitStages:
- "RequestReceived"
rules:
# The following requests were manually identified as high-volume and low-risk,
# so drop them.
- level: None
    users: [ "system:kube-proxy" ]
    verbs: [ "watch" ]
    resources:
    - group: "" # core
        resources: [ "endpoints", "services" ]
- level: None
    users: [ "system:unsecured" ]
    namespaces: [ "kube-system" ]
    verbs: [ "get" ]
    resources:
    - group: "" # core
        resources: [ "configmaps" ]
- level: None
    users: [ "kubelet" ] # legacy kubelet identity
    verbs: [ "get" ]
    resources:
    - group: "" # core
        resources: [ "nodes" ]
- level: None
    userGroups: [ "system:nodes" ]
    verbs: [ "get" ]
    resources:
    - group: "" # core
        resources: [ "nodes" ]
- level: None
    users:
    - system:kube-controller-manager
    - system:kube-scheduler
    - system:serviceaccount:kube-system:endpoint-controller
    verbs: [ "get", "update" ]
    namespaces: [ "kube-system" ]
    resources:
    - group: "" # core
        resources: [ "endpoints" ]
- level: None
    users: [ "system:apiserver" ]
    verbs: [ "get" ]
    resources:
    - group: "" # core
        resources: [ "namespaces" ]
# Don't log these read-only URLs.
- level: None
    nonResourceURLs:
    - /healthz*
    - /version
    - /swagger*
# Don't log events requests.
- level: None
    resources:
    - group: "" # core
        resources: [ "events" ]
# Secrets, ConfigMaps, and TokenReviews can contain sensitive & binary data,
# so only log at the Metadata level.
- level: Metadata
    resources:
    - group: "" # core
        resources: [ "secrets", "configmaps" ]
    - group: authentication.k8s.io
        resources: [ "tokenreviews" ]
# Get repsonses can be large; skip them.
- level: Request
    verbs: [ "get", "list", "watch" ]
    resources:
    - group: "" # core
    - group: "admissionregistration.k8s.io"
    - group: "apps"
    - group: "authentication.k8s.io"
    - group: "authorization.k8s.io"
    - group: "autoscaling"
    - group: "batch"
    - group: "certificates.k8s.io"
    - group: "extensions"
    - group: "networking.k8s.io"
    - group: "policy"
    - group: "rbac.authorization.k8s.io"
    - group: "settings.k8s.io"
    - group: "storage.k8s.io"
# Default level for known APIs
- level: RequestResponse
    resources:
    - group: "" # core
    - group: "admissionregistration.k8s.io"
    - group: "apps"
    - group: "authentication.k8s.io"
    - group: "authorization.k8s.io"
    - group: "autoscaling"
    - group: "batch"
    - group: "certificates.k8s.io"
    - group: "extensions"
    - group: "networking.k8s.io"
    - group: "policy"
    - group: "rbac.authorization.k8s.io"
    - group: "settings.k8s.io"
    - group: "storage.k8s.io"
    - group: "autoscaling.alibabacloud.com"
# Default level for all other requests.
- level: Metadata

💡해당 정책 정보는 실제 요구에 맞게 조정할 수 있습니다.

API Server 감사 로그 활성화

❗이미 활성화되어 있으면 무시하세요

디렉터리 /etc/kubernetes/manifests로 이동한 뒤 kube-apiserver.yaml 파일을 먼저 백업하고, 백업 파일은 /etc/kubernetes/manifests/ 아래에 두지 않은 상태에서 파일 내용을 조정합니다

  • spec.containers.command 아래에 명령을 추가합니다:
  - command:
    - kube-apiserver
    - --advertise-address=10.0.16.204
    - --allow-privileged=true
    - --audit-log-format=json
    - --audit-log-maxage=7
    - --audit-log-maxbackup=10
    - --audit-log-maxsize=100
    - --audit-log-path=/var/log/kubernetes/audit.log
    - --audit-policy-file=/etc/kubernetes/audit-policy.yml
  • spec.containers.volumeMounts 아래에 추가합니다:
    - mountPath: /etc/kubernetes
      name: audit
    - mountPath: /var/log/kubernetes
      name: audit-log
  • spec.volumes 아래에 추가합니다:
  - hostPath:
      path: /etc/kubernetes
      type: DirectoryOrCreate
    name: audit
  - hostPath:
      path: /var/log/kubernetes
      type: DirectoryOrCreate
    name: audit-log
  • 적용

API Server가 변경되면 자동으로 재시작되므로 몇 분만 기다리면 됩니다.

  • 검증

다음 명령을 실행해 audit.log 파일이 생성되었는지 확인합니다. 생성되었다면 이미 적용된 것입니다.

ls /var/log/kubernetes

K8S 감사 로그 수집

K8S 감사 로그는 해당 master 노드의 /var/log/kubernetes 디렉터리에 저장되며, 여기서는 annotation 방식으로 수집합니다

  • pod 생성: k8s-audit-log.yaml
apiVersion: v1
kind: Pod
metadata:
  name: kube-audit-log
  annotations:
        datakit/logs: |
          [
            {
              "disable": false,
              "type": "file",
              "path":"/var/log/kubernetes/audit.log",
              "source":  "k8s-audit",
              "tags" : {
                "atype": "kube-audit-log"
              }
            }
          ]

spec:
  containers:
  - name: kube-audit-log
    image: busybox
#    command: ["sleep", "1"]
    args:
    - /bin/sh
    - -c
    - >
      i=0;
      while true;
      do
        i=$((i+1));
        sleep 10;
      done
    volumeMounts:
    - mountPath: /var/log/kubernetes
      name: datakit-vol-opt
  volumes:
  - name: datakit-vol-opt
    hostPath: 
      path: /var/log/kubernetes
  nodeSelector:
     kubernetes.io/hostname: k8s-master
  tolerations:
  - key: "node-role.kubernetes.io/master"
    operator: "Exists"
    effect: "NoSchedule"
  - key: "node-role.kubernetes.io/control-plane"
    operator: "Exists"
    effect: "NoSchedule"

❗현재 pod는 master 노드에서만 실행할 수 있습니다.

  • 실행
kubectl apply -f k8s-audit-log.yaml 
  • 확인

몇 분 후면 Guance에서 해당 로그를 확인할 수 있습니다. json 형식이므로, Guance는 @+json 필드명 방식으로 검색을 지원하며, 예를 들어 @verb:update⁠처럼 검색할 수 있습니다.

감사 로그 필드 추출

감사 로그를 수집한 뒤에는 Guance의 pipeline 기능을 통해 감사 로그의 핵심 필드를 추출하여, 감사 로그에 대해 추가 데이터 분석을 수행할 수 있습니다

  • Guance에서 로그 - pipeline - 새로 만들기
  • 해당 로그 소스 k8s-audit 선택
  • Pipeline 이름: kubelet-audit
  • 파싱 규칙 정의
abc = load_json(_)

add_key(kind, abc["kind"])
add_key(level, abc["level"])
add_key(stage, abc["stage"])
add_key(verb, abc["verb"])
add_key(auditID, abc["auditID"])
add_key(username, abc["user"]["username"])
add_key(responseCode, abc["responseStatus"]["code"])
if abc["responseStatus"]["code"]==200 {
  add_key(status, "OK")
}else{
  add_key(status, "FAIL")
}
add_key(sourceIP_0,abc["sourceIPs"][0])

add_key(namespace,abc["objectRef"]["namespace"])
add_key(node,abc["objectRef"]["name"])
  • 스크립트 가져오기를 클릭해 테스트
  • 저장

문서 평가

이 페이지가 도움이 되었나요?