Membuat dan mengelola Konfigurasi Notifikasi

Halaman ini menjelaskan cara menggunakan fitur notifikasi Security Command Center API, termasuk contoh berikut:

  • Membuat NotificationConfig
  • Dapatkan NotificationConfig
  • Mengupdate NotificationConfig
  • Menghapus NotificationConfig
  • Mencantumkan NotificationConfig
  • Menerima notifikasi Pub/Sub

Atau, Anda dapat menyiapkan ekspor berkelanjutan untuk Pub/Sub di Security Command Center.

Sebelum memulai

Untuk menggunakan contoh di halaman ini, Anda harus menyelesaikan panduan untuk menyiapkan penemuan notifikasi.

Untuk menjalankan contoh berikut, Anda memerlukan peran Identity and Access Management (IAM) dengan izin yang sesuai:

  • Buat NotificationConfig: Editor Konfigurasi Notifikasi Pusat Keamanan (roles/securitycenter.notificationConfigEditor)
  • Mendapatkan dan Mencantumkan NotificationConfig: Pelihat Konfigurasi Notifikasi Pusat Keamanan (roles/securitycenter.notificationConfigViewer) atau Editor Konfigurasi Notifikasi Pusat Keamanan (roles/securitycenter.notificationConfigEditor)
  • Memperbarui dan Menghapus NotificationConfig: Editor Konfigurasi Notifikasi Pusat Keamanan (roles/securitycenter.notificationConfigEditor)

Untuk memberikan peran yang sesuai kepada akun utama yang mengakses notificationConfig, Anda harus memiliki salah satu peran IAM berikut:

  • Administrator Organisasi (roles/resourcemanager.organizationAdmin)
  • Folder IAM Admin (roles/resourcemanager.folderIamAdmin)
  • Project IAM Admin (roles/resourcemanager.projectIamAdmin)

Peran IAM untuk Security Command Center dapat diberikan di tingkat organisasi, folder, atau project. Kemampuan Anda untuk melihat, mengedit, membuat, atau memperbarui temuan, aset, dan sumber keamanan bergantung pada tingkat akses yang diberikan kepada Anda. Untuk mempelajari lebih lanjut peran Security Command Center, lihat Kontrol akses.

Residensi data dan notifikasi

Jika aset data diaktifkan untuk Security Command Center, konfigurasi yang menentukan ekspor berkelanjutan ke resource Pub/Sub—notificationConfig—tunduk pada kontrol aset data dan disimpan di lokasi Security Command Center Anda.

Untuk mengekspor temuan di lokasi Security Command Center ke Pub/Sub, Anda harus mengonfigurasi ekspor berkelanjutan di lokasi Security Command Center yang sama dengan temuan.

Karena filter yang digunakan dalam ekspor berkelanjutan dapat berisi data yang tunduk pada kontrol domisili, pastikan Anda menentukan lokasi yang benar sebelum membuatnya. Security Command Center tidak membatasi lokasi tempat Anda membuat ekspor.

Ekspor berkelanjutan hanya disimpan di lokasi tempat ekspor tersebut dibuat dan tidak dapat dilihat atau diedit di lokasi lain.

Setelah membuat ekspor berkelanjutan, Anda tidak dapat mengubah lokasinya. Untuk mengubah lokasi, Anda harus menghapus ekspor berkelanjutan dan membuatnya ulang di lokasi baru.

Untuk mempelajari cara menggunakan Security Command Center saat residensi data diaktifkan, lihat Endpoint regional Security Command Center.

Membuat NotificationConfig

Untuk membuat NotificationConfig, Anda harus memiliki:

  • Topik Pub/Sub yang sudah ada yang ingin Anda kirimi notifikasi.
  • Peran IAM yang diperlukan untuk akun utama yang membuat notificationConfig.

Untuk mengetahui informasi selengkapnya, lihat langkah-langkah untuk menyiapkan topik Pub/Sub dalam panduan untuk menyiapkan notifikasi temuan.

Sebelum membuat NotificationConfig, perhatikan bahwa setiap organisasi dapat memiliki sejumlah file NotificationConfig yang terbatas. Untuk mengetahui informasi selengkapnya, lihat Kuota dan batas.

NotificationConfig menyertakan kolom filter yang membatasi notifikasi ke peristiwa yang berguna. Kolom ini menerima semua filter yang tersedia di metode Security Command Center API findings.list.

