AWS CloudFormation을 사용하여 IAM 이벤트를 모니터링하고 이벤트 알림을 설정하려면 어떻게 해야 합니까?
최종 업데이트 날짜: 2020년 11월 18일
AWS CloudFormation을 사용하여 AWS Identity and Access Management(IAM) 활동을 모니터링하려고 합니다. 예를 들어 특정 IAM 이벤트가 발생할 때마다 이메일 알림을 수신하려고 합니다.
간략한 설명
다음 해결 방법에 있는 AWS CloudFormation 템플릿을 사용하여 IAM 이벤트를 모니터링하고 Amazon CloudWatch 이벤트로 알림을 설정할 수 있습니다.
다음을 고려합니다.
- 이 템플릿은 미국 동부(버지니아 북부) - us-east-1 AWS 리전에서 배포해야 합니다.
- 추가 이메일 주소를 포함하도록 AWS። SNS። Topic 리소스를 수정할 수 있습니다.
- AWS። Events። Rule 리소스를 편집하여 추가 API 호출을 추가하거나 제거할 수 있습니다.
해결 방법
다음 템플릿에는 EventPattern 속성이 포함된 AWS::Events::Rule 리소스가 포함되어 있습니다. EventPattern 속성을 사용하여 다양한 이벤트 소스와 API 호출에 사용 사례에 대한 특정 이벤트를 추가하거나 제한하는 기능을 제공할 수 있습니다. 각 API 호출은 이벤트에서 서로 다른 파라미터와 정보가 있습니다. 획일적인 이벤트 규칙을 만들 수는 없습니다. 다음 샘플 템플릿은 서로 다른 여러 API 호출을 함께 그룹화하는 두 가지 규칙만 제공합니다. 그러나 여러 API 호출에 대한 이메일 또는 알림을 만드는 데 필요한 만큼의 규칙을 사용할 수 있습니다. 모니터링할 API 호출을 사용자 지정하고 정의하며 각 호출에 대해 사용자 지정된 이메일 및 정보를 정의할 수 있습니다.
1. 템플릿의 다음 JSON 또는 YAML 버전을 복사한 다음 해당 환경의 값으로 업데이트합니다.
JSON:
{
"AWSTemplateFormatVersion": "2010-09-09",
"Description": "Monitor IAM events with CloudWatch Events 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@company.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 CloudWatch Event 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 CloudWatch Event 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 CloudWatch Events 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@company.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 CloudWatch Event 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 CloudWatch Event 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 명령줄 인터페이스(AWS CLI)를 사용하여 템플릿을 배포할 수 있습니다.
AWS CloudFormation 콘솔
1. 템플릿을 다운로드합니다.
2. AWS CloudFormation 콘솔을 엽니다.
3. 탐색 모음의 AWS 리전 선택기에서 us-east-1을 선택합니다.
4. [스택 만들기(Create stack)]를 선택한 다음 [새 리소스 사용(표준)(With new resources(standard))]을 선택합니다.
5. [템플릿 지정(Specify template)] 섹션에서 [템플릿 파일 업로드(Upload a template file)]를 선택합니다.
6. [파일 선택(Choose file)]을 선택하고 1단계에서 다운로드한 템플릿을 선택한 후 [다음(Next)]을 선택합니다.
7. [스택 이름(Stack name )] 섹션에서 [스택 이름(Stack name)]에 스택 이름을 입력합니다.
8. [파라미터(Parameters)] 섹션에서 EmailList에 알림을 받을 이메일 주소를 입력합니다.
9. [모니터 상태(MonitorStatus)]에 대해 [활성화됨(ENABLED)]을 선택합니다.
10. SNStopicName의 경우 기본 이름을 그대로 두거나 Amazon Simple Notification Service(Amazon SNS) 주제에 대해 고유한 이름을 선택합니다.
11. 설정 마법사의 나머지 단계를 완료한 다음, [스택 생성(Create stack)]을 선택합니다.
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@company.com"
참고: mail@company.com을 알림을 수신할 이메일로 바꿉니다.
5. 받은 편지함(4단계에서 입력한 이메일 주소 사용)에서 확인 이메일을 확인한 다음 이메일의 지침에 따라 구독을 확인합니다.
모니터링 알림 테스트
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.