welcome at SebWalak.com

Demo user with AWS-CLI and MFA.

categories: /dev-ops
tags: #aws   #cloud

Why?

I was preparing to a demo of AWS features and I was going to use CLI for most AWS interactions. Presented material was spanning across multiple services and involved creation and destruction of resources that incur cost. Some of the actions required a user that is empowered. The broad range of services required a versatile one. Who knows what you may need during a live demo?

For AWS-CLI interactions I used to create an IAM user (at least didn’t use root) and invoke aws configure. It would bake that user’s key into the filesystem in a plain form. Such set of credentials is long-lived and the permission-set would usually remain fairly static in my case. This method was convenient and authentication was done automatically in a transparent fashion. While I usually go for cattle approach when working with servers, I was definitely petting the IAM primitives.

I had no major reservations about this workflow on my main workstation, but when I started parading around with my laptop, alarm bells started ringing in my head. Even though I have limits set low for the count and size of resources, these credentials would potentially be an attractive target for attackers to intercept. Whoever was to gain access to that key would be able to do much damage to my services and to my wallet.

Few icons in series. MFA, AWS CLI, AWS IAM, AWS Cloud. Just for visual reference and thumbnail.

Multi-factor authentication

MFA is an authentication mechanism requiring the users to provide:

  • something that they know (e.g. password, pin, collection of personal details)
  • something that they have (e.g. physical key, bespoke hardware or software token generator)
  • something that they are (e.g. retina scan, fingerprint, DNA)

I hope you can see the benefit right away.

Simply speaking, MFA adds an extra layer of security. An attacker will not be able to gain illicit access to your account having your key (equivalent of credentials) alone. While compromise is still possible, it now becomes significantly harder for an attacker. It often would also require the attacker to be in proximity of the victim. I presume it is something that many “software” attackers would want to avoid.

To set it up in AWS use IAM service.

AWS documentation serves you all the information needed to create an appropriate policy enforcing MFA and provides guidance on how to attach it to a group. This policy can remain static and linked to multiple groups, even though each group or user within a group may have different effective permission.

Identity and Access Management (IAM) setup

For reference, here is an example of MFA policy fetched from AWS docs (page link above) at the time of writing:

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "AllowAllUsersToListAccounts",
            "Effect": "Allow",
            "Action": [
                "iam:ListAccountAliases",
                "iam:ListUsers",
                "iam:ListVirtualMFADevices",
                "iam:GetAccountPasswordPolicy",
                "iam:GetAccountSummary"
            ],
            "Resource": "*"
        },
        {
            "Sid": "AllowIndividualUserToSeeAndManageOnlyTheirOwnAccountInformation",
            "Effect": "Allow",
            "Action": [
                "iam:ChangePassword",
                "iam:CreateAccessKey",
                "iam:CreateLoginProfile",
                "iam:DeleteAccessKey",
                "iam:DeleteLoginProfile",
                "iam:GetLoginProfile",
                "iam:ListAccessKeys",
                "iam:UpdateAccessKey",
                "iam:UpdateLoginProfile",
                "iam:ListSigningCertificates",
                "iam:DeleteSigningCertificate",
                "iam:UpdateSigningCertificate",
                "iam:UploadSigningCertificate",
                "iam:ListSSHPublicKeys",
                "iam:GetSSHPublicKey",
                "iam:DeleteSSHPublicKey",
                "iam:UpdateSSHPublicKey",
                "iam:UploadSSHPublicKey"
            ],
            "Resource": "arn:aws:iam::*:user/${aws:username}"
        },
        {
            "Sid": "AllowIndividualUserToViewAndManageTheirOwnMFA",
            "Effect": "Allow",
            "Action": [
                "iam:CreateVirtualMFADevice",
                "iam:DeleteVirtualMFADevice",
                "iam:EnableMFADevice",
                "iam:ListMFADevices",
                "iam:ResyncMFADevice"
            ],
            "Resource": [
                "arn:aws:iam::*:mfa/${aws:username}",
                "arn:aws:iam::*:user/${aws:username}"
            ]
        },
        {
            "Sid": "AllowIndividualUserToDeactivateOnlyTheirOwnMFAOnlyWhenUsingMFA",
            "Effect": "Allow",
            "Action": [
                "iam:DeactivateMFADevice"
            ],
            "Resource": [
                "arn:aws:iam::*:mfa/${aws:username}",
                "arn:aws:iam::*:user/${aws:username}"
            ],
            "Condition": {
                "Bool": {
                    "aws:MultiFactorAuthPresent": "true"
                }
            }
        },
        {
            "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": {
                "BoolIfExists": {
                    "aws:MultiFactorAuthPresent": "false"
                }
            }
        }
    ]
}

Elaboration of the statements can be found on the aforementioned site.

You can set it all up via AWS console (instruction on that same site) or AWS-CLI. For AWS-CLI ensure the user you are executing commands with has the following permissions:

  • iam:CreatePolicy
  • iam:CreateGroup
  • iam:CreateUser
  • iam:AddUserToGroup
  • iam:AttachGroupPolicy
  • iam:AttachUserPolicy

