Pub/Sub の検出結果の通知を有効にする

このページでは、Security Command Center API の通知を有効にする方法について説明します。

通知は、数分以内に、検出結果と検出結果の更新を Pub/Sub トピックに送信します。Security Command Center API の通知には、Security Command Center によって Google Cloud コンソールに表示されるすべての検出結果の情報が含まれます。

Pub/Sub の Security Command Center の通知は、直接 Cloud Functions のアクションに接続できます。レスポンス、拡充、改善に役立つ関数の例については、Cloud Functions コードの Security Command Center のオープンソース リポジトリをご覧ください。このリポジトリには、セキュリティに関する検出結果に対する自動処置に役立つソリューションが含まれています。

また、検出結果を BigQuery にエクスポートするか、Google Cloud コンソールで Pub/Sub の継続的エクスポートを設定することもできます。

始める前に

通知を設定して構成するには、次の Identity and Access Management(IAM)ロールが必要です。

  • セキュリティ センター管理者roles/securitycenter.Admin): Security Command Center API の通知を有効にします。
  • セキュリティ センター管理閲覧者roles/securitycenter.adminViewer): Google Cloud コンソールで Security Command Center にアクセスします。
  • 通知サービス アカウントまたは gcloud CLI アカウントに、組織レベル、フォルダレベル、プロジェクト レベルでロールを付与するために、次のいずれかのロール。
    • 組織管理者roles/resourcemanager.organizationAdmin
    • フォルダ IAM 管理者roles/resourcemanager.folderIamAdmin
    • プロジェクト IAM 管理者roles/resourcemanager.projectIamAdmin

Security Command Center の IAM ロールは、組織レベル、フォルダレベル、またはプロジェクト レベルで付与できます。検出結果、アセット、セキュリティ ソースを表示、編集、作成、更新する権限は、アクセス権が付与されているレベルによって異なります。Security Command Center のロールの詳細については、アクセス制御をご覧ください。

Security Command Center API の通知の設定

通知を設定するには、まず Security Command Center API を有効にします。

Security Command Center API の有効化

Security Command Center API を有効にするには、次のようにします。

  1. Google Cloud コンソールで [API ライブラリ] ページに移動します。

    [API ライブラリ] に移動

  2. 通知 API を有効にするプロジェクトを選択します。

  3. [検索] ボックスに「Security Command Center」と入力し、検索結果で [Security Command Center] をクリックします。

  4. 表示された API ページで [有効にする] をクリックします。

プロジェクトで Security Command Center API が有効になります。次に、gcloud CLI かクライアント ライブラリを使用して Pub/Sub トピックをサブスクライブし、権限を設定します。

データ所在地と通知

Security Command Center でデータ所在地が有効になっている場合、Pub/Sub(notificationConfig リソース)への継続的なエクスポートを定義する構成はデータの対象であり、Security Command Center のロケーションに保存されます。

Security Command Center のロケーションの検出結果を Pub/Sub にエクスポートするには、検出結果と同じ Security Command Center のロケーションに継続的なエクスポートを構成する必要があります。

継続的なエクスポートで使用されるフィルタには、所在地管理の対象となるデータが含まれる可能性があるため、作成する前に正しいロケーションを指定していることを確認してください。Security Command Center では、エクスポートを作成するロケーションは制限されません。

継続的エクスポートは作成場所にのみ保存され、他のロケーションで表示や編集はできません。

継続的なエクスポートを作成した後に、そのロケーションを変更することはできません。ロケーションを変更するには、継続的なエクスポートを削除して、新しいロケーションに再作成する必要があります。

API 呼び出しを使用して継続的なエクスポートを取得するには、notificationConfig の完全なリソース名でロケーションを指定する必要があります。次に例を示します。

GET https://securitycenter.googleapis.com/v2/{name=organizations/123/locations/eu/notificationConfigs/my-pubsub-export-01}

同様に、gcloud CLI を使用して継続的なエクスポートを取得するには、構成の完全なリソース名または --locations フラグを使用してロケーションを指定する必要があります。次に例を示します。

gcloud scc notifications describe myContinuousExport organizations/123 \
    --location=locations/us

Pub/Sub トピックの設定

この手順では、通知を送信する Pub/Sub トピックを作成してサブスクライブします。プログラムで API を呼び出す必要がない場合は、gcloud CLI コマンドをおすすめします。

gcloud

