Creazione e gestione di oggetti NotificationConfig

Questa pagina descrive come utilizzare la funzionalità di notifiche dell'API Security Command Center, inclusi i seguenti esempi:

  • Crea un NotificationConfig
  • Ricevi un NotificationConfig
  • Aggiornare un NotificationConfig
  • Eliminare un NotificationConfig
  • Elenco NotificationConfig
  • Ricevere notifiche Pub/Sub

In alternativa, puoi configurare le esportazioni continue per Pub/Sub in Security Command Center.

Prima di iniziare

Per utilizzare gli esempi in questa pagina, devi completare la guida alla configurazione delle notifiche di ritrovamento.

Per eseguire gli esempi seguenti, devi disporre di un ruolo Identity and Access Management (IAM) con le autorizzazioni appropriate:

  • Crea NotificationConfig: Editor configurazioni notifiche Centro sicurezza (roles/securitycenter.notificationConfigEditor)
  • Get e List NotificationConfig: Visualizzatore configurazioni notifiche Centro sicurezza (roles/securitycenter.notificationConfigViewer) o Editor configurazioni notifiche Centro sicurezza (roles/securitycenter.notificationConfigEditor)
  • Aggiornamento ed eliminazione di NotificationConfig: Editor configurazioni notifiche Centro sicurezza (roles/securitycenter.notificationConfigEditor)

Per concedere i ruoli appropriati a un'entità che accede a un notificationConfig, devi disporre di uno dei seguenti ruoli IAM:

  • Amministratore organizzazione (roles/resourcemanager.organizationAdmin)
  • Amministratore IAM cartella (roles/resourcemanager.folderIamAdmin)
  • Project IAM Admin (roles/resourcemanager.projectIamAdmin)

I ruoli IAM per Security Command Center possono essere concessi a livello di organizzazione, cartella o progetto. La possibilità di visualizzare, modificare, creare o aggiornare risultati, asset e origini di sicurezza dipende dal livello per cui ti è stato concesso l'accesso. Per scoprire di più sui ruoli di Security Command Center, consulta Controllo dell'accesso.

Residenza dei dati e notifiche

Se la residenza dei dati è abilitata per Security Command Center, le configurazioni che definiscono le esportazioni continue in Pub/Sub, ovvero le risorse notificationConfig, sono soggette al controllo della residenza dei dati e vengono archiviate nella posizione di Security Command Center.

Per esportare i risultati in una posizione di Security Command Center in Pub/Sub, devi configurare l'esportazione continua nella stessa posizione di Security Command Center dei risultati.

Poiché i filtri utilizzati nelle esportazioni continue possono contenere dati soggetti a controlli di residenza, assicurati di specificare la posizione corretta prima di crearli. Security Command Center non limita la località in cui creare le esportazioni.

Le esportazioni continue vengono archiviate solo nella località in cui vengono create e non possono essere visualizzate o modificate in altre località.

Dopo aver creato un'esportazione continua, non puoi modificarne la posizione. Per modificare la posizione, devi eliminare l'esportazione continua e ricrearla nella nuova posizione.

Per scoprire come utilizzare Security Command Center quando la residenza dei dati è abilitata, consulta Endpoint regionali di Security Command Center.

Creazione di un oggetto NotificationConfig

Per creare un NotificationConfig, devi disporre di:

  • Un argomento Pub/Sub esistente a cui vuoi inviare le notifiche.
  • Ruoli IAM richiesti per l'entità che crea notificationConfig.

Per ulteriori informazioni, consulta il passaggio per configurare un argomento Pub/Sub nella guida alla configurazione delle notifiche sui risultati.

Prima di creare un NotificationConfig, tieni presente che ogni organizzazione può avere un numero limitato di file NotificationConfig. Per ulteriori informazioni, consulta Quote e limiti.

NotificationConfig include un campo filter che limita le notifiche agli eventi utili. Questo campo accetta tutti i filtri disponibili nel metodo findings.list dell'API Security Command Center.

