Mencantumkan aset menggunakan Security Command Center API

Aset adalah resource Google Cloud organisasi, seperti instance Compute Engine atau bucket Cloud Storage.

Panduan ini menunjukkan cara menggunakan library klien Security Command Center untuk mengakses catatan yang tidak digunakan lagi yang dikelola Security Command Center untuk aset dalam project atau organisasi.

Security Command Center menyimpan catatan hanya untuk sebagian aset di Inventaris Aset Cloud. Untuk daftar aset yang paling lengkap di lingkungan Anda, gunakan Inventaris Aset Cloud untuk mencantumkan aset.

Untuk informasi selengkapnya, lihat referensi berikut:

Tingkat pemberian untuk peran IAM

Peran IAM untuk Security Command Center dapat diberikan di tingkat organisasi, folder, atau project. Kemampuan Anda untuk melihat, mengedit, membuat, atau memperbarui temuan, aset, dan sumber keamanan bergantung pada tingkat akses yang Anda terima. Untuk mempelajari peran Security Command Center lebih lanjut, lihat Kontrol akses.

Sebelum memulai

Sebelum menyiapkan sumber, Anda harus menyelesaikan hal-hal berikut:

Ukuran Halaman

Semua API daftar Security Command Center memiliki penomoran halaman. Setiap respons menampilkan halaman hasil dan token untuk menampilkan halaman berikutnya. Ukuran halaman dapat dikonfigurasi. pageSize default adalah 10, dapat disetel ke minimum 1, dan maksimum 1.000.

Jenis resource

Atribut resourceType di Security Command Center menggunakan konvensi penamaan yang berbeda dengan Inventaris Aset Cloud. Untuk daftar format jenis resource, lihat Jenis aset yang didukung di Security Command Center.

Mencantumkan semua aset

Contoh ini menunjukkan cara mencantumkan semua aset:

gcloud

Untuk menampilkan daftar semua aset dalam project, folder, atau organisasi, jalankan perintah berikut:

gcloud scc assets list PARENT_ID

Ganti PARENT_ID dengan salah satu nilai berikut:

  • ID organisasi dalam format berikut: ORGANIZATION_ID (hanya ID numerik)
  • ID folder dalam format berikut: folders/FOLDER_ID
  • Project ID dalam format berikut: projects/PROJECT_ID

Untuk contoh lainnya, jalankan:

 gcloud scc assets list --help

Untuk contoh dalam dokumentasi, lihat gcloud scc assets list.

Python

from google.cloud import securitycenter

client = securitycenter.SecurityCenterClient()
# 'parent' must be in one of the following formats:
#   "organizations/{organization_id}"
#   "projects/{project_id}"
#   "folders/{folder_id}"
parent = f"organizations/{organization_id}"

# Call the API and print results.
asset_iterator = client.list_assets(request={"parent": parent})
for i, asset_result in enumerate(asset_iterator):
    print(i, asset_result)

Java

static ImmutableList<ListAssetsResult> listAssets(OrganizationName organizationName) {
  try (SecurityCenterClient client = SecurityCenterClient.create()) {
    // Start setting up a request to search for all assets in an organization, project, or folder.
    //
    // Parent must be in one of the following formats:
    //    OrganizationName organizationName = OrganizationName.of("organization-id");
    //    ProjectName projectName = ProjectName.of("project-id");
    //    FolderName folderName = FolderName.of("folder-id");
    ListAssetsRequest.Builder request =
        ListAssetsRequest.newBuilder().setParent(organizationName.toString());

    // Call the API.
    ListAssetsPagedResponse response = client.listAssets(request.build());

    // This creates one list for all assets.  If your organization has a large number of assets
    // this can cause out of memory issues.  You can process them incrementally by returning
    // the Iterable returned response.iterateAll() directly.
    ImmutableList<ListAssetsResult> results = ImmutableList.copyOf(response.iterateAll());
    System.out.println("All assets:");
    System.out.println(results);
    return results;
  } catch (IOException e) {
    throw new RuntimeException("Couldn't create client.", e);
  }
}

Go

