forked from hashicorp/vault
-
Notifications
You must be signed in to change notification settings - Fork 2
/
server.go
1495 lines (1292 loc) · 40.6 KB
/
server.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
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package command
import (
"context"
"encoding/base64"
"fmt"
"io/ioutil"
"net"
"net/http"
"net/url"
"os"
"path/filepath"
"runtime"
"sort"
"strconv"
"strings"
"sync"
"time"
colorable "github.com/mattn/go-colorable"
log "github.com/mgutz/logxi/v1"
"github.com/mitchellh/cli"
testing "github.com/mitchellh/go-testing-interface"
"github.com/posener/complete"
"google.golang.org/grpc/grpclog"
"github.com/armon/go-metrics"
"github.com/armon/go-metrics/circonus"
"github.com/armon/go-metrics/datadog"
"github.com/hashicorp/errwrap"
hclog "github.com/hashicorp/go-hclog"
"github.com/hashicorp/go-multierror"
"github.com/hashicorp/vault/audit"
"github.com/hashicorp/vault/command/server"
"github.com/hashicorp/vault/helper/gated-writer"
"github.com/hashicorp/vault/helper/logbridge"
"github.com/hashicorp/vault/helper/logformat"
"github.com/hashicorp/vault/helper/mlock"
"github.com/hashicorp/vault/helper/parseutil"
"github.com/hashicorp/vault/helper/reload"
vaulthttp "github.com/hashicorp/vault/http"
"github.com/hashicorp/vault/logical"
"github.com/hashicorp/vault/physical"
"github.com/hashicorp/vault/vault"
"github.com/hashicorp/vault/version"
)
var _ cli.Command = (*ServerCommand)(nil)
var _ cli.CommandAutocomplete = (*ServerCommand)(nil)
type ServerCommand struct {
*BaseCommand
AuditBackends map[string]audit.Factory
CredentialBackends map[string]logical.Factory
LogicalBackends map[string]logical.Factory
PhysicalBackends map[string]physical.Factory
ShutdownCh chan struct{}
SighupCh chan struct{}
WaitGroup *sync.WaitGroup
logGate *gatedwriter.Writer
logger log.Logger
cleanupGuard sync.Once
reloadFuncsLock *sync.RWMutex
reloadFuncs *map[string][]reload.ReloadFunc
startedCh chan (struct{}) // for tests
reloadedCh chan (struct{}) // for tests
// new stuff
flagConfigs []string
flagLogLevel string
flagDev bool
flagDevRootTokenID string
flagDevListenAddr string
flagDevPluginDir string
flagDevHA bool
flagDevLatency int
flagDevLatencyJitter int
flagDevLeasedKV bool
flagDevSkipInit bool
flagDevThreeNode bool
flagDevTransactional bool
flagTestVerifyOnly bool
}
func (c *ServerCommand) Synopsis() string {
return "Start a Vault server"
}
func (c *ServerCommand) Help() string {
helpText := `
Usage: vault server [options]
This command starts a Vault server that responds to API requests. By default,
Vault will start in a "sealed" state. The Vault cluster must be initialized
before use, usually by the "vault init" command. Each Vault server must also
be unsealed using the "vault unseal" command or the API before the server can
respond to requests.
Start a server with a configuration file:
$ vault server -config=/etc/vault/config.hcl
Run in "dev" mode:
$ vault server -dev -dev-root-token-id="root"
For a full list of examples, please see the documentation.
` + c.Flags().Help()
return strings.TrimSpace(helpText)
}
func (c *ServerCommand) Flags() *FlagSets {
set := c.flagSet(FlagSetHTTP)
f := set.NewFlagSet("Command Options")
f.StringSliceVar(&StringSliceVar{
Name: "config",
Target: &c.flagConfigs,
Completion: complete.PredictOr(
complete.PredictFiles("*.hcl"),
complete.PredictFiles("*.json"),
complete.PredictDirs("*"),
),
Usage: "Path to a configuration file or directory of configuration " +
"files. This flag can be specified multiple times to load multiple " +
"configurations. If the path is a directory, all files which end in " +
".hcl or .json are loaded.",
})
f.StringVar(&StringVar{
Name: "log-level",
Target: &c.flagLogLevel,
Default: "info",
EnvVar: "VAULT_LOG_LEVEL",
Completion: complete.PredictSet("trace", "debug", "info", "warn", "err"),
Usage: "Log verbosity level. Supported values (in order of detail) are " +
"\"trace\", \"debug\", \"info\", \"warn\", and \"err\".",
})
f = set.NewFlagSet("Dev Options")
f.BoolVar(&BoolVar{
Name: "dev",
Target: &c.flagDev,
Usage: "Enable development mode. In this mode, Vault runs in-memory and " +
"starts unsealed. As the name implies, do not run \"dev\" mode in " +
"production.",
})
f.StringVar(&StringVar{
Name: "dev-root-token-id",
Target: &c.flagDevRootTokenID,
Default: "",
EnvVar: "VAULT_DEV_ROOT_TOKEN_ID",
Usage: "Initial root token. This only applies when running in \"dev\" " +
"mode.",
})
f.StringVar(&StringVar{
Name: "dev-listen-address",
Target: &c.flagDevListenAddr,
Default: "127.0.0.1:8200",
EnvVar: "VAULT_DEV_LISTEN_ADDRESS",
Usage: "Address to bind to in \"dev\" mode.",
})
// Internal-only flags to follow.
//
// Why hello there little source code reader! Welcome to the Vault source
// code. The remaining options are intentionally undocumented and come with
// no warranty or backwards-compatability promise. Do not use these flags
// in production. Do not build automation using these flags. Unless you are
// developing against Vault, you should not need any of these flags.
f.StringVar(&StringVar{
Name: "dev-plugin-dir",
Target: &c.flagDevPluginDir,
Default: "",
Completion: complete.PredictDirs("*"),
Hidden: true,
})
f.BoolVar(&BoolVar{
Name: "dev-ha",
Target: &c.flagDevHA,
Default: false,
Hidden: true,
})
f.BoolVar(&BoolVar{
Name: "dev-transactional",
Target: &c.flagDevTransactional,
Default: false,
Hidden: true,
})
f.IntVar(&IntVar{
Name: "dev-latency",
Target: &c.flagDevLatency,
Hidden: true,
})
f.IntVar(&IntVar{
Name: "dev-latency-jitter",
Target: &c.flagDevLatencyJitter,
Hidden: true,
})
f.BoolVar(&BoolVar{
Name: "dev-leased-kv",
Target: &c.flagDevLeasedKV,
Default: false,
Hidden: true,
})
f.BoolVar(&BoolVar{
Name: "dev-skip-init",
Target: &c.flagDevSkipInit,
Default: false,
Hidden: true,
})
f.BoolVar(&BoolVar{
Name: "dev-three-node",
Target: &c.flagDevThreeNode,
Default: false,
Hidden: true,
})
// TODO: should this be a public flag?
f.BoolVar(&BoolVar{
Name: "test-verify-only",
Target: &c.flagTestVerifyOnly,
Default: false,
Hidden: true,
})
// End internal-only flags.
return set
}
func (c *ServerCommand) AutocompleteArgs() complete.Predictor {
return complete.PredictNothing
}
func (c *ServerCommand) AutocompleteFlags() complete.Flags {
return c.Flags().Completions()
}
func (c *ServerCommand) Run(args []string) int {
f := c.Flags()
if err := f.Parse(args); err != nil {
c.UI.Error(err.Error())
return 1
}
// Create a logger. We wrap it in a gated writer so that it doesn't
// start logging too early.
c.logGate = &gatedwriter.Writer{Writer: colorable.NewColorable(os.Stderr)}
var level int
c.flagLogLevel = strings.ToLower(strings.TrimSpace(c.flagLogLevel))
switch c.flagLogLevel {
case "trace":
level = log.LevelTrace
case "debug":
level = log.LevelDebug
case "info", "":
level = log.LevelInfo
case "notice":
level = log.LevelNotice
case "warn", "warning":
level = log.LevelWarn
case "err", "error":
level = log.LevelError
default:
c.UI.Error(fmt.Sprintf("Unknown log level: %s", c.flagLogLevel))
return 1
}
logFormat := os.Getenv("VAULT_LOG_FORMAT")
if logFormat == "" {
logFormat = os.Getenv("LOGXI_FORMAT")
}
switch strings.ToLower(logFormat) {
case "vault", "vault_json", "vault-json", "vaultjson", "json", "":
if c.flagDevThreeNode {
c.logger = logbridge.NewLogger(hclog.New(&hclog.LoggerOptions{
Mutex: &sync.Mutex{},
Output: c.logGate,
})).LogxiLogger()
} else {
c.logger = logformat.NewVaultLoggerWithWriter(c.logGate, level)
}
default:
c.logger = log.NewLogger(c.logGate, "vault")
c.logger.SetLevel(level)
}
grpclog.SetLogger(&grpclogFaker{
logger: c.logger,
log: os.Getenv("VAULT_GRPC_LOGGING") != "",
})
// Automatically enable dev mode if other dev flags are provided.
if c.flagDevHA || c.flagDevTransactional || c.flagDevLeasedKV || c.flagDevThreeNode {
c.flagDev = true
}
// Validation
if !c.flagDev {
switch {
case len(c.flagConfigs) == 0:
c.UI.Error("Must specify at least one config path using -config")
return 1
case c.flagDevRootTokenID != "":
c.UI.Warn(wrapAtLength(
"You cannot specify a custom root token ID outside of \"dev\" mode. " +
"Your request has been ignored."))
c.flagDevRootTokenID = ""
}
}
// Load the configuration
var config *server.Config
if c.flagDev {
config = server.DevConfig(c.flagDevHA, c.flagDevTransactional)
if c.flagDevListenAddr != "" {
config.Listeners[0].Config["address"] = c.flagDevListenAddr
}
}
for _, path := range c.flagConfigs {
current, err := server.LoadConfig(path, c.logger)
if err != nil {
c.UI.Error(fmt.Sprintf("Error loading configuration from %s: %s", path, err))
return 1
}
if config == nil {
config = current
} else {
config = config.Merge(current)
}
}
// Ensure at least one config was found.
if config == nil {
c.UI.Output(wrapAtLength(
"No configuration files found. Please provide configurations with the " +
"-config flag. If you are supply the path to a directory, please " +
"ensure the directory contains files with the .hcl or .json " +
"extension."))
return 1
}
// Ensure that a backend is provided
if config.Storage == nil {
c.UI.Output("A storage backend must be specified")
return 1
}
// If mlockall(2) isn't supported, show a warning. We disable this
// in dev because it is quite scary to see when first using Vault.
if !c.flagDev && !mlock.Supported() {
c.UI.Warn(wrapAtLength(
"WARNING! mlock is not supported on this system! An mlockall(2)-like " +
"syscall to prevent memory from being swapped to disk is not " +
"supported on this system. For better security, only run Vault on " +
"systems where this call is supported. If you are running Vault " +
"in a Docker container, provide the IPC_LOCK cap to the container."))
}
if err := c.setupTelemetry(config); err != nil {
c.UI.Error(fmt.Sprintf("Error initializing telemetry: %s", err))
return 1
}
// Initialize the backend
factory, exists := c.PhysicalBackends[config.Storage.Type]
if !exists {
c.UI.Error(fmt.Sprintf("Unknown storage type %s", config.Storage.Type))
return 1
}
backend, err := factory(config.Storage.Config, c.logger)
if err != nil {
c.UI.Error(fmt.Sprintf("Error initializing storage of type %s: %s", config.Storage.Type, err))
return 1
}
infoKeys := make([]string, 0, 10)
info := make(map[string]string)
info["log level"] = c.flagLogLevel
infoKeys = append(infoKeys, "log level")
var seal vault.Seal = &vault.DefaultSeal{}
// Ensure that the seal finalizer is called, even if using verify-only
defer func() {
if seal != nil {
err = seal.Finalize(context.Background())
if err != nil {
c.UI.Error(fmt.Sprintf("Error finalizing seals: %v", err))
}
}
}()
if seal == nil {
c.UI.Error(fmt.Sprintf("Could not create seal! Most likely proper Seal configuration information was not set, but no error was generated."))
return 1
}
coreConfig := &vault.CoreConfig{
Physical: backend,
RedirectAddr: config.Storage.RedirectAddr,
HAPhysical: nil,
Seal: seal,
AuditBackends: c.AuditBackends,
CredentialBackends: c.CredentialBackends,
LogicalBackends: c.LogicalBackends,
Logger: c.logger,
DisableCache: config.DisableCache,
DisableMlock: config.DisableMlock,
MaxLeaseTTL: config.MaxLeaseTTL,
DefaultLeaseTTL: config.DefaultLeaseTTL,
ClusterName: config.ClusterName,
CacheSize: config.CacheSize,
PluginDirectory: config.PluginDirectory,
EnableRaw: config.EnableRawEndpoint,
}
if c.flagDev {
coreConfig.DevToken = c.flagDevRootTokenID
if c.flagDevLeasedKV {
coreConfig.LogicalBackends["kv"] = vault.LeasedPassthroughBackendFactory
}
if c.flagDevPluginDir != "" {
coreConfig.PluginDirectory = c.flagDevPluginDir
}
if c.flagDevLatency > 0 {
injectLatency := time.Duration(c.flagDevLatency) * time.Millisecond
if _, txnOK := backend.(physical.Transactional); txnOK {
coreConfig.Physical = physical.NewTransactionalLatencyInjector(backend, injectLatency, c.flagDevLatencyJitter, c.logger)
} else {
coreConfig.Physical = physical.NewLatencyInjector(backend, injectLatency, c.flagDevLatencyJitter, c.logger)
}
}
}
if c.flagDevThreeNode {
return c.enableThreeNodeDevCluster(coreConfig, info, infoKeys, c.flagDevListenAddr, os.Getenv("VAULT_DEV_TEMP_DIR"))
}
var disableClustering bool
// Initialize the separate HA storage backend, if it exists
var ok bool
if config.HAStorage != nil {
factory, exists := c.PhysicalBackends[config.HAStorage.Type]
if !exists {
c.UI.Error(fmt.Sprintf("Unknown HA storage type %s", config.HAStorage.Type))
return 1
}
habackend, err := factory(config.HAStorage.Config, c.logger)
if err != nil {
c.UI.Error(fmt.Sprintf(
"Error initializing HA storage of type %s: %s", config.HAStorage.Type, err))
return 1
}
if coreConfig.HAPhysical, ok = habackend.(physical.HABackend); !ok {
c.UI.Error("Specified HA storage does not support HA")
return 1
}
if !coreConfig.HAPhysical.HAEnabled() {
c.UI.Error("Specified HA storage has HA support disabled; please consult documentation")
return 1
}
coreConfig.RedirectAddr = config.HAStorage.RedirectAddr
disableClustering = config.HAStorage.DisableClustering
if !disableClustering {
coreConfig.ClusterAddr = config.HAStorage.ClusterAddr
}
} else {
if coreConfig.HAPhysical, ok = backend.(physical.HABackend); ok {
coreConfig.RedirectAddr = config.Storage.RedirectAddr
disableClustering = config.Storage.DisableClustering
if !disableClustering {
coreConfig.ClusterAddr = config.Storage.ClusterAddr
}
}
}
if envRA := os.Getenv("VAULT_API_ADDR"); envRA != "" {
coreConfig.RedirectAddr = envRA
} else if envRA := os.Getenv("VAULT_REDIRECT_ADDR"); envRA != "" {
coreConfig.RedirectAddr = envRA
} else if envAA := os.Getenv("VAULT_ADVERTISE_ADDR"); envAA != "" {
coreConfig.RedirectAddr = envAA
}
// Attempt to detect the redirect address, if possible
var detect physical.RedirectDetect
if coreConfig.HAPhysical != nil && coreConfig.HAPhysical.HAEnabled() {
detect, ok = coreConfig.HAPhysical.(physical.RedirectDetect)
} else {
detect, ok = coreConfig.Physical.(physical.RedirectDetect)
}
if ok && coreConfig.RedirectAddr == "" {
redirect, err := c.detectRedirect(detect, config)
if err != nil {
c.UI.Error(fmt.Sprintf("Error detecting redirect address: %s", err))
} else if redirect == "" {
c.UI.Error("Failed to detect redirect address.")
} else {
coreConfig.RedirectAddr = redirect
}
}
if coreConfig.RedirectAddr == "" && c.flagDev {
coreConfig.RedirectAddr = fmt.Sprintf("http://%s", config.Listeners[0].Config["address"])
}
// After the redirect bits are sorted out, if no cluster address was
// explicitly given, derive one from the redirect addr
if disableClustering {
coreConfig.ClusterAddr = ""
} else if envCA := os.Getenv("VAULT_CLUSTER_ADDR"); envCA != "" {
coreConfig.ClusterAddr = envCA
} else {
var addrToUse string
switch {
case coreConfig.ClusterAddr == "" && coreConfig.RedirectAddr != "":
addrToUse = coreConfig.RedirectAddr
case c.flagDev:
addrToUse = fmt.Sprintf("http://%s", config.Listeners[0].Config["address"])
default:
goto CLUSTER_SYNTHESIS_COMPLETE
}
u, err := url.ParseRequestURI(addrToUse)
if err != nil {
c.UI.Error(fmt.Sprintf(
"Error parsing synthesized cluster address %s: %v", addrToUse, err))
return 1
}
host, port, err := net.SplitHostPort(u.Host)
if err != nil {
// This sucks, as it's a const in the function but not exported in the package
if strings.Contains(err.Error(), "missing port in address") {
host = u.Host
port = "443"
} else {
c.UI.Error(fmt.Sprintf("Error parsing redirect address: %v", err))
return 1
}
}
nPort, err := strconv.Atoi(port)
if err != nil {
c.UI.Error(fmt.Sprintf(
"Error parsing synthesized address; failed to convert %q to a numeric: %v", port, err))
return 1
}
u.Host = net.JoinHostPort(host, strconv.Itoa(nPort+1))
// Will always be TLS-secured
u.Scheme = "https"
coreConfig.ClusterAddr = u.String()
}
CLUSTER_SYNTHESIS_COMPLETE:
if coreConfig.ClusterAddr != "" {
// Force https as we'll always be TLS-secured
u, err := url.ParseRequestURI(coreConfig.ClusterAddr)
if err != nil {
c.UI.Error(fmt.Sprintf("Error parsing cluster address %s: %v", coreConfig.RedirectAddr, err))
return 11
}
u.Scheme = "https"
coreConfig.ClusterAddr = u.String()
}
// Initialize the core
core, newCoreError := vault.NewCore(coreConfig)
if newCoreError != nil {
if !errwrap.ContainsType(newCoreError, new(vault.NonFatalError)) {
c.UI.Error(fmt.Sprintf("Error initializing core: %s", newCoreError))
return 1
}
}
// Copy the reload funcs pointers back
c.reloadFuncs = coreConfig.ReloadFuncs
c.reloadFuncsLock = coreConfig.ReloadFuncsLock
// Compile server information for output later
info["storage"] = config.Storage.Type
info["log level"] = c.flagLogLevel
info["mlock"] = fmt.Sprintf(
"supported: %v, enabled: %v",
mlock.Supported(), !config.DisableMlock && mlock.Supported())
infoKeys = append(infoKeys, "mlock", "storage")
if coreConfig.ClusterAddr != "" {
info["cluster address"] = coreConfig.ClusterAddr
infoKeys = append(infoKeys, "cluster address")
}
if coreConfig.RedirectAddr != "" {
info["redirect address"] = coreConfig.RedirectAddr
infoKeys = append(infoKeys, "redirect address")
}
if config.HAStorage != nil {
info["HA storage"] = config.HAStorage.Type
infoKeys = append(infoKeys, "HA storage")
} else {
// If the storage supports HA, then note it
if coreConfig.HAPhysical != nil {
if coreConfig.HAPhysical.HAEnabled() {
info["storage"] += " (HA available)"
} else {
info["storage"] += " (HA disabled)"
}
}
}
clusterAddrs := []*net.TCPAddr{}
// Initialize the listeners
c.reloadFuncsLock.Lock()
lns := make([]net.Listener, 0, len(config.Listeners))
for i, lnConfig := range config.Listeners {
ln, props, reloadFunc, err := server.NewListener(lnConfig.Type, lnConfig.Config, c.logGate, c.UI)
if err != nil {
c.UI.Error(fmt.Sprintf("Error initializing listener of type %s: %s", lnConfig.Type, err))
return 1
}
lns = append(lns, ln)
if reloadFunc != nil {
relSlice := (*c.reloadFuncs)["listener|"+lnConfig.Type]
relSlice = append(relSlice, reloadFunc)
(*c.reloadFuncs)["listener|"+lnConfig.Type] = relSlice
}
if !disableClustering && lnConfig.Type == "tcp" {
var addrRaw interface{}
var addr string
var ok bool
if addrRaw, ok = lnConfig.Config["cluster_address"]; ok {
addr = addrRaw.(string)
tcpAddr, err := net.ResolveTCPAddr("tcp", addr)
if err != nil {
c.UI.Error(fmt.Sprintf("Error resolving cluster_address: %s", err))
return 1
}
clusterAddrs = append(clusterAddrs, tcpAddr)
} else {
tcpAddr, ok := ln.Addr().(*net.TCPAddr)
if !ok {
c.UI.Error("Failed to parse tcp listener")
return 1
}
clusterAddr := &net.TCPAddr{
IP: tcpAddr.IP,
Port: tcpAddr.Port + 1,
}
clusterAddrs = append(clusterAddrs, clusterAddr)
addr = clusterAddr.String()
}
props["cluster address"] = addr
}
// Store the listener props for output later
key := fmt.Sprintf("listener %d", i+1)
propsList := make([]string, 0, len(props))
for k, v := range props {
propsList = append(propsList, fmt.Sprintf(
"%s: %q", k, v))
}
sort.Strings(propsList)
infoKeys = append(infoKeys, key)
info[key] = fmt.Sprintf(
"%s (%s)", lnConfig.Type, strings.Join(propsList, ", "))
}
c.reloadFuncsLock.Unlock()
if !disableClustering {
if c.logger.IsTrace() {
c.logger.Trace("cluster listener addresses synthesized", "cluster_addresses", clusterAddrs)
}
}
// Make sure we close all listeners from this point on
listenerCloseFunc := func() {
for _, ln := range lns {
ln.Close()
}
}
defer c.cleanupGuard.Do(listenerCloseFunc)
infoKeys = append(infoKeys, "version")
verInfo := version.GetVersion()
info["version"] = verInfo.FullVersionNumber(false)
if verInfo.Revision != "" {
info["version sha"] = strings.Trim(verInfo.Revision, "'")
infoKeys = append(infoKeys, "version sha")
}
infoKeys = append(infoKeys, "cgo")
info["cgo"] = "disabled"
if version.CgoEnabled {
info["cgo"] = "enabled"
}
// Server configuration output
padding := 24
sort.Strings(infoKeys)
c.UI.Output("==> Vault server configuration:\n")
for _, k := range infoKeys {
c.UI.Output(fmt.Sprintf(
"%s%s: %s",
strings.Repeat(" ", padding-len(k)),
strings.Title(k),
info[k]))
}
c.UI.Output("")
// Tests might not want to start a vault server and just want to verify
// the configuration.
if c.flagTestVerifyOnly {
return 0
}
handler := vaulthttp.Handler(core)
// This needs to happen before we first unseal, so before we trigger dev
// mode if it's set
core.SetClusterListenerAddrs(clusterAddrs)
core.SetClusterHandler(handler)
err = core.UnsealWithStoredKeys(context.Background())
if err != nil {
if !errwrap.ContainsType(err, new(vault.NonFatalError)) {
c.UI.Error(fmt.Sprintf("Error initializing core: %s", err))
return 1
}
}
// Perform service discovery registrations and initialization of
// HTTP server after the verifyOnly check.
// Instantiate the wait group
c.WaitGroup = &sync.WaitGroup{}
// If the backend supports service discovery, run service discovery
if coreConfig.HAPhysical != nil && coreConfig.HAPhysical.HAEnabled() {
sd, ok := coreConfig.HAPhysical.(physical.ServiceDiscovery)
if ok {
activeFunc := func() bool {
if isLeader, _, _, err := core.Leader(); err == nil {
return isLeader
}
return false
}
sealedFunc := func() bool {
if sealed, err := core.Sealed(); err == nil {
return sealed
}
return true
}
if err := sd.RunServiceDiscovery(c.WaitGroup, c.ShutdownCh, coreConfig.RedirectAddr, activeFunc, sealedFunc); err != nil {
c.UI.Error(fmt.Sprintf("Error initializing service discovery: %v", err))
return 1
}
}
}
// If we're in Dev mode, then initialize the core
if c.flagDev && !c.flagDevSkipInit {
init, err := c.enableDev(core, coreConfig)
if err != nil {
c.UI.Error(fmt.Sprintf("Error initializing Dev mode: %s", err))
return 1
}
export := "export"
quote := "'"
if runtime.GOOS == "windows" {
export = "set"
quote = ""
}
// Print the big dev mode warning!
c.UI.Warn(wrapAtLength(
"WARNING! dev mode is enabled! In this mode, Vault runs entirely " +
"in-memory and starts unsealed with a single unseal key. The root " +
"token is already authenticated to the CLI, so you can immediately " +
"begin using Vault."))
c.UI.Warn("")
c.UI.Warn("You may need to set the following environment variable:")
c.UI.Warn("")
c.UI.Warn(fmt.Sprintf(" $ %s VAULT_ADDR=%s%s%s",
export, quote, "http://"+config.Listeners[0].Config["address"].(string), quote))
// Unseal key is not returned if stored shares is supported
if len(init.SecretShares) > 0 {
c.UI.Warn("")
c.UI.Warn(wrapAtLength(
"The unseal key and root token are displayed below in case you want " +
"to seal/unseal the Vault or re-authenticate."))
c.UI.Warn("")
c.UI.Warn(fmt.Sprintf("Unseal Key: %s", base64.StdEncoding.EncodeToString(init.SecretShares[0])))
}
if len(init.RecoveryShares) > 0 {
c.UI.Warn("")
c.UI.Warn(wrapAtLength(
"The recovery key and root token are displayed below in case you want " +
"to seal/unseal the Vault or re-authenticate."))
c.UI.Warn("")
c.UI.Warn(fmt.Sprintf("Unseal Key: %s", base64.StdEncoding.EncodeToString(init.RecoveryShares[0])))
}
c.UI.Warn(fmt.Sprintf("Root Token: %s", init.RootToken))
c.UI.Warn("")
c.UI.Warn(wrapAtLength(
"Development mode should NOT be used in production installations!"))
c.UI.Warn("")
}
// Initialize the HTTP servers
for _, ln := range lns {
server := &http.Server{
Handler: handler,
}
go server.Serve(ln)
}
if newCoreError != nil {
c.UI.Warn(wrapAtLength(
"WARNING! A non-fatal error occurred during initialization. Please " +
"check the logs for more information."))
c.UI.Warn("")
}
// Output the header that the server has started
c.UI.Output("==> Vault server started! Log data will stream in below:\n")
// Inform any tests that the server is ready
select {
case c.startedCh <- struct{}{}:
default:
}
// Release the log gate.
c.logGate.Flush()
// Write out the PID to the file now that server has successfully started
if err := c.storePidFile(config.PidFile); err != nil {
c.UI.Error(fmt.Sprintf("Error storing PID: %s", err))
return 1
}
defer func() {
if err := c.removePidFile(config.PidFile); err != nil {
c.UI.Error(fmt.Sprintf("Error deleting the PID file: %s", err))
}
}()
// Wait for shutdown
shutdownTriggered := false
for !shutdownTriggered {
select {
case <-c.ShutdownCh:
c.UI.Output("==> Vault shutdown triggered")
// Stop the listners so that we don't process further client requests.
c.cleanupGuard.Do(listenerCloseFunc)
// Shutdown will wait until after Vault is sealed, which means the
// request forwarding listeners will also be closed (and also
// waited for).
if err := core.Shutdown(); err != nil {
c.UI.Error(fmt.Sprintf("Error with core shutdown: %s", err))
}
shutdownTriggered = true
case <-c.SighupCh:
c.UI.Output("==> Vault reload triggered")
if err := c.Reload(c.reloadFuncsLock, c.reloadFuncs, c.flagConfigs); err != nil {
c.UI.Error(fmt.Sprintf("Error(s) were encountered during reload: %s", err))
}
}
}
// Wait for dependent goroutines to complete
c.WaitGroup.Wait()
return 0
}
func (c *ServerCommand) enableDev(core *vault.Core, coreConfig *vault.CoreConfig) (*vault.InitResult, error) {
var recoveryConfig *vault.SealConfig
barrierConfig := &vault.SealConfig{
SecretShares: 1,
SecretThreshold: 1,
}
if core.SealAccess().RecoveryKeySupported() {
recoveryConfig = &vault.SealConfig{
SecretShares: 1,
SecretThreshold: 1,
}
}
if core.SealAccess().StoredKeysSupported() {
barrierConfig.StoredShares = 1
}
ctx := context.Background()
// Initialize it with a basic single key
init, err := core.Initialize(ctx, &vault.InitParams{
BarrierConfig: barrierConfig,
RecoveryConfig: recoveryConfig,
})
if err != nil {
return nil, err
}
// Handle unseal with stored keys
if core.SealAccess().StoredKeysSupported() {
err := core.UnsealWithStoredKeys(ctx)
if err != nil {
return nil, err
}
} else {
// Copy the key so that it can be zeroed
key := make([]byte, len(init.SecretShares[0]))
copy(key, init.SecretShares[0])
// Unseal the core
unsealed, err := core.Unseal(key)
if err != nil {
return nil, err
}
if !unsealed {
return nil, fmt.Errorf("failed to unseal Vault for dev mode")
}
}
isLeader, _, _, err := core.Leader()
if err != nil && err != vault.ErrHANotEnabled {
return nil, fmt.Errorf("failed to check active status: %v", err)
}
if err == nil {
leaderCount := 5
for !isLeader {
if leaderCount == 0 {
buf := make([]byte, 1<<16)
runtime.Stack(buf, true)
return nil, fmt.Errorf("failed to get active status after five seconds; call stack is\n%s\n", buf)
}
time.Sleep(1 * time.Second)
isLeader, _, _, err = core.Leader()
if err != nil {
return nil, fmt.Errorf("failed to check active status: %v", err)
}
leaderCount--
}
}
// Generate a dev root token if one is provided in the flag
if coreConfig.DevToken != "" {
req := &logical.Request{
ID: "dev-gen-root",
Operation: logical.UpdateOperation,
ClientToken: init.RootToken,
Path: "auth/token/create",
Data: map[string]interface{}{
"id": coreConfig.DevToken,
"policies": []string{"root"},
"no_parent": true,
"no_default_policy": true,