Quando crei un NotificationConfig, specifichi un elemento padre per il NotificationConfig dalla gerarchia delle risorse Google Cloud , ovvero un'organizzazione, una cartella o un progetto. Se in un secondo momento devi recuperare, aggiornare o eliminare NotificationConfig, devi includere l'ID numerico dell'organizzazione, della cartella o del progetto principale quando fai riferimento.

Nella console Google Cloud , alcune risorse NotificationConfig potrebbero avere un'etichetta Legacy, che indica che sono state create con l'API Security Command Center v1. Puoi gestire queste risorse NotificationConfig con la console Google Cloud , gcloud CLI, l'API Security Command Center v1 o le librerie client v1 per Security Command Center.

Per gestire queste risorse NotificationConfig con gcloud CLI, non devi specificare una località quando esegui il comando gcloud CLI.

Per creare NotificationConfig utilizzando la lingua o la piattaforma che preferisci:

gcloud

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

Sostituisci quanto segue:

  • NOTIFICATION_NAME: il nome della notifica. Deve essere compreso tra 1 e 128 caratteri e contenere solo caratteri alfanumerici, trattini bassi o trattini.
  • PARENT: l'ambito nella gerarchia delle risorse a cui si applica la notifica, organization, folder o project.
  • PARENT_ID: l'ID dell'organizzazione, della cartella o del progetto principale, specificato nel formato organizations/123, folders/456 o projects/789.
  • LOCATION: la posizione di Security Command Center in cui creare un NotificationConfig; se la residenza dei dati è abilitata, utilizza eu, ksa o us; altrimenti, utilizza il valore global.
  • NOTIFICATION_DESCRIPTION: una descrizione della notifica di massimo 1024 caratteri.
  • PUBSUB_TOPIC: l'argomento Pub/Sub che riceverà le notifiche. Il formato è projects/PROJECT_ID/topics/TOPIC.
  • FILTER: l'espressione che definisci per selezionare quali risultati vengono inviati a Pub/Sub. Ad esempio, state=\"ACTIVE\".

Terraform

Crea un NotificationConfig per un'organizzazione:

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

Creare un NotificationConfig per una cartella:

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

Creare un NotificationConfig per un progetto:

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

Le notifiche vengono ora pubblicate nell'argomento Pub/Sub che hai specificato.

Per pubblicare le notifiche, viene creato un account di servizio nel formato service-org-ORGANIZATION_ID@gcp-sa-scc-notification.iam.gserviceaccount.com. Questo account di servizio viene creato quando crei il tuo primo NotificationConfig e gli viene concesso automaticamente il ruolo securitycenter.notificationServiceAgent nel criterio IAM per PUBSUB_TOPIC durante la creazione della configurazione di notifica. Questo ruolo delaccount di serviziot è necessario per il funzionamento delle notifiche.

Recuperare un oggetto NotificationConfig

Per ottenere un NotificationConfig, devi disporre di un ruolo IAM che includa l'autorizzazione securitycenter.notification.get.

gcloud

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

Sostituisci quanto segue:

  • NOTIFICATION_NAME: il nome della configurazione di notifica.
  • PARENT_TYPE il livello della gerarchia delle risorse in cui è specificata la configurazione; utilizza organization, folder o project.
  • PARENT_ID: l'ID numerico della risorsa principale.
  • LOCATION: la posizione di Security Command Center in cui ottenere NotificationConfig; se la residenza dei dati è abilitata, utilizza eu, ksa o us; altrimenti, utilizza il valore global.

Aggiornamento di un NotificationConfig

Per aggiornare un NotificationConfig, devi disporre di un ruolo IAM che includa l'autorizzazione securitycenter.notification.update.

Quando esegui l'aggiornamento utilizzando una maschera di campo, vengono aggiornati solo i campi specificati. Se non utilizzi una maschera di campo, tutti i campi modificabili in NotificationConfig vengono sostituiti dai nuovi valori. Puoi utilizzare una maschera di campo per aggiornare l'argomento e la descrizione Pub/Sub.

Per completare questo esempio, devi iscriverti al nuovo argomento e il tuo account di servizio di notifica deve disporre dell'autorizzazione pubsub.topics.setIamPolicy per l'argomento.

