Pub/Sub의 발견 항목 알림 사용 설정

이 페이지에서는 Security Command Center API 알림을 사용 설정하는 방법을 설명합니다.

알림은 몇 분 내로 Pub/Sub 주제에 발견 항목과 발견 항목 업데이트를 전송합니다. Security Command Center API 알림에는 Google Cloud 콘솔에서 Security Command Center가 표시하는 모든 발견 항목 정보가 포함됩니다.

Pub/Sub의 Security Command Center 알림을 Cloud Functions 작업에 직접 연결할 수 있습니다. 응답, 보강, 구제 조치에 도움이 되는 함수 예시는 Cloud Functions 코드의 Security Command Center 오픈소스 저장소를 참조하세요. 저장소에는 보안 발견 항목에 대한 자동 작업을 수행하는 데 도움이 되는 솔루션이 포함되어 있습니다.

또는 발견 항목을 BigQuery로 내보내거나 Google Cloud 콘솔에서 Pub/Sub에 대해 지속적 내보내기를 설정할 수 있습니다.

시작하기 전에

알림을 설정하고 구성하려면 다음 Identity and Access Management(IAM) 역할이 있어야 합니다.

  • 보안 센터 관리자(roles/securitycenter.Admin): Security Command Center API 알림을 사용 설정합니다.
  • 보안 센터 관리자 뷰어 (roles/securitycenter.adminViewer): Google Cloud 콘솔에서 Security Command Center에 액세스합니다.
  • 조직 수준, 폴더 수준, 프로젝트 수준에서 알림 서비스 계정이나 gcloud CLI 계정에 역할을 부여하려면 다음 역할 중 하나가 있어야 합니다.
    • 조직 관리자(roles/resourcemanager.organizationAdmin)
    • 폴더 IAM 관리자(roles/resourcemanager.folderIamAdmin)
    • 프로젝트 IAM 관리자(roles/resourcemanager.projectIamAdmin)

Security Command Center의 IAM 역할은 조직, 폴더, 프로젝트 수준에서 부여할 수 있습니다. 발견 항목, 애셋, 보안 소스를 보거나 수정하거나 만들거나 업데이트할 수 있는 기능은 액세스 권한이 부여된 수준에 따라 다릅니다. Security Command Center 역할에 대해 자세히 알아보려면 액세스 제어를 참조하세요.

Security Command Center API 알림 설정

알림을 설정하려면 먼저 Security Command Center API를 사용 설정하세요.

Security Command Center API 사용 설정

Security Command Center API를 사용 설정하려면 다음 단계를 따르세요.

  1. Google Cloud 콘솔의 API 라이브러리 페이지로 이동합니다.

    API 라이브러리로 이동

  2. Notifications API를 사용 설정하려는 프로젝트를 선택합니다.

  3. 검색 상자에 Security Command Center를 입력한 다음 검색 결과에서 Security Command Center를 클릭합니다.

  4. 표시되는 API 페이지에서 사용 설정을 클릭합니다.

프로젝트에 Security Command Center API가 사용 설정됩니다. 그런 다음 gcloud CLI 또는 클라이언트 라이브러리를 사용하여 Pub/Sub 주제를 구독하고 권한을 설정합니다.

데이터 상주 및 알림

Security Command Center에 데이터 상주가 사용 설정된 경우 Pub/Sub(notificationConfig 리소스)에 대한 지속적인 내보내기를 정의하는 구성은 데이터 상주 제어의 대상이 되며 Security Command Center 위치에 저장됩니다.

Security Command Center 위치의 발견 항목을 Pub/Sub로 내보내려면 발견 항목과 동일한 Security Command Center 위치에 지속적 내보내기를 구성해야 합니다.

지속적 내보내기에 사용된 필터는 상주 제어가 적용되는 데이터를 포함할 수 있기 때문에 이를 만들기 전에 올바른 위치를 지정해야 합니다. Security Command Center는 내보내기를 만드는 위치를 제한하지 않습니다.

지속적 내보내기는 생성되는 위치에만 저장되며 다른 위치에서 보거나 수정할 수 없습니다.

지속적 내보내기를 만든 후에는 해당 위치를 변경할 수 없습니다. 위치를 변경하려면 지속적 내보내기를 삭제하고 새 위치에 다시 만들어야 합니다.

API 호출을 사용해서 지속적 내보내기를 검색하려면 notificationConfig의 전체 리소스 이름에 위치를 지정해야 합니다. 예를 들면 다음과 같습니다.

GET https://securitycenter.googleapis.com/v2/{name=organizations/123/locations/eu/notificationConfigs/my-pubsub-export-01}

마찬가지로 gcloud CLI를 사용하여 지속적 내보내기를 가져오려면 구성의 전체 리소스 이름 또는 --locations 플래그를 사용하여 위치를 지정해야 합니다. 예를 들면 다음과 같습니다.

gcloud scc notifications describe myContinuousExport organizations/123 \
    --location=locations/us

Pub/Sub 주제 설정

이 단계에서는 알림을 보낼 Pub/Sub 주제를 만들고 구독합니다. API를 프로그래매틱 방식으로 호출할 필요가 없는 경우 gcloud CLI 명령어를 사용하는 것이 좋습니다.

gcloud

gcloud CLI를 사용하여 Security Command Center API 알림 기능을 설정하려면 다음 단계를 수행하세요.

  1. Pub/Sub 주제 및 구독 설정
  2. gcloud CLI 계정 권한을 설정합니다.

1단계: Pub/Sub 설정

Pub/Sub 주제를 설정하고 구독하려면 다음을 수행합니다.

  1. Google Cloud 콘솔로 이동합니다.

    Google Cloud 콘솔로 이동

  2. Security Command Center API를 사용 설정한 프로젝트를 선택합니다.

  3. Cloud Shell 활성화를 클릭합니다.

  4. 새 Pub/Sub 주제를 만들거나 기존 주제를 사용하려면 다음 명령어를 실행하세요.

      gcloud pubsub topics create TOPIC_ID
    

    TOPIC_ID를 주제 이름으로 바꿉니다.

  5. 주제 ID 환경 변수를 설정합니다.

      export TOPIC_ID=TOPIC_ID
    
  6. 주제에 대한 구독을 만듭니다.

      gcloud pubsub subscriptions create SUBSCRIPTION_ID --topic TOPIC_ID
    

    SUBSCRIPTION_ID를 구독 이름으로 바꿉니다.

Pub/Sub 설정에 대한 자세한 내용은 주제 및 구독 관리를 참조하세요.

다음으로 계정에 대한 권한을 설정합니다.

2단계: gcloud CLI 계정 권한 설정

NotificationConfig를 만들려면 gcloud CLI 계정에 다음 역할을 부여해야 합니다.

  • 보안 센터 관리자(roles/securitycenter.admin) 또는 보안 센터 알림 구성 편집자(roles/securitycenter.notificationConfigEditor). 이 역할은 NotificationConfig를 만드는 것과 동일한 수준(조직, 폴더 또는 프로젝트)에서 부여해야 합니다.
  • 알림을 수신하는 Pub/Sub 주제에 대한 Pub/Sub 관리자(roles/pubsub.admin)

조직, 폴더 또는 프로젝트 수준

이러한 권한을 부여하려면 다음을 수행합니다.

  1. Google Cloud 콘솔로 이동합니다.

    Google Cloud 콘솔로 이동

  2. Security Command Center API를 사용 설정한 프로젝트를 선택합니다.

  3. Cloud Shell 활성화를 클릭합니다.

    1. 조직 이름을 설정합니다.

      export ORGANIZATION_ID=ORGANIZATION_ID
      

      ORGANIZATION_ID를 조직 ID로 바꿉니다.

    2. Pub/Sub 주제가 속한 프로젝트의 프로젝트 ID를 설정합니다.

      export PUBSUB_PROJECT=PROJECT_ID
      

      PROJECT_ID를 프로젝트 ID로 바꿉니다.

    3. 사용 중인 gcloud CLI 계정을 설정합니다.

      export GCLOUD_ACCOUNT=EMAIL
      

      EMAIL을 gcloud CLI 명령어를 실행하는 계정의 이메일 주소로 바꿉니다.

    4. 주제 ID를 설정하거나 이전에 설정한 주제를 사용합니다.

      export TOPIC_ID=TOPIC_ID
      

      TOPIC_ID를 주제 이름으로 바꿉니다.

    5. gcloud CLI 계정에 pubsub.topics.setIamPolicy 권한이 있는 Pub/Sub 역할을 부여합니다.

      gcloud pubsub topics add-iam-policy-binding \
        projects/$PUBSUB_PROJECT/topics/$TOPIC_ID \
        --member="user:$GCLOUD_ACCOUNT" \
        --role='roles/pubsub.admin'
      
    6. gcloud CLI 계정에 roles/securitycenter.notificationConfigEditor 또는 roles/securitycenter.admin 같은 모든 securitycenter.notification 권한이 포함된 역할을 부여합니다. 프로젝트, 폴더, 조직 수준에서 역할을 부여할 수 있습니다.

      프로젝트 수준에서 역할을 부여하려면 다음을 수행합니다.

      gcloud projects add-iam-policy-binding PROJECT_ID \
      --member="user:$GCLOUD_ACCOUNT" \
      --role='ROLE_NAME'
      

      다음을 바꿉니다.

      • PROJECT_ID: Security Command Center가 사용 설정된 프로젝트의 ID입니다.
      • ROLE_NAME: 할당할 역할입니다.

      조직 수준에서 역할을 부여하려면 다음 안내를 따르세요.

      gcloud organizations add-iam-policy-binding $ORGANIZATION_ID \
        --member="user:$GCLOUD_ACCOUNT" \
        --role='ROLE_NAME'
      

      ROLE_NAME을 할당될 역할로 바꿉니다.

그런 다음 NotificationConfig를 만듭니다.

클라이언트 라이브러리

클라이언트 라이브러리를 사용하여 Security Command Center API 알림 기능을 설정하려면 다음 단계를 수행합니다.

  1. 서비스 계정을 설정합니다.
  2. API 클라이언트 라이브러리를 다운로드합니다.
  3. 개발 환경을 설정합니다.
  4. Pub/Sub 주제 및 구독 설정

1단계: 서비스 계정 설정

Security Command Center API 알림 기능은 적절한 권한이 있는 서비스 계정을 사용하여 알림을 구성합니다. 이 서비스 계정은 구성의 초기 설정에만 사용되며, 나중에 이 계정을 사용하여 추가 알림 구성을 만들 수 있습니다. 이 서비스 계정은 Security Command Center를 설정할 때 생성된 서비스 계정과는 별개입니다.

서비스 계정을 만들려면 다음을 수행합니다.

  1. Google Cloud 콘솔로 이동합니다.

    Google Cloud 콘솔로 이동

  2. Security Command Center API를 사용 설정한 프로젝트를 선택합니다.

  3. Cloud Shell 활성화를 클릭합니다.

  4. 환경 변수를 설정합니다.

    1. 조직 이름을 설정합니다.

        export ORGANIZATION_ID=ORGANIZATION_ID
      

      ORGANIZATION_ID를 조직 ID로 바꿉니다.

    2. 알림 API를 사용 설정하려는 프로젝트의 프로젝트 ID를 설정합니다.

        export PROJECT_ID=PROJECT_ID
      

      PROJECT_ID를 프로젝트 ID로 바꿉니다.

    3. 새 서비스 계정에 사용할 커스텀 ID를 설정합니다(예: scc-notifications). 서비스 계정 이름은 6~30자(영문 기준)여야 하고 문자로 시작해야 하며 모두 소문자 영숫자 문자와 하이픈이어야 합니다.

        export SERVICE_ACCOUNT=CUSTOM_ID
      

      CUSTOM_ID를 서비스 계정의 커스텀 이름으로 바꿉니다.

    4. export KEY_LOCATION=/home/$USER/mykeys/$SERVICE_ACCOUNT.json와 같이 서비스 계정 키를 저장할 경로를 설정합니다.

        export KEY_LOCATION=FULL_KEY_LOCATION_PATH
        # This is used by client libraries to find the key
        export GOOGLE_APPLICATION_CREDENTIALS=$KEY_LOCATION
      

      FULL_KEY_LOCATION_PATH를 서비스 계정 키의 전체 경로로 바꿉니다.

  5. 프로젝트 ID와 연결된 서비스 계정을 만듭니다.

       gcloud iam service-accounts create $SERVICE_ACCOUNT  --display-name \
        "Service Account for [USER]"  --project $PROJECT_ID
    
  6. 서비스 계정과 연결할 키를 만듭니다. 키는 NotificationConfig를 만들 때 사용되며 이전 단계에서 지정한 KEY_LOCATION에 영구 저장됩니다.

       gcloud iam service-accounts keys create $KEY_LOCATION  --iam-account \
        $SERVICE_ACCOUNT@$PROJECT_ID.iam.gserviceaccount.com
    
  7. 서비스 계정에 roles/securitycenter.notificationConfigEditor 또는 roles/securitycenter.admin 같은 모든 securitycenter.notification 권한이 포함된 역할을 부여합니다. 프로젝트, 폴더, 조직 수준에서 역할을 부여할 수 있습니다.

    프로젝트 수준에서 역할을 부여합니다.

       gcloud projects add-iam-policy-binding $PROJECT_ID \
         --member="serviceAccount:$SERVICE_ACCOUNT@$PROJECT_ID.iam.gserviceaccount.com" \
         --role='ROLE_NAME'
    

    ROLE_NAME을 할당될 역할로 바꿉니다.

    조직 수준에서 역할을 부여하려면 다음 안내를 따르세요.

       gcloud organizations add-iam-policy-binding $ORGANIZATION_ID \
         --member="serviceAccount:$SERVICE_ACCOUNT@$PROJECT_ID.iam.gserviceaccount.com" \
         --role='ROLE_NAME'
    

    ROLE_NAME을 할당될 역할로 바꿉니다.

이제 알림과 함께 사용하도록 서비스 계정이 설정되며 서비스 계정 키가 지정한 KEY_LOCATION에 저장됩니다. 서비스 계정에 대한 자세한 내용은 서비스 계정 키 만들기 및 관리를 참조하세요.

2단계: 개발 환경 설정

Security Command Center API 알림 기능을 사용하려면 gcloud CLI를 사용하거나 클라이언트 라이브러리를 다운로드하여 원하는 언어로 개발 환경을 설정하면 됩니다.

Python

  1. 선택사항: Python 라이브러리를 설치하기 전에 Virtualenv를 사용하여 격리된 Python 환경을 만드는 것이 좋습니다.

     virtualenv YOUR_ENV
     source YOUR_ENV/bin/activate
    

    YOUR_ENV를 가상 환경 이름으로 바꿉니다.

  2. pip를 설치하여 Python 라이브러리 설치를 관리합니다.

  3. 다음 명령어를 실행하여 Python 라이브러리를 설치합니다.

     pip install google-cloud-securitycenter
    

자바

Security Command Center 자바 라이브러리를 프로젝트의 종속 항목으로 포함하려면 Maven 저장소에서 아티팩트를 선택합니다. 알림은 라이브러리 버전 0.119.0 이상에 포함됩니다.

Intellij를 사용하는 경우 GOOGLE_APPLICATION_CREDENTIALS 환경 변수를 이전 단계에서 다운로드한 알림 서비스 계정 키의 절대 경로로 설정합니다.

  1. Intellij에서 실행 > 구성 편집을 클릭합니다.
  2. 애플리케이션, Run_Configuration_For_Sample, 환경 변수에서 다음 변수를 설정합니다.

      GOOGLE_APPLICATION_CREDENTIALS=ABSOLUTE_PATH_TO_SERVICE_ACCOUNT_KEY
    

    ABSOLUTE_PATH_TO_SERVICE_ACCOUNT_KEY를 서비스 계정 키의 전체 경로로 바꿉니다.

Go

알림 API Go 종속 항목을 설치하려면 Go 라이브러리를 다운로드합니다.

  go get cloud.google.com/go/securitycenter/apiv1

Node.js

프로젝트 폴더에서 npm를 사용하여 필요한 알림 API 종속 항목을 설치합니다.

  npm install --save @google-cloud/security-center/

3단계: Pub/Sub 설정

Pub/Sub에 알림을 전달하려면 Pub/Sub 주제를 구독하고 알림 서비스 계정에 pubsub.topics.setIamPolicy 권한이 있는 IAM 역할을 부여합니다.

  1. 새 Pub/Sub 주제를 만들거나 기존 주제를 사용하세요.

       gcloud pubsub topics create TOPIC_ID
    

    TOPIC_ID를 주제 ID로 바꿉니다.

  2. 환경 변수를 설정합니다.

    1. 주제 ID를 설정합니다.

        export TOPIC_ID=TOPIC_ID
      
    2. Notifications API를 사용 설정한 프로젝트의 프로젝트 ID를 설정합니다.

        export CONSUMER_PROJECT=PROJECT_ID
      

      PROJECT_ID를 프로젝트 ID로 바꿉니다.

    3. 이전 단계에서 만든 서비스 계정의 이메일을 설정합니다.

        export SERVICE_ACCOUNT_EMAIL=SERVICE_ACCOUNT_NAME@$CONSUMER_PROJECT.iam.gserviceaccount.com
      

      SERVICE_ACCOUNT_NAME을 서비스 계정의 이름으로 바꿉니다.

  3. 주제에 대한 구독을 만듭니다.

       gcloud pubsub subscriptions create SUBSCRIPTION_ID --topic TOPIC_ID
    

    SUBSCRIPTION_ID를 구독 ID로 바꿉니다.

  4. 알림 서비스 계정에 pubsub.topics.setIamPolicy 권한이 있는 역할을 부여합니다.

    gcloud pubsub topics add-iam-policy-binding \
         projects/$CONSUMER_PROJECT/topics/$TOPIC_ID \
      --member="serviceAccount:$SERVICE_ACCOUNT_EMAIL" \
      --role='roles/pubsub.admin'
    

Pub/Sub 설정에 대한 자세한 내용은 주제 및 구독 관리를 참조하세요. 다음 단계에서 NotificationConfig를 만들어 설정을 완료합니다.

NotificationConfig 만들기

NotificationConfig를 만들기 전에 각 조직에는 제한된 수의 NotificationConfig 파일이 있을 수 있습니다. 자세한 내용은 할당량 및 한도를 참조하세요.

NotificationConfig에는 알림을 유용한 이벤트로 제한하는 filter 필드가 포함되어 있습니다. 이 필드는 Security Command Center API findings.list 메서드에서 사용할 수 있는 모든 필터를 허용합니다.

NotificationConfig를 만들 때 Google Cloud 리소스 계층 구조(조직, 폴더 또는 프로젝트)에서 NotificationConfig의 상위 요소를 지정합니다. NotificationConfig를 검색, 업데이트 또는 삭제해야 하는 경우 참조할 때 상위 조직, 폴더 또는 프로젝트의 숫자 ID를 포함해야 합니다.