Saat membuat NotificationConfig, Anda menentukan induk untuk NotificationConfig dari hierarki resource Google Cloud , baik organisasi, folder, atau project. Jika Anda perlu mengambil, memperbarui, atau menghapus NotificationConfig nanti, Anda harus menyertakan ID numerik organisasi induk, folder, atau project saat mereferensikannya.

Di konsol Google Cloud , beberapa resource NotificationConfig mungkin memiliki label Legacy yang menunjukkan bahwa resource tersebut dibuat dengan Security Command Center API v1. Anda dapat mengelola resource NotificationConfig ini dengan konsol Google Cloud , gcloud CLI, Security Command Center API v1, atau library klien v1 untuk Security Command Center.

Untuk mengelola resource NotificationConfig ini dengan gcloud CLI, Anda tidak boleh menentukan lokasi saat menjalankan perintah gcloud CLI.

Untuk membuat NotificationConfig menggunakan bahasa atau platform pilihan Anda:

gcloud

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

Ganti kode berikut:

  • NOTIFICATION_NAME: nama notifikasi. Harus terdiri dari 1 hingga 128 karakter dan hanya berisi karakter alfanumerik, garis bawah, atau tanda hubung.
  • PARENT: cakupan dalam hierarki resource yang berlaku untuk notifikasi, organization, folder, atau project.
  • PARENT_ID: ID organisasi, folder, atau project induk, yang ditentukan dalam format organizations/123, folders/456, atau projects/789.
  • LOCATION: lokasi Security Command Center tempat NotificationConfig akan dibuat; jika retensi data diaktifkan, gunakan eu, ksa, atau us; jika tidak, gunakan nilai global.
  • NOTIFICATION_DESCRIPTION: deskripsi notifikasi yang tidak lebih dari 1.024 karakter.
  • PUBSUB_TOPIC: Topik Pub/Sub yang akan menerima notifikasi. Formatnya adalah projects/PROJECT_ID/topics/TOPIC.
  • FILTER: ekspresi yang Anda tentukan untuk memilih temuan mana yang dikirim ke Pub/Sub. Contoh, state=\"ACTIVE\".

Terraform

Buat NotificationConfig untuk organisasi:

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\""
  }
}

Membuat NotificationConfig untuk folder:

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\""
  }
}

Membuat NotificationConfig untuk project:

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

Notifikasi kini dipublikasikan ke topik Pub/Sub yang Anda tentukan.

Untuk memublikasikan notifikasi, akun layanan dibuat untuk Anda dalam bentuk service-org-ORGANIZATION_ID@gcp-sa-scc-notification.iam.gserviceaccount.com. Akun layanan ini dibuat saat Anda membuat NotificationConfig pertama dan secara otomatis diberi peran securitycenter.notificationServiceAgent pada kebijakan IAM untuk PUBSUB_TOPIC saat membuat konfigurasi notifikasi. Peran akun layanan ini diperlukan agar notifikasi dapat berfungsi.

Mendapatkan NotificationConfig

Untuk mendapatkan NotificationConfig, Anda harus memiliki peran IAM yang menyertakan izin securitycenter.notification.get.

gcloud

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

Ganti kode berikut:

  • NOTIFICATION_NAME: nama konfigurasi notifikasi.
  • PARENT_TYPE tingkat hierarki resource tempat konfigurasi ditentukan; gunakan organization, folder, atau project.
  • PARENT_ID: ID numerik resource induk.
  • LOCATION: lokasi Security Command Center tempat untuk mendapatkan NotificationConfig; jika retensi data diaktifkan, gunakan eu, ksa, atau us; jika tidak, gunakan nilai global.

Memperbarui NotificationConfig

Untuk memperbarui NotificationConfig, Anda harus memiliki peran IAM yang mencakup izin securitycenter.notification.update.

Saat Anda memperbarui menggunakan mask kolom, hanya kolom yang Anda tentukan yang diperbarui. Jika Anda tidak menggunakan mask kolom, semua kolom yang dapat diubah dalam NotificationConfig akan digantikan oleh nilai baru. Anda dapat menggunakan mask kolom untuk memperbarui topik dan deskripsi Pub/Sub.

