使用AWS re:Post即您表示您同意 AWS re:Post 使用条款

如何使用带有 Amazon SNS 主题的 EventBridge 为 Security Hub 检测结果设置自定义电子邮件通知?

7 分钟阅读
0

我想要使用 Amazon EventBridge 和 Amazon Simple Notification Service(Amazon SNS)主题为 Security Hub 检测结果设置自定义电子邮件通知。

简短描述

以下解决方案向您展示了如何使用 SNS 配置 EventBridge 以接收 Security Hub 通知。根据该 EventBridge 规则,Amazon SNS 会在您的事件发生时发送通知到电子邮件地址或订阅主题的地址。由于它的格式设置,生成的消息难以被读取。但是,系统将添加 AWS Lambda 函数,该函数会创建具有改进格式的自定义警报消息,然后再将警报消息发送给 SNS 订阅者。

要创建自定义电子邮件通知,请执行以下操作:

1.    创建以下 EventBridge 规则目标:
SNS 主题和电子邮件订阅。
Lambda 函数。

2.    创建 EventBridge 规则。

3.    接收自定义通知。

**重要提示:**以下解决方法使用 AWS Security Hub 事件和 Lambda 函数进行自定义。如需了解关于成本的更多信息,见 AWS Security Hub 定价AWS Lambda 定价

解决方案

创建 SNS 主题和订阅

1.    打开 Amazon SNS 控制台

2.    在导航窗格中,选择 Topics(主题)。

3.    选择创建主题

4.    在 Details(详细信息)部分,为 Type(类型)选择 Standard(标准)。

5.    对于 Name(名称),输入主题的名称。

6.    选择创建主题

7.    在创建的主题中,选择 Create subscription(创建订阅)。

8.    对于 Topic ARN(主题 ARN),选择您之前所创建主题的 Amazon Resource Name(ARN)(如果未自动填充)。

9.    对于 Protocol(协议),输入 Email(电子邮件)。

10.    对于 Endpoint(端点),输入您希望接收 SNS 通知的电子邮件地址。

11.    选择 Create subscription(创建订阅)。

**重要提示:**您必须在发送给订阅者的确认电子邮件中确认订阅,以便订阅的状态从 PendingConfirmation(待确认)切换到 Confirmed(已确认)。

注意:(可选)您还可以创建基于身份验证的订阅,防止对您的主题进行取消订阅操作。

创建 Lambda 函数

创建 Lambda 函数,以便从 JSON 内容提取您想要的信息,并将自定义消息发布到 Amazon SNS。

1.    打开 Lambda 控制台

2.    在导航窗格中,选择 Functions(函数)。

3.    选择 Create function(创建函数)。

4.    选择 Author from scratch(从头开始创建)。

5.    对于 Function name(函数名称),输入函数的名称。

6.    选择 Runtime(运行时),然后选择 Python 3.9

7.    对于 Architecture(架构),请选择 x86_64

8.    展开 Change default execution role(更改默认的执行角色)。

9.    对于 Execution role(执行角色),选择 Create a new role from AWS policy templates(从 AWS 策略模板创建新的角色)。

10.    对于角色名称,请为角色输入一个名称。

11.    对于 Policy template(策略模板),选择 Amazon SNS publish policy(Amazon SNS 发布策略)。

12.    选择 Create function(创建函数)。

13.    创建函数后,在 Code source(代码源)部分粘贴以下代码。 

import json
import boto3

sns = boto3.client('sns')

