Sensitive Data Protection 검사 작업 결과를 Security Command Center로 보내기

이 가이드에서는 Cloud Storage, Datastore 모드의 Firestore(Datastore) 또는 BigQuery에서 데이터를 검사하고 Security Command Center로 검사 결과를 전송하는 방법을 안내합니다.

BigQuery 데이터의 경우 검사 작업과 다른 프로파일링을 추가로 수행할 수 있습니다. 또한 Security Command Center로 데이터 프로필을 보낼 수 있습니다. 자세한 내용은 Security Command Center에 데이터 프로필 게시를 참조하세요.

개요

Security Command Center를 사용하면 보안 위협에 대해 데이터를 수집하고 식별하여 조치를 취해 비즈니스에 손상이나 손실을 입히지 않도록 방지할 수 있습니다. Security Command Center를 사용하면 중앙 집중식 단일 대시보드에서 여러 보안 관련 작업을 수행할 수 있습니다.

Sensitive Data Protection은 Security Command Center와 기본적으로 통합됩니다. Sensitive Data Protection 작업(action)을 사용하여 Google Cloud 스토리지 저장소에서 민감한 정보를 검사하면 결과를 Security Command Center 대시보드로 직접 전송할 수 있습니다. 결과는 다른 보안 측정항목 옆에 표시됩니다.

이 가이드의 단계를 완료하면 다음 작업을 수행할 수 있습니다.

  • Security Command Center 및 Sensitive Data Protection 사용 설정
  • Cloud Storage 버킷, BigQuery 테이블 또는 Datastore 종류와 같은 Google Cloud 스토리지 저장소를 검사하도록 Sensitive Data Protection을 설정합니다.
  • Sensitive Data Protection 스캔을 구성하여 검사 작업 결과를 Security Command Center로 전송합니다.

Security Command Center에 대한 자세한 내용은 Security Command Center 문서를 참조하세요.

검사 작업이 아닌 검색 스캔 결과를 Security Command Center로 보내려면 대신 조직, 폴더 프로파일링 또는 프로젝트에 대한 문서를 참조하세요.

비용

이 문서에서는 비용이 청구될 수 있는 다음과 같은 Google Cloud 구성요소를 사용합니다.

  • Sensitive Data Protection
  • Cloud Storage
  • BigQuery
  • Datastore

프로젝트 사용량을 기준으로 예상 비용을 산출하려면 가격 계산기를 사용하세요. Google Cloud를 처음 사용하는 사용자는 무료 체험판을 사용할 수 있습니다.

시작하기 전에

Sensitive Data Protection 스캔 결과를 Security Command Center로 보내려면 먼저 다음을 수행해야 합니다.

  • 1단계: Google Cloud 스토리지 저장소 설정
  • 2단계: Identity and Access Management(IAM) 역할 설정
  • 3단계: Security Command Center 사용 설정
  • 4단계: Sensitive Data Protection 사용 설정
  • 5단계: Security Command Center의 보안 소스로 Sensitive Data Protection 사용 설정

이러한 구성요소를 설정하는 단계는 다음 섹션에서 설명합니다.

1단계: Google Cloud Storage 저장소 설정

자체 Google Cloud 스토리지 저장소를 스캔할지 아니면 예시 저장소를 스캔할지 선택합니다. 이 주제에서는 두 시나리오 모두에 대한 안내를 제공합니다.

자체 데이터 스캔

자체의 기존 Cloud Storage 버킷, BigQuery 테이블 또는 Datastore 종류를 스캔하려면 먼저 저장소가 있는 프로젝트를 엽니다. 이후 단계에서 이 프로젝트와 조직에 Security Command Center 및 Sensitive Data Protection을 모두 사용 설정합니다.

사용할 프로젝트를 연 후 2단계로 진행하여 일부 IAM 역할을 설정합니다.

샘플 데이터 스캔

데이터의 테스트 세트를 스캔하려면 먼저 결제 계정이 설정되어 있는지 확인한 다음 새 프로젝트를 만듭니다. 이 단계를 완료하려면 IAM 프로젝트 생성자 역할이 있어야 합니다. IAM 역할을 자세히 알아보세요.

  1. 아직 결제를 구성하지 않은 경우 결제 계정을 설정합니다.

    결제 사용 설정 방법 알아보기

  2. Google Cloud Console에서 새 프로젝트 페이지로 이동합니다.

    새 프로젝트로 이동

  3. 결제 계정 드롭다운 목록에서 결제 계정을 선택합니다. 이 계정으로 프로젝트의 비용이 청구됩니다.
  4. 조직 드롭다운 목록에서 프로젝트를 만들 조직을 선택합니다.
  5. 위치 드롭다운 목록에서 프로젝트를 만들 조직 또는 폴더를 선택합니다.

그런 다음, 샘플 데이터를 다운로드하고 저장합니다.

  1. GitHub의 Cloud Functions 튜토리얼 저장소로 이동합니다.
  2. 클론 또는 다운로드를 클릭한 다음 ZIP 다운로드를 클릭합니다.
  3. 다운로드한 zip 파일의 압축을 풉니다.
  4. Google Cloud 콘솔에서 스토리지 브라우저 페이지로 이동합니다.

    Cloud Storage로 이동

  5. 버킷 생성을 클릭합니다.
  6. 버킷 만들기 페이지에서 버킷에 고유한 이름을 지정한 후 만들기를 클릭합니다.
  7. 버킷 세부정보 페이지에서 폴더 업로드를 클릭합니다.
  8. 압축을 푼 dlp-cloud-functions-tutorials-master 폴더로 이동하여 폴더를 열고 sample_data 폴더를 선택합니다. 업로드를 클릭하여 폴더의 콘텐츠를 Cloud Storage에 업로드합니다.

나중에 사용할 수 있도록 Cloud Storage 버킷의 이름을 기록해 둡니다. 파일 업로드가 완료되면 계속 진행할 수 있습니다.

2단계: IAM 역할 설정

Sensitive Data Protection을 사용하여 스캔 결과를 Security Command Center로 보내려면 보안 센터 관리자Sensitive Data Protection 작업 편집자 IAM 역할이 필요합니다. 이 섹션에서는 역할을 추가하는 방법을 설명합니다. 이 섹션을 완료하려면 조직 관리자 IAM 역할이 있어야 합니다.

  1. IAM 페이지로 이동합니다.

    IAM으로 이동

  2. 주 구성원별로 보기 탭에서 Google 계정을 찾아 주 구성원 수정을 클릭합니다.
  3. 보안 센터 관리자Sensitive Data Protection 작업 편집자 역할을 추가합니다.

    1. 액세스 수정 패널에서 다른 역할 추가를 클릭합니다.
    2. 역할 선택 목록에서 보안 센터 관리자를 검색하여 선택합니다.
    3. 다른 역할 추가를 클릭합니다.
    4. 역할 선택 목록에서 DLP 작업 편집자를 검색하여 선택합니다.
    5. 저장을 클릭합니다.

이제 조직의 Sensitive Data Protection 작업 편집자 및 보안 센터 관리자 역할이 사용 설정되었습니다. 이러한 역할을 통해 이 주제의 나머지 부분에서 작업을 완료할 수 있습니다.

3단계: Security Command Center 사용 설정

  1. Google Cloud 콘솔에서 Security Command Center 페이지로 이동합니다.

    Security Command Center로 이동

  2. 조직 드롭다운 목록에서 Sensitive Data Protection을 사용 설정할 조직을 선택한 다음 선택을 클릭하세요.

  3. 표시되는 애셋 검색 사용 설정 페이지에서 현재 및 이후의 모든 프로젝트를 선택한 다음 사용 설정을 클릭합니다. Sensitive Data Protection이 애셋 검색을 시작하고 있다는 메시지가 표시됩니다.

애셋 검색이 완료되면 Sensitive Data Protection에 지원되는 Google Cloud 애셋이 표시됩니다. 애셋 검색은 몇 분 정도 걸릴 수 있으며 애셋을 표시하기 위해 페이지를 새로고침해야 할 수 있습니다.

Security Command Center 사용 설정에 대한 자세한 내용은 Security Command Center 문서를 참조하세요.

4단계: Sensitive Data Protection 사용 설정

스캔하려는 프로젝트에 Sensitive Data Protection을 사용 설정합니다. 프로젝트가 Security Command Center를 사용 설정한 조직 내에 있어야 합니다. Google Cloud 콘솔을 사용하여 Sensitive Data Protection을 사용 설정하려면 다음 안내를 따르세요.

  1. Google Cloud 콘솔에서 API에 대한 액세스 사용 설정 페이지로 이동합니다.

    API 사용 설정하기

  2. 툴바에서 이 가이드의 1단계에서 설정한 프로젝트를 선택합니다. 프로젝트에는 스캔할 Cloud Storage 버킷, BigQuery 테이블 또는 Datastore 종류가 포함되어야 합니다.
  3. 다음을 클릭합니다.
  4. 사용 설정을 클릭합니다.

이제 프로젝트에 Sensitive Data Protection이 사용 설정되었습니다.

5단계: Security Command Center에 Sensitive Data Protection을 통합 서비스로 사용 설정

Security Command Center에서 Sensitive Data Protection 스캔 발견 항목을 보려면 Sensitive Data Protection을 통합 서비스로 사용 설정합니다. 자세한 내용은 Security Command Center 문서의 Google Cloud 통합 서비스 추가를 참조하세요.

Sensitive Data Protection 발견 항목은 Security Command Center의 발견 항목 페이지에 표시됩니다.

Sensitive Data Protection 검사 스캔 구성 및 실행

이 섹션에서는 Sensitive Data Protection 검사 작업을 구성하고 실행합니다.

여기에서 구성한 검사 작업Cloud Storage에 저장된 샘플 데이터 또는 Cloud Storage, Datastore, BigQuery에 저장된 자체 데이터를 스캔하도록 Sensitive Data Protection에 지시합니다. 또한 개발자가 지정한 작업 구성은 스캔 결과를 Security Command Center에 저장하도록 Sensitive Data Protection에 지시합니다.

1단계: 프로젝트 식별자 메모

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

    Google Cloud 콘솔로 이동합니다.

  2. 선택을 클릭합니다.
  3. 다음 조직에서 선택 드롭다운 목록에서 Security Command Center를 사용 설정한 조직을 선택합니다.
  4. ID에서 스캔할 데이터가 포함된 프로젝트의 프로젝트 ID를 복사해 둡니다.
  5. 이름에서 프로젝트를 클릭하여 선택합니다.

2단계: API 탐색기를 열고 작업 구성

  1. 다음 버튼을 클릭하여 dlpJobs.create 메서드 참조 페이지의 API 탐색기로 이동합니다.

    API 탐색기 열기

  2. parent 입력란에 다음을 입력합니다. 여기서 PROJECT_ID는 1단계에서 기록한 프로젝트 ID입니다.
    projects/PROJECT_ID

요청 본문 필드의 콘텐츠를 사용할 데이터 종류(예: Cloud Storage 버킷의 샘플 데이터 또는 Cloud Storage, Datastore 또는 BigQuery에 저장된 자체 데이터)에 따라 다음 JSON으로 바꿉니다.

샘플 데이터

샘플 데이터를 저장하기 위해 Cloud Storage 버킷을 만든 경우 다음 JSON을 복사하여 요청 본문 필드에 붙여넣습니다. BUCKET_NAME을 Cloud Storage 버킷에 지정한 이름으로 바꿉니다.

{
  "inspectJob":{
    "storageConfig":{
      "cloudStorageOptions":{
        "fileSet":{
          "url":"gs://BUCKET_NAME/**"
        }
      }
    },
    "inspectConfig":{
      "infoTypes":[
        {
          "name":"EMAIL_ADDRESS"
        },
        {
          "name":"PERSON_NAME"
        },
        {
          "name": "LOCATION"
        },
        {
          "name":"PHONE_NUMBER"
        }
      ],
      "includeQuote":true,
      "minLikelihood":"UNLIKELY",
      "limits":{
        "maxFindingsPerRequest":100
      }
    },
    "actions":[
      {
        "publishSummaryToCscc":{

        }
      }
    ]
  }
}

Cloud Storage 데이터

자체 Cloud Storage 버킷을 검색하려면 다음 JSON을 복사하여 요청 본문 필드에 붙여넣습니다.

PATH_NAME을 검색할 위치의 경로로 바꿉니다. 재귀적으로 검색하려면 경로 끝에 별표 두 개를 추가하고(예: gs://path_to_files/**), 특정 디렉터리를 검색하고 하위 디렉터리는 검색하지 않으려면 경로 끝에 별표 한 개만 추가합니다(예: gs://path_to_files/*).

{
  "inspectJob":{
    "storageConfig":{
      "cloudStorageOptions":{
        "fileSet":{
          "url":"gs://PATH_NAME"
        }
      }
    },
    "inspectConfig":{
      "infoTypes":[
        {
          "name":"EMAIL_ADDRESS"
        },
        {
          "name":"PERSON_NAME"
        },
        {
          "name": "LOCATION"
        },
        {
          "name":"PHONE_NUMBER"
        }
      ],
      "includeQuote":true,
      "minLikelihood":"UNLIKELY",
      "limits":{
        "maxFindingsPerRequest":100
      }
    },
    "actions":[
      {
        "publishSummaryToCscc":{

        }
      }
    ]
  }
}

사용 가능한 검색 옵션에 대해 자세히 알아보려면 저장소 및 데이터베이스에서 민감한 정보 검사를 참조하세요.

Datastore 데이터

Datastore에 저장된 자체 데이터를 검색하려면 다음 JSON을 복사하여 요청 본문 필드에 붙여넣습니다.

DATASTORE_KIND를 Datastore 종류의 이름으로 바꿉니다. 또한 NAMESPACE_IDPROJECT_ID를 각각 네임스페이스 및 프로젝트 식별자로 대체하거나 필요에 따라 "partitionID"를 완전히 삭제할 수도 있습니다.

{
  "inspectJob":{
    "storageConfig":{
      "datastoreOptions":{
        "kind":{
          "name":"DATASTORE_KIND"
        },
        "partitionId":{
          "namespaceId":"NAMESPACE_ID",
          "projectId":"PROJECT_ID"
        }
      }
    },
    "inspectConfig":{
      "infoTypes":[
        {
          "name":"EMAIL_ADDRESS"
        },
        {
          "name":"PERSON_NAME"
        },
        {
          "name": "LOCATION"
        },
        {
          "name":"PHONE_NUMBER"
        }
      ],
      "includeQuote":true,
      "minLikelihood":"UNLIKELY",
      "limits":{
        "maxFindingsPerRequest":100
      }
    },
    "actions":[
      {
        "publishSummaryToCscc":{

        }
      }
    ]
  }
}

사용 가능한 검색 옵션에 대해 자세히 알아보려면 저장소 및 데이터베이스에서 민감한 정보 검사를 참조하세요.

BigQuery 데이터

자체 BigQuery 테이블을 검색하려면 다음과 같은 JSON을 복사하여 요청 본문 필드에 붙여넣습니다.

PROJECT_ID, BIGQUERY_DATASET_NAME, BIGQUERY_TABLE_NAME을 각각 프로젝트 ID, BigQuery 데이터 세트 이름, 테이블 이름으로 바꿉니다.

{
  "inspectJob":
  {
    "storageConfig":
    {
      "bigQueryOptions":
      {
        "tableReference":
        {
          "projectId": "PROJECT_ID",
          "datasetId": "BIGQUERY_DATASET_NAME",
          "tableId": "BIGQUERY_TABLE_NAME"
        }
      }
    },
    "inspectConfig":
    {
      "infoTypes":
      [
        {
          "name": "EMAIL_ADDRESS"
        },
        {
          "name": "PERSON_NAME"
        },
        {
          "name": "LOCATION"
        },
        {
          "name": "PHONE_NUMBER"
        }
      ],
      "includeQuote": true,
      "minLikelihood": "UNLIKELY",
      "limits":
      {
        "maxFindingsPerRequest": 100
      }
    },
    "actions":
    [
      {
        "publishSummaryToCscc":
        {
        }
      }
    ]
  }
}

사용 가능한 검색 옵션에 대해 자세히 알아보려면 저장소 및 데이터베이스에서 민감한 정보 검사를 참조하세요.

3단계: 검색 작업 시작 요청 실행

위 단계에 따라 작업을 구성한 후 실행을 클릭하여 요청을 전송합니다. 요청이 성공하면 성공 코드와 만든 Sensitive Data Protection 작업의 상태를 나타내는 JSON 객체 및 성공 코드와 함께 요청 아래에 응답이 나타납니다.

Sensitive Data Protection 검사 스캔의 상태 확인

스캔 요청에 대한 응답에는 검사 스캔 작업의 작업 ID가 "name" 키로, 검사 스캔 작업의 현재 상태가 "state" 키로 포함됩니다. 요청을 제출한 직후 작업 상태는 "PENDING"입니다.

검색 요청을 제출하면 콘텐츠 검사가 즉시 시작됩니다.

검사 작업의 상태를 확인하려면 다음 안내를 따르세요.

  1. 다음 버튼을 클릭하여 dlpJobs.get 메서드 참조 페이지의 API 탐색기로 이동합니다.

    API 탐색기 열기

  2. name 입력란에 스캔 요청에 대한 JSON 응답에서 가져온 작업 이름을 다음 형식으로 입력합니다.
    projects/PROJECT_ID/dlpJobs/JOB_ID
    작업 ID는 i-1234567890123456789 형식입니다.
  3. 요청을 제출하려면 실행을 클릭합니다.

응답 JSON 객체의 "state" 키에 작업이 "DONE"으로 표시될 경우 검사 작업이 완료된 것입니다.

나머지 응답 JSON을 보려면 페이지를 아래로 스크롤하세요. "result" > "infoTypeStats" 아래에 나열된 각 정보 유형에 해당하는 "count"가 있어야 합니다. 그렇지 않은 경우 JSON을 정확하게 입력했는지, 데이터의 경로 또는 위치가 올바른지 확인하세요.

검사 작업이 완료되면 이 가이드의 다음 섹션으로 이동하여 Security Command Center에서 스캔 결과를 볼 수 있습니다.

코드 샘플: Cloud Storage 버킷 검사

이 예시에서는 DLP API를 사용하여 Cloud Storage 버킷을 검사하고 Security Command Center로 발견 항목을 전송하는 검사 작업을 만드는 방법을 보여줍니다.

C#

Sensitive Data Protection의 클라이언트 라이브러리를 설치하고 사용하는 방법은 Sensitive Data Protection 클라이언트 라이브러리를 참조하세요.

Sensitive Data Protection에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.


using System.Collections.Generic;
using System.Linq;
using Google.Api.Gax.ResourceNames;
using Google.Cloud.Dlp.V2;
using static Google.Cloud.Dlp.V2.InspectConfig.Types;

public class InspectStorageWithSCCIntegration
{
    public static DlpJob SendGcsData(
        string projectId,
        string gcsPath,
        Likelihood minLikelihood = Likelihood.Unlikely,
        IEnumerable<InfoType> infoTypes = null)
    {
        // Instantiate the dlp client.
        var dlp = DlpServiceClient.Create();

        // Specify the GCS file to be inspected.
        var storageConfig = new StorageConfig
        {
            CloudStorageOptions = new CloudStorageOptions
            {
                FileSet = new CloudStorageOptions.Types.FileSet
                {
                    Url = gcsPath
                }
            }
        };

        // Specify the type of info to be inspected and construct the inspect config.
        var inspectConfig = new InspectConfig
        {
            InfoTypes =
            {
                infoTypes ?? new InfoType[]
                {
                    new InfoType { Name = "EMAIL_ADDRESS" },
                    new InfoType { Name = "PERSON_NAME" },
                    new InfoType { Name = "LOCATION" },
                    new InfoType { Name = "PHONE_NUMBER" }
                }
            },
            IncludeQuote = true,
            MinLikelihood = minLikelihood,
            Limits = new FindingLimits
            {
                MaxFindingsPerRequest = 100
            }
        };

        // Construct the SCC action which will be performed after inspecting the storage.
        var actions = new Action[]
        {
            new Action
            {
                PublishSummaryToCscc = new Action.Types.PublishSummaryToCscc()
            }
        };

        // Construct the inspect job config using storage config, inspect config and action.
        var inspectJob = new InspectJobConfig
        {
            StorageConfig = storageConfig,
            InspectConfig = inspectConfig,
            Actions = { actions }
        };

        // Construct the request.
        var request = new CreateDlpJobRequest
        {
            ParentAsLocationName = new LocationName(projectId, "global"),
            InspectJob = inspectJob
        };

        // Call the API.
        DlpJob response = dlp.CreateDlpJob(request);

        return response;
    }
}

Go

Sensitive Data Protection의 클라이언트 라이브러리를 설치하고 사용하는 방법은 Sensitive Data Protection 클라이언트 라이브러리를 참조하세요.

Sensitive Data Protection에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

import (
	"context"
	"fmt"
	"io"

	dlp "cloud.google.com/go/dlp/apiv2"
	"cloud.google.com/go/dlp/apiv2/dlppb"
)

// inspectGCSFileSendToScc inspects sensitive data in a Google Cloud Storage (GCS) file
// and sends the inspection results to Google Cloud Security Command Center (SCC) for further analysis.
func inspectGCSFileSendToScc(w io.Writer, projectID, gcsPath string) error {
	// projectID := "my-project-id"
	// gcsPath := "gs://" + "your-bucket-name" + "path/to/file.txt"

	ctx := context.Background()

	// Initialize a client once and reuse it to send multiple requests. Clients
	// are safe to use across goroutines. When the client is no longer needed,
	// call the Close method to cleanup its resources.
	client, err := dlp.NewClient(ctx)
	if err != nil {
		return err
	}

	// Closing the client safely cleans up background resources.
	defer client.Close()

	// Specify the GCS file to be inspected.
	cloudStorageOptions := &dlppb.CloudStorageOptions{
		FileSet: &dlppb.CloudStorageOptions_FileSet{
			Url: gcsPath,
		},
	}

	// storageCfg represents the configuration for data inspection in various storage types.
	storageConfig := &dlppb.StorageConfig{
		Type: &dlppb.StorageConfig_CloudStorageOptions{
			CloudStorageOptions: cloudStorageOptions,
		},
	}

	// Specify the type of info the inspection will look for.
	// See https://cloud.google.com/dlp/docs/infotypes-reference for complete list of info types
	infoTypes := []*dlppb.InfoType{
		{Name: "EMAIL_ADDRESS"},
		{Name: "PERSON_NAME"},
		{Name: "LOCATION"},
		{Name: "PHONE_NUMBER"},
	}

	// The minimum likelihood required before returning a match.
	minLikelihood := dlppb.Likelihood_UNLIKELY

	// The maximum number of findings to report (0 = server maximum).
	findingLimits := &dlppb.InspectConfig_FindingLimits{
		MaxFindingsPerItem: 100,
	}

	inspectConfig := &dlppb.InspectConfig{
		InfoTypes:     infoTypes,
		MinLikelihood: minLikelihood,
		Limits:        findingLimits,
		IncludeQuote:  true,
	}

	// Specify the action that is triggered when the job completes.
	action := &dlppb.Action{
		Action: &dlppb.Action_PublishSummaryToCscc_{
			PublishSummaryToCscc: &dlppb.Action_PublishSummaryToCscc{},
		},
	}

	// Configure the inspection job we want the service to perform.
	inspectJobConfig := &dlppb.InspectJobConfig{
		StorageConfig: storageConfig,
		InspectConfig: inspectConfig,
		Actions: []*dlppb.Action{
			action,
		},
	}

	// Create the request for the job configured above.
	req := &dlppb.CreateDlpJobRequest{
		Parent: fmt.Sprintf("projects/%s/locations/global", projectID),
		Job: &dlppb.CreateDlpJobRequest_InspectJob{
			InspectJob: inspectJobConfig,
		},
	}

	// Send the request.
	resp, err := client.CreateDlpJob(ctx, req)
	if err != nil {
		return err
	}

	// Print the result.
	fmt.Fprintf(w, "Job created successfully: %v", resp.Name)
	return nil
}

Java

Sensitive Data Protection의 클라이언트 라이브러리를 설치하고 사용하는 방법은 Sensitive Data Protection 클라이언트 라이브러리를 참조하세요.

Sensitive Data Protection에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.


import com.google.cloud.dlp.v2.DlpServiceClient;
import com.google.privacy.dlp.v2.Action;
import com.google.privacy.dlp.v2.CloudStorageOptions;
import com.google.privacy.dlp.v2.CreateDlpJobRequest;
import com.google.privacy.dlp.v2.DlpJob;
import com.google.privacy.dlp.v2.InfoType;
import com.google.privacy.dlp.v2.InfoTypeStats;
import com.google.privacy.dlp.v2.InspectConfig;
import com.google.privacy.dlp.v2.InspectDataSourceDetails;
import com.google.privacy.dlp.v2.InspectJobConfig;
import com.google.privacy.dlp.v2.Likelihood;
import com.google.privacy.dlp.v2.LocationName;
import com.google.privacy.dlp.v2.StorageConfig;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class InspectGcsFileSendToScc {

  private static final int TIMEOUT_MINUTES = 15;

  public static void main(String[] args) throws Exception {
    // TODO(developer): Replace these variables before running the sample.
    // The Google Cloud project id to use as a parent resource.
    String projectId = "your-project-id";
    // The name of the file in the Google Cloud Storage bucket.
    String gcsPath = "gs://" + "your-bucket-name" + "path/to/file.txt";
    createJobSendToScc(projectId, gcsPath);
  }

  // Creates a DLP Job to scan the sample data stored in a Cloud Storage and save its scan results
  // to Security Command Center.
  public static void createJobSendToScc(String projectId, String gcsPath)
      throws IOException, InterruptedException {
    // 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 (DlpServiceClient dlpServiceClient = DlpServiceClient.create()) {

      // Specify the GCS file to be inspected.
      CloudStorageOptions cloudStorageOptions =
          CloudStorageOptions.newBuilder()
              .setFileSet(CloudStorageOptions.FileSet.newBuilder().setUrl(gcsPath))
              .build();

      StorageConfig storageConfig =
          StorageConfig.newBuilder()
              .setCloudStorageOptions(cloudStorageOptions)
              .build();

      // Specify the type of info the inspection will look for.
      // See https://cloud.google.com/dlp/docs/infotypes-reference for complete list of info types
      List<InfoType> infoTypes =
          Stream.of("EMAIL_ADDRESS", "PERSON_NAME", "LOCATION", "PHONE_NUMBER")
              .map(it -> InfoType.newBuilder().setName(it).build())
              .collect(Collectors.toList());

      // The minimum likelihood required before returning a match.
      // See: https://cloud.google.com/dlp/docs/likelihood
      Likelihood minLikelihood = Likelihood.UNLIKELY;

      // The maximum number of findings to report (0 = server maximum)
      InspectConfig.FindingLimits findingLimits =
          InspectConfig.FindingLimits.newBuilder().setMaxFindingsPerItem(100).build();

      InspectConfig inspectConfig =
          InspectConfig.newBuilder()
              .addAllInfoTypes(infoTypes)
              .setIncludeQuote(true)
              .setMinLikelihood(minLikelihood)
              .setLimits(findingLimits)
              .build();

      // Specify the action that is triggered when the job completes.
      Action.PublishSummaryToCscc publishSummaryToCscc =
          Action.PublishSummaryToCscc.getDefaultInstance();
      Action action = Action.newBuilder().setPublishSummaryToCscc(publishSummaryToCscc).build();

      // Configure the inspection job we want the service to perform.
      InspectJobConfig inspectJobConfig =
          InspectJobConfig.newBuilder()
              .setInspectConfig(inspectConfig)
              .setStorageConfig(storageConfig)
              .addActions(action)
              .build();

      // Construct the job creation request to be sent by the client.
      CreateDlpJobRequest createDlpJobRequest =
          CreateDlpJobRequest.newBuilder()
              .setParent(LocationName.of(projectId, "global").toString())
              .setInspectJob(inspectJobConfig)
              .build();

      // Send the job creation request and process the response.
      DlpJob response = dlpServiceClient.createDlpJob(createDlpJobRequest);
      // Get the current time.
      long startTime = System.currentTimeMillis();

      // Check if the job state is DONE.
      while (response.getState() != DlpJob.JobState.DONE) {
        // Sleep for 30 second.
        Thread.sleep(30000);

        // Get the updated job status.
        response = dlpServiceClient.getDlpJob(response.getName());

        // Check if the timeout duration has exceeded.
        long elapsedTime = System.currentTimeMillis() - startTime;
        if (TimeUnit.MILLISECONDS.toMinutes(elapsedTime) >= TIMEOUT_MINUTES) {
          System.out.printf("Job did not complete within %d minutes.%n", TIMEOUT_MINUTES);
          break;
        }
      }
      // Print the results.
      System.out.println("Job status: " + response.getState());
      System.out.println("Job name: " + response.getName());
      InspectDataSourceDetails.Result result = response.getInspectDetails().getResult();
      System.out.println("Findings: ");
      for (InfoTypeStats infoTypeStat : result.getInfoTypeStatsList()) {
        System.out.print("\tInfo type: " + infoTypeStat.getInfoType().getName());
        System.out.println("\tCount: " + infoTypeStat.getCount());
      }
    }
  }
}

Node.js

Sensitive Data Protection의 클라이언트 라이브러리를 설치하고 사용하는 방법은 Sensitive Data Protection 클라이언트 라이브러리를 참조하세요.

Sensitive Data Protection에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

// Imports the Google Cloud Data Loss Prevention library
const DLP = require('@google-cloud/dlp');

// Instantiates a client
const dlpClient = new DLP.DlpServiceClient();

// The project ID to run the API call under
// const projectId = 'your-project-id';

// The name of the file in the bucket
// const gcsPath = 'gcs-file-path';

async function inspectGCSSendToScc() {
  // Specify the storage configuration object with GCS URL.
  const storageConfig = {
    cloudStorageOptions: {
      fileSet: {
        url: gcsPath,
      },
    },
  };

  // Construct the info types to look for in the GCS file.
  const infoTypes = [
    {name: 'EMAIL_ADDRESS'},
    {name: 'PERSON_NAME'},
    {name: 'LOCATION'},
    {name: 'PHONE_NUMBER'},
  ];

  // Construct the inspection configuration.
  const inspectConfig = {
    infoTypes,
    minLikelihood: DLP.protos.google.privacy.dlp.v2.Likelihood.UNLIKELY,
    limits: {
      maxFindingsPerItem: 100,
    },
  };

  // Specify the action that is triggered when the job completes.
  const action = {
    publishSummaryToCscc: {},
  };

  // Configure the inspection job we want the service to perform.
  const jobConfig = {
    inspectConfig,
    storageConfig,
    actions: [action],
  };

  // Construct the job creation request to be sent by the client.
  const request = {
    parent: `projects/${projectId}/locations/global`,
    inspectJob: jobConfig,
  };

  // Send the job creation request and process the response.
  const [jobsResponse] = await dlpClient.createDlpJob(request);
  const jobName = jobsResponse.name;

  // Waiting for a maximum of 15 minutes for the job to get complete.
  let job;
  let numOfAttempts = 30;
  while (numOfAttempts > 0) {
    // Fetch DLP Job status
    [job] = await dlpClient.getDlpJob({name: jobName});

    // Check if the job has completed.
    if (job.state === 'DONE') {
      break;
    }
    if (job.state === 'FAILED') {
      console.log('Job Failed, Please check the configuration.');
      return;
    }
    // Sleep for a short duration before checking the job status again.
    await new Promise(resolve => {
      setTimeout(() => resolve(), 30000);
    });
    numOfAttempts -= 1;
  }

  // Print out the results.
  const infoTypeStats = job.inspectDetails.result.infoTypeStats;
  if (infoTypeStats.length > 0) {
    infoTypeStats.forEach(infoTypeStat => {
      console.log(
        `Found ${infoTypeStat.count} instance(s) of infoType ${infoTypeStat.infoType.name}.`
      );
    });
  } else {
    console.log('No findings.');
  }
}
await inspectGCSSendToScc();

PHP

Sensitive Data Protection의 클라이언트 라이브러리를 설치하고 사용하는 방법은 Sensitive Data Protection 클라이언트 라이브러리를 참조하세요.

Sensitive Data Protection에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

use Google\Cloud\Dlp\V2\CloudStorageOptions;
use Google\Cloud\Dlp\V2\CloudStorageOptions\FileSet;
use Google\Cloud\Dlp\V2\DlpServiceClient;
use Google\Cloud\Dlp\V2\InfoType;
use Google\Cloud\Dlp\V2\InspectConfig;
use Google\Cloud\Dlp\V2\InspectConfig\FindingLimits;
use Google\Cloud\Dlp\V2\StorageConfig;
use Google\Cloud\Dlp\V2\Likelihood;
use Google\Cloud\Dlp\V2\Action;
use Google\Cloud\Dlp\V2\Action\PublishSummaryToCscc;
use Google\Cloud\Dlp\V2\InspectJobConfig;
use Google\Cloud\Dlp\V2\DlpJob\JobState;

