-
Notifications
You must be signed in to change notification settings - Fork 64
/
main.go
381 lines (310 loc) · 8.16 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
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
// 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 (
"bytes"
"context"
"crypto/tls"
"encoding/base64"
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
"os/signal"
"runtime"
"strconv"
"syscall"
"time"
"cloud.google.com/go/storage"
"golang.org/x/oauth2/google"
"google.golang.org/api/cloudkms/v1"
"google.golang.org/api/option"
)
var (
vaultAddr string
checkInterval string
gcsBucketName string
httpClient http.Client
kmsService *cloudkms.Service
kmsKeyId string
storageClient *storage.Client
userAgent = fmt.Sprintf("vault-init/0.1.0 (%s)", runtime.Version())
)
// InitRequest holds a Vault init request.
type InitRequest struct {
SecretShares int `json:"secret_shares"`
SecretThreshold int `json:"secret_threshold"`
}
// InitResponse holds a Vault init response.
type InitResponse struct {
Keys []string `json:"keys"`
KeysBase64 []string `json:"keys_base64"`
RootToken string `json:"root_token"`
}
// UnsealRequest holds a Vault unseal request.
type UnsealRequest struct {
Key string `json:"key"`
Reset bool `json:"reset"`
}
// UnsealResponse holds a Vault unseal response.
type UnsealResponse struct {
Sealed bool `json:"sealed"`
T int `json:"t"`
N int `json:"n"`
Progress int `json:"progress"`
}
func main() {
log.Println("Starting the vault-init service...")
vaultAddr = os.Getenv("VAULT_ADDR")
if vaultAddr == "" {
vaultAddr = "https://127.0.0.1:8200"
}
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
gcsBucketName = os.Getenv("GCS_BUCKET_NAME")
if gcsBucketName == "" {
log.Fatal("GCS_BUCKET_NAME must be set and not empty")
}
kmsKeyId = os.Getenv("KMS_KEY_ID")
if kmsKeyId == "" {
log.Fatal("KMS_KEY_ID must be set and not empty")
}
kmsCtx, kmsCtxCancel := context.WithCancel(context.Background())
defer kmsCtxCancel()
kmsClient, err := google.DefaultClient(kmsCtx, "https://www.googleapis.com/auth/cloudkms")
if err != nil {
log.Println(err)
return
}
kmsService, err = cloudkms.New(kmsClient)
if err != nil {
log.Println(err)
return
}
kmsService.UserAgent = userAgent
storageCtx, storageCtxCancel := context.WithCancel(context.Background())
defer storageCtxCancel()
storageClient, err = storage.NewClient(storageCtx,
option.WithUserAgent(userAgent),
option.WithScopes(storage.ScopeReadWrite),
)
if err != nil {
log.Fatal(err)
}
httpClient = http.Client{
Transport: &http.Transport{
TLSClientConfig: &tls.Config{
InsecureSkipVerify: true,
},
},
}
signalCh := make(chan os.Signal)
signal.Notify(signalCh,
syscall.SIGINT,
syscall.SIGTERM,
syscall.SIGKILL,
)
stop := func() {
log.Printf("Shutting down")
kmsCtxCancel()
storageCtxCancel()
os.Exit(0)
}
for {
select {
case <-signalCh:
stop()
default:
}
response, err := httpClient.Head(vaultAddr + "/v1/sys/health")
if response != nil && response.Body != nil {
response.Body.Close()
}
if err != nil {
log.Println(err)
time.Sleep(checkIntervalDuration)
continue
}
switch response.StatusCode {
case 200:
log.Println("Vault is initialized and unsealed.")
case 429:
log.Println("Vault is unsealed and in standby mode.")
case 501:
log.Println("Vault is not initialized. Initializing and unsealing...")
initialize()
unseal()
case 503:
log.Println("Vault is sealed. Unsealing...")
unseal()
default:
log.Printf("Vault is in an unknown state. Status code: %d", response.StatusCode)
}
log.Printf("Next check in %s", checkIntervalDuration)
select {
case <-signalCh:
stop()
case <-time.After(checkIntervalDuration):
}
}
}
func initialize() {
initRequest := InitRequest{
SecretShares: 5,
SecretThreshold: 3,
}
initRequestData, err := json.Marshal(&initRequest)
if err != nil {
log.Println(err)
return
}
r := bytes.NewReader(initRequestData)
request, err := http.NewRequest("PUT", vaultAddr+"/v1/sys/init", r)
if err != nil {
log.Println(err)
return
}
response, err := httpClient.Do(request)
if err != nil {
log.Println(err)
return
}
defer response.Body.Close()
initRequestResponseBody, err := ioutil.ReadAll(response.Body)
if err != nil {
log.Println(err)
return
}
if response.StatusCode != 200 {
log.Printf("init: non 200 status code: %d", response.StatusCode)
return
}
var initResponse InitResponse
if err := json.Unmarshal(initRequestResponseBody, &initResponse); err != nil {
log.Println(err)
return
}
log.Println("Encrypting unseal keys and the root token...")
rootTokenEncryptRequest := &cloudkms.EncryptRequest{
Plaintext: base64.StdEncoding.EncodeToString([]byte(initResponse.RootToken)),
}
rootTokenEncryptResponse, err := kmsService.Projects.Locations.KeyRings.CryptoKeys.Encrypt(kmsKeyId, rootTokenEncryptRequest).Do()
if err != nil {
log.Println(err)
return
}
unsealKeysEncryptRequest := &cloudkms.EncryptRequest{
Plaintext: base64.StdEncoding.EncodeToString(initRequestResponseBody),
}
unsealKeysEncryptResponse, err := kmsService.Projects.Locations.KeyRings.CryptoKeys.Encrypt(kmsKeyId, unsealKeysEncryptRequest).Do()
if err != nil {
log.Println(err)
return
}
bucket := storageClient.Bucket(gcsBucketName)
// Save the encrypted unseal keys.
ctx := context.Background()
unsealKeysObject := bucket.Object("unseal-keys.json.enc").NewWriter(ctx)
defer unsealKeysObject.Close()
_, err = unsealKeysObject.Write([]byte(unsealKeysEncryptResponse.Ciphertext))
if err != nil {
log.Println(err)
}
log.Printf("Unseal keys written to gs://%s/%s", gcsBucketName, "unseal-keys.json.enc")
// Save the encrypted root token.
rootTokenObject := bucket.Object("root-token.enc").NewWriter(ctx)
defer rootTokenObject.Close()
_, err = rootTokenObject.Write([]byte(rootTokenEncryptResponse.Ciphertext))
if err != nil {
log.Println(err)
}
log.Printf("Root token written to gs://%s/%s", gcsBucketName, "root-token.enc")
log.Println("Initialization complete.")
}
func unseal() {
bucket := storageClient.Bucket(gcsBucketName)
ctx := context.Background()
unsealKeysObject, err := bucket.Object("unseal-keys.json.enc").NewReader(ctx)
if err != nil {
log.Println(err)
return
}
defer unsealKeysObject.Close()
unsealKeysData, err := ioutil.ReadAll(unsealKeysObject)
if err != nil {
log.Println(err)
return
}
unsealKeysDecryptRequest := &cloudkms.DecryptRequest{
Ciphertext: string(unsealKeysData),
}
unsealKeysDecryptResponse, err := kmsService.Projects.Locations.KeyRings.CryptoKeys.Decrypt(kmsKeyId, unsealKeysDecryptRequest).Do()
if err != nil {
log.Println(err)
return
}
var initResponse InitResponse
unsealKeysPlaintext, err := base64.StdEncoding.DecodeString(unsealKeysDecryptResponse.Plaintext)
if err != nil {
log.Println(err)
return
}
if err := json.Unmarshal(unsealKeysPlaintext, &initResponse); err != nil {
log.Println(err)
return
}
for _, key := range initResponse.KeysBase64 {
done, err := unsealOne(key)
if done {
return
}
if err != nil {
log.Println(err)
return
}
}
}
func unsealOne(key string) (bool, error) {
unsealRequest := UnsealRequest{
Key: key,
}
unsealRequestData, err := json.Marshal(&unsealRequest)
if err != nil {
return false, err
}
r := bytes.NewReader(unsealRequestData)
request, err := http.NewRequest(http.MethodPut, vaultAddr+"/v1/sys/unseal", r)
if err != nil {
return false, err
}
response, err := httpClient.Do(request)
if err != nil {
return false, err
}
defer response.Body.Close()
if response.StatusCode != 200 {
return false, fmt.Errorf("unseal: non-200 status code: %d", response.StatusCode)
}
unsealRequestResponseBody, err := ioutil.ReadAll(response.Body)
if err != nil {
return false, err
}
var unsealResponse UnsealResponse
if err := json.Unmarshal(unsealRequestResponseBody, &unsealResponse); err != nil {
return false, err
}
if !unsealResponse.Sealed {
return true, nil
}
return false, nil
}