import (
	"context"
	"fmt"
	"io"

	securitycenter "cloud.google.com/go/securitycenter/apiv1"
	"cloud.google.com/go/securitycenter/apiv1/securitycenterpb"
	"google.golang.org/api/iterator"
)

// listAllAssets prints every asset to w for orgID. orgID is the numeric
// Organization ID.
func listAllAssets(w io.Writer, orgID string) error {
	// orgID := "12321311"
	// Instantiate a context and a security service client to make API calls.
	ctx := context.Background()
	client, err := securitycenter.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("securitycenter.NewClient: %w", err)
	}
	defer client.Close() // Closing the client safely cleans up background resources.

	req := &securitycenterpb.ListAssetsRequest{
		// Parent must be in one of the following formats:
		//		"organizations/{orgId}"
		//		"projects/{projectId}"
		//		"folders/{folderId}"
		Parent: fmt.Sprintf("organizations/%s", orgID),
	}

	assetsFound := 0
	it := client.ListAssets(ctx, req)
	for {
		result, err := it.Next()
		if err == iterator.Done {
			break
		}
		if err != nil {
			return fmt.Errorf("ListAssets: %w", err)
		}
		asset := result.Asset
		properties := asset.SecurityCenterProperties
		fmt.Fprintf(w, "Asset Name: %s,", asset.Name)
		fmt.Fprintf(w, "Resource Name %s,", properties.ResourceName)
		fmt.Fprintf(w, "Resource Type %s\n", properties.ResourceType)
		assetsFound++
	}
	return nil
}

Node.js

// Imports the Google Cloud client library.
const {SecurityCenterClient} = require('@google-cloud/security-center');

// Creates a new client.
const client = new SecurityCenterClient();
//  organizationId is the numeric ID of the organization.
/*
 * TODO(developer): Uncomment the following lines
 */
// parent: must be in one of the following formats:
//    `organizations/${organization_id}`
//    `projects/${project_id}`
//    `folders/${folder_id}`
const parent = `organizations/${organizationId}`;
// Call the API with automatic pagination.
async function listAssets() {
  const [response] = await client.listAssets({parent: parent});
  let count = 0;
  Array.from(response).forEach(result =>
    console.log(
      `${++count} ${result.asset.name} ${
        result.asset.securityCenterProperties.resourceName
      }`
    )
  );
}

listAssets();

Output untuk setiap aset adalah objek JSON yang menyerupai berikut:

asset:
  createTime: '2020-10-05T17:55:14.823Z'
  iamPolicy:
    policyBlob: '{"bindings":[{"role":"roles/owner","members":["serviceAccount:SERVICE_ACCOUNT@PROJECT_ID.","user:USER_EMAIL@gmail.com"]}]}'
  name: organizations/ORGANIZATION_ID/assets/ASSET_ID
  resourceProperties:
    createTime: '2020-10-05T17:36:17.915Z'
    lifecycleState: ACTIVE
    name: PROJECT_ID
    parent: '{"id":"ORGANIZATION_ID","type":"organization"}'
    projectId: PROJECT_ID
    projectNumber: 'PROJECT_NUMBER'
  securityCenterProperties:
    resourceDisplayName: PROJECT_ID
    resourceName: //cloudresourcemanager.googleapis.com/projects/PROJECT_NUMBER
    resourceOwners:
    - serviceAccount:SERVICE_ACCOUNT@PROJECT_ID.
    - user:USER_EMAIL@gmail.com
    resourceParent: //cloudresourcemanager.googleapis.com/organizations/ORGANIZATION_ID
    resourceParentDisplayName: ORGANIZATION_NAME
    resourceProject: //cloudresourcemanager.googleapis.com/projects/PROJECT_NUMBER
    resourceProjectDisplayName: PROJECT_ID
    resourceType: google.cloud.resourcemanager.Project
  securityMarks:
    name: organizations/ORGANIZATION_ID/assets/ASSET_ID/securityMarks
  updateTime: '2020-10-05T17:55:14.823Z'

Memfilter aset