gcloud CLI を使用して Security Command Center API の通知機能を設定するには、次の手順を行います。

  1. Pub/Sub トピックとサブスクリプションを設定する。
  2. gcloud CLI アカウントの権限を設定する。

ステップ 1: Pub/Sub を設定する

Pub/Sub トピックを設定して登録するには、次のようにします。

  1. Google Cloud コンソールに移動します。

    Google Cloud コンソールに移動

  2. Security Command Center API を有効にしたプロジェクトを選択します。

  3. [Cloud Shell をアクティブにする] をクリックします。

  4. 新しい Pub/Sub トピックを作成するか、既存のトピックを使用するには、次のコマンドを実行します。

      gcloud pubsub topics create TOPIC_ID
    

    TOPIC_ID は、トピック名に置き換えます。

  5. トピック ID の環境変数を設定します。

      export TOPIC_ID=TOPIC_ID
    
  6. トピックへのサブスクリプションを作成します。

      gcloud pubsub subscriptions create SUBSCRIPTION_ID --topic TOPIC_ID
    

    SUBSCRIPTION_ID は、サブスクリプション名に置き換えます。

Pub/Sub の設定に関する詳細は、トピックとサブスクリプションの管理をご覧ください。

次に、アカウントの権限を設定します。

ステップ 2: gcloud CLI のアカウント権限を設定する

NotificationConfig を作成するには、gcloud CLI アカウントに次のロールを付与する必要があります。

  • セキュリティ センター管理者roles/securitycenter.admin)またはセキュリティ センター通知構成編集者roles/securitycenter.notificationConfigEditor)。このロールは、NotificationConfig を作成するレベル(組織、フォルダ、プロジェクト)で付与する必要があります。
  • 通知を受け取る Pub/Sub トピックに対する Pub/Sub 管理者roles/pubsub.admin

通知は、組織、フォルダ、またはプロジェクト レベルで受け取ります。

これらの権限を付与するには、次のようにします。

  1. Google Cloud コンソールに移動します。

    Google Cloud コンソールに移動

  2. Security Command Center API を有効にしたプロジェクトを選択します。

  3. [Cloud Shell をアクティブにする] をクリックします。

    1. 組織名を設定します。

      export ORGANIZATION_ID=ORGANIZATION_ID
      

      ORGANIZATION_ID は実際の組織 ID に置き換えます。

    2. Pub/Sub トピックが属するプロジェクトのプロジェクト ID を設定します。

      export PUBSUB_PROJECT=PROJECT_ID
      

      PROJECT_ID を実際のプロジェクト ID に置き換えます。

    3. 使用している gcloud CLI アカウントを設定します。

      export GCLOUD_ACCOUNT=EMAIL
      

      EMAIL は、gcloud CLI コマンドを実行するアカウントのメールアドレスに置き換えます。

    4. トピック ID を設定するか、以前に設定したトピックを使用します。

      export TOPIC_ID=TOPIC_ID
      

      TOPIC_ID は、トピック名に置き換えます。

    5. gcloud CLI アカウントに、pubsub.topics.setIamPolicy 権限がある Pub/Sub ロールを付与します。

      gcloud pubsub topics add-iam-policy-binding \
        projects/$PUBSUB_PROJECT/topics/$TOPIC_ID \
        --member="user:$GCLOUD_ACCOUNT" \
        --role='roles/pubsub.admin'
      
    6. gcloud CLI アカウントに、roles/securitycenter.notificationConfigEditorroles/securitycenter.admin など、すべての securitycenter.notification 権限を含むロールを付与します。このロールは、プロジェクト、フォルダ、または組織レベルで付与できます。

      プロジェクト レベルでロールを付与するには:

      gcloud projects add-iam-policy-binding PROJECT_ID \
      --member="user:$GCLOUD_ACCOUNT" \
      --role='ROLE_NAME'
      

      次のように置き換えます。

      • PROJECT_ID: Security Command Center が有効になっているプロジェクトの ID
      • ROLE_NAME: 割り当てられるロール

      組織レベルでロールを付与するには:

      gcloud organizations add-iam-policy-binding $ORGANIZATION_ID \
        --member="user:$GCLOUD_ACCOUNT" \
        --role='ROLE_NAME'
      

      ROLE_NAME は、付与するロールに置き換えます。

次に、NotificationConfig を作成します。

クライアント ライブラリ

