Ergebnisse von Inspektionsjobs zum Schutz sensibler Daten an Security Command Center senden

In dieser Anleitung erfahren Sie, wie Sie Daten in Cloud Storage, Firestore im Datastore-Modus (Datastore) oder BigQuery untersuchen und die Inspektionsergebnisse an Security Command Center senden.

Für BigQuery-Daten können Sie zusätzlich eine Profilerstellung durchführen, was sich von einem Inspektionsvorgang unterscheidet. Sie können auch Datenprofile an Security Command Center senden. Weitere Informationen finden Sie unter Datenprofile in Security Command Center veröffentlichen.

Überblick

Security Command Center ermöglicht Ihnen, Daten zu Sicherheitsbedrohungen zu erfassen, Sicherheitsbedrohungen zu identifizieren und entsprechende Maßnahmen zu ergreifen, bevor sie dem Unternehmen schaden oder zu Verlusten führen. Außerdem können Sie mit Security Command Center mehrere sicherheitsrelevante Aktionen über ein einziges, zentrales Dashboard ausführen.

Der Schutz sensibler Daten ist in Security Command Center eingebunden. Wenn Sie Ihre Google Cloud Storage-Repositories mithilfe einer Aktion zum Schutz sensibler Daten auf sensible Daten prüfen, können Ergebnisse direkt an das Security Command Center-Dashboard gesendet werden. Sie werden neben anderen Sicherheitsmesswerten angezeigt.

In dieser Anleitung führen Sie folgende Schritte aus:

  • Aktivieren Sie Security Command Center und Schutz sensibler Daten.
  • Richten Sie den Schutz sensibler Daten ein, um ein Google Cloud Storage-Repository zu überprüfen – entweder einen Cloud Storage-Bucket, eine BigQuery-Tabelle oder eine Datastore-Art.
  • Konfigurieren Sie einen Scan zum Schutz sensibler Daten, um die Ergebnisse der Inspektionsjobs an Security Command Center zu senden.

Weitere Informationen zu Security Command Center finden Sie in der zugehörigen Dokumentation.

Wenn Sie die Ergebnisse von Discovery-Scans und nicht von Inspektionsjobs an Security Command Center senden möchten, lesen Sie stattdessen die Dokumentation zur Profilerstellung für eine Organisation, einen Ordner oder ein Projekt.

Kosten

In diesem Dokument verwenden Sie die folgenden kostenpflichtigen Komponenten von Google Cloud:

  • Schutz sensibler Daten
  • Cloud Storage
  • BigQuery
  • Datastore

Mit dem Preisrechner können Sie eine Kostenschätzung für Ihre voraussichtliche Nutzung vornehmen. Neuen Google Cloud-Nutzern steht möglicherweise eine kostenlose Testversion zur Verfügung.

Hinweise

Bevor Sie Ergebnisse von Scans zum Schutz sensibler Daten an Security Command Center senden können, müssen Sie Folgendes tun:

  • Schritt 1: Google Cloud Storage-Repositories festlegen
  • Schritt 2: IAM-Rollen (Identity and Access Management) festlegen.
  • Schritt 3: Security Command Center aktivieren
  • Schritt 4: Schutz sensibler Daten aktivieren
  • Schritt 5: Schutz sensibler Daten als Sicherheitsquelle für Security Command Center aktivieren

Die Schritte zum Einrichten dieser Komponenten werden in folgenden Abschnitten beschrieben.

Schritt 1: Google Cloud Storage-Repositories festlegen

Legen Sie fest, ob Sie Ihr eigenes Google Cloud Storage-Repository oder ein Beispiel-Repository scannen möchten. Dieses Thema enthält Anweisungen für beide Szenarien.

Eigene Daten scannen

Wenn Sie Ihren eigenen vorhandenen Cloud Storage-Bucket, Ihre BigQuery-Tabelle oder Ihre Datastore-Art scannen möchten, öffnen Sie zuerst das Projekt, in dem sich das Repository befindet. In den folgenden Schritten aktivieren Sie sowohl Security Command Center als auch den Schutz sensibler Daten für dieses Projekt und seine Organisation.

