使用 AWS re:Post 即表示您同意 AWS re:Post 使用條款

如何使用 AWS CloudFormation 監控 IAM 事件和設定事件通知?

6 分的閱讀內容
0

我想要使用 AWS CloudFormation 監控 AWS Identity and Access Management (IAM) 活動。例如,我想要在發生特定 IAM 事件時收到電子郵件通知。

簡短說明

您可以使用下列解決方案中的 AWS CloudFormation 範本來監控 IAM 事件,並設定 Amazon EventBridge 的通知。

請考慮下列事項:

  • 您必須在美國東部 (維吉尼亞北部) - us-east-1 AWS 區域中部署範本。
  • 您可以修改 AWS::SNS::Topic 資源,以包含其他電子郵件地址。
  • 您可以編輯 AWS::Events::Rule 資源,以新增或移除其他 API 呼叫。

解決方案

下列範本包含 AWS::Events::Rule 資源,其中包含 EventPattern 屬性。您可以使用 EventPattern 屬性,讓不同的事件來源和 API 呼叫能夠為您的使用案例新增或限制特定事件。每個 API 呼叫在事件中都有不同的參數和資訊。無法建立一體適用的事件規則。下列範例範本僅提供兩種將許多不同 API 呼叫分組在一起的規則。但是,您可以根據需要使用任意數量的規則來為不同的 API 呼叫建立電子郵件或通知。您可以為每個呼叫自訂和定義需要監視和定義的自訂電子郵件和資訊的 API 呼叫。

1.    複製下列 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>'. "

2.    使用 AWS CloudFormation 主控台或 AWS Command Line Interface (AWS CLI) 部署範本:

AWS CloudFormation 主控台

1.    下載範本。

2.    開啟 AWS CloudFormation 主控台

3.    從導覽列的 AWS 區域選取器中,選擇 us-east-1

4.    選擇「建立堆疊」,然後選擇「使用新資源 (標準)」。

5.    在「指定範本」區段中,選擇「上傳範本檔案」。

6.    選擇「選擇檔案」,選取您在步驟 1 中下載的範本,然後選擇「下一步」。

7.    在「堆疊名稱」區段中,針對「堆疊名稱」,輸入堆疊的名稱。

8.    在「參數」區段中,針對 EmailList,輸入您想要接收通知的電子郵件地址。

9.    對於 MonitorStatus,請選擇「已啟用」。

10.    對於 SNSTopicName,請保留預設名稱,或為 Amazon Simple Notification Service (Amazon SNS) 主題選擇您的專屬名稱。

11.    完成設定精靈中的其餘步驟,然後選擇「建立堆疊」。

12.    檢查您的收件匣 (使用您在步驟 8 中輸入的電子郵件地址) 是否有確認電子郵件,然後遵循電子郵件說明確認您的訂閱。

AWS CLI

**注意事項:**如果您在執行 AWS CLI 命令時收到錯誤訊息,請確定您使用的是最新版本的 AWS CLI

1.    下載範本,然後將範本命名為 sample-event-rule-iam-sns.yaml

2.    設定 AWS CLI。

3.    在作業系統中開啟命令列,然後前往範本所在的資料夾。

4.    執行下列命令:

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 取代為您想要接收通知的電子郵件。

5.    檢查您的收件匣 (使用您在步驟 4 中輸入的電子郵件地址) 是否有確認電子郵件,然後遵循電子郵件說明確認您的訂閱。

測試監控通知

1.    開啟 IAM 主控台

2.    建立測試政策。

3.    檢查您的電子郵件,以取得有關事件的通知。您將會收到類似於下列內容的電子郵件:

API Call 'CreatePolicy' was issued on policy 'test-policy'.
This occurred at '2020-11-13T00:00:00Z' and was initiated by 'arn:aws:sts::123456789012:assumed-role/your-role' from IP 'X.Y.Z.T'.
Please review the details here: https://console.aws.amazon.com/iam/home?region=us-east-1#/policies/$jsonEditor?section=attached_entities.

相關資訊

CloudTrail 記錄內容

歡迎使用 IAM API 參考資料

AWS 官方
AWS 官方已更新 3 年前