建立及管理通知設定

本頁說明如何使用 Security Command Center API 通知功能,包括下列範例:

  • 建立 NotificationConfig
  • 取得 NotificationConfig
  • 更新 NotificationConfig
  • 刪除 NotificationConfig
  • 清單 NotificationConfig
  • 接收 Pub/Sub 通知

或者,您也可以在 Security Command Center 中設定 Pub/Sub 的持續匯出作業

事前準備

如要使用本頁的範例,請先完成設定尋找通知的指南。

如要執行下列範例,您需要具備適當權限的 Identity and Access Management (IAM) 角色:

  • 建立 NotificationConfig:安全中心通知設定編輯者 (roles/securitycenter.notificationConfigEditor)
  • 取得及列出 NotificationConfig:安全中心通知設定檢視者 (roles/securitycenter.notificationConfigViewer) 或安全中心通知設定編輯者 (roles/securitycenter.notificationConfigEditor)
  • 更新和刪除 NotificationConfig:安全中心通知設定編輯者 (roles/securitycenter.notificationConfigEditor)

如要將適當的角色授予存取 notificationConfig 的主體,您必須具備下列其中一個 IAM 角色:

  • 機構管理員 (roles/resourcemanager.organizationAdmin)
  • 資料夾 IAM 管理員 (roles/resourcemanager.folderIamAdmin)
  • 專案 IAM 管理員 (roles/resourcemanager.projectIamAdmin)

您可以在機構、資料夾或專案層級授予 Security Command Center 的 IAM 角色。您能否查看、編輯、建立或更新發現項目、資產和安全性來源,取決於您獲准的存取層級。如要進一步瞭解 Security Command Center 角色,請參閱存取權控管

資料落地和通知

如果 Security Command Center 已啟用資料落地,定義持續匯出至 Pub/Sub 的設定 (notificationConfig 資源) 會受到資料落地控管,並儲存在Security Command Center 位置

如要將 Security Command Center 位置中的發現項目匯出至 Pub/Sub,您必須在與發現項目相同的 Security Command Center 位置中,設定持續匯出功能。

由於持續匯出功能使用的篩選器可能包含受居住地控管的資料,因此請務必先指定正確位置,再建立篩選器。Security Command Center 不會限制您建立匯出作業的位置。

持續匯出作業只會儲存在建立時使用的位置,無法在其他位置查看或編輯。

建立連續匯出作業後,就無法變更位置。如要變更位置,請刪除持續匯出作業,然後在新位置重新建立。

如要瞭解啟用資料落地功能後如何使用 Security Command Center,請參閱「Security Command Center 區域端點」。

建立 NotificationConfig

如要建立 NotificationConfig,您必須具備下列條件:

  • 要傳送通知的現有 Pub/Sub 主題。
  • 建立 notificationConfig 的主體必須具備的 IAM 角色。

詳情請參閱設定發現項目通知指南中的設定 Pub/Sub 主題步驟。

建立 NotificationConfig 前,請注意每個機構可擁有的 NotificationConfig 檔案數量有限。詳情請參閱配額與限制

NotificationConfig 包含 filter 欄位,可將通知限制為實用事件。這個欄位接受 Security Command Center API findings.list 方法中提供的所有篩選器。

建立 NotificationConfig 時,您會從 Google Cloud 資源階層指定 NotificationConfig 的父項,可以是機構、資料夾或專案。如要日後擷取、更新或刪除 NotificationConfig,請在參照時一併提供父項機構、資料夾或專案的數值 ID。

在 Google Cloud 控制台中,部分NotificationConfig資源可能會顯示「舊版」標籤,表示這些資源是使用 v1 Security Command Center API 建立。您可以使用 Google Cloud 控制台、gcloud CLI、v1 版 Security Command Center API,或 Security Command Center 的 v1 版用戶端程式庫,管理這些 NotificationConfig 資源。

如要使用 gcloud CLI 管理這些 NotificationConfig 資源,執行 gcloud CLI 指令時不得指定位置。

如要使用所選語言或平台建立 NotificationConfig,請按照下列步驟操作:

gcloud