def lambda_handler(event, context):
    
    #Extract details from JSON event
    detailType= event["detail-type"]
    region = event["region"]
    accountId = event["account"] 
    
    #Security Hub Insight Results
    if (detailType == "Security Hub Insight Results"):
        
        action = event["detail"]["actionDescription"]
        
        message = "Alert: %s in %s for account: %s\n Action description: %s" % (detailType, region,accountId,action)
    
    elif  ("Security Hub Findings" in detailType):
        
        finding = event["detail"]["findings"][0] 
        findingTime = finding["FirstObservedAt"]
        findingType = finding["Types"][0]
        findingDescription = finding["Description"]
        remediation = finding["Remediation"]["Recommendation"]["Text"]
        
        #Security Hub Findings - Custom finding
        if(detailType == "Security Hub Findings - Custom"):
            complianceStatus = finding["Compliance"]["Status"]
            severity = finding["Severity"]["Label"]
            remediationUrl = finding["Remediation"]["Recommendation"]["Url"]
            
            message = "Alert: %s in %s for account: %s\n\nFinding regarding: [%s] %s\n Severity: %s\nDescription: %s\nFirst observed at: %s\n%s: %s" % (detailType, region, accountId, complianceStatus, findingType, 
            severity, findingDescription, findingTime, remediation, remediationUrl)
        
        #Security Hub Findings - Imported finding
        else:
            message = "Alert: %s in %s for account: %s\n\nFinding regarding: %s\nFirst observed at: %s\nRemediation recommendation: %s" % (detailType, region, accountId, findingDescription,findingTime, remediation)
    
    #AWS API Call via CloudTrail finding
    elif (detailType == "AWS API Call via CloudTrail"):
        
        time = event["detail"]["eventTime"]
        eventName = event["detail"]["eventName"]
        requestParameters = event["detail"]["requestParameters"]
        
        message = "Alert: %s in %s for account: %s at time: %s\n\n Event: %s \n Request parameters: %s" % (detailType, region, accountId, time, eventName, requestParameters)
        
        
    #If the event doesn't match any of the above, return the event    
    else:
        message = str(event)
    
    response = sns.publish(
            TopicArn = "arn:aws:sns:eu-west-x:xxxxxxxxxxxx:test",
            Message = message
            )
    
    return {
      'statusCode': 200,
      'body': json.dumps('Success!')
}

注意:上述代码会对所有 Security Hub 警报消息进行自定义和重新格式化。使用您的主题 ARN 替换 TopicArn("arn:aws:sns:REGION:ACCOUNT_ID:SecurityHubFindings")。将 eu-west-x:xxxxxxxxxxxx 替换为您的账户 ID。 

14.    要保存函数代码,选择 Deploy(部署)。

此函数接受默认的 Security Hub 事件,并将其重新格式化为更易读的格式。以下是示例消息:

示例 1:Security Hub 见解结果

默认值:

{"version": "0", "id": "ac844908-d14e-05b1-4b7b-836d85110e26", "detail-type": "Security Hub Insight Results", "source": "aws.securityhub", "account": "123456789012", "time": "2019-04-11T21:31:57Z", "region": "us-east-1", "resources": ["arn:aws:securityhub:us-east-1:123456789012:action/custom/slackMessaging"], "detail": {"actionName": "SendToSlack", "actionDescription": "Send Findings to Slack", "insightName": "5. AWS users with the most suspicious activity", "insightArn": "arn:aws:securityhub:::insight/securityhub/default/9", "resultType": "ResourceAwsIamAccessKeyUserName", "insightResults": [{"Admin": 7}, {"DenySlr_UI_User": 1}]}}

自定义:

Alert: Security Hub Insight Results in us-east-1 for account: 123456789012
Action description: Send Findings to Slack

示例 2:Security Hub 检测结果 – 自定义操作

默认值:

