fbpx

Use IAM Access Analyzer policy generation to grant fine-grained permissions for your AWS CloudFormation service roles

AWS Identity and Access Management (IAM) Access Analyzer provides tools to simplify permissions management by making it simpler for you to set, verify, and refine permissions. One such tool is IAM Access Analyzer policy generation, which creates fine-grained policies based on your AWS CloudTrail access activity—for example, the actions you use with Amazon Elastic Compute Cloud (Amazon EC2), AWS Lambda, and Amazon Simple Storage Service (Amazon S3). AWS has expanded policy generation capabilities to support the identification of actions used from over 140 services. New additions include services such as AWS CloudFormation, Amazon DynamoDB, and Amazon Simple Queue Service (Amazon SQS). When you request a policy, IAM Access Analyzer generates a policy by analyzing your CloudTrail logs to identify actions used from this group of over 140 services. The generated policy makes it efficient to grant only the required permissions for your workloads. For other services, Access Analyzer helps you by identifying the services used and guides you to add the necessary actions.

   <p>In this post, we will show how you can use Access Analyzer to generate an IAM permissions policy that restricts CloudFormation permissions to only those actions that are necessary to deploy a given template, in order to follow the principle of least privilege.</p> 
   <h2>Permissions for AWS CloudFormation</h2> 
   <p>AWS CloudFormation lets you create a collection of related AWS and third-party resources and provision them in a consistent and repeatable fashion. A common access management pattern is to grant developers permission to use CloudFormation to provision resources in the production environment and limit their ability to do so directly. This directs developers to make infrastructure changes in production through CloudFormation, using infrastructure-as-code patterns to manage the changes.</p> 
   <p>CloudFormation can create, update, and delete resources on the developer’s behalf by assuming an IAM role that has sufficient permissions. Cloud administrators often grant this IAM role broad permissions–in excess of what’s necessary to just create, update, and delete the resources from the developer’s template–because it’s not clear what the minimum permissions are for the template. As a result, the developer could use CloudFormation to create or modify resources outside of what’s required for their workload.</p> 
   <p>The best practice for CloudFormation is to acquire permissions by using the credentials from an IAM role you pass to CloudFormation. When you attach a least-privilege permissions policy to the role, the actions CloudFormation is allowed to perform can be scoped to only those that are necessary to manage the resources in the template. In this way, you can avoid anti-patterns such as assigning the <span>AdministratorAccess</span> or <span>PowerUserAccess</span> policies—both of which grant excessive permissions—to the role.</p> 
   <p>The following section will describe how to set up your account and grant these permissions.</p> 
   <h2>Prepare your development account</h2> 
   <p>Within your development account, you will configure the same method for deploying infrastructure as you use in production: passing a role to CloudFormation when you launch a stack. First, you will verify that you have the necessary permissions, and then you will create the role and the role’s permissions policy.</p> 
   <h3>Get permissions to use CloudFormation and IAM Access Analyzer</h3> 
   <p>You will need the following minimal permissions in your development account:</p> 
   <ul> 
    <li>Permission to use CloudFormation, in particular to create, update, and delete stacks</li> 
    <li>Permission to pass an IAM role to CloudFormation</li> 
    <li>Permission to create IAM roles and policies</li> 
    <li>Permission to use Access Analyzer, specifically the <span>GetGeneratedPolicy</span>, <span>ListPolicyGenerations</span>, and <span>StartPolicyGeneration</span> actions</li> 
   </ul> 
   <p>The following IAM permissions policy can be used to grant your identity these permissions.</p> 
   <div class="hide-language"> 
    <pre class="unlimited-height-code"><code class="lang-text">{
"Version": "2012-10-17",
"Statement": [
    {
        "Sid": "DeveloperPermissions”,
        "Effect": "Allow",
        "Action": [
            "access-analyzer:GetGeneratedPolicy",
            "access-analyzer:ListPolicyGenerations",
            "access-analyzer:StartPolicyGeneration",
            "cloudformation:*",
            "iam:AttachRolePolicy",
            "iam:CreatePolicy",
            "iam:CreatePolicyVersion",
            "iam:CreateRole",
            "iam:DeletePolicyVersion",
            "iam:DeleteRolePolicy",
            "iam:DetachRolePolicy",
            "iam:GetPolicy",
            "iam:GetPolicyVersion",
            "iam:GetRole",
            "iam:GetRolePolicy",
            "iam:ListPolicies",
            "iam:ListPolicyTags",
            "iam:ListPolicyVersions",
            "iam:ListRolePolicies",
            "iam:ListRoleTags",
            "iam:ListRoles",
            "iam:PutRolePolicy",
            "iam:UpdateAssumeRolePolicy"
        ],
        "Resource": "*"
    },
    {
        "Sid": "AllowPassCloudFormationRole”,
        "Effect": "Allow",
        "Action": [
            "iam:PassRole"
        ]
        "Resource": "*",
        "Condition": {
            "StringEquals": {
                "iam:PassedToService": "cloudformation.amazonaws.com"
            }
        }
    }
]

}

   <blockquote> 
    <strong>Note:</strong> If your identity already has these permissions through existing permissions policies, there is no need to apply the preceding policy to your identity.</p> 
   </blockquote> 
   <h3>Create a role for CloudFormation</h3> 
   <p>Creating a service role for CloudFormation in the development account makes it less challenging to generate the least-privilege policy, because it becomes simpler to identify the actions CloudFormation is taking as it creates and deletes resources defined in the template. By identifying the actions CloudFormation has taken, you can create a permissions policy to match.</p> 
   <p><strong>To create an IAM role in your development account for CloudFormation</strong></p> 
   <ol> 
    <li><a href="https://console.aws.amazon.com/iam/" target="_blank" rel="noopener noreferrer">Open the IAM console</a> and choose <strong>Roles</strong>, then choose <strong>Create role</strong>.</li> 
    <li>For the trusted entity, choose <strong>AWS service</strong>. From the list of services, choose <strong>CloudFormation</strong>.</li> 
    <li>Choose <strong>Next: Permissions</strong>.</li> 
    <li>Select one or more permissions policies that align with the types of resources your stack will create. For example, if your stack creates a Lambda function and an IAM role, choose the <strong>AWSLambda_FullAccess</strong> and <strong>IAMFullAccess</strong> policies.<br /><blockquote> 
      <p><strong>Note:</strong> Because you have not yet created the least-privilege permissions policy, the role is granted broader permissions than required. You will use this role to launch your stack and evaluate the resulting actions that CloudFormation takes, in order to build a lower-privilege policy.</p> 
     </blockquote> </li> 
    <li>Choose <strong>Next: Tags</strong> to proceed.</li> 
    <li>Enter one or more optional tags, and then choose <strong>Next: Review</strong>.</li> 
    <li>Enter a name for the role, such as <span>CloudFormationDevExecRole</span>.</li> 
    <li>Choose <strong>Create role</strong>.</li> 
   </ol> 
   <h3>Create and destroy the stack</h3> 
   <p>To have CloudFormation exercise the actions required by the stack, you will need to create and destroy the stack.</p> 
   <p><strong>To create and destroy the stack</strong></p> 
   <ol> 
    <li>Navigate to CloudFormation in the console, expand the menu in the left-hand pane, and choose <strong>Stacks</strong>.</li> 
    <li>On the <strong>Stacks</strong> page, choose <strong>Create Stack</strong>, and then choose <strong>With new resources</strong>.</li> 
    <li>Choose <strong>Template is ready</strong>, choose <strong>Upload a template file</strong>, and then select the file for your template. Choose <strong>Next</strong>.</li> 
    <li>Enter a <strong>Stack name</strong>, and then choose <strong>Next</strong>.</li> 
    <li>For <strong>IAM execution role name</strong>, select the name of the role you created in the previous section (<span>CloudFormationDevExecRole</span>). Choose <strong>Next</strong>.</li> 
    <li>Review the stack configuration. If present, select the check box(es) in the <strong>Capabilities</strong> section, and then choose <strong>Create stack</strong>.</li> 
    <li>Wait for the stack to reach the <span>CREATE_COMPLETE</span> state before continuing.</li> 
    <li>From the list of stacks, select the stack you just created, choose <strong>Delete</strong>, and then choose <strong>Delete stack</strong>.</li> 
    <li>Wait until the stack reaches the <span>DELETE_COMPLETE</span> state (at which time it will also disappear from the list of active stacks).</li> 
   </ol> 
   <blockquote> 
    <p><strong>Note:</strong> It’s recommended that you also modify the CloudFormation template and update the stack to initiate updates to the deployed resources. This will allow Access Analyzer to capture actions that update the stack’s resources, in addition to create and delete actions. You should also review the API documentation for the resources that are being used in your stack and identify any additional actions that may be required.</p> 
   </blockquote> 
   <p>Now that the development environment is ready, you can create the least-privilege permissions policy for the CloudFormation role.</p> 
   <h2>Use Access Analyzer to generate a fine-grained identity policy</h2> 
   <p>Access Analyzer reviews the access history in AWS CloudTrail to identify the actions an IAM role has used. Because CloudTrail delivers logs within an average of <a href="https://docs.aws.amazon.com/awscloudtrail/latest/userguide/how-cloudtrail-works.html" target="_blank" rel="noopener noreferrer">about 15 minutes of an API call</a>, you should wait at least that long after you delete the stack before you attempt to generate the policy, in order to properly capture all of the actions.</p> 
   <blockquote> 
    <p><strong>Note:</strong> CloudTrail must be enabled in your AWS account in order for policy generation to work. To learn how create a CloudTrail trail, see <a href="https://docs.aws.amazon.com/awscloudtrail/latest/userguide/cloudtrail-create-and-update-a-trail.html" target="_blank" rel="noopener noreferrer">Creating a trail for your AWS account</a> in the <em>AWS CloudTrail User Guide</em>.</p> 
   </blockquote> 
   <p><strong>To generate a permissions policy by using Access Analyzer</strong></p> 
   <ol> 
    <li><a href="https://console.aws.amazon.com/iam/" target="_blank" rel="noopener noreferrer">Open the IAM console</a> and choose <strong>Roles</strong>. In the search box, enter <span>CloudFormationDevExecRole</span> and select the role name in the list.</li> 
    <li>On the <strong>Permissions</strong> tab, scroll down and choose <strong>Generate policy based on CloudTrail events</strong> to expand this section. Choose <strong>Generate policy</strong>.</li> 
    <li>Select the time period of the CloudTrail logs you want analyzed.</li> 
    <li>Select the AWS Region where you created and deleted the stack, and then select the CloudTrail trail name in the drop-down list.</li> 
    <li>If this is your first time generating a policy, choose <strong>Create and use a new service role</strong> to have an IAM role automatically created for you. You can view the permissions policy the role will receive by choosing <strong>View permission details</strong>. Otherwise, choose <strong>Use an existing service role</strong> and select a role in the drop-down list. <p>The policy generation options are shown in Figure 1.</p> 
     <div id="attachment_27413" class="wp-caption aligncenter"> 
      <img aria-describedby="caption-attachment-27413" src="https://infracom.com.sg/wp-content/uploads/2022/10/img1-1024x806-1.png" alt="Figure 1: Policy generation options" width="700" class="size-large wp-image-27413" /> 
      <p id="caption-attachment-27413" class="wp-caption-text">Figure 1: Policy generation options</p> 
     </div> </li> 
    <li>Choose <strong>Generate policy.</strong></li> 
   </ol> 
   <p>You will be redirected back to the page that shows the <span>CloudFormationDevExecRole</span> role. The <strong>Status</strong> in the <strong>Generate policy based on CloudTrail events</strong> section will show <strong>In progress</strong>. Wait for the policy to be generated, at which time the status will change to <strong>Success</strong>.</p> 
   <h2>Review the generated policy</h2> 
   <p>You must review and save the generated policy before it can be applied to the role.</p> 
   <p><strong>To review the generated policy</strong></p> 
   <ol> 
    <li>While you are still viewing the <span>CloudFormationDevExecRole</span> role in the IAM console, under <strong>Generate policy based on CloudTrail events</strong>, choose <strong>View generated policy</strong>.</li> 
    <li>The <strong>Generated policy</strong> page will open. The <strong>Actions included in the generated policy</strong> section will show a list of services and one or more actions that were found in the CloudTrail log. Review the list for omissions. Refer to the <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_generate-policy.html" target="_blank" rel="noopener noreferrer">IAM documentation</a> for a list of AWS services for which an action-level policy can be generated. An example list of services and actions for a CloudFormation template that creates a Lambda function is shown in Figure 2. 
     <div id="attachment_27414" class="wp-caption aligncenter"> 
      <img aria-describedby="caption-attachment-27414" src="https://infracom.com.sg/wp-content/uploads/2022/10/img2.png" alt="Figure 2: Actions included in the generated policy" width="700" class="size-full wp-image-27414" /> 
      <p id="caption-attachment-27414" class="wp-caption-text">Figure 2: Actions included in the generated policy</p> 
     </div> </li> 
    <li>Use the drop-down menus in the <strong>Add actions for services used</strong> section to add any necessary additional actions to the policy for the services that were identified by using CloudTrail. This might be needed if an action isn’t recorded in CloudTrail or if action-level information isn’t supported for a service.<br /><blockquote> 
      <p><strong>Note:</strong> The <span>iam:PassRole</span> action will not show up in CloudTrail and should be added manually if your CloudFormation template assigns an IAM role to a service (for example, when creating a Lambda function). A good rule of thumb is: If you see <span>iam:CreateRole</span> in the actions, you likely need to also allow <span>iam:PassRole</span>. An example of this is shown in Figure 3.</p> 
     </blockquote> 
     <div id="attachment_27415" class="wp-caption aligncenter"> 
      <img aria-describedby="caption-attachment-27415" src="https://infracom.com.sg/wp-content/uploads/2022/10/img3.png" alt="Figure 3: Adding PassRole as an IAM action" width="800" class="size-full wp-image-27415" /> 
      <p id="caption-attachment-27415" class="wp-caption-text">Figure 3: Adding PassRole as an IAM action</p> 
     </div> </li> 
    <li>When you’ve finished adding additional actions, choose <strong>Next</strong>.</li> 
   </ol> 
   <p>Generated policies contain placeholders that need to be filled in with resource names, AWS Region names, and other variable data. The actual values for these placeholders should be determined based on the content of your CloudFormation template and the Region or Regions you plan to deploy the template to.</p> 
   <p><strong>To replace placeholders with real values</strong></p> 
   <ul> 
    <li>In the generated policy, identify each of the <span>Resource</span> properties that use placeholders in the value, such as <span>${RoleNameWithPath}</span> or <span>${Region}</span>. Use your knowledge of the resources that your CloudFormation template creates to properly fill these in with real values. 
     <ul> 
      <li><span>${RoleNameWithPath}</span> is an example of a placeholder that reflects the name of a resource from your CloudFormation template. Replace the placeholder with the actual name of the resource.</li> 
      <li><span>${Region}</span> is an example of a placeholder that reflects where the resource is being deployed, which in this case is the AWS Region. Replace this with either the Region name (for example, <strong>us-east-1</strong>), or a wildcard character (<strong><em></em></strong>), depending on whether you want to restrict the policy to a specific Region or to all Regions, respectively.</li> 
     </ul> </li> 
   </ul> 
   <p>For example, a statement from the policy generated earlier is shown following.</p> 
   <div class="hide-language"> 
    <pre class="unlimited-height-code"><code class="lang-text">{
"Effect": "Allow",
"Action": [
    "lambda:CreateFunction",
    "lambda:DeleteFunction",
    "lambda:GetFunction",
    "lambda:GetFunctionCodeSigningConfig"
],
"Resource": "arn:aws:lambda:${Region}:${Account}:function:${FunctionName}"

},