and for user cleanup:

  • iam:DetachUserPolicy - if you just want to do that, otherwise simply delete user
  • iam:RemoveUserFromGroup
  • iam:DeleteUser

Save the above json snippet of a policy as ‘mfa.json’ and run

# once only
POLICY_ARN=$(aws iam create-policy --policy-name force-mfa --policy-document file://mfa.json | jq '.Policy.Arn' -r)
aws iam create-group --group-name disposables
aws iam attach-group-policy --group-name disposables --policy-arn ${POLICY_ARN}

# for each new user
aws iam create-user --user-name disposable-demo
aws iam add-user-to-group --group-name disposables --user-name disposable-demo

POLICY_ARN will contain string in format arn:aws:iam::\<your-acc-no\>:policy/force-mfa. You can also find it in AWS console, in IAM -> Policies -> filter by “Customer managed” -> select policy

Now you have a ‘disposable-demo’ user, added to a ‘disposables’ group with policy ‘force-mfa’, forcing MFA on majority of operations performed by that user. This user can’t do anything exciting yet, apart from viewing some basic info and managing its own details (check the AWS site mentioned before).

Let’s say your demo involves all things EC2 related. You can now attach AWS managed policy ‘AmazonEC2FullAccess’ to your user

aws iam attach-user-policy --user-name disposable-demo --policy-arn arn:aws:iam::aws:policy/AmazonEC2FullAccess

And by doing that user will be able to use EC2 service but will be forced to use MFA.

Once you are done with the user (after the demo?), remove it

aws iam remove-user-from-group --group-name disposables --user-name disposable-demo
aws iam delete-user --user-name disposable-demo

In order to use that user from AWS-CLI we need to obtain access key id and secret key and configure our development environment.

That’s when I became slightly disappointed with my new shiny toy.

Configure AWS-CLI to use MFA

I was spoiled by the workflow utilising long-lived credentials, which handles authentication for you. After initial and quick setup (e.g. aws configure), you just work with AWS API without a need to pay much attention to what happens behind the scenes.

You may be already somewhat familiar with the AWS’es config and credentials files:

$ cat ~/.aws/credentials
[demo-of-ec2-s3-iam]
aws_access_key_id = <from AWS console>
aws_secret_access_key = <from AWS console>

[disposable-demo]
aws_access_key_id = <from AWS console>
aws_secret_access_key = <from AWS console>
$ cat ~/.aws/config
[default]
region = eu-west-1

Once you start using MFA, you have to incorporate few extra hops into the interaction:

  • generate MFA token every so and often, frequency depending on token longevity (configurable)
  • call STS with the above token to obtain temporary credentials, these are consisting of access key id, secret access key and session token
  • parse the json output of above call and extract all three pieces of information
  • make the temporary credentials available to subsequent AWS invocations (e.g. export AWS_*)

So, quite few steps and had to be scripted. The following script will prompt for MFA, call STS, extract the key information and export it:

$ cat set_token.sh
# provide your account number here
ACC_NO=123456789012

# and the token expiry, 1h in this example
TOKEN_EXPIRY_SECS=3600

# default your user
USERNAME=${1:-disposable-demo}

if [ "$0" = "$BASH_SOURCE" ]; then
  echo "This script needs to be sourced!"
  exit 1
fi

read -sp "Enter the MFA token for user '${USERNAME}': " TOKEN
echo
export AWS_SESSION_TOKEN_RESPONSE=$(aws sts get-session-token --serial-number "arn:aws:iam::${ACC_NO}:mfa/${USERNAME}" --duration-seconds ${TOKEN_EXPIRY_SECS} --profile ${USERNAME} --token-code ${TOKEN})
$(echo ${AWS_SESSION_TOKEN_RESPONSE} | jq '.Credentials | "export AWS_ACCESS_KEY_ID=\(.AccessKeyId)\nexport AWS_SECRET_ACCESS_KEY=\(.SecretAccessKey)\nexport AWS_SESSION_TOKEN=\(.SessionToken)"' --raw-output)

Note: In the above snippets I am using the username as profile name as it simplifies the scripts and fits my use case.

and a script to clear the exported key information in one go:

$ cat unset_token.sh
if [ "$0" = "$BASH_SOURCE" ]; then
  echo "This script needs to be sourced!"
  exit 1
fi

unset AWS_ACCESS_KEY_ID
unset AWS_SECRET_ACCESS_KEY
unset AWS_SESSION_TOKEN

then, whenever token expires you just do:

# for default, to request temporary credentials for a default user  
. set_token.sh
> Enter the MFA token for user 'disposable-demo':
> ******

# or for specific one
. set_token.sh demo-of-ec2-s3-iam
> Enter the MFA token for user 'demo-of-ec2-s3-iam':
> ******

# just continue to use AWS-CLI

# when done
. unset_token.sh

and I’ve found it convenient enough.

Thumbnail