forked from 99designs/aws-vault
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathaws-iam-create-yubikey-mfa.sh
executable file
·55 lines (43 loc) · 1.55 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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#!/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
cleanup() { rm -f "${OUTFILE:-}"; }
trap cleanup EXIT
waittime() {
# wait until next code can be generated
# if SECONDS are :00 or :30, generate right away
SECONDS=$(date +%S)
if [ ${SECONDS#0} -gt 0 ] && [ ${SECONDS#0} -lt 30 ]; then
WAIT_SECONDS=$(( 30 - ${SECONDS#0} ))
elif [ ${SECONDS#0} -gt 30 ] && [ ${SECONDS#0} -lt 60 ]; then
WAIT_SECONDS=$(( 60 - ${SECONDS#0} ))
fi
echo ${WAIT_SECONDS:-0}
}
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)
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 add -ft "$SERIAL_NUMBER" < "$OUTFILE" 2> /dev/null
rm "$OUTFILE"
CODE1=$(ykman oath code -s "$SERIAL_NUMBER")
WAIT_TIME=$(waittime)
echo "Waiting ${WAIT_TIME}s before generating a second code" >&2
sleep ${WAIT_TIME}
CODE2=$(ykman oath code -s "$SERIAL_NUMBER")
aws iam enable-mfa-device \
--user-name "$USERNAME" \
--serial-number "$SERIAL_NUMBER" \
--authentication-code1 "$CODE1" \
--authentication-code2 "$CODE2"