Skip to content

Instantly share code, notes, and snippets.

@jonasfj
Created November 8, 2017 23:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jonasfj/8b4848574f70474b941e0428087ac97b to your computer and use it in GitHub Desktop.
Save jonasfj/8b4848574f70474b941e0428087ac97b to your computer and use it in GitHub Desktop.
A simple script for forcing 2FA usage with AWS credentials
#!/bin/bash
# This script expects AWS credentials:
# SIGNIN_AWS_ACCESS_KEY_ID
# SIGNIN_AWS_SECRET_ACCESS_KEY
# And optionally the TOTP entry name in your yubikey
# SIGNIN_AWS_YUBIKEY_OATH_NAME
# Put these environment variables into your .bashrc.local (or .bashrc, if you
# don't sync dot-files). In your .bashrc you'll also want:
# alias signin-aws='eval `signin-aws`'
# Then put this script in your PATH as 'signin-aws', and you should be able to
# sign-in by typing 'signin-aws' in your shell.
#
# Note: if using a yubikey nano, you'll probably want touch-required on your
# TOTP generator. That should also work with this script.
# Expiration time of login session (in seconds)
DURATION="21600" # 6 hours
# Attempt to get token from yubikey
TOKEN=''
if [[ ! -z "$SIGNIN_AWS_YUBIKEY_OATH_NAME" ]]; then
killall -q scdaemon
TOKEN=`yubioath-cli show "$SIGNIN_AWS_YUBIKEY_OATH_NAME" | rev | cut -b -6 | rev`
if [ ! $? -eq 0 ]; then
TOKEN=''
fi
fi
# Ask user for token
if [[ -z "$TOKEN" ]]; then
(>&2 echo "Enter token:")
read TOKEN
fi
# Re-export AWS credentials for use in this script
export AWS_ACCESS_KEY_ID="$SIGNIN_AWS_ACCESS_KEY_ID"
export AWS_SECRET_ACCESS_KEY="$SIGNIN_AWS_SECRET_ACCESS_KEY"
(>&2 echo "Fetching temporary credentials")
SERIAL_NUMBER=`aws iam list-mfa-devices | jq -r .MFADevices[0].SerialNumber`
STS_CREDENTIALS=`aws sts get-session-token --serial-number "$SERIAL_NUMBER" --token-code "$TOKEN" --duration-seconds $DURATION`
# Print result as importable for eval
echo "export AWS_ACCESS_KEY_ID='`echo $STS_CREDENTIALS | jq -r .Credentials.AccessKeyId`'"
echo "export AWS_SECRET_ACCESS_KEY='`echo $STS_CREDENTIALS | jq -r .Credentials.SecretAccessKey`'"
echo "export AWS_SESSION_TOKEN='`echo $STS_CREDENTIALS | jq -r .Credentials.SessionToken`'"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment