跳至內容

如何使用 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 呼叫。

下列範本範例包含 AWS::Events::Rule 資源,其中包含 EventPattern 屬性。使用 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 Command Line Interface (AWS CLI)。

AWS CloudFormation 主控台

請完成下列步驟:

  1. 下載您在上一節中更新的範本。
  2. 開啟 AWS CloudFormation console (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 console (IAM 主控台)。

  2. 建立測試政策。

  3. 檢查您的電子郵件,以取得有關事件的通知。電子郵件通知類似於下列範例:

    「針對政策 'test-policy' 發出了 API 呼叫 'CreatePolicy'。此事件發生於 '2020-11-13T00:00:00Z',由來自 IP 'X.Y.Z.T' 的 'arn:aws:sts::123456789012:assumed-role/your-role' 發起。
    請在這裡查看詳細資訊:https://us-east-1.console.aws.amazon.com/iam/home?region=us-east-1#/policies/。」

相關資訊

管理、資料和網路活動事件的 CloudTrail 記錄內容

歡迎使用 IAM API 參考資料

AWS 官方已更新 2 年前