

# IAM
<a name="automation-ref-iam"></a>

 AWS Systems Manager Automation provides predefined runbooks for AWS Identity and Access Management. For more information about runbooks, see [Working with runbooks](https://docs.aws.amazon.com/systems-manager/latest/userguide/automation-documents.html). For information about how to view runbook content, see [View runbook content](automation-runbook-reference.md#view-automation-json). 

**Topics**
+ [`AWSSupport-TroubleshootIAMAccessDeniedEvents`](awssupport-troubleshootiamaccessdeniedevents.md)
+ [`AWS-AttachIAMToInstance`](automation-aws-attachiamtoinstance.md)
+ [`AWS-DeleteIAMInlinePolicy`](delete-iam-inline-policy.md)
+ [`AWSConfigRemediation-DeleteIAMRole`](automation-aws-delete-iam-role.md)
+ [`AWSConfigRemediation-DeleteIAMUser`](automation-aws-delete-iam-user.md)
+ [`AWSConfigRemediation-DeleteUnusedIAMGroup`](automation-aws-delete-iam-group.md)
+ [`AWSConfigRemediation-DeleteUnusedIAMPolicy`](automation-aws-delete-iam-policy.md)
+ [`AWSConfigRemediation-DetachIAMPolicy`](automation-aws-detach-iam-policy.md)
+ [`AWSConfigRemediation-EnableAccountAccessAnalyzer`](automation-aws-enable-account-access-analyzer.md)
+ [`AWSSupport-GrantPermissionsToIAMUser`](automation-awssupport-grantpermissionstoiamuser.md)
+ [`AWSConfigRemediation-RemoveUserPolicies`](automation-aws-remove-user-policies.md)
+ [`AWSConfigRemediation-ReplaceIAMInlinePolicy`](automation-aws-replace-iam-policy.md)
+ [`AWSConfigRemediation-RevokeUnusedIAMUserCredentials`](automation-aws-revoke-iam-user.md)
+ [`AWSConfigRemediation-SetIAMPasswordPolicy`](automation-aws-set-iam-policy.md)
+ [`AWSSupport-ContainIAMPrincipal`](awssupport-contain-iam-principal.md)
+ [`AWSSupport-TroubleshootSAMLIssues`](awssupport-troubleshootsamlissues.md)

# `AWSSupport-TroubleshootIAMAccessDeniedEvents`
<a name="awssupport-troubleshootiamaccessdeniedevents"></a>

 **Description** 

 **The AWSSupport-TroubleshootIAMAccessDeniedEvents ** automation runbook helps troubleshooting AWS Identity and Access Management (IAM) access denied issues. The runbook queries CloudTrail for recent access denied events related to the specified IAM entity and AWS service event source. It analyzes events within a configurable time window of up to 24 hours, processing up to 10 events per execution. Each identified access denied event is examined to help understand the context of the denial and the attempted actions. The automation analyzes both identity-based and resource-based IAM policies. For identity-based policies, it examines inline and managed policies attached to the IAM entity. For resource-based policies, it evaluates policies across multiple AWS services including Amazon Simple Storage Service(Amazon S3), AWS Key Management Service (AWS KMS), AWS Lambda, Amazon Simple Notification Service (Amazon SNS), Amazon Elastic Container Registry (Amazon ECR), Amazon API Gateway, CodeArtifact, Amazon Elastic File System (Amazon EFS), Amazon Simple Queue Service (Amazon SQS), AWS Cloud9, Amazon OpenSearch Service, AWS Signer, AWS Serverless Application Repository, and AWS Secrets Manager. 

 The runbook utilizes IAM policy simulation capabilities to evaluate these policies against the denied actions found in the CloudTrail events. The runbook leverages IAM's policy simulation capabilities through both [SimulatePrincipalPolicy ](https://docs.aws.amazon.com/IAM/latest/APIReference/API_SimulatePrincipalPolicy.html) for IAM users and [SimulateCustomPolicy](https://docs.aws.amazon.com/IAM/latest/APIReference/API_SimulateCustomPolicy.html) for IAM roles to evaluate these policies against the denied actions found in the CloudTrail events. The automation outputs a report that helps identify the specific actions that were denied, differentiating between implicit and explicit denies, listing the policies responsible for access denials and provides explanations for each denial. The report also suggests potential resolutions, such as identifying missing allow statements or conflicting deny statements 

 **How does it work?** 

 The runbook performs the following steps: 
+ Describes and validates `RequesterARN` (role or user) to get information such as IAM entity type, and IAM Id.
+ Fetches CloudTrail events associated with the `RequesterARN`, `EventSource`, and `ResourceARN` if provided.
+ Analyzes the CloudTrail events to get the action that was performed when the Access Denied error was returned, then examines all the IAM policies such as inline and managed policies attached to the IAM entity, as well as resource-based policies. It then simulates these policies against the actions found in the Access Denied errors from the CloudTrail events in question to determine the cause of the error.
+ Outputs a report determining the type of Access Denied error, the policies responsible for the errors, and gives suggestions for potential solution to the error.

 [Run this Automation (console)](https://console.aws.amazon.com/systems-manager/automation/execute/AWSSupport-TroubleshootIAMAccessDeniedEvents) 

**Document type**

Automation

**Owner**

Amazon

**Platforms**

/

**Required IAM permissions**

The `AutomationAssumeRole` parameter requires the following actions to use the runbook successfully.
+ `apigateway:GetRestApis`
+ `cloudtrail:LookupEvents`
+ `cloud9:GetEnvironment`
+ `codeartifact:GetRepositoryPermissionsPolicy`
+ `ecr:GetRepositoryPolicy`
+ `elasticfilesystem:GetFileSystemPolicy`
+ `es:DescribeDomain`
+ `iam:GetPolicy`
+ `iam:GetPolicyVersion`
+ `iam:GetRole`
+ `iam:GetRolePolicy`
+ `iam:GetUser`
+ `iam:GetUserPolicy`
+ `iam:ListAttachedRolePolicies`
+ `iam:ListAttachedUserPolicies`
+ `iam:ListRolePolicies`
+ `iam:ListUserPolicies`
+ `iam:SimulatePrincipalPolicy`
+ `iam:SimulateCustomPolicy`
+ `kms:GetKeyPolicy`
+ `lambda:GetPolicy`
+ `secretsmanager:GetResourcePolicy`
+ `serverlessrepo:GetApplication`
+ `signer:GetSigningProfile`
+ `sns:GetTopicAttributes`
+ `ssm:StartAutomationExecution`
+ `ssm:StopAutomationExecution`
+ `sqs:GetQueueAttributes`
+ `s3:GetBucketPolicy`

Example Policy: 

------
#### [ JSON ]

****  

```
        {
            "Version":"2012-10-17",		 	 	 
            "Statement": [
                {
                    "Action": [
                        "iam:GetUser",
                        "iam:GetRole",
                        "iam:SimulatePrincipalPolicy",
                        "iam:ListUserPolicies",
                        "iam:ListRolePolicies",
                        "iam:GetRolePolicy",
                        "iam:ListAttachedRolePolicies",
                        "iam:GetPolicy",
                        "iam:GetUserPolicy",
                        "iam:GetPolicyVersion",
                        "iam:ListAttachedUserPolicies",
                        "ssm:StartAutomationExecution",
                        "ssm:StopAutomationExecution",
                        "cloudtrail:LookupEvents",
                        "iam:SimulateCustomPolicy"
                    ],
                    "Resource": "*",
                    "Effect": "Allow"
                },
                {
                    "Action": [
                        "s3:GetBucketPolicy",
                        "kms:GetKeyPolicy",
                        "lambda:GetPolicy",
                        "sns:GetTopicAttributes",
                        "ecr:GetRepositoryPolicy",
                        "apigateway:GET",
                        "codeartifact:GetRepositoryPermissionsPolicy",
                        "elasticfilesystem:DescribeFileSystemPolicy",
                        "sqs:GetQueueAttributes",
                        "cloud9:DescribeEnvironmentStatus",
                        "es:DescribeDomain",
                        "signer:GetSigningProfile",
                        "serverlessrepo:GetApplication",
                        "secretsmanager:GetResourcePolicy"
                    ],
                    "Resource": "*",
                    "Effect": "Allow"
                }
            ]
        }
```

------

 **Instructions** 

Follow these steps to configure the automation:

1. Navigate to [https://console.aws.amazon.com/systems-manager/documents/AWSSupport-TroubleshootIAMAccessDeniedEvents/description](https://console.aws.amazon.com/systems-manager/documents/AWSSupport-TroubleshootIAMAccessDeniedEvents/description) in Systems Manager under Documents.

1. Select **Execute automation.**

1. For the input parameters, enter the following:
   + **AutomationAssumeRole (Optional):**
     + Description: (Optional) The Amazon Resource Name (ARN) of the AWS Identity and Access Management (IAM) role that allows SSM Automation to perform the actions on your behalf. The role needs to be added to your Amazon EKS cluster access entry or RBAC permission to allow Kubernetes API calls.
     + Type: `AWS::IAM::Role::Arn`
   + **RequesterARN (Required):**
     + Description: (Required) The ARN of the IAM user or role for which you want to investigate the access permissions on a specific AWS resource.
     + Type: `String`
     + Allow Pattern: `^arn:(aws|aws-cn|aws-us-gov|aws-iso(-[a-z])?):iam::[0-9]{12}:(role|user)\\/[\\w+\\/=,.@-]+$`
   + **ResourceARN (Optional):**
     + Description: (Optional) The ARN of AWS the resource for which the access denied is evaluated. The AWS target resource should exist in the same region where the automation runbook is executed.
     + Type: `String`
     + Allow Pattern: `^$|^arn:(aws|aws-cn|aws-us-gov|aws-iso(-[a-z])?):([a-zA-Z0-9\\-]{1,63}):([a-z0-9\\-]{0,63})?:(\\d{12})?:([a-zA-Z0-9\\-_/:.]{1,1024})$`
   + **EventSource (Required):**
     + Description: (Required) The Amazon API endpoint where the CloudTrail event originated. For example: `s3.amazonaws.com`.
     + Type: `String`
     + Allow Pattern: `^([a-zA-Z0-9.-]+)\\.amazonaws\\.com$`
   + **EventName (Optional):**
     + Description: (Optional) The Amazon API action name associated with the CloudTrail event. For example: `s3:CreateBucket`.
     + Type: `String`
     + Allow Pattern: `^$|^[a-z0-9]+:[A-Za-z0-9]+$`
   + **LookBackHours (Optional):**
     + Description: (Optional) The number of hours to look back in the CloudTrail events when searching for `Access Denied` events. Valid range: `1` to `24` hours.
     + Type: Integer
     + Allow Pattern: `^([1-9]|1[0-9]|2[0-4])$`
     + Default: 12
   + **MaxEvents (Optional):**
     + Description: (Optional) The maximum number of CloudTrail `Access Denied` events returned when searching for events. Valid range: `1` to `5` events.
     + Type: Integer
     + Allow Pattern: `^([1-9]|1[0-9]|2[0-4])$`
     + Default: 3
   + **UseContextEntries (Optional):**
     + Description: (Optional) If you specify `true`, the automation extracts details about the context of the API request from the CloudTrail event and include them for the IAM policy simulation.
     + Type: Boolean
     + Allow Pattern: `^([1-9]|1[0-9]|2[0-4])$`
     + Default: 3

1. Select **Execute**.

1. The automation initiates.

1. The document performs the following steps:
   + **ValidateRequesterArn**

     Validates and deconstructs the `RequesterArn` ARN, retrieving information about the target IAM user or role.
   + **GetCloudTrailEvents****WithAccessDeniedError**

     Queries the CloudTrail events for recent `Access Denied` events related to the specified IAM entity and AWS service `EventSource`.
   + **EvaluateIAMRequesterPolicies**

     Evaluates the IAM permissions of the requester IAM entity against the actions from CloudTrail events. This evaluation includes analyzing both identity-based and resource-based policies associated with the requester. The automation utilizes IAM's policy simulation capabilities to assess these policies in the context of the denied actions identified in the CloudTrail events.

1. After completed, review the **Outputs** section for the detailed results of the execution:
   + **PermissionEvaluationResults**

     Outputs a report that helps to identify the specific actions that were denied, differentiating between implicit and explicit denials. It also lists the policies responsible for access denials and provides explanations for each denial. The report also suggests potential resolutions, such as identifying missing allow statements or conflicting deny statements

 **References** 

Systems Manager Automation
+ [Run this Automation (console)](https://console.aws.amazon.com/systems-manager/documents/TroubleshootIAMAccessDeniedEvents/description)
+ [Run an automation](https://docs.aws.amazon.com//systems-manager/latest/userguide/automation-working-executing.html)
+ [Setting up an Automation](https://docs.aws.amazon.com//systems-manager/latest/userguide/automation-setup.html)
+ [Support Automation Workflows landing page](https://aws.amazon.com/premiumsupport/technology/saw/)

# `AWS-AttachIAMToInstance`
<a name="automation-aws-attachiamtoinstance"></a>

 **Description** 

Attach an AWS Identity and Access Management (IAM) role to a managed instance.

 [Run this Automation (console)](https://console.aws.amazon.com/systems-manager/automation/execute/AWS-AttachIAMToInstance) 

**Document type**

Automation

**Owner**

Amazon

**Platforms**

Linux, macOS, Windows

**Parameters**
+ AutomationAssumeRole

  Type: String

  Description: (Optional) The Amazon Resource Name (ARN) of the AWS Identity and Access Management (IAM) role that allows Systems Manager Automation to perform the actions on your behalf. If no role is specified, Systems Manager Automation uses the permissions of the user that starts this runbook.
+ ForceReplace

  Type: Boolean

  Description: (Optional) Flag to specify whether to replace the existing IAM profile or not.

  Default: true
+ InstanceId

  Type: String

  Description: (Required) The ID of the instance on which you want to assign an IAM role.
+ RoleName

  Type: String

  Description: (Required) The IAM role name to add to the managed instance.

 **Document Steps** 

1.  `aws:executeAwsApi` - DescribeInstanceProfile - Find the IAM instance profile attached to the EC2 instance. 

1.  `aws:branch` - CheckInstanceProfileAssociations - Check the IAM instance profile attached to the EC2 instance. 

   1.  If an IAM instance profile is attached and `ForceReplace` is set to `true` : 

      1.  `aws:executeAwsApi` - DisassociateIamInstanceProfile - Disassociate the IAM instance profile from the EC2 instance. 

   1.  `aws:executeAwsApi` - ListInstanceProfilesForRole - List instance profiles for the IAM role provided. 

   1.  `aws:branch` - CheckInstanceProfileCreated - Check if the IAM role provided has an associated instance profile. 

      1. If the IAM role has an associated instance profile:

         1.  `aws:executeAwsApi` - AttachIAMProfileToInstance - Attach the IAM instance profile role to the EC2 instance. 

      1. If the IAM role does not have an associated instance profile:

         1.  `aws:executeAwsApi` - CreateInstanceProfileForRole - Create an instance profile role for the specified IAM role. 

         1.  `aws:executeAwsApi` - AddRoleToInstanceProfile - Attach the instance profile role to the specified IAM role. 

         1.  `aws:executeAwsApi` - GetInstanceProfile - Get the instance profile data for the specified IAM role. 

         1.  `aws:executeAwsApi` - AttachIAMProfileToInstanceWithRetry - Attach the IAM instance profile role to the EC2 instance. 

 **Outputs** 

AttachIAMProfileToInstanceWithRetry.AssociationId

GetInstanceProfile.InstanceProfileName

GetInstanceProfile.InstanceProfileArn

AttachIAMProfileToInstance.AssociationId

ListInstanceProfilesForRole.InstanceProfileName

ListInstanceProfilesForRole.InstanceProfileArn

# `AWS-DeleteIAMInlinePolicy`
<a name="delete-iam-inline-policy"></a>

**Description**

The `AWS-DeleteIAMInlinePolicy` runbook deletes all AWS Identity and Access Management (IAM) inline policies attached to the IAM identities you specify.

[Run this Automation (console)](https://console.aws.amazon.com/systems-manager/automation/execute/AWS-DeleteIAMInlinePolicy)

**Document type**

Automation

**Owner**

Amazon

**Platforms**

Linux, macOS, Windows

**Parameters**
+ AutomationAssumeRole

  Type: String

  Description: (Optional) The Amazon Resource Name (ARN) of the AWS Identity and Access Management (IAM) role that allows Systems Manager Automation to perform the actions on your behalf. If no role is specified, Systems Manager Automation uses the permissions of the user that starts this runbook.
+ IamArns

  Type: String

  Description: (Required) A comma separated list of ARNs for the IAM identities you want to delete inline policies from. This list can include IAM users, groups, or roles.

**Required IAM permissions**

The `AutomationAssumeRole` parameter requires the following actions to use the runbook successfully.
+ `iam:DeleteGroupPolicy`
+ `iam:DeleteRolePolicy`
+ `iam:DeleteUserPolicy`
+ `iam:ListGroupPolicies`
+ `iam:ListRolePolicies`
+ `iam:ListUserPolicies`

**Document Steps**
+ `aws:executeScript` - Deletes the IAM inline policies attached to the targeted IAM identities.

# `AWSConfigRemediation-DeleteIAMRole`
<a name="automation-aws-delete-iam-role"></a>

 **Description** 

 The `AWSConfigRemediation-DeleteIAMRole` runbook deletes the AWS Identity and Access Management (IAM) role you specify. This automation does not delete instance profiles associated with the IAM role, or service-linked roles. 

 [Run this Automation (console)](https://console.aws.amazon.com/systems-manager/automation/execute/AWSConfigRemediation-DeleteIAMRole) 

**Document type**

Automation

**Owner**

Amazon

**Platforms**

Linux, macOS, Windows

**Parameters**
+ AutomationAssumeRole

  Type: String

  Description: (Required) The Amazon Resource Name (ARN) of the AWS Identity and Access Management (IAM) role that allows Systems Manager Automation to perform the actions on your behalf.
+ IAMRoleID

  Type: String

  Description: (Required) The ID of the IAM role you want to delete.

**Required IAM permissions**

The `AutomationAssumeRole` parameter requires the following actions to use the runbook successfully.
+  `ssm:StartAutomationExecution` 
+  `ssm:GetAutomationExecution` 
+  `iam:DeleteRole` 
+  `iam:DeleteRolePolicy` 
+  `iam:GetRole` 
+  `iam:ListAttachedRolePolicies` 
+  `iam:ListInstanceProfilesForRole` 
+  `iam:ListRolePolicies` 
+  `iam:ListRoles` 
+  `iam:RemoveRoleFromInstanceProfile` 

 **Document Steps** 
+  `aws:executeScript` - Gathers the name of the IAM role you specify in the `IAMRoleID` parameter. 
+  `aws:executeScript` - Gathers policies and instance profiles associated with the IAM role. 
+  `aws:executeScript` - Deletes attached policies. 
+  `aws:executeScript` - Deletes the IAM role and verifies the role has been deleted. 

# `AWSConfigRemediation-DeleteIAMUser`
<a name="automation-aws-delete-iam-user"></a>

 **Description** 

 The `AWSConfigRemediation-DeleteIAMUser` runbook deletes the AWS Identity and Access Management (IAM) user you specify. This automation deletes or detaches the following resources associated with the IAM user: 
+ Access keys
+ Attached managed policies
+ Git credentials
+ IAM group memberships
+ IAM user password
+ Inline policies
+ Multi-factor authentication (MFA) devices
+ Signing certificates
+ SSH public keys

 [Run this Automation (console)](https://console.aws.amazon.com/systems-manager/automation/execute/AWSConfigRemediation-DeleteIAMUser) 

**Document type**

Automation

**Owner**

Amazon

**Platforms**

Linux, macOS, Windows

**Parameters**
+ AutomationAssumeRole

  Type: String

  Description: (Required) The Amazon Resource Name (ARN) of the AWS Identity and Access Management (IAM) role that allows Systems Manager Automation to perform the actions on your behalf.
+ IAMUserId

  Type: String

  Description: (Required) The ID of the IAM user you want to delete.

**Required IAM permissions**

The `AutomationAssumeRole` parameter requires the following actions to use the runbook successfully.
+  `ssm:StartAutomationExecution` 
+  `ssm:GetAutomationExecution` 
+  `iam:DeactivateMFADevice` 
+  `iam:DeleteAccessKey` 
+  `iam:DeleteLoginProfile` 
+  `iam:DeleteServiceSpecificCredential` 
+  `iam:DeleteSigningCertificate` 
+  `iam:DeleteSSHPublicKey` 
+  `iam:DeleteVirtualMFADevice` 
+  `iam:DeleteUser` 
+  `iam:DeleteUserPolicy` 
+  `iam:DetachUserPolicy` 
+  `iam:GetUser` 
+  `iam:ListAttachedUserPolicies` 
+  `iam:ListAccessKeys` 
+  `iam:ListGroupsForUser` 
+  `iam:ListMFADevices` 
+  `iam:ListServiceSpecificCredentials` 
+  `iam:ListSigningCertificates` 
+  `iam:ListSSHPublicKeys` 
+  `iam:ListUserPolicies` 
+  `iam:ListUsers` 
+  `iam:RemoveUserFromGroup` 

 **Document Steps** 
+  `aws:executeScript` - Gathers the user name of the IAM user you specify in the `IAMUserId` parameter. 
+  `aws:executeScript` - Gathers access keys, certificates, credentials, MFA devices, and SSH keys associated with the IAM user. 
+  `aws:executeScript` - Gathers group memberships and policies for the IAM user. 
+  `aws:executeScript` - Deletes access keys, certificates, credentials, MFA devices, and SSH keys associated with the IAM user. 
+  `aws:executeScript` - Deletes group memberships and policies for the IAM user. 
+  `aws:executeScript` - Deletes the IAM user and verifies the user has been deleted. 

# `AWSConfigRemediation-DeleteUnusedIAMGroup`
<a name="automation-aws-delete-iam-group"></a>

 **Description** 

 The `AWSConfigRemediation-DeleteUnusedIAMGroup` runbook deletes an IAM group that does not contain any users. 

 The `AWSConfigRemediation-DeleteUnusedIAMGroup` runbook deletes an IAM group that does not contain any users. 

 [Run this Automation (console)](https://console.aws.amazon.com/systems-manager/automation/execute/AWSConfigRemediation-DeleteUnusedIAMGroup) 

**Document type**

Automation

**Owner**

Amazon

**Platforms**

Linux, macOS, Windows

**Parameters**
+ AutomationAssumeRole

  Type: String

  Description: (Required) The Amazon Resource Name (ARN) of the AWS Identity and Access Management (IAM) role that allows Systems Manager Automation to perform the actions on your behalf.
+ GroupName

  Type: String

  Description: (Required) The name of the IAM group that you want to delete.

**Required IAM permissions**

The `AutomationAssumeRole` parameter requires the following actions to use the runbook successfully.
+  `ssm:StartAutomationExecution` 
+  `ssm:GetAutomationExecution` 
+  `iam:DeleteGroup` 
+  `iam:DeleteGroupPolicy` 
+  `iam:DetachGroupPolicy` 

 **Document Steps** 
+  `aws:executeScript` - Removes managed and inline IAM policies attached to the target IAM group, and then deletes the IAM group. 

# `AWSConfigRemediation-DeleteUnusedIAMPolicy`
<a name="automation-aws-delete-iam-policy"></a>

 **Description** 

 The `AWSConfigRemediation-DeleteUnusedIAMPolicy` runbook deletes an AWS Identity and Access Management (IAM) policy that is not attached to any users, groups, or roles. 

 [Run this Automation (console)](https://console.aws.amazon.com/systems-manager/automation/execute/AWSConfigRemediation-DeleteUnusedIAMPolicy) 

**Document type**

Automation

**Owner**

Amazon

**Platforms**

Linux, macOS, Windows

**Parameters**
+ AutomationAssumeRole

  Type: String

  Description: (Required) The Amazon Resource Name (ARN) of the AWS Identity and Access Management (IAM) role that allows Systems Manager Automation to perform the actions on your behalf.
+ IAMResourceId

  Type: String

  Description: (Required) The resource identifier of the IAM policy that you want to delete.

**Required IAM permissions**

The `AutomationAssumeRole` parameter requires the following actions to use the runbook successfully.
+  `ssm:StartAutomationExecution` 
+  `ssm:GetAutomationExecution` 
+  `config:GetResourceConfigHistory` 
+  `config:ListDiscoveredResources` 
+  `iam:DeletePolicy` 
+  `iam:DeletePolicyVersion` 
+  `iam:GetPolicy` 
+  `iam:ListEntitiesForPolicy` 
+  `iam:ListPolicyVersions` 

 **Document Steps** 
+  `aws:executeScript` - Deletes the policy you specify in the `IAMResourceId` parameter, and verifies the policy was deleted. 

# `AWSConfigRemediation-DetachIAMPolicy`
<a name="automation-aws-detach-iam-policy"></a>

 **Description** 

 The `AWSConfigRemediation-DetachIAMPolicy` runbook detaches the AWS Identity and Access Management (IAM) policy you specify. 

 [Run this Automation (console)](https://console.aws.amazon.com/systems-manager/automation/execute/AWSConfigRemediation-DetachIAMPolicy) 

**Document type**

Automation

**Owner**

Amazon

**Platforms**

Linux, macOS, Windows

**Parameters**
+ AutomationAssumeRole

  Type: String

  Description: (Required) The Amazon Resource Name (ARN) of the AWS Identity and Access Management (IAM) role that allows Systems Manager Automation to perform the actions on your behalf.
+ IAMResourceId

  Type: String

  Description: (Required) The ID of the IAM policy you want to detach.

**Required IAM permissions**

The `AutomationAssumeRole` parameter requires the following actions to use the runbook successfully.
+  `ssm:StartAutomationExecution` 
+  `ssm:GetAutomationExecution` 
+  `config:GetResourceConfigHistory` 
+  `config:ListDiscoveredResources` 
+  `iam:DetachGroupPolicy` 
+  `iam:DetachRolePolicy` 
+  `iam:DetachUserPolicy` 
+  `iam:GetPolicy` 
+  `iam:ListEntitiesForPolicy` 

 **Document Steps** 
+  `aws:executeScript` - Detaches the IAM policy from all resources. 

# `AWSConfigRemediation-EnableAccountAccessAnalyzer`
<a name="automation-aws-enable-account-access-analyzer"></a>

 **Description** 

 The `AWSConfigRemediation-EnableAccountAccessAnalyzer` runbook creates an AWS Identity and Access Management (IAM) Access Analyzer in your AWS account. For information about Access Analyzer, see [Using AWS IAM Access Analyzer](https://docs.aws.amazon.com/IAM/latest/UserGuide/what-is-access-analyzer.html) in the *IAM User Guide* . 

 [Run this Automation (console)](https://console.aws.amazon.com/systems-manager/automation/execute/AWSConfigRemediation-EnableAccountAccessAnalyzer) 

**Document type**

Automation

**Owner**

Amazon

**Platforms**

Linux, macOS, Windows

**Parameters**
+ AnalyzerName

  Type: String

  Description: (Required) The name of the analyzer to create.
+ AutomationAssumeRole

  Type: String

  Description: (Required) The Amazon Resource Name (ARN) of the AWS Identity and Access Management (IAM) role that allows Systems Manager Automation to perform the actions on your behalf.

**Required IAM permissions**

The `AutomationAssumeRole` parameter requires the following actions to use the runbook successfully.
+  `ssm:StartAutomationExecution` 
+  `ssm:GetAutomationExecution` 
+  `access-analyzer:CreateAnalyzer` 
+  `access-analyzer:GetAnalyzer` 

 **Document Steps** 
+  `aws:executeAwsApi` - Creates an access analyzer for your account. 
+  `aws:waitForAwsResourceProperty` - Waits for the status of the access analyzer to be `ACTIVE` . 
+  `aws:assertAwsResourceProperty` - Confirms the status of the access analyzer is `ACTIVE` . 

# `AWSSupport-GrantPermissionsToIAMUser`
<a name="automation-awssupport-grantpermissionstoiamuser"></a>

 **Description** 

 This runbook grants the specified permissions to an IAM group (new or existing), and adds the existing IAM user to it. Policies you can choose from: [Billing](https://console.aws.amazon.com/iam/home?#/policies/arn:aws:iam::aws:policy/job-function/Billing$serviceLevelSummary) or [Support](https://console.aws.amazon.com/iam/home?#/policies/arn:aws:iam::aws:policy/AWSSupportAccess$serviceLevelSummary) . To enable billing access for IAM, remember to also activate [IAM user and federated user access to the Billing and Cost Management pages](https://docs.aws.amazon.com/console/iam/billing-enable) . 

**Important**  
If you provide an existing IAM group, all current IAM users in the group receive the new permissions.

 [Run this Automation (console)](https://console.aws.amazon.com/systems-manager/automation/execute/AWSSupport-GrantPermissionsToIAMUser) 

**Document type**

Automation

**Owner**

Amazon

**Platforms**

Linux, macOS, Windows

**Parameters**
+ AutomationAssumeRole

  Type: String

  Description: (Optional) The Amazon Resource Name (ARN) of the AWS Identity and Access Management (IAM) role that allows Systems Manager Automation to perform the actions on your behalf. If no role is specified, Systems Manager Automation uses the permissions of the user that starts this runbook.
+ IAMGroupName

  Type: String

  Default: ExampleSupportAndBillingGroup

   Description: (Required) Can be a new or existing group. Must comply with [IAM Entity Name Limits](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_iam-limits.html#reference_iam-limits-names) . 
+ IAMUserName

  Type: String

  Default: ExampleUser

  Description: (Required) Must be an existing user.
+ LambdaAssumeRole

  Type: String

  Description: (Optional) The ARN of the role assumed by lambda.
+ Permissions

  Type: String

  Valid values: SupportFullAccess \$1 BillingFullAccess \$1 SupportAndBillingFullAccess

  Default: SupportAndBillingFullAccess

   Description: (Required) Choose one of: `SupportFullAccess` grants full access to the Support center. `BillingFullAccess` grants full access to the Billing dashboard. `SupportAndBillingFullAccess` grants full access to both Support center and the Billing dashboard. More info on policies under Document details. 

**Required IAM permissions**

The `AutomationAssumeRole` parameter requires the following actions to use the runbook successfully.

 The permissions required depend on how `AWSSupport-GrantPermissionsToIAMUser` is run. 

 **Running as the currently logged in user or role** 

 It is recommended you have the `AmazonSSMAutomationRole` Amazon managed policy attached, and the following additional permissions to be able to create the Lambda function and the IAM role to pass to Lambda: 

------
#### [ JSON ]

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Action": [
                "lambda:InvokeFunction",
                "lambda:CreateFunction",
                "lambda:DeleteFunction",
                "lambda:GetFunction"
            ],
            "Resource": "arn:aws:lambda:*:111122223333:function:AWSSupport-*",
            "Effect": "Allow"
        },
        {
            "Effect": "Allow",
            "Action": [
                "iam:CreateGroup",
                "iam:AddUserToGroup",
                "iam:ListAttachedGroupPolicies",
                "iam:GetGroup",
                "iam:GetUser"
            ],
            "Resource": [
                "arn:aws:iam::*:user/*",
                "arn:aws:iam::*:group/*"
            ]
        },
        {
            "Effect": "Allow",
            "Action": [
                "iam:AttachGroupPolicy"
            ],
            "Resource": "*",
            "Condition": {
                "ArnEquals": {
                    "iam:PolicyArn": [
                        "arn:aws:iam::aws:policy/job-function/Billing",
                        "arn:aws:iam::aws:policy/AWSSupportAccess"
                    ]
                }
            }
        },
        {
            "Effect": "Allow",
            "Action": [
                "iam:ListAccountAliases",
                "iam:GetAccountSummary"
            ],
            "Resource": "*"
        }
    ]
}
```

------

 **Using AutomationAssumeRole and LambdaAssumeRole** 

 The user must have the **ssm:StartAutomationExecution** permissions on the runbook, and **iam:PassRole** on the IAM roles passed as **AutomationAssumeRole** and **LambdaAssumeRole** . Here are the permissions each IAM role needs: 

```
AutomationAssumeRole

                    {
                        "Version": "2012-10-17",		 	 	 
                        "Statement": [
                            {
                                "Action": [
                                    "lambda:InvokeFunction",
                                    "lambda:CreateFunction",
                                    "lambda:DeleteFunction",
                                    "lambda:GetFunction"
                                ],
                                "Resource": "arn:aws:lambda:*:ACCOUNTID:function:AWSSupport-*",
                                "Effect": "Allow"
                            }
                        ]
                    }
```

```
LambdaAssumeRole

                {
                    "Version": "2012-10-17",		 	 	 
                    "Statement": [
                        {
                            "Effect" : "Allow",
                            "Action" : [
                                "iam:CreateGroup",
                                "iam:AddUserToGroup",
                                "iam:ListAttachedGroupPolicies",
                                "iam:GetGroup",
                                "iam:GetUser"
                            ],
                            "Resource" : [
                                "arn:aws:iam::*:user/*",
                                "arn:aws:iam::*:group/*"
                            ]
                        },
                        {
                            "Effect" : "Allow",
                            "Action" : [
                                "iam:AttachGroupPolicy"
                            ],
                            "Resource": "*",
                            "Condition": {
                                "ArnEquals": {
                                    "iam:PolicyArn": [
                                        "arn:aws:iam::aws:policy/job-function/Billing",
                                        "arn:aws:iam::aws:policy/AWSSupportAccess"
                                    ]
                                }
                            }
                        },
                        {
                            "Effect" : "Allow",
                            "Action" : [
                                "iam:ListAccountAliases",
                                "iam:GetAccountSummary"
                            ],
                            "Resource" : "*"
                        }
                    ]
                }
```

 **Document Steps** 

1.  `aws:createStack` - Run CloudFormation Template to create a Lambda function. 

1.  `aws:invokeLambdaFunction` - Run Lambda to set IAM permissions. 

1.  `aws:deleteStack` - Delete CloudFormation Template. 

 **Outputs** 

configureIAM.Payload

# `AWSConfigRemediation-RemoveUserPolicies`
<a name="automation-aws-remove-user-policies"></a>

 **Description** 

 The `AWSConfigRemediation-RemoveUserPolicies` runbook deletes the AWS Identity and Access Management (IAM) inline policies and detaches any managed policies attached to the user you specify. 

 [Run this Automation (console)](https://console.aws.amazon.com/systems-manager/automation/execute/AWSConfigRemediation-RemoveUserPolicies) 

**Document type**

Automation

**Owner**

Amazon

**Platforms**

Linux, macOS, Windows

**Parameters**
+ AutomationAssumeRole

  Type: String

  Description: (Required) The Amazon Resource Name (ARN) of the AWS Identity and Access Management (IAM) role that allows Systems Manager Automation to perform the actions on your behalf.
+ IAMUserID

  Type: String

  Description: (Required) The ID of the user you want to remove policies from.
+ PolicyType

  Type: String

  Valid values: All \$1 Inline \$1 Managed

  Default: All

  Description: (Required) The type of IAM policies you want to remove from the user.

**Required IAM permissions**

The `AutomationAssumeRole` parameter requires the following actions to use the runbook successfully.
+  `ssm:StartAutomationExecution` 
+  `ssm:GetAutomationExecution` 
+  `iam:DeleteUserPolicy` 
+  `iam:DetachUserPolicy` 
+  `iam:ListAttachedUserPolicies` 
+  `iam:ListUserPolicies` 
+  `iam:ListUsers` 

 **Document Steps** 
+  `aws:executeScript` - Deletes and detaches IAM policies from the user you specify in the `IAMUserID` parameter. 

# `AWSConfigRemediation-ReplaceIAMInlinePolicy`
<a name="automation-aws-replace-iam-policy"></a>

 **Description** 

 The `AWSConfigRemediation-ReplaceIAMInlinePolicy` runbook replaces an inline AWS Identity and Access Management (IAM) policy with a replicated managed IAM policy. For an inline policy attached to a user, group, or role, the inline policy permissions are cloned into a managed IAM policy. The managed IAM policy is added to the resource, and the inline policy is removed. AWS Config must be enabled in the AWS Region where you run this automation. 

 [Run this Automation (console)](https://console.aws.amazon.com/systems-manager/automation/execute/AWSConfigRemediation-ReplaceIAMInlinePolicy) 

**Document type**

Automation

**Owner**

Amazon

**Platforms**

Linux, macOS, Windows

**Parameters**
+ AutomationAssumeRole

  Type: String

  Description: (Required) The Amazon Resource Name (ARN) of the AWS Identity and Access Management (IAM) role that allows Systems Manager Automation to perform the actions on your behalf.
+ InlinePolicyName

  Type: StringList

  Description: (Required) The inline IAM policy you want to replace.
+ ResourceId

  Type: String

  Description: (Required) The ID of the IAM user, group, or role whose inline policy you want to replace.

**Required IAM permissions**

The `AutomationAssumeRole` parameter requires the following actions to use the runbook successfully.
+  `ssm:StartAutomationExecution` 
+  `ssm:GetAutomationExecution` 
+  `iam:AttachGroupPolicy` 
+  `iam:AttachRolePolicy` 
+  `iam:AttachUserPolicy` 
+  `iam:CreatePolicy` 
+  `iam:CreatePolicyVersion` 
+  `iam:DeleteGroupPolicy` 
+  `iam:DeleteRolePolicy` 
+  `iam:DeleteUserPolicy` 
+  `iam:GetGroupPolicy` 
+  `iam:GetRolePolicy` 
+  `iam:GetUserPolicy` 
+  `iam:ListGroupPolicies` 
+  `iam:ListRolePolicies` 
+  `iam:ListUserPolicies` 

 **Document Steps** 
+  `aws:executeScript` - Replace the inline IAM policy with an AWS replicated policy on the resource that you specify. 

# `AWSConfigRemediation-RevokeUnusedIAMUserCredentials`
<a name="automation-aws-revoke-iam-user"></a>

 **Description** 

 The `AWSConfigRemediation-RevokeUnusedIAMUserCredentials` runbook revokes unused AWS Identity and Access Management (IAM) passwords and active access keys. This runbook also deactivates expired access keys, and deletes expired login profiles. AWS Config must be enabled in the AWS Region where you run this automation. 

 [Run this Automation (console)](https://console.aws.amazon.com/systems-manager/automation/execute/AWSConfigRemediation-RevokeUnusedIAMUserCredentials) 

**Document type**

Automation

**Owner**

Amazon

**Platforms**

Linux, macOS, Windows

**Parameters**
+ AutomationAssumeRole

  Type: String

  Description: (Required) The Amazon Resource Name (ARN) of the AWS Identity and Access Management (IAM) role that allows Systems Manager Automation to perform the actions on your behalf.
+ IAMResourceId

  Type: String

  Description: (Required) The ID of the IAM resource you want to revoke unused credentials from.
+ MaxCredentialUsageAge

  Type: String

  Default: 90

  Description: (Required) The number of days within which the credential must have been used.

**Required IAM permissions**

The `AutomationAssumeRole` parameter requires the following actions to use the runbook successfully.
+  `ssm:StartAutomationExecution` 
+  `ssm:GetAutomationExecution` 
+  `config:ListDiscoveredResources` 
+  `iam:DeleteAccessKey` 
+  `iam:DeleteLoginProfile` 
+  `iam:GetAccessKeyLastUsed` 
+  `iam:GetLoginProfile` 
+  `iam:GetUser` 
+  `iam:ListAccessKeys` 
+  `iam:UpdateAccessKey` 

 **Document Steps** 
+  `aws:executeScript` - Revokes IAM credentials for the user specified in the `IAMResourceId` parameter. Expired access keys are deactivated, and expired login profiles are deleted. 

**Note**  
Make sure to configure the `MaxCredentialUsageAge`parameter of this remediation action to match the `maxAccessKeyAge` parameter of the AWS Config rule you use to trigger this action: [access-keys-rotated](https://docs.aws.amazon.com/config/latest/developerguide/access-keys-rotated.html).

# `AWSConfigRemediation-SetIAMPasswordPolicy`
<a name="automation-aws-set-iam-policy"></a>

 **Description** 

 The `AWSConfigRemediation-SetIAMPasswordPolicy` runbook sets the AWS Identity and Access Management (IAM) user password policy for your AWS account. 

 [Run this Automation (console)](https://console.aws.amazon.com/systems-manager/automation/execute/AWSConfigRemediation-SetIAMPasswordPolicy) 

**Document type**

Automation

**Owner**

Amazon

**Platforms**

Linux, macOS, Windows

**Parameters**
+ AutomationAssumeRole

  Type: String

  Description: (Required) The Amazon Resource Name (ARN) of the AWS Identity and Access Management (IAM) role that allows Systems Manager Automation to perform the actions on your behalf.
+ AllowUsersToChangePassword

  Type: Boolean

  Default: false

   Description: (Optional) If set to `true` , all IAM users in your AWS account can use the AWS Management Console to change their passwords. 
+ HardExpiry

  Type: Boolean

  Default: false

   Description: (Optional) If set to `true` , IAM users are prevented from resetting their passwords after their password expires. 
+ MaxPasswordAge

  Type: Integer

  Default: 0

  Description: (Optional) The number of days an IAM user's password is valid.
+ MinimumPasswordLength

  Type: Integer

  Default: 6

  Description: (Optional) The minimum number of characters an IAM user's password can be.
+ PasswordReusePrevention

  Type: Integer

  Default: 0

  Description: (Optional) The number of previous passwords that an IAM user is prevented from reusing.
+ RequireLowercaseCharacters

  Type: Boolean

  Default: false

   Description: (Optional) If set to `true` , an IAM user's password must contain a lowercase character from the ISO basic Latin alphabet (a to z). 
+ RequireNumbers

  Type: Boolean

  Default: false

   Description: (Optional) If set to `true` , an IAM user's password must contain a numeric character (0-9). 
+ RequireSymbols

  Type: Boolean

  Default: false

   Description: (Optional) If set to `true` , an IAM user's password must contain a non-alphanumeric character (\$1 @ \$1 \$1 % ^ \$1 ( ) \$1 \$1 - = [ ] \$1 \$1 \$1 '). 
+ RequireUppercaseCharacters

  Type: Boolean

  Default: false

   Description: (Optional) If set to `true` , an IAM user's password must contain an uppercase character from the ISO basic Latin alphabet (A to Z). 

**Required IAM permissions**

The `AutomationAssumeRole` parameter requires the following actions to use the runbook successfully.
+  `ssm:StartAutomationExecution` 
+  `ssm:GetAutomationExecution` 
+  `iam:GetAccountPasswordPolicy` 
+  `iam:UpdateAccountPasswordPolicy` 

 **Document Steps** 
+  `aws:executeScript` - Sets the IAM user password policy based on the values you specify for the runbook parameters for your AWS account. 

# `AWSSupport-ContainIAMPrincipal`
<a name="awssupport-contain-iam-principal"></a>

 **Description** 

In the event of a security incident or a suspected compromise of an AWS Identity and Access Management (IAM) User/Role or AWS Identity Center (IDC) user, swift isolation of the affected identity is crucial while preserving its configuration for investigation. The `AWSSupport-ContainIAMPrincipal` runbook provides a structured, reversible approach to contain compromised IAM or IDC identities, effectively blocking their access to AWS resources and preventing potential spread of the compromise.

This automated process enables investigation without permanent alteration of the identity's configuration, allowing for restoration of normal access when deemed appropriate. The containment process maintains the user or role within IAM or the user within IDC, while effectively isolating it from all network activities. This isolation prevents the contained identity resource from communicating with resources inside your Amazon Virtual Private Cloud or accessing internet resources. The containment is designed to be reversible, allowing for restoration of normal access when deemed appropriate.

 **How does it work?** 

The `AWSSupport-ContainIAMPrincipal` runbook implements a comprehensive containment process for IAM users, roles, and Identity Center users. When executed in `Contain` mode, it first validates all input parameters and performs security checks on the specified Amazon S3 bucket. It then gathers detailed information about the target IAM principal and applies appropriate containment measures based on the principal type. For IAM users, it disables access keys, removes console access, and attaches a deny policy. For IAM roles, it attaches a deny policy that revokes permissions for sessions created before containment. For Identity Center users, it removes permission sets, group memberships, and applies a deny policy. Throughout the process, the runbook backs up the original configuration to an Amazon S3 bucket for potential restoration. When executed in `Restore` mode, it attempts to revert the principal to its pre-containment state using the backed-up configuration. The runbook includes a `DryRun` option to preview changes without applying them, and provides comprehensive reporting on both successful operations and failure scenarios.

**Important**  
**Use of Elevated Privileges:** This SSM document performs various operations that require elevated privileges, such as modifying IAM and IDC identity policies and applying quarantine configurations. These actions could potentially lead to a privilege escalation or impact other workloads that depend on the targeted identities. You should review the permissions granted to the role specified by the `AutomationAssumeRole` parameter and ensure they are appropriate for the intended use case. You can refer to the following AWS documentation for more information on IAM permissions:   
[Identity and Access Management (IAM) Permissions](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_permissions.html)
[AWS Systems Manager Automation Permissions](https://docs.aws.amazon.com/systems-manager/latest/userguide/automation-permissions.html)
**Workload Unavailability Risks:** This Systems Manager document performs isolation actions that could potentially cause unavailability or disruption to your workloads. When executed during a security event, it will restrict access to the affected resource by revoking AWS API permissions from the specified IAM and IDC identities, preventing them from making any AWS API calls or actions. This could impact any applications or services that depend on these identities.
**Creation of Additional Resources:** The automation document may conditionally create additional resources, such as an Amazon Simple Storage Service (Amazon S3) bucket and Amazon S3 objects stored in them, depending on the execution parameters. These resources will incur additional charges based on your AWS usage.
**Restoration Risks:** If the *Action* parameter is set to `Restore`, this SSM document attempts to restore the IAM or IDC identity configuration to its original state. However, there is a risk that the restoration process may fail, leaving the IAM or IDC identity in an inconsistent state. The document provides instructions for manual restoration in case of such failures, but you should be prepared to handle potential issues during the restoration process.
It is recommended to review the runbook thoroughly, understand its potential impacts, and test it in a non-production environment before executing it in your production environment.

 [Run this Automation (console)](https://console.aws.amazon.com/systems-manager/automation/execute/AWSSupport-ContainIAMPrincipal) 

**Document type**

Automation

**Owner**

Amazon

**Platforms**

/

 **Required IAM permissions** 

The `AutomationAssumeRole` parameter requires the following permissions to successfully use the runbook:
+ s3:GetBucketLocation
+ s3:GetBucket
+ s3:ListBucket
+ s3:GetBucketPublicAccessBlocks
+ s3:GetAccountPublicAccessBlocks
+ s3:GetBucketPolicyStatus
+ s3:GetBucketAcl
+ s3:GetObject
+ s3:CreateBucket
+ s3:PutObject
+ iam:GetUser
+ iam:GetUserPolicy
+ iam:GetRole
+ iam:ListUserPolicies
+ iam:ListAttachedUserPolicies
+ iam:ListAccessKeys
+ iam:ListMfaDevices
+ iam:ListVirtualMFADevices
+ iam:GetLoginProfile
+ iam:GetPolicy
+ iam:GetRolePolicy
+ iam:ListPolicies
+ iam:ListAttachedRolePolicies
+ iam:ListRolePolicies
+ iam:UpdateAccessKey
+ iam:CreateAccessKey
+ iam:DeleteLoginProfile
+ iam:DeleteAccessKey
+ iam:PutUserPolicy
+ iam:DeleteUserPolicy
+ iam:DeactivateMFADevice
+ iam:AttachRolePolicy
+ iam:AttachUserPolicy
+ iam:DeleteRolePolicy
+ iam:TagMFADevice
+ iam:PutRolePolicy
+ iam:TagPolicy
+ iam:TagRole
+ iam:TagUser
+ iam:UntagUser
+ iam:UntagRole
+ organizations:ListAccounts
+ sso:ListPermissionSetsProvisionedToAccount
+ sso:GetInlinePolicyForPermissionSet
+ sso:ListInstances
+ sso-directory:SearchUsers
+ sso:ListPermissionSets
+ sso:ListAccountAssignments
+ sso-directory:DescribeUser
+ identitystore:ListUsers
+ identitystore:ListGroups
+ identitystore:IsMemberInGroups
+ identitystore:ListGroupMemberships
+ secretsmanager:CreateSecret
+ secretsmanager:DeleteSecret
+ sso:DeleteAccountAssignment
+ sso:PutInlinePolicyToPermissionSet
+ sso:CreateAccountAssignment
+ sso:DeleteInlinePolicyFromPermissionSet
+ sso:TagResource
+ sso:UntagResource
+ identitystore:DeleteGroupMembership
+ identitystore:CreateGroupMembership

 Here is an example of an IAM policy that grants the necessary permissions for the `AutomationAssumeRole`: 

------
#### [ JSON ]

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Sid": "S3Permissions",
            "Effect": "Allow",
            "Action": [
                "s3:GetBucketLocation",
                "s3:ListBucket",
                "s3:GetBucketPublicAccessBlock",
                "s3:GetBucketPolicyStatus",
                "s3:GetBucketAcl",
                "s3:GetObject",
                "s3:CreateBucket",
                "s3:PutObject"
            ],
            "Resource": "*"
        },
        {
            "Sid": "IAMPermissions",
            "Effect": "Allow",
            "Action": [
                "iam:GetUser",
                "iam:GetUserPolicy",
                "iam:GetRole",
                "iam:ListUserPolicies",
                "iam:ListAttachedUserPolicies",
                "iam:ListAccessKeys",
                "iam:ListMfaDevices",
                "iam:ListVirtualMFADevices",
                "iam:GetLoginProfile",
                "iam:GetPolicy",
                "iam:GetRolePolicy",
                "iam:ListPolicies",
                "iam:ListAttachedRolePolicies",
                "iam:ListRolePolicies",
                "iam:UpdateAccessKey",
                "iam:CreateAccessKey",
                "iam:DeleteLoginProfile",
                "iam:DeleteAccessKey",
                "iam:PutUserPolicy",
                "iam:DeleteUserPolicy",
                "iam:DeactivateMFADevice",
                "iam:AttachRolePolicy",
                "iam:AttachUserPolicy",
                "iam:DeleteRolePolicy",
                "iam:TagMFADevice",
                "iam:PutRolePolicy",
                "iam:TagPolicy",
                "iam:TagRole",
                "iam:TagUser",
                "iam:UntagUser",
                "iam:UntagRole"
            ],
            "Resource": "*"
        },
        {
            "Sid": "OrganizationsPermissions",
            "Effect": "Allow",
            "Action": [
                "organizations:ListAccounts"
            ],
            "Resource": "*"
        },
        {
            "Sid": "SSOPermissions",
            "Effect": "Allow",
            "Action": [
                "sso:ListPermissionSetsProvisionedToAccount",
                "sso:GetInlinePolicyForPermissionSet",
                "sso:ListInstances",
                "sso-directory:SearchUsers",
                "sso:ListPermissionSets",
                "sso:ListAccountAssignments",
                "sso-directory:DescribeUser",
                "sso:DeleteAccountAssignment",
                "sso:PutInlinePolicyToPermissionSet",
                "sso:CreateAccountAssignment",
                "sso:DeleteInlinePolicyFromPermissionSet",
                "sso:TagResource",
                "sso:UntagResource"
            ],
            "Resource": "*"
        },
        {
            "Sid": "IdentityStorePermissions",
            "Effect": "Allow",
            "Action": [
                "identitystore:ListUsers",
                "identitystore:ListGroups",
                "identitystore:IsMemberInGroups",
                "identitystore:ListGroupMemberships",
                "identitystore:DeleteGroupMembership",
                "identitystore:CreateGroupMembership"
            ],
            "Resource": "*"
        },
        {
            "Sid": "SecretsManagerPermissions",
            "Effect": "Allow",
            "Action": [
                "secretsmanager:CreateSecret",
                "secretsmanager:DeleteSecret"
            ],
            "Resource": "*"
        }
    ]
}
```

------

 **Instructions** 

Follow these steps to configure the automation:

1. Navigate to the [AWSSupport-ContainIAMPrincipal](https://console.aws.amazon.com/systems-manager/documents/AWSSupport-ContainIAMPrincipal/description) in the AWS Systems Manager console.

1. Select **Execute automation.**

1. For the input parameters, enter the following:
   + **AutomationAssumeRole (Optional):**
     + Description: (Optional) The Amazon Resource Name (ARN) of the AWS Identity and Access Management (IAM) role that allows Systems Manager Automation to perform the actions on your behalf. If no role is specified, Systems Manager Automation uses the permissions of the user who starts this runbook.
     + Type: `AWS::IAM::Role::Arn`
   + **PrincipalType (Required):**
     + Description: (Required) The AWS IAM principal type: IAM user, IAM role, or Identity Center user.
     + Type: String
     + Allowed Values: `IAM user|IAM role|Identity Center user`
   + **PrincipalName (Required):**
     + Description: (Required) The name of the IAM principal. For Identity Center users, provide the username.
     + Type: String
     + Allowed Pattern: `^[a-zA-Z0-9\\.\\-_\\\\!*'()/+=,@]{1,1024}$`
   + **Action (Required):**
     + Description: (Required) Select `Contain` to isolate the target IAM principal or `Restore` to try to restore the IAM principal to its original configuration from a previous backup.
     + Type: String
     + Allowed Values: `Contain|Restore`
   + **DryRun (Optional):**
     + Description: (Optional) When set to `true`, the automation will not make any changes to the target IAM principal, instead it will output on what it would have attempted to change, detailing out on each step. Default value: `true`.
     + Type: Boolean
     + Allowed Values: `true|false`
   + **ActivateDisabledKeys (Conditional):**
     + Description: (Conditional) If the input parameter Action is set to `Restore` and the PrincipalType is set to IAM user, this option determines if this automation should try to activate the associated access keys if deactivated. Please note that the integrity of a compromised access key cannot be verified. AWS strongly recommends against reactivating a compromised key. Instead, it is advisable to generate new keys. Default value: `false`.
     + Type: Boolean
     + Allowed Values: `true|false`
   + **BackupS3BucketName (Conditional):**
     + Description: (Conditional) The Amazon Amazon S3 bucket to backup the IAM principal configuration when the Action is set to `Contain` or to restore the configuration from when the Action is `Restore`. Note that if the specified Action is `Contain` and the runbook is not able to access the bucket or a value is not provided, a new bucket is created in your account with the name `awssupport-containiamprincipal-<random-string>`. If DryRun is set to `true` this parameter is required.
     + Type: `AWS::S3::Bucket::Name`
   + **BackupS3KeyName (Conditional):**
     + Description: (Conditional) If Action is set to `Restore`, this specifies the Amazon Amazon S3 key the automation will use to try to restore the IAM principal configuration. The Amazon Amazon S3 key typically follows this format: `{year}/{month}/{day}/{hour}/{minute}/{automation_execution_id}.json`. The key can be obtained from the output of a previous containment automation execution.
     + Type: String
     + Allowed Pattern: `^[a-zA-Z0-9\\.\\-_\\\\!*'()/]{0,1024}$`
   + **BackupS3BucketAccess (Conditional):**
     + Description: (Conditional) The ARN of the IAM users or roles that will be allowed access to the backup Amazon Amazon S3 bucket after running the containment actions. This parameter is required when Action is `Contain`. The AutomationAssumeRole, or in its absence the user under whose context the automation is running is automatically added to the list.
     + Type: StringList
     + Allowed Pattern: `^$|^arn:(aws|aws-cn|aws-us-gov|aws-iso(-[a-z])?):iam::[0-9]{12}:(role|user)\\/[\\w+\\/=,.@-]+$`
   + **TagIdentifier (Optional):**
     + Description: (Optional) Tag the IAM principal with a tag of your choice using the following format: `Key=<EXAMPLE_KEY>,Value=<EXAMPLE_VALUE>`. This option allows you to track the IAM principals that have been targeted by this runbook. **Note:** Tag keys and values are case-sensitive.
     + Type: String
     + Allowed Pattern: `^$|^[Kk][Ee][Yy]=[\\+\\-\\=\\.\\_\\:\\/@a-zA-Z0-9]{1,128},[Vv][Aa][Ll][Uu][Ee]=[\\+\\-\\=\\.\\_\\:\\/@a-zA-Z0-9]{0,128}$`

1. Select Execute.

1. The automation initiates.

1. The document performs the following steps:
   + **ValidateRequiredInputs**

     Validates the required automation input parameters based on the `Action` specified.
   + **CheckBackupS3BucketName**

     Checks if the target Amazon Amazon S3 bucket potentially grants `read` or `write` public access to its objects. In case of containment workflow, a new Amazon Amazon S3 bucket is created if the `BackupS3BucketName` bucket doesn't exist.
   + **BranchOnAction**

     Branches the automation based on the value of the specified `Action`.
   + **BranchOnPrincipalTypeAndDryRun**

     Branches the automation based on the type of IAM principal (IAM user, IAM role, or Identity Center user) and if it is running in `DryRun` mode.
   + **BranchOnPrincipalTypeForContain**

     Branches the automation for the `Contain` action based and the IAM principal type (IAM user, IAM role, or Identity Center user) specified in the input.
   + **GetIAMUser**

     Gets the creation time and username of the target IAM user.
   + **GetIAMUserDetails**

     Gets and stores the configuration of the target IAM user, including inline policies, managed policies, access keys, MFA devices, and login profile.
   + **UpdateS3KeyForUser**

     Updates the automation 'S3Key' variable from output of the step `GetIAMUserDetails`.
   + **GetIAMRole**

     Gets the creation time, role name, and path of the target IAM role.
   + **GetIAMRoleDetails**

     Gets and stores the configuration of the target IAM role, including inline policies and managed policies attached to the role.
   + **UpdateS3KeyForRole**

     Updates the automation 'S3Key' variable from output of the step `GetIAMRoleDetails`.
   + **GetIdentityStoreId**

     Gets the ID of the AWS IAM Identity Center instance associated with the AWS account.
   + **GetIDCUser**

     Gets the user ID of the target Identity Center user using the Identity Store ID.
   + **GatherIDCUserDetails**

     Gets and stores the configuration of the target Identity Center user, including account assignments, associated permission sets, and inline policies.
   + **UpdateS3KeyForIDCUser**

     Updates the automation 'S3Key' variable from output of the step `GatherIDCUserDetails`.
   + **BranchOnIdentityContain**

     Branches the automation based on the value of `DryRun` and the IAM principal type for the `Contain` action.
   + **BranchOnDisableAccessKeys**

     Branches the automation based on whether the IAM user has access keys that need to be disabled.
   + **DisableAccessKeys**

     Disables the active IAM user access keys.
   + **BranchOnDisableConsoleAccess**

     Branches based on whether the IAM user has AWS Management Console access enabled or not.
   + **DisableConsoleAccess**

     Removes the IAM user's password-based access to the AWS Management Console.
   + **AttachInlineDenyPolicyToUser**

     Attaches a deny policy to the IAM user to revoke permissions for older session tokens.
   + **AttachInlineDenyPolicyToRole**

     Attaches a deny policy to the IAM role to revoke permissions for older session tokens.
   + **RemovePermissionSets**

     Removes permission sets associated with the Identity Center user.
   + **RemoveIDCUserFromIDCGroups**

     Removes the Identity Center user from Identity Center groups.
   + **AttachInlineDenyPolicyToPermissionSet**

     Attaches a deny policy to the permission sets associated with the Identity Center user.
   + **BranchOnReactivateKeys**

     Branches the automation based on the `ActivateDisabledKeys` parameter during the restore process.
   + **DetachInlineDenyPolicy**

     Removes the deny policy attached to the IAM role during the containment process.
   + **DetachInlineDenyPolicyFromPermissionSet**

     Removes the deny policy attached to the permission sets during the containment process.
   + **ReportContain**

     Outputs detailed information about the containment actions that would be performed when `DryRun` is set to `True`.
   + **ReportRestore**

     Outputs detailed information about the restoration actions that would be performed when `DryRun` is set to `True`.
   + **ReportContainFailure**

     Provides comprehensive instructions to manually restore the IAM principal's original configuration during a containment workflow failure scenario.
   + **ReportRestoreFailure**

     Provides detailed instructions to manually complete the restoration of the IAM principal's original configuration during a restore workflow failure scenario.

1. After the execution completes, review the Outputs section for the detailed results of the execution:
   + **ContainIAMPrincipal.Output**

     Provides detailed information about the containment actions performed when Action is set to Contain and DryRun is set to False. Includes information about the backup location, applied deny policies, and modified configurations.
   + **RestoreIAMPrincipal.Output**

     Provides detailed information about the restoration actions performed when Action is set to Restore and DryRun is set to False. Includes information about the restored configurations and any issues encountered during restoration.
   + **ReportContain.Output**

     Outputs detailed information about the containment actions that would be performed when Action is set to Contain and DryRun is set to True. Includes a comparison of current and post-containment configurations.
   + **ReportRestore.Output**

     Outputs detailed information about the restoration actions that would be performed when Action is set to Restore and DryRun is set to True. Shows the current configuration and the original configuration that would be restored.
   + **ReportContainFailure.Output**

     Provides comprehensive instructions to manually restore the IAM principal's original configuration during a containment workflow failure scenario.
   + **ReportRestoreFailure.Output**

     Provides detailed instructions to manually complete the restoration of the IAM principal's original configuration during a restore workflow failure scenario.

 **Outputs** 

After the execution completes, review the Outputs section for the detailed results:
+ **ContainIAMPrincipal.Output**

  Provides detailed information about the containment actions performed when Action is set to Contain and DryRun is set to False. Includes information about the backup location, applied deny policies, and modified configurations.
+ **RestoreIAMPrincipal.Output**

  Provides detailed information about the restoration actions performed when Action is set to Restore and DryRun is set to False. Includes information about the restored configurations and any issues encountered during restoration.
+ **ReportContain.Output**

  Outputs detailed information about the containment actions that would be performed when Action is set to Contain and DryRun is set to True. Includes a comparison of current and post-containment configurations.
+ **ReportRestore.Output**

  Outputs detailed information about the restoration actions that would be performed when Action is set to Restore and DryRun is set to True. Shows the current configuration and the original configuration that would be restored.
+ **ReportContainFailure.Output**

  Provides comprehensive instructions to manually restore the IAM principal's original configuration during a containment workflow failure scenario.
+ **ReportRestoreFailure.Output**

  Provides detailed instructions to manually complete the restoration of the IAM principal's original configuration during a restore workflow failure scenario.

 **References** 

Systems Manager Automation
+ [Run this Automation (console)](https://console.aws.amazon.com/systems-manager/automation/execute/AWSSupport-ContainIAMPrincipal)
+ [Running a simple automation](https://docs.aws.amazon.com//systems-manager/latest/userguide/automation-working-executing.html)
+ [Setting up Automation](https://docs.aws.amazon.com//systems-manager/latest/userguide/automation-setup.html)
+ [Support Automation Workflows](https://aws.amazon.com/premiumsupport/technology/saw/)

# `AWSSupport-TroubleshootSAMLIssues`
<a name="awssupport-troubleshootsamlissues"></a>

 **Description** 

 The **AWSSupport-TroubleshootSAMLIssues ** automation runbook helps diagnose Security Assertion Markup Language (SAML) related issues by analyzing SAML response files stored in Amazon Simple Storage Service (Amazon S3). It performs comprehensive validation including schema verification, signature validation, audience restriction checking, and expiration time verification. The runbook decodes and extracts key SAML elements including issuer, assertions, subject, conditions, signatures, and attributes from the SAML response. For environments where SAML is used to access AWS resources (such as Amazon Connect or Amazon WorkSpaces Applications) through an IAM Identity Provider, it verifies whether the certificates in the SAML response signatures match the certificates configured in the IAM Identity Provider. 

 **How does it work?** 

 The runbook performs the following steps: 
+ Validates SAML response format and required elements.
+ Decodes and extracts SAML response components (issuer, assertions, subject, conditions, signatures, attributes).
+ Verifies digital signatures against IAM Identity Provider certificates when provided.
+ Checks audience restrictions and time validity.
+ Provides detailed diagnostic information showing the parsed SAML structure and validation results.

 [Run this Automation (console)](https://console.aws.amazon.com/systems-manager/automation/execute/AWSSupport-TroubleshootSAMLIssues) 

**Document type**

Automation

**Owner**

Amazon

**Platforms**

/

**Required IAM permissions**

The `AutomationAssumeRole` parameter requires the following actions to use the runbook successfully.
+ `s3:GetBucketLocation`
+ `s3:ListBucket`
+ `s3:GetBucketPublicAccessBlock`
+ `s3:GetAccountPublicAccessBlock`
+ `s3:GetObject`
+ `s3:GetBucketPolicyStatus`
+ `s3:GetEncryptionConfiguration`
+ `s3:GetBucketOwnershipControls`
+ `s3:GetBucketAcl`
+ `s3:GetBucketPolicy`
+ `s3:PutObject`
+ `iam:GetSAMLProvider`
+ `sts:AssumeRole`

Example Policy: 

------
#### [ JSON ]

****  

```
        {
            "Version":"2012-10-17",		 	 	 
            "Statement": [
                {
                    "Action": [
                        "s3:GetBucketLocation",
                        "s3:ListBucket",
                        "s3:GetBucketPublicAccessBlock",
                        "s3:GetAccountPublicAccessBlock",
                        "s3:GetObject",
                        "s3:GetBucketPolicyStatus",
                        "s3:GetEncryptionConfiguration",
                        "s3:GetBucketOwnershipControls",
                        "s3:GetBucketAcl",
                        "s3:GetBucketPolicy",
                        "s3:PutObject",
                        "iam:GetSAMLProvider",
                        "sts:AssumeRole"
                    ],
                    "Resource": "*",
                    "Effect": "Allow"
                }
            ]
        }
```

------

 **Instructions** 

Follow these steps to configure the automation:

1. Before using this runbook, you need to capture and store a Base64-encoded SAML response (txt file) in an S3 bucket. Instructions for capturing SAML responses can be found in [this document](https://docs.aws.amazon.com//IAM/latest/UserGuide/troubleshoot_saml_view-saml-response.html)

1. Navigate to [https://console.aws.amazon.com/systems-manager/documents/AWSSupport-TroubleshootSAMLIssues/description](https://console.aws.amazon.com/systems-manager/documents/AWSSupport-TroubleshootSAMLIssues/description) in Systems Manager under Documents.

1. Select **Execute automation.**

1. For the input parameters, enter the following:
   + **AutomationAssumeRole (Optional):**
     + Description: (Optional) The Amazon Resource Name (ARN) of the AWS Identity and Access Management (IAM) role that allows SSM Automation to perform the actions on your behalf. If no role is specified, Systems Manager Automation uses the permissions of the user that starts this runbook.
     + Type: `AWS::IAM::Role::Arn`
   + **InputFileS3URI (Required):**
     + Description: (Required) Amazon Simple Storage Service (Amazon S3) URI of SAML Response txt file (e.g., s3://bucket-name/path/to/file.txt).
     + Type: String
     + Allow Pattern: `^s3://[a-z0-9][a-z0-9.-][a-z0-9](/.)?$`
   + **S3OutputPrefix (Optional):**
     + Description: (Optional) The analysis output files are stored in the input bucket under the name 'saml\$1analysis\$1<executionID of the runbook>.json'. You can use this parameter if you want to output a file with a specific prefix. The default value is "output/", in which case the file URI that output the result will be 's3://bucket-name/output/saml\$1analysis\$1<executionID of the runbook>.json'.
     + Type: String
     + Allow Pattern: `^[a-zA-Z0-9+=,.@\\-_/]*/$`
   + **ExpectedAudience (Optional):**
     + Description: (Optional) Expected audience value in the SAML response. If not specified, we use `urn:amazon:webservices`. If you have configured a specific audience value in your IdP and SP setup, please provide the exact format (e.g., `urn:amazon:webservices`, `https://signin.aws.amazon.com/saml`).
     + Type: String
     + Default: urn:amazon:webservices
   + **IamIdProviderArn (Optional):**
     + Description: (Optional) If you are using an IAM ID Provider entity to directly link your IdP with AWS IAM, please provide its ARN (e.g., `arn:aws:iam::<account-id>:saml-provider/<provider-name>`).
     + Type: String
     + Allow Pattern: `^$|^arn:aws:iam::[0-9]{12}:saml-provider/[a-zA-Z0-9_-]+$`
   + **SAMLAuthenticationTime (Optional):**
     + Description: (Optional) The date and time when SAML authentication was performed. Timezone must be UTC. Must be in YYYY-MM-DDThh:mm:ss format (e.g., 2025-02-01T10:00:00). If this parameter is not provided, expiration checks will be performed against the current timestamp.
     + Type: String
     + Allow Pattern: `^$|^\\d{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[12]\\d|3[01])T(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d$`
   + **S3BucketOwnerRoleArn (Optional):**
     + Description: (Optional) IAM Role ARN to access the Amazon S3 buckets. The ARN of the IAM role with permissions to get the Amazon S3 bucket and account block public access settings, bucket encryption configuration, the bucket ACLs, the bucket policy status, and upload objects to the bucket. If this parameter is not specified, the runbook uses the `AutomationAssumeRole` (if specified) or user that starts this runbook (if `AutomationAssumeRole` is not specified).
     + Type: `AWS::IAM::Role::Arn`

1. Select **Execute**.

1. The automation initiates.

1. The document performs the following steps:
   + **ValidateIAMIDProvider**

     Validates the provided IAM ID Provider ARN by checking if it exists and is accessible. If no ARN is provided, the validation is skipped and the step completes successfully.
   + **CheckS3BucketPublicStatus**

     Checks if the Amazon S3 bucket allows anonymous, or public read or write access permissions. If the bucket allows these permissions, the automation stops at this step.
   + **CheckS3ObjectExistence**

     Validates access to the Amazon S3 buckets. Checks if the bucket and the object exist and if the automation has necessary permissions to read from source and write to destination.
   + **AnalyzeSAMLResponse**

     Analyzes the SAML response file by performing the checks (schema validation, signature verification, audience validation, expiration checking). Generates a detailed JSON report and saves it to the specified Amazon S3 location.

1. After completed, review the **Outputs** section for the detailed results of the execution:
   + **Outputs** section contains information about the Amazon S3 object where the analysis results are described.

1. The Amazon S3 object in the analysis results is a Json file containing the following information:
   + **validation\$1result**: contains basic validation results of the SAML response.
     + **saml\$1info**: key SAML information including issuer, signatures, and assertions.
     + **schema\$1validation**: results of SAML schema validation.
   + **verification\$1result**: provides more detailed diagnostic results.
     + **signature**: results of signature verification.
     + **audience**: results of audience restriction validation.
     + **expiration**: results of expiration time verification.

 **References** 

Systems Manager Automation
+ [Run this Automation (console)](https://console.aws.amazon.com/systems-manager/automation/execute/AWSSupport-TroubleshootSAMLIssues)
+ [Run an automation](https://docs.aws.amazon.com//systems-manager/latest/userguide/automation-working-executing.html)
+ [Setting up an Automation](https://docs.aws.amazon.com//systems-manager/latest/userguide/automation-setup.html)
+ [Support Automation Workflows landing page](https://aws.amazon.com/premiumsupport/technology/saw/)