forked from 99designs/aws-vault
-
Notifications
You must be signed in to change notification settings - Fork 0
/
aws-iam-create-yubikey-mfa.sh
executable file
·41 lines (30 loc) · 1.17 KB
/
aws-iam-create-yubikey-mfa.sh
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#!/bin/sh
# Adds a Yubikey TOTP device to IAM
set -eu
if [ -n "${AWS_SESSION_TOKEN:-}" ]; then
echo "aws-vault must be run without a STS session, please run it with the --no-session flag" >&2
exit 1
fi
ACCOUNT_ARN=$(aws sts get-caller-identity --query Arn --output text)
# Assume that the final portion of the ARN is the username
# Works for ARNs like `users/<user>` and `users/engineers/<user>`
USERNAME=$(echo "$ACCOUNT_ARN" | rev | cut -d/ -f1 | rev)
OUTFILE=$(mktemp)
trap 'rm -f "$OUTFILE"' EXIT
SERIAL_NUMBER=$(aws iam create-virtual-mfa-device \
--virtual-mfa-device-name "$USERNAME" \
--bootstrap-method Base32StringSeed \
--outfile "$OUTFILE" \
--query VirtualMFADevice.SerialNumber \
--output text)
ykman oath accounts add -ft "$SERIAL_NUMBER" < "$OUTFILE" 2> /dev/null
CODE1=$(ykman oath accounts code -s "$SERIAL_NUMBER")
WAIT_TIME=$((30-$(date +%s)%30))
echo "Waiting $WAIT_TIME seconds before generating a second code" >&2
sleep $WAIT_TIME
CODE2=$(ykman oath accounts code -s "$SERIAL_NUMBER")
aws iam enable-mfa-device \
--user-name "$USERNAME" \
--serial-number "$SERIAL_NUMBER" \
--authentication-code1 "$CODE1" \
--authentication-code2 "$CODE2"