为 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) 角色:

  • Security Center Admin (roles/securitycenter.Admin):用于启用 Security Command Center API 通知
  • Security Center Admin Viewer (roles/securitycenter.adminViewer):可在 Google Cloud 控制台中访问 Security Command Center
  • 如需在组织级层、文件夹级层或项目级层向通知服务账号或 gcloud CLI 账号授予角色,请使用以下角色之一:
    • Organization Administrator (roles/resourcemanager.organizationAdmin)
    • Folder IAM Admin (roles/resourcemanager.folderIamAdmin)
    • Project IAM Admin (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. 选择您要为其启用 Notifications 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 账号授予以下角色:

  • Security Center Admin (roles/securitycenter.admin) 或 Security Center Notification configurations Editor (roles/securitycenter.notificationConfigEditor)。您需要在创建 NotificationConfig 的同一级层(组织、文件夹或项目)授予此角色。
  • 针对要接收通知的 Pub/Sub 主题的 Pub/Sub Admin (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 账号授予具有所有 securitycenter.notification 权限的角色,例如 roles/securitycenter.notificationConfigEditorroles/securitycenter.admin。您可以在项目、文件夹或组织级层授予角色。

      如需在项目级层授予角色,请运行以下命令:

      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. 为要启用 Notifications 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. 向服务账号授予具有所有 securitycenter.notification 权限的角色,例如 roles/securitycenter.notificationConfigEditorroles/securitycenter.admin。您可以在项目、文件夹或组织级层授予角色。

    如需在项目级层授予角色,请运行以下命令:

       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. 安装 pip 以管理 Python 库安装。

  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

如需安装通知 API Go 依赖项,请下载 Go 库:

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

Node.js

在项目文件夹中,使用 npm 安装任何所需的 Notifications PI 依赖项:

  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:通知适用的资源层次结构中的范围,即 organizationfolderproject
  • PARENT_ID:父级组织、文件夹或项目的 ID,采用 organizations/123folders/456projects/789 格式指定。
  • LOCATION:如果启用了数据驻留,请指定要在其中创建通知的 Security Command Center 位置。生成的 notificationConfig 资源仅存储在此位置。系统仅会将在此位置发布的发现结果发送到 Pub/Sub。

    如果未启用数据驻留,则指定 --location 标志会使用 Security Command Center API v2 创建通知,并且该标志的唯一有效值为 global

  • NOTIFICATION_DESCRIPTION:不超过 1024 个字符的通知说明。

  • PUBSUB_TOPIC:将接收通知的 Pub/Sub 主题。其格式为 projects/PROJECT_ID/topics/TOPIC

  • FILTER:您定义的表达式,用于选择将哪些发现结果发送到 Pub/Sub。例如 state="ACTIVE"

Python

以下示例使用 v1 API。如需修改 v2 的示例,请将 v1 替换为 v2,并将 /locations/LOCATION 添加到资源名称中。

对于大多数资源,请在资源名称的 /PARENT/PARENT_ID 后添加 /locations/LOCATION,其中 PARENTorganizationsfoldersprojects

对于发现结果,请在资源名称的 /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 的示例,请将 v1 替换为 v2,并将 /locations/LOCATION 添加到资源名称中。

对于大多数资源,请在资源名称的 /PARENT/PARENT_ID 后添加 /locations/LOCATION,其中 PARENTorganizationsfoldersprojects

对于发现结果,请在资源名称的 /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 的示例,请将 v1 替换为 v2,并将 /locations/LOCATION 添加到资源名称中。

对于大多数资源,请在资源名称的 /PARENT/PARENT_ID 后添加 /locations/LOCATION,其中 PARENTorganizationsfoldersprojects

对于发现结果,请在资源名称的 /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 的示例,请将 v1 替换为 v2,并将 /locations/LOCATION 添加到资源名称中。

对于大多数资源,请在资源名称的 /PARENT/PARENT_ID 后添加 /locations/LOCATION,其中 PARENTorganizationsfoldersprojects

对于发现结果,请在资源名称的 /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 的示例,请将 v1 替换为 v2,并将 /locations/LOCATION 添加到资源名称中。

对于大多数资源,请在资源名称的 /PARENT/PARENT_ID 后添加 /locations/LOCATION,其中 PARENTorganizationsfoldersprojects

对于发现结果,请在资源名称的 /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 的示例,请将 v1 替换为 v2,并将 /locations/LOCATION 添加到资源名称中。

对于大多数资源,请在资源名称的 /PARENT/PARENT_ID 后添加 /locations/LOCATION,其中 PARENTorganizationsfoldersprojects

对于发现结果,请在资源名称的 /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 的示例,请将 v1 替换为 v2,并将 /locations/LOCATION 添加到资源名称中。

对于大多数资源,请在资源名称的 /PARENT/PARENT_ID 后添加 /locations/LOCATION,其中 PARENTorganizationsfoldersprojects

对于发现结果,请在资源名称的 /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 验证用户是否具有对 Pub/Sub 主题的 setIamPolicy 权限。

创建 NotificationConfig 之前

在完成创建 NotificationConfig 中的步骤之前,请执行以下操作:

  1. 转到 Google Cloud 控制台中的 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 特性
      • 来源下拉菜单中,选择所有来源
      • 身份下拉菜单中,选择选定的身份
      • 点击选择,然后输入用于调用 Security Command Center API 的主账号。
    • Google Cloud 服务/资源的 TO 属性
      • 项目下拉菜单中,选择选定的项目
      • 点击选择,然后输入 Pub/Sub 主题所属的项目。
      • 服务下拉菜单中,选择选定的服务,然后选择 Cloud Pub/Sub API
      • 方法下拉菜单中,选择所有操作
  7. 点击保存

  8. 在导航菜单中,点击出站流量政策

  9. 点击添加规则 (Add Rule)。

  10. 如需为用户或服务账号配置出站流量规则,请输入以下参数:

    • API 客户端的 FROM 特性
      • 身份下拉菜单中,选择选定的身份
      • 点击选择,然后输入用于调用 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 特性
      • 来源下拉菜单中,选择所有来源
      • 身份下拉菜单中,选择选定的身份
      • 点击选择,然后输入 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 主题。

后续步骤