Skip to content

Instantly share code, notes, and snippets.

@djmitche
Forked from jonasfj/signin-aws
Last active July 28, 2021 18:44
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save djmitche/80353576a0f389bf130bcb439f63d070 to your computer and use it in GitHub Desktop.
Save djmitche/80353576a0f389bf130bcb439f63d070 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
# Or it will use the credentials set up with `aws configure` if those are not set.
#
# It optionally epects 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:
# signin-aws() {
# eval `~/bin/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.
# reset any existing credentials
unset AWS_SESSION_TOKEN
unset AWS_SECRET_ACCESS_KEY
unset AWS_ACCESS_KEY_ID
# 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 -n "Enter token: ")
read TOKEN
fi
# Re-export AWS credentials for use in this script, if set
if [ -n "$SIGNIN_AWS_ACCESS_KEY_ID" ]; then
export AWS_ACCESS_KEY_ID="$SIGNIN_AWS_ACCESS_KEY_ID"
export AWS_SECRET_ACCESS_KEY="$SIGNIN_AWS_SECRET_ACCESS_KEY"
fi
(>&2 echo "Fetching temporary credentials")
SERIAL_NUMBER=`aws "${@}" iam list-mfa-devices | jq -r .MFADevices[0].SerialNumber`
if [ -z "$SERIAL_NUMBER" ]; then
echo "Could not list MFA devices"
return 1
fi
STS_CREDENTIALS=`aws "${@}" sts get-session-token --serial-number "$SERIAL_NUMBER" --token-code "$TOKEN" --duration-seconds $DURATION`
if [ -z "$STS_CREDENTIALS" ]; then
echo "Could not get session token"
return 1
fi
# 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