After substituting real values for the placeholders in Resource, it looks like the following.

{
    "Effect": "Allow",
    "Action": [
        "lambda:CreateFunction",
        "lambda:DeleteFunction",
        "lambda:GetFunction",
        "lambda:GetFunctionCodeSigningConfig"
    ],
    "Resource": "arn:aws:lambda::123456789012:function:MyLambdaFunction"
},

This statement allows the Lambda actions to be performed on a function named MyLambdaFunction in AWS account 123456789012 in any Region (). Substitute the correct values for Region, Account, and FunctionName in your policy.

The IAM policy editor window will automatically identify security or other issues in the generated policy. Review and remediate the issues identified in the Security, Errors, Warnings, and Suggestions tabs across the bottom of the window.

To review and remediate policy issues

  1. Use the Errors tab at the bottom of the IAM policy editor window (powered by IAM Access Analyzer policy validation) to help identify any placeholders that still need to be replaced. Access Analyzer policy validation reviews the policy and provides findings that include security warnings, errors, general warnings, and suggestions for your policy. To find more information about the different checks, see Access Analyzer policy validation. An example of policy errors caused by placeholders still being present in the policy is shown in Figure 4.
    Figure 4: Errors identified in the generated policy

Figure 4: Errors identified in the generated policy

  • Use the Security tab at the bottom of the editor window to review any security warnings, such as passing a wildcard () resource with the iam:PassRole permission. Choose the Learn more link beside each warning for information about remediation. An example of a security warning related to PassRole is shown in Figure 5.

    Figure 5: Security warnings identified in the generated policy

    Figure 5: Security warnings identified in the generated policy