クライアント ライブラリを使用して Security Command Center API 通知機能を設定するには、次の手順を行います。

  1. サービス アカウントを設定する。
  2. API クライアント ライブラリをダウンロードする。
  3. 開発環境を設定する。
  4. Pub/Sub トピックとサブスクリプションを設定する。

ステップ 1: サービス アカウントを設定する

Security Command Center API の通知機能は、適切な権限を持つサービス アカウントを使用して通知を構成します。このサービス アカウントは、構成ファイルの初期設定にのみ使用します。後で、追加の通知構成ファイルを作成するために再利用することもできます。このサービス アカウントは、Security Command Center を設定する際に作成したサービス アカウントとは別のものです。

サービス アカウントを作成するには、次のようにします。

  1. Google Cloud コンソールに移動します。

    Google Cloud コンソールに移動

  2. Security Command Center API を有効にしたプロジェクトを選択します。

  3. [Cloud Shell をアクティブにする] をクリックします。

  4. 環境変数を設定します。

    1. 組織名を設定します。

        export ORGANIZATION_ID=ORGANIZATION_ID
      

      ORGANIZATION_ID は実際の組織 ID に置き換えます。

    2. 通知 API を有効にするプロジェクトのプロジェクト ID を設定します。

        export PROJECT_ID=PROJECT_ID
      

      PROJECT_ID を実際のプロジェクト ID に置き換えます。

    3. 新しいサービス アカウントに使用するカスタム ID を設定します(scc-notifications など)。サービス アカウント名は 6~30 文字で、英字で始まり、英小文字、数字、ハイフンで構成します。

        export SERVICE_ACCOUNT=CUSTOM_ID
      

      CUSTOM_ID は、サービス アカウントのカスタム名に置き換えます。

    4. サービス アカウント キーを保存するパスを設定します(export KEY_LOCATION=/home/$USER/mykeys/$SERVICE_ACCOUNT.jsonなど)。

        export KEY_LOCATION=FULL_KEY_LOCATION_PATH
        # This is used by client libraries to find the key
        export GOOGLE_APPLICATION_CREDENTIALS=$KEY_LOCATION
      

      FULL_KEY_LOCATION_PATH は、サービス アカウント キーのフルパスに置き換えます。

  5. プロジェクト ID に関連付けられたサービス アカウントを作成します。

       gcloud iam service-accounts create $SERVICE_ACCOUNT  --display-name \
        "Service Account for [USER]"  --project $PROJECT_ID
    
  6. サービス アカウントに関連付ける鍵を作成します。この鍵は NotificationConfig の作成時に使用され、前の手順で指定した KEY_LOCATION に永続的に保存されます。

       gcloud iam service-accounts keys create $KEY_LOCATION  --iam-account \
        $SERVICE_ACCOUNT@$PROJECT_ID.iam.gserviceaccount.com
    
  7. サービス アカウントに、roles/securitycenter.notificationConfigEditorroles/securitycenter.admin など、すべての securitycenter.notification 権限を含むロールを付与します。このロールは、プロジェクト、フォルダ、または組織レベルで付与できます。

    プロジェクト レベルでロールを付与するには:

       gcloud projects add-iam-policy-binding $PROJECT_ID \
         --member="serviceAccount:$SERVICE_ACCOUNT@$PROJECT_ID.iam.gserviceaccount.com" \
         --role='ROLE_NAME'
    

    ROLE_NAME は、付与するロールに置き換えます。

    組織レベルでロールを付与するには:

       gcloud organizations add-iam-policy-binding $ORGANIZATION_ID \
         --member="serviceAccount:$SERVICE_ACCOUNT@$PROJECT_ID.iam.gserviceaccount.com" \
         --role='ROLE_NAME'
    

    ROLE_NAME は、付与するロールに置き換えます。

これで、通知で使用できるようにサービス アカウントが設定され、サービス アカウント キーが指定した KEY_LOCATION に保存されました。サービス アカウントの詳細については、サービス アカウントキーの作成と管理をご覧ください。

ステップ 2: 開発環境を設定する

Security Command Center API の通知機能を使用するには、gcloud CLI を使用するか、クライアント ライブラリをダウンロードして、選択した言語で開発環境を設定します。

