Security Command Center API를 사용하여 애셋 나열

>

애셋은 Compute Engine 인스턴스 또는 Cloud Storage 버킷과 같은 조직의 Google Cloud 리소스입니다. 이 가이드에서는 Security Command Center 클라이언트 라이브러리를 사용하여 조직의 애셋에 대한 메타데이터에 액세스하는 방법을 보여줍니다.

시작하기 전에

소스를 설정하기 전에 다음을 완료해야 합니다.

페이지 크기

모든 Security Command Center 목록 API는 페이지로 나뉩니다. 각 응답은 결과 페이지와 다음 페이지를 반환하는 토큰을 반환합니다. 페이지 크기는 구성 가능합니다. 기본 pageSize는 10, 최소 1, 최대 1000으로 설정할 수 있습니다.

모든 애셋 나열

다음 예시에서는 조직의 모든 애셋을 나열하는 방법을 보여줍니다.

gcloud

  # ORGANIZATION_ID=12344321

  gcloud scc assets list $ORGANIZATION_ID

더 많은 예시를 보려면 다음을 실행하세요.

  gcloud scc assets list --help

Python

from google.cloud import securitycenter

client = securitycenter.SecurityCenterClient()
# organization_id is the numeric ID of the organization.
# organization_id = "1234567777"
org_name = "organizations/{org_id}".format(org_id=organization_id)

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

자바

