Kubernetes 하드닝

Tip

AWS 해킹 배우기 및 연습하기:HackTricks Training AWS Red Team Expert (ARTE)
GCP 해킹 배우기 및 연습하기: HackTricks Training GCP Red Team Expert (GRTE) Azure 해킹 배우기 및 연습하기: HackTricks Training Azure Red Team Expert (AzRTE)

HackTricks 지원하기

클러스터 분석 도구

Steampipe - Kubernetes Compliance

이는 Kubernetes 클러스터에 대한 여러 컴플라이언스 검사를 제공합니다. CIS, National Security Agency (NSA) 및 Cybersecurity and Infrastructure Security Agency (CISA)의 Kubernetes 하드닝 관련 사이버보안 기술 보고서를 지원합니다.

# Install Steampipe
brew install turbot/tap/powerpipe
brew install turbot/tap/steampipe
steampipe plugin install kubernetes

# Start the service
steampipe service start

# Install the module
mkdir dashboards
cd dashboards
powerpipe mod init
powerpipe mod install github.com/turbot/steampipe-mod-kubernetes-compliance

# Run the module
powerpipe server

Kubescape

Kubescape는 K8s 오픈소스 도구로, 멀티클라우드 환경에서 K8s를 한눈에 볼 수 있는 단일 창(single pane of glass)을 제공하며 리스크 분석, 보안 컴플라이언스, RBAC 시각화 도구 및 이미지 취약점 스캐닝을 포함합니다. Kubescape는 K8s 클러스터, YAML 파일, 그리고 HELM 차트를 스캔하여 여러 프레임워크(예: NSA-CISA , MITRE ATT&CK®)에 따른 잘못된 구성(misconfigurations), 소프트웨어 취약점 및 CI/CD 파이프라인 초기 단계에서의 RBAC (role-based-access-control) 위반을 탐지하고 즉시 리스크 점수를 계산하며 시간에 따른 리스크 추세를 보여줍니다.

curl -s https://raw.githubusercontent.com/kubescape/kubescape/master/install.sh | /bin/bash
kubescape scan --verbose

Popeye

Popeye는 라이브 Kubernetes 클러스터를 스캔하고 배포된 리소스 및 구성에서 발생할 수 있는 문제를 보고하는 유틸리티입니다. 이 도구는 디스크에 있는 것이 아니라 실제로 배포된 내용을 기준으로 클러스터를 정리합니다. 클러스터를 스캔함으로써 잘못된 구성들을 감지하고 모범 사례가 적용되었는지 확인하는 데 도움을 주어 향후 문제를 예방합니다. 이는 현장에서 Kubernetes 클러스터를 운영할 때 겪게 되는 인지적 과부하를 줄이는 것을 목표로 합니다. 또한 클러스터가 metric-server를 사용 중이라면 잠재적인 리소스 과/부족 할당을 보고하고 클러스터 용량이 부족해질 경우 경고하려 시도합니다.

Kube-bench

The tool kube-bench is a tool that checks whether Kubernetes is deployed securely by running the checks documented in the CIS Kubernetes Benchmark.
You can choose to:

  • run kube-bench from inside a container (sharing PID namespace with the host)
  • run a container that installs kube-bench on the host, and then run kube-bench directly on the host
  • install the latest binaries from the Releases page,
  • compile it from source.

Kubeaudit

[DEPRECATED] The tool kubeaudit is a command line tool and a Go package to audit Kubernetes clusters for various different security concerns.

Kubeaudit can detect if it is running within a container in a cluster. If so, it will try to audit all Kubernetes resources in that cluster:

kubeaudit all

이 도구는 autofix 인수를 통해 감지된 문제를 자동으로 수정할 수 있습니다.

Kube-hunter

[DEPRECATED] 이 도구인 kube-hunter는 Kubernetes 클러스터의 보안 취약점을 찾아냅니다. 이 도구는 Kubernetes 환경의 보안 문제에 대한 인식과 가시성을 높이기 위해 개발되었습니다.

kube-hunter --remote some.node.com

Trivy

Trivy 는 보안 문제를 찾는 스캐너를 제공하며, 다음과 같은 대상에서 문제를 탐지할 수 있습니다:

  • 컨테이너 이미지
  • 파일시스템
  • Git Repository (원격)
  • 가상 머신 이미지
  • Kubernetes

Kubei

[유지 관리되지 않는 것으로 보임]

Kubei 는 취약점 스캐닝 및 CIS Docker 벤치마크 도구로, 사용자가 Kubernetes 클러스터의 정확하고 즉각적인 리스크 평가를 받을 수 있게 해줍니다. Kubei는 애플리케이션 pod와 시스템 pod의 이미지 등 Kubernetes 클러스터에서 사용되는 모든 이미지를 스캔합니다.

KubiScan

KubiScan 은 Kubernetes의 역할 기반 접근 제어(Role-based access control, RBAC) 권한 모델에서 위험한 권한을 검색하는 도구입니다.

