使用用戶端程式庫存取儲存在 GKE 叢集外的密碼

本教學課程說明如何將 Google Kubernetes Engine (GKE) 叢集使用的機密資料儲存在 Secret Manager。您將瞭解如何使用 Workload Identity Federation for GKE 和Google Cloud 用戶端程式庫,以更安全的方式從 Pod 存取資料。

將機密資料儲存在叢集儲存空間之外,可降低攻擊發生時資料遭到未授權存取的風險。使用 Workload Identity Federation for GKE 存取資料,可避免管理長期服務帳戶金鑰的相關風險,並可使用 Identity and Access Management (IAM) 控制 Secret 存取權,而非叢集內 RBAC 規則。您可以使用任何外部 Secret 儲存庫供應商,例如 Secret Manager 或 HashiCorp Vault。

本頁面適用於想將機密資料移出叢集內儲存空間的資安專員。如要進一步瞭解 Google Cloud 內容中提及的常見角色和工作範例,請參閱「常見的 GKE 使用者角色和工作」。

本教學課程使用 GKE Autopilot 叢集。如要使用 GKE Standard 執行步驟,您必須手動啟用 Workload Identity Federation for GKE。

您可以使用 Workload Identity Federation for GKE,從 GKE 工作負載存取任何 Google Cloud API,不必使用靜態服務帳戶金鑰檔案等安全性較低的方法。本教學課程以 Secret Manager 為例,但您可以使用相同步驟存取其他 Google CloudAPI。詳情請參閱「Workload Identity Federation for GKE」。

目標

  • 在 Google Cloud Secret Manager 中建立密鑰。
  • 建立 GKE Autopilot 叢集、Kubernetes 命名空間和 Kubernetes 服務帳戶。
  • 建立 IAM 允許政策,授予 Kubernetes 服務帳戶對密鑰的存取權。
  • 使用測試應用程式驗證服務帳戶存取權。
  • 執行範例應用程式,使用 Secret Manager API 存取 Secret。

費用

在本文件中,您會使用下列 Google Cloud計費元件:

您可以使用 Pricing Calculator,根據預測用量估算費用。

初次使用 Google Cloud 的使用者可能符合免費試用期資格。

完成本文所述工作後,您可以刪除建立的資源,避免繼續計費,詳情請參閱「清除所用資源」。

事前準備

  1. 登入 Google Cloud 帳戶。如果您未曾使用過 Google Cloud,歡迎建立帳戶,親自體驗實際使用我們產品的成效。新客戶還能獲得價值 $300 美元的免費抵免額,用於執行、測試及部署工作負載。
  2. 安裝 Google Cloud CLI。

  3. 若您採用的是外部識別資訊提供者 (IdP),請先使用聯合身分登入 gcloud CLI。

  4. 執行下列指令,初始化 gcloud CLI:

    gcloud init
  5. 建立或選取 Google Cloud 專案。

    選取或建立專案所需的角色

    • 選取專案:選取專案時,不需具備特定 IAM 角色,只要您已獲派角色,即可選取任何專案。
    • 建立專案:如要建立專案,您必須具備專案建立者角色 (roles/resourcemanager.projectCreator),其中包含 resourcemanager.projects.create 權限。瞭解如何授予角色。
    • 建立 Google Cloud 專案:

      gcloud projects create PROJECT_ID

      將 PROJECT_ID 替換為您要建立的 Google Cloud 專案名稱。

    • 選取您建立的 Google Cloud 專案:

      gcloud config set project PROJECT_ID

      將 PROJECT_ID 替換為 Google Cloud 專案名稱。

  6. 確認 Google Cloud 專案已啟用計費功能。

  7. 啟用 Kubernetes Engine 和 Secret Manager API (如果尚未啟用):

    啟用 API 所需的角色

    如要啟用 API,您必須具備 serviceusage.services.enable 權限。如果您建立了專案,可能已透過擁有者角色 (roles/owner) 取得這項權限。否則,您可以透過 Service Usage 管理員角色 (roles/serviceusage.serviceUsageAdmin) 取得這項權限。瞭解如何授予角色。

    gcloud services enable container.googleapis.com secretmanager.googleapis.com
  8. 安裝 Google Cloud CLI。

  9. 若您採用的是外部識別資訊提供者 (IdP),請先使用聯合身分登入 gcloud CLI。

  10. 執行下列指令,初始化 gcloud CLI:

    gcloud init
  11. 建立或選取 Google Cloud 專案。

    選取或建立專案所需的角色

    • 選取專案:選取專案時,不需具備特定 IAM 角色,只要您已獲派角色,即可選取任何專案。
    • 建立專案:如要建立專案,您必須具備專案建立者角色 (roles/resourcemanager.projectCreator),其中包含 resourcemanager.projects.create 權限。瞭解如何授予角色。
    • 建立 Google Cloud 專案:

      gcloud projects create PROJECT_ID

      將 PROJECT_ID 替換為您要建立的 Google Cloud 專案名稱。

    • 選取您建立的 Google Cloud 專案:

      gcloud config set project PROJECT_ID

      將 PROJECT_ID 替換為 Google Cloud 專案名稱。

  12. 確認 Google Cloud 專案已啟用計費功能。

  13. 啟用 Kubernetes Engine 和 Secret Manager API (如果尚未啟用):

    啟用 API 所需的角色

    如要啟用 API,您必須具備 serviceusage.services.enable 權限。如果您建立了專案,可能已透過擁有者角色 (roles/owner) 取得這項權限。否則,您可以透過 Service Usage 管理員角色 (roles/serviceusage.serviceUsageAdmin) 取得這項權限。瞭解如何授予角色。

    gcloud services enable container.googleapis.com secretmanager.googleapis.com
  14. 將角色授予使用者帳戶。針對下列各個 IAM 角色,執行下列指令一次:roles/secretmanager.admin, roles/container.clusterAdmin

    gcloud projects add-iam-policy-binding PROJECT_ID --member="user:USER_IDENTIFIER" --role=ROLE

    更改下列內容:

    • PROJECT_ID:專案 ID。
    • USER_IDENTIFIER:使用者帳戶的 ID。 例如:myemail@example.com。
    • ROLE:您授予使用者帳戶的 IAM 角色。

