יצירה וניהול של הגדרות התראות

בדף הזה מוסבר איך להשתמש בתכונת ההתראות של Security Command Center API, כולל הדוגמאות הבאות:

  • יצירת NotificationConfig
  • קבלת NotificationConfig
  • עדכון של NotificationConfig
  • מחיקת NotificationConfig
  • רשימה NotificationConfig
  • קבלת התראות Pub/Sub

לחלופין, אפשר להגדיר ייצוא רציף ל-Pub/Sub ב-Security Command Center.

לפני שמתחילים

כדי להשתמש בדוגמאות שבדף הזה, צריך להשלים את המדריך בנושא הגדרת התראות על מציאת מכשיר.

כדי להריץ את הדוגמאות הבאות, אתם צריכים תפקיד בממשק לניהול הזהויות והרשאות הגישה (IAM) עם ההרשאות המתאימות:

  • יצירה NotificationConfig: Security Center Notification Configurations Editor (roles/securitycenter.notificationConfigEditor)
  • קבלת רשימה של NotificationConfig: Security Center Notification Configurations Viewer (roles/securitycenter.notificationConfigViewer) או Security Center Notification Configurations Editor (roles/securitycenter.notificationConfigEditor)
  • עדכון ומחיקה NotificationConfig: עורך ההגדרות (roles/securitycenter.notificationConfigEditor) של הודעה במרכז האבטחה

כדי להקצות תפקידים מתאימים לחשבון ראשי שמקבל גישה ל-notificationConfig, אתם צריכים להיות בעלי אחד מתפקידי ה-IAM הבאים:

  • אדמין ארגוני (roles/resourcemanager.organizationAdmin)
  • אדמין IAM בתיקייה (roles/resourcemanager.folderIamAdmin)
  • אדמין IAM בפרויקט (roles/resourcemanager.projectIamAdmin)

אפשר להעניק את תפקידי ה-IAM של Security Command Center ברמת הארגון, התיקייה או הפרויקט. היכולת שלכם להציג, לערוך, ליצור או לעדכן ממצאים, נכסים ומקורות אבטחה תלויה ברמת הגישה שניתנה לכם. מידע נוסף על תפקידים ב-Security Command Center זמין במאמר בקרת גישה.

המיקום של נתונים והתראות

אם הגדרתם את מיקום הנתונים ב-Security Command Center, ההגדרות שמגדירות ייצוא רציף ל-Pub/Sub – משאבי notificationConfig – כפופות לבקרה על מיקום הנתונים ומאוחסנות במיקום של Security Command Center.

כדי לייצא ממצאים במיקום של Security Command Center אל Pub/Sub, צריך להגדיר את הייצוא הרציף באותו מיקום של Security Command Center שבו נמצאים הממצאים.

המסננים שמשמשים לייצוא רציף יכולים להכיל נתונים שחלים עליהם אמצעי בקרה על מיקום הנתונים, ולכן חשוב לציין את המיקום הנכון לפני שיוצרים אותם. ב-Security Command Center אין הגבלה על המיקום שבו אפשר ליצור ייצוא.

ייצוא רציף נשמר רק במיקום שבו הוא נוצר, ואי אפשר לראות או לערוך אותו במיקומים אחרים.

אחרי שיוצרים ייצוא רציף, אי אפשר לשנות את המיקום שלו. כדי לשנות את המיקום, צריך למחוק את הייצוא הרציף וליצור אותו מחדש במיקום החדש.

הנחיות לשימוש ב-Security Command Center כשמפעילים את התכונה 'שמירת נתונים באזור מסוים' מופיעות במאמר נקודות קצה אזוריות של Security Command Center.

יצירת NotificationConfig

כדי ליצור NotificationConfig, צריך:

  • נושא Pub/Sub קיים שאליו רוצים לשלוח התראות.
  • התפקידים שנדרשים ב-IAM לחשבון המשתמש שיוצר את notificationConfig.

מידע נוסף זמין בשלב הגדרת נושא Pub/Sub במדריך הגדרת התראות על ממצאים.

לפני שיוצרים NotificationConfig, חשוב לדעת שלכל ארגון יכול להיות מספר מוגבל של קובצי NotificationConfig. מידע נוסף זמין במאמר מכסות ומגבלות.

השדה NotificationConfig כולל את השדה filter שמגביל את ההתראות לאירועים שימושיים. בשדה הזה אפשר להזין את כל המסננים שזמינים בשיטה findings.list של Security Command Center API.

כשיוצרים NotificationConfig, מציינים את ההורה של NotificationConfig מתוך היררכיית המשאבים Google Cloud , כלומר ארגון, תיקייה או פרויקט. אם תצטרכו לאחזר, לעדכן או למחוק את NotificationConfig בהמשך, תצטרכו לכלול את המזהה המספרי של ארגון האב, התיקייה או הפרויקט כשמפנים אליו.

במסוף Google Cloud , יכול להיות שלחלק מהמשאבים של NotificationConfig תהיה התווית Legacy, שמציינת שהם נוצרו באמצעות Security Command Center API בגרסה 1. אפשר לנהל את המשאבים האלה NotificationConfig באמצעות מסוף Google Cloud , ה-CLI של gcloud, Security Command Center API בגרסה v1 או ספריות הלקוח של Security Command Center בגרסה v1.

כדי לנהל את המשאבים האלה של NotificationConfig באמצעות ה-CLI של gcloud, אסור לציין מיקום כשמריצים את הפקודה של ה-CLI של gcloud.

כדי ליצור את 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: ההיקף בהיררכיית המשאבים שההתראה רלוונטית לגביו, organization,‏ folder או project.
  • PARENT_ID: המזהה של הארגון, התיקייה או הפרויקט ברמת ההורה, שצוין בפורמט organizations/123,‏ folders/456 או projects/789.
  • LOCATION: המיקום של Security Command Center שבו רוצים ליצור NotificationConfig. אם מופעלת שמירת נתונים באזור מסוים, צריך להשתמש בערך eu, sa או us. אחרת, צריך להשתמש בערך global.
  • NOTIFICATION_DESCRIPTION: תיאור של ההתראה, באורך של עד 1,024 תווים.
  • PUBSUB_TOPIC: נושא ה-Pub/Sub שיקבל התראות. הפורמט שלו הוא projects/PROJECT_ID/topics/TOPIC.
  • FILTER: הביטוי שאתם מגדירים כדי לבחור אילו ממצאים יישלחו ל-Pub/Sub. לדוגמה, state=\"ACTIVE\".

Terraform

כדי ליצור NotificationConfig לארגון:

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

כדי ליצור NotificationConfig לתיקייה:

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

יצירת NotificationConfig לפרויקט:

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

ההתראות מתפרסמות עכשיו בנושא Pub/Sub שציינתם.

כדי לפרסם התראות, נוצר עבורכם חשבון שירות בפורמט service-org-ORGANIZATION_ID@gcp-sa-scc-notification.iam.gserviceaccount.com. חשבון השירות הזה נוצר כשיוצרים את NotificationConfig הראשון, ומקבל אוטומטית את התפקיד securitycenter.notificationServiceAgent במדיניות IAM עבור PUBSUB_TOPIC כשיוצרים את הגדרת ההתראות. תפקיד חשבון השירות הזה נדרש כדי שההתראות יפעלו.

קבלת NotificationConfig

כדי לקבל NotificationConfig, צריך להיות לכם תפקיד ב-IAM שכולל את ההרשאה securitycenter.notification.get.

gcloud

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

מחליפים את מה שכתוב בשדות הבאים:

  • NOTIFICATION_NAME: השם של הגדרות ההתראה.
  • PARENT_TYPE הרמה בהיררכיית המשאבים שבה מצוינת ההגדרה. אפשר להשתמש ב-organization, folder או project.
  • PARENT_ID: המזהה המספרי של משאב האב.
  • LOCATION: המיקום של Security Command Center שבו רוצים לקבל את NotificationConfig. אם מופעלת שמירת נתונים באזור מסוים, צריך להשתמש ב-eu, ב-sa או ב-us. אחרת, צריך להשתמש בערך global.

עדכון של NotificationConfig

כדי לעדכן NotificationConfig, צריך תפקיד ב-IAM שכולל את ההרשאה securitycenter.notification.update.

כשמעדכנים באמצעות מסכת שדות, רק השדות שמציינים מתעדכנים. אם לא משתמשים במסכת שדות, כל השדות שניתנים לשינוי ב-NotificationConfig מוחלפים בערכים החדשים. אפשר להשתמש במסכת שדות כדי לעדכן את הנושא ואת התיאור של Pub/Sub.

כדי להשלים את הדוגמה הזו, אתם צריכים להירשם לנושא החדש, ולחשבון השירות של שירות ההתראות צריכה להיות ההרשאה pubsub.topics.setIamPolicy בנושא.

אחרי שנותנים את ההרשאות הנדרשות, מעדכנים את NotificationConfigהתיאור, נושא Pub/Sub והמסנן בשפה הרצויה:

gcloud

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

מחליפים את מה שכתוב בשדות הבאים:

  • NOTIFICATION_NAME: השם של הגדרות ההתראה.
  • PARENT_TYPE הרמה בהיררכיית המשאבים שבה מצוינת ההגדרה. אפשר להשתמש ב-organization, folder או project.
  • PARENT_ID: המזהה המספרי של משאב האב.
  • LOCATION: המיקום של Security Command Center שבו צריך לעדכן את NotificationConfig. אם מופעלת שמירת נתונים באזור מסוים, צריך להשתמש בערך eu, sa או us. אחרת, צריך להשתמש בערך global.
  • NOTIFICATION_DESCRIPTION: תיאור של ההתראה, באורך של עד 1,024 תווים.
  • PUBSUB_TOPIC: נושא ה-Pub/Sub שיקבל את ההתראות. הפורמט שלו הוא projects/PROJECT_ID/topics/TOPIC.
  • FILTER: הביטוי שאתם מגדירים כדי לבחור אילו ממצאים יישלחו ל-Pub/Sub. לדוגמה, state="ACTIVE".

מחיקת NotificationConfig

כדי למחוק NotificationConfig, צריך להיות לכם תפקיד IAM שכולל את ההרשאה securitycenter.notification.delete.

כשמוחקים NotificationConfig, התפקיד securitycenter.notificationServiceAgent נשאר בנושא ב-Pub/Sub. אם אתם לא משתמשים בנושא Pub/Sub באף NotificationConfig אחר, אתם יכולים להסיר את התפקיד מהנושא. מידע נוסף זמין במאמר בנושא בקרת גישה.

מחיקת NotificationConfig בשפה שבחרתם:

gcloud

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

מחליפים את מה שכתוב בשדות הבאים:

  • NOTIFICATION_NAME: השם של הגדרות ההתראה.
  • PARENT_TYPE הרמה בהיררכיית המשאבים שבה מצוינת ההגדרה. אפשר להשתמש ב-organization, folder או project.
  • PARENT_ID: המזהה המספרי של משאב האב.
  • LOCATION: המיקום של Security Command Center שבו רוצים למחוק את NotificationConfig. אם מופעלת תכונת שמירת נתונים באזור מסוים, צריך להשתמש בערכים eu,‏ sa או us. אחרת, צריך להשתמש בערך global.

הצגת רשימה של NotificationConfigs

כדי להציג את NotificationConfigs, צריך להיות לכם תפקיד ב-IAM שכולל את ההרשאה securitycenter.notification.list.

כל הרשימות ב-Security Command Center API מחולקות לדפים. כל תגובה מחזירה דף של תוצאות ואסימון להחזרת הדף הבא. ערך ברירת המחדל pageSize הוא 10. אפשר להגדיר את גודל הדף למינימום של 1 ולמקסימום של 1, 000.

רשימה NotificationConfigs בשפה שבחרתם:

gcloud

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

מחליפים את מה שכתוב בשדות הבאים:

  • PARENT_TYPE הרמה בהיררכיית המשאבים שבה מצוינת ההגדרה. אפשר להשתמש ב-organizations, folders או projects.
  • PARENT_ID: המזהה המספרי של משאב האב.
  • LOCATION: המיקום של Security Command Center שבו רוצים להציג את משאבי NotificationConfig. אם מופעלת שמירת נתונים באזור מסוים, צריך להשתמש בערכים eu, sa או us. אחרת, צריך להשתמש בערך global.

קבלת התראות Pub/Sub

בקטע הזה מופיעה הודעת התראה לדוגמה ודוגמאות שמראות איך להמיר הודעת Pub/Sub ל-NotificationMessage שמכילה ממצא.

ההתראות מתפרסמות ב-Pub/Sub בפורמט JSON. דוגמה להודעת התראה:

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

המרת הודעת Pub/Sub ל-NotificationMessage באמצעות השפה שבחרתם:

gcloud

ממשק ה-CLI של gcloud לא תומך בהמרת הודעה ב-Pub/Sub ל-NotificationMessage. אפשר להשתמש ב-CLI של gcloud כדי לקבל NotificationMessage ולהדפיס את JSON ישירות בטרמינל:

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

  gcloud pubsub subscriptions pull $PUBSUB_SUBSCRIPTION

מחליפים את מה שכתוב בשדות הבאים:

  • PROJECT_ID במזהה הפרויקט.
  • SUBSCRIPTION_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
}

המאמרים הבאים