Remediate the PassRole With Star In Resource warning by modifying Resource in the iam:PassRole statement to list the Amazon Resource Name (ARN) of any roles that CloudFormation needs to pass to other services. Additionally, add a condition to restrict which service the role can be passed to. For example, to allow passing a role named MyLambdaRole to the Lambda service, the statement would look like the following.

        {
            "Effect": "Allow",
            "Action": [
                "iam:PassRole"
            ],
            "Resource": [
                "arn:aws:iam::123456789012:role/MyLambdaRole"
            ],
            "Condition": {
                "StringEquals": {
                    "iam:PassedToService": [
                        "lambda.amazonaws.com"
                    ]
                }
            }
        }

The generated policy can now be saved as an IAM policy.

To save the generated policy

  1. In the IAM policy editor window, choose Next.
  2. Enter a name for the policy and an optional description.
  3. Review the Summary section with the list of permissions in the policy.
  4. Enter optional tags in the Tags section.
  5. Choose Create and attach policy.

Test this policy by replacing the existing role policy with this newly generated policy. Then create and destroy the stack again so that the necessary permissions are granted. If the stack fails during creation or deletion, follow the steps to generate the policy again and make sure that the correct values are being used for any iam:PassRole statements.

Deploy the CloudFormation role and policy

Now that you have the least-privilege policy created, you can give this policy to the cloud administrator so that they can deploy the policy and CloudFormation service role into production.