원하는 언어 또는 플랫폼을 사용하여 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 형식으로 지정된 상위 조직, 폴더 또는 프로젝트의 ID입니다.
  • LOCATION: 데이터 상주가 사용 설정된 경우 알림을 만들 Security Command Center 위치를 지정합니다. 결과 notificationConfig 리소스는 이 위치에만 저장됩니다. 이 위치에서 발급된 발견 항목만 Pub/Sub로 전송됩니다.

    데이터 상주가 사용 설정되지 않은 경우 --location 플래그를 지정하면 Security Command Center API v2를 사용하여 알림이 생성되고 플래그에 대한 유효한 유일한 값은 global입니다.

  • NOTIFICATION_DESCRIPTION: 알림에 대한 설명입니다(1,024자 이내). .

  • PUBSUB_TOPIC: 알림을 수신할 Pub/Sub 주제입니다. 형식은 projects/PROJECT_ID/topics/TOPIC입니다.

  • FILTER: Pub/Sub로 전송되는 발견 항목을 선택하기 위해 정의하는 표현식입니다. 예를 들면 state="ACTIVE"입니다.

Python

다음 샘플은 v1 API를 사용합니다. v2의 샘플을 수정하려면 v1v2로 바꾸고 /locations/LOCATION을 리소스 이름에 추가합니다.

대부분의 리소스의 경우 /PARENT/PARENT_ID 뒤에 /locations/LOCATION을 리소스 이름에 추가합니다. 여기서 PARENTorganizations, folders 또는 projects입니다.

발견 항목의 경우 /sources/SOURCE_ID 뒤에 /locations/LOCATION을 리소스 이름에 추가합니다. 여기서 SOURCE_ID는 발견 항목을 실행한 Security Command Center 서비스의 ID입니다.

def create_notification_config(parent_id, notification_config_id, pubsub_topic):
    """
    Args:
        parent_id: must be in one of the following formats:
            "organizations/{organization_id}"
            "projects/{project_id}"
            "folders/{folder_id}"
        notification_config_id: "your-config-id"
        pubsub_topic: "projects/{your-project-id}/topics/{your-topic-ic}"

    Ensure this ServiceAccount has the "pubsub.topics.setIamPolicy" permission on the new topic.
    """
    from google.cloud import securitycenter as securitycenter

    client = securitycenter.SecurityCenterClient()

    created_notification_config = 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(created_notification_config)

Java

다음 샘플은 v1 API를 사용합니다. v2의 샘플을 수정하려면 v1v2로 바꾸고 /locations/LOCATION을 리소스 이름에 추가합니다.

대부분의 리소스의 경우 /PARENT/PARENT_ID 뒤에 /locations/LOCATION을 리소스 이름에 추가합니다. 여기서 PARENTorganizations, folders 또는 projects입니다.

발견 항목의 경우 /sources/SOURCE_ID 뒤에 /locations/LOCATION을 리소스 이름에 추가합니다. 여기서 SOURCE_ID는 발견 항목을 실행한 Security Command Center 서비스의 ID입니다.


import com.google.cloud.securitycenter.v1.CreateNotificationConfigRequest;
import com.google.cloud.securitycenter.v1.NotificationConfig;
import com.google.cloud.securitycenter.v1.NotificationConfig.StreamingConfig;
import com.google.cloud.securitycenter.v1.SecurityCenterClient;
import java.io.IOException;

public class CreateNotificationConfigSnippets {

  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 = String.format("organizations/%s", "ORG_ID");
    String notificationConfigId = "{config-id}";
    String projectId = "{your-project}";
    String topicName = "{your-topic}";

    createNotificationConfig(parentId, notificationConfigId, projectId, topicName);
  }

  // Crete a notification config.
  // Ensure the ServiceAccount has the "pubsub.topics.setIamPolicy" permission on the new topic.
  public static NotificationConfig createNotificationConfig(
      String parentId, String notificationConfigId, String projectId, String topicName)
      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()) {

      // Ensure this ServiceAccount has the "pubsub.topics.setIamPolicy" permission on the topic.
      String pubsubTopic = String.format("projects/%s/topics/%s", projectId, topicName);

      CreateNotificationConfigRequest request =
          CreateNotificationConfigRequest.newBuilder()
              .setParent(parentId)
              .setConfigId(notificationConfigId)
              .setNotificationConfig(
                  NotificationConfig.newBuilder()
                      .setDescription("Java notification config")
                      .setPubsubTopic(pubsubTopic)
                      .setStreamingConfig(
                          StreamingConfig.newBuilder().setFilter("state = \"ACTIVE\"").build())
                      .build())
              .build();

      NotificationConfig response = client.createNotificationConfig(request);
      System.out.printf("Notification config was created: %s%n", response);
      return response;
    }
  }
}

Go

다음 샘플은 v1 API를 사용합니다. v2의 샘플을 수정하려면 v1v2로 바꾸고 /locations/LOCATION을 리소스 이름에 추가합니다.

