숨기기 규칙 만들기

필터를 사용하여 향후 발견 항목을 자동으로 숨기는 구성인 숨기기 규칙을 만드는 방법을 보여줍니다.

더 살펴보기

이 코드 샘플이 포함된 자세한 문서는 다음을 참조하세요.

코드 샘플

Go

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


import (
	"context"
	"fmt"
	"io"

	securitycenter "cloud.google.com/go/securitycenter/apiv1"
	"cloud.google.com/go/securitycenter/apiv1/securitycenterpb"
)

// createMuteRule: Creates a mute configuration under a given scope that will mute
// all new findings that match a given filter.
// Existing findings will not be muted.
func createMuteRule(w io.Writer, parent string, muteConfigId string) error {
	// parent: Use any one of the following options:
	//             - organizations/{organization_id}
	//             - folders/{folder_id}
	//             - projects/{project_id}
	// parent := fmt.Sprintf("projects/%s", "your-google-cloud-project-id")
	// muteConfigId: Set a random id; max of 63 chars.
	// muteConfigId := "random-mute-id-" + uuid.New().String()
	ctx := context.Background()
	client, err := securitycenter.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("securitycenter.NewClient: %w", err)
	}
	defer client.Close()

	muteConfig := &securitycenterpb.MuteConfig{
		Description: "Mute low-medium IAM grants excluding 'compute' ",
		// Set mute rule(s).
		// To construct mute rules and for supported properties, see:
		// https://cloud.google.com/security-command-center/docs/how-to-mute-findings#create_mute_rules
		Filter: "severity=\"LOW\" OR severity=\"MEDIUM\" AND " +
			"category=\"Persistence: IAM Anomalous Grant\" AND " +
			"-resource.type:\"compute\"",
	}

	req := &securitycenterpb.CreateMuteConfigRequest{
		Parent:       parent,
		MuteConfigId: muteConfigId,
		MuteConfig:   muteConfig,
	}

	response, err := client.CreateMuteConfig(ctx, req)
	if err != nil {
		return fmt.Errorf("failed to create mute rule: %w", err)
	}
	fmt.Fprintf(w, "Mute rule created successfully: %s", response.Name)
	return nil
}

Java

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


import com.google.cloud.securitycenter.v1.CreateMuteConfigRequest;
import com.google.cloud.securitycenter.v1.MuteConfig;
import com.google.cloud.securitycenter.v1.SecurityCenterClient;
import java.io.IOException;
import java.util.UUID;

public class CreateMuteRule {

  public static void main(String[] args) {
    // TODO: Replace the variables within {}

    // parentPath: Use any one of the following options:
    //             - organizations/{organization_id}
    //             - folders/{folder_id}
    //             - projects/{project_id}
    String parentPath = String.format("projects/%s", "your-google-cloud-project-id");

    // muteConfigId: Set a random id; max of 63 chars.
    String muteConfigId = "random-mute-id-" + UUID.randomUUID();
    createMuteRule(parentPath, muteConfigId);
  }

  // Creates a mute configuration under a given scope that will mute
  // all new findings that match a given filter.
  // Existing findings will not be muted.
  public static void createMuteRule(String parentPath, String muteConfigId) {
    // 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 (SecurityCenterClient client = SecurityCenterClient.create()) {

      MuteConfig muteConfig =
          MuteConfig.newBuilder()
              .setDescription("Mute low-medium IAM grants excluding 'compute' ")
              // Set mute rule(s).
              // To construct mute rules and for supported properties, see:
              // https://cloud.google.com/security-command-center/docs/how-to-mute-findings#create_mute_rules
              .setFilter(
                  "severity=\"LOW\" OR severity=\"MEDIUM\" AND "
                      + "category=\"Persistence: IAM Anomalous Grant\" AND "
                      + "-resource.type:\"compute\"")
              .build();

      CreateMuteConfigRequest request =
          CreateMuteConfigRequest.newBuilder()
              .setParent(parentPath)
              .setMuteConfigId(muteConfigId)
              .setMuteConfig(muteConfig)
              .build();

      // ExecutionException is thrown if the below call fails.
      MuteConfig response = client.createMuteConfig(request);
      System.out.println("Mute rule created successfully: " + response.getName());
    } catch (IOException e) {
      System.out.println("Mute rule creation failed! \n Exception: " + e);
    }
  }
}

Python

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



def create_mute_rule(parent_path: str, mute_config_id: str) -> None:
    """
    Creates a mute configuration under a given scope that will mute
    all new findings that match a given filter.
    Existing findings will NOT BE muted.
    Args:
        parent_path: use any one of the following options:
                     - organizations/{organization_id}
                     - folders/{folder_id}
                     - projects/{project_id}
        mute_config_id: Set a unique id; max of 63 chars.
    """

    from google.cloud import securitycenter

    client = securitycenter.SecurityCenterClient()

    mute_config = securitycenter.MuteConfig()
    mute_config.description = "Mute low-medium IAM grants excluding 'compute' "
    # Set mute rule(s).
    # To construct mute rules and for supported properties, see:
    # https://cloud.google.com/security-command-center/docs/how-to-mute-findings#create_mute_rules
    mute_config.filter = (
        'severity="LOW" OR severity="MEDIUM" AND '
        'category="Persistence: IAM Anomalous Grant" AND '
        '-resource.type:"compute"'
    )

    request = securitycenter.CreateMuteConfigRequest()
    request.parent = parent_path
    request.mute_config_id = mute_config_id
    request.mute_config = mute_config

    mute_config = client.create_mute_config(request=request)
    print(f"Mute rule created successfully: {mute_config.name}")

다음 단계

다른 Google Cloud 제품의 코드 샘플을 검색하고 필터링하려면 Google Cloud 샘플 브라우저를 참조하세요.