Nachdem Sie das gewünschte Projekt geöffnet haben, fahren Sie mit Schritt 2 fort, um IAM-Rollen einzurichten.

Beispieldaten scannen

Wenn Sie ein Test-Dataset scannen möchten, müssen Sie zuerst ein Rechnungskonto einrichten und dann ein neues Projekt erstellen. Für diesen Schritt benötigen Sie die IAM-Rolle Projektersteller. Weitere Informationen zu IAM-Rollen

  1. Falls noch keine Abrechnung konfiguriert ist, richten Sie ein Rechnungskonto ein.

    Weitere Informationen zum Aktivieren der Abrechnung

  2. Rufen Sie in der Google Cloud Console die Seite Neues Projekt auf.

    Zur Seite "Neues Projekt"

  3. Wählen Sie in der Drop-down-Liste Rechnungskonto das Rechnungskonto aus, dem das Projekt in Rechnung gestellt werden soll.
  4. Wählen Sie in der Drop-down-Liste Organisation die Organisation aus, in der Sie das Projekt erstellen möchten.
  5. Wählen Sie in der Drop-down-Liste Speicherort die Organisation oder den Ordner aus, in der bzw. dem Sie das Projekt erstellen möchten.

Laden Sie anschließend die Beispieldaten herunter und speichern Sie diese:

  1. Öffnen Sie das Repository für Anleitungen zu Cloud Functions auf GitHub.
  2. Klicken Sie auf Clone or download und dann auf Download ZIP.
  3. Extrahieren Sie die heruntergeladene ZIP-Datei.
  4. Rufen Sie in der Google Cloud Console die Seite Storage-Browser auf.

    Cloud Storage aufrufen

  5. Klicken Sie auf Bucket erstellen.
  6. Geben Sie dem Bucket auf der Seite Bucket erstellen einen eindeutigen Namen und klicken Sie dann auf Erstellen.
  7. Klicken Sie auf der Seite Bucket-Details auf Ordner hochladen.
  8. Wechseln Sie zum extrahierten Ordner dlp-cloud-functions-tutorials-master, öffnen Sie ihn und wählen Sie den Ordner sample_data aus. Klicken Sie auf Hochladen, um den Inhalt des Ordners in Cloud Storage hochzuladen.

Notieren Sie sich den Namen, den Sie dem Cloud Storage-Bucket gegeben haben. Sie benötigen den Namen später. Wenn die Datei hochgeladen wurde, können Sie fortfahren.

Schritt 2: IAM-Rollen festlegen

Wenn Sie den Schutz sensibler Daten verwenden möchten, um Scanergebnisse an Security Command Center zu senden, benötigen Sie die IAM-Rollen Security Center-Administrator und Bearbeiter von Jobs zum Schutz sensibler Daten. In diesem Abschnitt wird beschrieben, wie Sie die Rollen hinzufügen. Für diesen Abschnitt benötigen Sie die IAM-Rolle Administrator der Organisation.

  1. Rufen Sie die IAM-Seite auf.

    IAM aufrufen

  2. Suchen Sie auf dem Tab Nach Hauptkonten ansehen Ihr Google-Konto und klicken Sie auf Hauptkonto bearbeiten.
  3. Fügen Sie die Rollen Sicherheitscenter-Administrator und Bearbeiter von Jobs für den Schutz sensibler Daten hinzu:

    1. Klicken Sie im Bereich Zugriff bearbeiten auf Weitere Rolle hinzufügen.
    2. Suchen Sie in der Liste Rolle auswählen nach Sicherheitscenter-Administrator und wählen Sie diese aus.
    3. Klicken Sie auf Weitere Rolle hinzufügen.
    4. Suchen Sie in der Liste Rolle auswählen nach DLP-Jobs-Bearbeiter und wählen Sie die Rolle aus.
    5. Klicken Sie auf Speichern.

Ihnen haben jetzt die Rollen „Bearbeiter von Jobs für den Schutz sensibler Daten“ und „Sicherheitscenter-Administrator“ für Ihre Organisation. Mit diesen Rollen können Sie die verbleibenden Aufgaben in diesem Thema ausführen.

Schritt 3: Security Command Center aktivieren

  1. Rufen Sie in der Google Cloud Console die Seite Security Command Center auf.

    Zum Security Command Center

  2. Wählen Sie in der Drop-down-Liste Organisation die Organisation aus, für die Sie den Schutz sensibler Daten aktivieren möchten, und klicken Sie dann auf Auswählen.

  3. Wählen Sie auf der Seite Asset-Erkennung aktivieren die Option Alle aktuellen und zukünftigen Projekte aus und klicken Sie dann auf Aktivieren. Es sollte eine Meldung angezeigt werden, dass der Schutz sensibler Daten mit der Asset-Erkennung beginnt.

Nach Abschluss der Asset-Erkennung werden Ihre unterstützten Google Cloud-Assets durch den Schutz sensibler Daten angezeigt. Die Asset-Erkennung kann einige Minuten dauern. Möglicherweise müssen Sie die Seite aktualisieren, damit die Assets angezeigt werden.

Weitere Informationen zum Aktivieren von Security Command Center finden Sie in der Dokumentation zu Security Command Center.

Schritt 4: Schutz sensibler Daten aktivieren

Aktivieren Sie den Schutz sensibler Daten für das Projekt, das Sie scannen möchten. Das Projekt muss sich in der Organisation befinden, für die Sie Security Command Center aktiviert haben. So aktivieren Sie den Schutz sensibler Daten über die Google Cloud Console:

  1. Rufen Sie in der Google Cloud Console die Seite Zugriff auf API aktivieren auf.

    API aktivieren

  2. Wählen Sie in der Symbolleiste das Projekt aus Schritt 1 dieser Anleitung aus. Das Projekt muss den Cloud Storage-Bucket, die BigQuery-Tabelle oder die Datastore-Art enthalten, den bzw. die Sie scannen möchten.
  3. Klicken Sie auf Next (Weiter).
  4. Klicken Sie auf Aktivieren.

Der Schutz sensibler Daten ist jetzt für Ihr Projekt aktiviert.

Schritt 5: Schutz sensibler Daten als integrierten Dienst für Security Command Center aktivieren

Aktivieren Sie den Schutz sensibler Daten als integrierten Dienst, um die Scanergebnisse für den Schutz sensibler Daten in Security Command Center anzusehen. Weitere Informationen finden Sie in der Dokumentation zu Security Command Center unter Integrierten Google Cloud-Dienst hinzufügen.

Die Ergebnisse für den Schutz sensibler Daten werden in Security Command Center auf der Seite Ergebnisse angezeigt.

Inspektionsscan für den Schutz sensibler Daten konfigurieren und ausführen

In diesem Abschnitt konfigurieren Sie einen Inspektionsjob für den Schutz sensibler Daten und führen ihn aus.

Der hier konfigurierte Inspektionsjob weist den Schutz sensibler Daten an, entweder die in Cloud Storage gespeicherten Beispieldaten oder Ihre eigenen in Cloud Storage, Datastore oder BigQuery gespeicherten Daten zu scannen. In der von Ihnen angegebenen Jobkonfiguration weisen Sie den Schutz sensibler Daten an, die Scanergebnisse in Security Command Center zu speichern.

Schritt 1: Projektkennung notieren

  1. Öffnen Sie die Google Cloud Console.

    Weiter zur Google Cloud Console

  2. Klicken Sie auf Auswählen.
  3. Wählen Sie in der Drop-down-Liste Auswählen aus die Organisation aus, für die Sie Security Command Center aktiviert haben.
  4. Kopieren Sie unter ID die Projekt-ID des Projekts, das die zu scannenden Daten enthält.
  5. Klicken Sie unter Name auf das Projekt, um es auszuwählen.