gcloud scc notifications create NOTIFICATION_NAME \
  --PARENT=PARENT_ID \
  --location=LOCATION \
  --description="NOTIFICATION_DESCRIPTION" \
  --pubsub-topic=PUBSUB_TOPIC \
  --filter="FILTER"

更改下列內容:

  • NOTIFICATION_NAME:通知名稱。 長度必須介於 1 至 128 個字元之間,而且只能使用英數字元、底線或連字號。
  • PARENT:通知適用的資源階層範圍,即 organizationfolderproject
  • PARENT_ID:父項機構、資料夾或專案的 ID,格式為 organizations/123folders/456projects/789
  • LOCATION: 要建立 NotificationConfigSecurity Command Center 位置。如果已啟用資料落地功能,請使用 euksaus;否則請使用 global 值。
  • NOTIFICATION_DESCRIPTION:通知說明,最多 1,024 個字元。
  • PUBSUB_TOPIC:將接收通知的 Pub/Sub 主題。格式為 projects/PROJECT_ID/topics/TOPIC
  • FILTER:您定義的運算式,用於選取要傳送至 Pub/Sub 的調查結果。例如:state=\"ACTIVE\"

Terraform

為機構建立 NotificationConfig

resource "google_pubsub_topic" "scc_v2_organization_notification_config" {
  name = "my-topic"
}

resource "google_scc_v2_organization_notification_config" "custom_organization_notification_config" {
  config_id    = "my-config"
  organization = "123456789"
  location     = "global"
  description  = "My custom Cloud Security Command Center Finding Organization Notification Configuration"
  pubsub_topic = google_pubsub_topic.scc_v2_organization_notification_config.id

  streaming_config {
    filter = "category = \"OPEN_FIREWALL\" AND state = \"ACTIVE\""
  }
}

為資料夾建立 NotificationConfig

resource "google_folder" "folder" {
  parent       = "organizations/123456789"
  display_name = "folder-name"
}

resource "google_pubsub_topic" "scc_v2_folder_notification_config" {
  name = "my-topic"
}

resource "google_scc_v2_folder_notification_config" "custom_notification_config" {
  config_id    = "my-config"
  folder       = google_folder.folder.folder_id
  location     = "global"
  description  = "My custom Cloud Security Command Center Finding Notification Configuration"
  pubsub_topic =  google_pubsub_topic.scc_v2_folder_notification_config.id

  streaming_config {
    filter = "category = \"OPEN_FIREWALL\" AND state = \"ACTIVE\""
  }
}

為專案建立 NotificationConfig

resource "google_pubsub_topic" "scc_v2_project_notification" {
  name = "my-topic"
}

resource "google_scc_v2_project_notification_config" "custom_notification_config" {
  config_id    = "my-config"
  project      = "my-project-name"
  location     = "global"
  description  = "My custom Cloud Security Command Center Finding Notification Configuration"
  pubsub_topic =  google_pubsub_topic.scc_v2_project_notification.id

  streaming_config {
    filter = "category = \"OPEN_FIREWALL\" AND state = \"ACTIVE\""
  }
}

Go

import (
	"context"
	"fmt"
	"io"

	securitycenter "cloud.google.com/go/securitycenter/apiv2"
	"cloud.google.com/go/securitycenter/apiv2/securitycenterpb"
)

func createNotificationConfig(w io.Writer, orgID string, pubsubTopic string, notificationConfigID string) error {
	// orgID := "your-org-id"
	// pubsubTopic := "projects/{your-project}/topics/{your-topic}"
	// notificationConfigID := "your-config-id"

	ctx := context.Background()
	client, err := securitycenter.NewClient(ctx)

	if err != nil {
		return fmt.Errorf("securitycenter.NewClient: %w", err)
	}
	defer client.Close()

	req := &securitycenterpb.CreateNotificationConfigRequest{
		// Parent must be in one of the following formats:
		//		"organizations/{orgId}/locations/global"
		//		"projects/{projectId}/locations/global"
		//		"folders/{folderId}/locations/global"
		Parent:   fmt.Sprintf("organizations/%s/locations/global", orgID),
		ConfigId: notificationConfigID,
		NotificationConfig: &securitycenterpb.NotificationConfig{
			Description: "Go sample config",
			PubsubTopic: pubsubTopic,
			NotifyConfig: &securitycenterpb.NotificationConfig_StreamingConfig_{
				StreamingConfig: &securitycenterpb.NotificationConfig_StreamingConfig{
					Filter: `state = "ACTIVE"`,
				},
			},
		},
	}

	notificationConfig, err := client.CreateNotificationConfig(ctx, req)
	if err != nil {
		return fmt.Errorf("Failed to create notification config: %w", err)
	}
	fmt.Fprintln(w, "New NotificationConfig created: ", notificationConfig)

	return nil
}

