forked from kelseyhightower/vault-init
-
Notifications
You must be signed in to change notification settings - Fork 4
/
main.go
241 lines (199 loc) · 5.13 KB
/
main.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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
// Copyright 2018 Google Inc. All Rights Reserved.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
package main
import (
"flag"
"log"
"os"
"os/signal"
"strconv"
"syscall"
"time"
"github.com/hashicorp/vault/api"
"github.com/kelseyhightower/vault-init/pkg/keystore"
)
var (
checkInterval string
)
const (
providerGcp = "gcp"
providerAws = "aws"
providerAwsS3 = "aws-s3"
)
func getEnv(name string) string {
value := os.Getenv(name)
if name == "" {
log.Fatalf("%s must be set and not empty", name)
}
return value
}
func createAwsConfig() *keystore.AwsConfig {
retryOnCredentialsWait, err := time.ParseDuration(os.Getenv("AWS_RETRY_ON_CREDENTIALS_WAIT"))
if err != nil || retryOnCredentialsWait == 0 {
retryOnCredentialsWait = 5 * time.Second
}
return &keystore.AwsConfig{
Endpoint: os.Getenv("AWS_ENDPOINT"),
RetryOnCredentialsWait: retryOnCredentialsWait,
}
}
func createGcpKeystore() *keystore.GcpKeystore {
gcsBucketName := getEnv("GCS_BUCKET_NAME")
kmsKeyID := getEnv("KMS_KEY_ID")
gcpKeystore, err := keystore.NewGcpKeystore(gcsBucketName, kmsKeyID)
if err != nil {
log.Fatalln(err)
}
return gcpKeystore
}
func createAwsKeystore() *keystore.AwsKeystore {
awsKeystore, err := keystore.NewAwsKeystore(&keystore.AwsKeystoreConfig{
AwsConfig: createAwsConfig(),
KmsKeyID: getEnv("KMS_KEY_ID"),
SecretsPath: getEnv("AWS_SECRETS_PATH"),
})
if err != nil {
log.Fatalf("failed to initialize aws store: %v", err)
}
return awsKeystore
}
func createAwsS3Keystore() *keystore.AwsS3Keystore {
s3Keystore, err := keystore.NewAwsS3Keystore(&keystore.AwsS3KeystoreConfig{
AwsConfig: createAwsConfig(),
EncryptionKey: getEnv("AWS_ENCRYPTION_KEY"),
BucketName: getEnv("AWS_BUCKET_NAME"),
BucketPath: getEnv("AWS_BUCKET_PATH"),
})
if err != nil {
log.Fatalf("failed to initialize aws store: %v", err)
}
return s3Keystore
}
func createKeystore() keystore.Keystore {
cloudProvider := os.Getenv("CLOUD_PROVIDER")
if cloudProvider == "" {
cloudProvider = providerGcp
}
switch cloudProvider {
case providerGcp:
return createGcpKeystore()
case providerAws:
return createAwsKeystore()
case providerAwsS3:
return createAwsS3Keystore()
}
log.Fatalf("Unknow CLOUD_PROVIDER: %s", cloudProvider)
return nil
}
func main() {
log.Println("Starting the vault-init service...")
var initOne = flag.String("init-one", "", "Specify a single pod name where vault should be initialized")
flag.Parse()
checkInterval = os.Getenv("CHECK_INTERVAL")
if checkInterval == "" {
checkInterval = "10"
}
i, err := strconv.Atoi(checkInterval)
if err != nil {
log.Fatalf("CHECK_INTERVAL is invalid: %s", err)
}
checkIntervalDuration := time.Duration(i) * time.Second
keystoreClient := createKeystore()
defer keystoreClient.Close()
podName := os.Getenv("POD_NAME")
vaultConfig := api.DefaultConfig()
vaultClient, err := api.NewClient(vaultConfig)
if err != nil {
log.Fatalf("Failed to create vault client %s", err)
}
signalCh := make(chan os.Signal)
signal.Notify(signalCh,
syscall.SIGINT,
syscall.SIGTERM,
syscall.SIGKILL,
)
stop := func() {
log.Printf("Shutting down")
keystoreClient.Close()
os.Exit(0)
}
for {
checkVaultStatus(vaultClient, keystoreClient, *initOne, podName)
select {
case <-signalCh:
stop()
case <-time.After(checkIntervalDuration):
}
}
}
func checkVaultStatus(vaultClient *api.Client, keystoreClient keystore.Keystore, initOne string, podName string) {
response, err := vaultClient.Sys().Health()
if err != nil {
log.Println(err)
return
}
if !response.Initialized {
if initOne != "" && podName == initOne {
log.Println("Vault is not initialized. Initializing...")
initialize(vaultClient, keystoreClient)
}
log.Println("Vault is sealed. Unsealing...")
unseal(vaultClient, keystoreClient)
return
}
if response.Sealed {
log.Println("Vault is sealed. Unsealing...")
unseal(vaultClient, keystoreClient)
return
}
if response.Standby {
log.Println("Vault is unsealed and in standby mode.")
return
}
}
func initialize(vaultClient *api.Client, keystoreClient keystore.Keystore) {
initRequest := api.InitRequest{
SecretShares: 5,
SecretThreshold: 3,
}
initResponse, err := vaultClient.Sys().Init(&initRequest)
if err != nil {
log.Println(err)
return
}
log.Println("Encrypting unseal keys and the root token...")
err = keystoreClient.EncryptAndWrite(initResponse)
if err != nil {
log.Println(err)
return
}
log.Println("Initialization complete.")
}
func unseal(vaultClient *api.Client, keystoreClient keystore.Keystore) {
initResponse, err := keystoreClient.ReadAndDecrypt()
if err != nil {
log.Println(err)
return
}
for _, key := range initResponse.KeysB64 {
done, err := unsealOne(vaultClient, key)
if done {
return
}
if err != nil {
log.Println(err)
return
}
}
}
func unsealOne(vaultClient *api.Client, key string) (bool, error) {
unsealResponse, err := vaultClient.Sys().Unseal(key)
if err != nil {
return false, err
}
if !unsealResponse.Sealed {
return true, nil
}
return false, nil
}