Untuk menyelesaikan contoh ini, Anda harus berlangganan topik baru, dan akun layanan notifikasi Anda harus memiliki izin pubsub.topics.setIamPolicy pada topik tersebut.

Setelah Anda memberikan izin yang diperlukan, perbarui deskripsi NotificationConfig, topik dan filter Pub/Sub menggunakan bahasa pilihan Anda:

gcloud

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

Ganti kode berikut:

  • NOTIFICATION_NAME: nama konfigurasi notifikasi.
  • PARENT_TYPE tingkat hierarki resource tempat konfigurasi ditentukan; gunakan organization, folder, atau project.
  • PARENT_ID: ID numerik resource induk.
  • LOCATION: lokasi Security Command Center tempat NotificationConfig akan diperbarui; jika retensi data diaktifkan, gunakan eu, ksa, atau us; jika tidak, gunakan nilai global.
  • NOTIFICATION_DESCRIPTION: deskripsi notifikasi yang tidak lebih dari 1.024 karakter.
  • PUBSUB_TOPIC: topik Pub/Sub yang akan menerima notifikasi. Formatnya adalah projects/PROJECT_ID/topics/TOPIC.
  • FILTER: ekspresi yang Anda tentukan untuk memilih temuan mana yang dikirim ke Pub/Sub. Contoh, state="ACTIVE".

Menghapus NotificationConfig

Untuk menghapus NotificationConfig, Anda harus memiliki peran IAM yang menyertakan izin securitycenter.notification.delete.

Saat Anda menghapus NotificationConfig, peran securitycenter.notificationServiceAgent tetap ada di topik Pub/Sub. Jika Anda tidak menggunakan topik Pub/Sub di NotificationConfig lain, hapus peran dari topik. Untuk mengetahui informasi selengkapnya, lihat kontrol akses.

Hapus NotificationConfig menggunakan bahasa pilihan Anda:

gcloud

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

Ganti kode berikut:

  • NOTIFICATION_NAME: nama konfigurasi notifikasi.
  • PARENT_TYPE tingkat hierarki resource tempat konfigurasi ditentukan; gunakan organization, folder, atau project.
  • PARENT_ID: ID numerik resource induk.
  • LOCATION: lokasi Security Command Centertempat NotificationConfig akan dihapus; jika retensi data diaktifkan, gunakan eu, ksa, atau us; jika tidak, gunakan nilai global.

Mencantumkan NotificationConfigs

Untuk mencantumkan NotificationConfigs, Anda harus memiliki peran IAM yang menyertakan izin securitycenter.notification.list.

Semua daftar Security Command Center API dipaginasi. Setiap respons menampilkan halaman hasil dan token untuk menampilkan halaman berikutnya. Nilai default pageSize adalah 10. Anda dapat mengonfigurasi ukuran halaman minimum 1, dan maksimum 1.000.

Buat daftar NotificationConfigs menggunakan bahasa pilihan Anda:

gcloud

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

Ganti kode berikut:

  • PARENT_TYPE tingkat hierarki resource tempat konfigurasi ditentukan; gunakan organizations, folders, atau projects.
  • PARENT_ID: ID numerik resource induk.
  • LOCATION: lokasi Security Command Center tempat mencantumkan resource NotificationConfig; jika retensi data diaktifkan, gunakan eu, ksa, atau us; jika tidak, gunakan nilai global.

Menerima notifikasi Pub/Sub

Bagian ini memberikan contoh pesan notifikasi dan contoh yang menunjukkan cara mengonversi pesan Pub/Sub menjadi NotificationMessage yang berisi temuan.

Notifikasi dipublikasikan ke Pub/Sub dalam format JSON. Berikut adalah contoh pesan notifikasi:

{
   "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"
   }
 }

Mengonversi pesan Pub/Sub menjadi NotificationMessage menggunakan bahasa pilihan Anda:

gcloud

gcloud CLI tidak mendukung konversi pesan Pub/Sub menjadi NotificationMessage. Anda dapat menggunakan gcloud CLI untuk mendapatkan NotificationMessage dan mencetak JSON langsung di terminal:

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

  gcloud pubsub subscriptions pull $PUBSUB_SUBSCRIPTION

Ganti kode berikut:

  • PROJECT_ID dengan ID project Anda.
  • SUBSCRIPTION_ID dengan ID langganan Anda.

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
}

Langkah berikutnya