如何使用 AWS CloudFormation 监控 IAM 事件并设置事件通知?

6 分钟阅读
0

我想使用 AWS CloudFormation 监控 AWS Identity and Access Management (IAM) 活动。例如,我想在某个 IAM 事件发生时收到电子邮件通知。

解决方法

创建 CloudFormation 模板

您必须在美国东部(弗吉尼亚州北部)- us-east-1 AWS 区域部署该模板。您可以修改 AWS::SNS::Topic 资源来添加电子邮件地址。您还可以编辑 AWS::Events::Rule 资源来添加或删除 API 调用。

以下示例模板包含具有 EventPattern 属性的 AWS::Events::Rule 资源。使用 EventPattern 属性定义事件源和 API 调用可以添加或限制的事件。每个 API 调用在事件中具有不同的参数和信息。该模板仅提供两条规则,用于对不同的 API 调用进行分组。但是,您可以使用多条规则为不同的 API 调用创建电子邮件或通知。您还可以定义用于监控和定义每个调用的自定义电子邮件和信息的 API 调用。

**注意:**在以下 JSON 或 YAML 模板中,请将示例值替换为您的环境的值。

JSON:

{
    "AWSTemplateFormatVersion": "2010-09-09",
    "Description": "Monitor IAM events with EventBridge rules with AWS CloudFormation. This Stack must be deployed in 'us-east-1' (IAM).",
    "Parameters": {
        "EmailList": {
            "Type": "String",
            "Description": "Email to notify!",
            "AllowedPattern": "[a-zA-Z0-9]+@[a-zA-Z0-9]+\\.[a-zA-Z]+",
            "Default": "mail@example.com"
        },
        "SNSTopicName": {
            "Type": "String",
            "Description": "Name for the notification topic.",
            "AllowedPattern": "[a-zA-Z0-9_-]+",
            "Default": "iam-monitoring-topic"
        },
        "MonitorStatus": {
            "Type": "String",
            "Description": "Enable / Disable monitor.",
            "AllowedValues": [
                "ENABLED",
                "DISABLED"
            ],
            "Default": "ENABLED"
        }
    },
    "Resources": {
        "SNSMonitoringTopic": {
            "Type": "AWS::SNS::Topic",
            "Properties": {
                "Subscription": [
                    {
                        "Endpoint": {
                            "Ref": "EmailList"
                        },
                        "Protocol": "email"
                    }
                ],
                "TopicName": {
                    "Fn::Sub": "${AWS::StackName}-${SNSTopicName}"
                }
            }
        },
        "SNSMonitoringTopicTopicPolicy": {
            "Type": "AWS::SNS::TopicPolicy",
            "Properties": {
                "Topics": [
                    {
                        "Ref": "SNSMonitoringTopic"
                    }
                ],
                "PolicyDocument": {
                    "Version": "2012-10-17",
                    "Statement": [
                        {
                            "Sid": "SnsIAMTopicPolicy",
                            "Effect": "Allow",
                            "Principal": {
                                "Service": "events.amazonaws.com"
                            },
                            "Action": [
                                "sns:Publish"
                            ],
                            "Resource": {
                                "Ref": "SNSMonitoringTopic"
                            }
                        },
                        {
                            "Sid": "AllowAccessToTopicOwner",
                            "Effect": "Allow",
                            "Principal": {
                                "AWS": "*"
                            },
                            "Action": [
                                "sns:GetTopicAttributes",
                                "sns:SetTopicAttributes",
                                "sns:AddPermission",
                                "sns:RemovePermission",
                                "sns:DeleteTopic",
                                "sns:Subscribe",
                                "sns:ListSubscriptionsByTopic",
                                "sns:Publish",
                                "sns:Receive"
                            ],
                            "Resource": {
                                "Ref": "SNSMonitoringTopic"
                            },
                            "Condition": {
                                "StringEquals": {
                                    "AWS:SourceOwner": {
                                        "Ref": "AWS::AccountId"
                                    }
                                }
                            }
                        }
                    ]
                }
            }
        },
        "EventRulePolicyMonitor": {
            "Type": "AWS::Events::Rule",
            "Properties": {
                "Name": {
                    "Fn::Sub": "${AWS::StackName}-policy-monitor"
                },
                "Description": "This EventBridge rule will capture IAM API Calls and events related to creation and deletion of policies.\n",
                "State": {
                    "Ref": "MonitorStatus"
                },
                "EventPattern": {
                    "source": [
                        "aws.iam"
                    ],
                    "detail-type": [
                        "AWS API Call via CloudTrail"
                    ],
                    "detail": {
                        "eventSource": [
                            "iam.amazonaws.com"
                        ],
                        "eventName": [
                            "CreatePolicy",
                            "DeletePolicy",
                            "PutGroupPolicy",
                            "DeleteGroupPolicy",
                            "PutRolePolicy",
                            "DeleteRolePolicy",
                            "PutUserPolicy",
                            "DeleteUserPolicy",
                            "CreatePolicyVersion",
                            "DeletePolicyVersion",
                            "AttachRolePolicy",
                            "DetachRolePolicy",
                            "AttachUserPolicy",
                            "DetachUserPolicy",
                            "AttachGroupPolicy",
                            "DetachGroupPolicy"
                        ]
                    }
                },
                "Targets": [
                    {
                        "Arn": {
                            "Ref": "SNSMonitoringTopic"
                        },
                        "Id": "iam-policy-monitor",
                        "InputTransformer": {
                            "InputPathsMap": {
                                "eventName": "$.detail.eventName",
                                "policyName": "$.detail.requestParameters.policyName",
                                "policyArn": "$.detail.requestParameters.policyArn",
                                "eventTime": "$.detail.eventTime",
                                "userIdentity": "$.detail.userIdentity.arn",
                                "sourceIPAddress": "$.detail.sourceIPAddress"
                            },
                            "InputTemplate": "\"API Call '<eventName>' was issued on policy '<policyName><policyArn>'. This occurred at '<eventTime>' and was initiated by '<userIdentity>' from IP '<sourceIPAddress>'. Please review the details here: https://console.aws.amazon.com/iam/home?region=us-east-1#/policies/<policyArn>$jsonEditor?section=attached_entities .\"\n"
                        }
                    }
                ]
            }
        },
        "EventRulePrincipalsMonitor": {
            "Type": "AWS::Events::Rule",
            "Properties": {
                "Name": {
                    "Fn::Sub": "${AWS::StackName}-principals-monitor"
                },
                "Description": "This EventBridge rule will capture IAM API Calls and events related to creation and deletion of users, groups and roles.",
                "State": {
                    "Ref": "MonitorStatus"
                },
                "EventPattern": {
                    "source": [
                        "aws.iam"
                    ],
                    "detail-type": [
                        "AWS API Call via CloudTrail"
                    ],
                    "detail": {
                        "eventSource": [
                            "iam.amazonaws.com"
                        ],
                        "eventName": [
                            "CreateUser",
                            "CreateGroup",
                            "CreateRole",
                            "UpdateUser",
                            "UpdateGroup",
                            "UpdateRole",
                            "DeleteUser",
                            "DeleteGroup",
                            "DeleteRole"
                        ]
                    }
                },
                "Targets": [
                    {
                        "Arn": {
                            "Ref": "SNSMonitoringTopic"
                        },
                        "Id": "iam-user-monitor",
                        "InputTransformer": {
                            "InputPathsMap": {
                                "eventName": "$.detail.eventName",
                                "userName": "$.detail.requestParameters.userName",
                                "roleName": "$.detail.requestParameters.roleName",
                                "groupName": "$.detail.requestParameters.groupName",
                                "eventTime": "$.detail.eventTime",
                                "userIdentity": "$.detail.userIdentity.arn",
                                "sourceIPAddress": "$.detail.sourceIPAddress"
                            },
                            "InputTemplate": "\"API Call '<eventName>' was issued on '<userName><roleName><groupName>'. This occurred at '<eventTime>' and was initiated by '<userIdentity>' from IP '<sourceIPAddress>'. \"\n"
                        }
                    }
                ]
            }
        }
    }
}