Schritt 2: APIs Explorer öffnen und den Job konfigurieren

  1. Klicken Sie auf die folgende Schaltfläche, um APIs Explorer auf der Referenzseite für die Methode dlpJobs.create aufzurufen:

    APIs Explorer öffnen

  2. Geben Sie im Feld parent Folgendes ein, wobei PROJECT_ID die Projekt-ID ist, die Sie in Schritt 1 notiert haben:
    projects/PROJECT_ID

Ersetzen Sie den Inhalt des Felds Request body durch den folgenden JSON-Code für die Art von Daten, die Sie verwenden möchten: Beispieldaten in einem Cloud Storage-Bucket oder Ihre eigenen Daten, die in Cloud Storage, Datastore oder BigQuery gespeichert sind.

Beispieldaten

Wenn Sie einen Cloud Storage-Bucket zum Speichern von Beispieldaten erstellt haben, kopieren Sie den folgenden JSON-Code und fügen ihn in das Feld Anfragetext ein. Ersetzen Sie BUCKET_NAME durch den Namen, den Sie dem Cloud Storage-Bucket gegeben haben:

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

Wenn Sie Ihren eigenen Cloud Storage-Bucket scannen möchten, kopieren Sie den folgenden JSON-Code und fügen ihn in das Feld Request body.

Ersetzen Sie PATH_NAME durch den Pfad zum Speicherort, den Sie scannen möchten. Wenn Sie rekursiv scannen möchten, fügen Sie am Ende des Pfads zwei Sternchen an, z. B. gs://path_to_files/**. Wenn nur das angegebene Verzeichnis und nicht tiefer gescannt werden soll, fügen Sie am Ende des Pfads ein Sternchen an, z. B. 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":{

        }
      }
    ]
  }
}

Weitere Informationen zu den verfügbaren Scanoptionen finden Sie unter Speicher und Datenbanken auf sensible Daten prüfen.

Datastore-Daten

Wenn Sie Ihre eigenen Daten in Datastore scannen möchten, kopieren Sie den folgenden JSON-Code und fügen ihn in das Feld Request body ein.

Ersetzen Sie DATASTORE_KIND durch den Namen der Datastore-Art. Sie können NAMESPACE_ID und PROJECT_ID auch durch die Namespace- bzw. Projektkennungen ersetzen oder "partitionID" bei Bedarf vollständig entfernen.

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

        }
      }
    ]
  }
}

Weitere Informationen zu den verfügbaren Scanoptionen finden Sie unter Speicher und Datenbanken auf sensible Daten prüfen.

BigQuery-Daten

Wenn Sie Ihre eigene BigQuery-Tabelle scannen möchten, kopieren Sie den folgenden JSON-Code und fügen ihn in das Feld Request body ein.

Ersetzen Sie PROJECT_ID, BIGQUERY_DATASET_NAME und BIGQUERY_TABLE_NAME jeweils durch die Projekt-ID, den Namen des BigQuery-Datasets und den Namen der BigQuery-Tabelle.

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

Weitere Informationen zu den verfügbaren Scanoptionen finden Sie unter Speicher und Datenbanken auf sensible Daten prüfen.

Schritt 3: Anfrage ausführen, um den Inspektionsjob zu starten

Nachdem Sie den Job mithilfe der vorherigen Schritte konfiguriert haben, klicken Sie auf Execute, um die Anfrage zu senden. Wenn die Anfrage erfolgreich ist, wird unter der Anfrage eine Antwort mit einem Erfolgscode und einem JSON-Objekt angezeigt, das den Status des von Ihnen erstellten Jobs zum Schutz sensibler Daten angibt.

Status des Inspektionsscans für den Schutz sensibler Daten prüfen

Die Antwort auf Ihre Scananfrage enthält die Job-ID Ihres Inspektionsscanjobs als "name"-Schlüssel und den aktuellen Status des Inspektionsjobs als "state"-Schlüssel. Unmittelbar nach dem Senden der Anfrage lautet der Jobstatus "PENDING".