/**
 * (GCS) Send Cloud DLP scan results to Security Command Center.
 * Using Cloud Data Loss Prevention to scan specific Google Cloud resources and send data to Security Command Center.
 *
 * @param string $callingProjectId  The project ID to run the API call under.
 * @param string $gcsUri            GCS file to be inspected.
 */
function inspect_gcs_send_to_scc(
    // TODO(developer): Replace sample parameters before running the code.
    string $callingProjectId,
    string $gcsUri = 'gs://GOOGLE_STORAGE_BUCKET_NAME/dlp_sample.csv'
): void {
    // Instantiate a client.
    $dlp = new DlpServiceClient();

    // Construct the items to be inspected.
    $cloudStorageOptions = (new CloudStorageOptions())
        ->setFileSet((new FileSet())
            ->setUrl($gcsUri));

    $storageConfig = (new StorageConfig())
        ->setCloudStorageOptions(($cloudStorageOptions));

    // Specify the type of info the inspection will look for.
    $infoTypes = [
        (new InfoType())->setName('EMAIL_ADDRESS'),
        (new InfoType())->setName('PERSON_NAME'),
        (new InfoType())->setName('LOCATION'),
        (new InfoType())->setName('PHONE_NUMBER')
    ];

    // Specify how the content should be inspected.
    $inspectConfig = (new InspectConfig())
        ->setMinLikelihood(likelihood::UNLIKELY)
        ->setLimits((new FindingLimits())
            ->setMaxFindingsPerRequest(100))
        ->setInfoTypes($infoTypes)
        ->setIncludeQuote(true);

    // Specify the action that is triggered when the job completes.
    $action = (new Action())
        ->setPublishSummaryToCscc(new PublishSummaryToCscc());

    // Construct inspect job config to run.
    $inspectJobConfig = (new InspectJobConfig())
        ->setInspectConfig($inspectConfig)
        ->setStorageConfig($storageConfig)
        ->setActions([$action]);

    // Send the job creation request and process the response.
    $parent = "projects/$callingProjectId/locations/global";
    $job = $dlp->createDlpJob($parent, [
        'inspectJob' => $inspectJobConfig
    ]);

    $numOfAttempts = 10;
    do {
        printf('Waiting for job to complete' . PHP_EOL);
        sleep(10);
        $job = $dlp->getDlpJob($job->getName());
        if ($job->getState() == JobState::DONE) {
            break;
        }
        $numOfAttempts--;
    } while ($numOfAttempts > 0);

    // Print finding counts.
    printf('Job %s status: %s' . PHP_EOL, $job->getName(), JobState::name($job->getState()));
    switch ($job->getState()) {
        case JobState::DONE:
            $infoTypeStats = $job->getInspectDetails()->getResult()->getInfoTypeStats();
            if (count($infoTypeStats) === 0) {
                printf('No findings.' . PHP_EOL);
            } else {
                foreach ($infoTypeStats as $infoTypeStat) {
                    printf(
                        '  Found %s instance(s) of infoType %s' . PHP_EOL,
                        $infoTypeStat->getCount(),
                        $infoTypeStat->getInfoType()->getName()
                    );
                }
            }
            break;
        case JobState::FAILED:
            printf('Job %s had errors:' . PHP_EOL, $job->getName());
            $errors = $job->getErrors();
            foreach ($errors as $error) {
                var_dump($error->getDetails());
            }
            break;
        case JobState::PENDING:
            printf('Job has not completed. Consider a longer timeout or an asynchronous execution model' . PHP_EOL);
            break;
        default:
            printf('Unexpected job state. Most likely, the job is either running or has not yet started.');
    }
}

Python

Sensitive Data Protection의 클라이언트 라이브러리를 설치하고 사용하는 방법은 Sensitive Data Protection 클라이언트 라이브러리를 참조하세요.

Sensitive Data Protection에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

import time
from typing import List

import google.cloud.dlp

def inspect_gcs_send_to_scc(
    project: str,
    bucket: str,
    info_types: List[str],
    max_findings: int = 100,
) -> None:
    """
    Uses the Data Loss Prevention API to inspect Google Cloud Storage
    data and send the results to Google Security Command Center.
    Args:
        project: The Google Cloud project id to use as a parent resource.
        bucket: The name of the GCS bucket containing the file, as a string.
        info_types: A list of strings representing infoTypes to inspect for.
            A full list of infoType categories can be fetched from the API.
        max_findings: The maximum number of findings to report; 0 = no maximum.
    """
    # Instantiate a client.
    dlp = google.cloud.dlp_v2.DlpServiceClient()

    # Prepare info_types by converting the list of strings into a list of
    # dictionaries.
    info_types = [{"name": info_type} for info_type in info_types]

    # Construct the configuration dictionary.
    inspect_config = {
        "info_types": info_types,
        "min_likelihood": google.cloud.dlp_v2.Likelihood.UNLIKELY,
        "limits": {"max_findings_per_request": max_findings},
        "include_quote": True,
    }

    # Construct a cloud_storage_options dictionary with the bucket's URL.
    url = f"gs://{bucket}"
    storage_config = {"cloud_storage_options": {"file_set": {"url": url}}}

    # Tell the API where to send a notification when the job is complete.
    actions = [{"publish_summary_to_cscc": {}}]

    # Construct the job definition.
    job = {
        "inspect_config": inspect_config,
        "storage_config": storage_config,
        "actions": actions,
    }

    # Convert the project id into a full resource id.
    parent = f"projects/{project}"

    # Call the API.
    response = dlp.create_dlp_job(
        request={
            "parent": parent,
            "inspect_job": job,
        }
    )
    print(f"Inspection Job started : {response.name}")

    job_name = response.name

    # Waiting for maximum 15 minutes for the job to get complete.
    no_of_attempts = 30
    while no_of_attempts > 0:
        # Get the DLP job status.
        job = dlp.get_dlp_job(request={"name": job_name})
        # Check if the job has completed.
        if job.state == google.cloud.dlp_v2.DlpJob.JobState.DONE:
            break
        elif job.state == google.cloud.dlp_v2.DlpJob.JobState.FAILED:
            print("Job Failed, Please check the configuration.")
            return

        # Sleep for a short duration before checking the job status again.
        time.sleep(30)
        no_of_attempts -= 1

    # Print out the results.
    print(f"Job name: {job.name}")
    result = job.inspect_details.result
    print("Processed Bytes: ", result.processed_bytes)
    if result.info_type_stats:
        for stats in result.info_type_stats:
            print(f"Info type: {stats.info_type.name}")
            print(f"Count: {stats.count}")
    else:
        print("No findings.")

코드 샘플: BigQuery 테이블 검사

이 예시에서는 DLP API를 사용하여 BigQuery 테이블을 검사하고 Security Command Center로 발견 항목을 전송하는 검사 작업을 만드는 방법을 보여줍니다.

C#

Sensitive Data Protection의 클라이언트 라이브러리를 설치하고 사용하는 방법은 Sensitive Data Protection 클라이언트 라이브러리를 참조하세요.

Sensitive Data Protection에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.


using System.Collections.Generic;
using Google.Api.Gax.ResourceNames;
using Google.Cloud.Dlp.V2;
using static Google.Cloud.Dlp.V2.InspectConfig.Types;

public class InspectBigQueryWithSCCIntegration
{
    public static DlpJob SendBigQueryData(
        string projectId,
        Likelihood minLikelihood = Likelihood.Unlikely,
        IEnumerable<InfoType> infoTypes = null)
    {
        // Instantiate the dlp client.
        var dlp = DlpServiceClient.Create();

        // Construct the storage config by providing the table to be inspected.
        var storageConfig = new StorageConfig
        {
            BigQueryOptions = new BigQueryOptions
            {
                TableReference = new BigQueryTable
                {
                    ProjectId = "bigquery-public-data",
                    DatasetId = "usa_names",
                    TableId = "usa_1910_current",
                }
            }
        };

        // Construct the inspect config by specifying the type of info to be inspected.
        var inspectConfig = new InspectConfig
        {
            InfoTypes =
            {
                infoTypes ?? new InfoType[]
                {
                    new InfoType { Name = "EMAIL_ADDRESS" },
                    new InfoType { Name = "PERSON_NAME" }
                }
            },
            IncludeQuote = true,
            MinLikelihood = minLikelihood,
            Limits = new FindingLimits
            {
                MaxFindingsPerRequest = 100
            }
        };

        // Construct the SCC action which will be performed after inspecting the source.
        var actions = new Action[]
        {
            new Action
            {
                PublishSummaryToCscc = new Action.Types.PublishSummaryToCscc()
            }
        };

        // Construct the inspect job config using storage config, inspect config and action.
        var inspectJob = new InspectJobConfig
        {
            StorageConfig = storageConfig,
            InspectConfig = inspectConfig,
            Actions = { actions }
        };

        // Construct the request.
        var request = new CreateDlpJobRequest
        {
            ParentAsLocationName = new LocationName(projectId, "global"),
            InspectJob = inspectJob
        };

        // Call the API.
        DlpJob response = dlp.CreateDlpJob(request);

        System.Console.WriteLine($"Job created successfully. Job name: {response.Name}");

        return response;
    }
}

Go

Sensitive Data Protection의 클라이언트 라이브러리를 설치하고 사용하는 방법은 Sensitive Data Protection 클라이언트 라이브러리를 참조하세요.

Sensitive Data Protection에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

import (
	"context"
	"fmt"
	"io"

	dlp "cloud.google.com/go/dlp/apiv2"
	"cloud.google.com/go/dlp/apiv2/dlppb"
)

// inspectBigQuerySendToScc configures the inspection job that instructs Cloud DLP to scan data stored in BigQuery,
// and also instructs Cloud DLP to save its scan results to Security Command Center.
func inspectBigQuerySendToScc(w io.Writer, projectID, bigQueryDatasetId, bigQueryTableId string) error {
	// projectID := "my-project-id"
	// bigQueryDatasetId := "your-project-bigquery-dataset"
	// bigQueryTableId := "your-project-bigquery_table"

	ctx := context.Background()

	// Initialize a client once and reuse it to send multiple requests. Clients
	// are safe to use across goroutines. When the client is no longer needed,
	// call the Close method to cleanup its resources.
	client, err := dlp.NewClient(ctx)
	if err != nil {
		return err
	}

	// Closing the client safely cleans up background resources.
	defer client.Close()

	// Specify the BigQuery table to be inspected.
	tableReference := &dlppb.BigQueryTable{
		ProjectId: projectID,
		DatasetId: bigQueryDatasetId,
		TableId:   bigQueryTableId,
	}

	bigQueryOptions := &dlppb.BigQueryOptions{
		TableReference: tableReference,
	}

	// Specify the type of storage that you have configured.
	storageConfig := &dlppb.StorageConfig{
		Type: &dlppb.StorageConfig_BigQueryOptions{
			BigQueryOptions: bigQueryOptions,
		},
	}

	// Specify the type of info the inspection will look for.
	// See https://cloud.google.com/dlp/docs/infotypes-reference for complete list of info types.
	infoTypes := []*dlppb.InfoType{
		{Name: "EMAIL_ADDRESS"},
		{Name: "PERSON_NAME"},
		{Name: "LOCATION"},
		{Name: "PHONE_NUMBER"},
	}

	// The minimum likelihood required before returning a match.
	minLikelihood := dlppb.Likelihood_UNLIKELY

	// The maximum number of findings to report (0 = server maximum).
	findingLimits := &dlppb.InspectConfig_FindingLimits{
		MaxFindingsPerItem: 100,
	}

	// Specify how the content should be inspected.
	inspectConfig := &dlppb.InspectConfig{
		InfoTypes:     infoTypes,
		MinLikelihood: minLikelihood,
		Limits:        findingLimits,
		IncludeQuote:  true,
	}

	// Specify the action that is triggered when the job completes.
	action := &dlppb.Action{
		Action: &dlppb.Action_PublishSummaryToCscc_{
			PublishSummaryToCscc: &dlppb.Action_PublishSummaryToCscc{},
		},
	}

	// Configure the inspection job we want the service to perform.
	inspectJobConfig := &dlppb.InspectJobConfig{
		StorageConfig: storageConfig,
		InspectConfig: inspectConfig,
		Actions: []*dlppb.Action{
			action,
		},
	}

	// Create the request for the job configured above.
	req := &dlppb.CreateDlpJobRequest{
		Parent: fmt.Sprintf("projects/%s/locations/global", projectID),
		Job: &dlppb.CreateDlpJobRequest_InspectJob{
			InspectJob: inspectJobConfig,
		},
	}

	// Send the request.
	resp, err := client.CreateDlpJob(ctx, req)
	if err != nil {
		return err
	}

	// Print the result
	fmt.Fprintf(w, "Job created successfully: %v", resp.Name)
	return nil
}