{ "version": "0", "id": "e215f5c7-a866-e0cd-6d11-fc7ecf97e381", "detail-type": "Security Hub Findings - Custom Action", "source": "aws.securityhub", "account": "123456789012", "time": "2019-04-11T22:06:13Z", "region": "us-east-1", "resources": ["arn:aws:securityhub:us-east-1:123456789012:action/custom/slackMessaging"], "detail": { "actionName": "SendToSlack", "actionDescription": "Send Findings to Slack", "findings": [{ "SchemaVersion": "2018-10-08", "Id": "arn:aws:securityhub:us-east-1:123456789012:subscription/cis-aws-foundations-benchmark/v/1.2.0/1.12/finding/17932c44-6d58-4b3c", "ProductArn": "arn:aws:securityhub:us-east-1::product/aws/securityhub", "GeneratorId": "arn:aws:securityhub:::ruleset/cis-aws-foundations-benchmark/v/1.2.0/rule/1.12", "AwsAccountId": "123456789012", "Types": ["Software and Configuration Checks/Industry and Regulatory Standards/CIS AWS Foundations Benchmark"], "FirstObservedAt": "2018-12-02T05:06:34.874Z", "LastObservedAt": "2019-04-11T18:07:10.995Z", "CreatedAt": "2018-12-02T05:06:34.874Z", "UpdatedAt": "2019-04-11T18:26:20.631Z", "Severity": { "Product": 0, "Normalized": 0 }, "Title": "1.12 Ensure no root account access key exists", "Description": "The root account is the most privileged user in an AWS account...", "Remediation": { "Recommendation": { "Text": "For directions on how to fix this issue, please consult the AWS Security Hub CIS documentation.", "Url": "https://docs.aws.amazon.com/securityhub/latest/userguide/securityhub-standards.html#securityhub-standards-checks-1.12" } }, "ProductFields": { "StandardsGuideArn": "arn:aws:securityhub:::ruleset/cis-aws-foundations-benchmark/v/1.2.0", "StandardsGuideSubscriptionArn": "arn:aws:securityhub:us-east-1:123456789012:subscription/cis-aws-foundations-benchmark/v/1.2.0", "RuleId": "1.12", "RecommendationUrl": "https://docs.aws.amazon.com/securityhub/latest/userguide/securityhub-standards.html#securityhub-standards-checks-1.12", "RecordState": "ACTIVE", "aws/securityhub/FindingId": "arn:aws:securityhub:us-east-1::product/aws/securityhub/arn:aws:securityhub:us-east-1:123456789012:subscription/cis-aws-foundations-benchmark/v/1.2.0/1.12/finding/17932c44-6d58-4b3c", "aws/securityhub/SeverityLabel": "INFORMATIONAL", "aws/securityhub/ProductName": "Security Hub", "aws/securityhub/CompanyName": "AWS" }, "Resources": [{ "Type": "AwsAccount", "Id": "AWS::::Account:123456789012", "Partition": "aws", "Region": "us-east-1" }], "Compliance": { "Status": "PASSED" }, "RecordState": "ACTIVE", "WorkflowState": "NEW" }, { "SchemaVersion": "2018-10-08", "Id": "arn:aws:securityhub:us-east-1:123456789012:subscription/cis-aws-foundations-benchmark/v/1.2.0/2.8/finding/5d6b42d8-122b-4cdf-8498-e045752e170c", "ProductArn": "arn:aws:securityhub:us-east-1::product/aws/securityhub", "GeneratorId": "arn:aws:securityhub:::ruleset/cis-aws-foundations-benchmark/v/1.2.0/rule/2.8", "AwsAccountId": "123456789012", "Types": ["Software and Configuration Checks/Industry and Regulatory Standards/CIS AWS Foundations Benchmark"], "FirstObservedAt": "2019-01-05T05:21:44.990Z", "LastObservedAt": "2019-04-11T18:26:12.510Z", "CreatedAt": "2019-01-05T05:21:44.990Z", "UpdatedAt": "2019-04-11T18:26:12.510Z", "Severity": { "Product": 0, "Normalized": 0 }, "Title": "2.8 Ensure rotation for customer created CMKs is enabled", "Description": "AWS Key Management Service (KMS) allows customers to rotate the backing key...", "Remediation": { "Recommendation": { "Text": "For directions on how to fix this issue, please consult the AWS Security Hub CIS documentation.", "Url": "https://docs.aws.amazon.com/securityhub/latest/userguide/securityhub-standards.html#securityhub-standards-checks-2.8" } }, "ProductFields": { "StandardsGuideArn": "arn:aws:securityhub:::ruleset/cis-aws-foundations-benchmark/v/1.2.0", "StandardsGuideSubscriptionArn": "arn:aws:securityhub:us-east-1:123456789012:subscription/cis-aws-foundations-benchmark/v/1.2.0", "RuleId": "2.8", "RecommendationUrl": "https://docs.aws.amazon.com/securityhub/latest/userguide/securityhub-standards.html#securityhub-standards-checks-2.8", "RecordState": "ACTIVE", "aws/securityhub/FindingId": "arn:aws:securityhub:us-east-1::product/aws/securityhub/arn:aws:securityhub:us-east-1:123456789012:subscription/cis-aws-foundations-benchmark/v/1.2.0/2.8/finding/5d6b42d8-122b-4cdf-8498-e045752e170c", "aws/securityhub/SeverityLabel": "INFORMATIONAL", "aws/securityhub/ProductName": "Security Hub", "aws/securityhub/CompanyName": "AWS" }, "Resources": [{ "Type": "AwsAccount", "Id": "AWS::::Account:123456789012", "Partition": "aws", "Region": "us-east-1" }], "Compliance": { "Status": "PASSED" }, "RecordState": "ACTIVE", "WorkflowState": "NEW" }] } }

