open-vault/command/init.go

320 lines
10 KiB
Go
Raw Normal View History

2015-03-13 17:32:39 +00:00
package command
import (
"fmt"
2016-07-20 19:38:53 +00:00
"os"
"runtime"
2015-03-13 17:32:39 +00:00
"strings"
2016-07-20 19:38:53 +00:00
consulapi "github.com/hashicorp/consul/api"
2015-03-13 17:32:39 +00:00
"github.com/hashicorp/vault/api"
"github.com/hashicorp/vault/helper/pgpkeys"
2016-04-01 17:16:05 +00:00
"github.com/hashicorp/vault/meta"
2015-03-13 17:32:39 +00:00
)
// InitCommand is a Command that initializes a new Vault server.
type InitCommand struct {
2016-04-01 17:16:05 +00:00
meta.Meta
2015-03-13 17:32:39 +00:00
}
func (c *InitCommand) Run(args []string) int {
2016-04-04 14:44:22 +00:00
var threshold, shares, storedShares, recoveryThreshold, recoveryShares int
var pgpKeys, recoveryPgpKeys pgpkeys.PubKeyFilesFlag
var auto, check bool
var consulService string
2016-04-01 17:16:05 +00:00
flags := c.Meta.FlagSet("init", meta.FlagSetDefault)
2015-03-13 17:32:39 +00:00
flags.Usage = func() { c.Ui.Error(c.Help()) }
2015-08-25 22:33:58 +00:00
flags.IntVar(&shares, "key-shares", 5, "")
2015-03-13 17:32:39 +00:00
flags.IntVar(&threshold, "key-threshold", 3, "")
2016-04-04 14:44:22 +00:00
flags.IntVar(&storedShares, "stored-shares", 0, "")
flags.Var(&pgpKeys, "pgp-keys", "")
flags.IntVar(&recoveryShares, "recovery-shares", 5, "")
flags.IntVar(&recoveryThreshold, "recovery-threshold", 3, "")
flags.Var(&recoveryPgpKeys, "recovery-pgp-keys", "")
2016-04-04 14:44:22 +00:00
flags.BoolVar(&check, "check", false, "")
flags.BoolVar(&auto, "auto", false, "")
flags.StringVar(&consulService, "consul-service", "", "")
2015-03-13 17:32:39 +00:00
if err := flags.Parse(args); err != nil {
return 1
}
2016-07-20 19:38:53 +00:00
initRequest := &api.InitRequest{
SecretShares: shares,
SecretThreshold: threshold,
StoredShares: storedShares,
PGPKeys: pgpKeys,
RecoveryShares: recoveryShares,
RecoveryThreshold: recoveryThreshold,
RecoveryPGPKeys: recoveryPgpKeys,
}
// If running in 'auto' mode, run service discovery based on environment
// variables of Consul.
if auto {
if strings.TrimSpace(consulService) == "" {
c.Ui.Error("'consul-service' must be supplied when 'auto' is set")
return 1
}
2016-07-20 19:38:53 +00:00
// Create configuration for Consul
consulConfig := consulapi.DefaultConfig()
// Create a client to communicate with Consul
consulClient, err := consulapi.NewClient(consulConfig)
if err != nil {
c.Ui.Error(fmt.Sprintf("failed to create Consul client:%v", err))
return 1
}
var uninitializedVaults []string
var initializedVault string
// Query the nodes belonging to the cluster
if services, _, err := consulClient.Catalog().Service(consulService, "", &consulapi.QueryOptions{AllowStale: true}); err == nil {
2016-07-20 19:38:53 +00:00
Loop:
for _, service := range services {
vaultAddress := fmt.Sprintf("%s://%s:%d", consulConfig.Scheme, service.ServiceAddress, service.ServicePort)
// Set VAULT_ADDR to the discovered node
os.Setenv(api.EnvVaultAddress, vaultAddress)
// Create a client to communicate with the discovered node
client, err := c.Client()
if err != nil {
c.Ui.Error(fmt.Sprintf(
"Error initializing client: %s", err))
return 1
}
// Check the initialization status of the discovered node
inited, err := client.Sys().InitStatus()
switch {
case err != nil:
c.Ui.Error(fmt.Sprintf("Error checking initialization status of discovered node: %s err:%s", vaultAddress, err))
return 1
case inited:
// One of the nodes in the cluster is initialized. Break out.
initializedVault = vaultAddress
break Loop
default:
// Vault is uninitialized.
uninitializedVaults = append(uninitializedVaults, vaultAddress)
}
}
}
export := "export"
quote := "'"
if runtime.GOOS == "windows" {
export = "set"
quote = ""
}
if initializedVault != "" {
c.Ui.Output(fmt.Sprintf("Discovered an initialized Vault node at '%s'", initializedVault))
c.Ui.Output("\nSet the following environment variable to operate on the discovered Vault:\n")
2016-07-20 19:38:53 +00:00
c.Ui.Output(fmt.Sprintf("\t%s VAULT_ADDR=%shttp://%s%s", export, quote, initializedVault, quote))
return 0
}
switch len(uninitializedVaults) {
case 0:
c.Ui.Error(fmt.Sprintf("Failed to discover Vault nodes under Consul service name '%s'", consulService))
2016-07-20 19:38:53 +00:00
return 1
case 1:
// There was only one node found in the Vault cluster and it
// was uninitialized.
// Set the VAULT_ADDR to the discovered node. This will ensure
// that the client created will operate on the discovered node.
os.Setenv(api.EnvVaultAddress, uninitializedVaults[0])
// Let the client know that initialization is perfomed on the
// discovered node.
c.Ui.Output(fmt.Sprintf("Discovered Vault at '%s'\n", uninitializedVaults[0]))
// Attempt initializing it
ret := c.runInit(check, initRequest)
// Regardless of success or failure, instruct client to update VAULT_ADDR
c.Ui.Output("\nSet the following environment variable to operate on the discovered Vault:\n")
2016-07-20 19:38:53 +00:00
c.Ui.Output(fmt.Sprintf("\t%s VAULT_ADDR=%shttp://%s%s", export, quote, uninitializedVaults[0], quote))
return ret
default:
// If more than one Vault node were discovered, print out all of them,
// requiring the client to update VAULT_ADDR and to run init again.
c.Ui.Output(fmt.Sprintf("Discovered more than one uninitialized Vaults under Consul service name '%s'\n", consulService))
c.Ui.Output("To initialize these Vaults, set any *one* of the following environment variables and run 'vault init':")
2016-07-20 19:38:53 +00:00
// Print valid commands to make setting the variables easier
for _, vaultNode := range uninitializedVaults {
c.Ui.Output(fmt.Sprintf("\t%s VAULT_ADDR=%s%s%s", export, quote, vaultNode, quote))
2016-07-20 19:38:53 +00:00
}
return 0
}
}
return c.runInit(check, initRequest)
}
func (c *InitCommand) runInit(check bool, initRequest *api.InitRequest) int {
2015-03-13 17:32:39 +00:00
client, err := c.Client()
if err != nil {
c.Ui.Error(fmt.Sprintf(
"Error initializing client: %s", err))
return 1
}
2016-01-22 18:06:40 +00:00
if check {
return c.checkStatus(client)
}
2016-07-20 19:38:53 +00:00
resp, err := client.Sys().Init(initRequest)
2015-03-13 17:32:39 +00:00
if err != nil {
c.Ui.Error(fmt.Sprintf(
"Error initializing Vault: %s", err))
return 1
}
for i, key := range resp.Keys {
2016-04-04 14:44:22 +00:00
c.Ui.Output(fmt.Sprintf("Unseal Key %d: %s", i+1, key))
}
for i, key := range resp.RecoveryKeys {
c.Ui.Output(fmt.Sprintf("Recovery Key %d: %s", i+1, key))
2015-03-13 17:32:39 +00:00
}
2015-03-29 23:25:53 +00:00
c.Ui.Output(fmt.Sprintf("Initial Root Token: %s", resp.RootToken))
2016-07-20 19:38:53 +00:00
if initRequest.StoredShares < 1 {
2016-04-04 14:44:22 +00:00
c.Ui.Output(fmt.Sprintf(
"\n"+
"Vault initialized with %d keys and a key threshold of %d. Please\n"+
"securely distribute the above keys. When the Vault is re-sealed,\n"+
"restarted, or stopped, you must provide at least %d of these keys\n"+
"to unseal it again.\n\n"+
"Vault does not store the master key. Without at least %d keys,\n"+
"your Vault will remain permanently sealed.",
2016-07-20 19:38:53 +00:00
initRequest.SecretShares,
initRequest.SecretThreshold,
initRequest.SecretThreshold,
initRequest.SecretThreshold,
2016-04-04 14:44:22 +00:00
))
} else {
c.Ui.Output(
"\n" +
"Vault initialized successfully.",
)
}
if len(resp.RecoveryKeys) > 0 {
c.Ui.Output(fmt.Sprintf(
"\n"+
"Recovery key initialized with %d keys and a key threshold of %d. Please\n"+
"securely distribute the above keys.",
2016-07-20 19:38:53 +00:00
initRequest.RecoveryShares,
initRequest.RecoveryThreshold,
2016-04-04 14:44:22 +00:00
))
}
2015-03-13 17:32:39 +00:00
return 0
}
2016-01-22 18:06:40 +00:00
func (c *InitCommand) checkStatus(client *api.Client) int {
inited, err := client.Sys().InitStatus()
switch {
case err != nil:
c.Ui.Error(fmt.Sprintf(
"Error checking initialization status: %s", err))
return 1
case inited:
c.Ui.Output("Vault has been initialized")
return 0
default:
c.Ui.Output("Vault is not initialized")
return 2
}
}
2015-03-13 17:32:39 +00:00
func (c *InitCommand) Synopsis() string {
return "Initialize a new Vault server"
}
func (c *InitCommand) Help() string {
helpText := `
Usage: vault init [options]
Initialize a new Vault server.
This command connects to a Vault server and initializes it for the
first time. This sets up the initial set of master keys and sets up the
backend data store structure.
This command can't be called on an already-initialized Vault.
General Options:
` + meta.GeneralOptionsUsage() + `
2015-03-13 17:32:39 +00:00
Init Options:
-check Don't actually initialize, just check if Vault is
already initialized. A return code of 0 means Vault
is initialized; a return code of 2 means Vault is not
initialized; a return code of 1 means an error was
encountered.
-key-shares=5 The number of key shares to split the master key
into.
-key-threshold=3 The number of key shares required to reconstruct
the master key.
-stored-shares=0 The number of unseal keys to store. This is not
normally available.
-pgp-keys If provided, must be a comma-separated list of
files on disk containing binary- or base64-format
public PGP keys, or Keybase usernames specified as
"keybase:<username>". The number of given entries
must match 'key-shares'. The output unseal keys will
be encrypted and hex-encoded, in order, with the
given public keys. If you want to use them with the
'vault unseal' command, you will need to hex decode
and decrypt; this will be the plaintext unseal key.
-recovery-shares=5 The number of key shares to split the recovery key
into. This is not normally available.
-recovery-threshold=3 The number of key shares required to reconstruct
the recovery key. This is not normally available.
-recovery-pgp-keys If provided, behaves like "pgp-keys" but for the
recovery key shares. This is not normally available.
-auto If set, performs service discovery using the underlying
Consul storage backend. When one or more Vault servers
are running on Consul storage backend (none else),
setting this flag will create a Consul client and
discovrs the nodes using the service name under which
Vault nodes are registered with Consul. Service name
should be supplied using 'consul-service' flag. This
option works well when each Vault cluster is registered
under a unique service name. Ensure that environment
variables required to communicate with Consul, like
(CONSUL_HTTP_ADDR, CONSUL_HTTP_TOKEN, CONSUL_HTTP_SSL,
et al) are properly set. If, only one Vault node is
discovered, then an initialization attempt will be made.
If more than one Vault nodes are discovered, they will
be listed on the output, requiring another execution of
this command with updated VAULT_ADDR environment variable.
-consul-service Service name under which the all nodes of Vault are
registered with Consul. When Vault is using Consul
as its storage backend, by default, it will auto register
itself with Consul under the default name of "vault".
This name can be modified in Vault's configuration file,
using the "service" option under Consul backend.
2015-03-13 17:32:39 +00:00
`
return strings.TrimSpace(helpText)
}