-
Notifications
You must be signed in to change notification settings - Fork 479
/
init.go
596 lines (528 loc) · 20.5 KB
/
init.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
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
/*******************************************************************************
* Copyright 2019 Dell Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*
*******************************************************************************/
package secretstore
import (
"context"
"crypto/sha256"
"encoding/json"
"errors"
"fmt"
"net/http"
"os"
"path/filepath"
"sync"
"time"
"github.com/edgexfoundry/edgex-go/internal"
"github.com/edgexfoundry/edgex-go/internal/security/kdf"
"github.com/edgexfoundry/edgex-go/internal/security/pipedhexreader"
"github.com/edgexfoundry/edgex-go/internal/security/secretstore/config"
"github.com/edgexfoundry/edgex-go/internal/security/secretstore/container"
"github.com/edgexfoundry/edgex-go/internal/security/secretstoreclient"
bootstrapContainer "github.com/edgexfoundry/go-mod-bootstrap/bootstrap/container"
"github.com/edgexfoundry/go-mod-bootstrap/bootstrap/startup"
"github.com/edgexfoundry/go-mod-bootstrap/di"
"github.com/edgexfoundry/go-mod-core-contracts/clients/logger"
"github.com/edgexfoundry/go-mod-secrets/pkg/token/fileioperformer"
)
type Bootstrap struct {
insecureSkipVerify bool
vaultInterval int
}
func NewBootstrap(insecureSkipVerify bool, vaultInterval int) *Bootstrap {
return &Bootstrap{
insecureSkipVerify: insecureSkipVerify,
vaultInterval: vaultInterval,
}
}
// BootstrapHandler fulfills the BootstrapHandler contract and performs initialization needed by the data service.
func (b *Bootstrap) BootstrapHandler(ctx context.Context, _ *sync.WaitGroup, _ startup.Timer, dic *di.Container) bool {
configuration := container.ConfigurationFrom(dic.Get)
lc := bootstrapContainer.LoggingClientFrom(dic.Get)
//step 1: boot up secretstore general steps same as other EdgeX microservice
//step 2: initialize the communications
fileOpener := fileioperformer.NewDefaultFileIoPerformer()
var req internal.HttpCaller
if caFilePath := configuration.SecretService.CaFilePath; caFilePath != "" {
lc.Info("using certificate verification for secret store connection")
caReader, err := fileOpener.OpenFileReader(caFilePath, os.O_RDONLY, 0400)
if err != nil {
lc.Error(fmt.Sprintf("failed to load CA certificate: %s", err.Error()))
return false
}
req = secretstoreclient.NewRequestor(lc).WithTLS(caReader, configuration.SecretService.ServerName)
} else {
lc.Info("bypassing certificate verification for secret store connection")
req = secretstoreclient.NewRequestor(lc).Insecure()
}
vaultScheme := configuration.SecretService.Scheme
vaultHost := fmt.Sprintf("%s:%v", configuration.SecretService.Server, configuration.SecretService.Port)
intervalDuration := time.Duration(b.vaultInterval) * time.Second
vc := secretstoreclient.NewSecretStoreClient(lc, req, vaultScheme, vaultHost)
pipedHexReader := pipedhexreader.NewPipedHexReader()
kdf := kdf.NewKdf(fileOpener, configuration.SecretService.TokenFolderPath, sha256.New)
vmkEncryption := NewVMKEncryption(fileOpener, pipedHexReader, kdf)
hook := os.Getenv("IKM_HOOK")
if len(hook) > 0 {
err := vmkEncryption.LoadIKM(hook)
defer vmkEncryption.WipeIKM() // Ensure IKM is wiped from memory
if err != nil {
lc.Error(fmt.Sprintf("failed to setup vault master key encryption: %s", err.Error()))
return false
}
lc.Info("Enabled encryption of Vault master key")
} else {
lc.Info("vault master key encryption not enabled. IKM_HOOK not set.")
}
var initResponse secretstoreclient.InitResponse // reused many places in below flow
//step 3: initialize and unseal Vault
for shouldContinue := true; shouldContinue; {
// Anonymous function used to prevent file handles from accumulating
successful := func() bool {
sCode, _ := vc.HealthCheck()
switch sCode {
case http.StatusOK:
// Load the init response from disk since we need it to regenerate root token later
if err := loadInitResponse(lc, fileOpener, configuration.SecretService, &initResponse); err != nil {
lc.Error(fmt.Sprintf("unable to load init response: %s", err.Error()))
return false
}
lc.Info(fmt.Sprintf("vault is initialized and unsealed (status code: %d)", sCode))
shouldContinue = false
case http.StatusTooManyRequests:
lc.Error(fmt.Sprintf("vault is unsealed and in standby mode (Status Code: %d)", sCode))
shouldContinue = false
case http.StatusNotImplemented:
lc.Info(fmt.Sprintf("vault is not initialized (status code: %d). Starting initialization and unseal phases", sCode))
_, err := vc.Init(configuration.SecretService.VaultSecretThreshold,
configuration.SecretService.VaultSecretShares, &initResponse)
if configuration.SecretService.RevokeRootTokens {
// Never persist the root token to disk on secret store initialization if we intend to revoke it later
initResponse.RootToken = ""
lc.Info("Root token stripped from init response for security reasons")
}
_, err = vc.Unseal(&initResponse)
if err == nil {
shouldContinue = false
}
// We need the unencrypted initResponse in order to generate a temporary root token later
// Make a copy and save the copy, possibly encrypted
encryptedInitResponse := initResponse
// Optionally encrypt the vault init response based on whether encryption was enabled
if vmkEncryption.IsEncrypting() {
if err := vmkEncryption.EncryptInitResponse(&encryptedInitResponse); err != nil {
lc.Error(fmt.Sprintf("failed to encrypt init response from secret store: %s", err.Error()))
return false
}
}
if err := saveInitResponse(lc, fileOpener, configuration.SecretService, &encryptedInitResponse); err != nil {
lc.Error(fmt.Sprintf("unable to save init response: %s", err.Error()))
return false
}
case http.StatusServiceUnavailable:
lc.Info(fmt.Sprintf("vault is sealed (status code: %d). Starting unseal phase", sCode))
if err := loadInitResponse(lc, fileOpener, configuration.SecretService, &initResponse); err != nil {
lc.Error(fmt.Sprintf("unable to load init response: %s", err.Error()))
return false
}
// Optionally decrypt the vault init response based on whether encryption was enabled
if vmkEncryption.IsEncrypting() {
if err := vmkEncryption.DecryptInitResponse(&initResponse); err != nil {
lc.Error(fmt.Sprintf("failed to decrypt key shares for sercret store unsealing: %s", err.Error()))
return false
}
}
_, err := vc.Unseal(&initResponse)
if err == nil {
shouldContinue = false
}
default:
if sCode == 0 {
lc.Error(fmt.Sprintf("vault is in an unknown state. No Status code available"))
} else {
lc.Error(fmt.Sprintf("vault is in an unknown state. Status code: %d", sCode))
}
}
return true
}()
if !successful {
return false
}
if shouldContinue {
lc.Info(fmt.Sprintf("trying Vault init/unseal again in %d seconds", b.vaultInterval))
time.Sleep(intervalDuration)
}
}
/* After vault is init'd and unsealed, it takes a while to get ready to accept any request. During which period any request will get http 500 error.
We need to check the status constantly until it return http StatusOK.
*/
ticker := time.NewTicker(time.Second)
healthOkCh := make(chan struct{})
go func() {
for {
select {
case <-ticker.C:
if sCode, _ := vc.HealthCheck(); sCode == http.StatusOK {
close(healthOkCh)
ticker.Stop()
return
}
}
}
}()
// Wait on a StatusOK response from vc.HealthCheck()
<-healthOkCh
// create new root token
// defer revoke token
// optional: revoke other root token
// revoke old tokens
// create delegate credential
// spawn token provider
// create db credentials
// upload kong certificate
tokenMaintenance := NewTokenMaintenance(lc, vc)
// Create a transient root token from the key shares
var rootToken string
if err := vc.RegenRootToken(&initResponse, &rootToken); err != nil {
lc.Error(fmt.Sprintf("could not regenerate root token %s", err.Error()))
os.Exit(1)
}
defer func() {
// Revoke transient root token at the end of this funciton
lc.Info("revoking temporary root token")
_, err := vc.RevokeSelf(rootToken)
if err != nil {
lc.Error(fmt.Sprintf("could not revoke temporary root token %s", err.Error()))
}
}()
lc.Info("generated transient root token")
// Revoke the other root tokens
if configuration.SecretService.RevokeRootTokens {
if initResponse.RootToken != "" {
initResponse.RootToken = ""
if err := saveInitResponse(lc, fileOpener, configuration.SecretService, &initResponse); err != nil {
lc.Error(fmt.Sprintf("unable to save init response: %s", err.Error()))
os.Exit(1)
}
lc.Info("Root token stripped from init response (on disk) for security reasons")
}
if err := tokenMaintenance.RevokeRootTokens(rootToken); err != nil {
lc.Warn(fmt.Sprintf("failed to revoke non-transient root tokens %s", err.Error()))
}
lc.Info("completed cleanup of old root tokens")
} else {
lc.Info("not revoking existing root tokens")
}
// Revoke non-root tokens from previous runs
if err := tokenMaintenance.RevokeNonRootTokens(rootToken); err != nil {
lc.Warn("failed to revoke non-root tokens")
}
lc.Info("completed cleanup of old admin/service tokens")
// If configured to do so, create a token issuing token
if configuration.SecretService.TokenProviderAdminTokenPath != "" {
revokeIssuingTokenFuc, err := makeTokenIssuingToken(lc, configuration, tokenMaintenance, fileOpener, rootToken)
if err != nil {
lc.Error(fmt.Sprintf("failed to create token issuing token %s", err.Error()))
os.Exit(1)
}
if configuration.SecretService.TokenProviderType == OneShotProvider {
// Revoke the admin token at the end of the current function if running a one-shot provider
// otherwise assume the token provider will keep its token fresh after this point
defer revokeIssuingTokenFuc()
}
}
//Step 4: Launch token handler
tokenProvider := NewTokenProvider(ctx, lc, NewDefaultExecRunner())
if configuration.SecretService.TokenProvider != "" {
if err := tokenProvider.SetConfiguration(configuration.SecretService); err != nil {
lc.Error(fmt.Sprintf("failed to configure token provider: %s", err.Error()))
os.Exit(1)
}
if err := tokenProvider.Launch(); err != nil {
lc.Error(fmt.Sprintf("token provider failed: %s", err.Error()))
os.Exit(1)
}
} else {
lc.Info("no token provider configured")
}
// Enable KV secret engine
if err := enableKVSecretsEngine(lc, vc, rootToken); err != nil {
lc.Error(fmt.Sprintf("failed to enable KV secrets engine: %s", err.Error()))
os.Exit(1)
}
// credential creation
gen := NewPasswordGenerator(lc, configuration.SecretService.PasswordProvider, configuration.SecretService.PasswordProviderArgs)
cred := NewCred(req, rootToken, gen, configuration.SecretService.GetSecretSvcBaseURL(), lc)
// continue credential creation
// A little note on why there are two secrets paths. For each microservice, the username/password
// is uploaded to the vault on both /v1/secret/edgex/%s/mongodb and /v1/secret/edgex/mongo/%s).
// The go-mod-secrets client requires a Path property to prefix all secrets. docker-edgex-mongo
// uses that
// (https://github.com/edgexfoundry/docker-edgex-mongo/blob/master/cmd/res/configuration.toml) in
// order to enumerate the users and passwords when setting up the initial database authentication.
// So edgex/%s/mongodb is for the microservices (microservices are restricted to their specific
// edgex/%s), and edgex/mongo/* is enumerated by docker-edgex-mongo to initialize the database.
//
// The Redis implementation parallels the existing Mongo code but until the update for Redis 6,
// there is only a single Redis password.
//
// Redis 5.x only supports a single shared password. When Redis 6 is released, this can be updated
// to a per service password.
redis5Password, err := cred.GeneratePassword(ctx)
if err != nil {
lc.Error("failed to generate redis5 password")
os.Exit(1)
}
redis5Pair := UserPasswordPair{
User: "redis5",
Password: redis5Password,
}
for dbname, info := range configuration.Databases {
service := info.Service
// generate credentials
password, err := cred.GeneratePassword(ctx)
if err != nil {
lc.Error(fmt.Sprintf("failed to generate credential pair for service %s", service))
os.Exit(1)
}
pair := UserPasswordPair{
User: info.Username,
Password: password,
}
// add credentials to service path if specified and they're not already there
if len(service) != 0 {
err = addServiceCredential(lc, "mongodb", cred, service, pair)
if err != nil {
lc.Error(err.Error())
os.Exit(1)
}
err = addServiceCredential(lc, "redisdb", cred, service, redis5Pair)
if err != nil {
lc.Error(err.Error())
os.Exit(1)
}
}
err = addDBCredential(lc, "mongo", cred, dbname, pair)
if err != nil {
lc.Error(err.Error())
os.Exit(1)
}
}
// security-bootstrap-redis uses the path /v1/secret/edgex/bootstrap-redis/ and go-mod-bootstrap
// with append the DB type (redisdb)
err = addDBCredential(lc, "bootstrap-redis", cred, "redisdb", redis5Pair)
if err != nil {
lc.Error(err.Error())
os.Exit(1)
}
cert := NewCerts(req, configuration.SecretService.CertPath, rootToken, configuration.SecretService.GetSecretSvcBaseURL(), lc)
existing, err := cert.AlreadyinStore()
if err != nil {
lc.Error(err.Error())
os.Exit(1)
}
if existing == true {
lc.Info("proxy certificate pair are in the secret store already, skip uploading")
return false
}
lc.Info("proxy certificate pair are not in the secret store yet, uploading them")
cp, err := cert.ReadFrom(configuration.SecretService.CertFilePath, configuration.SecretService.KeyFilePath)
if err != nil {
lc.Error("failed to get certificate pair from volume")
os.Exit(1)
}
lc.Info("proxy certificate pair are loaded from volume successfully, will upload to secret store")
err = cert.UploadToStore(cp)
if err != nil {
lc.Error("failed to upload the proxy cert pair into the secret store")
lc.Error(err.Error())
os.Exit(1)
}
lc.Info("proxy certificate pair are uploaded to secret store successfully, Vault init done successfully")
return false
}
// XXX Collapse addServiceCredential and addDBCredential together by passing in the path or using
// variadic functions
func addServiceCredential(lc logger.LoggingClient, db string, cred Cred, service string, pair UserPasswordPair) error {
path := fmt.Sprintf("/v1/secret/edgex/%s/%s", service, db)
existing, err := cred.AlreadyInStore(path)
if err != nil {
return err
}
if !existing {
err = cred.UploadToStore(&pair, path)
if err != nil {
lc.Error(fmt.Sprintf("failed to upload credential pair for %s on path %s", service, path))
return err
}
} else {
lc.Info(fmt.Sprintf("credentials for %s already present at path %s", service, path))
}
return err
}
func addDBCredential(lc logger.LoggingClient, db string, cred Cred, service string, pair UserPasswordPair) error {
path := fmt.Sprintf("/v1/secret/edgex/%s/%s", db, service)
existing, err := cred.AlreadyInStore(path)
if err != nil {
lc.Error(err.Error())
return err
}
if !existing {
err = cred.UploadToStore(&pair, path)
if err != nil {
lc.Error(fmt.Sprintf("failed to upload credential pair for db %s on path %s", service, path))
return err
}
} else {
lc.Info(fmt.Sprintf("credentials for %s already present at path %s", service, path))
}
return err
}
func makeTokenIssuingToken(
lc logger.LoggingClient,
configuration *config.ConfigurationStruct,
tokenMaintenance *TokenMaintenance,
fileOpener fileioperformer.FileIoPerformer,
rootToken string) (RevokeFunc, error) {
configAdminTokenPath := configuration.SecretService.TokenProviderAdminTokenPath
if configAdminTokenPath == "" {
err := fmt.Errorf("TokenProviderAdminTokenPath is a required configuration setting")
lc.Error(err.Error())
return nil, err
}
// Create delegate credential for use by the token provider
tokenIssuingToken, revokeIssuingTokenFuc, err := tokenMaintenance.CreateTokenIssuingToken(rootToken)
if err != nil {
lc.Error(fmt.Sprintf("failed to create token issuing token %s", err.Error()))
return nil, err
}
lc.Info("created token issuing token")
// Write the token issuing token to disk to pass it to the token provider
adminTokenPath, err := filepath.Abs(configAdminTokenPath)
if err != nil {
lc.Error(fmt.Sprintf("failed to convert to absolute path %s: %s", configAdminTokenPath, err.Error()))
revokeIssuingTokenFuc()
return nil, err
}
dirOfAdminToken := filepath.Dir(adminTokenPath)
err = fileOpener.MkdirAll(dirOfAdminToken, 0700)
if err != nil {
lc.Error(fmt.Sprintf("failed to create tokenpath base dir: %s", err.Error()))
revokeIssuingTokenFuc()
return nil, err
}
tokenWriter, err := fileOpener.OpenFileWriter(adminTokenPath, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0600)
if err != nil {
lc.Error(fmt.Sprintf("failed to create token issuing file %s: %s", adminTokenPath, err.Error()))
revokeIssuingTokenFuc()
return nil, err
}
encoder := json.NewEncoder(tokenWriter)
if encoder == nil {
err := fmt.Errorf("failed to create token encoder")
lc.Error(err.Error())
tokenWriter.Close()
revokeIssuingTokenFuc()
return nil, err
}
if err = encoder.Encode(tokenIssuingToken); err != nil {
lc.Error(fmt.Sprintf("failed to write token issing token: %s", err.Error()))
tokenWriter.Close()
revokeIssuingTokenFuc()
return nil, err
}
if err = tokenWriter.Close(); err != nil {
lc.Error(fmt.Sprintf("failed to close token issuing file: %s", err.Error()))
revokeIssuingTokenFuc()
return nil, err
}
return revokeIssuingTokenFuc, nil
}
func enableKVSecretsEngine(
lc logger.LoggingClient,
vc secretstoreclient.SecretStoreClient,
rootToken string) error {
installed, err := vc.CheckSecretEngineInstalled(rootToken, "secret/", "kv")
if err != nil {
lc.Error(fmt.Sprintf("failed call to check if kv secrets engine is installed: %s", err.Error()))
return err
}
if !installed {
lc.Info("enabling KV secrets engine for the first time...")
// Enable KV version 1 at /v1/secret path (/v1 prefix supplied by Vault)
_, err := vc.EnableKVSecretEngine(rootToken, "secret", "1")
if err != nil {
lc.Error(fmt.Sprintf("failed call to enable KV secrets engine: %s", err.Error()))
return err
}
} else {
lc.Info("KV secrets engine already enabled...")
}
return nil
}
func loadInitResponse(
lc logger.LoggingClient,
fileOpener fileioperformer.FileIoPerformer,
secretConfig secretstoreclient.SecretServiceInfo,
initResponse *secretstoreclient.InitResponse) error {
absPath := filepath.Join(secretConfig.TokenFolderPath, secretConfig.TokenFile)
tokenFile, err := fileOpener.OpenFileReader(absPath, os.O_RDONLY, 0400)
if err != nil {
lc.Error(fmt.Sprintf("could not read master key shares file %s: %s", absPath, err.Error()))
return err
}
tokenFileCloseable := fileioperformer.MakeReadCloser(tokenFile)
defer tokenFileCloseable.Close()
decoder := json.NewDecoder(tokenFileCloseable)
if decoder == nil {
err := errors.New("Failed to create JSON decoder")
lc.Error(err.Error())
return err
}
if err := decoder.Decode(initResponse); err != nil {
lc.Error(fmt.Sprintf("unable to read token file at %s with error: %s", absPath, err.Error()))
return err
}
return nil
}
func saveInitResponse(
lc logger.LoggingClient,
fileOpener fileioperformer.FileIoPerformer,
secretConfig secretstoreclient.SecretServiceInfo,
initResponse *secretstoreclient.InitResponse) error {
absPath := filepath.Join(secretConfig.TokenFolderPath, secretConfig.TokenFile)
tokenFile, err := fileOpener.OpenFileWriter(absPath, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0600)
if err != nil {
lc.Error(fmt.Sprintf("could not read master key shares file %s: %s", absPath, err.Error()))
return err
}
encoder := json.NewEncoder(tokenFile)
if encoder == nil {
err := errors.New("Failed to create JSON encoder")
lc.Error(err.Error())
_ = tokenFile.Close()
return err
}
if err := encoder.Encode(initResponse); err != nil {
lc.Error(fmt.Sprintf("unable to write token file at %s with error: %s", absPath, err.Error()))
_ = tokenFile.Close()
return err
}
if err := tokenFile.Close(); err != nil {
lc.Error(fmt.Sprintf("unable to close token file at %s with error: %s", absPath, err.Error()))
_ = tokenFile.Close()
return err
}
return nil
}