自定义:

Alert: Security Hub Findings - Custom Action in us-east-1 for account: 123456789012

Finding regarding: The root account is the most privileged user in an AWS account...
First observed at: 2018-12-02T05:06:34.874Z
Remediation recommendation: For directions on how to fix this issue, please consult the AWS Security Hub CIS documentation.

示例 3:Security Hub 检测结果 – 已导入

默认值:

{ "version": "0", "id": "8e5622f9-d81c-4d81-612a-9319e7ee2506", "detail-type": "Security Hub Findings - Imported", "source": "aws.securityhub", "account": "123456789012", "time": "2019-04-11T21:52:17Z", "region": "us-west-2", "resources": ["arn:aws:securityhub:us-west-2::product/aws/macie/arn:aws:macie:us-west-2:123456789012:integtest/trigger/6294d71b927c41cbab915159a8f326a3/alert/f2893b211841"], "detail": { "findings": [{ "SchemaVersion": "2018-10-08", "Id": "arn:aws:macie:us-west-2:123456789012:integtest/trigger/6214d71b927c41cbab015159a8f316a3/alert/f2893b211841467198cc1201e9031ee4", "ProductArn": "arn:aws:securityhub:us-west-2::product/aws/macie", "GeneratorId": "arn:aws:macie:us-west-2:123456789012:integtest/trigger/6214d71b927c41cbab015159a8f316a3", "AwsAccountId": "123456789012", "Types": ["Sensitive Data Identifications/Passwords/Google Suite Two-factor backup codes in S3"], "FirstObservedAt": "2019-04-11T21:52:15.900Z", "LastObservedAt": "2019-04-11T21:52:15.900Z", "CreatedAt": "2019-04-11T21:52:15.900Z", "UpdatedAt": "2019-04-11T21:52:15.900Z", "Severity": { "Product": 6, "Normalized": 15 }, "Confidence": 5, "Title": "Google Suite Two-Factor Backup Codes uploaded to S3", "Description": "Google Suite two-factor backup codes uploaded to S3....", "Remediation": { "Recommendation": { "Text": "v2 Release" } }, "ProductFields": { "rule-arn": "arn:aws:macie:us-west-2:123456789012:trigger/6214d71b927c41cbab015159a8f316a3", "tags:0": "DATA_COMPLIANCE", "tags:1": "BASIC_ALERT", "themes:0/theme": "google_two_factor_backup", "themes:0/count": "1", "dlpRisk:0/risk": "8", "dlpRisk:0/count": "1", "owner:0/name": "vchin", "owner:0/count": "1", "aws/securityhub/FindingId": "arn:aws:securityhub:us-west-2::product/aws/macie/arn:aws:macie:us-west-2:123456789012:integtest/trigger/6214d71b927c41cbab015159a8f316a3/alert/f2893b211841467198cc1201e9031ee4", "aws/securityhub/SeverityLabel": "LOW", "aws/securityhub/ProductName": "Macie", "aws/securityhub/CompanyName": "Amazon" }, "Resources": [{ "Type": "AwsS3Bucket", "Id": "arn:aws:s3:::test-bucket-12", "Partition": "aws", "Region": "us-west-2" }], "RecordState": "ACTIVE", "WorkflowState": "NEW" }] } }

自定义:

Alert: Security Hub Findings - Imported in us-west-2 for account: 123456789012

Finding regarding: Google Suite two-factor backup codes uploaded to S3....
First observed at: 2019-04-11T21:52:15.900Z
Remediation recommendation: v2 Release

示例 4 – 通过 CloudTrail 的 AWS API 调用

默认值:

