gke-security
google/skills
透過 Workload Identity、Secret Manager、RBAC、二進位授權、網路政策及 Pod 安全標準,強化 Google Kubernetes Engine (GKE) 叢集的安全性。
...展開全部GKE 安全性
本參考指南涵蓋 GKE 叢集的安全性設定。黃金路徑 預設會強制實施強化安全措施。
MCP 工具:
get_cluster、check_k8s_auth、get_k8s_resource、apply_k8s_manifest、update_cluster
黃金路徑的安全預設值
| 設定 | 黃金路徑值 | 第 0/1 天 | 備註 |
|---|---|---|---|
workloadIdentityConfig.workloadPool |
|
第 0 天 | Pod 的工作負載身分聯邦 |
secretManagerConfig.enabled |
true |
第 1 天 | Google Secret Manager 整合 |
secretManagerConfig.rotationConfig |
啟用:true,輪替間隔:120 秒 |
第 1 天 | 自動機密輪替 |
rbacBindingConfig.enableInsecureBindingSystemAuthenticated |
false |
第 0 天 | 封鎖舊版「系統已驗證」綁定 |
rbacBindingConfig.enableInsecureBindingSystemUnauthenticated |
false |
Day-0 | 封鎖舊版系統:未經認證的綁定 |
nodeConfig.shieldedInstanceConfig.enableSecureBoot |
true |
第 0 天 | 可驗證的開機完整性 |
nodeConfig.shieldedInstanceConfig.enableIntegrityMonitoring |
true |
第 0 天 | 執行階段完整性檢查 |
nodeConfig.workloadMetadataConfig.mode |
GKE_METADATA |
第 0 天 | 封鎖舊版元資料 API,強制執行工作負載身分識別 |
| 私有叢集 + 資料平面 V2 設定 | 請參閱gke-networking技能 |
Day-0 | 私有節點、私有端點強制執行、ADVANCED_DATAPATH |
工作負載身分聯邦
「工作負載身分識別」是 Pod 存取 Google Cloud API 的建議方式。 此方法可免除使用靜態服務帳戶金鑰的必要。
設定
# 1. 建立 Google 服務帳戶 (GSA)
gcloud iam service-accounts create \
--project \
--display-name "Workload Identity SA" \
--quiet
# 2. 授予 GSA IAM 角色
gcloud projects add-iam-policy-binding \
--member "serviceAccount:@.iam.gserviceaccount.com" \
--role "" \
--quiet
# 3. 建立 Kubernetes 服務帳戶 (KSA)
kubectl create namespace
kubectl create serviceaccount --namespace
# 4. 將 KSA 綁定至 GSA
gcloud iam service-accounts add-iam-policy-binding \
@.iam.gserviceaccount.com \
--role roles/iam.workloadIdentityUser \
--member "serviceAccount:.svc.id.goog[/]" \
--quiet
# 5. 為 KSA 添加註解
kubectl annotate serviceaccount \
--namespace \
iam.gke.io/gcp-service-account=@.iam.gserviceaccount.com
請參閱 assets/workload-identity-pod.yaml 以取得測試 Pod。
驗證
kubectl run workload-identity-test \
--image=gcr.io/google.com/cloudsdktool/cloud-sdk:slim \
--serviceaccount= --namespace= \
--rm -it -- gcloud auth list --quiet
Secret Manager 整合
此黃金路徑可啟用具備自動輪替功能的 Secret Manager。機密會 同步至 Kubernetes Secrets。
# 驗證叢集中是否已啟用 Secret Manager
gcloud container clusters describe --region \
--format="value(secretManagerConfig.enabled)" \
--quiet
# 若尚未啟用,請啟用(Day-1 變更)
gcloud container clusters update --region \
--enable-secret-manager \
--secret-manager-rotation-interval=120s \
--quiet
透過 CSI 卷掛載機密(部署範例)
啟用 Secret Manager 附加元件後,工作負載即可透過 Secrets Store CSI 驅動程式, 將機密掛載為卷。此操作需執行以下兩個步驟:
- 定義
SecretProviderClass以指定要從 Secret Manager 擷取哪些祕密。 - 在引用該類別的
Deployment中掛載該卷。
[!重要]生產環境最佳實務:始終使用符合生產環境標準的
Deployment宣言來示範工作負載 整合(例如 Secret Manager CSI),而非原始的Pod宣言。
步驟 1:建立 SecretProviderClass
apiVersion: secrets-store.csi.x-k8s.io/v1
kind: SecretProviderClass
metadata:
name: app-secrets-provider
namespace: default
spec:
provider: gke # 識別 GKE 託管提供者
parameters:
secrets: |
- resourceName: "projects//secrets/db-password/versions/latest"
fileName: "db-password.txt"
步驟 2:在 Deployment 中掛載機密
apiVersion: apps/v1
kind: Deployment
metadata:
name: secure-app
namespace: default
spec:
replicas: 2
selector:
matchLabels:
app: secure-app
template:
metadata:
labels:
app: secure-app
spec:
serviceAccountName: secure-ksa # 必須綁定至具備 Secret Manager 「Secret Accessor」角色的 GSA
containers:
- name: app
image:
volumeMounts:
- name: secrets-volume
mountPath: "/var/secrets"
readOnly: true
volumes:
- name: secrets-volume
csi:
driver: secrets-store.csi.k8s.io
readOnly: true
volumeAttributes:
secretProviderClass: "app-secrets-provider"
RBAC 強化措施
黃金路徑會停用不安全的舊版 RBAC 綁定,這些綁定會授予
system:authenticated和system:unauthenticated群組廣泛的存取權限。
# 驗證是否已停用不安全的綁定
gcloud container clusters describe --region \
--format="yaml(rbacBindingConfig)" \
--quiet
RBAC 的最佳實務:
- 優先使用命名空間範圍的角色,而非全叢集範圍的 ClusterRoles
- 應綁定至特定群組或服務帳戶,切勿綁定至
system:authenticated - 透過 MCP 稽核權限:
check_k8s_auth(parent="...", verb="list", resourceType="pods", namespace="...")(或使用kubectl auth can-i --list --as=) - 透過 MCP 檢視綁定:
get_k8s_resource(parent="...", resourceType="clusterrolebinding")(或使用kubectl get clusterrolebindings,rolebindings --all-namespaces)
有關企業級 RBAC 規劃,請參閱
gke-multitenancy技能,以及 https://docs.cloud.google.com/kubernetes-engine/docs/best-practices/rbac.md.txt
二進位授權
預設在黃金路徑中未啟用,但建議用於生產環境的映像 來源追蹤:
# 啟用二進位授權
gcloud container clusters update --region \
--binauthz-evaluation-mode=PROJECT_SINGLETON_POLICY_ENFORCE \
--quiet
網路政策
Dataplane V2(黃金路徑)提供內建的網路政策執行功能。針對每個命名空間套用 預設拒絕政策:
# MCP(首選)
apply_k8s_manifest(parent="...", yamlManifest="")
# kubectl 備用方案
kubectl apply -f ./assets/default-deny-netpol.yaml -n
GKE 沙箱 (gVisor)
若要在隔離的沙盒中執行不可信的工作負載:
# 在叢集上啟用(標準叢集)
gcloud container clusters update --region --enable-gke-sandbox --quiet
# 在 Pod 規格中使用
# 新增:runtimeClassName: gvisor
Pod 安全標準(黃金路徑)
Pod 安全標準定義了三種配置檔,用以限制 Pod 的操作範圍。
「受限」配置檔是生產環境命名空間的黃金路徑預設值。
| 配置檔 | 等級 | 使用情境 |
|---|---|---|
特權 |
無限制 | 系統命名空間 (kube-system), |
| : : : 基礎架構控制器 : | ||
基準 |
限制程度最低 | 共享/dev 命名空間、舊版應用程式 |
| : : : 正在遷移中 : | ||
受限 |
黃金路徑 | 生產環境工作負載 -- 區塊 |
| : : : 權限提升、主機存取、 : | ||
| : : : root : |
透過命名空間標籤強制執行(Pod 安全性准入):
apiVersion: v1
kind: Namespace
metadata:
name: production
labels:
pod-security.kubernetes.io/enforce: restricted
pod-security.kubernetes.io/warn: restricted
pod-security.kubernetes.io/audit: restricted
漸進式部署策略:
- 首先對現有命名空間進行
警告+稽核,以識別違規情況 - 修正不符合規範的工作負載(移除
特權、hostNetwork、root 使用者等) - 待所有工作負載均通過檢查後,啟用
強制執行
受限項目:以 root 身分執行、權限提升、主機
網路/PID/IPC、主機路徑儲存區,以及多數功能。黃金路徑
workload-identity-pod.yaml已符合規範。
網路政策記錄 (建議)
透過 Dataplane V2(黃金路徑),您可以啟用網路政策 決策的記錄功能。此設定並非黃金路徑的預設值,但建議用於安全稽核。
gcloud container clusters update --region \
--enable-network-policy-logging \
--quiet
此設定會記錄允許與拒絕的連線,有助於排除網路 政策規則的疑難排解,並稽核流量。
常見的 IAM 角色
GKE 最常見的五個預定義 IAM 角色:
| 角色 | 用途 | 何時使用 |
|---|---|---|
roles/container.admin |
對 | 平台團隊管理員 |
| : : 叢集及 : 管理叢集 : | ||
| : : Kubernetes : 生命週期 : | ||
| : : 資源 : : | ||
角色/container.clusterAdmin |
管理叢集,但 | 叢集操作員 |
| : : 並非專案層級 : 負責建立/刪除 : | ||
| : : IAM : 叢集 : | ||
roles/container.developer |
部署工作負載 | 應用程式 |
| : : (Pod、服務、 : 開發人員將 : | ||
| : : 部署) : 至現有叢集 : | ||
roles/container.viewer |
對 | 監控、 |
| : : 叢集與 : 稽核,或 : | ||
| : : Kubernetes : 唯讀儀表板 : | ||
| : : 資源 : : | ||
roles/container.clusterViewer |
列出並取得 | 符合以下條件的 CI/CD 管道: |
| : : 叢集詳細資訊 : 需要叢集 : | ||
| : : 僅需 : 元資料 : |
最小權限原則:請從
roles/container.viewer或roles/container.developer開始,並僅在必要時提升權限。避免廣泛授予roles/container.admin 權限。
服務帳戶與代理程式
- GKE 服務代理
(
service-): 自動建立。代表您管理節點、網路及叢集運作。 請勿移除或修改其權限。@container-engine-robot.iam.gserviceaccount.com - 節點服務帳戶:預設情況下,節點會使用 Compute Engine 的預設 服務帳戶。在生產環境中,請建立一個權限最低的專用服務帳戶, 並透過節點群組設定加以指派。
- 工作負載身分識別:Pod 存取 Google Cloud API 的建議方式。將 Kubernetes ServiceAccount 映射至 Google IAM ServiceAccount — 請參閱 上方的「工作負載身分識別」設定。
跨服務驗證模式
授予 GKE 工作負載存取其他 Google Cloud 服務的常見模式:
# 授予 GKE 工作負載存取 Cloud Storage 的權限
gcloud projects add-iam-policy-binding \
--member "serviceAccount:@.iam.gserviceaccount.com" \
--role "roles/storage.objectViewer" \
--quiet
# 授予 GKE 工作負載存取 Cloud SQL 的權限
gcloud projects add-iam-policy-binding \
--member "serviceAccount:@.iam.gserviceaccount.com" \
--role "roles/cloudsql.client" \
--quiet
# 授予 GKE 工作負載存取 Pub/Sub 的權限
gcloud projects add-iam-policy-binding \
--member "serviceAccount:@.iam.gserviceaccount.com" \
--role "roles/pubsub.subscriber" \
--quiet
在所有情況下,GSA 都必須透過「工作負載身分識別」(參見上文的設定) 與 KSA 建立綁定關係。隨後,Pod 會使用 KSA 來以 GSA 的身分進行驗證。
---
name: gke-security
description: Hardens Google Kubernetes Engine (GKE) clusters with Workload Identity, Secret Manager, RBAC, Binary Authorization, Network Policies, and Pod Security Standards.
---
# GKE Security
This reference covers security configuration for GKE clusters. The golden path
enforces a hardened security posture by default.
> **MCP Tools:** `get_cluster`, `check_k8s_auth`, `get_k8s_resource`,
> `apply_k8s_manifest`, `update_cluster`
## Golden Path Security Defaults
Setting | Golden Path Value | Day-0/1 | Notes
-------------------------------------------------------------- | --------------------------------------- | ------- | -----
`workloadIdentityConfig.workloadPool` | `<PROJECT>.svc.id.goog` | Day-0 | Workload Identity Federation for Pods
`secretManagerConfig.enabled` | `true` | Day-1 | Google Secret Manager integration
`secretManagerConfig.rotationConfig` | `enabled: true, rotationInterval: 120s` | Day-1 | Automatic secret rotation
`rbacBindingConfig.enableInsecureBindingSystemAuthenticated` | `false` | Day-0 | Blocks legacy `system:authenticated` bindings
`rbacBindingConfig.enableInsecureBindingSystemUnauthenticated` | `false` | Day-0 | Blocks legacy `system:unauthenticated` bindings
`nodeConfig.shieldedInstanceConfig.enableSecureBoot` | `true` | Day-0 | Verifiable boot integrity
`nodeConfig.shieldedInstanceConfig.enableIntegrityMonitoring` | `true` | Day-0 | Runtime integrity checks
`nodeConfig.workloadMetadataConfig.mode` | `GKE_METADATA` | Day-0 | Blocks legacy metadata API, enforces Workload Identity
Private cluster + Dataplane V2 settings | See the `gke-networking` skill | Day-0 | Private nodes, private endpoint enforcement, ADVANCED_DATAPATH
## Workload Identity Federation
Workload Identity is the recommended way for pods to access Google Cloud APIs.
It eliminates the need for static service account keys.
### Setup
```bash
# 1. Create a Google Service Account (GSA)
gcloud iam service-accounts create <GSA_NAME> \
--project <PROJECT_ID> \
--display-name "Workload Identity SA" \
--quiet
# 2. Grant IAM roles to the GSA
gcloud projects add-iam-policy-binding <PROJECT_ID> \
--member "serviceAccount:<GSA_NAME>@<PROJECT_ID>.iam.gserviceaccount.com" \
--role "<ROLE>" \
--quiet
# 3. Create Kubernetes Service Account (KSA)
kubectl create namespace <NAMESPACE>
kubectl create serviceaccount <KSA_NAME> --namespace <NAMESPACE>
# 4. Bind KSA to GSA
gcloud iam service-accounts add-iam-policy-binding \
<GSA_NAME>@<PROJECT_ID>.iam.gserviceaccount.com \
--role roles/iam.workloadIdentityUser \
--member "serviceAccount:<PROJECT_ID>.svc.id.goog[<NAMESPACE>/<KSA_NAME>]" \
--quiet
# 5. Annotate KSA
kubectl annotate serviceaccount <KSA_NAME> \
--namespace <NAMESPACE> \
iam.gke.io/gcp-service-account=<GSA_NAME>@<PROJECT_ID>.iam.gserviceaccount.com
```
> See [assets/workload-identity-pod.yaml](./assets/workload-identity-pod.yaml)
> for a test pod.
### Verification
```bash
kubectl run workload-identity-test \
--image=gcr.io/google.com/cloudsdktool/cloud-sdk:slim \
--serviceaccount=<KSA_NAME> --namespace=<NAMESPACE> \
--rm -it -- gcloud auth list --quiet
```
## Secret Manager Integration
The golden path enables Secret Manager with automatic rotation. Secrets are
synced to Kubernetes Secrets.
```bash
# Verify Secret Manager is enabled on cluster
gcloud container clusters describe <CLUSTER_NAME> --region <REGION> \
--format="value(secretManagerConfig.enabled)" \
--quiet
# Enable if not already (Day-1 change)
gcloud container clusters update <CLUSTER_NAME> --region <REGION> \
--enable-secret-manager \
--secret-manager-rotation-interval=120s \
--quiet
```
### Mounting Secrets via CSI Volume (Deployment Example)
Once the Secret Manager add-on is enabled, workloads can mount secrets as
volumes using the Secrets Store CSI driver. This requires two steps:
1. **Define a `SecretProviderClass`** to specify which secrets to retrieve from
Secret Manager.
2. **Mount the volume in a `Deployment`** referencing that class.
> [!IMPORTANT] **Production Best Practice**: Always demonstrate workload
> integrations (like Secret Manager CSI) using production-standard
> **`Deployment`** manifests rather than raw `Pod` manifests.
#### Step 1: Create the SecretProviderClass
```yaml
apiVersion: secrets-store.csi.x-k8s.io/v1
kind: SecretProviderClass
metadata:
name: app-secrets-provider
namespace: default
spec:
provider: gke # Identifies GKE managed provider
parameters:
secrets: |
- resourceName: "projects/<PROJECT_ID>/secrets/db-password/versions/latest"
fileName: "db-password.txt"
```
#### Step 2: Mount the secret in a Deployment
```yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: secure-app
namespace: default
spec:
replicas: 2
selector:
matchLabels:
app: secure-app
template:
metadata:
labels:
app: secure-app
spec:
serviceAccountName: secure-ksa # Must be bound to GSA with Secret Manager Secret Accessor role
containers:
- name: app
image: <IMAGE>
volumeMounts:
- name: secrets-volume
mountPath: "/var/secrets"
readOnly: true
volumes:
- name: secrets-volume
csi:
driver: secrets-store.csi.k8s.io
readOnly: true
volumeAttributes:
secretProviderClass: "app-secrets-provider"
```
## RBAC Hardening
The golden path disables insecure legacy RBAC bindings that grant broad access
to `system:authenticated` and `system:unauthenticated` groups.
```bash
# Verify insecure bindings are disabled
gcloud container clusters describe <CLUSTER_NAME> --region <REGION> \
--format="yaml(rbacBindingConfig)" \
--quiet
```
**Best practices for RBAC:**
- Use namespace-scoped Roles over cluster-wide ClusterRoles
- Bind to specific Groups or ServiceAccounts, never to `system:authenticated`
- Audit permissions via MCP: `check_k8s_auth(parent="...", verb="list",
resourceType="pods", namespace="...")` (or `kubectl auth can-i --list
--as=<user>`)
- Review bindings via MCP: `get_k8s_resource(parent="...",
resourceType="clusterrolebinding")` (or `kubectl get
clusterrolebindings,rolebindings --all-namespaces`)
> See the `gke-multitenancy` skill for enterprise RBAC planning and
> https://docs.cloud.google.com/kubernetes-engine/docs/best-practices/rbac.md.txt
## Binary Authorization
Not enabled in golden path by default but recommended for production image
provenance:
```bash
# Enable Binary Authorization
gcloud container clusters update <CLUSTER_NAME> --region <REGION> \
--binauthz-evaluation-mode=PROJECT_SINGLETON_POLICY_ENFORCE \
--quiet
```
## Network Policies
Dataplane V2 (golden path) provides built-in Network Policy enforcement. Apply
default-deny per namespace:
```
# MCP (preferred)
apply_k8s_manifest(parent="...", yamlManifest="<contents of default-deny-netpol.yaml>")
# kubectl fallback
kubectl apply -f ./assets/default-deny-netpol.yaml -n <NAMESPACE>
```
## GKE Sandbox (gVisor)
For running untrusted workloads in an isolated sandbox:
```bash
# Enable on cluster (Standard clusters)
gcloud container clusters update <CLUSTER_NAME> --region <REGION> --enable-gke-sandbox --quiet
# Use in pod spec
# Add: runtimeClassName: gvisor
```
## Pod Security Standards (Golden Path)
Pod Security Standards define three profiles that restrict what pods can do. The
**`restricted` profile is the golden path default** for production namespaces.
| Profile | Level | Use Case |
| ------------ | --------------------- | ---------------------------------- |
| `privileged` | Unrestricted | System namespaces (`kube-system`), |
: : : infrastructure controllers :
| `baseline` | Minimally restrictive | Shared/dev namespaces, legacy apps |
: : : being migrated :
| `restricted` | **Golden path** | Production workloads -- blocks |
: : : privilege escalation, host access, :
: : : root :
**Enforce via namespace labels (Pod Security Admission):**
```yaml
apiVersion: v1
kind: Namespace
metadata:
name: production
labels:
pod-security.kubernetes.io/enforce: restricted
pod-security.kubernetes.io/warn: restricted
pod-security.kubernetes.io/audit: restricted
```
**Gradual rollout strategy:**
1. Start with `warn` + `audit` on existing namespaces to identify violations
2. Fix non-compliant workloads (remove `privileged`, `hostNetwork`, root user,
etc.)
3. Enable `enforce` once all workloads pass
`restricted` blocks: running as root, privilege escalation, host
networking/PID/IPC, host path volumes, and most capabilities. The golden path
`workload-identity-pod.yaml` already complies.
## Network Policy Logging (Recommended)
With Dataplane V2 (golden path), you can enable logging for Network Policy
decisions. **Not a golden path default** -- recommended for security auditing.
```bash
gcloud container clusters update <CLUSTER_NAME> --region <REGION> \
--enable-network-policy-logging \
--quiet
```
This logs allowed and denied connections, useful for troubleshooting Network
Policy rules and auditing traffic flows.
## Common IAM Roles
The five most common predefined IAM roles for GKE:
| Role | Purpose | When to Use |
| ------------------------------- | ------------------- | -------------------- |
| `roles/container.admin` | Full control over | Platform team admins |
: : clusters and : managing cluster :
: : Kubernetes : lifecycle :
: : resources : :
| `roles/container.clusterAdmin` | Manage clusters but | Cluster operators |
: : not project-level : who create/delete :
: : IAM : clusters :
| `roles/container.developer` | Deploy workloads | Application |
: : (pods, services, : developers deploying :
: : deployments) : to existing clusters :
| `roles/container.viewer` | Read-only access to | Monitoring, |
: : clusters and : auditing, or :
: : Kubernetes : read-only dashboards :
: : resources : :
| `roles/container.clusterViewer` | List and get | CI/CD pipelines that |
: : cluster details : need cluster :
: : only : metadata :
> **Principle of least privilege**: Start with `roles/container.viewer` or
> `roles/container.developer` and escalate only as needed. Avoid granting
> `roles/container.admin` broadly.
## Service Accounts & Agents
- **GKE Service Agent**
(`service-<PROJECT_NUMBER>@container-engine-robot.iam.gserviceaccount.com`):
Automatically created. Manages nodes, networking, and cluster operations on
your behalf. Do not remove or modify its permissions.
- **Node Service Account**: By default, nodes use the Compute Engine default
service account. For production, create a dedicated SA with minimal
permissions and assign it via node pool config.
- **Workload Identity**: The recommended way for pods to access Google Cloud
APIs. Maps a Kubernetes ServiceAccount to a Google IAM ServiceAccount — see
[Workload Identity setup](#workload-identity-federation) above.
## Cross-Service Authentication Patterns
Common patterns for granting GKE workloads access to other Google Cloud
services:
```bash
# Grant a GKE workload access to Cloud Storage
gcloud projects add-iam-policy-binding <PROJECT_ID> \
--member "serviceAccount:<GSA_NAME>@<PROJECT_ID>.iam.gserviceaccount.com" \
--role "roles/storage.objectViewer" \
--quiet
# Grant a GKE workload access to Cloud SQL
gcloud projects add-iam-policy-binding <PROJECT_ID> \
--member "serviceAccount:<GSA_NAME>@<PROJECT_ID>.iam.gserviceaccount.com" \
--role "roles/cloudsql.client" \
--quiet
# Grant a GKE workload access to Pub/Sub
gcloud projects add-iam-policy-binding <PROJECT_ID> \
--member "serviceAccount:<GSA_NAME>@<PROJECT_ID>.iam.gserviceaccount.com" \
--role "roles/pubsub.subscriber" \
--quiet
```
In all cases, the GSA must be bound to a KSA via Workload Identity (see setup
above). The pod then uses the KSA to authenticate as the GSA.
所有檔案
0 個檔案安裝 gke-security
請下載並將技能檔案解壓縮至您的 .claude/skills/ 目錄中。
下載 ZIP複製儲存庫並將技能檔案複製到您的專案中。
git clone https://github.com/google/skills/tree/main/skills/cloud/gke-security # Copy SKILL.md to your .claude/skills/ directory
複製





首頁
