Create Event Threat Detection custom modules

Sample code for creation of Event Threat Detection custom modules.

Code sample

Go

To authenticate to Security Command Center, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.


import (
	"context"
	"fmt"
	"io"
	"regexp"

	securitycentermanagement "cloud.google.com/go/securitycentermanagement/apiv1"
	securitycentermanagementpb "cloud.google.com/go/securitycentermanagement/apiv1/securitycentermanagementpb"
	"github.com/google/uuid"
	"google.golang.org/protobuf/types/known/structpb"
)

// createEventThreatDetectionCustomModule creates a custom module for Event Threat Detection.
func createEventThreatDetectionCustomModule(w io.Writer, parent string) error {
	// parent: Use any one of the following options:
	// - organizations/{organization_id}/locations/{location_id}
	// - folders/{folder_id}/locations/{location_id}
	// - projects/{project_id}/locations/{location_id}

	ctx := context.Background()
	client, err := securitycentermanagement.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("securitycentermanagement.NewClient: %w", err)
	}
	defer client.Close()

	uniqueSuffix := uuid.New().String()

	// Remove invalid characters (anything that isn't alphanumeric or an underscore)
	re := regexp.MustCompile(`[^a-zA-Z0-9_]`)
	uniqueSuffix = re.ReplaceAllString(uniqueSuffix, "_")

	// Create unique display name
	displayName := fmt.Sprintf("go_sample_etd_custom_module_%s", uniqueSuffix)

	// Define the metadata and other config parameters as a map
	configMap := map[string]interface{}{
		"metadata": map[string]interface{}{
			"severity": "MEDIUM",
			//Replace with the desired description.
			"description":    "Sample custom module for testing purpose. Please do not delete.",
			"recommendation": "na",
		},
		"ips": []interface{}{"0.0.0.0"},
	}

	// Convert the map to a Struct
	configStruct, err := structpb.NewStruct(configMap)
	if err != nil {
		return fmt.Errorf("structpb.NewStruct: %w", err)
	}

	// Define the Event Threat Detection custom module configuration
	customModule := &securitycentermanagementpb.EventThreatDetectionCustomModule{
		Config: configStruct,
		//Replace with desired Display Name.
		DisplayName:     displayName,
		EnablementState: securitycentermanagementpb.EventThreatDetectionCustomModule_ENABLED,
		Type:            "CONFIGURABLE_BAD_IP",
	}

	req := &securitycentermanagementpb.CreateEventThreatDetectionCustomModuleRequest{
		Parent:                           parent,
		EventThreatDetectionCustomModule: customModule,
	}

	module, err := client.CreateEventThreatDetectionCustomModule(ctx, req)
	if err != nil {
		return fmt.Errorf("failed to create EventThreatDetectionCustomModule: %w", err)
	}

	fmt.Fprintf(w, "Created EventThreatDetectionCustomModule: %s\n", module.Name)
	return nil
}

Java

To authenticate to Security Command Center, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