Nachdem Sie die Scananfrage gesendet haben, wird der Inhalt sofort abgesucht.

So prüfen Sie den Status des Inspektionsjobs:

  1. Klicken Sie auf die folgende Schaltfläche, um APIs Explorer auf der Referenzseite für die Methode dlpJobs.get aufzurufen:

    APIs Explorer öffnen

  2. Geben Sie im Feld Name den Namen des Jobs aus der JSON-Antwort auf die Scananfrage im folgenden Format ein:
    projects/PROJECT_ID/dlpJobs/JOB_ID
    Die Job-ID hat das Format i-1234567890123456789.
  3. Zum Absenden der Anfrage klicken Sie auf Ausführen.

Wenn der Schlüssel "state" des JSON-Antwortobjekts angibt, dass der Job "DONE" ist, ist der Inspektionsjob abgeschlossen.

Scrollen Sie die Seite nach unten, um den Rest des JSON-Antwortcodes anzusehen. Unter "result" > "infoTypeStats" sollte jeder aufgeführte Informationstyp einen entsprechenden "count" haben. Wenn nicht, prüfen Sie, ob Sie den JSON-Code richtig eingegeben haben und der Pfad oder Speicherort Ihrer Daten korrekt ist.

Nachdem der Inspektionsjob abgeschlossen ist, können Sie mit dem nächsten Abschnitt dieser Anleitung fortfahren, um die Scanergebnisse in Security Command Center anzusehen.

Codebeispiele: Cloud Storage-Bucket prüfen

In diesem Beispiel wird gezeigt, wie Sie mit der DLP API einen Inspektionsjob erstellen, der einen Cloud Storage-Bucket prüft und Ergebnisse an Security Command Center sendet.

C#

Informationen zum Installieren und Verwenden der Clientbibliothek für den Schutz sensibler Daten finden Sie unter Clientbibliotheken für den Schutz sensibler Daten.

Richten Sie Standardanmeldedaten für Anwendungen ein, um sich beim Schutz sensibler Daten zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.


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

Informationen zum Installieren und Verwenden der Clientbibliothek für den Schutz sensibler Daten finden Sie unter Clientbibliotheken für den Schutz sensibler Daten.

Richten Sie Standardanmeldedaten für Anwendungen ein, um sich beim Schutz sensibler Daten zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.

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

Informationen zum Installieren und Verwenden der Clientbibliothek für den Schutz sensibler Daten finden Sie unter Clientbibliotheken für den Schutz sensibler Daten.

Richten Sie Standardanmeldedaten für Anwendungen ein, um sich beim Schutz sensibler Daten zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.


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

Informationen zum Installieren und Verwenden der Clientbibliothek für den Schutz sensibler Daten finden Sie unter Clientbibliotheken für den Schutz sensibler Daten.

Richten Sie Standardanmeldedaten für Anwendungen ein, um sich beim Schutz sensibler Daten zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.

// 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

Informationen zum Installieren und Verwenden der Clientbibliothek für den Schutz sensibler Daten finden Sie unter Clientbibliotheken für den Schutz sensibler Daten.

Richten Sie Standardanmeldedaten für Anwendungen ein, um sich beim Schutz sensibler Daten zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.

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

Informationen zum Installieren und Verwenden der Clientbibliothek für den Schutz sensibler Daten finden Sie unter Clientbibliotheken für den Schutz sensibler Daten.

Richten Sie Standardanmeldedaten für Anwendungen ein, um sich beim Schutz sensibler Daten zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.

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.")

Codebeispiele: BigQuery-Tabelle prüfen

In diesem Beispiel wird gezeigt, wie Sie mit der DLP API einen Inspektionsjob erstellen, der eine BigQuery-Tabelle prüft und Ergebnisse an Security Command Center sendet.

C#

Informationen zum Installieren und Verwenden der Clientbibliothek für den Schutz sensibler Daten finden Sie unter Clientbibliotheken für den Schutz sensibler Daten.