Java


package vtwo.notifications;

import com.google.cloud.securitycenter.v2.LocationName;
import com.google.cloud.securitycenter.v2.NotificationConfig;
import com.google.cloud.securitycenter.v2.SecurityCenterClient;
import java.io.IOException;

public class CreateNotification {

  public static void main(String[] args) throws IOException {
    // parentId: must be in one of the following formats:
    //    "organizations/{organization_id}"
    //    "projects/{project_id}"
    //    "folders/{folder_id}"
    String parentId = "{parent-id}";
    String topicName = "{your-topic}";
    String notificationConfigId = "{your-notification-id}";
    // Specify the location of the notification config.
    String location = "global";

    createNotificationConfig(parentId, location, topicName, notificationConfigId);
  }

  // Crete a notification config.
  // Ensure the ServiceAccount has the "pubsub.topics.setIamPolicy" permission on the new topic.
  public static NotificationConfig createNotificationConfig(
      String parentId, String location, String topicName, String notificationConfigId)
      throws IOException {
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests. After completing all of your requests, call
    // the "close" method on the client to safely clean up any remaining background resources.
    try (SecurityCenterClient client = SecurityCenterClient.create()) {

      String pubsubTopic = String.format("projects/%s/topics/%s", parentId, topicName);

      NotificationConfig notificationConfig = NotificationConfig.newBuilder()
          .setDescription("Java notification config")
          .setPubsubTopic(pubsubTopic)
          .setStreamingConfig(
              NotificationConfig.StreamingConfig.newBuilder().setFilter("state = \"ACTIVE\"")
                  .build())
          .build();

      NotificationConfig response = client.createNotificationConfig(
          LocationName.of(parentId, location), notificationConfig, notificationConfigId);

      System.out.printf("Notification config was created: %s%n", response);
      return response;
    }
  }
}

Node.js

// npm install '@google-cloud/security-center'
const {SecurityCenterClient} = require('@google-cloud/security-center').v2;
const uuidv1 = require('uuid').v1;

const client = new SecurityCenterClient();
/*
 *  Required. Resource name of the new notification config's parent. Its format
 *  is "organizations/[organization_id]/locations/[location_id]",
 *  "folders/[folder_id]/locations/[location_id]", or
 *  "projects/[project_id]/locations/[location_id]".
 */
const parent = `projects/${projectId}/locations/${location}`;

/**
 *  Required.
 *  Unique identifier provided by the client within the parent scope.
 *  It must be between 1 and 128 characters and contain alphanumeric
 *  characters, underscores, or hyphens only.
 */
const configId = 'notif-config-test-node-create-' + uuidv1();

// pubsubTopic = "projects/{your-project}/topics/{your-topic}";
const pubsubTopic = `projects/${projectId}/topics/${topicName}`;

/**
 *  Required. The notification config being created. The name and the service
 *  account will be ignored as they are both output only fields on this
 *  resource.
 */
const notificationConfig = {
  description: 'Sample config for node v2',
  pubsubTopic: pubsubTopic,
  streamingConfig: {filter: 'state = "ACTIVE"'},
};

// Build the request.
const createNotificationRequest = {
  parent: parent,
  configId: configId,
  notificationConfig: notificationConfig,
};

async function createNotificationConfig() {
  const [response] = await client.createNotificationConfig(
    createNotificationRequest
  );
  console.log('Notification configuration creation successful: %j', response);
}

await createNotificationConfig();

Python