Project, folder, atau organisasi mungkin memiliki banyak aset. Contoh sebelumnya tidak menggunakan filter apa pun, sehingga semua aset ditampilkan. Security Command Center memungkinkan Anda menggunakan filter aset untuk mendapatkan informasi tentang aset tertentu. Filter seperti klausa "where" dalam pernyataan SQL, kecuali, bukan kolom, filter berlaku untuk objek yang ditampilkan oleh API.

Contoh output dalam contoh sebelumnya menunjukkan beberapa kolom dan subkolom, serta propertinya, yang dapat digunakan dalam filter aset. Security Command Center mendukung array dan objek JSON lengkap sebagai jenis properti potensial. Anda dapat memfilter berdasarkan:

  • Elemen array
  • Objek JSON lengkap dengan pencocokan string sebagian dalam objek
  • Subkolom objek JSON

Sub-kolom harus berupa angka, string, atau boolean, dan ekspresi filter harus menggunakan operator perbandingan berikut:

  • String:
    • Persamaan penuh =
    • Pencocokan string sebagian :
  • Angka:
    • Ketidaksetaraan <, >, <=, >=
    • Persamaan =
  • Boolean:
    • Persamaan =

Contoh berikut memfilter aset:

gcloud

Gunakan perintah berikut untuk memfilter aset:

gcloud scc assets list PARENT_ID --filter="FILTER"

Ganti kode berikut:

  • FILTER dengan filter yang perlu Anda gunakan. Misalnya, filter berikut hanya menampilkan resource project:
    --filter="security_center_properties.resource_type=\"google.cloud.resourcemanager.Project\""
  • PARENT_ID dengan salah satu nilai berikut:
    • ID organisasi dalam format berikut: ORGANIZATION_ID (hanya ID numerik)
    • ID folder dalam format berikut: folders/FOLDER_ID
    • Project ID dalam format berikut: projects/PROJECT_ID

Untuk contoh lainnya, jalankan:

gcloud scc assets list --help

Untuk contoh dalam dokumentasi, lihat gcloud scc assets list.

Python

from google.cloud import securitycenter

client = securitycenter.SecurityCenterClient()

# 'parent' must be in one of the following formats:
#   "organizations/{organization_id}"
#   "projects/{project_id}"
#   "folders/{folder_id}"
parent = f"organizations/{organization_id}"

project_filter = (
    "security_center_properties.resource_type="
    + '"google.cloud.resourcemanager.Project"'
)
# Call the API and print results.
asset_iterator = client.list_assets(
    request={"parent": parent, "filter": project_filter}
)
for i, asset_result in enumerate(asset_iterator):
    print(i, asset_result)

Java

static ImmutableList<ListAssetsResult> listAssetsWithFilter(OrganizationName organizationName) {
  try (SecurityCenterClient client = SecurityCenterClient.create()) {
    // Start setting up a request to search for all assets in an organization, project, or folder.
    //
    // Parent must be in one of the following formats:
    //    OrganizationName organizationName = OrganizationName.of("organization-id");
    //    ProjectName projectName = ProjectName.of("project-id");
    //    FolderName folderName = FolderName.of("folder-id");
    ListAssetsRequest.Builder request =
        ListAssetsRequest.newBuilder()
            .setParent(organizationName.toString())
            .setFilter(
                "security_center_properties.resource_type=\"google.cloud.resourcemanager.Project\"");

    // Call the API.
    ListAssetsPagedResponse response = client.listAssets(request.build());

    // This creates one list for all assets.  If your organization has a large number of assets
    // this can cause out of memory issues.  You can process them incrementally by returning
    // the Iterable returned response.iterateAll() directly.
    ImmutableList<ListAssetsResult> results = ImmutableList.copyOf(response.iterateAll());
    System.out.println("Project assets:");
    System.out.println(results);
    return results;
  } catch (IOException e) {
    throw new RuntimeException("Couldn't create client.", e);
  }
}

Go

import (
	"context"
	"fmt"
	"io"

	securitycenter "cloud.google.com/go/securitycenter/apiv1"
	"cloud.google.com/go/securitycenter/apiv1/securitycenterpb"
	"google.golang.org/api/iterator"
)