Java

Sensitive Data Protection의 클라이언트 라이브러리를 설치하고 사용하는 방법은 Sensitive Data Protection 클라이언트 라이브러리를 참조하세요.

Sensitive Data Protection에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.


import com.google.cloud.dlp.v2.DlpServiceClient;
import com.google.privacy.dlp.v2.Action;
import com.google.privacy.dlp.v2.BigQueryOptions;
import com.google.privacy.dlp.v2.BigQueryTable;
import com.google.privacy.dlp.v2.CreateDlpJobRequest;
import com.google.privacy.dlp.v2.DlpJob;
import com.google.privacy.dlp.v2.InfoType;
import com.google.privacy.dlp.v2.InfoTypeStats;
import com.google.privacy.dlp.v2.InspectConfig;
import com.google.privacy.dlp.v2.InspectDataSourceDetails;
import com.google.privacy.dlp.v2.InspectJobConfig;
import com.google.privacy.dlp.v2.Likelihood;
import com.google.privacy.dlp.v2.LocationName;
import com.google.privacy.dlp.v2.StorageConfig;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class InspectBigQuerySendToScc {

  private static final int TIMEOUT_MINUTES = 15;

  public static void main(String[] args) throws Exception {
    // TODO(developer): Replace these variables before running the sample.
    // The Google Cloud project id to use as a parent resource.
    String projectId = "your-project-id";
    // The BigQuery dataset id to be used and the reference table name to be inspected.
    String bigQueryDatasetId = "your-project-bigquery-dataset";
    String bigQueryTableId = "your-project-bigquery_table";
    inspectBigQuerySendToScc(projectId, bigQueryDatasetId, bigQueryTableId);
  }

  // Inspects a BigQuery Table to send data to Security Command Center.
  public static void inspectBigQuerySendToScc(
      String projectId, String bigQueryDatasetId, String bigQueryTableId) throws Exception {
    // 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 (DlpServiceClient dlpServiceClient = DlpServiceClient.create()) {

      // Specify the BigQuery table to be inspected.
      BigQueryTable tableReference =
          BigQueryTable.newBuilder()
              .setProjectId(projectId)
              .setDatasetId(bigQueryDatasetId)
              .setTableId(bigQueryTableId)
              .build();

      BigQueryOptions bigQueryOptions =
          BigQueryOptions.newBuilder().setTableReference(tableReference).build();

      StorageConfig storageConfig =
          StorageConfig.newBuilder().setBigQueryOptions(bigQueryOptions).build();

      // Specify the type of info the inspection will look for.
      List<InfoType> infoTypes =
          Stream.of("EMAIL_ADDRESS", "PERSON_NAME", "LOCATION", "PHONE_NUMBER")
              .map(it -> InfoType.newBuilder().setName(it).build())
              .collect(Collectors.toList());

      // The minimum likelihood required before returning a match.
      Likelihood minLikelihood = Likelihood.UNLIKELY;

      // The maximum number of findings to report (0 = server maximum)
      InspectConfig.FindingLimits findingLimits =
          InspectConfig.FindingLimits.newBuilder().setMaxFindingsPerItem(100).build();

      // Specify how the content should be inspected.
      InspectConfig inspectConfig =
          InspectConfig.newBuilder()
              .addAllInfoTypes(infoTypes)
              .setIncludeQuote(true)
              .setMinLikelihood(minLikelihood)
              .setLimits(findingLimits)
              .build();

      // Specify the action that is triggered when the job completes.
      Action.PublishSummaryToCscc publishSummaryToCscc =
          Action.PublishSummaryToCscc.getDefaultInstance();
      Action action = Action.newBuilder().setPublishSummaryToCscc(publishSummaryToCscc).build();

      // Configure the inspection job we want the service to perform.
      InspectJobConfig inspectJobConfig =
          InspectJobConfig.newBuilder()
              .setInspectConfig(inspectConfig)
              .setStorageConfig(storageConfig)
              .addActions(action)
              .build();

      // Construct the job creation request to be sent by the client.
      CreateDlpJobRequest createDlpJobRequest =
          CreateDlpJobRequest.newBuilder()
              .setParent(LocationName.of(projectId, "global").toString())
              .setInspectJob(inspectJobConfig)
              .build();

      // Send the job creation request and process the response.
      DlpJob response = dlpServiceClient.createDlpJob(createDlpJobRequest);

      // Get the current time.
      long startTime = System.currentTimeMillis();

      // Check if the job state is DONE.
      while (response.getState() != DlpJob.JobState.DONE) {
        // Sleep for 30 second.
        Thread.sleep(30000);

        // Get the updated job status.
        response = dlpServiceClient.getDlpJob(response.getName());

        // Check if the timeout duration has exceeded.
        long elapsedTime = System.currentTimeMillis() - startTime;
        if (TimeUnit.MILLISECONDS.toMinutes(elapsedTime) >= TIMEOUT_MINUTES) {
          System.out.printf("Job did not complete within %d minutes.%n", TIMEOUT_MINUTES);
          break;
        }
      }
      // Print the results.
      System.out.println("Job status: " + response.getState());
      System.out.println("Job name: " + response.getName());
      InspectDataSourceDetails.Result result = response.getInspectDetails().getResult();
      System.out.println("Findings: ");
      for (InfoTypeStats infoTypeStat : result.getInfoTypeStatsList()) {
        System.out.print("\tInfo type: " + infoTypeStat.getInfoType().getName());
        System.out.println("\tCount: " + infoTypeStat.getCount());
      }
    }
  }
}

Node.js

Sensitive Data Protection의 클라이언트 라이브러리를 설치하고 사용하는 방법은 Sensitive Data Protection 클라이언트 라이브러리를 참조하세요.

Sensitive Data Protection에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

// Imports the Google Cloud Data Loss Prevention library
const DLP = require('@google-cloud/dlp');

// Instantiates a client
const dlp = new DLP.DlpServiceClient();

// The project ID to run the API call under.
// const projectId = "your-project-id";

// The project ID the table is stored under
// This may or (for public datasets) may not equal the calling project ID
// const dataProjectId = 'my-project';

// The ID of the dataset to inspect, e.g. 'my_dataset'
// const datasetId = 'my_dataset';

// The ID of the table to inspect, e.g. 'my_table'
// const tableId = 'my_table';

async function inspectBigQuerySendToScc() {
  // Specify the storage configuration object with big query table.
  const storageItem = {
    bigQueryOptions: {
      tableReference: {
        projectId: dataProjectId,
        datasetId: datasetId,
        tableId: tableId,
      },
    },
  };

  // Specify the type of info the inspection will look for.
  const infoTypes = [
    {name: 'EMAIL_ADDRESS'},
    {name: 'PERSON_NAME'},
    {name: 'LOCATION'},
    {name: 'PHONE_NUMBER'},
  ];

  // Construct inspect configuration.
  const inspectConfig = {
    infoTypes: infoTypes,
    includeQuote: true,
    minLikelihood: DLP.protos.google.privacy.dlp.v2.Likelihood.UNLIKELY,
    limits: {
      maxFindingsPerItem: 100,
    },
  };

  // Specify the action that is triggered when the job completes.
  const action = {
    publishSummaryToCscc: {
      enable: true,
    },
  };

  // Configure the inspection job we want the service to perform.
  const inspectJobConfig = {
    inspectConfig: inspectConfig,
    storageConfig: storageItem,
    actions: [action],
  };

  // Construct the job creation request to be sent by the client.
  const request = {
    parent: `projects/${projectId}/locations/global`,
    inspectJob: inspectJobConfig,
  };

  // Send the job creation request and process the response.
  const [jobsResponse] = await dlp.createDlpJob(request);
  const jobName = jobsResponse.name;

  // Waiting for a maximum of 15 minutes for the job to get complete.
  let job;
  let numOfAttempts = 30;
  while (numOfAttempts > 0) {
    // Fetch DLP Job status
    [job] = await dlp.getDlpJob({name: jobName});

    // Check if the job has completed.
    if (job.state === 'DONE') {
      break;
    }
    if (job.state === 'FAILED') {
      console.log('Job Failed, Please check the configuration.');
      return;
    }
    // Sleep for a short duration before checking the job status again.
    await new Promise(resolve => {
      setTimeout(() => resolve(), 30000);
    });
    numOfAttempts -= 1;
  }

  // Print out the results.
  const infoTypeStats = job.inspectDetails.result.infoTypeStats;
  if (infoTypeStats.length > 0) {
    infoTypeStats.forEach(infoTypeStat => {
      console.log(
        `  Found ${infoTypeStat.count} instance(s) of infoType ${infoTypeStat.infoType.name}.`
      );
    });
  } else {
    console.log('No findings.');
  }
}
await inspectBigQuerySendToScc();

PHP

Sensitive Data Protection의 클라이언트 라이브러리를 설치하고 사용하는 방법은 Sensitive Data Protection 클라이언트 라이브러리를 참조하세요.

Sensitive Data Protection에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

use Google\Cloud\Dlp\V2\DlpServiceClient;
use Google\Cloud\Dlp\V2\InfoType;
use Google\Cloud\Dlp\V2\InspectConfig;
use Google\Cloud\Dlp\V2\InspectConfig\FindingLimits;
use Google\Cloud\Dlp\V2\StorageConfig;
use Google\Cloud\Dlp\V2\Likelihood;
use Google\Cloud\Dlp\V2\Action;
use Google\Cloud\Dlp\V2\Action\PublishSummaryToCscc;
use Google\Cloud\Dlp\V2\BigQueryOptions;
use Google\Cloud\Dlp\V2\BigQueryTable;
use Google\Cloud\Dlp\V2\InspectJobConfig;
use Google\Cloud\Dlp\V2\DlpJob\JobState;