準備環境

複製 GitHub 存放區,其中包含本教學課程的範例檔案:

git clone https://github.com/GoogleCloudPlatform/kubernetes-engine-samples
cd ~/kubernetes-engine-samples/security/wi-secrets

在 Secret Manager 中建立密鑰

  1. 以下範例顯示建立密鑰時會用到的資料:

    key=my-api-key
  2. 建立 Secret 來儲存樣本資料:

    gcloud secrets create bq-readonly-key \
        --data-file=manifests/bq-readonly-key \
        --ttl=3600s
    

    這個指令會執行下列動作:

    • 在us-central1 Google Cloud 區域中,使用範例金鑰建立新的 Secret Manager 密鑰。
    • 將 Secret 設為在執行指令一小時後到期。

建立叢集和 Kubernetes 資源

建立 GKE 叢集、Kubernetes 命名空間和 Kubernetes 服務帳戶。您建立了兩個命名空間,一個用於唯讀存取權,另一個用於密鑰的讀取/寫入權限。您也會在每個命名空間中建立 Kubernetes 服務帳戶,以便與 Workload Identity Federation for GKE 搭配使用。

  1. 建立 GKE Autopilot 叢集:

    gcloud container clusters create-auto secret-cluster \
        --location=us-central1
    

    叢集可能需要約五分鐘才能部署完畢。Autopilot 叢集一律會啟用 Workload Identity Federation for GKE。如要改用 GKE Standard 叢集,請先手動啟用 GKE 適用的 Workload Identity Federation,再繼續操作。

  2. 建立 readonly-ns 命名空間和 admin-ns 命名空間:

    kubectl create namespace readonly-ns
    kubectl create namespace admin-ns
    
  3. 建立 readonly-sa Kubernetes 服務帳戶和 admin-sa Kubernetes 服務帳戶:

    kubectl create serviceaccount readonly-sa --namespace=readonly-ns
    kubectl create serviceaccount admin-sa --namespace=admin-ns
    

建立 IAM 允許政策

  1. 授予 readonly-sa 服務帳戶對密鑰的唯讀存取權:

    gcloud secrets add-iam-policy-binding bq-readonly-key \
        --member=principal://iam.googleapis.com/projects/PROJECT_NUMBER/locations/global/workloadIdentityPools/PROJECT_ID.svc.id.goog/subject/ns/readonly-ns/sa/readonly-sa \
        --role='roles/secretmanager.secretAccessor' \
        --condition=None
    

    更改下列內容:

    • PROJECT_NUMBER: Google Cloud專案的數值編號。
    • PROJECT_ID:您的 Google Cloud 專案 ID。
  2. 授予 admin-sa 服務帳戶對密鑰的讀取/寫入權限:

    gcloud secrets add-iam-policy-binding bq-readonly-key \
        --member=principal://iam.googleapis.com/projects/PROJECT_NUMBER/locations/global/workloadIdentityPools/PROJECT_ID.svc.id.goog/subject/ns/admin-ns/sa/admin-sa \
        --role='roles/secretmanager.secretAccessor' \
        --condition=None
    gcloud secrets add-iam-policy-binding bq-readonly-key \
        --member=principal://iam.googleapis.com/projects/PROJECT_NUMBER/locations/global/workloadIdentityPools/PROJECT_ID.svc.id.goog/subject/ns/admin-ns/sa/admin-sa \
        --role='roles/secretmanager.secretVersionAdder' \
        --condition=None
    