// listAllProjectAssets lists all current GCP project assets in orgID and
// prints out results to w. orgID is the numeric organization ID of interest.
func listAllProjectAssets(w io.Writer, orgID string) error {
	// orgID := "12321311"
	// Instantiate a context and a security service client to make API calls.
	ctx := context.Background()
	client, err := securitycenter.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("securitycenter.NewClient: %w", err)
	}
	defer client.Close() // Closing the client safely cleans up background resources.
	req := &securitycenterpb.ListAssetsRequest{
		// Parent must be in one of the following formats:
		//		"organizations/{orgId}"
		//		"projects/{projectId}"
		//		"folders/{folderId}"
		Parent: fmt.Sprintf("organizations/%s", orgID),
		Filter: `security_center_properties.resource_type="google.cloud.resourcemanager.Project"`,
	}

	assetsFound := 0
	it := client.ListAssets(ctx, req)
	for {
		result, err := it.Next()
		if err == iterator.Done {
			break
		}
		if err != nil {
			return fmt.Errorf("ListAssets: %w", err)
		}
		asset := result.Asset
		properties := asset.SecurityCenterProperties
		fmt.Fprintf(w, "Asset Name: %s,", asset.Name)
		fmt.Fprintf(w, "Resource Name %s,", properties.ResourceName)
		fmt.Fprintf(w, "Resource Type %s\n", properties.ResourceType)
		assetsFound++
	}
	return nil
}

Node.js

// Imports the Google Cloud client library.
const {SecurityCenterClient} = require('@google-cloud/security-center');

// Creates a new client.
const client = new SecurityCenterClient();
//  organizationId is the numeric ID of the organization.
/*
 * TODO(developer): Uncomment the following lines
 */
// const organizationId = "1234567777";
const orgName = client.organizationPath(organizationId);

// Call the API with automatic pagination.
// You can also list assets in a project/ folder. To do so, modify the parent
// value and filter condition.
async function listFilteredAssets() {
  const [response] = await client.listAssets({
    parent: orgName,
    filter:
      'security_center_properties.resource_type="google.cloud.resourcemanager.Project"',
  });
  let count = 0;
  Array.from(response).forEach(result =>
    console.log(
      `${++count} ${result.asset.name} ${
        result.asset.securityCenterProperties.resourceName
      } ${result.stateChange}`
    )
  );
}

listFilteredAssets();

Mencantumkan pada titik waktu tertentu

Contoh sebelumnya menunjukkan cara membuat daftar kumpulan aset saat ini. Security Command Center juga memungkinkan Anda melihat ringkasan historis aset. Contoh berikut menampilkan status semua aset pada titik waktu tertentu. Security Command Center mendukung resolusi waktu milidetik.

gcloud

Gunakan perintah berikut untuk mencantumkan aset pada titik waktu tertentu:

gcloud scc assets list PARENT_ID --read-time="READ_TIME"

Ganti kode berikut:

  • READ_TIME dengan waktu untuk mencantumkan aset. Gunakan format berikut: YYYY-MM-DDThh:mm:ss.ffffffZ. Contoh:
    --read-time="2022-12-21T07:00:06.861Z"
  • PARENT_ID dengan salah satu nilai berikut:
    • ID organisasi dalam format berikut: ORGANIZATION_ID (hanya ID numerik)
    • Project ID dalam format berikut: projects/PROJECT_ID
    • ID folder dalam format berikut: folders/FOLDER_ID

Untuk contoh lainnya, jalankan:

gcloud scc assets list --help

Untuk contoh dalam dokumentasi, lihat gcloud scc assets list.

Python

from datetime import datetime, timedelta, timezone

from google.cloud import securitycenter

client = securitycenter.SecurityCenterClient()

# 'parent' must be in one of the following formats:
#   "organizations/{organization_id}"
#   "projects/{project_id}"
#   "folders/{folder_id}"
parent = f"organizations/{organization_id}"

project_filter = (
    "security_center_properties.resource_type="
    + '"google.cloud.resourcemanager.Project"'
)