def create_notification_config(
    parent_id, location_id, pubsub_topic, notification_config_id
) -> NotificationConfig:
    """
    This method is used to create the Notification Config.
    Args:
        parent_id: must be in one of the following formats:
            "organizations/{organization_id}"
            "projects/{project_id}"
            "folders/{folder_id}"
        location_id: "global"
        pubsub_topic: "projects/{your-project-id}/topics/{your-topic-id}"
        notification_config_id: "your-config-id"


    Ensure this ServiceAccount has the "pubsub.topics.setIamPolicy" permission on the new topic.
    """
    from google.cloud import securitycenter_v2 as securitycenter_v2

    client = securitycenter_v2.SecurityCenterClient()
    parent_id = parent_id + "/locations/" + location_id
    response = client.create_notification_config(
        request={
            "parent": parent_id,
            "config_id": notification_config_id,
            "notification_config": {
                "description": "Notification for active findings",
                "pubsub_topic": pubsub_topic,
                "streaming_config": {"filter": 'state = "ACTIVE"'},
            },
        }
    )
    print(f"create notification config response:{response}")
    return response

通知現在會發布至您指定的 Pub/Sub 主題。

系統會以 service-org-ORGANIZATION_ID@gcp-sa-scc-notification.iam.gserviceaccount.com 形式為您建立服務帳戶,以便發布通知。您首次建立 NotificationConfig 時,系統會建立這個服務帳戶,並在建立通知設定時,自動授予 PUBSUB_TOPIC 的 IAM 政策 securitycenter.notificationServiceAgent 角色。通知功能需要這個服務帳戶角色才能運作。

取得 NotificationConfig

如要取得 NotificationConfig,您必須具備含有 securitycenter.notification.get 權限的 IAM 角色。

gcloud

gcloud scc notifications describe NOTIFICATION_NAME \
  --PARENT_TYPE=PARENT_ID \
  --location=LOCATION

更改下列內容:

  • NOTIFICATION_NAME:通知設定的名稱。
  • PARENT_TYPE:指定設定的資源階層層級;請使用 organizationfolderproject
  • PARENT_ID:父項資源的數值 ID。
  • LOCATION: 要取得 NotificationConfigSecurity Command Center 位置;如果已啟用資料落地功能,請使用 euksaus;否則請使用 global 值。

更新 NotificationConfig

如要更新 NotificationConfig,您必須具備含有 securitycenter.notification.update 權限的 IAM 角色。

使用欄位遮罩更新時,系統只會更新您指定的欄位。如果您未使用欄位遮罩,NotificationConfig 中的所有可變動欄位都會由新值取代。您可以使用欄位遮罩更新 Pub/Sub 主題和說明。

如要完成這個範例,您必須訂閱新主題,且通知服務帳戶必須具備該主題的 pubsub.topics.setIamPolicy 權限。

授予必要權限後,請使用所選語言更新NotificationConfig說明、Pub/Sub 主題和篩選器:

gcloud

gcloud scc notifications update NOTIFICATION_NAME \
  --PARENT_TYPE=PARENT_ID \
  --location=LOCATION \
  --description="NOTIFICATION_DESCRIPTION" \
  --pubsub-topic=PUBSUB_TOPIC \
  --filter="FILTER"

更改下列內容:

  • NOTIFICATION_NAME:通知設定的名稱。
  • PARENT_TYPE:指定設定的資源階層層級;請使用 organizationfolderproject
  • PARENT_ID:父項資源的數值 ID。
  • LOCATION: 要更新 NotificationConfigSecurity Command Center 位置;如果已啟用資料落地功能,請使用 euksaus;否則請使用 global 值。
  • NOTIFICATION_DESCRIPTION:通知說明,最多 1,024 個字元。
  • PUBSUB_TOPIC:接收通知的 Pub/Sub 主題。格式為 projects/PROJECT_ID/topics/TOPIC
  • FILTER:您定義的運算式,用於選取要傳送至 Pub/Sub 的發現項目。例如:state="ACTIVE"

刪除 NotificationConfig

如要刪除 NotificationConfig,您必須具備含有 securitycenter.notification.delete 權限的 IAM 角色。

刪除 NotificationConfig 時,securitycenter.notificationServiceAgent 角色會保留在 Pub/Sub 主題中。如果您未在任何其他 NotificationConfig 中使用 Pub/Sub 主題,請從主題中移除角色。詳情請參閱存取權控管

使用所選語言刪除 NotificationConfig

gcloud

gcloud scc notifications delete NOTIFICATION_NAME \
  --PARENT_TYPE=PARENT_ID \
  --location=LOCATION

