-
Notifications
You must be signed in to change notification settings - Fork 22
/
vault_aws_authorizer_script.go
102 lines (93 loc) · 2.26 KB
/
vault_aws_authorizer_script.go
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
package cloudconfig
const VaultAWSAuthorizerScript = `#!/bin/bash -e
{{ if eq .EncrypterType "vault" }}
token_path=/var/token
nonce_path=/var/nonce
wait_for_vault_elb(){
local service_name="$1"
local state="${2:-active}"
for i in $(seq 80); do
if curl -k -s -o /dev/null -w "%{http_code}" --max-time 3 {{ .VaultAddress }}/v1/sys/health | grep -q "200"; then
return 0
fi
echo "{{ .VaultAddress }} not accessible yet, waiting..."
sleep 15;
done
echo "{{ .VaultAddress }} not accessible"
return 1
}
token_exists () {
if [ -f $token_path ]; then
return 0
else
return 1
fi
}
token_is_valid() {
# https://www.vaultproject.io/api/auth/token/index.html#lookup-a-token-self-
echo "Checking token validity"
token_lookup=$(curl -k \
--request GET \
--silent \
--header "X-Vault-Token: $(cat $token_path)" \
--write-out %{http_code} \
--output /dev/null \
{{ .VaultAddress }}/v1/auth/token/lookup-self)
if [ "$token_lookup" == "200" ]; then
echo "$0 - Valid token found, exiting"
return 0
else
echo "$0 - Invalid token found"
return 1
fi
}
aws_login () {
# query EC2 metadata endpoint (common for all AWS infrastructure).
pkcs7=$(curl -s http://169.254.169.254/latest/dynamic/instance-identity/pkcs7 | tr -d '\n')
if [ -z "$1" ]; then
# do not load nonce if initial login
login_payload=$(cat <<EOF
{
"role": "decrypter",
"pkcs7": "$pkcs7"
}
EOF
)
else
# load nonce in payload for reauthentication
login_payload=$(cat <<EOF
{
"role": "decrypter",
"pkcs7": "$pkcs7",
"nonce": "$1"
}
EOF
)
fi
counter=3
while ! token_is_valid || [ $counter -eq 0 ]; do
curl -k \
--request POST \
--silent \
--data "$login_payload" \
{{ .VaultAddress }}/v1/auth/aws/login | tee \
>(jq -r .auth.client_token > $token_path) \
>(jq -r .auth.metadata.nonce > $nonce_path)
((counter--))
done
}
main () {
if ! wait_for_vault_elb; then
exit 1;
fi
if ! token_exists; then
aws_login ""
elif token_exists && ! token_is_valid; then
aws_login "$(cat $nonce_path)"
else
logger $0 "current vault token is still valid"
fi
}
main
{{ end }}
`