建立 Event Threat Detection 自訂模組的範例程式碼。
程式碼範例
Go
如要向 Security Command Center 進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。
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
如要向 Security Command Center 進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。
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
如要向 Security Command Center 進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。
// 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();
Python
如要向 Security Command Center 進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。
def create_event_threat_detection_custom_module(parent: str) -> securitycentermanagement_v1.EventThreatDetectionCustomModule:
"""
Creates a Event Threat Detection Custom Module.
This custom module creates a configurable bad IP type custom module, which can be used to detect and block malicious IP addresses.
Args:
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}
Returns:
EventThreatDetectionCustomModule
"""
client = securitycentermanagement_v1.SecurityCenterManagementClient()
try:
# Generate a unique suffix
unique_suffix = str(uuid.uuid4()).replace("-", "_")
# Create unique display name
display_name = f"python_sample_etd_custom_module_{unique_suffix}"
# Define the metadata and other config parameters as a dictionary
config_map = {
"metadata": {
"severity": "MEDIUM",
"description": "Sample custom module for testing purposes. Please do not delete.",
"recommendation": "na",
},
"ips": ["0.0.0.0"],
}
# Convert the dictionary to a Struct
config_struct = Struct()
config_struct.update(config_map)
# Define the Event Threat Detection custom module configuration
custom_module = securitycentermanagement_v1.EventThreatDetectionCustomModule(
config=config_struct,
display_name=display_name,
enablement_state=securitycentermanagement_v1.EventThreatDetectionCustomModule.EnablementState.ENABLED,
type_="CONFIGURABLE_BAD_IP",
)
# Create the request
request = securitycentermanagement_v1.CreateEventThreatDetectionCustomModuleRequest(
parent=parent,
event_threat_detection_custom_module=custom_module,
)
# Make the API call
response = client.create_event_threat_detection_custom_module(request=request)
print(f"Created EventThreatDetectionCustomModule: {response.name}")
return response
except GoogleAPICallError as e:
print(f"Failed to create EventThreatDetectionCustomModule: {e}")
raise
後續步驟
如要搜尋及篩選其他 Google Cloud 產品的程式碼範例,請參閱Google Cloud 範例瀏覽器。