# Lists assets as of yesterday.
read_time = datetime.now(tz=timezone.utc) - timedelta(days=1)

# Call the API and print results.
asset_iterator = client.list_assets(
    request={"parent": parent, "filter": project_filter, "read_time": read_time}
)
for i, asset_result in enumerate(asset_iterator):
    print(i, asset_result)

Java

static ImmutableList<ListAssetsResult> listAssetsAsOfYesterday(
    OrganizationName organizationName, Instant asOf) {
  try (SecurityCenterClient client = SecurityCenterClient.create()) {
    // Start setting up a request to search for all assets in an organization, project, or folder.
    //
    // Parent must be in one of the following formats:
    //    OrganizationName organizationName = OrganizationName.of("organization-id");
    //    ProjectName projectName = ProjectName.of("project-id");
    //    FolderName folderName = FolderName.of("folder-id");
    // Initialize the builder with the parent and filter
    ListAssetsRequest.Builder request =
        ListAssetsRequest.newBuilder()
            .setParent(organizationName.toString())
            .setFilter(
                "security_center_properties.resource_type=\"google.cloud.resourcemanager.Project\"");

    // Set read time to either the instant passed in or one day ago.
    asOf = MoreObjects.firstNonNull(asOf, Instant.now().minus(Duration.ofDays(1)));
    request.getReadTimeBuilder().setSeconds(asOf.getEpochSecond()).setNanos(asOf.getNano());

    // Call the API.
    ListAssetsPagedResponse response = client.listAssets(request.build());

    // This creates one list for all assets.  If your organization has a large number of assets
    // this can cause out of memory issues.  You can process them incrementally by returning
    // the Iterable returned response.iterateAll() directly.
    ImmutableList<ListAssetsResult> results = ImmutableList.copyOf(response.iterateAll());
    System.out.println("Projects:");
    System.out.println(results);
    return results;
  } catch (IOException e) {
    throw new RuntimeException("Couldn't create client.", e);
  }
}

Go

import (
	"context"
	"fmt"
	"io"
	"time"

	securitycenter "cloud.google.com/go/securitycenter/apiv1"
	"cloud.google.com/go/securitycenter/apiv1/securitycenterpb"
	"github.com/golang/protobuf/ptypes"
	"google.golang.org/api/iterator"
)

// listAllProjectAssets lists all GCP Projects in orgID at asOf time and prints
// out results to w. orgID is the numeric organization ID of interest.
func listAllProjectAssetsAtTime(w io.Writer, orgID string, asOf time.Time) error {
	// orgID := "12321311"
	// Instantiate a context and a security service client to make API calls.
	ctx := context.Background()
	client, err := securitycenter.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("securitycenter.NewClient: %w", err)
	}
	defer client.Close() // Closing the client safely cleans up background resources.

	// Convert the time to a Timestamp protobuf
	readTime, err := ptypes.TimestampProto(asOf)
	if err != nil {
		return fmt.Errorf("TimestampProto(%v): %w", asOf, err)
	}

	// You can also list assets in a project/ folder. To do so, modify the parent and
	// filter condition.
	req := &securitycenterpb.ListAssetsRequest{
		// Parent must be in one of the following formats:
		//		"organizations/{orgId}"
		//		"projects/{projectId}"
		//		"folders/{folderId}"
		Parent:   fmt.Sprintf("organizations/%s", orgID),
		Filter:   `security_center_properties.resource_type="google.cloud.resourcemanager.Project"`,
		ReadTime: readTime,
	}

	assetsFound := 0
	it := client.ListAssets(ctx, req)
	for {
		result, err := it.Next()
		if err == iterator.Done {
			break
		}
		if err != nil {
			return fmt.Errorf("ListAssets: %w", err)
		}
		asset := result.Asset
		properties := asset.SecurityCenterProperties
		fmt.Fprintf(w, "Asset Name: %s,", asset.Name)
		fmt.Fprintf(w, "Resource Name %s,", properties.ResourceName)
		fmt.Fprintf(w, "Resource Type %s\n", properties.ResourceType)
		assetsFound++
	}
	return nil
}