YAML:

AWSTemplateFormatVersion: 2010-09-09
Description: >
             - Monitor IAM events with EventBridge rules with AWS CloudFormation.
             - This Stack must be deployed in 'us-east-1' (IAM).


Parameters:

  EmailList:
    Type: String
    Description: "Email to notify!"
    AllowedPattern: '[a-zA-Z0-9]+@[a-zA-Z0-9]+\.[a-zA-Z]+'
    Default: "mail@example.com"

  SNSTopicName:
    Type: String
    Description: "Name for the notification topic."
    AllowedPattern: '[a-zA-Z0-9_-]+'
    Default: "iam-monitoring-topic"

  MonitorStatus:
    Type: String
    Description: "Enable / Disable monitor."
    AllowedValues:
      - ENABLED
      - DISABLED
    Default: ENABLED


Resources:

  SNSMonitoringTopic:
    Type: AWS::SNS::Topic
    Properties:
      Subscription:
        - Endpoint: !Ref EmailList
          Protocol: email
      TopicName: !Sub ${AWS::StackName}-${SNSTopicName}

  SNSMonitoringTopicTopicPolicy:
    Type: AWS::SNS::TopicPolicy
    Properties:
      Topics:
        - !Ref SNSMonitoringTopic
      PolicyDocument:
          Version: '2012-10-17'
          Statement:
          - Sid: SnsIAMTopicPolicy
            Effect: Allow
            Principal:
              Service: events.amazonaws.com
            Action: [  'sns:Publish' ]
            Resource: !Ref SNSMonitoringTopic
          - Sid: AllowAccessToTopicOwner
            Effect: Allow
            Principal:
              AWS: '*'
            Action: [  'sns:GetTopicAttributes',
                       'sns:SetTopicAttributes',
                       'sns:AddPermission',
                       'sns:RemovePermission',
                       'sns:DeleteTopic',
                       'sns:Subscribe',
                       'sns:ListSubscriptionsByTopic',
                       'sns:Publish',
                       'sns:Receive' ]
            Resource: !Ref SNSMonitoringTopic
            Condition:
              StringEquals:
                'AWS:SourceOwner': !Ref 'AWS::AccountId'

  EventRulePolicyMonitor:
    Type: AWS::Events::Rule
    Properties:
      Name: !Sub ${AWS::StackName}-policy-monitor
      Description: >
        This EventBridge rule will capture IAM API Calls and
        events related to creation and deletion of policies.
      State: !Ref MonitorStatus
      EventPattern:
        source:
           - aws.iam
        detail-type:
          - AWS API Call via CloudTrail
        detail:
          eventSource:
            - iam.amazonaws.com
          eventName:
            - CreatePolicy
            - DeletePolicy
            - PutGroupPolicy
            - DeleteGroupPolicy
            - PutRolePolicy
            - DeleteRolePolicy
            - PutUserPolicy
            - DeleteUserPolicy
            - CreatePolicyVersion
            - DeletePolicyVersion
            - AttachRolePolicy
            - DetachRolePolicy
            - AttachUserPolicy
            - DetachUserPolicy
            - AttachGroupPolicy
            - DetachGroupPolicy
      Targets:
        - Arn:
            Ref: SNSMonitoringTopic
          Id: iam-policy-monitor
          InputTransformer:
            InputPathsMap:
              eventName: $.detail.eventName
              policyName: $.detail.requestParameters.policyName
              policyArn: $.detail.requestParameters.policyArn
              eventTime: $.detail.eventTime
              userIdentity: $.detail.userIdentity.arn
              sourceIPAddress: $.detail.sourceIPAddress
            InputTemplate: >
                "API Call '<eventName>' was issued on policy '<policyName><policyArn>'. This occurred at '<eventTime>' and was initiated by '<userIdentity>' from IP '<sourceIPAddress>'. Please review the details here: https://console.aws.amazon.com/iam/home?region=us-east-1#/policies/<policyArn>$jsonEditor?section=attached_entities ."

  EventRulePrincipalsMonitor:
    Type: AWS::Events::Rule
    Properties:
      Name: !Sub ${AWS::StackName}-principals-monitor
      Description: >
        This EventBridge rule will capture IAM API Calls and
        events related to creation and deletion of users, groups
        and roles.
      State: !Ref MonitorStatus
      EventPattern:
        source:
           - aws.iam
        detail-type:
          - AWS API Call via CloudTrail
        detail:
          eventSource:
            - iam.amazonaws.com
          eventName:
            - CreateUser
            - CreateGroup
            - CreateRole
            - UpdateUser
            - UpdateGroup
            - UpdateRole
            - DeleteUser
            - DeleteGroup
            - DeleteRole
      Targets:
        - Arn:
            Ref: SNSMonitoringTopic
          Id: iam-user-monitor
          InputTransformer:
            InputPathsMap:
              eventName: $.detail.eventName
              userName: $.detail.requestParameters.userName
              roleName: $.detail.requestParameters.roleName
              groupName: $.detail.requestParameters.groupName
              eventTime: $.detail.eventTime
              userIdentity: $.detail.userIdentity.arn
              sourceIPAddress: $.detail.sourceIPAddress
            InputTemplate: >
                "API Call '<eventName>' was issued on '<userName><roleName><groupName>'. This occurred at '<eventTime>' and was initiated by '<userIdentity>' from IP '<sourceIPAddress>'. "

