

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

# 使用以下方法为公共子网部署基于侦探属性的访问控制 AWS Config
<a name="deploy-detective-attribute-based-access-controls-for-public-subnets-by-using-aws-config"></a>

*Alberto Menendez，Amazon Web Services*

## Summary
<a name="deploy-detective-attribute-based-access-controls-for-public-subnets-by-using-aws-config-summary"></a>

分布式边缘网络架构依赖于与其虚拟私有云中的工作负载一起运行的网络边缘安全（VPCs）。与更常见的集中式方法相比，此方法的可扩展性无可比拟。尽管在工作负载账户中部署公有子网可以带来好处，但它也会带来新的安全风险，因为它增加了攻击面。我们建议您仅在这些资源的公有子网中部署 Elastic Load Balancing 资源，例如应用程序负载均衡器或 NAT 网关。 VPCs在专用公有子网中使用负载均衡器和 NAT 网关有助于实现对入站和出站流量的精细控制。

我们建议您同时实施预防性控件和检测性控件，以限制可在公有子网中部署的资源类型。有关使用基于属性的访问权限控制（ABAC）为公有子网部署预防性控件的更多信息，请参阅[为公有子网部署预防性的基于属性的访问权限控制](https://docs.aws.amazon.com/prescriptive-guidance/latest/patterns/deploy-preventative-attribute-based-access-controls-for-public-subnets.html)。尽管这些预防性控件对大多数情况都有效，但可能无法处理所有可能的使用案例。因此，此模式以 ABAC 方法为基础，可帮助您配置提醒，就部署在公有子网中的不合规资源发出提醒。该解决方案检查弹性网络接口是否属于公有子网中不允许使用的资源。

为此，此模式使用 [AWS Config 自定义规则](https://docs.aws.amazon.com/config/latest/developerguide/evaluate-config_develop-rules.html)和 [ABAC](https://aws.amazon.com/identity/attribute-based-access-control/)。无论何时创建或修改弹性网络接口的配置，自定义规则都会对其进行处理。简而言之，此规则会执行两个操作，以来确定网络接口是否合规：

1. 为了确定网络接口是否在规则范围内，此规则会检查子网是否具有可表明其为公有子网的特定 [AWS 标签](https://docs.aws.amazon.com/tag-editor/latest/userguide/tagging.html)。例如，此标签可能是 `IsPublicFacing=True`。

1. 如果网络接口部署在公有子网中，则该规则将检查 AWS 服务 创建此资源的原因。如果此资源不是弹性负载均衡资源或 NAT 网关，则它会将此资源标记为不合规。

## 先决条件和限制
<a name="deploy-detective-attribute-based-access-controls-for-public-subnets-by-using-aws-config-prereqs"></a>

**先决条件**
+ 活跃的 AWS 账户
+ AWS Config，在工作负载账户中[设置](https://docs.aws.amazon.com/config/latest/developerguide/gs-console.html)
+ 在工作负载账户中部署所需资源的权限
+ 具有公有子网的 VPC
+ 正确应用标签以识别目标公有子网
+ （可选）中的组织 AWS Organizations
+ （可选）中央安全账户，它是 AWS Config 和的委派管理员 AWS Security Hub CSPM

## 架构
<a name="deploy-detective-attribute-based-access-controls-for-public-subnets-by-using-aws-config-architecture"></a>

**目标架构**

![\[使用 AWS Config 自定义规则，检测公有子网中的不合规资源\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/85d54ead-7f00-4381-89fb-cffe307c4cfc/images/a8c19913-d260-4b70-96ba-732bb1b9881f.png)


下图说明了以下内容：

1. 部署或修改 elastic network interface 资源 (`AWS::EC2::NetworkInterface`) 时，会 AWS Config 捕获事件和配置。

1. AWS Config 将此事件与用于评估配置的自定义规则进行匹配。

1. 调用与此自定义规则关联的 AWS Lambda 函数。该函数评估资源并应用指定的逻辑，进而确定资源配置是 `COMPLIANT`、`NON_COMPLIANT` 还是 `NOT_APPLICABLE`。

1. 如果确定资源为，则通过亚马逊简单通知服务 (Amazon SNS) Simple Notification Service AWS Config 发送提醒。`NON_COMPLIANT`    
[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/deploy-detective-attribute-based-access-controls-for-public-subnets-by-using-aws-config.html)

**Lambda 函数评估逻辑**

下图显示了 Lambda 函数用于评估弹性网络接口的合规性的逻辑。

![\[Lambda 函数逻辑示意图\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/85d54ead-7f00-4381-89fb-cffe307c4cfc/images/9575e20f-142b-4eba-b34d-3b9bda163144.png)


**自动化和扩展**

此模式是一种检测性解决方案。您还可以使用修复规则对其进行补充，以自动解决任何不合规的资源。有关更多信息，请参阅使用规则[修复不合规的 AWS Config 资源](https://docs.aws.amazon.com/config/latest/developerguide/remediation.html)。

您可以通过以下方式扩展此解决方案：
+ 强制应用您为识别面向公众的子网而建立的相应 AWS 标签。有关更多信息，请参阅 AWS Organizations 文档中的[标签策略](https://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_policies_tag-policies.html)。
+ 配置一个中央安全帐户，将 AWS Config 自定义规则应用于组织中的每个工作负载帐户。有关更多信息，请参阅 AWS（AWS 博客文章）[中的大规模自动配置合规性](https://aws.amazon.com/blogs/mt/automate-configuration-compliance-at-scale-in-aws/)。
+  AWS Config 与集成 AWS Security Hub CSPM ，以便大规模捕获、集中和通知。有关更多信息，请参阅 AWS Security Hub CSPM 文档 AWS Config中的[配置](https://docs.aws.amazon.com/securityhub/latest/userguide/securityhub-prereq-config.html)。

## 工具
<a name="deploy-detective-attribute-based-access-controls-for-public-subnets-by-using-aws-config-tools"></a>
+ [AWS Config](https://docs.aws.amazon.com/config/latest/developerguide/WhatIsConfig.html)提供了您的资源 AWS 账户 及其配置方式的详细视图。它可以帮助您确定资源之间的相互关系，以及它们的配置如何随时间变化。
+ [弹性负载均衡](https://docs.aws.amazon.com/elasticloadbalancing/latest/userguide/what-is-load-balancing.html)在多个目标上分配传入的应用程序或网络流量。例如，您可以跨亚马逊弹性计算云 (Amazon EC2) 实例、容器以及一个或多个可用区中的 IP 地址分配流量。
+ [AWS Lambda](https://docs.aws.amazon.com/lambda/latest/dg/welcome.html) 是一项计算服务，可帮助您运行代码，无需预调配或管理服务器。它只在需要时运行您的代码，并自动进行扩展，因此您只需为使用的计算时间付费。
+ [Amazon Simple Notiﬁcation Service (Amazon SNS)](https://docs.aws.amazon.com/sns/latest/dg/welcome.html) 可帮助您协调和管理发布者与客户端（包括 Web 服务器和电子邮件地址）之间的消息交换。 
+ [Amazon Virtual Private Cloud（亚马逊 VPC）](https://docs.aws.amazon.com/vpc/latest/userguide/what-is-amazon-vpc.html)可帮助您将 AWS 资源启动到您定义的虚拟网络中。该虚拟网络类似于您在数据中心中运行的传统网络，并具有使用 AWS的可扩展基础设施的优势。

## 最佳实践
<a name="deploy-detective-attribute-based-access-controls-for-public-subnets-by-using-aws-config-best-practices"></a>

有关开发自定义 AWS Config 规则的更多示例和最佳实践，请参阅上的官方[AWS Config 规则存储库](https://github.com/awslabs/aws-config-rules) GitHub。

## 操作说明
<a name="deploy-detective-attribute-based-access-controls-for-public-subnets-by-using-aws-config-epics"></a>

### 部署解决方案
<a name="deploy-the-solution"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 创建 Lambda 函数。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/deploy-detective-attribute-based-access-controls-for-public-subnets-by-using-aws-config.html) | 常规 AWS | 
| 为 Lambda 函数的执行角色添加这些权限。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/deploy-detective-attribute-based-access-controls-for-public-subnets-by-using-aws-config.html) | 常规 AWS | 
| 检索 Lambda 函数 Amazon 资源名称（ARN）。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/deploy-detective-attribute-based-access-controls-for-public-subnets-by-using-aws-config.html) | 常规 AWS | 
| 创建 AWS Config 自定义规则。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/deploy-detective-attribute-based-access-controls-for-public-subnets-by-using-aws-config.html) | 常规 AWS | 
| 配置通知。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/deploy-detective-attribute-based-access-controls-for-public-subnets-by-using-aws-config.html) | 常规 AWS | 

### 测试解决方案
<a name="test-the-solution"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 创建合规资源。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/deploy-detective-attribute-based-access-controls-for-public-subnets-by-using-aws-config.html) | 常规 AWS | 
| 创建不合规资源。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/deploy-detective-attribute-based-access-controls-for-public-subnets-by-using-aws-config.html) | 常规 AWS | 
| 创建不适用的资源。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/deploy-detective-attribute-based-access-controls-for-public-subnets-by-using-aws-config.html) | 常规 AWS | 

## 相关资源
<a name="deploy-detective-attribute-based-access-controls-for-public-subnets-by-using-aws-config-resources"></a>

**AWS 文档**
+ [设置 AWS Config](https://docs.aws.amazon.com/config/latest/developerguide/gs-console.html)
+ [AWS Config 自定义规则](https://docs.aws.amazon.com/config/latest/developerguide/evaluate-config_develop-rules.html)
+ [ABAC for AWS](https://aws.amazon.com/identity/attribute-based-access-control/)
+ [为公有子网部署基于属性的预防性访问权限控制](https://docs.aws.amazon.com/prescriptive-guidance/latest/patterns/deploy-preventative-attribute-based-access-controls-for-public-subnets.html)

**其他 AWS 资源**
+ [大规模自动实现配置合规性 AWS](https://aws.amazon.com/blogs/mt/automate-configuration-compliance-at-scale-in-aws/)
+ [使用网关负载均衡器的分布式检查架构](https://d1.awsstatic.com/architecture-diagrams/ArchitectureDiagrams/distributed-inspection-architectures-gwlb-ra.pdf)

## 附加信息
<a name="deploy-detective-attribute-based-access-controls-for-public-subnets-by-using-aws-config-additional"></a>

以下是一个 Lambda 函数示例，仅用于演示目的。

```
import boto3
import json
import os

# Init clients
config_client = boto3.client('config')
ec2_client = boto3.client('ec2')

def lambda_handler(event, context):

    # Init values
    compliance_value = 'NOT_APPLICABLE'
    invoking_event = json.loads(event['invokingEvent'])
    configuration_item = invoking_event['configurationItem']
    
    status = configuration_item['configurationItemStatus']
    eventLeftScope = event['eventLeftScope']

    # First check if the event configuration applies. Ex. resource event is not delete
    if (status == 'OK' or status == 'ResourceDiscovered') and not eventLeftScope:
        compliance_value = evaluate_change_notification_compliance(configuration_item)
    
    
    config_client.put_evaluations(
       Evaluations=[
           {
               'ComplianceResourceType': invoking_event['configurationItem']['resourceType'],
               'ComplianceResourceId': invoking_event['configurationItem']['resourceId'],
               'ComplianceType': compliance_value,
               'OrderingTimestamp': invoking_event['configurationItem']['configurationItemCaptureTime']
           },
       ],
       ResultToken=event['resultToken'])
    
# Function with the logs to evaluate the resource
def evaluate_change_notification_compliance(configuration_item):
    is_in_scope = is_in_scope_subnet(configuration_item['configuration']['subnetId'])
    
    if (configuration_item['resourceType'] != 'AWS::EC2::NetworkInterface') or not is_in_scope:
        return 'NOT_APPLICABLE'

    else:
        alb_condition = configuration_item['configuration']['requesterId'] in ['amazon-elb']
        nlb_condition = configuration_item['configuration']['interfaceType'] in ['network_load_balancer']
        nat_gateway_condition = configuration_item['configuration']['interfaceType'] in ['nat_gateway']

        if alb_condition or nlb_condition or nat_gateway_condition:
            return 'COMPLIANT'
    return 'NON_COMPLIANT'

# Function to check if elastic network interface is in public subnet
def is_in_scope_subnet(eni_subnet):

    subnet_description = ec2_client.describe_subnets(
        SubnetIds=[eni_subnet]
    )

    for subnet in subnet_description['Subnets']:
        for tag in subnet['Tags']:
            if tag['Key'] == os.environ.get('TAG_KEY') and tag['Value'] == os.environ.get('TAG_VALUE'):
                return True
    
    return False
```