{"version": "0", "id": "b34c4525-95f0-8dd1-cd9e-9fc5be10039e", "detail-type": "AWS API Call via CloudTrail", "source": "aws.securityhub", "account": "123456789012", "time": "2021-12-10T10:47:54Z", "region": "eu-west-1", "resources": [], "detail": {"eventVersion": "1.08", "userIdentity": {"type": "AssumedRole", "principalId": "AROATGMYP4FKHTE5RKJC3", "arn": "arn:aws:sts::123456789012", "accountId": "123456789012", "accessKeyId": "ASIATGMYXXFKNHWOYQF7", "sessionContext": {"sessionIssuer": {"type": "Role", "principalId": "AROATGMYP4FKHX5RKJC3", "arn": "arn:aws:iam::123456789012:role/Admin", "accountId": "123456789012", "userName": "Admin"}, "webIdFederationData": {}, "attributes": {"creationDate": "2021-12-10T10:08:16Z", "mfaAuthenticated": "false"}}}, "eventTime": "2021-12-10T10:47:54Z", "eventSource": "securityhub.amazonaws.com", "eventName": "BatchUpdateFindings", "awsRegion": "eu-west-1", "sourceIPAddress": "54.240.197.20", "userAgent": "aws-internal/3 aws-sdk-java/1.12.112 Linux/5.4.156-94.273.amzn2int.x86_64 OpenJDK_64-Bit_Server_VM/25.312-b07 java/1.8.0_312 vendor/Oracle_Corporation cfg/retry-mode/standard", "requestParameters": {"Workflow": {"Status": "NEW"}, "FindingIdentifiers": [{"Id": "arn:aws:securityhub:eu-west-1:123456789012:subscription/cis-aws-foundations-benchmark/v/1.2.0/2.5/finding/2fd7f0dd-1088-44c5-bbe1-9c8a0ddce035", "ProductArn": "arn:aws:securityhub:eu-west-1::product/aws/securityhub"}]}, "responseElements": {"UnprocessedFindings": [], "ProcessedFindings": [{"Id": "arn:aws:securityhub:eu-west-1:123456789012:subscription/cis-aws-foundations-benchmark/v/1.2.0/2.5/finding/2fd7f0dd-1088-44c5-bbe1-9c8a0ddce035", "ProductArn": "arn:aws:securityhub:eu-west-1::product/aws/securityhub"}]}, "requestID": "fd52e76e-282f-47c7-a7bc-b9a1e1ca2cdd", "eventID": "433b8e9c-cf08-4909-adf7-ea0c548459ad", "readOnly": "False", "eventType": "AwsApiCall", "managementEvent": "True", "recipientAccountId": "123456789012", "eventCategory": "Management"}}

自定义:

Alert: AWS API Call via CloudTrail in eu-west-1 for account: 123456789012 at time: 2021-12-10T10:47:32Z

Event: BatchUpdateFindings
Request parameters: {'Workflow': {'Status': 'NOTIFIED'}, 'FindingIdentifiers': [{'Id': 'arn:aws:securityhub:eu-west-x:xxxxxxxxxxxx:subscription/cis-aws-foundations-benchmark/v/1.2.0/2.5/finding/2fd7f0dd-1088-44c5-bbe1-9c8a0ddce035', 'ProductArn': 'arn:aws:securityhub:eu-west-1::product/aws/securityhub'}]}

**注意:**您可以编辑每个 Security 检测结果类型的消息,使其更适合您的使用案例。

创建和配置 EventBridge 规则

1.    打开 EventBridge 控制台

2.    选择创建规则

3.    为规则输入名称。可选择输入描述

4.    在 Define pattern(定义模式)中,选择 Event pattern(事件模式)。

5.    对于 Event matching pattern(事件匹配模式),选择 Pre-defined pattern by service(按服务分类的预定义模式)。

6.    对于 Service provider(服务提供商),选择 AWS

7.    对于 Service name(服务名称),选择 Security hub

8.    对于 Event type(事件类型),选择 All Events(所有事件)。

**注意:**您还可以为特定事件配置警报,而不是为所有事件配置警报。Lambda 函数配置为将所有事件重新格式化为更易读的格式。

9.    在 Select event bus(选择事件总线)部分中,选择 AWS default event bus(AWS 默认事件总线)。

10.    在 Select targets(选择目标)中的 Target(目标)菜单中选择 Lambda target(Lambda 目标)。

11.    选择之前创建的 Lambda 函数。

接收自定义通知

当任何一个配置的事件发生时,您都会通过电子邮件收到来自 no-reply@sns.amazonaws.com 的自定义通知。


相关信息

如何配置 EventBridge 规则,以便在特定 AWS 服务事件类型触发时让 GuardDuty 发送自定义的 SNS 通知?

教程:使用输入转换器自定义 EventBridge 传递给事件目标的内容

为什么我的 EventBridge 规则未触发 Lambda 函数?

AWS 官方
AWS 官方已更新 3 年前