部署并激活 EventBridge 规则

要部署 EventBridge 规则,请使用 AWS CloudFormation 控制台或 AWS 命令行界面 (AWS CLI)。

AWS CloudFormation 控制台

完成以下步骤:

  1. 下载您在前面的部分中更新的模板。
  2. 打开 AWS CloudFormation 控制台
  3. 对于 AWS Region(AWS 区域),选择 us-east-1
  4. 选择 Create stack(创建堆栈),然后选择 With new resources (standard)(使用新资源(标准))。
  5. Specify template(指定模板)部分中,选择 Upload a template file(上传模板文件)。
  6. 选择 Choose file(选择文件),然后选择模板。
  7. 选择 Next(下一步)。
  8. Stack name(堆栈名称)部分中,对于 Stack name(堆栈名称),输入堆栈的名称。
  9. Parameters(参数)部分中,对于 EmailList,输入要用于接收通知的电子邮件地址。
  10. 对于 MonitorStatus,选择 ENABLED(启用)。
  11. 对于 SNSTopicName,保留默认名称,或者为 Amazon Simple Notification Service (Amazon SNS) 主题选择您自己的名称。
  12. 完成安装向导中的剩余步骤,然后选择 Create stack(创建堆栈)。
  13. 查看您的电子邮件收件箱中是否有确认电子邮件,然后按照电子邮件说明确认您的订阅。

