AWS/oathtool and awscli with mfa totp

From Ever changing code
< AWS
Jump to navigation Jump to search
Install
sudo apt install oathtool
oathtool --version # -> Ubuntu 20.04: oathtool (OATH Toolkit) 2.6.1

aws --version
aws-cli/1.18.69 Python/3.8.2 Linux/5.4.0-42-generic botocore/1.16.19
Save seeding MFA/2FA secret for oauthtool

Obtain MFA/2FA seeding code from AWS console by navigating to IAM > Users > myuser > Security credentials > Assigned MFA device > Manage. The secret is only visible during registration.

# Save your MFA seeding code to the convenient file
echo "aaa" > ~/.aws/aws-mfa


Get credentials from sts make sure your time is correct and not skewed
ACCOUNT=111111111111; USER=piotr@acme.com; \
aws sts get-session-token --region eu-west-1 --serial-number arn:aws:iam::${ACCOUNT}:mfa/${USER} --token-code $(oathtool --base32 --totp $(cat ~/.aws/aws-mfa))
{
    "Credentials": {
        "AccessKeyId": "ASIA3CPG2R2NHEXAMPLE",
        "SecretAccessKey": "xYJZmbkWNEXAMPLE",
        "SessionToken": "FwoGZXIvYXdzEGgaDKZGWUjNKkUlWY5UHyKGAbxlDGl6C4MHv2m9iUKVWucMMqYcpDIHEl9FNhGB04EXAMPLE",
        "Expiration": "2020-08-10T02:11:01Z"
    }
}


Parse sts output
# file based, use default aws profile
aws-login() {
  local ACCOUNT=111111111111
  local USER=piotr@acme.com
  OUTPUT=$(aws sts get-session-token --region us-east-1 --serial-number arn:aws:iam::${ACCOUNT}:mfa/${USER} --token-code $(oathtool --base32 --totp $(cat ~/.aws-mfa)))
  export AWS_ACCESS_KEY_ID=$(    echo $OUTPUT | jq .Credentials.AccessKeyId     --raw-output)
  export AWS_SECRET_ACCESS_KEY=$(echo $OUTPUT | jq .Credentials.SecretAccessKey --raw-output)
  export AWS_SESSION_TOKEN=$(    echo $OUTPUT | jq .Credentials.SessionToken    --raw-output)
  export AWS_SECURITY_TOKEN=$AWS_SESSION_TOKEN
}

# selfcontained
aws-login() {
  export AWS_PROFILE=myprofile
  local ACCOUNT=111111111111 # accaunt where IAMuser exists
  local USER=piotr@acme.com  # IAMUser
  local TOTP=<totpseed>
  OUTPUT=$(aws sts get-session-token --region us-east-1 --serial-number arn:aws:iam::${ACCOUNT}:mfa/${USER} --token-code $(oathtool --base32 --totp $TOTP))
  export AWS_ACCESS_KEY_ID=$(    echo $OUTPUT | jq .Credentials.AccessKeyId     --raw-output)
  export AWS_SECRET_ACCESS_KEY=$(echo $OUTPUT | jq .Credentials.SecretAccessKey --raw-output)
  export AWS_SESSION_TOKEN=$(    echo $OUTPUT | jq .Credentials.SessionToken    --raw-output)
  export AWS_SECURITY_TOKEN=$AWS_SESSION_TOKEN
}