スキップしてコンテンツを表示

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 呼び出しをグループ化するルールが 2種類のみ用意されています。ただし、複数のルールを使用すると、さまざまな 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 リージョン]us-east-1 を選択します。
  4. [スタックを作成] を選択し、[新しいリソースを使用 (標準)] を選択します。
  5. [テンプレートを指定] セクションで [テンプレートファイルをアップロード] を選択します。
  6. [ファイルを選択] を選択し、該当するテンプレートを選択します。
  7. [次へ] を選択します。
  8. [スタック名] セクションの [スタック名] にスタックの名前を入力します。
  9. [パラメータ] セクションの [EmailList] に通知の受信に使用する電子メールアドレスを入力します。
  10. **[MonitorStatus]**で ENABLED を選択します。
  11. SNSTopicName ではデフォルトの名前をそのまま使用するか、Amazon Simple Notification Service (Amazon SNS) トピック用の独自の名前を選択します、。
  12. セットアップウィザードで残りの手順を完了し、[スタックを作成] を選択します。
  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. メールにイベントに関する通知が届いているかどうかを確認します。メール通知は次の例のようになります。

    「API Call 'CreatePolicy' was issued on policy 'test-policy'. (API コール 'CreatePolicy' がポリシー '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'. ('2020-11-13T00:00:00Z' に発生し、IP アドレス 'X.Y.Z.T' の 'arn:aws:sts::123456789012:assumed-role/your-role' が開始しました)
    Please review the details here: https://us-east-1.console.aws.amazon.com/iam/home?region=us-east-1#/policies/」

関連情報

管理、データ、ネットワークアクティビティイベントに関する CloudTrail レコードのコンテンツ

IAM API リファレンス - はじめに

AWS公式更新しました 10ヶ月前
コメントはありません

関連するコンテンツ