Dopo aver concesso le autorizzazioni necessarie, aggiorna la NotificationConfig descrizione, l'argomento Pub/Sub e il filtro utilizzando la lingua che preferisci:

gcloud

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

Sostituisci quanto segue:

  • NOTIFICATION_NAME: il nome della configurazione di notifica.
  • PARENT_TYPE il livello della gerarchia delle risorse in cui è specificata la configurazione; utilizza organization, folder o project.
  • PARENT_ID: l'ID numerico della risorsa principale.
  • LOCATION: la posizione di Security Command Center in cui aggiornare NotificationConfig; se la residenza dei dati è attivata, utilizza eu, ksa o us; altrimenti, utilizza il valore global.
  • NOTIFICATION_DESCRIPTION: una descrizione della notifica di massimo 1024 caratteri.
  • PUBSUB_TOPIC: l'argomento Pub/Sub che riceverà le notifiche. Il formato è projects/PROJECT_ID/topics/TOPIC.
  • FILTER: l'espressione che definisci per selezionare i risultati da inviare a Pub/Sub. Ad esempio, state="ACTIVE".

Eliminazione di un NotificationConfig

Per eliminare un NotificationConfig, devi disporre di un ruolo IAM che includa l'autorizzazione securitycenter.notification.delete.

Quando elimini un NotificationConfig, il ruolo securitycenter.notificationServiceAgent rimane nell'argomento Pub/Sub. Se non utilizzi l'argomento Pub/Sub in altri NotificationConfig, rimuovi il ruolo dall'argomento. Per ulteriori informazioni, consulta Controllo dell'accesso.

Elimina un NotificationConfig utilizzando la lingua che preferisci:

gcloud

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

Sostituisci quanto segue:

  • NOTIFICATION_NAME: il nome della configurazione di notifica.
  • PARENT_TYPE il livello della gerarchia delle risorse in cui è specificata la configurazione; utilizza organization, folder o project.
  • PARENT_ID: l'ID numerico della risorsa principale.
  • LOCATION: la posizione di Security Command Center in cui eliminare NotificationConfig; se la residenza dei dati è abilitata, utilizza eu, ksa o us; altrimenti, utilizza il valore global.

Elenco di NotificationConfigs

Per elencare NotificationConfigs, devi disporre di un ruolo IAM che includa l'autorizzazione securitycenter.notification.list.

Tutti gli elenchi dell'API Security Command Center sono paginati. Ogni risposta restituisce una pagina di risultati e un token per restituire la pagina successiva. Il valore predefinito di pageSize è 10. Puoi configurare le dimensioni della pagina con un minimo di 1 e un massimo di 1000.

Elenco NotificationConfigs nella lingua che preferisci:

gcloud

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

Sostituisci quanto segue:

  • PARENT_TYPE il livello della gerarchia delle risorse in cui è specificata la configurazione; utilizza organizations, folders o projects.
  • PARENT_ID: l'ID numerico della risorsa principale.
  • LOCATION: la posizione di Security Command Center in cui elencare le risorse NotificationConfig; se la residenza dei dati è abilitata, utilizza eu, ksa o us; altrimenti, utilizza il valore global.

Ricezione di notifiche Pub/Sub

Questa sezione fornisce un messaggio di notifica di esempio ed esempi che mostrano come convertire un messaggio Pub/Sub in un NotificationMessage che contiene un problema.

Le notifiche vengono pubblicate su Pub/Sub nel formato JSON. Di seguito è riportato un esempio di messaggio di notifica:

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

Converti un messaggio Pub/Sub in un NotificationMessage utilizzando la lingua che preferisci:

gcloud

L'interfaccia a riga di comando gcloud non supporta la conversione di un messaggio Pub/Sub in un NotificationMessage. Puoi utilizzare gcloud CLI per ottenere un NotificationMessage e stampare il JSON direttamente nel terminale:

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

  gcloud pubsub subscriptions pull $PUBSUB_SUBSCRIPTION

Sostituisci quanto segue:

  • PROJECT_ID con l'ID progetto.
  • SUBSCRIPTION_ID con l'ID abbonamento.

Vai

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
}

Passaggi successivi