/**
 * (BIGQUERY) Send Cloud DLP scan results to Security Command Center.
 * Using Cloud Data Loss Prevention to scan specific Google Cloud resources and send data to Security Command Center.
 *
 * @param string $callingProjectId  The project ID to run the API call under.
 * @param string $projectId         The ID of the Project.
 * @param string $datasetId         The ID of the BigQuery Dataset.
 * @param string $tableId           The ID of the BigQuery Table to be inspected.
 */
function inspect_bigquery_send_to_scc(
    // TODO(developer): Replace sample parameters before running the code.
    string $callingProjectId,
    string $projectId,
    string $datasetId,
    string $tableId
): void {
    // Instantiate a client.
    $dlp = new DlpServiceClient();

    // Construct the items to be inspected.
    $bigqueryTable = (new BigQueryTable())
        ->setProjectId($projectId)
        ->setDatasetId($datasetId)
        ->setTableId($tableId);
    $bigQueryOptions = (new BigQueryOptions())
        ->setTableReference($bigqueryTable);

    $storageConfig = (new StorageConfig())
        ->setBigQueryOptions(($bigQueryOptions));

    // Specify the type of info the inspection will look for.
    $infoTypes = [
        (new InfoType())->setName('EMAIL_ADDRESS'),
        (new InfoType())->setName('PERSON_NAME'),
        (new InfoType())->setName('LOCATION'),
        (new InfoType())->setName('PHONE_NUMBER')
    ];

    // Specify how the content should be inspected.
    $inspectConfig = (new InspectConfig())
        ->setMinLikelihood(likelihood::UNLIKELY)
        ->setLimits((new FindingLimits())
            ->setMaxFindingsPerRequest(100))
        ->setInfoTypes($infoTypes)
        ->setIncludeQuote(true);

    // Specify the action that is triggered when the job completes.
    $action = (new Action())
        ->setPublishSummaryToCscc(new PublishSummaryToCscc());

    // Configure the inspection job we want the service to perform.
    $inspectJobConfig = (new InspectJobConfig())
        ->setInspectConfig($inspectConfig)
        ->setStorageConfig($storageConfig)
        ->setActions([$action]);

    // Send the job creation request and process the response.
    $parent = "projects/$callingProjectId/locations/global";
    $job = $dlp->createDlpJob($parent, [
        'inspectJob' => $inspectJobConfig
    ]);

    $numOfAttempts = 10;
    do {
        printf('Waiting for job to complete' . PHP_EOL);
        sleep(10);
        $job = $dlp->getDlpJob($job->getName());
        if ($job->getState() == JobState::DONE) {
            break;
        }
        $numOfAttempts--;
    } while ($numOfAttempts > 0);

    // Print finding counts.
    printf('Job %s status: %s' . PHP_EOL, $job->getName(), JobState::name($job->getState()));
    switch ($job->getState()) {
        case JobState::DONE:
            $infoTypeStats = $job->getInspectDetails()->getResult()->getInfoTypeStats();
            if (count($infoTypeStats) === 0) {
                printf('No findings.' . PHP_EOL);
            } else {
                foreach ($infoTypeStats as $infoTypeStat) {
                    printf(
                        '  Found %s instance(s) of infoType %s' . PHP_EOL,
                        $infoTypeStat->getCount(),
                        $infoTypeStat->getInfoType()->getName()
                    );
                }
            }
            break;
        case JobState::FAILED:
            printf('Job %s had errors:' . PHP_EOL, $job->getName());
            $errors = $job->getErrors();
            foreach ($errors as $error) {
                var_dump($error->getDetails());
            }
            break;
        case JobState::PENDING:
            printf('Job has not completed. Consider a longer timeout or an asynchronous execution model' . PHP_EOL);
            break;
        default:
            printf('Unexpected job state. Most likely, the job is either running or has not yet started.');
    }
}

Python

Sensitive Data Protection의 클라이언트 라이브러리를 설치하고 사용하는 방법은 Sensitive Data Protection 클라이언트 라이브러리를 참조하세요.

Sensitive Data Protection에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

import time
from typing import List

import google.cloud.dlp

def inspect_bigquery_send_to_scc(
    project: str,
    info_types: List[str],
    max_findings: int = 100,
) -> None:
    """
    Uses the Data Loss Prevention API to inspect public bigquery dataset
    and send the results to Google Security Command Center.
    Args:
        project: The Google Cloud project id to use as a parent resource.
        info_types: A list of strings representing infoTypes to inspect for.
            A full list of infoType categories can be fetched from the API.
        max_findings: The maximum number of findings to report; 0 = no maximum
    """
    # Instantiate a client.
    dlp = google.cloud.dlp_v2.DlpServiceClient()

    # Prepare info_types by converting the list of strings into a list of
    # dictionaries.
    info_types = [{"name": info_type} for info_type in info_types]

    # Construct the configuration dictionary.
    inspect_config = {
        "info_types": info_types,
        "min_likelihood": google.cloud.dlp_v2.Likelihood.UNLIKELY,
        "limits": {"max_findings_per_request": max_findings},
        "include_quote": True,
    }

    # Construct a Cloud Storage Options dictionary with the big query options.
    storage_config = {
        "big_query_options": {
            "table_reference": {
                "project_id": "bigquery-public-data",
                "dataset_id": "usa_names",
                "table_id": "usa_1910_current",
            }
        }
    }

    # Tell the API where to send a notification when the job is complete.
    actions = [{"publish_summary_to_cscc": {}}]

    # Construct the job definition.
    job = {
        "inspect_config": inspect_config,
        "storage_config": storage_config,
        "actions": actions,
    }

    # Convert the project id into a full resource id.
    parent = f"projects/{project}"

    # Call the API.
    response = dlp.create_dlp_job(
        request={
            "parent": parent,
            "inspect_job": job,
        }
    )
    print(f"Inspection Job started : {response.name}")

    job_name = response.name

    # Waiting for a maximum of 15 minutes for the job to get complete.
    no_of_attempts = 30
    while no_of_attempts > 0:
        # Get the DLP job status.
        job = dlp.get_dlp_job(request={"name": job_name})
        # Check if the job has completed.
        if job.state == google.cloud.dlp_v2.DlpJob.JobState.DONE:
            break
        if job.state == google.cloud.dlp_v2.DlpJob.JobState.FAILED:
            print("Job Failed, Please check the configuration.")
            return

        # Sleep for a short duration before checking the job status again.
        time.sleep(30)
        no_of_attempts -= 1

    # Print out the results.
    print(f"Job name: {job.name}")
    result = job.inspect_details.result
    if result.info_type_stats:
        for stats in result.info_type_stats:
            print(f"Info type: {stats.info_type.name}")
            print(f"Count: {stats.count}")
    else:
        print("No findings.")

코드 샘플: Datastore 종류 검사

이 예시에서는 DLP API를 사용하여 Datastore 종류를 검사하고 Security Command Center로 발견 항목을 보내는 검사 작업을 만드는 방법을 보여줍니다.

C#

Sensitive Data Protection의 클라이언트 라이브러리를 설치하고 사용하는 방법은 Sensitive Data Protection 클라이언트 라이브러리를 참조하세요.

Sensitive Data Protection에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.


using System.Collections.Generic;
using System.Linq;
using Google.Api.Gax.ResourceNames;
using Google.Cloud.Dlp.V2;
using static Google.Cloud.Dlp.V2.InspectConfig.Types;

public class InspectDataStoreJobWithSCCIntegration
{
    public static DlpJob SendInspectDatastoreToSCC(
        string projectId,
        string kindName,
        string namespaceId,
        Likelihood minLikelihood = Likelihood.Unlikely,
        IEnumerable<InfoType> infoTypes = null)
    {
        // Instantiate the dlp client.
        var dlp = DlpServiceClient.Create();

        // Specify the Datastore entity to be inspected and construct the storage
        // config. The NamespaceId is to be used for partition entity and the datastore kind defining
        // a data set.
        var storageConfig = new StorageConfig
        {
            DatastoreOptions = new DatastoreOptions
            {
                Kind = new KindExpression { Name = kindName },
                PartitionId = new PartitionId
                {
                    NamespaceId = namespaceId,
                    ProjectId = projectId
                }
            }
        };

        // Specify the type of info to be inspected and construct the inspect config.
        var inspectConfig = new InspectConfig
        {
            InfoTypes =
            {
                infoTypes ?? new InfoType[]
                {
                    new InfoType { Name = "EMAIL_ADDRESS" },
                    new InfoType { Name = "PERSON_NAME" },
                    new InfoType { Name = "LOCATION" },
                    new InfoType { Name = "PHONE_NUMBER" }
                }
            },
            IncludeQuote = true,
            MinLikelihood = minLikelihood,
            Limits = new FindingLimits
            {
                MaxFindingsPerRequest = 100
            }
        };

        // Construct the SCC action which will be performed after inspecting the datastore.
        var actions = new Action[]
        {
            new Action
            {
                PublishSummaryToCscc = new Action.Types.PublishSummaryToCscc()
            }
        };

        // Construct the inspect job config using storage config, inspect config and action.
        var inspectJob = new InspectJobConfig
        {
            StorageConfig = storageConfig,
            InspectConfig = inspectConfig,
            Actions = { actions }
        };

        // Construct the request.
        var request = new CreateDlpJobRequest
        {
            ParentAsLocationName = new LocationName(projectId, "global"),
            InspectJob = inspectJob
        };

        // Call the API.
        DlpJob response = dlp.CreateDlpJob(request);

        return response;
    }
}

Go

Sensitive Data Protection의 클라이언트 라이브러리를 설치하고 사용하는 방법은 Sensitive Data Protection 클라이언트 라이브러리를 참조하세요.

Sensitive Data Protection에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

import (
	"context"
	"fmt"
	"io"

	dlp "cloud.google.com/go/dlp/apiv2"
	"cloud.google.com/go/dlp/apiv2/dlppb"
)

