>

Accessing Cloud SCC programmatically

This section walks you through accessing Cloud Security Command Center (Cloud SCC) programmatically using Cloud Shell to get the client library and authenticate a service account. This guide uses the Python library, and includes example calls for Python and Java.

Before you begin

To complete this guide, you'll need the following:

  • A Cloud Identity and Access Management (Cloud IAM) role that includes an appropriate editor role, like Security Center Admin Editor. For more information about Cloud SCC Cloud IAM roles, see Access control.
  • To complete this guide, you'll need an existing directory path in which a service account private key can be stored. This path is in the context of your Cloud Shell environment, such as /home/myuser/mykeys/.

Accessing Cloud SCC

To access Cloud SCC programmatically, you'll use Cloud Shell to get the client library and authenticate a service account.

Setting up environment variables

  1. Go to the Google Cloud Platform Console.
    Go to the Google Cloud Platform Console
  2. Click Activate Cloud Shell.
  3. Run the following commands to set environment variables:
    1. Set your organization name:

      ORG_ID=YOUR_ORGANIZATION_ID

    2. Set the project ID for which Cloud SCC is enabled:

      PROJECT_ID=Cloud SCC-ENABLED_PROJECT_ID

    3. Set the custom ID you want to use for a new service account, such as SCC-SA:

      SERVICE_ACCOUNT=CUSTOM_ID

    4. Set the path in which the service account key should be stored, such as /home/myuser/mykeys/SERVICE_ACCOUNT.json:

      KEY_LOCATION=FULL_PATH

Installing the Python library

  1. [Optional] Before you install the Python library, we recommend using Virtualenv to create an isolated Python environment.

    virtualenv onboarding_example
    source onboarding_example/bin/activate
          

  2. Install pip to manage the Python library installation.
  3. Run the following commands to install the Python library:

    pip install google-cloud-securitycenter
          

Setting up a service account

The Python library takes a private key from a service account to be used by the client. The service account must have the organization level role securitycenter.adminEditor.

  1. Create a service account that's associated with your project ID:

    gcloud iam service-accounts create SERVICE_ACCOUNT  --display-name
     "Service Account for USER"  --project PROJECT_ID
          
  2. Create a key to associate with the service account. The key will be used for the life of the service and persistently stored at the KEY_LOCATION you specify.

    gcloud iam service-accounts keys create KEY_LOCATION  --iam-account
     SERVICE_ACCOUNT@PROJECT_ID.iam.gserviceaccount.com
          
  3. Grant the service account the securitycenter.adminEditor role for the organization.

    gcloud beta organizations add-iam-policy-binding $ORG_ID
      --member="serviceAccount:SERVICE_ACCOUNT@PROJECT_ID.iam.gserviceaccount.com"
      --role='roles/securitycenter.adminEditor'
        

Starting the service

Start the interactive Python shell and set up imports, variables, and helper function.

$ python
from google.cloud import securitycenter
from google.oauth2 import service_account
from google.protobuf import timestamp_pb2, duration_pb2, struct_pb2
from datetime import datetime, timedelta
from google.cloud.securitycenter_v1beta1 import enums
from google.protobuf import field_mask_pb2
from google.protobuf.struct_pb2 import Value
from google.iam.v1 import policy_pb2

ORGANIZATION = "organizations/TO_BE_UPDATED"
credentials = service_account.Credentials.from_service_account_file(
  'KEY_LOCATION')
scoped_credentials = credentials.with_scopes(
  ['https://www.googleapis.com/auth/cloud-platform'])
client = securitycenter.SecurityCenterClient(credentials = scoped_credentials)
def print_iterator( resource_iterator ):
  for asset in resource_iterator:
    print(asset)
def unix_time_millis(dt):
  return int((dt - datetime.utcfromtimestamp(0)).total_seconds())

Example calls

Python

Most of the following example calls use the print_iterator defined above to print results. In the following examples, the : operator performs partial and substring matching.

Java

To include the Cloud SCC Java library as a dependency in your project, select an artifact from the Maven repository.

To run the operations below, import the following:

