The Lambda Blog

Serverless Cloud Guide

Menu
  • Home
  • Categories
  • Projects
  • About Us
  • Privacy Policy
  • Disclaimer
  • Contact
Menu
how to setup iam multifactor authentication mfa for the aws cli

How to Setup IAM Multifactor Authentication (MFA) for the AWS CLI

Posted on April 25, 2022August 14, 2022 by user
Navigation » Home » AWS CLI

If you are working with the Amazon Cloud Platform, you are probably familiar with IAM – Identity and Access Management, the sometimes complex to use and understand service that manages all access controls in AWS. You are also probably familiar with the powerful AWS Command Line Interface which allows you to manage much of your AWS account through command line invocations.

This article is not going to dwell much into the details of either the IAM service or the CLI toolset beyond perhaps a little setup context towards the title – setting up Multifactor Authentication in IAM so that it even works with your CLI invocations. Basically once setup, any invocation via the command line using the AWS CLI, or even a derivative tool of the AWS CLI like AWS SAM, will prompt for the MFA code before setting up a limited duration session for all other subsequent operations.

Brief Prerequisite Setup Reminder

You do need elevated privileges in your own Amazon account in order to make these changes, especially since it touches on IAM changes.

Additionally, you must have the AWS CLI installed locally.

There are multiple installation guides depending on the specific OS of your choice. I prefer using the Python Package Installer pip as it should then work regardless of whether I work with a Linux shell emulator on my Windows machine or with command prompt.

pip install awscli

And if you have used the AWS CLI before you, you probably have these next steps already setup, but just as a reminder before I demonstrate modifications for setting up MFA…

aws-iam-access-key

And in your Home directory…Where you find your home directory based on the environment variable %UserProfile% in Windows and $HOME or ~ in Linux/macOS…you will have the following two files

~/.aws/credentials
~/.aws/config

The config file will have some defaults…

[default]
region=us-east-1

While the credential file will have the Access Key and Secret

[profileName]
aws_access_key_id = <ACCESS_KEY_ID>
aws_secret_access_key = <SECRET_KEY>
region=<your_region>

And if you haven’t set it up – well here is a condensed tutorial which is all you need to get going!

Setting up a rule requiring Multifactor Authentication (MFA) in IAM

First step is to enforce this in IAM by creating a Group in IAM where MFA is required. Once done and if you add users to that group, now even for CLI invocations, an MFA code will become required for those users.

First Navigate to IAM, user groups and hit the Create Group Button

iam-create-group

In the prompt add a name for your group, probably makes sense for the word “MFA” to be suffixed, your call, and add the users you want initially in the group.

iam-create-group-modal

And most critically, in the permissions section…hit create policy.

iam-create-group-attach-policy

And in the next JSON policy…add the following JSON below which will basically block any operation unless MFA is present.

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "DenyAllAboveExceptBelowOperationsIfNoMFACode",
            "Effect": "Deny",
            "NotAction": [
                "iam:CreateVirtualMFADevice",
                "iam:EnableMFADevice",
                "iam:GetUser",
                "iam:ListMFADevices",
                "iam:ListVirtualMFADevices",
                "iam:ResyncMFADevice",
                "sts:GetSessionToken"
            ],
            "Resource": "*",
            "Condition": {
                "BoolIfExists": {
                    "aws:MultiFactorAuthPresent": "false"
                }
            }
        }
    ]
}

Hit create Group and now IAM will enforce the policy.

Next step is to slightly modify the setup for the local config and credentials file to account for this setup.

Verify Virtual MFA Device is Assigned and confirm Role ARN for Access

First confirm MFA is setup for the user(s) – a MFA virtual device ARN is required as seen in IAM.

iam-user-security-credentials-tab

Additionally – users will need the ROLE ARN that manage the permissions they are assigned to.

For example, this is my own Admin Role that is setup…

iam-role-admin-access

This role also controls how long the MFA session lasts – I have this configured in the above example for 1 hour.

Setting up local config and credentials file with MFA enabled

Almost there now…

First in the Config File – setup a new Pointer to the profile.

[profile mfabasedaccess]
source_profile = AWSAccountProfileName
role_arn = arn:aws:iam::<account>:role/<rolename>
mfa_serial = arn:aws:iam::<account>:mfa/<aws_user_name>

No change to the credential file…just ensure the source_profile name exists

[AWSAccountProfileName]
aws_access_key_id = <ACCESS_KEY_ID>
aws_secret_access_key = <SECRET_KEY>
region=<your_region>

Testing the MFA CLI access

Ensure your export (Set in Windows) your AWS_PROFILE to the new one you created in the config file…

export AWS_PROFILE=mfabasedaccess

And try a command to see a prompt for the MFA code

aws s3 ls
Enter MFA code for arn:aws:iam::<account>:mfa/<aws_user_name>

Enter your Authenticator Device code and now you will have a valid session with the terminal or script that will last 1 hour.

Word of caution

If you are using this with long running scripts and operations like an s3 cleanup that could go past the session set here, the access will be revoked and the operation terminated. As of now there is no support for extending tokens. So either use a different system user for those kinds of operations or create a longer expiration period for the session.

Recent Posts

  • Coding a JSON format logger in Python for use as a Lambda Layer package
  • Configuring an S3 Bucket to send events to a Lambda destination for processing
  • How to request a public SSL certificate for a domain name from the AWS Certificate Manager Console
  • Creating automated CloudFormation Stack Build and Deployments with AWS CodePipeline and CodeBuild
  • A concise guide to setting up the AWS command-line libraries on your local development environment
  • How to implement a Lambda Authorizer for an AWS AppSync API and invoke the API with the required Authorization Token
  • Filtering CloudWatch Logs by LogGroups and LogStreams and reading them using Python and the Boto3 SDK
  • Azure AD Multi Tenancy issue in AWS Cognito
  • Setting up Enterprise Federation from Azure Active Directory to Amazon Cognito using Open ID Connect
  • How to Setup IAM Multifactor Authentication (MFA) for the AWS CLI

Categories

  • Amplify
  • API Gateway
  • AppSync
  • AWS CLI
  • CloudFormation
  • CloudWatch
  • Cognito
  • DynamoDB
  • EventBridge
  • KMS
  • Lambda
  • Projects
  • Route 53
  • SES
  • SNS

Post Tags

ACM Amplify API Gateway AppSync AWS CLI Azure Boto3 CloudFormation CloudWatch CodeBuild CodePipeline Cognito DynamoDB EventBridge Firebase IAM KMS Lambda OIDC Project Python Rekognition Route53 S3 SAM SES SNS VPC

©2022 The Lambda Blog