Node.js

// Imports the Google Cloud client library.
const {SecurityCenterClient} = require('@google-cloud/security-center');

// Creates a new client.
const client = new SecurityCenterClient();
//  organizationId is the numeric ID of the organization.
/*
 * TODO(developer): Uncomment the following lines
 */
// parent: must be in one of the following formats:
//    `organizations/${organization_id}`
//    `projects/${project_id}`
//    `folders/${folder_id}`
const parent = `organizations/${organizationId}`;

const oneDayAgo = new Date();
oneDayAgo.setDate(oneDayAgo.getDate() - 1);

// Call the API with automatic pagination.
async function listAssetsAtTime() {
  const [response] = await client.listAssets({
    parent: parent,
    filter:
      'security_center_properties.resource_type="google.cloud.resourcemanager.Project"',
    // readTime must be in the form of a google.protobuf.Timestamp object
    // which takes seconds and nanoseconds.
    readTime: {
      seconds: Math.floor(oneDayAgo.getTime() / 1000),
      nanos: (oneDayAgo.getTime() % 1000) * 1e6,
    },
  });
  let count = 0;
  Array.from(response).forEach(result =>
    console.log(
      `${++count} ${result.asset.name} ${
        result.asset.securityCenterProperties.resourceName
      }`
    )
  );
}

listAssetsAtTime();

Mencantumkan aset dengan perubahan status

Security Command Center memungkinkan Anda membandingkan aset pada dua titik waktu untuk mengidentifikasi apakah aset tersebut ditambahkan, dihapus, atau ada selama jangka waktu yang ditentukan. Contoh berikut membandingkan project yang ada di READ_TIME dengan titik waktu sebelumnya yang ditentukan oleh COMPARE_DURATION. COMPARE_DURATION diberikan dalam detik.

Saat COMPARE_DURATION ditetapkan, atribut stateChange pada hasil aset daftar akan diperbarui dengan salah satu nilai berikut:

  • ADDED: aset tidak ada di awal compareDuration, tetapi ada di readTime.
  • REMOVED: aset ada di awal compareDuration, tetapi tidak ada di readTime.
  • ACTIVE: aset ada di awal dan akhir jangka waktu yang ditentukan oleh compareDuration dan readTime.

gcloud

Gunakan perintah berikut untuk membandingkan status aset pada dua titik waktu:

gcloud scc assets list PARENT_ID \
    --filter="FILTER" \
    --read-time=READ_TIME \
    --compare-duration=COMPARE_DURATION

Ganti kode berikut:

  • COMPARE_DURATION dengan jumlah detik yang menentukan titik waktu sebelum waktu yang ditentukan pada tanda --read-time. Contoh:
    --compare-duration=84600s
  • FILTER dengan filter yang perlu Anda gunakan. Misalnya, filter berikut hanya menampilkan resource project:
    --filter="security_center_properties.resource_type=\"google.cloud.resourcemanager.Project\""
  • PARENT_ID dengan salah satu nilai berikut:
    • ID organisasi dalam format berikut: ORGANIZATION_ID (hanya ID numerik)
    • Project ID dalam format berikut: projects/PROJECT_ID
    • ID folder dalam format berikut: folders/FOLDER_ID
  • READ_TIME dengan waktu untuk mencantumkan aset. Gunakan format berikut: YYYY-MM-DDThh:mm:ss.ffffffZ. Contoh:
    --read-time="2022-12-21T07:00:06.861Z"
    Untuk contoh lainnya, jalankan:
gcloud scc assets list --help

Untuk contoh dalam dokumentasi, lihat gcloud scc assets list.

Python

from datetime import timedelta

from google.cloud import securitycenter

client = securitycenter.SecurityCenterClient()

# 'parent' must be in one of the following formats:
#   "organizations/{organization_id}"
#   "projects/{project_id}"
#   "folders/{folder_id}"
parent = f"organizations/{organization_id}"
project_filter = (
    "security_center_properties.resource_type="
    + '"google.cloud.resourcemanager.Project"'
)