AWS CLI

**注意:**如果您在运行 AWS CLI 命令时收到错误,请参阅 AWS CLI 错误故障排除。此外,请确保您使用的是最新版本的 AWS CLI

完成以下步骤:

  1. 下载模板,然后将模板命名为 sample-event-rule-iam-sns.yaml

  2. 在操作系统 (OS) 中打开命令行,然后转到模板所在的文件夹。

  3. 运行以下命令:

    aws cloudformation --region=us-east-1 \                   
                       create-stack \
                       --stack-name iam-sample-monitor \
                       --template-body file://sample-event-rule-iam-sns.yaml \
                       --parameters \
                       ParameterKey=EmailList,ParameterValue="mail@example.com"

    **注意:**请将 mail@example.com 替换为要用于接收通知的电子邮件,将 us-east-1 替换为您所在的区域。

  4. 查看您的电子邮件收件箱中是否有确认电子邮件,然后按照电子邮件说明确认您的订阅。

测试您是否收到通知

完成以下步骤:

  1. 打开 IAM 控制台

  2. 创建测试策略

  3. 检查您的电子邮件中是否存在有关该事件的通知。电子邮件通知类似于以下示例:

    “针对策略 'test-policy' 发出了 API 调用 'CreatePolicy'。此调用发生于 '2020-11-13T00:00:00Z',由 'arn:aws:sts::123456789012:assumed-role/your-role' 通过 IP 'X.Y.Z.T' 发起。
    请在此处查看详细信息:https://us-east-1.console.aws.amazon.com/iam/home?region=us-east-1#/policies/。”

相关信息

CloudTrail 针对管理、数据和网络活动事件的记录内容

Welcome to the IAM API reference

AWS 官方
AWS 官方已更新 1 个月前