To create a CloudFormation template that the cloud administrator can use

  1. Open the IAM console, choose Policies, and then use the search box to search for the policy you created. Select the policy name in the list.
  2. On the Permissions tab, make sure that the {}JSON button is activated. Select the policy document by highlighting from line 1 all the way to the last line in the policy, as shown in Figure 6.

    Figure 6: Highlighting the generated policy

    Figure 6: Highlighting the generated policy

  3. With the policy still highlighted, use your keyboard to copy the policy into the clipboard (Ctrl-C on Linux or Windows, Option-C on macOS).
  4. Paste the permissions policy JSON object into the following CloudFormation template, replacing the <POLICY-JSON-GOES-HERE> marker. Be sure to indent the left-most curly braces of the JSON object so that they are to the right of the PolicyDocument keyword.
    AWSTemplateFormatVersion: '2010-09-09'
    
    Parameters:
      PolicyName:
        Type: String
        Description: The name of the IAM policy that will be created
    
    RoleName:
        Type: String
        Description: The name of the IAM role that will be created
    
    Resources:
      CfnPolicy:
        Type: AWS::IAM::ManagedPolicy
        Properties:
          ManagedPolicyName: !Ref PolicyName
          Path: /
          PolicyDocument: >
            <POLICY-JSON-GOES-HERE>
    
    CfnRole:
        Type: AWS::IAM::Role
        Properties:
          RoleName: !Ref RoleName
          AssumeRolePolicyDocument:
            Version: '2012-10-17'
            Statement:
              - Action:
                - sts:AssumeRole
                Effect: Allow
                Principal:
                  Service:
                    - cloudformation.amazonaws.com
          ManagedPolicyArns:
            - !Ref CfnPolicy
          Path: /

    For example, after pasting the policy, the CfnPolicy resource in the template will look like the following.

    CfnPolicy:
        Type: AWS::IAM::ManagedPolicy
        Properties:
          ManagedPolicyName: !Ref PolicyName
          Path: /
          PolicyDocument: >
            {
                "Version": "2012-10-17",
                "Statement": [
                    {
                        "Effect": "Allow",
                        "Action": "ec2:DescribeNetworkInterfaces",
                        "Resource": [
                            ""
                        ]
                    },
                    {
                        "Effect": "Allow",
                        "Action": [
                            "iam:AttachRolePolicy",
                            "iam:CreateRole",
                            "iam:DeleteRole",
                            "iam:DetachRolePolicy",
                            "iam:GetRole"
                        ],
                        "Resource": [
                            "arn:aws:iam::123456789012:role/MyLambdaRole"
                        ]
                    },
                    {
                        "Effect": "Allow",
                        "Action": [
                            "lambda:CreateFunction",
                            "lambda:DeleteFunction",
                            "lambda:GetFunction",
                            "lambda:GetFunctionCodeSigningConfig"
                        ],
                        "Resource": [
                            "arn:aws:lambda::123456789012:function:MyLambdaFunction"
                        ]
                    },
                    {
                        "Effect": "Allow",
                        "Action": [
                            "iam:PassRole"
                        ],
                        "Resource": [
                            "arn:aws:iam::123456789012:role/MyLambdaRole"
                        ],
                        "Condition": {
                            "StringEquals": {
                                "iam:PassedToService": [
                                    "lambda.amazonaws.com"
                                ]
                            }
                        }
                    }
                ]
            }
  5. Save the CloudFormation template and share it with the cloud administrator. They can use this template to create an IAM role and permissions policy that CloudFormation can use to deploy resources in the production account.

