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",
"aws:ViaAWSService": "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 aren't prompted to enter MFA authentication credentials and can access AWS services.
Resolution
Note: If you receive errors when running AWS CLI commands, make sure that you’re using the most recent version of the AWS CLI.
The MultiFactorAuthPresent key doesn't exist in requests made using long-term credentials. With the Boolean condition operator, if the key in the policy isn't present, then the values don't match. The MultiFactorAuthPresent key doesn't deny access to requests made using long-term credentials.
IAM users using the AWS Management Console generate temporary credentials and allow access only if MFA is used.
The Boolean condition lets you restrict access with a key value set to true or false. You can add the IfExists 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", "aws:ViaAWSService":"false"} }
Note: IAM users using the AWS CLI with long-term credentials are denied access and must use MFA to authenticate. Therefore, be sure to use an MFA token to authenticate your CLI session.
Related information
Using multi-factor authentication
AssumeRole
Enabling and managing virtual MFA devices (AWS CLI or AWS API)