

本文為英文版的機器翻譯版本，如內容有任何歧義或不一致之處，概以英文版為準。

# 使用 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*

## 總結
<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 函數或使用policy-as-code[AWS CloudFormation Guard](https://github.com/aws-cloudformation/cloudformation-guard)(GitHub) 建立自訂規則。

使用 Guard 建立的規則提供比受管規則更精細的控制，而且通常比完全自訂的 Lambda 規則更容易設定。此方法可讓工程師和架構師能夠建置規則，而不需要知道 Python、NodeJS 或 Java，而這些都是透過 Lambda 部署自訂規則的必要項目。

此模式提供可行的範本、程式碼範例和部署方法，協助您使用 Guard 來採用自訂規則。透過使用此模式，管理員可以使用 AWS Config 來建置具有[組態項目](https://docs.aws.amazon.com/config/latest/developerguide/config-concepts.html#config-items)屬性的自訂合規規則。例如，開發人員可以針對 AWS Config 組態項目使用 Guard 政策，以持續監控已部署 AWS 和非AWS 資源的狀態、偵測規則違規，並自動啟動修復。

**目標**

讀取此模式後，您應該能夠：
+ 了解 Guard 政策程式碼如何與服務互動 AWS Config 。
+ 部署*案例 1*，這是使用 Guard 語法來驗證加密磁碟區合規性的 AWS Config 自訂規則。此規則會驗證磁碟機正在使用中，並驗證磁碟機類型為 [gp3](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/general-purpose.html#gp3-ebs-volume-type)。
+ 部署*案例 2*，這是使用 Guard 語法來驗證 Amazon GuardDuty 合規性的 AWS Config 自訂規則。此規則會驗證 GuardDuty 記錄器是否已啟用 [Amazon Simple Storage Service (Amazon S3) 保護](https://docs.aws.amazon.com/guardduty/latest/ug/s3-protection.html)和 [Amazon Elastic Kubernetes Service (Amazon EKS) 保護](https://docs.aws.amazon.com/guardduty/latest/ug/kubernetes-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 記錄中的鍵值對

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

您可以將 Guard 語法套用到 AWS Config 規則做為自訂 policy. AWS Config captures 每個指定資源的階層式 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 部署使用 Guard 語法來驗證加密磁碟區合規性的 AWS Config 自訂規則。此規則會驗證磁碟機正在使用中，並驗證磁碟機類型為 gp3。

以下是案例 1 的 AWS Config 組態項目範例。此組態項目中有三個鍵值對，用作 Guard 政策中的變數：`volumeencryptionstatus`、 `volumestatus`和 `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`命令定義變數。  系統會為他們指派衍生自組態項目屬性的名稱和值。
+ 當條件相依性尋找符合 的`resourceType`鍵值對時，`compliancecheck`規則區塊會新增 `AWS::EC2::Volume`。如果找到相符項目，則規則會繼續進行其餘 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 自訂政策，請參閱 GitHub 程式碼儲存庫中的 [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)。如需在 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 部署使用 Guard 語法來驗證 Amazon GuardDuty 合規性的 AWS Config 自訂規則。此規則會驗證 GuardDuty 記錄器是否已啟用 Amazon S3 保護和 Amazon EKS 保護。它也會驗證每 15 分鐘發佈一次 GuardDuty 調查結果。此案例可以部署到組織 (in AWS Organizations) AWS 區域 中的所有 AWS 帳戶 和 。

以下是案例 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`命令定義變數。  系統會為他們指派衍生自組態項目屬性的名稱和值。
+ 當條件相依性尋找符合 的`resourceType`鍵值對時，`compliancecheck`規則區塊會新增 `AWS::GuardDuty::Detector`。如果找到相符項目，則規則會繼續進行其餘的 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) 工具，可協助您使用程式碼來佈建和管理雲端基礎設施和資源。

**程式碼儲存庫**

此模式的程式碼可在 [AWS Config GitHub AWS CloudFormation Guard](https://github.com/aws-samples/aws-config-custom-rule-cloudformation-guard/tree/main) GitHub 搭配儲存庫中使用。此程式碼儲存庫包含此模式所述的兩種案例的範例。

## 史詩
<a name="create-aws-config-custom-rules-by-using-aws-cloudformation-guard-policies-epics"></a>

### 建立 AWS Config 自訂規則
<a name="creating-cc-custom-rules"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| （選用） 選取規則的鍵/值對。 | 如果您要定義自訂 Guard 政策，請完成以下步驟。如果您針對案例 1 或 2 使用其中一個範例政策，請略過這些步驟。[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/create-aws-config-custom-rules-by-using-aws-cloudformation-guard-policies.html) | AWS 管理員、安全工程師 | 
| 建立自訂規則。 | 使用您先前識別的鍵/值對，或使用其中一個提供的範例 Guard 政策，遵循[建立 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_tw/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>


| 問題 | 解決方案 | 
| --- | --- | 
| 在 外部測試 Guard 政策 AWS Config | 單元測試可以在本機裝置或整合開發環境 (IDE) 中完成，例如 AWS Cloud9 IDE。若要執行單位測試，請執行下列動作：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/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)(Guard 文件）

**AWS 部落格文章和研討會**
+ [Introducing 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)