대부분의 리소스의 경우 /PARENT/PARENT_ID 뒤에 /locations/LOCATION을 리소스 이름에 추가합니다. 여기서 PARENTorganizations, folders 또는 projects입니다.

발견 항목의 경우 /sources/SOURCE_ID 뒤에 /locations/LOCATION을 리소스 이름에 추가합니다. 여기서 SOURCE_ID는 발견 항목을 실행한 Security Command Center 서비스의 ID입니다.

import (
	"context"
	"fmt"
	"io"

	securitycenter "cloud.google.com/go/securitycenter/apiv1"
	"cloud.google.com/go/securitycenter/apiv1/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}"
		//		"projects/{projectId}"
		//		"folders/{folderId}"
		Parent:   fmt.Sprintf("organizations/%s", 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
}

Node.js

다음 샘플에서는 v1 API를 사용합니다. v2의 샘플을 수정하려면 v1v2로 바꾸고 /locations/LOCATION을 리소스 이름에 추가합니다.

대부분의 리소스의 경우 /PARENT/PARENT_ID 뒤에 /locations/LOCATION을 리소스 이름에 추가합니다. 여기서 PARENTorganizations, folders 또는 projects입니다.

발견 항목의 경우 /sources/SOURCE_ID 뒤에 /locations/LOCATION을 리소스 이름에 추가합니다. 여기서 SOURCE_ID는 발견 항목을 실행한 Security Command Center 서비스의 ID입니다.

// npm install '@google-cloud/security-center'
const {SecurityCenterClient} = require('@google-cloud/security-center');

const client = new SecurityCenterClient();

// parent: must be in one of the following formats:
//    `organizations/${organization_id}`
//    `projects/${project_id}`
//    `folders/${folder_id}`
// configId = "your-config-name";
// pubsubTopic = "projects/{your-project}/topics/{your-topic}";
// Ensure this Service Account has the "pubsub.topics.setIamPolicy" permission on this topic.
const parent = `organizations/${organizationId}`;

async function createNotificationConfig() {
  const [response] = await client.createNotificationConfig({
    parent: parent,
    configId: configId,
    notificationConfig: {
      description: 'Sample config for node.js',
      pubsubTopic: pubsubTopic,
      streamingConfig: {filter: 'state = "ACTIVE"'},
    },
  });
  console.log('Notification config creation succeeded: ', response);
}

createNotificationConfig();

PHP

다음 샘플에서는 v1 API를 사용합니다. v2의 샘플을 수정하려면 v1v2로 바꾸고 /locations/LOCATION을 리소스 이름에 추가합니다.

대부분의 리소스의 경우 /PARENT/PARENT_ID 뒤에 /locations/LOCATION을 리소스 이름에 추가합니다. 여기서 PARENTorganizations, folders 또는 projects입니다.

발견 항목의 경우 /sources/SOURCE_ID 뒤에 /locations/LOCATION을 리소스 이름에 추가합니다. 여기서 SOURCE_ID는 발견 항목을 실행한 Security Command Center 서비스의 ID입니다.

use Google\Cloud\SecurityCenter\V1\Client\SecurityCenterClient;
use Google\Cloud\SecurityCenter\V1\CreateNotificationConfigRequest;
use Google\Cloud\SecurityCenter\V1\NotificationConfig;
use Google\Cloud\SecurityCenter\V1\NotificationConfig\StreamingConfig;

/**
 * @param string $organizationId        Your org ID
 * @param string $notificationConfigId  A unique identifier
 * @param string $projectId             Your Cloud Project ID
 * @param string $topicName             Your topic name
 */
function create_notification(
    string $organizationId,
    string $notificationConfigId,
    string $projectId,
    string $topicName
): void {
    $securityCenterClient = new SecurityCenterClient();
    // 'parent' must be in one of the following formats:
    //		"organizations/{orgId}"
    //		"projects/{projectId}"
    //		"folders/{folderId}"
    $parent = $securityCenterClient::organizationName($organizationId);
    $pubsubTopic = $securityCenterClient::topicName($projectId, $topicName);

    $streamingConfig = (new StreamingConfig())->setFilter('state = "ACTIVE"');
    $notificationConfig = (new NotificationConfig())
        ->setDescription('A sample notification config')
        ->setPubsubTopic($pubsubTopic)
        ->setStreamingConfig($streamingConfig);
    $createNotificationConfigRequest = (new CreateNotificationConfigRequest())
        ->setParent($parent)
        ->setConfigId($notificationConfigId)
        ->setNotificationConfig($notificationConfig);

    $response = $securityCenterClient->createNotificationConfig($createNotificationConfigRequest);
    printf('Notification config was created: %s' . PHP_EOL, $response->getName());
}

Ruby

다음 샘플에서는 v1 API를 사용합니다. v2의 샘플을 수정하려면 v1v2로 바꾸고 /locations/LOCATION을 리소스 이름에 추가합니다.

대부분의 리소스의 경우 /PARENT/PARENT_ID 뒤에 /locations/LOCATION을 리소스 이름에 추가합니다. 여기서 PARENTorganizations, folders 또는 projects입니다.

발견 항목의 경우 /sources/SOURCE_ID 뒤에 /locations/LOCATION을 리소스 이름에 추가합니다. 여기서 SOURCE_ID는 발견 항목을 실행한 Security Command Center 서비스의 ID입니다.

require "google/cloud/security_center"

# Your organization id. e.g. for "organizations/123", this would be "123".
# org_id = "YOUR_ORGANZATION_ID"

# Your notification config id. e.g. for
# "organizations/123/notificationConfigs/my-config" this would be "my-config".
# config_id = "YOUR_CONFIG_ID"

# The PubSub topic where notifications will be published.
# pubsub_topic = "YOUR_TOPIC"

client = Google::Cloud::SecurityCenter.security_center

# You can also use 'project_id' or 'folder_id' as a parent.
# client.project_path project: project_id
# client.folder_path folder: folder_id
parent = client.organization_path organization: org_id

notification_config = {
  description:      "Sample config for Ruby",
  pubsub_topic:     pubsub_topic,
  streaming_config: { filter: 'state = "ACTIVE"' }
}

response = client.create_notification_config(
  parent:              parent,
  config_id:           config_id,
  notification_config: notification_config
)
puts "Created notification config #{config_id}: #{response}."

C#

다음 샘플에서는 v1 API를 사용합니다. v2의 샘플을 수정하려면 v1v2로 바꾸고 /locations/LOCATION을 리소스 이름에 추가합니다.

대부분의 리소스의 경우 /PARENT/PARENT_ID 뒤에 /locations/LOCATION을 리소스 이름에 추가합니다. 여기서 PARENTorganizations, folders 또는 projects입니다.

발견 항목의 경우 /sources/SOURCE_ID 뒤에 /locations/LOCATION을 리소스 이름에 추가합니다. 여기서 SOURCE_ID는 발견 항목을 실행한 Security Command Center 서비스의 ID입니다.


using Google.Api.Gax.ResourceNames;
using Google.Cloud.SecurityCenter.V1;
using System;

///<summary> Create NotificationConfig Snippet. </summary>
public class CreateNotificationConfigSnippets
{
    public static NotificationConfig CreateNotificationConfig(
        string organizationId, string notificationConfigId, string projectId, string topicName)
    {
        // You can also use 'projectId' or 'folderId' instead of the 'organizationId'.
        //      ProjectName projectName = new ProjectName(projectId);
        //      FolderName folderName = new FolderName(folderId);
        OrganizationName orgName = new OrganizationName(organizationId);
        TopicName pubsubTopic = new TopicName(projectId, topicName);

        SecurityCenterClient client = SecurityCenterClient.Create();
        CreateNotificationConfigRequest request = new CreateNotificationConfigRequest
        {
            ParentAsOrganizationName = orgName,
            ConfigId = notificationConfigId,
            NotificationConfig = new NotificationConfig
            {
                Description = ".Net notification config",
                PubsubTopicAsTopicName = pubsubTopic,
                StreamingConfig = new NotificationConfig.Types.StreamingConfig { Filter = "state = \"ACTIVE\"" }
            }
        };

        NotificationConfig response = client.CreateNotificationConfig(request);
        Console.WriteLine($"Notification config was created: {response}");
        return response;
    }
}

이제 알림이 지정된 Pub/Sub 주제에 게시됩니다.

알림을 게시하려면 service-org-ORGANIZATION_ID@gcp-sa-scc-notification.iam.gserviceaccount.com 형식으로 서비스 계정이 생성됩니다. 이 서비스 계정은 첫 번째 NotificationConfig를 만들 때 생성되며 알림 구성을 만들 때 PUBSUB_TOPIC에 대한 IAM 정책에 securitycenter.notificationServiceAgent 역할이 자동으로 부여됩니다. 알림이 작동하려면 서비스 계정 역할이 필요합니다.

VPC 서비스 제어에서 경계 액세스 권한 부여

VPC 서비스 제어를 사용하고 Pub/Sub 주제가 서비스 경계 내 프로젝트의 일부인 경우, 알림을 만들려면 프로젝트에 대한 액세스 권한을 부여해야 합니다.

프로젝트에 대한 액세스 권한을 부여하려면 알림을 만드는 데 사용되는 주 구성원 및 프로젝트에 대한 인그레스 및 이그레스 규칙을 만드세요. 이 규칙을 이용하여 보호된 리소스에 대한 액세스를 허용하고 Pub/Sub가 Pub/Sub 주제에 대한 setIamPolicy 권한을 가지고 있는지 확인할 수 있습니다.

NotificationConfig를 만들기 전에

NotificationConfig 만들기 단계를 완료하기 전에 다음을 수행합니다.

  1. Google Cloud 콘솔에서 VPC 서비스 제어 페이지로 이동합니다.

    VPC 서비스 제어로 이동

  2. 필요한 경우 조직을 선택합니다.

  3. 변경할 서비스 경계의 이름을 클릭합니다.

    수정해야 하는 서비스 경계를 찾으려면 RESOURCES_NOT_IN_SAME_SERVICE_PERIMETER 위반을 표시하는 항목의 로그를 확인하면 됩니다. 해당 항목에서 servicePerimeterName 필드를 확인합니다(accessPolicies/ACCESS_POLICY_ID/servicePerimeters/SERVICE_PERIMETER_NAME).

  4. 경계 수정을 클릭합니다.

  5. 탐색 메뉴에서 인그레스 정책을 클릭합니다.

  6. 사용자 또는 서비스 계정에 대한 인그레스 규칙을 구성하려면 다음 매개변수를 사용합니다.

    • API 클라이언트의 FROM 속성:
      • 소스 드롭다운 메뉴에서 모든 소스를 선택합니다.
      • ID 드롭다운 메뉴에서 선택한 ID를 선택합니다.
      • 선택을 클릭한 후 Security Command Center API를 호출하는 데 사용되는 주 구성원을 입력합니다.
    • Google Cloud 서비스/리소스의 TO 속성:
      • 프로젝트 드롭다운 메뉴에서 선택한 프로젝트를 선택합니다.
      • 선택을 클릭한 후 Pub/Sub 주제가 포함된 프로젝트를 입력합니다.
      • 서비스 드롭다운 메뉴에서 선택한 서비스를 선택한 후 Cloud Pub/Sub API를 선택합니다.
      • 메서드 드롭다운 메뉴에서 모든 작업을 선택합니다.
  7. 저장을 클릭합니다.

  8. 탐색 메뉴에서 이그레스 정책을 클릭합니다.

  9. '규칙 추가'를 클릭합니다.

  10. 사용자나 서비스 계정에 대한 이그레스 규칙을 구성하려면 다음 매개변수를 입력합니다.

    • API 클라이언트의 FROM 속성:
      • ID 드롭다운 메뉴에서 선택한 ID를 선택합니다.
      • 선택을 클릭한 후 Security Command Center API를 호출하는 데 사용되는 주 구성원을 입력합니다.
    • Google Cloud 서비스/리소스의 TO 속성:
      • 프로젝트 드롭다운 메뉴에서 모든 프로젝트를 선택합니다.
      • 서비스 드롭다운 메뉴에서 선택한 서비스를 선택한 후 Cloud Pub/Sub API를 선택합니다.
      • 메서드 드롭다운 메뉴에서 모든 작업을 선택합니다.
  11. 저장을 클릭합니다.

NotificationConfig에 대한 인그레스 규칙 만들기

NotificationConfig에 대한 인그레스 규칙을 만들려면 다음을 수행합니다.

  1. NotificationConfig 만들기의 안내를 완료합니다.
  2. 이전 섹션의 서비스 경계를 다시 엽니다.
  3. 인그레스 정책을 클릭합니다.
  4. '규칙 추가'를 클릭합니다.
  5. 만든 NotificationConfig 서비스 계정에 대한 인그레스 규칙을 구성하려면 다음 매개변수를 입력합니다.
    • API 클라이언트의 FROM 속성:
      • 소스 드롭다운 메뉴에서 모든 소스를 선택합니다.
      • ID 드롭다운 메뉴에서 선택한 ID를 선택합니다.
      • 선택을 클릭하고 NotificationConfig 서비스 계정 이름을 입력합니다. service-org-ORGANIZATION_ID@gcp-sa-scc-notification.iam.gserviceaccount.com
    • GCP 서비스/리소스의 TO 속성:
      • 프로젝트 드롭다운 메뉴에서 선택한 프로젝트를 선택합니다.
      • 선택을 클릭한 후 Pub/Sub 주제가 포함된 프로젝트를 선택합니다.
      • 서비스 드롭다운 메뉴에서 선택한 서비스를 선택한 후 Cloud Pub/Sub API를 선택합니다.
      • 메서드 드롭다운 메뉴에서 모든 작업을 선택합니다.
  6. 탐색 메뉴에서 저장을 클릭합니다.

이제 선택한 프로젝트, 사용자, 서비스 계정에서 보호된 리소스에 액세스하고 알림을 만들 수 있습니다.

이 가이드의 모든 단계를 수행했고 알림이 올바르게 작동하면 이제 다음을 삭제할 수 있습니다.

  • 주 구성원의 인그레스 규칙
  • 주 구성원의 이그레스 규칙

이러한 규칙은 NotificationConfig만 구성해야 했습니다. 하지만 알림이 계속 작동하게 하려면 NotificationConfig에 대한 인그레스 규칙을 유지해야 합니다. 이렇게 하면 서비스 경계 뒤에 있는 Pub/Sub 주제에 알림을 게시할 수 있습니다.

다음 단계