驗證 Secret 存取權

在每個命名空間部署測試 Pod,驗證唯讀和讀取/寫入權限。

  1. 查看唯讀 Pod 資訊清單:

    # Copyright 2022 Google LLC
    #
    # 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: v1
    kind: Pod
    metadata:
      name: readonly-test
      namespace: readonly-ns
    spec:
      containers:
      - image: google/cloud-sdk:slim
        name: workload-identity-test
        command: ["sleep","infinity"]
        resources:
          requests:
            cpu: "150m"
            memory: "150Mi"
      serviceAccountName: readonly-sa

    這個 Pod 會使用 readonly-ns 命名空間中的 readonly-sa 服務帳戶。

  2. 查看讀寫 Pod 資訊清單:

    # Copyright 2022 Google LLC
    #
    # 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: v1
    kind: Pod
    metadata:
      name: admin-test
      namespace: admin-ns
    spec:
      containers:
      - image: google/cloud-sdk:slim
        name: workload-identity-test
        command: ["sleep","infinity"]
        resources:
          requests:
            cpu: "150m"
            memory: "150Mi"
      serviceAccountName: admin-sa

    這個 Pod 會使用 admin-ns 命名空間中的 admin-sa 服務帳戶。

  3. 部署測試 Pod:

    kubectl apply -f manifests/admin-pod.yaml
    kubectl apply -f manifests/readonly-pod.yaml
    

    Pod 可能需要幾分鐘才會開始運作。如要監控進度,請執行下列指令:

    watch kubectl get pods -n readonly-ns
    

    Pod 狀態變更為 RUNNING 時,請按下 Ctrl+C 返回指令列。

測試唯讀存取權

  1. 在 readonly-test Pod 中開啟殼層:

    kubectl exec -it readonly-test --namespace=readonly-ns -- /bin/bash
    
  2. 嘗試讀取 Secret:

    gcloud secrets versions access 1 --secret=bq-readonly-key
    

    輸出內容為 key=my-api-key。

  3. 嘗試將新資料寫入密鑰:

    printf "my-second-api-key" | gcloud secrets versions add bq-readonly-key --data-file=-
    

    輸出結果會與下列內容相似:

    ERROR: (gcloud.secrets.versions.add) PERMISSION_DENIED: Permission 'secretmanager.versions.add' denied for resource 'projects/PROJECT_ID/secrets/bq-readonly-key' (or it may not exist).
    

    使用唯讀服務帳戶的 Pod 只能讀取 Secret,無法寫入新資料。

  4. 結束 Pod:

    exit
    

測試讀取/寫入權限

  1. 在 admin-test Pod 中開啟殼層:

    kubectl exec -it admin-test --namespace=admin-ns -- /bin/bash
    
  2. 嘗試讀取 Secret:

    gcloud secrets versions access 1 --secret=bq-readonly-key
    

    輸出內容為 key=my-api-key。

  3. 嘗試將新資料寫入密鑰:

    printf "my-second-api-key" | gcloud secrets versions add bq-readonly-key --data-file=-
    

    輸出結果會與下列內容相似:

    Created version [2] of the secret [bq-readonly-key].
    
  4. 讀取新的密鑰版本:

    gcloud secrets versions access 2 --secret=bq-readonly-key
    

    輸出內容為 my-second-api-key。

  5. 結束 Pod:

    exit
    

Pod 只會取得您授予 Kubernetes 服務帳戶 (用於 Pod 資訊清單) 的存取權層級。在 admin-ns 命名空間中使用 admin-sa Kubernetes 帳戶的任何 Pod 都可以寫入新版本的密鑰,但在 readonly-ns 命名空間中使用 readonly-sa Kubernetes 服務帳戶的任何 Pod 只能讀取密鑰。

透過程式碼存取密鑰

在本節中,執行以下操作:

  1. 部署範例應用程式,使用用戶端程式庫讀取 Secret Manager 中的密鑰。

  2. 確認應用程式可以存取 Secret。