// inspectDataStoreSendToScc inspects sensitive data in a Datastore
// and sends the results to Google Cloud Security Command Center (SCC).
func inspectDataStoreSendToScc(w io.Writer, projectID, datastoreNamespace, datastoreKind string) error {
	// projectID := "my-project-id"
	// datastoreNamespace := "your-datastore-namespace"
	// datastoreKind := "your-datastore-kind"

	ctx := context.Background()

	// Initialize a client once and reuse it to send multiple requests. Clients
	// are safe to use across goroutines. When the client is no longer needed,
	// call the Close method to cleanup its resources.
	client, err := dlp.NewClient(ctx)
	if err != nil {
		return err
	}

	// Closing the client safely cleans up background resources.
	defer client.Close()

	// Specify the Datastore entity to be inspected.
	partitionId := &dlppb.PartitionId{
		ProjectId:   projectID,
		NamespaceId: datastoreNamespace,
	}

	// kindExpr represents an expression specifying a kind or range of kinds for data inspection in DLP.
	kindExpression := &dlppb.KindExpression{
		Name: datastoreKind,
	}

	// Specify datastoreOptions so that It holds the configuration options for inspecting data in
	// Google Cloud Datastore.
	datastoreOptions := &dlppb.DatastoreOptions{
		PartitionId: partitionId,
		Kind:        kindExpression,
	}

	// Specify the storageConfig to represents the configuration settings for inspecting data
	// in different storage types, such as BigQuery and Cloud Storage.
	storageConfig := &dlppb.StorageConfig{
		Type: &dlppb.StorageConfig_DatastoreOptions{
			DatastoreOptions: datastoreOptions,
		},
	}

	// Specify the type of info the inspection will look for.
	// See https://cloud.google.com/dlp/docs/infotypes-reference for complete list of info types
	infoTypes := []*dlppb.InfoType{
		{Name: "EMAIL_ADDRESS"},
		{Name: "PERSON_NAME"},
		{Name: "LOCATION"},
		{Name: "PHONE_NUMBER"},
	}

	// The minimum likelihood required before returning a match.
	minLikelihood := dlppb.Likelihood_UNLIKELY

	// The maximum number of findings to report (0 = server maximum).
	findingLimits := &dlppb.InspectConfig_FindingLimits{
		MaxFindingsPerItem: 100,
	}

	inspectConfig := &dlppb.InspectConfig{
		InfoTypes:     infoTypes,
		MinLikelihood: minLikelihood,
		Limits:        findingLimits,
		IncludeQuote:  true,
	}

	// Specify the action that is triggered when the job completes.
	action := &dlppb.Action{
		Action: &dlppb.Action_PublishSummaryToCscc_{
			PublishSummaryToCscc: &dlppb.Action_PublishSummaryToCscc{},
		},
	}

	// Configure the inspection job we want the service to perform.
	inspectJobConfig := &dlppb.InspectJobConfig{
		StorageConfig: storageConfig,
		InspectConfig: inspectConfig,
		Actions: []*dlppb.Action{
			action,
		},
	}

	// Create the request for the job configured above.
	req := &dlppb.CreateDlpJobRequest{
		Parent: fmt.Sprintf("projects/%s/locations/global", projectID),
		Job: &dlppb.CreateDlpJobRequest_InspectJob{
			InspectJob: inspectJobConfig,
		},
	}

	// Send the request.
	resp, err := client.CreateDlpJob(ctx, req)
	if err != nil {
		return err
	}

	// Print the result
	fmt.Fprintf(w, "Job created successfully: %v", resp.Name)
	return nil
}

Java

Sensitive Data Protection의 클라이언트 라이브러리를 설치하고 사용하는 방법은 Sensitive Data Protection 클라이언트 라이브러리를 참조하세요.

Sensitive Data Protection에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.


import com.google.cloud.dlp.v2.DlpServiceClient;
import com.google.privacy.dlp.v2.Action;
import com.google.privacy.dlp.v2.CreateDlpJobRequest;
import com.google.privacy.dlp.v2.DatastoreOptions;
import com.google.privacy.dlp.v2.DlpJob;
import com.google.privacy.dlp.v2.InfoType;
import com.google.privacy.dlp.v2.InfoTypeStats;
import com.google.privacy.dlp.v2.InspectConfig;
import com.google.privacy.dlp.v2.InspectDataSourceDetails;
import com.google.privacy.dlp.v2.InspectJobConfig;
import com.google.privacy.dlp.v2.KindExpression;
import com.google.privacy.dlp.v2.Likelihood;
import com.google.privacy.dlp.v2.LocationName;
import com.google.privacy.dlp.v2.PartitionId;
import com.google.privacy.dlp.v2.StorageConfig;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class InspectDatastoreSendToScc {

  private static final int TIMEOUT_MINUTES = 15;

  public static void main(String[] args) throws Exception {
    // TODO(developer): Replace these variables before running the sample.
    // The Google Cloud project id to use as a parent resource.
    String projectId = "your-project-id";
    // The namespace specifier to be used for the partition entity.
    String datastoreNamespace = "your-datastore-namespace";
    // The datastore kind defining a data set.
    String datastoreKind = "your-datastore-kind";
    inspectDatastoreSendToScc(projectId, datastoreNamespace, datastoreKind);
  }

  // Creates a DLP Job to scan the sample data stored in a DataStore table and save its scan results
  // to Security Command Center.
  public static void inspectDatastoreSendToScc(
      String projectId, String datastoreNamespace, String datastoreKind)
      throws IOException, InterruptedException {
    // 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 (DlpServiceClient dlpServiceClient = DlpServiceClient.create()) {

      // Specify the Datastore entity to be inspected.
      PartitionId partitionId =
          PartitionId.newBuilder()
              .setProjectId(projectId)
              .setNamespaceId(datastoreNamespace)
              .build();

      KindExpression kindExpression = KindExpression.newBuilder().setName(datastoreKind).build();

      DatastoreOptions datastoreOptions =
          DatastoreOptions.newBuilder().setKind(kindExpression).setPartitionId(partitionId).build();

      StorageConfig storageConfig =
          StorageConfig.newBuilder().setDatastoreOptions(datastoreOptions).build();

      // Specify the type of info the inspection will look for.
      List<InfoType> infoTypes =
          Stream.of("EMAIL_ADDRESS", "PERSON_NAME", "LOCATION", "PHONE_NUMBER")
              .map(it -> InfoType.newBuilder().setName(it).build())
              .collect(Collectors.toList());

      // The minimum likelihood required before returning a match.
      Likelihood minLikelihood = Likelihood.UNLIKELY;

      // The maximum number of findings to report (0 = server maximum)
      InspectConfig.FindingLimits findingLimits =
          InspectConfig.FindingLimits.newBuilder().setMaxFindingsPerItem(100).build();

      // Specify how the content should be inspected.
      InspectConfig inspectConfig =
          InspectConfig.newBuilder()
              .addAllInfoTypes(infoTypes)
              .setIncludeQuote(true)
              .setMinLikelihood(minLikelihood)
              .setLimits(findingLimits)
              .build();

      // Specify the action that is triggered when the job completes.
      Action.PublishSummaryToCscc publishSummaryToCscc =
          Action.PublishSummaryToCscc.getDefaultInstance();
      Action action = Action.newBuilder().setPublishSummaryToCscc(publishSummaryToCscc).build();

      // Configure the inspection job we want the service to perform.
      InspectJobConfig inspectJobConfig =
          InspectJobConfig.newBuilder()
              .setInspectConfig(inspectConfig)
              .setStorageConfig(storageConfig)
              .addActions(action)
              .build();

      // Construct the job creation request to be sent by the client.
      CreateDlpJobRequest createDlpJobRequest =
          CreateDlpJobRequest.newBuilder()
              .setParent(LocationName.of(projectId, "global").toString())
              .setInspectJob(inspectJobConfig)
              .build();

      // Send the job creation request and process the response.
      DlpJob response = dlpServiceClient.createDlpJob(createDlpJobRequest);
      // Get the current time.
      long startTime = System.currentTimeMillis();

      // Check if the job state is DONE.
      while (response.getState() != DlpJob.JobState.DONE) {
        // Sleep for 30 second.
        Thread.sleep(30000);

        // Get the updated job status.
        response = dlpServiceClient.getDlpJob(response.getName());

        // Check if the timeout duration has exceeded.
        long elapsedTime = System.currentTimeMillis() - startTime;
        if (TimeUnit.MILLISECONDS.toMinutes(elapsedTime) >= TIMEOUT_MINUTES) {
          System.out.printf("Job did not complete within %d minutes.%n", TIMEOUT_MINUTES);
          break;
        }
      }
      // Print the results.
      System.out.println("Job status: " + response.getState());
      System.out.println("Job name: " + response.getName());
      InspectDataSourceDetails.Result result = response.getInspectDetails().getResult();
      System.out.println("Findings: ");
      for (InfoTypeStats infoTypeStat : result.getInfoTypeStatsList()) {
        System.out.print("\tInfo type: " + infoTypeStat.getInfoType().getName());
        System.out.println("\tCount: " + infoTypeStat.getCount());
      }
    }
  }
}

Node.js

Sensitive Data Protection의 클라이언트 라이브러리를 설치하고 사용하는 방법은 Sensitive Data Protection 클라이언트 라이브러리를 참조하세요.

Sensitive Data Protection에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

// Imports the Google Cloud Data Loss Prevention library
const DLP = require('@google-cloud/dlp');

// Instantiates a client
const dlp = new DLP.DlpServiceClient();

// The project ID to run the API call under.
// const projectId = "your-project-id";

// Datastore namespace
// const datastoreNamespace = 'datastore-namespace';

// Datastore kind
// const datastoreKind = 'datastore-kind';

async function inspectDatastoreSendToScc() {
  // Specify the storage configuration object with datastore.
  const storageConfig = {
    datastoreOptions: {
      kind: {
        name: datastoreKind,
      },
      partitionId: {
        projectId: projectId,
        namespaceId: datastoreNamespace,
      },
    },
  };

  // Construct the info types to look for in the datastore.
  const infoTypes = [
    {name: 'EMAIL_ADDRESS'},
    {name: 'PERSON_NAME'},
    {name: 'LOCATION'},
    {name: 'PHONE_NUMBER'},
  ];

  // Construct the inspection configuration.
  const inspectConfig = {
    infoTypes: infoTypes,
    minLikelihood: DLP.protos.google.privacy.dlp.v2.Likelihood.UNLIKELY,
    limits: {
      maxFindingsPerItem: 100,
    },
    includeQuote: true,
  };

  // Specify the action that is triggered when the job completes
  const action = {
    publishSummaryToCscc: {enable: true},
  };

  // Configure the inspection job we want the service to perform.
  const inspectJobConfig = {
    inspectConfig: inspectConfig,
    storageConfig: storageConfig,
    actions: [action],
  };

  // Construct the job creation request to be sent by the client.
  const request = {
    parent: `projects/${projectId}/locations/global`,
    inspectJob: inspectJobConfig,
  };

  // Send the job creation request and process the response.
  const [jobsResponse] = await dlp.createDlpJob(request);
  const jobName = jobsResponse.name;

  // Waiting for a maximum of 15 minutes for the job to get complete.
  let job;
  let numOfAttempts = 30;
  while (numOfAttempts > 0) {
    // Fetch DLP Job status
    [job] = await dlp.getDlpJob({name: jobName});

    // Check if the job has completed.
    if (job.state === 'DONE') {
      break;
    }
    if (job.state === 'FAILED') {
      console.log('Job Failed, Please check the configuration.');
      return;
    }
    // Sleep for a short duration before checking the job status again.
    await new Promise(resolve => {
      setTimeout(() => resolve(), 30000);
    });
    numOfAttempts -= 1;
  }

  // Print out the results.
  const infoTypeStats = job.inspectDetails.result.infoTypeStats;
  if (infoTypeStats.length > 0) {
    infoTypeStats.forEach(infoTypeStat => {
      console.log(
        `Found ${infoTypeStat.count} instance(s) of infoType ${infoTypeStat.infoType.name}.`
      );
    });
  } else {
    console.log('No findings.');
  }
}
await inspectDatastoreSendToScc();

PHP

Sensitive Data Protection의 클라이언트 라이브러리를 설치하고 사용하는 방법은 Sensitive Data Protection 클라이언트 라이브러리를 참조하세요.

Sensitive Data Protection에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