Managed Kubernetes Auditing Toolkit

Mkat 은 다른 도구들과 비교해 더 높은 위험도 검사를 수행하도록 만들어진 도구입니다. 주로 다음의 3가지 모드를 제공합니다:

  • find-role-relationships: 어떤 AWS roles가 어떤 pods에서 실행되고 있는지 찾습니다.
  • find-secrets: Pods, ConfigMaps, Secrets 등과 같은 K8s 리소스에서 secrets를 식별하려고 시도합니다.
  • test-imds-access: pod를 실행하고 metadata v1 및 v2에 접근을 시도합니다. 경고: 이 모드는 클러스터에서 pod를 실행하므로 매우 주의하세요 — 원치 않을 수 있습니다!

Audit IaC Code

KICS

KICS보안 취약점, 규정 준수 문제 및 인프라 구성 오류를 다음의 Infrastructure as Code 솔루션들에서 찾아냅니다: Terraform, Kubernetes, Docker, AWS CloudFormation, Ansible, Helm, Microsoft ARM, 및 OpenAPI 3.0 명세

Checkov

Checkov 은 infrastructure-as-code를 위한 정적 코드 분석 도구입니다.

이 도구는 Terraform, Terraform plan, Cloudformation, AWS SAM, Kubernetes, Dockerfile, Serverless 또는 ARM Templates를 사용해 프로비저닝된 클라우드 인프라를 스캔하고 그래프 기반 스캐닝을 사용하여 보안 및 규정 준수 구성 오류를 탐지합니다.

Kube-score

kube-score 는 Kubernetes 객체 정의에 대한 정적 코드 분석을 수행하는 도구입니다.

설치:

배포형명령 / 링크
macOS, Linux, Windows용 미리 빌드된 바이너리GitHub releases
Dockerdocker pull zegl/kube-score (Docker Hub)
Homebrew (macOS 및 Linux)brew install kube-score
Krew (macOS 및 Linux)kubectl krew install score

Tools to analyze YAML files & Helm Charts

Kube-linter

# Install Kube-linter
brew install kube-linter

# Run Kube-linter
## lint ./path/to/yaml/or/chart

Checkov

# Install Checkov
pip install checkov

# Run Checkov
checkov -d ./path/to/yaml/or/chart

kube‑score

# Install kube-score
brew install kube-score

# Run kube-score
kube-score score ./path/to/yaml
# or
helm template chart /path/to/chart | kube-score score -
# or if the chart needs some values
helm template chart /path/to/chart \
--set 'config.urls[0]=https://dummy.backend.internal' \
| kube-score score -

Kubesec

# Install Kubesec
## Download from https://github.com/controlplaneio/kubesec/releases

# Run Kubesec in a yaml
kubesec scan ./path/to/yaml
# or
helm template chart /path/to/chart | kubesec scan -
# or if the chart needs some values
helm template chart /path/to/chart \
--set 'config.urls[0]=https://dummy.backend.internal' \
| kubesec scan -

종속성 문제 스캔

이미지 스캔

#!/bin/bash
export images=$(kubectl get pods --all-namespaces -o jsonpath="{range .items[]}{.spec.containers[].image}{'\n'}{end}" | sort | uniq)
echo "All images found: $images"
echo ""
echo ""
for image in $images; do
# Run trivy scan and save JSON output
trivy image --format json --output /tmp/result.json --severity HIGH,CRITICAL "$image" >/dev/null 2>&1
# Extract binary targets that have vulnerabilities
binaries=$(jq -r '.Results[] | select(.Vulnerabilities != null) | .Target' /tmp/result.json)
if [ -n "$binaries" ]; then
echo "- **Image:** $image"
while IFS= read -r binary; do
echo "  - **Binary:** $binary"
jq -r --arg target "$binary" '
.Results[] | select(.Target == $target) | .Vulnerabilities[] |
"    - **\(.Title)** (\(.Severity)): Affecting `\(.PkgName)` fixed in version `\(.FixedVersion)` (current version is `\(.InstalledVersion)`)."
' /tmp/result.json
done <<< "$binaries"
echo ""
echo ""
echo ""
fi
done

Helm charts 스캔

#!/bin/bash
# scan-helm-charts.sh
# This script lists all Helm releases, renders their manifests,
# and then scans each manifest with Trivy for configuration issues.

# Check that jq is installed
if ! command -v jq &>/dev/null; then
echo "jq is required but not installed. Please install jq and rerun."
exit 1
fi

# List all helm releases and extract namespace and release name
echo "Listing Helm releases..."
helm list --all-namespaces -o json | jq -r '.[] | "\(.namespace) \(.name)"' > helm_releases.txt

# Check if any releases were found
if [ ! -s helm_releases.txt ]; then
echo "No Helm releases found."
exit 0
fi