請盡可能使用 Secret Manager API,從應用程式程式碼存取 Secret Manager 密鑰。

  1. 查看範例應用程式原始碼:

    // Copyright 2022 Google LLC
    //
    // 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.
    
    package main
    
    import (
    	"context"
    	"fmt"
    	"log"
    	"os"
    
    	secretmanager "cloud.google.com/go/secretmanager/apiv1"
    	secretmanagerpb "google.golang.org/genproto/googleapis/cloud/secretmanager/v1"
    )
    
    func main() {
    
            // Get environment variables from Pod spec.
            projectID := os.Getenv("PROJECT_ID")
            secretId := os.Getenv("SECRET_ID")
            secretVersion := os.Getenv("SECRET_VERSION")
    
            // Create the Secret Manager client.
            ctx := context.Background()
            client, err := secretmanager.NewClient(ctx)
            if err != nil {
                    log.Fatalf("failed to setup client: %v", err)
            }
            defer client.Close()
    
            // Create the request to access the secret.
            accessSecretReq := &secretmanagerpb.AccessSecretVersionRequest{
                    Name: fmt.Sprintf("projects/%s/secrets/%s/versions/%s", projectID, secretId, secretVersion),
            }
    
            secret, err := client.AccessSecretVersion(ctx, accessSecretReq)
            if err != nil {
                    log.Fatalf("failed to access secret: %v", err)
            }
    
            // Print the secret payload.
            //
            // WARNING: Do not print the secret in a production environment - this
            // snippet is showing how to access the secret material.
            log.Printf("Welcome to the key store, here's your key:\nKey: %s", secret.Payload.Data)
    }
    

    這個應用程式會呼叫 Secret Manager API,嘗試讀取密鑰。

  2. 查看範例應用程式 Pod 資訊清單:

    # Copyright 2022 Google LLC
    #
    # 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: v1
    kind: Pod
    metadata:
      name: readonly-secret-test
      namespace: readonly-ns
    spec:
      containers:
      - image: us-docker.pkg.dev/google-samples/containers/gke/wi-secret-store:latest
        name: secret-app
        env:
          - name: PROJECT_ID
            value: "YOUR_PROJECT_ID"
          - name: SECRET_ID
            value: "bq-readonly-key"
          - name: SECRET_VERSION
            value: "latest"
        resources:
          requests:
            cpu: "125m"
            memory: "64Mi"
      serviceAccountName: readonly-sa

    這個資訊清單會執行下列操作:

    • 在 readonly-ns 命名空間中建立使用 readonly-sa 服務帳戶的 Pod。
    • 從 Google 映像檔登錄檔提取範例應用程式。這個應用程式會使用Google Cloud 用戶端程式庫呼叫 Secret Manager API。您可以在存放區的 /main.go 中查看應用程式程式碼。
    • 設定範例應用程式要使用的環境變數。
  3. 替換範例應用程式中的環境變數:

    sed -i "s/YOUR_PROJECT_ID/PROJECT_ID/g" "manifests/secret-app.yaml"
    
  4. 部署範例應用程式:

    kubectl apply -f manifests/secret-app.yaml
    

    Pod 可能需要幾分鐘才會開始運作。如果 Pod 需要叢集中的新節點,您可能會在 GKE 佈建節點時看到 CrashLoopBackOff 類型的事件。節點佈建成功後,當機就會停止。

  5. 驗證 Secret 存取權:

    kubectl logs readonly-secret-test -n readonly-ns
    

    輸出內容為 my-second-api-key。如果輸出內容為空白,表示 Pod 可能尚未執行。請稍後再試。

替代做法

如需將機密資料掛接至 Pod,請使用 GKE 適用的 Secret Manager 外掛程式。這項外掛程式會部署及管理 GKE 叢集中 Kubernetes Secret Store CSI 驅動程式的 Google Cloud Secret Manager 供應器。如需操作說明,請參閱「搭配使用 Secret Manager 外掛程式與 GKE」。

以掛接磁碟區的形式提供 Secret,會產生下列風險:

  1. 已掛接的磁碟區容易遭受目錄遍歷攻擊。
  2. 如果設定錯誤 (例如開啟偵錯端點),環境變數可能會遭到入侵。

建議您盡可能透過 Secret Manager API,以程式輔助方式存取 Secret。如需操作說明,請使用本教學課程中的範例應用程式,或參閱「Secret Manager 用戶端程式庫」。

清除所用資源

為避免因為本教學課程所用資源,導致系統向 Google Cloud 帳戶收取費用,請刪除含有相關資源的專案,或者保留專案但刪除個別資源。

刪除個別資源

  1. 刪除叢集:

    gcloud container clusters delete secret-cluster \
        --location=us-central1
    
  2. (選用) 刪除 Secret Manager 中的密鑰:

    gcloud secrets delete bq-readonly-key
    

    如果您未執行這個步驟,Secret 會自動過期,因為您在建立時設定了 --ttl 旗標。

刪除專案

    刪除 Google Cloud 專案:

    gcloud projects delete PROJECT_ID

後續步驟