# List assets and their state change the last 30 days
compare_delta = timedelta(days=30)

# Call the API and print results.
asset_iterator = client.list_assets(
    request={
        "parent": parent,
        "filter": project_filter,
        "compare_duration": compare_delta,
    }
)
for i, asset in enumerate(asset_iterator):
    print(i, asset)

Java

static ImmutableList<ListAssetsResult> listAssetAndStatusChanges(
    OrganizationName organizationName, Duration timeSpan, Instant asOf) {
  try (SecurityCenterClient client = SecurityCenterClient.create()) {

    // Start setting up a request to search for all assets in an organization, project, or folder.
    //
    // Parent must be in one of the following formats:
    //    OrganizationName organizationName = OrganizationName.of("organization-id");
    //    ProjectName projectName = ProjectName.of("project-id");
    //    FolderName folderName = FolderName.of("folder-id");
    ListAssetsRequest.Builder request =
        ListAssetsRequest.newBuilder()
            .setParent(organizationName.toString())
            .setFilter(
                "security_center_properties.resource_type=\"google.cloud.resourcemanager.Project\"");
    request
        .getCompareDurationBuilder()
        .setSeconds(timeSpan.getSeconds())
        .setNanos(timeSpan.getNano());

    // Set read time to either the instant passed in or now.
    asOf = MoreObjects.firstNonNull(asOf, Instant.now());
    request.getReadTimeBuilder().setSeconds(asOf.getEpochSecond()).setNanos(asOf.getNano());

    // Call the API.
    ListAssetsPagedResponse response = client.listAssets(request.build());

    // This creates one list for all assets.  If your organization has a large number of assets
    // this can cause out of memory issues.  You can process them incrementally by returning
    // the Iterable returned response.iterateAll() directly.
    ImmutableList<ListAssetsResult> results = ImmutableList.copyOf(response.iterateAll());
    System.out.println("Projects:");
    System.out.println(results);
    return results;
  } catch (IOException e) {
    throw new RuntimeException("Couldn't create client.", e);
  }
}

Go

import (
	"context"
	"fmt"
	"io"
	"time"

	securitycenter "cloud.google.com/go/securitycenter/apiv1"
	"cloud.google.com/go/securitycenter/apiv1/securitycenterpb"
	"github.com/golang/protobuf/ptypes"
	"google.golang.org/api/iterator"
)

// listAllProjectAssetsAndStateChange lists all current GCP project assets in
// orgID and prints the projects and there change from a day ago out to w.
// orgID is the numeric // organization ID of interest.
func listAllProjectAssetsAndStateChanges(w io.Writer, orgID string) error {
	// orgID := "12321311"
	// Instantiate a context and a security service client to make API calls.
	ctx := context.Background()
	client, err := securitycenter.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("securitycenter.NewClient: %w", err)
	}
	defer client.Close() // Closing the client safely cleans up background resources.

	req := &securitycenterpb.ListAssetsRequest{
		// Parent must be in one of the following formats:
		//		"organizations/{orgId}"
		//		"projects/{projectId}"
		//		"folders/{folderId}"
		Parent:          fmt.Sprintf("organizations/%s", orgID),
		Filter:          `security_center_properties.resource_type="google.cloud.resourcemanager.Project"`,
		CompareDuration: ptypes.DurationProto(24 * time.Hour),
	}

	assetsFound := 0
	it := client.ListAssets(ctx, req)
	for {
		result, err := it.Next()
		if err == iterator.Done {
			break
		}
		if err != nil {
			return fmt.Errorf("ListAssets: %w", err)
		}
		asset := result.Asset
		properties := asset.SecurityCenterProperties
		fmt.Fprintf(w, "Asset Name: %s,", asset.Name)
		fmt.Fprintf(w, "Resource Name %s,", properties.ResourceName)
		fmt.Fprintf(w, "Resource Type %s", properties.ResourceType)
		fmt.Fprintf(w, "State Change %s\n", result.StateChange)
		assetsFound++
	}
	return nil
}

Node.js

// Imports the Google Cloud client library.
const {SecurityCenterClient} = require('@google-cloud/security-center');