Python

  1. 省略可: Python ライブラリをインストールする前に、Virtualenv を使用して、隔離された Python 環境を作成することをおすすめします。

     virtualenv YOUR_ENV
     source YOUR_ENV/bin/activate
    

    YOUR_ENV は、仮想環境の名前に置き換えます。

  2. Python ライブラリのインストールを管理するために、pip をインストールします。

  3. 次のコマンドを実行して、Python ライブラリをインストールします。

     pip install google-cloud-securitycenter
    

Java

Security Command Center の Java ライブラリを依存関係としてプロジェクトに含めるには、Maven リポジトリからアーティファクトを選択します。通知は、ライブラリ バージョン 0.119.0 以降に含まれています。

Intellij を使用している場合は、GOOGLE_APPLICATION_CREDENTIALS 環境変数を、前の手順でダウンロードした通知サービス アカウントキーの絶対パスに設定します。

  1. Intellij で、[実行] > [構成を編集] の順にクリックします。
  2. [アプリケーション] > [Run_Configuration_For_Sample] > [環境変数] で次の変数を設定します。

      GOOGLE_APPLICATION_CREDENTIALS=ABSOLUTE_PATH_TO_SERVICE_ACCOUNT_KEY
    

    ABSOLUTE_PATH_TO_SERVICE_ACCOUNT_KEY は、サービス アカウント キーのフルパスに置き換えます。

Go

Notifications API Go の依存関係をインストールするには、Go ライブラリをダウンロードします。

  go get cloud.google.com/go/securitycenter/apiv1

Node.js

プロジェクト フォルダで、npm を使用して必要な通知 API の依存関係をインストールします。

  npm install --save @google-cloud/security-center/

ステップ 3: Pub/Sub を設定する

Pub/Sub に通知を配信するには、Pub/Sub トピックをサブスクライブし、通知サービス アカウントに pubsub.topics.setIamPolicy 権限を含む IAM ロールを付与します。

  1. 新しい Pub/Sub トピックを作成するか、既存のトピックを使用します。

       gcloud pubsub topics create TOPIC_ID
    

    TOPIC_ID は、トピック ID に置き換えます。

  2. 環境変数を設定します。

    1. トピック ID を設定します。

        export TOPIC_ID=TOPIC_ID
      
    2. 通知 API を有効にしたプロジェクトのプロジェクト ID を設定します。

        export CONSUMER_PROJECT=PROJECT_ID
      

      PROJECT_ID を実際のプロジェクト ID に置き換えます。

    3. 前の手順で作成したサービス アカウントのメールを設定します。

        export SERVICE_ACCOUNT_EMAIL=SERVICE_ACCOUNT_NAME@$CONSUMER_PROJECT.iam.gserviceaccount.com
      

      SERVICE_ACCOUNT_NAME は、サービス アカウントの名前に置き換えます。

  3. トピックへのサブスクリプションを作成します。

       gcloud pubsub subscriptions create SUBSCRIPTION_ID --topic TOPIC_ID
    

    SUBSCRIPTION_ID は、サブスクリプション ID に置き換えます。

  4. 通知サービス アカウントに、pubsub.topics.setIamPolicy 権限を含むロールを付与します。

    gcloud pubsub topics add-iam-policy-binding \
         projects/$CONSUMER_PROJECT/topics/$TOPIC_ID \
      --member="serviceAccount:$SERVICE_ACCOUNT_EMAIL" \
      --role='roles/pubsub.admin'
    

Pub/Sub の設定に関する詳細は、トピックとサブスクリプションの管理をご覧ください。次のステップでは、NotificationConfig を作成して設定を完了します。

NotificationConfig の作成

NotificationConfig を作成する前に、各組織で保持できる NotificationConfig ファイルの数に上限があることを確認してください。詳細については、割り当てと上限をご覧ください。

NotificationConfig には、通知を有用なイベントに限定する filter フィールドが含まれています。このフィールドは、Security Command Center API の findings.list メソッドで使用できるすべてのフィルタを受け入れます。

NotificationConfig を作成する場合は、Google Cloud リソース階層(組織、フォルダ、プロジェクトのいずれか)から NotificationConfig の親を指定します。後で NotificationConfig を取得、更新、削除する必要がある場合は、参照時に親の組織、フォルダ、またはプロジェクトの数値 ID を指定する必要があります。

