How to use Multifactor Authentication (MFA) in AWS from the command line

Nowadays, relying on password-only authentication for AWS accounts managing production-related workload is extremely dangerours. Multi-factor authentication (MFA) is a must for user with administrative privileges.

Using MFA through an application in your mobile phone or a hardware token can be cumbersome when you are continuously updating your environment using Infrastructure as Code (IaC) tools like Terraform.

Here is where the need of been able to generate MFA codes from the command line comes into play. Fortunately, for Linux users we can take advantage of tools like oath which allows us to get a code with just one command.

 

Oath Tool Setup

 

I’m currently using the latest version of Kali Linux (2020.1) but this process should be the same for any debian-based Linux distribution.

In order to set it up we have just two steps:

  1. Update your debian package repositories

$ sudo apt-get -y update

  1. Install the oathtool package

$ sudo apt-get install -y oathtool

 

Configuring the software-based MFA code generator within your AWS Account

 

  1. In order to configure your software-based MFA code generator in the AWS console, go to the “Security Credentials” tab of your IAM user.

 

  1. Select the “Manage” link within the “Assigned MFA device” field.

 

  1. Choose “Virtual MFA device” and click on “Continue”.

 

  1. In the listed Step 2, click on the “Show secret key” link and copy the secret. I recommend creating a “secrets” folder within the .aws directory pasting it in a file that identifies the account you are using (my-security-account, for example).

 

  1. Generate two codes to complete the setup using the following command (assuming the file was named as in Step 4)

$ oathtool --totp --base32 $(cat ~/.aws/secrets/my-security-account)

 

  1. Once you entered the two codes, select “Assign MFA” and your MFA is now ready to be used.

 

Daily Usage

Now that you have your software-based MFA code generator configured, when you are using a tool like terraform or just need to access your account through the console, you just have to run:

$ oathtool --totp --base32 $(cat ~/.aws/secrets/my-security-account)

Thanks for reading!