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 は、リスク分析、セキュリティコンプライアンス、RBACビジュアライザー、イメージ脆弱性スキャンなどを含むマルチクラウド対応のK8s単一の管理画面を提供するK8s向けオープンソースツールです。KubescapeはK8sクラスター、YAMLファイル、HELMチャートをスキャンし、複数のフレームワーク(例えば the NSA-CISA , MITRE ATT&CK®)に沿ったミスコンフィギュレーション、ソフトウェア脆弱性、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 is a utility that scans live Kubernetes cluster and reports potential issues with deployed resources and configurations. It sanitizes your cluster based on what’s deployed and not what’s sitting on disk. By scanning your cluster, it detects misconfigurations and helps you to ensure that best practices are in place, thus preventing future headaches. It aims at reducing the cognitive _over_load one faces when operating a Kubernetes cluster in the wild. Furthermore, if your cluster employs a metric-server, it reports potential resources over/under allocations and attempts to warn you should your cluster run out of capacity.

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

[非推奨] ツール kube-hunter は Kubernetes クラスターのセキュリティ上の脆弱性を検出します。 このツールは Kubernetes 環境におけるセキュリティ問題に対する認識と可視性を高めるために開発されました。

kube-hunter --remote some.node.com

Trivy

Trivy はセキュリティ問題を検出するスキャナを備えており、以下の対象をスキャンできます:

  • コンテナイメージ
  • ファイルシステム
  • Gitリポジトリ(リモート)
  • 仮想マシンイメージ
  • 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ロールがどのPodで動作しているかを特定します
  • find-secrets: Pods、ConfigMaps、SecretsなどのK8sリソース内のシークレットを特定しようとします
  • test-imds-access: Podを実行してmetadata v1およびv2にアクセスしようとします。WARNING: これはクラスタ内でPodを実行します。非常に注意してください — 実行したくない場合があるかもしれません!

IaCコードの監査

KICS

KICS は、以下のInfrastructure as Codeソリューションにおけるセキュリティ脆弱性、コンプライアンス問題、およびインフラのミスコンフィギュレーションを検出します: Terraform, Kubernetes, Docker, AWS CloudFormation, Ansible, Helm, Microsoft ARM, および OpenAPI 3.0 specifications

Checkov

Checkov は infrastructure-as-code 向けの静的コード解析ツールです。

Terraform、Terraform plan、CloudformationAWS SAMKubernetesDockerfileServerless または ARM Templates を使用してプロビジョニングされたクラウドインフラをスキャンし、グラフベースのスキャンによりセキュリティおよびコンプライアンスのミスコンフィグを検出します。

Kube-score

kube-score は、Kubernetesのオブジェクト定義に対して静的コード解析を実行するツールです。

To install:

DistributionCommand / Link
macOS、Linux、Windows向けの事前ビルド済バイナリGitHub releases
Dockerdocker pull zegl/kube-score (Docker Hub)
Homebrew (macOS and Linux)brew install kube-score
Krew (macOS and Linux)kubectl krew install score

YAMLファイル & 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."

ヒント

Kubernetes PodSecurityContext and SecurityContext

Pod の security contextPodSecurityContext で、実行される containerssecurity contextSecurityContext で設定できます。詳細は次を参照してください:

Kubernetes SecurityContext(s)

Kubernetes API のハードニング

Kubernetes Api Server へのアクセスを保護すること は非常に重要です。特権を持つ悪意あるアクターがそれを悪用し、環境に多大な被害を与える可能性があります。\
アクセス(API Server へのオリジンを whitelist しその他の接続を拒否する)とauthentication最小 権限 の原則に従う)の両方を確実に保護することが重要です。そして決して 匿名 リクエスト を許可してはいけません。

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

ヒント:

  • ポートを閉じる。
  • 匿名アクセスを避ける。
  • NodeRestriction; 指定したノードからの API へのアクセスを禁止する。
  • https://kubernetes.io/docs/reference/access-authn-authz/admission-controllers/#noderestriction
  • 基本的に kubelets が node-restriction.kubernetes.io/ プレフィックスを持つラベルの追加/削除/更新を行うのを防ぎます。このラベルプレフィックスは管理者が Node オブジェクトにワークロード分離の目的でラベル付けするために予約されており、kubelets はそのプレフィックスを持つラベルを変更できません。
  • また、特定の場合に kubelets がこれらのラベルやラベルプレフィックスを追加/削除/更新できるようにします。
  • ラベルを使ってワークロードの安全な分離を確保する。
  • 特定の Pod からの API アクセスを制限する。
  • ApiServer をインターネットに公開しない。
  • RBAC で不正アクセスを防ぐ。
  • ApiServer のポートはファイアウォールと IP ホワイトリストで保護する。

SecurityContext のハードニング

デフォルトでは、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

一般的なハードニング

Kubernetes 環境は以下を維持するために、必要に応じて頻繁に更新する必要があります:

  • 依存関係を最新の状態に保つ。
  • バグおよびセキュリティパッチを適用する。

Release cycles: 3か月ごとに新しいマイナーリリースが出ます – 1.20.3 = 1(メジャー).20(マイナー).3(パッチ)

Kubernetes クラスターを更新する最良の方法は(参照元:here):

  • Master Node のコンポーネントを以下の順序でアップグレードします:
  • etcd(すべてのインスタンス)。
  • kube-apiserver(すべてのコントロールプレーンホスト)。
  • kube-controller-manager。
  • kube-scheduler。
  • cloud controller manager(使用している場合)。
  • Worker Node のコンポーネント(kube-proxy、kubelet など)をアップグレードします。

Kubernetes の監視とセキュリティ:

  • Kyverno Policy Engine
  • Cilium Tetragon - eBPF ベースのセキュリティ可観測性とランタイム強制
  • Network Security Policies(ネットワークセキュリティポリシー)
  • 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をサポートする