更改下列內容:

  • NOTIFICATION_NAME:通知設定的名稱。
  • PARENT_TYPE:指定設定的資源階層層級;請使用 organizationfolderproject
  • PARENT_ID:父項資源的數值 ID。
  • LOCATION: 要刪除 NotificationConfigSecurity Command Center 位置。如果已啟用資料落地功能,請使用 euksaus;否則請使用 global 值。

列出 NotificationConfig

如要列出 NotificationConfigs,您必須具備含有 securitycenter.notification.list 權限的 IAM 角色。

所有 Security Command Center API 清單都會分頁。每個回應都會傳回一頁結果和一個符記,用於傳回下一頁。預設 pageSize 為 10。您可以將頁面大小設為最少 1 個,最多 1000 個。

使用所選語言列出 NotificationConfigs

gcloud

gcloud scc notifications list PARENT_TYPE/PARENT_ID \
  --location=LOCATION

更改下列內容:

  • PARENT_TYPE:指定設定的資源階層層級;請使用 organizationsfoldersprojects
  • PARENT_ID:父項資源的數值 ID。
  • LOCATION: 列出 NotificationConfig 資源的Security Command Center 位置;如果已啟用資料落地設定,請使用 euksaus;否則請使用 global 值。

接收 Pub/Sub 通知

本節提供範例通知訊息,以及如何將 Pub/Sub 訊息轉換為包含發現項目的 NotificationMessage

通知會以 JSON 格式發布至 Pub/Sub。 以下是通知訊息範例:

{
   "notificationConfigName": "organizations/ORGANIZATION_ID/notificationConfigs/CONFIG_ID",
   "finding": {
     "name": "organizations/ORGANIZATION_ID/sources/SOURCE_ID/findings/FINDING_ID",
     "parent": "organizations/ORGANIZATION_ID/sources/SOURCE_ID",
     "state": "ACTIVE",
     "category": "TEST-CATEGORY",
     "securityMarks": {
       "name": "organizations/ORGANIZATION_ID/sources/SOURCE_ID/findings/FINDING_ID/securityMarks"
     },
     "eventTime": "2019-07-26T07:32:37Z",
     "createTime": "2019-07-29T18:45:27.243Z"
   }
 }

使用您選擇的語言,將 Pub/Sub 訊息轉換為 NotificationMessage

gcloud

gcloud CLI 不支援將 Pub/Sub 訊息轉換為 NotificationMessage。您可以使用 gcloud CLI 取得 NotificationMessage,並直接在終端機中列印 JSON

  # The subscription used to receive published messages from a topic
  PUBSUB_SUBSCRIPTION="projects/PROJECT_ID/subscriptions/SUBSCRIPTION_ID"

  gcloud pubsub subscriptions pull $PUBSUB_SUBSCRIPTION

更改下列內容:

  • PROJECT_ID 為您的專案 ID。
  • SUBSCRIPTION_ID 改成您的訂閱 ID。

Go

import (
	"bytes"
	"context"
	"fmt"
	"io"

	"cloud.google.com/go/pubsub"
	"cloud.google.com/go/securitycenter/apiv2/securitycenterpb"
	"github.com/golang/protobuf/jsonpb"
)

func receiveMessages(w io.Writer, projectID string, subscriptionName string) error {
	// projectID := "your-project-id"
	// subsriptionName := "your-subscription-name"

	ctx := context.Background()

	client, err := pubsub.NewClient(ctx, projectID)
	if err != nil {
		return fmt.Errorf("pubsub.NewClient: %w", err)
	}
	defer client.Close()

	sub := client.Subscription(subscriptionName)
	cctx, cancel := context.WithCancel(ctx)
	err = sub.Receive(cctx, func(ctx context.Context, msg *pubsub.Message) {
		var notificationMessage = new(securitycenterpb.NotificationMessage)
		jsonpb.Unmarshal(bytes.NewReader(msg.Data), notificationMessage)

		fmt.Fprintln(w, "Got finding: ", notificationMessage.GetFinding())
		msg.Ack()
		cancel()
	})
	if err != nil {
		return fmt.Errorf("Receive: %w", err)
	}

	return nil
}

後續步驟