

本文属于机器翻译版本。若本译文内容与英语原文存在差异，则一律以英文原文为准。

# 使用 AWS CloudFormation Guard 策略创建 AWS Config 自定义规则
<a name="create-aws-config-custom-rules-by-using-aws-cloudformation-guard-policies"></a>

*Andrew Lok、Nicole Brown、Kailash Havildar 和 Tanya Howell，Amazon Web Services*

## Summary
<a name="create-aws-config-custom-rules-by-using-aws-cloudformation-guard-policies-summary"></a>

[AWS Config](https://docs.aws.amazon.com/config/latest/developerguide/WhatIsConfig.html)规则可帮助您评估 AWS 资源及其目标配置状态。有两种类型的 AWS Config 规则：托管规则和自定义规则。您可以使用 AWS Lambda 函数或 [AWS CloudFormation Guard](https://github.com/aws-cloudformation/cloudformation-guard)(GitHub)（一种 policy-as-code语言）创建自定义规则。

使用 Guard 创建的规则比托管式规则提供更精细的控制，而且它们通常比完全自定义 Lambda 规则更易于配置。利用这种方法，工程师和架构师无需掌握 Python、NodeJS 或 Java 即可构建规则，因此这些都是通过 Lambda 部署自定义规则所必需的。

此模式提供了可行的模板、代码示例和部署方法，可帮助您通过 Guard 采用自定义规则。通过使用此模式，管理员可以使用 AWS Config 来构建具有[配置项目](https://docs.aws.amazon.com/config/latest/developerguide/config-concepts.html#config-items)属性的自定义合规性规则。例如，开发人员可以对 AWS Config 配置项目使用防护策略来持续监控已部署 AWS 和非AWS 资源的状态，检测违反规则的行为，并自动启动补救。

**目标**

阅读此模式后，您应该能够：
+ 了解 Guard 策略代码如何与 AWS Config 服务交互。
+ 部署*场景 1*，这是一项 AWS Config 自定义规则，它使用 Guard 语法来验证加密卷的合规性。此规则验证驱动器是否在使用中，并验证驱动器类型是否为 [gp3](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/general-purpose.html#gp3-ebs-volume-type)。
+ 部署*场景 2*，这是一个使用防护语法来验证 Amazon GuardDuty 合规性的 AWS Config 自定义规则。该规则验证 GuardDuty 录像机是否启用了[亚马逊简单存储服务 (Amazon S3) 保护和亚马逊[弹性 Kubernetes Service (Amazon EK](https://docs.aws.amazon.com/guardduty/latest/ug/kubernetes-protection.html) S) 保护](https://docs.aws.amazon.com/guardduty/latest/ug/s3-protection.html)。

## 先决条件和限制
<a name="create-aws-config-custom-rules-by-using-aws-cloudformation-guard-policies-prereqs"></a>

**先决条件**
+ 活跃的 AWS 账户
+ AWS Config，[在](https://docs.aws.amazon.com/config/latest/developerguide/getting-started.html)你的 AWS 账户

**限制**
+ Guard 自定义规则只能查询目标配置 JSON 记录中的键值对

## 架构
<a name="create-aws-config-custom-rules-by-using-aws-cloudformation-guard-policies-architecture"></a>

您可以将 Guard 语法作为自定义策略应用于 AWS Config 规则。 AWS Config 捕获每个指定资源的分层 JSON。 AWS Config 配置项的 JSON 包含键值对。这些属性在 Guard 语法中用作分配给其相应值的变量。 

以下是对 Guard 语法的解释。使用配置项 JSON 中的变量，并在前面加上 `%` 字符。

```
# declare variable
let <variable name> = <'value'>

# create rule and assign condition and policy
    rule <rule name> when 
        <CI json key> == <"CI json value"> {
            <top level CI json key>.<next level CI json key> == %<variable name>
        }
```

**场景 1：Amazon EBS 卷**

场景 1 部署了一个 AWS Config 自定义规则，该规则使用 Guard 语法来验证加密卷的合规性。此规则验证驱动器是否在使用中，并验证驱动器类型是否为 gp3。

以下是方案 1 的 AWS Config 配置项目示例。 此配置项中有三个键值对用作警卫策略中的变量：`volumestatus``volumeencryptionstatus`、和。`volumetype`此外，`resourceType` 密钥还可用作 Guard 策略中的筛选器。

```
{
  "version": "1.3",
  "accountId": "111111111111",
  "configurationItemCaptureTime": "2023-01-15T19:04:45.402Z",
  "configurationItemStatus": "ResourceDiscovered",
  "configurationStateId": "4444444444444",
  "configurationItemMD5Hash": "",
  "arn": "arn:aws:ec2:us-west-2:111111111111:volume/vol-222222222222",
  "resourceType": "AWS::EC2::Volume",
  "resourceId": "vol-222222222222",
  "awsRegion": "us-west-2",
  "availabilityZone": "us-west-2b",
  "resourceCreationTime": "2023-01-15T19:03:22.247Z",
  "tags": {},
  "relatedEvents": [],
  "relationships": [
    {
      "resourceType": "AWS::EC2::Instance",
      "resourceId": "i-33333333333333333",
      "relationshipName": "Is attached to Instance"
    }
  ],
  "configuration": {
    "attachments": [
      {
        "attachTime": "2023-01-15T19:03:22.000Z",
        "device": "/dev/xvda",
        "instanceId": "i-33333333333333333",
        "state": "attached",
        "volumeId": "vol-222222222222",
        "deleteOnTermination": true,
        "associatedResource": null,
        "instanceOwningService": null
      }
    ],
    "availabilityZone": "us-west-2b",
    "createTime": "2023-01-15T19:03:22.247Z",
    "encrypted": false,
    "kmsKeyId": null,
    "outpostArn": null,
    "size": 8,
    "snapshotId": "snap-55555555555555555",
    "state": "in-use",
    "volumeId": "vol-222222222222",
    "iops": 100,
    "tags": [],
    "volumeType": "gp2",
    "fastRestored": null,
    "multiAttachEnabled": false,
    "throughput": null,
    "sseType": null
  },
  "supplementaryConfiguration": {}
}
```

以下是使用 Guard 语法定义场景 1 中的变量和规则的示例。在以下示例中：
+ 前三行使用 `let` 命令定义变量。  它们获分配了一个源自配置项属的名称和值。
+ `compliancecheck` 规则块添加了一个 when 条件依赖关系，用于查找与 `AWS::EC2::Volume` 匹配的 `resourceType` 键值对。如果找到匹配项，则规则会继续执行其余的 JSON 属性，并根据以下三个条件查找匹配项：`state`、`encrypted` 和 `volumeType`。

```
let volumestatus = 'available'
let volumetype = 'gp3'
let volumeencryptionstatus = true

    rule compliancecheck when 
        resourceType == "AWS::EC2::Volume" {
            configuration.state == %volumestatus
            configuration.encrypted == %volumeencryptionstatus
            configuration.volumeType == %volumetype
        }
```

有关实现此自定义规则的完整 Guard 自定义策略，请参阅代码存储库中的 [awsconfig-guard-cft.yaml](https://github.com/aws-samples/aws-config-custom-rule-cloudformation-guard/blob/main/awsconfig-guard-cft.yaml) 或 [awsconfig-guard-tf-ec2vol.json。](https://github.com/aws-samples/aws-config-custom-rule-cloudformation-guard/blob/main/awsconfig-guard-tf-ec2vol.json) GitHub 有关在 Guard 中部署此自定义策略的 HashiCorp Terraform 代码，请参阅代码存储库中的 [awsconfig-guard-tf-example.json。](https://github.com/aws-samples/aws-config-custom-rule-cloudformation-guard/blob/main/awsconfig-guard-tf-example.json)

**场景 2： GuardDuty 合规性**

方案 2 部署了使用防护语法来验证 Amazon GuardDuty 合规性的 AWS Config 自定义规则。此规则验证 GuardDuty 录像机是否启用了 Amazon S3 保护和 Amazon EKS 保护。它还会验证每隔 15 分钟发布一次 GuardDuty 调查结果。此场景可以部署在所有 AWS 账户 组织和组织 AWS 区域 中（中 AWS Organizations）。

以下是方案 2 的 AWS Config 配置项目示例。此配置项中有三个键值对用作 Guard 策略中的变量：`FindingPublishingFrequency`、`S3Logs` 和 `Kubernetes`。此外，`resourceType` 密钥还可用作策略中的筛选器。

```
{
  "version": "1.3",
  "accountId": "111111111111",
  "configurationItemCaptureTime": "2023-11-27T13:34:28.888Z",
  "configurationItemStatus": "OK",
  "configurationStateId": "7777777777777",
  "configurationItemMD5Hash": "",
  "arn": "arn:aws:guardduty:us-west-2:111111111111:detector/66666666666666666666666666666666",
  "resourceType": "AWS::GuardDuty::Detector",
  "resourceId": "66666666666666666666666666666666",
  "resourceName": "66666666666666666666666666666666",
  "awsRegion": "us-west-2",
  "availabilityZone": "Regional",
  "resourceCreationTime": "2020-02-17T02:48:04.511Z",
  "tags": {},
  "relatedEvents": [],
  "relationships": [],
  "configuration": {
    "Enable": true,
    "FindingPublishingFrequency": "FIFTEEN_MINUTES",
    "DataSources": {
      "S3Logs": {
        "Enable": true
      },
      "Kubernetes": {
        "AuditLogs": {
          "Enable": true
        }
      }
    },
    
    "Id": "66666666666666666666666666666666",
    "Tags": []
  },
  "supplementaryConfiguration": {
    "CreatedAt": "2020-02-17T02:48:04.511Z"
  }
}
```

以下是使用 Guard 语法定义场景 2 中的变量和规则的示例。在以下示例中：
+ 前三行使用 `let` 命令定义变量。  它们获分配了一个源自配置项属的名称和值。
+ `compliancecheck` 规则块添加了一个 when 条件依赖关系，用于查找与 `AWS::GuardDuty::Detector` 匹配的 `resourceType` 键值对。如果找到匹配项，则规则会继续执行其余的 JSON 属性，并根据以下三个条件查找匹配项：`S3Logs.Enable`、`Kubernetes.AuditLogs.Enable` 和 `FindingPublishingFrequency`。

```
let s3protection = true
let kubernetesprotection = true
let publishfrequency = 'FIFTEEN_MINUTES'

    rule compliancecheck when 
        resourceType == "AWS::GuardDuty::Detector" {
            configuration.DataSources.S3Logs.Enable == %s3protection
            configuration.DataSources.Kubernetes.AuditLogs.Enable == %kubernetesprotection
            configuration.FindingPublishingFrequency == %publishfrequency
        }
```

有关实现此自定义规则的完整 Guard 自定义策略，请参阅 GitHub 代码库中的 [awsconfig-guard-cft-gd.yaml](https://github.com/aws-samples/aws-config-custom-rule-cloudformation-guard/blob/main/awsconfig-guard-cft-gd.yaml)。有关在 Guard 中部署此自定义策略的 HashiCorp Terraform 代码，请参阅代码存储库中的 [awsconfig-guard-tf-gd.json。](https://github.com/aws-samples/aws-config-custom-rule-cloudformation-guard/blob/main/awsconfig-guard-tf-gd.json)

## 工具
<a name="create-aws-config-custom-rules-by-using-aws-cloudformation-guard-policies-tools"></a>

**AWS 服务**
+ [AWS CloudFormation](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/Welcome.html)帮助您设置 AWS 资源，快速一致地配置资源，并在资源的整个生命周期中跨地区对其 AWS 账户 进行管理。
+ [AWS Config](https://docs.aws.amazon.com/config/latest/developerguide/WhatIsConfig.html)提供了您的资源 AWS 账户 及其配置方式的详细视图。它可以帮助您确定资源之间的相互关系，以及它们的配置如何随时间变化。

**其他工具**
+ [HashiCorp Terraform](https://www.terraform.io/docs) 是一款基础设施即代码（IaC）工具，可帮助您使用代码来预调配和管理云基础设施和资源。

**代码存储库**

[此模式的代码可在 with AWS CloudFormation Guard存储库中 GitHub AWS Config 找到。](https://github.com/aws-samples/aws-config-custom-rule-cloudformation-guard/tree/main)此代码存储库包含此模式中描述的两种场景的示例。

## 操作说明
<a name="create-aws-config-custom-rules-by-using-aws-cloudformation-guard-policies-epics"></a>

### 创建 AWS Config 自定义规则
<a name="creating-cc-custom-rules"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| （可选）为规则选择键值对。 | 如果您要定义自定义 Guard 策略，请完成以下步骤。如果您使用方案 1 或 2 的任一示例，请跳过以下步骤。[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/create-aws-config-custom-rules-by-using-aws-cloudformation-guard-policies.html) | AWS 管理员、安全工程师 | 
| 创建自定义规则。 | 使用您之前确定的键值对或使用提供的示例警卫策略之一，按照[创建 AWS Config 自定义策略规则中的说明创建自定义规则](https://docs.aws.amazon.com/config/latest/developerguide/evaluate-config_develop-rules_cfn-guard.html#create-cfn-guard-rule-console)。 | AWS 管理员、安全工程师 | 
| 验证自定义规则。 | 执行以下任一操作以验证自定义 Guard 规则：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/create-aws-config-custom-rules-by-using-aws-cloudformation-guard-policies.html) | AWS 管理员、安全工程师 | 

## 问题排查
<a name="create-aws-config-custom-rules-by-using-aws-cloudformation-guard-policies-troubleshooting"></a>


| 问题 | 解决方案 | 
| --- | --- | 
| 在外部测试警卫策略 AWS Config | 单元测试可以在本地设备上完成，也可以在集成开发环境 (IDE)（例如 AWS Cloud9 IDE）中完成。要执行单元测试，请执行以下步骤：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/create-aws-config-custom-rules-by-using-aws-cloudformation-guard-policies.html) | 
| 调试 AWS Config 自定义规则 | 在您的 Guard 策略中，将 `EnableDebugLogDelivery` 值更改为 `true`。默认值为 `false`。日志消息存储在 Amazon 中 CloudWatch。 | 

## 相关资源
<a name="create-aws-config-custom-rules-by-using-aws-cloudformation-guard-policies-resources"></a>

**AWS 文档**
+ [创建 AWS Config 自定义策略规则](https://docs.aws.amazon.com/config/latest/developerguide/evaluate-config_develop-rules_cfn-guard.html)（AWS Config 文档）
+ [编写 AWS CloudFormation Guard 规则](https://docs.aws.amazon.com/cfn-guard/latest/ug/writing-rules.html)（警卫文档）

**AWS 博客文章和研讨会**
+ [AWS CloudFormation Guard 2.0 简介](https://aws.amazon.com/blogs/mt/introducing-aws-cloudformation-guard-2-0/)（AWS 博客文章）

**其他资源**
+ [AWS CloudFormation Guard](https://github.com/aws-cloudformation/cloudformation-guard) (GitHub)
+ [AWS CloudFormation Guard CLI 文档](https://github.com/aws-cloudformation/cloudformation-guard#guard-cli) (GitHub)