How can I enforce MFA authentication for IAM users that use the AWS CLI?

Last updated: 2020-06-16

I created a multi-factor authentication (MFA) condition policy to restrict access to AWS services for AWS Identity and Access Management (IAM) users. The policy works with the AWS Management Console, but not with the AWS Command Line Interface (AWS CLI). How can I use MFA with the AWS CLI?

Short description

The following example IAM policy requires IAM users to use MFA to access specific AWS services:

{

            "Sid": "BlockMostAccessUnlessSignedInWithMFA",
            "Effect": "Deny",
            "NotAction": [
                "iam:CreateVirtualMFADevice",
                "iam:DeleteVirtualMFADevice",
                "iam:ListVirtualMFADevices",
                "iam:EnableMFADevice",
                "iam:ResyncMFADevice",
                "iam:ListAccountAliases",
                "iam:ListUsers",
                "iam:ListSSHPublicKeys",
                "iam:ListAccessKeys",
                "iam:ListServiceSpecificCredentials",
                "iam:ListMFADevices",
                "iam:GetAccountSummary",
                "sts:GetSessionToken"
            ],
            "Resource": "*",
            "Condition": {
                "Bool": {
                    "aws:MultiFactorAuthPresent": "false"
                }
            }
}

IAM users with the AWS Management Console are prompted to enter MFA authentication credentials and can then access AWS services. However, IAM users with the AWS CLI are not prompted to enter MFA authentication credentials and can access AWS services.

Resolution

The MultiFactorAuthPresent key applies only to temporary security credentials that check if MFA is used. The MultiFactorAuthPresent key doesn't deny access to requests made using long-term credentials or to MFA requests with the AWS CLI.

IAM users using the AWS Management Console generate temporary credentials and allow access only if MFA is used.

The Bool condition operator lets you restrict access with a key value set to true or false. You can add the BoolIfExists condition operator to check if the MultiFactorAuthPresent key is present in the request. If the MultiFactorAuthPresent key isn't present, IfExists evaluates the condition element as true similar to the following:

"Effect" : "Deny",
"Condition" : { "BoolIfExists" : { "aws:MultiFactorAuthPresent" : "false" } }

IAM users using the AWS CLI with long term credentials are denied access and must use MFA to authenticate.

For more information, see Boolean condition operators.