Wednesday, June 9, 2021

Using MFA with AWS CLI

Lets say that the AWS account credentials get compromised, the hacker should be able to access the account and do a lot of damage. This is where the AWS MFA comes into play. But, the MFA doesn’t apply the CLI/SDK operations by default and some additional work has to be done.

  1. Create an IAM Policy with one of the the below JSON. Both have the same effect of giving the access to all the S3 operations using the short term access keys authenticated via the MFA.

    {
        "Version": "2012-10-17",
        "Statement": [
            {
                "Effect": "Deny",
                "Action": "s3:*",
                "Resource": "*",
                "Condition": {
                    "BoolIfExists": {
                        "aws:MultiFactorAuthPresent": "false"
                    }
                }
            }
        ]
    }
    
    {
        "Version": "2012-10-17",
        "Id": "123",
        "Statement": [
            {
                "Effect": "Deny",
                "Resource": "*",
                "Action": "s3:*",
                "Condition": {
                    "Null": {
                        "aws:MultiFactorAuthAge": true
                    }
                }
            }
        ]
    }
    
  2. Create an IAM User and get the access keys for this user.

  3. Attach the above Policy and the AmazonS3FullAccess Policy to the IAM user.

  4. Enable MFA for the user.

  5. Install the AWS CLI.

  6. Set the above access keys using the aws configure command. Specify the appropriate Region code.

  7. Get the short term credentials for the same IAM User using the below command. Make sure to replace the arn-of-the-mfa-device and code-from-token in the command.

    aws sts get-session-token --serial-number arn-of-the-mfa-device --token-code code-from-token

  8. In the .aws/credendtials file create a named profile with the below content. Make sure to replace the access key, secret access key and the session token from the previous command.

    [mfa]
    aws_access_key_id = example-access-key-as-in-returned-output
    aws_secret_access_key = example-secret-access-key-as-in-returned-output
    aws_session_token = example-session-Token-as-in-returned-output

  9. The below command uses the default named profile and so the long term credentials and so should fail.

    aws s3 ls

  10. The below command uses the long term credentials authenticated via MFA and should return the list of buckets in S3.

    aws s3 ls --profile mfa

Further Reading

  1. AWS CLI and MFA

  2. How do I use an MFA token to authenticate access to my AWS resources through the AWS CLI?

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

  4. Adding a bucket policy to require MFA

  5. aws:MultiFactorAuthPresent

  6. Boolean Condition

  7. IfExists condition

No comments:

Post a Comment