How do I monitor IAM events and set up event notifications with AWS CloudFormation?

8 minute read
0

I want to monitor AWS Identity and Access Management (IAM) activity with AWS CloudFormation. For example, I want to receive an email notification whenever a certain IAM event occurs.

Resolution

Create a CloudFormation template

You must deploy the template in the US East (N. Virginia) - us-east-1 AWS Region. You can modify the AWS::SNS::Topic resource to add email addresses. You can also edit the AWS::Events::Rule resource to add or remove API calls.

The following example template includes the AWS::Events::Rule resource that contains the EventPattern property. Use the EventPattern property to define what events the event sources and API calls can add or restrict. Each API call has different parameters and information in the events. The template provides only two rules that group different API calls. However, you can use several rules to create emails or notifications for different API calls. You can also define the API calls that monitor and define customized emails and information for each call.

Note: In the following JSON or YAML template, replace the example values with the values for your environment.

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>'. "

Deploy and activate the EventBridge rules

To deploy the EventBridge rules, use either the AWS CloudFormation console or the AWS Command Line Interface (AWS CLI).

AWS CloudFormation console

Complete the following steps:

  1. Download the template you updated in the preceding section.
  2. Open the AWS CloudFormation console.
  3. For AWS Region, choose us-east-1.
  4. Choose Create stack, and then choose With new resources (standard).
  5. In the Specify template section, choose Upload a template file.
  6. Choose Choose file, and then select the template. 
  7. Choose Next.
  8. In the Stack name section, for Stack name, enter a name for your stack.
  9. In the Parameters section, for EmailList, enter the email address where you want to receive notifications.
  10. For MonitorStatus, choose ENABLED.
  11. For SNSTopicName, keep the default name, or choose your own name for an Amazon Simple Notification Service (Amazon SNS) topic.
  12. Complete the rest of the steps in the setup wizard, and then choose Create stack.
  13. Check your email inbox for a confirmation email, and then follow the email instructions to confirm your subscription.

AWS CLI

Note: If you receive errors when you run AWS CLI commands, then see Troubleshooting errors for the AWS CLI. Also, make sure that you're using the most recent AWS CLI version.

Complete the following steps:

  1. Download the template, and then name the template sample-event-rule-iam-sns.yaml.

  2. Open a command line in your operating system (OS), and go to the folder where your template is located.

  3. Run the following command:

    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"

    Note: Replace mail@example.com with the email that you want to use to receive notifications and us-east-1 with your Region.

  4. Check your email inbox for a confirmation email, and then follow the email instructions to confirm your subscription.

Test whether you receive a notification

Complete the following steps:

  1. Open the IAM console.

  2. Create a test policy.

  3. Check your email for a notification about the event. The email notification is similar to the following example:

    "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://us-east-1.console.aws.amazon.com/iam/home?region=us-east-1#/policies/."

Related information

CloudTrail record contents for management, data, and network activity events

Welcome to the IAM API reference

AWS OFFICIALUpdated 2 months ago