任意の言語やプラットフォームを使用して 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: 通知が適用されるリソース階層内の範囲(organizationfolder、または project)。
  • PARENT_ID: 親組織、フォルダ、またはプロジェクトの ID。organizations/123folders/456projects/789 の形式で指定します。
  • LOCATION: データ所在地が有効になっている場合は、通知を作成する Security Command Center のロケーションを指定します。結果の notificationConfig リソースは、この場所にのみ保存されます。このロケーションで発行された検出結果のみが Pub/Sub に送信されます。

    データ所在地が有効になっていない場合、--location フラグを指定すると、Security Command Center API v2 を使用して通知が作成されます。フラグの有効な値は global のみです。

  • NOTIFICATION_DESCRIPTION: 通知の説明(1,024 文字以内)。

  • PUBSUB_TOPIC: 通知を受け取る Pub/Sub トピック。形式は projects/PROJECT_ID/topics/TOPIC です。

  • FILTER: Pub/Sub に送信する検出結果を選択するために定義する式。例: state="ACTIVE"

Python

次のサンプルでは、v1 API を使用します。v2 のサンプルを変更するには、v1v2 に置き換え、/locations/LOCATION をリソース名に追加します。

ほとんどのリソースでは、/PARENT/PARENT_ID の後に /locations/LOCATION をリソース名に追加します。ここで、PARENTorganizationsfolders、または projects です。

検出結果の場合は、/sources/SOURCE_ID の後に /locations/LOCATION をリソース名に追加します。ここで、SOURCE_ID は、検出結果を発行した Security Command Center サービスの ID です。