Note: Verify that in addition to having the necessary permissions to work with CloudFormation, your production identity also has permission to perform the iam:PassRole action with CloudFormation for the role that the preceding template creates.

As you continue to develop your stack, you will need to repeat the steps in the Use Access Analyzer to create a permissions policy and Deploy the CloudFormation role and policy sections of this post in order to make sure that the permissions policy remains up-to-date with the permissions required to deploy your stack.

Considerations

If your CloudFormation template uses custom resources that are backed by AWS Lambda, you should also run Access Analyzer on the IAM role that is created for the Lambda function in order to build an appropriate permissions policy for that role.

To generate a permissions policy for a Lambda service role

  1. Launch the stack in your development AWS account to create the Lamba function’s role.
  2. Make a note of the name of the role that was created.
  3. Destroy the stack in your development AWS account.
  4. Follow the instructions from the Use Access Analyzer to generate a fine-grained identity policy and Review the generated policy sections of this post to create the least-privilege policy for the role, substituting the Lambda function’s role name for CloudFormationDevExecRole.
  5. Build the resulting least-privilege policy into the CloudFormation template as the Lambda function’s permission policy.

Conclusion

IAM Access Analyzer helps generate fine-grained identity policies that you can use to grant CloudFormation the permissions it needs to create, update, and delete resources in your stack. By granting CloudFormation only the necessary permissions, you can incorporate the principle of least privilege, developers can deploy their stacks in production using reduced permissions, and cloud administrators can create guardrails for developers in production settings.

For additional information on applying the principle of least privilege to AWS CloudFormation, see How to implement the principle of least privilege with CloudFormation StackSets.

If you have feedback about this blog post, submit comments in the Comments section below. You can also start a new thread on AWS Identity and Access Management re:Post to get answers from the community.

Want more AWS Security news? Follow us on Twitter.

   <!-- '"` -->