Exemplo n.º 1
1
func (h *CLIHandler) Auth(c *api.Client, m map[string]string) (string, error) {
	mount, ok := m["mount"]
	if !ok {
		mount = "ldap"
	}

	username, ok := m["username"]
	if !ok {
		return "", fmt.Errorf("'username' var must be set")
	}
	password, ok := m["password"]
	if !ok {
		fmt.Printf("Password (will be hidden): ")
		var err error
		password, err = pwd.Read(os.Stdin)
		fmt.Println()
		if err != nil {
			return "", err
		}
	}

	path := fmt.Sprintf("auth/%s/login/%s", mount, username)
	secret, err := c.Logical().Write(path, map[string]interface{}{
		"password": password,
	})
	if err != nil {
		return "", err
	}
	if secret == nil {
		return "", fmt.Errorf("empty response from credential provider")
	}

	return secret.Auth.ClientToken, nil
}
Exemplo n.º 2
0
// rekeyStatus is used just to fetch and dump the status
func (c *RekeyCommand) rekeyStatus(client *api.Client) int {
	// Check the status
	status, err := client.Sys().RekeyStatus()
	if err != nil {
		c.Ui.Error(fmt.Sprintf("Error reading rekey status: %s", err))
		return 1
	}

	// Dump the status
	statString := fmt.Sprintf(
		"Nonce: %s\n"+
			"Started: %v\n"+
			"Key Shares: %d\n"+
			"Key Threshold: %d\n"+
			"Rekey Progress: %d\n"+
			"Required Keys: %d",
		status.Nonce,
		status.Started,
		status.N,
		status.T,
		status.Progress,
		status.Required,
	)
	if len(status.PGPFingerprints) != 0 {
		statString = fmt.Sprintf("\nPGP Key Fingerprints: %s", status.PGPFingerprints)
		statString = fmt.Sprintf("\nBackup Storage: %t", status.Backup)
	}
	c.Ui.Output(statString)
	return 0
}
Exemplo n.º 3
0
func (h *CLIHandler) Auth(c *api.Client, m map[string]string) (string, error) {
	mount, ok := m["mount"]
	if !ok {
		mount = "github"
	}

	token, ok := m["token"]
	if !ok {
		if token = os.Getenv("VAULT_AUTH_GITHUB_TOKEN"); token == "" {
			return "", fmt.Errorf("GitHub token should be provided either as 'value' for 'token' key,\nor via an env var VAULT_AUTH_GITHUB_TOKEN")
		}
	}

	path := fmt.Sprintf("auth/%s/login", mount)
	secret, err := c.Logical().Write(path, map[string]interface{}{
		"token": token,
	})
	if err != nil {
		return "", err
	}
	if secret == nil {
		return "", fmt.Errorf("empty response from credential provider")
	}

	return secret.Auth.ClientToken, nil
}
Exemplo n.º 4
0
func (s *VaultSource) setToken(c *api.Client) error {
	s.mu.Lock()
	defer func() {
		c.SetToken(s.token)
		s.mu.Unlock()
	}()

	if s.token != "" {
		return nil
	}

	if s.vaultToken == "" {
		return errors.New("vault: no token")
	}

	// did we get a wrapped token?
	resp, err := c.Logical().Unwrap(s.vaultToken)
	if err != nil {
		// not a wrapped token?
		if strings.HasPrefix(err.Error(), "no value found at") {
			s.token = s.vaultToken
			return nil
		}
		return err
	}
	log.Printf("[INFO] vault: Unwrapped token %s", s.vaultToken)

	s.token = resp.Auth.ClientToken
	return nil
}
Exemplo n.º 5
0
func doTokenLookup(args []string, client *api.Client) (*api.Secret, error) {
	if len(args) == 0 {
		return client.Auth().Token().LookupSelf()
	}

	token := args[0]
	return client.Auth().Token().Lookup(token)
}
Exemplo n.º 6
0
// cancelRekey is used to abort the rekey process
func (c *RekeyCommand) cancelRekey(client *api.Client) int {
	err := client.Sys().RekeyCancel()
	if err != nil {
		c.Ui.Error(fmt.Sprintf("Failed to cancel rekey: %s", err))
		return 1
	}
	c.Ui.Output("Rekey canceled.")
	return 0
}
Exemplo n.º 7
0
// cancelGenerateRoot is used to abort the generation process
func (c *GenerateRootCommand) cancelGenerateRoot(client *api.Client) int {
	err := client.Sys().GenerateRootCancel()
	if err != nil {
		c.Ui.Error(fmt.Sprintf("Failed to cancel root generation: %s", err))
		return 1
	}
	c.Ui.Output("Root generation canceled.")
	return 0
}
Exemplo n.º 8
0
func (c *RekeyCommand) rekeyDeleteStored(client *api.Client) int {
	err := client.Sys().RekeyDeleteStored()
	if err != nil {
		c.Ui.Error(fmt.Sprintf("Failed to delete stored keys: %s", err))
		return 1
	}
	c.Ui.Output("Stored keys deleted.")
	return 0
}
Exemplo n.º 9
0
// rekeyStatus is used just to fetch and dump the status
func (c *RekeyCommand) rekeyStatus(client *api.Client) int {
	// Check the status
	status, err := client.Sys().RekeyStatus()
	if err != nil {
		c.Ui.Error(fmt.Sprintf("Error reading rekey status: %s", err))
		return 1
	}

	return c.dumpRekeyStatus(status)
}
Exemplo n.º 10
0
// initGenerateRoot is used to start the generation process
func (c *GenerateRootCommand) initGenerateRoot(client *api.Client, otp string, pgpKey string) int {
	// Start the rekey
	err := client.Sys().GenerateRootInit(otp, pgpKey)
	if err != nil {
		c.Ui.Error(fmt.Sprintf("Error initializing root generation: %s", err))
		return 1
	}

	// Provide the current status
	return c.rootGenerationStatus(client)
}
Exemplo n.º 11
0
// rootGenerationStatus is used just to fetch and dump the status
func (c *GenerateRootCommand) rootGenerationStatus(client *api.Client) int {
	// Check the status
	status, err := client.Sys().GenerateRootStatus()
	if err != nil {
		c.Ui.Error(fmt.Sprintf("Error reading root generation status: %s", err))
		return 1
	}

	c.dumpStatus(status)

	return 0
}
Exemplo n.º 12
0
// initGenerateRoot is used to start the generation process
func (c *GenerateRootCommand) initGenerateRoot(client *api.Client, otp string, pgpKey string) int {
	// Start the rekey
	status, err := client.Sys().GenerateRootInit(otp, pgpKey)
	if err != nil {
		c.Ui.Error(fmt.Sprintf("Error initializing root generation: %s", err))
		return 1
	}

	c.dumpStatus(status)

	return 0
}
Exemplo n.º 13
0
func initializeNewVault(vc *vault.Client) *vault.InitResponse {
	log.Info("Initialize fresh vault")
	vaultInit := &vault.InitRequest{
		SecretShares:    1,
		SecretThreshold: 1,
	}
	initResponse, err := vc.Sys().Init(vaultInit)
	fatal(err)

	return initResponse

}
Exemplo n.º 14
0
func (c *RekeyCommand) rekeyRetrieveStored(client *api.Client) int {
	storedKeys, err := client.Sys().RekeyRetrieveStored()
	if err != nil {
		c.Ui.Error(fmt.Sprintf("Error retrieving stored keys: %s", err))
		return 1
	}

	secret := &api.Secret{
		Data: structs.New(storedKeys).Map(),
	}

	return OutputSecret(c.Ui, "table", secret)
}
Exemplo n.º 15
0
// cancelRekey is used to abort the rekey process
func (c *RekeyCommand) cancelRekey(client *api.Client, recovery bool) int {
	var err error
	if recovery {
		err = client.Sys().RekeyRecoveryKeyCancel()
	} else {
		err = client.Sys().RekeyCancel()
	}
	if err != nil {
		c.Ui.Error(fmt.Sprintf("Failed to cancel rekey: %s", err))
		return 1
	}
	c.Ui.Output("Rekey canceled.")
	return 0
}
Exemplo n.º 16
0
func (c *RekeyCommand) rekeyDeleteStored(client *api.Client, recovery bool) int {
	var err error
	if recovery {
		err = client.Sys().RekeyDeleteRecoveryBackup()
	} else {
		err = client.Sys().RekeyDeleteBackup()
	}
	if err != nil {
		c.Ui.Error(fmt.Sprintf("Failed to delete stored keys: %s", err))
		return 1
	}
	c.Ui.Output("Stored keys deleted.")
	return 0
}
Exemplo n.º 17
0
// initRekey is used to start the rekey process
func (c *RekeyCommand) initRekey(client *api.Client, shares, threshold int) int {
	// Start the rekey
	err := client.Sys().RekeyInit(&api.RekeyInitRequest{
		SecretShares:    shares,
		SecretThreshold: threshold,
	})
	if err != nil {
		c.Ui.Error(fmt.Sprintf("Error initializing rekey: %s", err))
		return 1
	}

	// Provide the current status
	return c.rekeyStatus(client)
}
Exemplo n.º 18
0
func (h *CLIHandler) Auth(c *api.Client, m map[string]string) (string, error) {
	var data struct {
		Username string `mapstructure:"username"`
		Password string `mapstructure:"password"`
		Mount    string `mapstructure:"mount"`
		Method   string `mapstructure:"method"`
		Passcode string `mapstructure:"passcode"`
	}
	if err := mapstructure.WeakDecode(m, &data); err != nil {
		return "", err
	}

	if data.Username == "" {
		return "", fmt.Errorf("'username' must be specified")
	}
	if data.Password == "" {
		fmt.Printf("Password (will be hidden): ")
		password, err := pwd.Read(os.Stdin)
		fmt.Println()
		if err != nil {
			return "", err
		}
		data.Password = password
	}
	if data.Mount == "" {
		data.Mount = "userpass"
	}

	options := map[string]interface{}{
		"password": data.Password,
	}
	if data.Method != "" {
		options["method"] = data.Method
	}
	if data.Passcode != "" {
		options["passcode"] = data.Passcode
	}

	path := fmt.Sprintf("auth/%s/login/%s", data.Mount, data.Username)
	secret, err := c.Logical().Write(path, options)
	if err != nil {
		return "", err
	}
	if secret == nil {
		return "", fmt.Errorf("empty response from credential provider")
	}

	return secret.Auth.ClientToken, nil
}
Exemplo n.º 19
0
Arquivo: init.go Projeto: mhurne/vault
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
	}
}
Exemplo n.º 20
0
// rekeyStatus is used just to fetch and dump the status
func (c *RekeyCommand) rekeyStatus(client *api.Client, recovery bool) int {
	// Check the status
	var status *api.RekeyStatusResponse
	var err error
	if recovery {
		status, err = client.Sys().RekeyRecoveryKeyStatus()
	} else {
		status, err = client.Sys().RekeyStatus()
	}
	if err != nil {
		c.Ui.Error(fmt.Sprintf("Error reading rekey status: %s", err))
		return 1
	}

	return c.dumpRekeyStatus(status)
}
Exemplo n.º 21
0
// initRekey is used to start the rekey process
func (c *RekeyCommand) initRekey(client *api.Client,
	shares, threshold int,
	pgpKeys pgpkeys.PubKeyFilesFlag,
	backup, recoveryKey bool) int {
	// Start the rekey
	request := &api.RekeyInitRequest{
		SecretShares:    shares,
		SecretThreshold: threshold,
		PGPKeys:         pgpKeys,
		Backup:          backup,
	}
	var status *api.RekeyStatusResponse
	var err error
	if recoveryKey {
		status, err = client.Sys().RekeyRecoveryKeyInit(request)
	} else {
		status, err = client.Sys().RekeyInit(request)
	}
	if err != nil {
		c.Ui.Error(fmt.Sprintf("Error initializing rekey: %s", err))
		return 1
	}

	if pgpKeys == nil || len(pgpKeys) == 0 {
		c.Ui.Output(`
WARNING: If you lose the keys after they are returned to you, there is no
recovery. Consider using the '-pgp-keys' option to protect the returned unseal
keys along with '-backup=true' to allow recovery of the encrypted keys in case
of emergency. They can easily be deleted at a later time with
'vault rekey -delete'.
`)
	}

	if pgpKeys != nil && len(pgpKeys) > 0 && !backup {
		c.Ui.Output(`
WARNING: You are using PGP keys for encryption, but have not set the option to
back up the new unseal keys to physical storage. If you lose the keys after
they are returned to you, there is no recovery. Consider setting '-backup=true'
to allow recovery of the encrypted keys in case of emergency. They can easily
be deleted at a later time with 'vault rekey -delete'.
`)
	}

	// Provide the current status
	return c.dumpRekeyStatus(status)
}
Exemplo n.º 22
0
// initRekey is used to start the rekey process
func (c *RekeyCommand) initRekey(client *api.Client,
	shares, threshold int,
	pgpKeys pgpkeys.PubKeyFilesFlag,
	backup bool) int {
	// Start the rekey
	err := client.Sys().RekeyInit(&api.RekeyInitRequest{
		SecretShares:    shares,
		SecretThreshold: threshold,
		PGPKeys:         pgpKeys,
		Backup:          backup,
	})
	if err != nil {
		c.Ui.Error(fmt.Sprintf("Error initializing rekey: %s", err))
		return 1
	}

	// Provide the current status
	return c.rekeyStatus(client)
}
Exemplo n.º 23
0
func (c *RekeyCommand) rekeyRetrieveStored(client *api.Client, recovery bool) int {
	var storedKeys *api.RekeyRetrieveResponse
	var err error
	if recovery {
		storedKeys, err = client.Sys().RekeyRetrieveRecoveryBackup()
	} else {
		storedKeys, err = client.Sys().RekeyRetrieveBackup()
	}
	if err != nil {
		c.Ui.Error(fmt.Sprintf("Error retrieving stored keys: %s", err))
		return 1
	}

	secret := &api.Secret{
		Data: structs.New(storedKeys).Map(),
	}

	return OutputSecret(c.Ui, "table", secret)
}
Exemplo n.º 24
0
func makeToken(t *testing.T, c *vaultapi.Client, wrapTTL string, req *vaultapi.TokenCreateRequest) string {
	c.SetWrappingLookupFunc(func(string, string) string { return wrapTTL })

	resp, err := c.Auth().Token().Create(req)
	if err != nil {
		t.Fatalf("Could not create a token: %s", err)
	}

	if wrapTTL != "" {
		if resp.WrapInfo == nil || resp.WrapInfo.Token == "" {
			t.Fatalf("Could not create a wrapped token")
		}
		return resp.WrapInfo.Token
	}

	if resp.WrapInfo != nil && resp.WrapInfo.Token != "" {
		t.Fatalf("Got a wrapped token but was not expecting one")
	}

	return resp.Auth.ClientToken
}
Exemplo n.º 25
0
func (h *CLIHandler) Auth(c *api.Client, m map[string]string) (string, error) {
	var data struct {
		Mount string `mapstructure:"mount"`
	}
	if err := mapstructure.WeakDecode(m, &data); err != nil {
		return "", err
	}

	if data.Mount == "" {
		data.Mount = "cert"
	}

	path := fmt.Sprintf("auth/%s/login", data.Mount)
	secret, err := c.Logical().Write(path, nil)
	if err != nil {
		return "", err
	}
	if secret == nil {
		return "", fmt.Errorf("empty response from credential provider")
	}

	return secret.Auth.ClientToken, nil
}
Exemplo n.º 26
0
Arquivo: rekey.go Projeto: nicr9/vault
// rekeyStatus is used just to fetch and dump the status
func (c *RekeyCommand) rekeyStatus(client *api.Client) int {
	// Check the status
	status, err := client.Sys().RekeyStatus()
	if err != nil {
		c.Ui.Error(fmt.Sprintf("Error reading rekey status: %s", err))
		return 1
	}

	// Dump the status
	c.Ui.Output(fmt.Sprintf(
		"Started: %v\n"+
			"Key Shares: %d\n"+
			"Key Threshold: %d\n"+
			"Rekey Progress: %d\n"+
			"Required Keys: %d",
		status.Started,
		status.N,
		status.T,
		status.Progress,
		status.Required,
	))
	return 0
}
Exemplo n.º 27
0
func (h *CLIHandler) Auth(c *api.Client, m map[string]string) (string, error) {
	mount, ok := m["mount"]
	if !ok {
		mount = "github"
	}

	token, ok := m["token"]
	if !ok {
		return "", fmt.Errorf("'token' var must be set")
	}

	path := fmt.Sprintf("auth/%s/login", mount)
	secret, err := c.Logical().Write(path, map[string]interface{}{
		"token": token,
	})
	if err != nil {
		return "", err
	}
	if secret == nil {
		return "", fmt.Errorf("empty response from credential provider")
	}

	return secret.Auth.ClientToken, nil
}
Exemplo n.º 28
0
func initVault() {
	// set up vault client
	var client *vault.Client
	if viper.GetString("vault-cubbyhole-token") != "" || viper.GetString("vault-token") != "" {
		config := vault.DefaultConfig()
		err := config.ReadEnvironment()
		if err != nil {
			log.WithError(err).Fatal("Error reading environment for Vault configuration")
		}
		client, err = vault.NewClient(config)
		if err != nil {
			log.WithError(err).Fatal("Error initializing Vault client")
		}
	}

	// unwrap real token
	if wrapped := viper.GetString("vault-cubbyhole-token"); wrapped != "" {
		token, err := client.Logical().Unwrap(wrapped)
		if err != nil {
			log.WithError(err).Fatal("Error unwrapping token")
		} else if token.WrapInfo != nil {
			log.Fatal("Secret appears to be doubly wrapped")
		} else if token.Auth == nil {
			log.Fatal("Secret contained no auth data")
		}

		viper.Set("vault-token", token.Auth.ClientToken)
	}

	// read secrets from vault
	if token := viper.GetString("vault-token"); token != "" {
		client.SetToken(token)

		secret, err := client.Logical().Read("secret/mantl-api")
		if err != nil {
			log.WithError(err).Fatal("Error reading secret/mantl-api")
		}

		for _, secretName := range []string{
			"mesos-principal", "mesos-secret",
			"marathon-user", "marathon-password",
		} {
			secretValue, ok := secret.Data[secretName].(string)
			if ok {
				viper.Set(secretName, secretValue)
			} else {
				log.Warnf("secret/mantl-api didn't contain %s", secretName)
			}
		}
	}
}
Exemplo n.º 29
0
// authenticate with the remote client
func authenticate(c *vaultapi.Client, authType string, params map[string]string) (err error) {
	var secret *vaultapi.Secret

	// handle panics gracefully by creating an error
	// this would happen when we get a parameter that is missing
	defer panicToError(&err)

	switch authType {
	case "app-id":
		secret, err = c.Logical().Write("/auth/app-id/login", map[string]interface{}{
			"app_id":  getParameter("app-id", params),
			"user_id": getParameter("user-id", params),
		})
	case "github":
		secret, err = c.Logical().Write("/auth/github/login", map[string]interface{}{
			"token": getParameter("token", params),
		})
	case "token":
		c.SetToken(getParameter("token", params))
		secret, err = c.Logical().Read("/auth/token/lookup-self")
	case "userpass":
		username, password := getParameter("username", params), getParameter("password", params)
		secret, err = c.Logical().Write(fmt.Sprintf("/auth/userpass/login/%s", username), map[string]interface{}{
			"password": password,
		})
	}

	if err != nil {
		return err
	}

	// if the token has already been set
	if c.Token() != "" {
		return nil
	}

	log.Debug("client authenticated with auth backend: %s", authType)
	// the default place for a token is in the auth section
	// otherwise, the backend will set the token itself
	c.SetToken(secret.Auth.ClientToken)
	return nil
}
Exemplo n.º 30
0
func unsealVault(vc *vault.Client, initResponse *vault.InitResponse) string {
	log.Info("Unseal vault")
	_, err := vc.Sys().Unseal(initResponse.Keys[0])
	fatal(err)
	return initResponse.RootToken
}