# Loop through each Helm release and scan its rendered manifest
while IFS=" " read -r namespace release; do
echo "---------------------------------------------"
echo "Scanning Helm release '$release' in namespace '$namespace'..."
# Render the Helm chart manifest
manifest_file="${release}-manifest.yaml"
helm get manifest "$release" -n "$namespace" > "$manifest_file"
if [ $? -ne 0 ]; then
echo "Failed to get manifest for $release in $namespace. Skipping."
continue
fi
# Scan the manifest with Trivy (configuration scan)
echo "Running Trivy config scan on $manifest_file..."
trivy config --severity MEDIUM,HIGH,CRITICAL "$manifest_file"
echo "Completed scan for $release."
done < helm_releases.txt

echo "---------------------------------------------"
echo "Helm chart scanning complete."

Tips

Kubernetes PodSecurityContext and SecurityContext

You can configure the security context of the Pods (with PodSecurityContext) and of the containers that are going to be run (with SecurityContext). For more information read:

Kubernetes SecurityContext(s)

Kubernetes API Hardening

Kubernetes Api Server에 대한 접근을 보호하는 것은 매우 중요합니다. 충분한 권한을 가진 악의적인 행위자가 이를 악용하면 환경에 심각한 피해를 줄 수 있습니다.
API Server에 대한 access(API Server에 접근할 수 있는 출처를 whitelist하고 다른 모든 연결을 차단)와 authentication (최소 권한 원칙을 따름)을 모두 안전하게 구성하는 것이 중요합니다. 그리고 절대 anonymous requests를 허용해서는 안 됩니다.

Common Request process:
User or K8s ServiceAccount –> Authentication –> Authorization –> Admission Control.

Tips:

  • 포트를 차단하세요.
  • Anonymous access를 피하세요.
  • NodeRestriction; 특정 노드에서 API에 접근하지 못하도록 합니다.
  • https://kubernetes.io/docs/reference/access-authn-authz/admission-controllers/#noderestriction
  • 기본적으로 node-restriction.kubernetes.io/ 접두사가 붙은 레이블을 kubelets가 추가/제거/업데이트하지 못하도록 방지합니다. 이 레이블 접두사는 워크로드 격리를 위해 관리자가 Node 객체에 레이블을 지정할 때 예약되며, kubelets는 해당 접두사가 붙은 레이블을 수정할 수 없습니다.
  • 또한 kubelets가 이러한 레이블 및 레이블 접두사를 추가/제거/업데이트하는 것을 허용합니다.
  • 레이블을 사용하여 안전한 워크로드 격리를 보장하세요.
  • 특정 pods의 API 접근을 차단하세요.
  • ApiServer의 인터넷 노출을 방지하세요.
  • 무단 접근을 RBAC으로 방지하세요.
  • ApiServer 포트는 방화벽과 IP 화이트리스트로 보호하세요.

SecurityContext Hardening

기본적으로 다른 사용자가 지정되지 않으면 Pod가 시작될 때 root 사용자가 사용됩니다. 다음과 유사한 템플릿을 사용하여 애플리케이션을 더 안전한 컨텍스트에서 실행할 수 있습니다:

apiVersion: v1
kind: Pod
metadata:
name: security-context-demo
spec:
securityContext:
runAsUser: 1000
runAsGroup: 3000
fsGroup: 2000
volumes:
- name: sec-ctx-vol
emptyDir: {}
containers:
- name: sec-ctx-demo
image: busybox
command: [ "sh", "-c", "sleep 1h" ]
securityContext:
runAsNonRoot: true
volumeMounts:
- name: sec-ctx-vol
mountPath: /data/demo
securityContext:
allowPrivilegeEscalation: true

일반 하드닝

You should update your Kubernetes environment as frequently as necessary to have:

  • 의존성을 최신 상태로 유지.
  • 버그 및 보안 패치 적용.

Release cycles: 각 3개월마다 새로운 마이너 릴리스가 있습니다 – 1.20.3 = 1(Major).20(Minor).3(patch)

Kubernetes 클러스터를 업데이트하는 가장 좋은 방법은 (출처 here):

  • Master Node 컴포넌트를 다음 순서로 업그레이드하십시오:
  • etcd (모든 인스턴스).
  • kube-apiserver (모든 control plane 호스트).
  • kube-controller-manager.
  • kube-scheduler.
  • cloud controller manager(사용 중이라면).
  • Worker Node 컴포넌트(kube-proxy, kubelet 등)를 업그레이드하십시오.

Kubernetes monitoring & security:

  • Kyverno Policy Engine
  • Cilium Tetragon - eBPF 기반의 보안 가시성 및 런타임 강제
  • 네트워크 보안 정책
  • Falco - 런타임 보안 모니터링 및 탐지

Tip

AWS 해킹 배우기 및 연습하기:HackTricks Training AWS Red Team Expert (ARTE)
GCP 해킹 배우기 및 연습하기: HackTricks Training GCP Red Team Expert (GRTE) Azure 해킹 배우기 및 연습하기: HackTricks Training Azure Red Team Expert (AzRTE)

HackTricks 지원하기