static ImmutableList<ListAssetsResult> listAssets(OrganizationName organizationName) {
  try (SecurityCenterClient client = SecurityCenterClient.create()) {
    // Start setting up a request for to search for all assets in an organization.
    // OrganizationName organizationName = OrganizationName.of(/*organizationId=*/"123234324");
    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"
	"google.golang.org/api/iterator"
	securitycenterpb "google.golang.org/genproto/googleapis/cloud/securitycenter/v1"
)

// 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: %v", err)
	}
	defer client.Close() // Closing the client safely cleans up background resources.

	req := &securitycenterpb.ListAssetsRequest{
		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: %v", 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 = "111122222444";
const orgName = client.organizationPath(organizationId);
// Call the API with automatic pagination.
async function listAssets() {
  const [response] = await client.listAssets({parent: orgName});
  let count = 0;
  Array.from(response).forEach(result =>
    console.log(
      `${++count} ${result.asset.name} ${
        result.asset.securityCenterProperties.resourceName
      }`
    )
  );
}

listAssets();

각 애셋의 출력은 다음과 비슷합니다.

asset:
  createTime: '2020-10-05T17:55:14.823Z'
  iamPolicy:
    policyBlob: '{"bindings":[{"role":"roles/owner","members":["serviceAccount:service-account@project-id.iam.gserviceaccount.com","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.iam.gserviceaccount.com
    - 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'

애셋 필터링

한 조직에는 여러 애셋이 있을 수 있습니다. 앞의 예시에서는 필터를 사용하지 않으므로 모든 애셋이 반환됩니다. Security Command Center를 사용하면 애셋 필터를 사용하여 특정 애셋에 대한 정보를 얻을 수 있습니다. 필터는 열 대신 API에서 반환한 객체를 적용하는 것을 제외하고는 SQL 문의 'where' 절과 같습니다.

아래 예시에서는 필터를 사용하여 조직의 프로젝트 리소스만 반환합니다.

gcloud

  # ORGANIZATION_ID=12344321
  FILTER="security_center_properties.resource_type=\"google.cloud.resourcemanager.Project\""

  gcloud scc assets list $ORGANIZATION_ID --filter="$FILTER"

더 많은 예시를 보려면 다음을 실행하세요.

  gcloud scc assets list --help

Python

from google.cloud import securitycenter

client = securitycenter.SecurityCenterClient()

# organization_id is the numeric ID of the organization.
# organization_id = "1234567777"
org_name = "organizations/{org_id}".format(org_id=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": org_name, "filter": project_filter}
)
for i, asset_result in enumerate(asset_iterator):
    print(i, asset_result)

자바

static ImmutableList<ListAssetsResult> listAssetsWithFilter(OrganizationName organizationName) {
  try (SecurityCenterClient client = SecurityCenterClient.create()) {
    // Start setting up a request for to search for all assets in an organization.
    // OrganizationName organizationName = OrganizationName.of(/*organizationId=*/"123234324");
    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"
	"google.golang.org/api/iterator"
	securitycenterpb "google.golang.org/genproto/googleapis/cloud/securitycenter/v1"
)

// 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: %v", err)
	}
	defer client.Close() // Closing the client safely cleans up background resources.
	req := &securitycenterpb.ListAssetsRequest{
		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: %v", 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.
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();

특정 시점으로 나열

이전 예시에서는 조직의 현재 애셋 집합을 나열하는 방법을 보여줍니다. Security Command Center를 사용하면 조직 애셋의 이전 스냅샷을 볼 수도 있습니다. 아래 예시에서는 특정 시점에 모든 리소스의 상태를 반환합니다. Security Command Center는 밀리초 시간 해결 방법을 지원합니다.

gcloud

  # ORGANIZATION_ID=12344321
  # READ_TIME follows the format YYYY-MM-DDThh:mm:ss.ffffffZ
  READ_TIME=2019-02-28T07:00:06.861Z

  gcloud scc assets list $ORGANIZATION_ID --read-time=$READ_TIME

더 많은 예시를 보려면 다음을 실행하세요.

  gcloud scc assets list --help

Python

from datetime import datetime, timedelta

from google.cloud import securitycenter

client = securitycenter.SecurityCenterClient()

# organization_id is the numeric ID of the organization.
# organization_id = "1234567777"
org_name = "organizations/{org_id}".format(org_id=organization_id)

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

# Lists assets as of yesterday.
read_time = datetime.utcnow() - timedelta(days=1)

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

자바

static ImmutableList<ListAssetsResult> listAssetsAsOfYesterday(
    OrganizationName organizationName, Instant asOf) {
  try (SecurityCenterClient client = SecurityCenterClient.create()) {
    // Start setting up a request for to search for all assets in an organization.
    // OrganizationName organizationName = OrganizationName.of(/*organizationId=*/"123234324");

    // Initialize the builder with the organization 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"
	"github.com/golang/protobuf/ptypes"
	"google.golang.org/api/iterator"
	securitycenterpb "google.golang.org/genproto/googleapis/cloud/securitycenter/v1"
)

// 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: %v", 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): %v", asOf, err)
	}

	req := &securitycenterpb.ListAssetsRequest{
		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: %v", 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);

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

// Call the API with automatic pagination.
async function listAssetsAtTime() {
  const [response] = await client.listAssets({
    parent: orgName,
    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();

상태 변경이 있는 애셋 나열

Security Command Center를 사용하면 애셋을 이전 기간과 비교하여 지정된 기간 동안 애셋이 생성, 삭제, 제공되었는지 확인할 수 있습니다. 이 정보는 목록 애셋 결과의 state_change 필드에서 캡처됩니다.

gcloud

  # ORGANIZATION_ID=12344321
  # READ_TIME follows the format YYYY-MM-DDThh:mm:ss.ffffffZ
  READ_TIME=2019-02-28T07:00:06.861Z
  FILTER="security_center_properties.resource_type=\"google.cloud.resourcemanager.Project\""
  COMPARE_DURATION=86400s

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

더 많은 예시를 보려면 다음을 실행하세요.

  gcloud scc assets list --help

Python

from datetime import timedelta

from google.cloud import securitycenter

client = securitycenter.SecurityCenterClient()

# organization_id is the numeric ID of the organization.
# organization_id = "1234567777"
org_name = "organizations/{org_id}".format(org_id=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": org_name,
        "filter": project_filter,
        "compare_duration": compare_delta,
    }
)
for i, asset in enumerate(asset_iterator):
    print(i, asset)

자바

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

    // Start setting up a request for to search for all assets in an organization.
    // OrganizationName organizationName = OrganizationName.of(/*organizationId=*/"123234324");
    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"
	"github.com/golang/protobuf/ptypes"
	"google.golang.org/api/iterator"
	securitycenterpb "google.golang.org/genproto/googleapis/cloud/securitycenter/v1"
)

// 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: %v", err)
	}
	defer client.Close() // Closing the client safely cleans up background resources.

	req := &securitycenterpb.ListAssetsRequest{
		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: %v", 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
 */
// const organizationId = "1234567777";
const orgName = client.organizationPath(organizationId);
// Call the API with automatic pagination.
async function listAssetsAndChanges() {
  const [response] = await client.listAssets({
    parent: orgName,
    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();

필터 예시

다음은 몇 가지의 다른 유용한 애셋 필터입니다.

특정 시간 또는 이전에 생성된 프로젝트 애셋 찾기

이러한 예시 필터는 2019년 7월 18일 오후 8:26:21(GMT) 또는 그 이전에 생성된 애셋과 일치합니다. create_time 필터를 사용하면 다음 형식 및 유형을 사용하여 시간을 표시할 수 있습니다.

  • 정수 리터럴로서의 Unix 시간(밀리초)

    "create_time <= 1563481581000"
    
  • 문자열 리터럴로서의 RFC 3339

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

특정 소유자가 있는 프로젝트 애셋 찾기

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

$USER는 일반적으로 user:someone@domain.com 형식입니다. user 비교 시 하위 문자열 연산자 :를 사용하므로 일치검색은 필요하지 않습니다.

열린 HTTP 포트가 있는 방화벽 규칙

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

특정 프로젝트에 속하는 리소스

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

$PROJECT_1_NAME$PROJECT_2_NAME//cloudresourcemanager.googleapis.com/projects/$PROJECT_ID 형식의 리소스 식별자입니다. 여기서 $PROJECT_ID는 프로젝트 번호입니다. 전체 예시는 //cloudresourcemanager.googleapis.com/projects/100090906와 같습니다.

이름에 특정 문자열이 포함된 Compute Engine 이미지 찾기

이 필터는 하위 문자열 'Debia'가 포함된 Compute Engine 이미지를 반환합니다.

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