// Creates a new client.
const client = new SecurityCenterClient();
//  organizationId is the numeric ID of the organization.
/*
 * TODO(developer): Uncomment the following lines
 */
// parent: must be in one of the following formats:
//    `organizations/${organization_id}`
//    `projects/${project_id}`
//    `folders/${folder_id}`
const parent = `organizations/${organizationId}`;
// Call the API with automatic pagination.
async function listAssetsAndChanges() {
  const [response] = await client.listAssets({
    parent: parent,
    compareDuration: {seconds: 30 * /*Second in Day=*/ 86400, nanos: 0},
    filter:
      'security_center_properties.resource_type="google.cloud.resourcemanager.Project"',
  });
  let count = 0;
  Array.from(response).forEach(result =>
    console.log(
      `${++count} ${result.asset.name} ${
        result.asset.securityCenterProperties.resourceName
      } ${result.stateChange}`
    )
  );
}

listAssetsAndChanges();

Contoh filter

Berikut beberapa filter aset lain yang berguna. Anda dapat menggunakan AND dan OR dalam filter untuk menggabungkan parameter dan memperluas atau menyaring hasil.

Menemukan Aset Project dengan pemilik tertentu

"security_center_properties.resource_type = \"google.cloud.resourcemanager.Project\" AND security_center_properties.resource_owners : \"$USER\""

$USER biasanya dalam format user:someone@domain.com. Perbandingan untuk user menggunakan operator substring : dan kecocokan persis tidak diperlukan.

Aturan firewall yang memiliki Port HTTP terbuka

"security_center_properties.resource_type = \"google.compute.Firewall\" AND resource_properties.name =\"default-allow-http\""

Resource yang termasuk dalam project tertentu

"security_center_properties.resource_parent = \"$PROJECT_1_NAME\" OR security_center_properties.resource_parent = \"$PROJECT_2_NAME\""

$PROJECT_1_NAME dan $PROJECT_2_NAME adalah ID resource dalam bentuk //cloudresourcemanager.googleapis.com/projects/$PROJECT_ID, dengan $PROJECT_ID adalah nomor project. Contoh lengkap akan berupa hal seperti: //cloudresourcemanager.googleapis.com/projects/100090906

Menemukan image Compute Engine yang namanya berisi string tertentu

Filter ini menampilkan image Compute Engine yang berisi substring "Debia":

"security_center_properties.resource_type = \"google.compute.Image\" AND resource_properties.name : \"Debia\""

Resource yang propertinya berisi key-value pair

Filter ini menampilkan bucket Cloud Storage tempat bucketPolicyOnly dinonaktifkan. Nilai resourceProperties.iamConfiguration dienkode sebagai string. Anda menggunakan karakter \ untuk meng-escape karakter khusus dalam string, termasuk operator : di antara nama kunci dan nilai.

"resourceProperties.iamConfiguration:"\"bucketPolicyOnly\"\:{\"enabled\"\:false""

Menemukan Aset Project yang dibuat pada atau sebelum waktu tertentu

Contoh filter ini cocok dengan aset yang dibuat pada atau sebelum 18 Juli 2019 pukul 20.26.21 GMT. Dengan filter create_time, Anda dapat menyatakan waktu menggunakan format dan jenis berikut:

  • Waktu Unix (dalam milidetik) sebagai literal bilangan bulat

    "create_time <= 1563481581000"
    
  • RFC 3339 sebagai literal string

    "create_time <= \"2019-07-18T20:26:21+00:00\""
    

Mengecualikan aset dari hasil

Untuk mengecualikan aset dari hasil, gunakan negasi dengan menempatkan karakter - di depan parameter. Operasi ini mirip dengan menggunakan operator NOT dalam pernyataan SQL.

Filter ini menampilkan semua resource project kecuali Debia:

"security_center_properties.resource_type = \"google.cloud.resourcemanager.Project\" AND -resource_properties.projectId = \"Debia\""

Langkah selanjutnya

Pelajari lebih lanjut cara mengakses Security Command Center menggunakan library klien.