use Google\Cloud\Dlp\V2\DlpServiceClient;
use Google\Cloud\Dlp\V2\InfoType;
use Google\Cloud\Dlp\V2\InspectConfig;
use Google\Cloud\Dlp\V2\InspectConfig\FindingLimits;
use Google\Cloud\Dlp\V2\StorageConfig;
use Google\Cloud\Dlp\V2\Likelihood;
use Google\Cloud\Dlp\V2\Action;
use Google\Cloud\Dlp\V2\Action\PublishSummaryToCscc;
use Google\Cloud\Dlp\V2\DatastoreOptions;
use Google\Cloud\Dlp\V2\InspectJobConfig;
use Google\Cloud\Dlp\V2\KindExpression;
use Google\Cloud\Dlp\V2\PartitionId;
use Google\Cloud\Dlp\V2\DlpJob\JobState;

/**
 * (DATASTORE) Send Cloud DLP scan results to Security Command Center.
 * Using Cloud Data Loss Prevention to scan specific Google Cloud resources and send data to Security Command Center.
 *
 * @param string $callingProjectId  The project ID to run the API call under.
 * @param string $kindName          Datastore kind name to be inspected.
 * @param string $namespaceId       Namespace Id to be inspected.
 */
function inspect_datastore_send_to_scc(
    string $callingProjectId,
    string $kindName,
    string $namespaceId
): void {
    // Instantiate a client.
    $dlp = new DlpServiceClient();

    // Construct the items to be inspected.
    $datastoreOptions = (new DatastoreOptions())
        ->setKind((new KindExpression())
            ->setName($kindName))
        ->setPartitionId((new PartitionId())
            ->setNamespaceId($namespaceId)
            ->setProjectId($callingProjectId));

    $storageConfig = (new StorageConfig())
        ->setDatastoreOptions(($datastoreOptions));

    // Specify the type of info the inspection will look for.
    $infoTypes = [
        (new InfoType())->setName('EMAIL_ADDRESS'),
        (new InfoType())->setName('PERSON_NAME'),
        (new InfoType())->setName('LOCATION'),
        (new InfoType())->setName('PHONE_NUMBER')
    ];

    // Specify how the content should be inspected.
    $inspectConfig = (new InspectConfig())
        ->setMinLikelihood(likelihood::UNLIKELY)
        ->setLimits((new FindingLimits())
            ->setMaxFindingsPerRequest(100))
        ->setInfoTypes($infoTypes)
        ->setIncludeQuote(true);

    // Specify the action that is triggered when the job completes.
    $action = (new Action())
        ->setPublishSummaryToCscc(new PublishSummaryToCscc());

    // Construct inspect job config to run.
    $inspectJobConfig = (new InspectJobConfig())
        ->setInspectConfig($inspectConfig)
        ->setStorageConfig($storageConfig)
        ->setActions([$action]);

    // Send the job creation request and process the response.
    $parent = "projects/$callingProjectId/locations/global";
    $job = $dlp->createDlpJob($parent, [
        'inspectJob' => $inspectJobConfig
    ]);

    $numOfAttempts = 10;
    do {
        printf('Waiting for job to complete' . PHP_EOL);
        sleep(10);
        $job = $dlp->getDlpJob($job->getName());
        if ($job->getState() == JobState::DONE) {
            break;
        }
        $numOfAttempts--;
    } while ($numOfAttempts > 0);

    // Print finding counts.
    printf('Job %s status: %s' . PHP_EOL, $job->getName(), JobState::name($job->getState()));
    switch ($job->getState()) {
        case JobState::DONE:
            $infoTypeStats = $job->getInspectDetails()->getResult()->getInfoTypeStats();
            if (count($infoTypeStats) === 0) {
                printf('No findings.' . PHP_EOL);
            } else {
                foreach ($infoTypeStats as $infoTypeStat) {
                    printf(
                        '  Found %s instance(s) of infoType %s' . PHP_EOL,
                        $infoTypeStat->getCount(),
                        $infoTypeStat->getInfoType()->getName()
                    );
                }
            }
            break;
        case JobState::FAILED:
            printf('Job %s had errors:' . PHP_EOL, $job->getName());
            $errors = $job->getErrors();
            foreach ($errors as $error) {
                var_dump($error->getDetails());
            }
            break;
        case JobState::PENDING:
            printf('Job has not completed. Consider a longer timeout or an asynchronous execution model' . PHP_EOL);
            break;
        default:
            printf('Unexpected job state. Most likely, the job is either running or has not yet started.');
    }
}

Python

Sensitive Data Protection의 클라이언트 라이브러리를 설치하고 사용하는 방법은 Sensitive Data Protection 클라이언트 라이브러리를 참조하세요.

Sensitive Data Protection에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

import time
from typing import List

import google.cloud.dlp

def inspect_datastore_send_to_scc(
    project: str,
    datastore_project: str,
    kind: str,
    info_types: List[str],
    namespace_id: str = None,
    max_findings: int = 100,
) -> None:
    """
    Uses the Data Loss Prevention API to inspect Datastore data and
    send the results to Google Security Command Center.
    Args:
        project: The Google Cloud project id to use as a parent resource.
        datastore_project: The Google Cloud project id of the target Datastore.
        kind: The kind of the Datastore entity to inspect, e.g. 'Person'.
        info_types: A list of strings representing infoTypes to inspect for.
            A full list of infoType categories can be fetched from the API.
        namespace_id: The namespace of the Datastore document, if applicable.
        max_findings: The maximum number of findings to report; 0 = no maximum

    """
    # Instantiate a client.
    dlp = google.cloud.dlp_v2.DlpServiceClient()

    # Prepare info_types by converting the list of strings into a list of
    # dictionaries.
    info_types = [{"name": info_type} for info_type in info_types]

    # Construct the configuration dictionary.
    inspect_config = {
        "info_types": info_types,
        "min_likelihood": google.cloud.dlp_v2.Likelihood.UNLIKELY,
        "limits": {"max_findings_per_request": max_findings},
        "include_quote": True,
    }

    # Construct a cloud_storage_options dictionary with datastore options.
    storage_config = {
        "datastore_options": {
            "partition_id": {
                "project_id": datastore_project,
                "namespace_id": namespace_id,
            },
            "kind": {"name": kind},
        }
    }

    # Tell the API where to send a notification when the job is complete.
    actions = [{"publish_summary_to_cscc": {}}]

    # Construct the job definition.
    job = {
        "inspect_config": inspect_config,
        "storage_config": storage_config,
        "actions": actions,
    }

    # Convert the project id into a full resource id.
    parent = f"projects/{project}"

    # Call the API
    response = dlp.create_dlp_job(
        request={
            "parent": parent,
            "inspect_job": job,
        }
    )
    print(f"Inspection Job started : {response.name}")

    job_name = response.name

    # Waiting for a maximum of 15 minutes for the job to get complete.
    no_of_attempts = 30
    while no_of_attempts > 0:
        # Get the DLP job status.
        job = dlp.get_dlp_job(request={"name": job_name})
        # Check if the job has completed.
        if job.state == google.cloud.dlp_v2.DlpJob.JobState.DONE:
            break
        if job.state == google.cloud.dlp_v2.DlpJob.JobState.FAILED:
            print("Job Failed, Please check the configuration.")
            return

        # Sleep for a short duration before checking the job status again.
        time.sleep(30)
        no_of_attempts -= 1

    # Print out the results.
    print(f"Job name: {job.name}")
    result = job.inspect_details.result
    if result.info_type_stats:
        for stats in result.info_type_stats:
            print(f"Info type: {stats.info_type.name}")
            print(f"Count: {stats.count}")
    else:
        print("No findings.")

Security Command Center에서 Sensitive Data Protection 스캔 결과 보기

Sensitive Data Protection에 검사 작업 결과를 Security Command Center로 보내도록 지시했으므로 이제 Security Command Center에서 검사 작업 결과를 볼 수 있습니다.

  1. Google Cloud 콘솔에서 Security Command Center 발견 항목 페이지로 이동합니다.

    발견 항목으로 이동

  2. Security Command Center를 사용하도록 설정한 조직을 선택합니다.
  3. 쿼리 편집기 필드에 다음을 입력하여 Sensitive Data Protection 발견 항목을 쿼리합니다.

    state="ACTIVE"
    AND NOT mute="MUTED"
    AND (parent_display_name="Sensitive Data Protection" OR parent_display_name="Cloud Data Loss Prevention")
    

    쿼리 편집기에 대한 자세한 내용은 Google Cloud 콘솔에서 발견 항목 쿼리 수정을 참조하세요.

    Sensitive Data Protection에서 발견 항목이 전송되면 발견 항목 목록에 발견 항목이 표시됩니다. 이 목록에는 Sensitive Data Protection의 모든 발견 항목이 포함되며, 검사 작업 및 검색(데이터 프로파일링) 작업의 발견 항목이 포함될 수 있습니다.

이 가이드에서 제공하는 안내는 Sensitive Data Protection의 기본 제공 감지기 중 일부만 설정합니다.

삭제

이 주제에서 사용한 리소스 비용이 Google Cloud 계정에 청구되지 않도록 하려면 다음 안내를 따르세요.

프로젝트 삭제

비용이 청구되지 않도록 하는 가장 쉬운 방법은 이 주제에 제시된 안내를 따르면서 생성된 프로젝트를 삭제하는 것입니다.

  1. Google Cloud 콘솔에서 리소스 관리 페이지로 이동합니다.

    리소스 관리로 이동

  2. 프로젝트 목록에서 삭제할 프로젝트를 선택하고 삭제를 클릭합니다.
  3. 대화상자에서 프로젝트 ID를 입력한 후 종료를 클릭하여 프로젝트를 삭제합니다.

이 방법을 사용하여 프로젝트를 삭제하면 생성한 Sensitive Data Protection 작업 및 Cloud Storage 버킷도 삭제됩니다. 다음 섹션의 지침을 따를 필요는 없습니다.

Sensitive Data Protection 작업 삭제

자체 데이터를 스캔한 경우 생성한 검사 작업만 삭제해야 합니다.

  1. 다음 버튼을 클릭하여 dlpJobs.delete 메서드 참조 페이지의 API 탐색기로 이동합니다.

    API 탐색기 열기

  2. 이름 입력란에 다음 형식의 검색 요청에 대한 JSON 응답의 작업 이름을 입력합니다.
    projects/PROJECT_ID/dlpJobs/JOB_ID
    작업 ID는 i-1234567890123456789 형식입니다.

검사 작업을 추가로 만들었거나 작업을 삭제했는지 확인하려면 기존 작업을 모두 나열합니다.

  1. 다음 버튼을 클릭하여 dlpJobs.list 메서드 참조 페이지의 API 탐색기로 이동합니다.

    API 탐색기 열기

  2. parent 입력란에 프로젝트 식별자를 다음 형식으로 입력합니다.
    projects/PROJECT_ID
  3. 실행을 클릭합니다.

응답에 나열된 작업이 없으면 모든 작업이 삭제된 것입니다. 응답에 작업이 나열된 경우 해당 작업에 대해 삭제 절차를 반복합니다.

Cloud Storage 버킷 삭제

샘플 데이터를 보관할 새 Cloud Storage 버킷을 만든 경우 버킷을 삭제합니다.

  1. Cloud Storage 브라우저를 엽니다.

    Cloud Storage 열기

  2. Cloud Storage 브라우저에서 앞서 만든 버킷의 이름 옆에 있는 체크박스를 선택한 후 삭제를 클릭합니다.

다음 단계