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 notifikasi temuan.

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

  • Buat NotificationConfig: Security Center Notification Configurations Editor (roles/securitycenter.notificationConfigEditor)
  • Mendapatkan dan Mencantumkan NotificationConfig: Security Center Notification Configurations Viewer (roles/securitycenter.notificationConfigViewer) atau Security Center Notification Configurations Editor (roles/securitycenter.notificationConfigEditor)
  • Memperbarui dan Menghapus NotificationConfig: Security Center Notification Configurations Editor (roles/securitycenter.notificationConfigEditor)

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

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

Peran IAM untuk Security Command Center dapat diberikan di level 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 residensi data diaktifkan untuk Security Command Center, konfigurasi yang menentukan ekspor berkelanjutan ke Pub/Sub—resource notificationConfig—tunduk pada kontrol residensi 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 residensi, 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 kembali 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 untuk menyiapkan topik Pub/Sub dalam panduan untuk menyiapkan notifikasi temuan.

Sebelum membuat NotificationConfig, perhatikan bahwa setiap organisasi dapat memiliki jumlah resource 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 dalam metode findings.list Security Command Center API.

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, folder, atau project induk saat mereferensikannya.

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" \
  --deletion-notifications-enabled

Ganti kode berikut:

  • NOTIFICATION_NAME: nama notifikasi. Harus berisi antara 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 membuat NotificationConfig; jika residensi data diaktifkan, gunakan eu, sa, 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 yang akan dikirim ke Pub/Sub. Contoh, state=\"ACTIVE\".

Gunakan flag berikut untuk mengonfigurasi apakah akan menerima notifikasi untuk temuan yang dihapus. Secara default, temuan yang dihapus tidak diekspor.

  • --deletion-notifications-enabled: mengaktifkan notifikasi untuk temuan yang dihapus karena kebijakan retensi data. Jika ditetapkan, notifikasi akan dipicu saat temuan dihapus. Notifikasi menyertakan atribut deletedFinding yang ditetapkan ke true.
  • --no-deletion-notifications-enabled: menonaktifkan notifikasi untuk temuan yang dihapus karena kebijakan retensi data.

Terraform

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

Buat 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"
  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.. 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 untuk mendapatkan NotificationConfig; jika residensi data diaktifkan, gunakan eu, sa, atau us; jika tidak, gunakan nilai global.

Memperbarui NotificationConfig

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

Saat Anda mengupdate menggunakan mask kolom, hanya kolom yang Anda tentukan yang akan diupdate. Jika Anda tidak menggunakan mask kolom, semua kolom yang dapat diubah di NotificationConfig akan diganti dengan nilai baru. Anda dapat menggunakan mask kolom untuk memperbarui topik dan deskripsi Pub/Sub.

Untuk menyelesaikan contoh ini, Anda harus berlangganan ke 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 Pub/Sub, dan filter:

gcloud

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

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 residensi data diaktifkan, gunakan eu, sa, 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 yang akan dikirim ke Pub/Sub. Contoh, state="ACTIVE".

Gunakan flag berikut untuk mengonfigurasi apakah akan menerima notifikasi untuk temuan yang dihapus. Jika Anda tidak menentukan salah satu flag, perilaku default-nya adalah tidak mengekspor temuan yang dihapus.

  • --deletion-notifications-enabled: mengaktifkan notifikasi untuk temuan yang dihapus karena kebijakan retensi. Jika diaktifkan, temuan yang dihapus akan diekspor ke Pub/Sub dengan deleted_finding = true. Flag ini hanya berlaku untuk peristiwa penghapusan mendatang. Temuan yang dihapus sebelum mengaktifkan flag ini tidak akan diekspor secara retroaktif.

  • --no-deletion-notifications-enabled: menonaktifkan notifikasi untuk temuan yang dihapus.

Menghapus NotificationConfig

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

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

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 Center tempat NotificationConfig akan dihapus; jika residensi data diaktifkan, gunakan eu, sa, atau us; jika tidak, gunakan nilai global.

Mencantumkan NotificationConfig

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

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

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 untuk mencantumkan resource NotificationConfig; jika residensi data diaktifkan, gunakan eu, sa, 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"
   },
   "deletedFinding": true
 }

Security Command Center menghapus temuan secara berkala berdasarkan kebijakan retensi data. Anda dapat mengonfigurasi apakah Security Command Center mengekspor snapshot temuan yang dihapus ke Pub/Sub.

Anda mengaktifkan notifikasi penghapusan saat membuat atau memperbarui konfigurasi ekspor. Jika notifikasi penghapusan diaktifkan pada konfigurasi ekspor, Security Command Center akan mengirimkan snapshot temuan yang dihapus ke Pub/Sub. Notifikasi memiliki kolom "deletedFinding": true yang ditetapkan dalam payload. Status temuan sebelum penghapusan (misalnya, "state": "ACTIVE") dipertahankan dalam payload dan eventTime ditetapkan ke waktu temuan dihapus di Security Command Center.

Saat Anda mengubah opsi notifikasi penghapusan pada konfigurasi ekspor, perubahan tersebut hanya berlaku untuk penghapusan temuan di masa mendatang. Temuan yang dihapus sebelum mengaktifkan opsi ini tidak akan diekspor secara retroaktif.

Konversikan 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 project ID 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