def create_notification_config(parent_id, notification_config_id, pubsub_topic):
    """
    Args:
        parent_id: must be in one of the following formats:
            "organizations/{organization_id}"
            "projects/{project_id}"
            "folders/{folder_id}"
        notification_config_id: "your-config-id"
        pubsub_topic: "projects/{your-project-id}/topics/{your-topic-ic}"

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

    client = securitycenter.SecurityCenterClient()

    created_notification_config = 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(created_notification_config)

Java

次のサンプルでは、v1 API を使用します。v2 のサンプルを変更するには、v1v2 に置き換え、/locations/LOCATION をリソース名に追加します。

ほとんどのリソースでは、/PARENT/PARENT_ID の後に /locations/LOCATION をリソース名に追加します。ここで、PARENTorganizationsfolders、または projects です。

検出結果の場合は、/sources/SOURCE_ID の後に /locations/LOCATION をリソース名に追加します。ここで、SOURCE_ID は、検出結果を発行した Security Command Center サービスの ID です。


import com.google.cloud.securitycenter.v1.CreateNotificationConfigRequest;
import com.google.cloud.securitycenter.v1.NotificationConfig;
import com.google.cloud.securitycenter.v1.NotificationConfig.StreamingConfig;
import com.google.cloud.securitycenter.v1.SecurityCenterClient;
import java.io.IOException;

public class CreateNotificationConfigSnippets {

  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 = String.format("organizations/%s", "ORG_ID");
    String notificationConfigId = "{config-id}";
    String projectId = "{your-project}";
    String topicName = "{your-topic}";

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

  // Crete a notification config.
  // Ensure the ServiceAccount has the "pubsub.topics.setIamPolicy" permission on the new topic.
  public static NotificationConfig createNotificationConfig(
      String parentId, String notificationConfigId, String projectId, String topicName)
      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()) {

      // Ensure this ServiceAccount has the "pubsub.topics.setIamPolicy" permission on the topic.
      String pubsubTopic = String.format("projects/%s/topics/%s", projectId, topicName);

      CreateNotificationConfigRequest request =
          CreateNotificationConfigRequest.newBuilder()
              .setParent(parentId)
              .setConfigId(notificationConfigId)
              .setNotificationConfig(
                  NotificationConfig.newBuilder()
                      .setDescription("Java notification config")
                      .setPubsubTopic(pubsubTopic)
                      .setStreamingConfig(
                          StreamingConfig.newBuilder().setFilter("state = \"ACTIVE\"").build())
                      .build())
              .build();

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

Go

次のサンプルでは、v1 API を使用します。v2 のサンプルを変更するには、v1v2 に置き換え、/locations/LOCATION をリソース名に追加します。

ほとんどのリソースでは、/PARENT/PARENT_ID の後に /locations/LOCATION をリソース名に追加します。ここで、PARENTorganizationsfolders、または projects です。

検出結果の場合は、/sources/SOURCE_ID の後に /locations/LOCATION をリソース名に追加します。ここで、SOURCE_ID は、検出結果を発行した Security Command Center サービスの ID です。

import (
	"context"
	"fmt"
	"io"

	securitycenter "cloud.google.com/go/securitycenter/apiv1"
	"cloud.google.com/go/securitycenter/apiv1/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}"
		//		"projects/{projectId}"
		//		"folders/{folderId}"
		Parent:   fmt.Sprintf("organizations/%s", 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
}

Node.js

次のサンプルでは、v1 API を使用します。v2 のサンプルを変更するには、v1v2 に置き換え、/locations/LOCATION をリソース名に追加します。

ほとんどのリソースでは、/PARENT/PARENT_ID の後に /locations/LOCATION をリソース名に追加します。ここで、PARENTorganizationsfolders、または projects です。

検出結果の場合は、/sources/SOURCE_ID の後に /locations/LOCATION をリソース名に追加します。ここで、SOURCE_ID は、検出結果を発行した Security Command Center サービスの ID です。

// npm install '@google-cloud/security-center'
const {SecurityCenterClient} = require('@google-cloud/security-center');

const client = new SecurityCenterClient();

// parent: must be in one of the following formats:
//    `organizations/${organization_id}`
//    `projects/${project_id}`
//    `folders/${folder_id}`
// configId = "your-config-name";
// pubsubTopic = "projects/{your-project}/topics/{your-topic}";
// Ensure this Service Account has the "pubsub.topics.setIamPolicy" permission on this topic.
const parent = `organizations/${organizationId}`;

async function createNotificationConfig() {
  const [response] = await client.createNotificationConfig({
    parent: parent,
    configId: configId,
    notificationConfig: {
      description: 'Sample config for node.js',
      pubsubTopic: pubsubTopic,
      streamingConfig: {filter: 'state = "ACTIVE"'},
    },
  });
  console.log('Notification config creation succeeded: ', response);
}

createNotificationConfig();

PHP

次のサンプルでは、v1 API を使用します。v2 のサンプルを変更するには、v1v2 に置き換え、/locations/LOCATION をリソース名に追加します。

ほとんどのリソースでは、/PARENT/PARENT_ID の後に /locations/LOCATION をリソース名に追加します。ここで、PARENTorganizationsfolders、または projects です。

検出結果の場合は、/sources/SOURCE_ID の後に /locations/LOCATION をリソース名に追加します。ここで、SOURCE_ID は、検出結果を発行した Security Command Center サービスの ID です。

use Google\Cloud\SecurityCenter\V1\Client\SecurityCenterClient;
use Google\Cloud\SecurityCenter\V1\CreateNotificationConfigRequest;
use Google\Cloud\SecurityCenter\V1\NotificationConfig;
use Google\Cloud\SecurityCenter\V1\NotificationConfig\StreamingConfig;

/**
 * @param string $organizationId        Your org ID
 * @param string $notificationConfigId  A unique identifier
 * @param string $projectId             Your Cloud Project ID
 * @param string $topicName             Your topic name
 */
function create_notification(
    string $organizationId,
    string $notificationConfigId,
    string $projectId,
    string $topicName
): void {
    $securityCenterClient = new SecurityCenterClient();
    // 'parent' must be in one of the following formats:
    //		"organizations/{orgId}"
    //		"projects/{projectId}"
    //		"folders/{folderId}"
    $parent = $securityCenterClient::organizationName($organizationId);
    $pubsubTopic = $securityCenterClient::topicName($projectId, $topicName);

    $streamingConfig = (new StreamingConfig())->setFilter('state = "ACTIVE"');
    $notificationConfig = (new NotificationConfig())
        ->setDescription('A sample notification config')
        ->setPubsubTopic($pubsubTopic)
        ->setStreamingConfig($streamingConfig);
    $createNotificationConfigRequest = (new CreateNotificationConfigRequest())
        ->setParent($parent)
        ->setConfigId($notificationConfigId)
        ->setNotificationConfig($notificationConfig);

    $response = $securityCenterClient->createNotificationConfig($createNotificationConfigRequest);
    printf('Notification config was created: %s' . PHP_EOL, $response->getName());
}

Ruby

次のサンプルでは、v1 API を使用します。v2 のサンプルを変更するには、v1v2 に置き換え、/locations/LOCATION をリソース名に追加します。

ほとんどのリソースでは、/PARENT/PARENT_ID の後に /locations/LOCATION をリソース名に追加します。ここで、PARENTorganizationsfolders、または projects です。

検出結果の場合は、/sources/SOURCE_ID の後に /locations/LOCATION をリソース名に追加します。ここで、SOURCE_ID は、検出結果を発行した Security Command Center サービスの ID です。

require "google/cloud/security_center"

# Your organization id. e.g. for "organizations/123", this would be "123".
# org_id = "YOUR_ORGANZATION_ID"

# Your notification config id. e.g. for
# "organizations/123/notificationConfigs/my-config" this would be "my-config".
# config_id = "YOUR_CONFIG_ID"

# The PubSub topic where notifications will be published.
# pubsub_topic = "YOUR_TOPIC"

client = Google::Cloud::SecurityCenter.security_center

# You can also use 'project_id' or 'folder_id' as a parent.
# client.project_path project: project_id
# client.folder_path folder: folder_id
parent = client.organization_path organization: org_id

notification_config = {
  description:      "Sample config for Ruby",
  pubsub_topic:     pubsub_topic,
  streaming_config: { filter: 'state = "ACTIVE"' }
}

response = client.create_notification_config(
  parent:              parent,
  config_id:           config_id,
  notification_config: notification_config
)
puts "Created notification config #{config_id}: #{response}."

C#

次のサンプルでは、v1 API を使用します。v2 のサンプルを変更するには、v1v2 に置き換え、/locations/LOCATION をリソース名に追加します。

ほとんどのリソースでは、/PARENT/PARENT_ID の後に /locations/LOCATION をリソース名に追加します。ここで、PARENTorganizationsfolders、または projects です。

検出結果の場合は、/sources/SOURCE_ID の後に /locations/LOCATION をリソース名に追加します。ここで、SOURCE_ID は、検出結果を発行した Security Command Center サービスの ID です。


using Google.Api.Gax.ResourceNames;
using Google.Cloud.SecurityCenter.V1;
using System;

///<summary> Create NotificationConfig Snippet. </summary>
public class CreateNotificationConfigSnippets
{
    public static NotificationConfig CreateNotificationConfig(
        string organizationId, string notificationConfigId, string projectId, string topicName)
    {
        // You can also use 'projectId' or 'folderId' instead of the 'organizationId'.
        //      ProjectName projectName = new ProjectName(projectId);
        //      FolderName folderName = new FolderName(folderId);
        OrganizationName orgName = new OrganizationName(organizationId);
        TopicName pubsubTopic = new TopicName(projectId, topicName);

        SecurityCenterClient client = SecurityCenterClient.Create();
        CreateNotificationConfigRequest request = new CreateNotificationConfigRequest
        {
            ParentAsOrganizationName = orgName,
            ConfigId = notificationConfigId,
            NotificationConfig = new NotificationConfig
            {
                Description = ".Net notification config",
                PubsubTopicAsTopicName = pubsubTopic,
                StreamingConfig = new NotificationConfig.Types.StreamingConfig { Filter = "state = \"ACTIVE\"" }
            }
        };

        NotificationConfig response = client.CreateNotificationConfig(request);
        Console.WriteLine($"Notification config was created: {response}");
        return response;
    }
}

これで、指定した Pub/Sub トピックに通知がパブリッシュされるようになりました。

通知をパブリッシュするため、サービス アカウントが service-org-ORGANIZATION_ID@gcp-sa-scc-notification.iam.gserviceaccount.com の形式で作成されます。このサービス アカウントは、最初の NotificationConfig を作成するときに作成され、通知構成の作成時に PUBSUB_TOPIC の IAM ポリシーに対する securitycenter.notificationServiceAgent ロールが自動的に付与されます。通知が機能するには、このサービス アカウントのロールが必要です。

VPC Service Controls で境界へのアクセス権を付与する

VPC Service Controls を使用していて、Pub/Sub トピックがサービス境界内のプロジェクトに含まれている場合、通知を作成するにはプロジェクトへのアクセス権を付与する必要があります。

プロジェクトへのアクセス権を付与するには、通知の作成に使用するプリンシパルとプロジェクトに上り(内向き)ルールと下り(外向き)ルールを作成します。このルールは、保護されたリソースへのアクセスを許可し、ユーザーが Pub/Sub トピックに対する setIamPolicy 権限を持っていることを Pub/Sub で確認できるようにします。

NotificationConfig を作成する前に

NotificationConfig の作成の手順を完了する前に、次の手順を行います。

  1. Google Cloud Console の [VPC Service Controls] ページに移動します。

    [VPC Service Controls] に移動

  2. 必要に応じて組織を選択します。

  3. 変更するサービス境界の名前をクリックします。

    変更する必要があるサービス境界を確認するには、ログで RESOURCES_NOT_IN_SAME_SERVICE_PERIMETER 違反を示すエントリを確認します。これらのエントリで、servicePerimeterName フィールド accessPolicies/ACCESS_POLICY_ID/servicePerimeters/SERVICE_PERIMETER_NAME を確認します。

  4. [境界を編集] をクリックします。

  5. ナビゲーション メニューで、[上り(内向き)ポリシー] をクリックします。

  6. ユーザーやサービス アカウントの上り(内向き)ルールを構成するには、次のパラメータを使用します。

    • API クライアントの FROM 属性:
      • [ソース] プルダウン メニューで、[すべてのソース] を選択します。
      • [ID] プルダウン メニューで [選択した ID] を選択します。
      • [選択] をクリックして、Security Command Center API の呼び出しに使用するプリンシパルを入力します。
    • Google Cloud サービス / リソースの TO 属性:
      • [プロジェクト] プルダウン メニューで、[選択したプロジェクト] を選択します。
      • [選択] をクリックしてから、Pub/Sub トピックを含むプロジェクトを入力します。
      • [サービス] プルダウン メニューで [選択したサービス]、[Cloud Pub/Sub API] の順に選択します。
      • [メソッド] プルダウン メニューで、[すべてのアクション] を選択します。
  7. [保存] をクリックします。

  8. ナビゲーション メニューで、[下り(外向き)ポリシー] をクリックします。

  9. [Add Rule] をクリックします。

  10. ユーザー アカウントやサービス アカウントの下り(外向き)ルールを構成するには、次のパラメータを入力します。

    • API クライアントの FROM 属性:
      • [ID] プルダウン メニューで [選択した ID] を選択します。
      • [選択] をクリックして、Security Command Center API の呼び出しに使用するプリンシパルを入力します。
    • Google Cloud サービス / リソースの TO 属性:
      • [プロジェクト] プルダウン メニューで、[すべてのプロジェクト] を選択します。
      • [サービス] プルダウン メニューで [選択したサービス]、[Cloud Pub/Sub API] の順に選択します。
      • [メソッド] プルダウン メニューで、[すべてのアクション] を選択します。
  11. [保存] をクリックします。

NotificationConfig の上り(内向き)ルールを作成する

NotificationConfig の上り(内向き)ルールを作成するには、次のようにします。

  1. NotificationConfig の作成の手順を完了します。
  2. 前のセクションのサービス境界を再度開きます。
  3. [上り(内向き)ポリシー] をクリックします。
  4. [Add Rule] をクリックします。
  5. 作成した NotificationConfig サービス アカウントの上り(内向き)ルールを構成するには、次のパラメータを入力します。
    • API クライアントの FROM 属性:
      • [ソース] プルダウン メニューで、[すべてのソース] を選択します。
      • [ID] プルダウン メニューで [選択した ID] を選択します。
      • [選択] をクリックして、NotificationConfig サービス アカウントの名前「service-org-ORGANIZATION_ID@gcp-sa-scc-notification.iam.gserviceaccount.com」を入力します。
    • GCP サービス / リソースの TO 属性:
      • [プロジェクト] プルダウン メニューで、[選択したプロジェクト] を選択します。
      • [選択] をクリックしてから、Pub/Sub トピックを含むプロジェクトを選択します。
      • [サービス] プルダウン メニューで [選択したサービス]、[Cloud Pub/Sub API] の順に選択します。
      • [メソッド] プルダウン メニューで、[すべてのアクション] を選択します。
  6. ナビゲーション メニューで、[保存] をクリックします。

これで、選択したプロジェクト、ユーザー、サービス アカウントが保護されたリソースにアクセスし、通知を作成できるようになりました。

このガイドの手順をすべて完了していて、通知が正しく機能している場合、次のルールは削除できます。

  • プリンシパルの上り(内向き)ルール
  • プリンシパルの下り(外向き)ルール

これらのルールは、NotificationConfig を構成するためだけに必要でした。ただし、通知が引き続き機能するには、NotificationConfig の上り(内向き)ルールは維持する必要があります。このルールによって、サービス境界の背後にある Pub/Sub トピックに通知をパブリッシュできます。

次のステップ