import com.google.api.gax.core.FixedCredentialsProvider;
import com.google.auth.oauth2.ServiceAccountCredentials;
import com.google.cloud.securitycenter.v1beta1.Finding;
import com.google.cloud.securitycenter.v1beta1.Finding.State;
import com.google.cloud.securitycenter.v1beta1.FindingName;
import com.google.cloud.securitycenter.v1beta1.ListAssetsRequest;
import com.google.cloud.securitycenter.v1beta1.ListAssetsResponse.ListAssetsResult;
import com.google.cloud.securitycenter.v1beta1.ListFindingsRequest;
import com.google.cloud.securitycenter.v1beta1.OrganizationName;
import com.google.cloud.securitycenter.v1beta1.OrganizationSettings;
import com.google.cloud.securitycenter.v1beta1.OrganizationSettingsName;
import com.google.cloud.securitycenter.v1beta1.SecurityCenterClient;
import com.google.cloud.securitycenter.v1beta1.SecurityCenterClient.ListAssetsPagedResponse;
import com.google.cloud.securitycenter.v1beta1.SecurityCenterClient.ListFindingsPagedResponse;
import com.google.cloud.securitycenter.v1beta1.SecurityCenterClient.ListSourcesPagedResponse;
import com.google.cloud.securitycenter.v1beta1.SecurityCenterSettings;
import com.google.cloud.securitycenter.v1beta1.SecurityMarks;
import com.google.cloud.securitycenter.v1beta1.Source;
import com.google.cloud.securitycenter.v1beta1.SourceName;
import com.google.cloud.securitycenter.v1beta1.UpdateFindingRequest;
import com.google.cloud.securitycenter.v1beta1.UpdateOrganizationSettingsRequest;
import com.google.cloud.securitycenter.v1beta1.UpdateSecurityMarksRequest;
import com.google.cloud.securitycenter.v1beta1.UpdateSourceRequest;
import com.google.iam.v1.Binding;
import com.google.iam.v1.Policy;
import com.google.iam.v1.TestIamPermissionsResponse;
import com.google.protobuf.Duration;
import com.google.protobuf.FieldMask;
import com.google.protobuf.Timestamp;
import com.google.protobuf.Value;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

Then set the main method:

  public static void main(String[] args) throws Exception {
    ServiceAccountCredentials credentials =
        ServiceAccountCredentials.fromStream(new FileInputStream(PATH_TO_JSON_KEY));
    FixedCredentialsProvider fixedCredentialsProvider =
        FixedCredentialsProvider.create(credentials);
    SecurityCenterSettings settings =
        SecurityCenterSettings.newBuilder()
            .setCredentialsProvider(fixedCredentialsProvider)
            .build();
    try (SecurityCenterClient securityCenterClient = SecurityCenterClient.create(settings)) {
      System.out.println(getOrganizationSettings(securityCenterClient));
    }
  }

Go

These samples use the following variables:

var ORGANIZATION = "organizations/[ORGANIZATION_ID]"
// Where ORGANIZATION_ID is the organization ID number from the
// GCP Console Manage Resources page.

var ORGANIZATION_SETTINGS = ORGANIZATION + "/organizationSettings"
var SOURCE = ORGANIZATION + "/sources/[SOURCE_ID]"
// Where SOURCE_ID is the source ID number returned by the
// organizations.sources.list method or found on the Cloud SCC
// dashboard Security Sources page.

var FINDING = SOURCE + "/findings/[FINDING_ID]"
// Where FINDING_ID is the unique finding ID number returned by the
// organizations.sources.findings.list method or found on the Cloud SCC
// dashboard Finding Details page.

var ASSET = ORGANIZATION + "/assets/[ASSET_ID]"
// Where ASSET_ID is the unique asset ID number returned by the
// organizations.assets.list method or found on the Cloud SCC dashboard
// Assets page.

var ASSET_MARK = ASSET + "/securityMarks"
var FINDING_MARK = FINDING + "/securityMarks"
var ASSET_MARK = [ASSET] + "/securityMarks"
var FINDING_MARK = [FINDING] + "/securityMarks"

func main() {
  ctx := context.Background()
  c, err := securitycenter.NewClient(ctx)

  if err != nil {
    fmt.Println("Error instantiating client")
    return
  }

  org_operations(c, ctx)
  iam_operations(c, ctx)
  project_operations(c, ctx)
  resource_operations(c, ctx)
  source_operations(c, ctx)
  findings_operations(c, ctx)
  list_asset_marks_operations(c, ctx)
  list_finding_marks(c, ctx)
  asset_marks_operations(c, ctx)
  finding_marks_operations(c, ctx)

}

To run the operations below, import the following:

import (
  "cloud.google.com/go/securitycenter/apiv1beta1"
  "context"
  "fmt"
  "github.com/golang/protobuf/ptypes/duration"
  "github.com/golang/protobuf/ptypes/struct"
  "github.com/golang/protobuf/ptypes/timestamp"
  "google.golang.org/api/iterator"
  securitycenterpb
    "google.golang.org/genproto/googleapis/cloud/securitycenter/v1beta1"
  "google.golang.org/genproto/googleapis/iam/v1"
  "google.golang.org/genproto/protobuf/field_mask"
  "time"
)
Was this page helpful? Let us know how we did:

Send feedback about...

Cloud Security Command Center
Need help? Visit our support page.