import com.google.cloud.securitycentermanagement.v1.CreateEventThreatDetectionCustomModuleRequest;
import com.google.cloud.securitycentermanagement.v1.EventThreatDetectionCustomModule;
import com.google.cloud.securitycentermanagement.v1.EventThreatDetectionCustomModule.EnablementState;
import com.google.cloud.securitycentermanagement.v1.SecurityCenterManagementClient;
import com.google.protobuf.ListValue;
import com.google.protobuf.Struct;
import com.google.protobuf.Value;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class CreateEventThreatDetectionCustomModule {

  public static void main(String[] args) throws IOException {
    // https://cloud.google.com/security-command-center/docs/reference/security-center-management/rest/v1/organizations.locations.eventThreatDetectionCustomModules/create
    // TODO: Developer should replace project_id with a real project ID before running this code
    String projectId = "project_id";

    String customModuleDisplayName = "custom_module_display_name";

    createEventThreatDetectionCustomModule(projectId, customModuleDisplayName);
  }

  public static EventThreatDetectionCustomModule createEventThreatDetectionCustomModule(
      String projectId, String customModuleDisplayName) throws IOException {

    // Initialize client that will be used to send requests. This client only needs
    // to be created
    // once, and can be reused for multiple requests.
    try (SecurityCenterManagementClient client = SecurityCenterManagementClient.create()) {

      String parent = String.format("projects/%s/locations/global", projectId);

      // define the metadata and other config parameters severity, description,
      // recommendation and ips below
      Map<String, Value> metadata = new HashMap<>();
      metadata.put("severity", Value.newBuilder().setStringValue("MEDIUM").build());
      metadata.put(
          "description", Value.newBuilder().setStringValue("add your description here").build());
      metadata.put(
          "recommendation",
          Value.newBuilder().setStringValue("add your recommendation here").build());
      List<Value> ips = Arrays.asList(Value.newBuilder().setStringValue("0.0.0.0").build());

      Value metadataVal =
          Value.newBuilder()
              .setStructValue(Struct.newBuilder().putAllFields(metadata).build())
              .build();
      Value ipsValue =
          Value.newBuilder().setListValue(ListValue.newBuilder().addAllValues(ips).build()).build();

      Struct configStruct =
          Struct.newBuilder().putFields("metadata", metadataVal).putFields("ips", ipsValue).build();

      // define the Event Threat Detection custom module configuration, update the EnablementState
      // below
      EventThreatDetectionCustomModule eventThreatDetectionCustomModule =
          EventThreatDetectionCustomModule.newBuilder()
              .setConfig(configStruct)
              .setDisplayName(customModuleDisplayName)
              .setEnablementState(EnablementState.ENABLED)
              .setType("CONFIGURABLE_BAD_IP")
              .build();

      CreateEventThreatDetectionCustomModuleRequest request =
          CreateEventThreatDetectionCustomModuleRequest.newBuilder()
              .setParent(parent)
              .setEventThreatDetectionCustomModule(eventThreatDetectionCustomModule)
              .build();

      EventThreatDetectionCustomModule response =
          client.createEventThreatDetectionCustomModule(request);

      return response;
    }
  }
}

Node.js

To authenticate to Security Command Center, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

// Imports the Google cloud client library.
const {SecurityCenterManagementClient} =
  require('@google-cloud/securitycentermanagement').v1;

// Create a Security Center Management client
const client = new SecurityCenterManagementClient();

/**
 *  Required. The name of the parent resource of the create event threat detection module. Its
 *  format is "organizations/[organization_id]/locations/[location_id]",
 *  "folders/[folder_id]/locations/[location_id]", or
 *  "projects/[project_id]/locations/[location_id]".
 */
//TODO(developer): Update the following references for your own environment before running the sample.
// const organizationId = 'YOUR_ORGANIZATION_ID';
// const location = 'LOCATION_ID';
const parent = `organizations/${organizationId}/locations/${location}`;

// define the event threat detection custom module configuration, update the EnablementState
// below
const eventThreatDetectionCustomModule = {
  displayName: customModuleDisplayName,
  enablementState: 'ENABLED',
  type: 'CONFIGURABLE_BAD_IP',
  config: prepareConfigDetails(),
};

// Build the request.
const createEventThreatDetectionCustomModuleRequest = {
  parent: parent,
  eventThreatDetectionCustomModule: eventThreatDetectionCustomModule,
};

async function createEventThreatDetectionCustomModule() {
  // Call the API.
  const [response] = await client.createEventThreatDetectionCustomModule(
    createEventThreatDetectionCustomModuleRequest
  );
  console.log('EventThreatDetectionCustomModule created : %j', response);
}

function prepareConfigDetails() {
  // define the metadata and other config parameters severity, description,
  // recommendation and ips below
  const config = {
    fields: {
      metadata: {
        structValue: {
          fields: {
            severity: {stringValue: 'LOW'},
            description: {stringValue: 'Flagged by Cymbal as malicious'},
            recommendation: {
              stringValue: 'Contact the owner of the relevant project.',
            },
          },
        },
      },
      ips: {
        listValue: {
          values: [{stringValue: '192.0.2.1'}, {stringValue: '192.0.2.0/24'}],
        },
      },
    },
  };
  return config;
}

createEventThreatDetectionCustomModule();

What's next

To search and filter code samples for other Google Cloud products, see the Google Cloud sample browser.