Richten Sie Standardanmeldedaten für Anwendungen ein, um sich beim Schutz sensibler Daten zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.


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

Informationen zum Installieren und Verwenden der Clientbibliothek für den Schutz sensibler Daten finden Sie unter Clientbibliotheken für den Schutz sensibler Daten.

Richten Sie Standardanmeldedaten für Anwendungen ein, um sich beim Schutz sensibler Daten zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.

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

Informationen zum Installieren und Verwenden der Clientbibliothek für den Schutz sensibler Daten finden Sie unter Clientbibliotheken für den Schutz sensibler Daten.

Richten Sie Standardanmeldedaten für Anwendungen ein, um sich beim Schutz sensibler Daten zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.


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

Informationen zum Installieren und Verwenden der Clientbibliothek für den Schutz sensibler Daten finden Sie unter Clientbibliotheken für den Schutz sensibler Daten.

Richten Sie Standardanmeldedaten für Anwendungen ein, um sich beim Schutz sensibler Daten zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.

// 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

Informationen zum Installieren und Verwenden der Clientbibliothek für den Schutz sensibler Daten finden Sie unter Clientbibliotheken für den Schutz sensibler Daten.

Richten Sie Standardanmeldedaten für Anwendungen ein, um sich beim Schutz sensibler Daten zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.

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

Informationen zum Installieren und Verwenden der Clientbibliothek für den Schutz sensibler Daten finden Sie unter Clientbibliotheken für den Schutz sensibler Daten.

Richten Sie Standardanmeldedaten für Anwendungen ein, um sich beim Schutz sensibler Daten zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.

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.")

Codebeispiele: Datenspeicherart prüfen

In diesem Beispiel wird gezeigt, wie Sie mit der DLP API einen Inspektionsjob erstellen, der eine Datastore-Art prüft und Ergebnisse an Security Command Center sendet.

C#

Informationen zum Installieren und Verwenden der Clientbibliothek für den Schutz sensibler Daten finden Sie unter Clientbibliotheken für den Schutz sensibler Daten.

Richten Sie Standardanmeldedaten für Anwendungen ein, um sich beim Schutz sensibler Daten zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.


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

Informationen zum Installieren und Verwenden der Clientbibliothek für den Schutz sensibler Daten finden Sie unter Clientbibliotheken für den Schutz sensibler Daten.

Richten Sie Standardanmeldedaten für Anwendungen ein, um sich beim Schutz sensibler Daten zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.

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

Informationen zum Installieren und Verwenden der Clientbibliothek für den Schutz sensibler Daten finden Sie unter Clientbibliotheken für den Schutz sensibler Daten.

Richten Sie Standardanmeldedaten für Anwendungen ein, um sich beim Schutz sensibler Daten zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.


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

Informationen zum Installieren und Verwenden der Clientbibliothek für den Schutz sensibler Daten finden Sie unter Clientbibliotheken für den Schutz sensibler Daten.

Richten Sie Standardanmeldedaten für Anwendungen ein, um sich beim Schutz sensibler Daten zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.

// 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

Informationen zum Installieren und Verwenden der Clientbibliothek für den Schutz sensibler Daten finden Sie unter Clientbibliotheken für den Schutz sensibler Daten.

Richten Sie Standardanmeldedaten für Anwendungen ein, um sich beim Schutz sensibler Daten zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.

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

Informationen zum Installieren und Verwenden der Clientbibliothek für den Schutz sensibler Daten finden Sie unter Clientbibliotheken für den Schutz sensibler Daten.

Richten Sie Standardanmeldedaten für Anwendungen ein, um sich beim Schutz sensibler Daten zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.

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.")

Ergebnisse von Scans zum Schutz sensibler Daten in Security Command Center ansehen

