Skip to content

Instantly share code, notes, and snippets.

@edouardp
Last active March 8, 2021 04:48
Show Gist options
  • Save edouardp/e3af544c64d69a1b47492bad534f647d to your computer and use it in GitHub Desktop.
Save edouardp/e3af544c64d69a1b47492bad534f647d to your computer and use it in GitHub Desktop.
Calling script to force MFA with AWS cli

TODO

  • Create a write-up on how this works
[default]
credential_process = sh -c '/home/jrandomhacker/.aws/get-session-token.sh 2> /dev/tty'
[profile low_privilege_user]
aws_access_key_id=AKIAXXXXXXXXXXXXXXXX
aws_secret_access_key=axxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
region=us-east-1
#!/bin/sh
#
# If the file ~/.aws/session-token.json exists and was created less than
# 718 minutes ago (12 hour - 2 minutes) then return that
# Otherwise read the MFA token, and call aws sts get-session-token with
# duration of 12 hours and recreate the file (and then return it)
#
if test "`find ~/.aws/session-token.json -type f -cmin -718 2>/dev/null`" ; then
cat ~/.aws/session-token.json
else
rm -f ~/.aws/session-token.json
read -p "Please enter MFA code: " mfa
aws sts get-session-token \
--serial-number "arn:aws:iam::777777777777:mfa/low_privilege_user" \
--profile low_privilege_user \
--duration 43200 \
--token-code $mfa \
--query 'Credentials' | jq '.Version += 1' > ~/.aws/session-token.json
cat ~/.aws/session-token.json
fi
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "BlockMostAccessUnlessSignedInWithMFA",
"Effect": "Deny",
"NotAction": [
"sts:GetSessionToken"
],
"Resource": "*",
"Condition": {
"BoolIfExists": {
"aws:MultiFactorAuthPresent": "false"
}
}
}
]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment