Benachrichtigungskonfigurationen erstellen und verwalten

Auf dieser Seite wird die Verwendung das Benachrichtigungsfeature der Security Command Center API beschrieben, einschließlich der folgenden Beispiele:

  • NotificationConfig erstellen
  • NotificationConfig abrufen
  • NotificationConfig aktualisieren
  • NotificationConfig löschen
  • NotificationConfig auflisten
  • Pub/Sub-Benachrichtigungen empfangen

Alternativ können Sie kontinuierliche Exporte für Pub/Sub in Security Command Center einrichten.

Hinweis

Um die Beispiele auf dieser Seite zu verwenden, müssen Sie die Anleitung zum Einrichten von Benachrichtigungenabschließen.

Zur Ausführung der folgenden Beispiele benötigen Sie eine IAM-Rolle (Identity and Access Management) mit den entsprechenden Berechtigungen:

  • NotificationConfig erstellen: Bearbeiter von Konfigurationen für Benachrichtigungen des Sicherheitscenters (roles/securitycenter.notificationConfigEditor)
  • NotificationConfig abrufen und auflisten: Betrachter von Konfigurationen für Benachrichtigungen des Sicherheitscenters (roles/securitycenter.notificationConfigViewer) oder Bearbeiter von Konfigurationen für Benachrichtigungen des Sicherheitscenters (roles/securitycenter.notificationConfigEditor)
  • NotificationConfig aktualisieren und löschen: Bearbeiter von Konfigurationen für Benachrichtigungen des Sicherheitscenters (roles/securitycenter.notificationConfigEditor)

Um einem Prinzipal, das auf eine notificationConfig zugreift, die entsprechenden Rollen zu gewähren, benötigen Sie eine der folgenden IAM-Rollen:

  • Organisationsadministrator (roles/resourcemanager.organizationAdmin)
  • Ordner-IAM-Administrator (roles/resourcemanager.folderIamAdmin)
  • Projekt-IAM-Administrator (roles/resourcemanager.projectIamAdmin)

Die IAM-Rollen für Security Command Center können auf Organisations-, Ordner- oder Projektebene gewährt werden. Die Möglichkeit, Ergebnisse, Assets und Sicherheitsquellen anzusehen, zu bearbeiten, zu erstellen oder zu aktualisieren, hängt von der Ebene ab, auf die Sie Zugriff haben. Weitere Informationen zu Security Command Center-Rollen finden Sie unter Zugriffssteuerung.

Datenstandort und Benachrichtigungen

Wenn der Datenstandort für Security Command Center aktiviert ist, unterliegen die Konfigurationen, die kontinuierliche Exporte nach Pub/Sub—notificationConfig Ressourcen—der Datenstandortsteuerung und werden in Ihrem Security Command Center-Standort gespeichert.

Wenn Sie Ergebnisse an einem Security Command Center-Standort nach Pub/Sub exportieren möchten, müssen Sie den kontinuierlichen Export am selben Security Command Center-Standort wie die Ergebnisse konfigurieren.

Da die in kontinuierlichen Exporten verwendeten Filter Daten enthalten können, die der Datenstandortsteuerung unterliegen, müssen Sie den richtigen Standort angeben, bevor Sie sie erstellen. In Security Command Center gibt es keine Einschränkungen hinsichtlich des Standorts, an dem Sie Exporte erstellen.

Kontinuierliche Exporte werden nur an dem Standort gespeichert, an dem sie erstellt wurden, und können nicht an anderen Standorten angesehen oder bearbeitet werden.

Nachdem Sie einen kontinuierlichen Export erstellt haben, können Sie den Standort nicht mehr ändern. Wenn Sie den Standort ändern möchten, müssen Sie den kontinuierlichen Export löschen und am neuen Standort neu erstellen.

Informationen zur Verwendung von Security Command Center, wenn der Datenstandort aktiviert ist, finden Sie unter Regionale Endpunkte von Security Command Center.

NotificationConfig erstellen

Zum Erstellen einer NotificationConfig benötigen Sie Folgendes:

  • Ein vorhandenes Pub/Sub-Thema, an das Sie Benachrichtigungen senden möchten.
  • Erforderliche IAM-Rollen für das Hauptkonto, das die notificationConfig erstellt.

Weitere Informationen finden Sie im Abschnitt Pub/Sub-Thema einrichten in der Anleitung Ergebnis-Benachrichtigungen einrichten.

Bevor Sie eine NotificationConfig erstellen, beachten Sie, dass jede Organisation nur eine begrenzte Anzahl von NotificationConfig-Dateien haben kann. Weitere Informationen finden Sie unter Kontingente und Limits.

Die NotificationConfig enthält ein Feld filter, das Benachrichtigungen auf nützliche Ereignisse beschränkt. In diesem Feld werden alle Filter akzeptiert, die in der Methode findings.list der Security Command Center API verfügbar sind.

Wenn Sie eine NotificationConfig erstellen, geben Sie ein übergeordnetes Element für die NotificationConfig aus der Google Cloud Ressourcenhierarchie an, entweder eine Organisation, einen Ordner oder ein Projekt. Wenn Sie die NotificationConfig später abrufen, aktualisieren oder löschen müssen, müssen Sie die numerische ID der übergeordneten Organisation, des Ordners oder des Projekts angeben, wenn Sie darauf verweisen.

In der Google Cloud Console können einige NotificationConfig Ressourcen das Label Legacy haben. Das bedeutet, dass sie mit Version 1 der Security Command Center API erstellt wurden. Sie können diese NotificationConfig Ressourcen mit der Google Cloud Console, der gcloud CLI, Version 1 der Security Command Center API oder den Clientbibliotheken für Version 1 von Security Command Center verwalten.

Wenn Sie diese NotificationConfig-Ressourcen mit der gcloud CLI verwalten möchten, dürfen Sie beim Ausführen des gcloud CLI-Befehls keinen Standort angeben.

So erstellen Sie die NotificationConfig mit der Sprache oder Plattform Ihrer Wahl:

gcloud

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

Dabei gilt:

  • NOTIFICATION_NAME: der Name der Benachrichtigung. Muss zwischen 1 und 128 Zeichen lang sein und darf nur alphanumerische Zeichen, Unterstriche oder Bindestriche enthalten.
  • PARENT: der Bereich in der Ressourcenhierarchie, auf den sich die Benachrichtigung bezieht: organization, folder oder project.
  • PARENT_ID: die ID der übergeordneten Organisation, des Ordners oder des Projekts im Format organizations/123, folders/456 oder projects/789.
  • LOCATION: the Security Command Center location in which to create a NotificationConfig; if data residency is enabled, use eu, sa, or us; otherwise, use the value global.
  • NOTIFICATION_DESCRIPTION: eine Beschreibung der Benachrichtigung mit maximal 1.024 Zeichen.
  • PUBSUB_TOPIC: das Pub/Sub-Thema, das Benachrichtigungen erhält. Das Format ist projects/PROJECT_ID/topics/TOPIC.
  • FILTER: der Ausdruck, den Sie definieren, um auszuwählen, welche Ergebnisse an Pub/Sub gesendet werden. Beispiel: state=\"ACTIVE\".

Terraform

So erstellen Sie eine NotificationConfig für eine Organisation:

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

So erstellen Sie eine NotificationConfig für einen Ordner:

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

So erstellen Sie eine NotificationConfig für ein Projekt:

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

Benachrichtigungen werden jetzt in dem von Ihnen angegebenen Pub/Sub-Thema veröffentlicht.

Für die Veröffentlichung von Benachrichtigungen wird ein Dienstkonto in der Form von service-org-ORGANIZATION_ID@gcp-sa-scc-notification.iam.gserviceaccount.com erstellt. Dieses Dienstkonto wird beim Erstellen der ersten NotificationConfig erstellt und erhält automatisch die Rolle securitycenter.notificationServiceAgent in der IAM-Richtlinie für PUBSUB_TOPIC, wenn die Benachrichtigungskonfiguration erstellt wird. Diese Dienstkontorolle ist erforderlich, damit Benachrichtigungen funktionieren.

NotificationConfig abrufen

Zum Abrufen eines NotificationConfig benötigen Sie eine IAM-Rolle mit der Berechtigung securitycenter.notification.get.