Da Sie den Schutz sensibler Daten angewiesen haben, die Ergebnisse der Inspektionsjobs an Security Command Center zu senden, können Sie sich die Ergebnisse des Inspektionsjobs jetzt in Security Command Center ansehen:

  1. Rufen Sie in der Google Cloud Console die Security Command Center-Seite Ergebnisse auf.

    Zu Ergebnissen

  2. Wählen Sie die Organisation aus, für die Sie Security Command Center aktiviert haben.
  3. Geben Sie im Feld Abfrageeditor Folgendes ein, um Ergebnisse aus dem Schutz sensibler Daten abzufragen.

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

    Weitere Informationen zum Abfrageeditor finden Sie unter Ergebnisabfrage in der Google Cloud Console bearbeiten.

    Wenn Ergebnisse vom Schutz sensibler Daten gesendet wurden, werden sie in der Ergebnisliste angezeigt. Die Liste enthält alle Ergebnisse des Schutzes sensibler Daten, einschließlich der Ergebnisse aus Inspektionsjobs und Erkennungsvorgängen (Datenprofilerstellung).

In diesem Leitfaden werden nur einige der integrierten Detektoren für den Schutz sensibler Daten aktiviert.

Bereinigen

So vermeiden Sie, dass Ihrem Google Cloud-Konto die in diesem Thema verwendeten Ressourcen in Rechnung gestellt werden:

Projekt löschen

Am einfachsten vermeiden Sie unnötige Kosten, wenn Sie das durch Befolgen der Anweisungen in diesem Thema erstellte Projekt löschen.

  1. Wechseln Sie in der Google Cloud Console zur Seite Ressourcen verwalten.

    Zur Seite „Ressourcen verwalten“

  2. Wählen Sie in der Projektliste das Projekt aus, das Sie löschen möchten, und klicken Sie dann auf Löschen.
  3. Geben Sie im Dialogfeld die Projekt-ID ein und klicken Sie auf Shut down (Beenden), um das Projekt zu löschen.

Wenn Sie Ihr Projekt mit dieser Methode löschen, werden auch der Job für den Schutz sensibler Daten und der von Ihnen erstellte Cloud Storage-Bucket gelöscht. Es ist nicht notwendig, die Anweisungen in den folgenden Abschnitten zu befolgen.

Job zum Schutz sensibler Daten löschen

Wenn Sie Ihre eigenen Daten gescannt haben, müssen Sie nur den von Ihnen erstellten Inspektionsjob löschen:

  1. Klicken Sie auf die folgende Schaltfläche, um APIs Explorer auf der Referenzseite für die Methode dlpJobs.delete aufzurufen:

    APIs Explorer öffnen

  2. Im Feld Name geben Sie den Namen des Jobs aus der JSON-Antwort auf die Scananfrage ein, der folgende Form hat:
    projects/PROJECT_ID/dlpJobs/JOB_ID
    Die Job-ID hat das Format i-1234567890123456789.

Wenn Sie zusätzliche Inspektionsjobs erstellt haben oder sichergehen möchten, dass Sie den Job erfolgreich gelöscht haben, können Sie alle vorhandenen Jobs auflisten:

  1. Klicken Sie auf die folgende Schaltfläche, um APIs Explorer auf der Referenzseite für die Methode dlpJobs.list aufzurufen:

    APIs Explorer öffnen

  2. Geben Sie im Feld parent (Übergeordnete Einheit) die Projektkennung im folgenden Format ein:
    projects/PROJECT_ID
  3. Klicken Sie auf Execute.

Wenn in der Antwort keine Jobs aufgeführt sind, haben Sie alle Jobs gelöscht. Werden Jobs in der Antwort aufgeführt, wiederholen Sie den Löschvorgang für diese Jobs.

Cloud Storage-Bucket löschen

Wenn Sie einen neuen Cloud Storage-Bucket für Beispieldaten erstellt haben, löschen Sie diesen Bucket:

  1. Öffnen Sie den Cloud Storage Browser.

    Cloud Storage öffnen

  2. Aktivieren Sie im Cloud Storage-Browser das Kästchen neben dem Namen des von Ihnen erstellten Buckets und klicken Sie dann auf Löschen.

Nächste Schritte