gcloud

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

Dabei gilt:

NotificationConfig aktualisieren

Zum Aktualisieren eines NotificationConfig benötigen Sie eine IAM-Rolle mit der Berechtigung securitycenter.notification.update.

Wenn Sie das Feld mithilfe einer Feldmaske aktualisieren, werden nur die von Ihnen angegebenen Felder aktualisiert. Wenn Sie keine Feldmaske verwenden, werden alle veränderlichen Felder in NotificationConfig durch die neuen Werte ersetzt. Sie können das Pub/Sub-Thema und die Beschreibung mit einer Feldmaske aktualisieren.

Um dieses Beispiel abzuschließen, müssen Sie das neue Thema abonniert haben und Ihr Benachrichtigungsdienstkonto muss die Berechtigung pubsub.topics.setIamPolicy für das Thema haben.

Nachdem Sie die erforderlichen Berechtigungen gewährt haben, aktualisieren Sie die NotificationConfig-Beschreibung, das Pub/Sub-Thema und den Filter mit der Sprache Ihrer Wahl:

gcloud

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

Dabei gilt:

NotificationConfig löschen

Zum Löschen eines NotificationConfig benötigen Sie eine IAM-Rolle mit der Berechtigung securitycenter.notification.delete.

Wenn Sie einen NotificationConfig löschen, bleibt die Rolle securitycenter.notificationServiceAgent im Pub/Sub-Thema. Wenn Sie das Pub/Sub-Thema in keinem anderen NotificationConfig verwenden, entfernen Sie die Rolle aus dem Thema. Weitere Informationen finden Sie unter Zugriffssteuerung.

Löschen Sie einen NotificationConfig mit der Sprache Ihrer Wahl:

gcloud

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

Dabei gilt:

  • NOTIFICATION_NAME: der Name der Benachrichtigungskonfiguration.
  • PARENT_TYPE : die Ebene der Ressourcenhierarchie, auf der die Konfiguration angegeben ist. Verwenden Sie organization, folder oder project.
  • PARENT_ID: die numerische ID der übergeordneten Ressource.
  • LOCATION: der Security Command Center Standort, an dem die NotificationConfig gelöscht werden soll. Wenn der Datenstandort aktiviert ist, verwenden Sie eu, sa, oder us. Andernfalls verwenden Sie den Wert global.

NotificationsConfigs auflisten

Sie benötigen eine IAM-Rolle mit der Berechtigung securitycenter.notification.list, um NotificationConfigs aufzulisten.

Alle Security Command Center API-Listen sind paginiert. Jede Antwort gibt eine Seite mit Ergebnissen und ein Token zurück, um die nächste Seite zurückzugeben. Der Standardwert von pageSize ist 10. Sie können die Seitengröße auf mindestens 1 und maximal 1.000 festlegen.

Listen Sie NotificationConfigs mit der gewünschten Sprache auf:

gcloud

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

Dabei gilt:

Pub/Sub-Benachrichtigungen erhalten

Dieser Abschnitt enthält eine Beispielbenachrichtigung und Beispiele, die zeigen, wie eine Pub/Sub-Nachricht in eine NotificationMessage umgewandelt wird, die ein Ergebnis enthält.

Benachrichtigungen werden im JSON-Format in Pub/Sub veröffentlicht. Hier ein Beispiel für eine Benachrichtigung:

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

Konvertieren Sie eine Pub/Sub-Nachricht mit der Sprache Ihrer Wahl in einen NotificationMessage:

gcloud

Die gcloud-CLI unterstützt nicht die Konvertierung einer Pub/Sub-Nachricht in eine NotificationMessage. Mit der gcloud-CLI können Sie eine NotificationMessage abrufen und JSON direkt in Ihrem Terminal ausgeben:

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

  gcloud pubsub subscriptions pull $PUBSUB_SUBSCRIPTION

Dabei gilt:

  • PROJECT_ID durch Ihre Projekt-ID,
  • SUBSCRIPTION_ID durch Ihre Abo-ID.

Go

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

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

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

	ctx := context.Background()

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

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

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

	return nil
}

Nächste Schritte