// UnloadKeys will unload all Teleport keys from the teleport agent as well as
// the system agent.
165370
func (a *LocalKeyAgent) UnloadKeys() error {
	agents := []agent.Agent{a.Agent}
	if a.sshAgent != nil {
		agents = append(agents, a.sshAgent)
	}

	// iterate over all agents we have
	for i, _ := range agents {
		// get a list of all keys in the agent
		keyList, err := agents[i].List()
		if err != nil {
			a.log.Warnf("Unable to communicate with agent and list keys: %v", err)
		}

		// remove any teleport keys we currently have loaded in the agent
		for _, key := range keyList {
			if strings.HasPrefix(key.Comment, "teleport:") {
				err = agents[i].Remove(key)
				if err != nil {
					a.log.Warnf("Unable to communicate with agent and remove key: %v", err)
				}
			}
		}
	}

	return nil
}
649490
func RemoveUnusedKeys(t *data.SignedTargets) {
	unusedIDs := UnusedDelegationKeys(*t)
	for _, id := range unusedIDs {
		delete(t.Signed.Delegations.Keys, id)
	}
}
942197
func (c *Core) unloadMounts(ctx context.Context) error {
	c.mountsLock.Lock()
	defer c.mountsLock.Unlock()

	if c.mounts != nil {
		mountTable := c.mounts.shallowClone()
		for _, e := range mountTable.Entries {
			backend := c.router.MatchingBackend(namespace.ContextWithNamespace(ctx, e.namespace), e.Path)
			if backend != nil {
				backend.Cleanup(ctx)
			}

			viewPath := e.ViewPath()
			removePathCheckers(c, e, viewPath)
		}
	}

	c.mounts = nil
	c.router = NewRouter()
	c.systemBarrierView = nil
	return nil
}
385568
func (kr *GroupResolver) RemoveAllKeys() {
	kr.Lock()
	defer kr.Unlock()
	kr.keyMap = make(map[string][]Key)
	return
}
891164
func (a *LocalKeyAgent) DeleteKeys() error {
	// Remove keys from the filesystem.
	err := a.keyStore.DeleteKeys()
	if err != nil {
		return trace.Wrap(err)
	}

	// Remove all keys from the Teleport and system agents.
	err = a.UnloadKeys()
	if err != nil {
		return trace.Wrap(err)
	}

	return nil
}
1279950
func (o *InfrastructureAccessProfile) SSHKeys(info *bambou.FetchingInfo) (SSHKeysList, *bambou.Error) {

	var list SSHKeysList
	err := bambou.CurrentSession().FetchChildren(o, SSHKeyIdentity, &list, info)
	return list, err
}
57129
func (k *KeyLoader) LoadKeyPair(certFile, keyFile string) (*tls.Certificate, error) {
	k.cacheLock.Lock()
	defer k.cacheLock.Unlock()

	// Allow downgrading
	if certFile == "" && keyFile == "" {
		k.certificate = nil
		return nil, nil
	}

	cert, err := tls.LoadX509KeyPair(certFile, keyFile)
	if err != nil {
		return nil, fmt.Errorf("Failed to load cert/key pair: %v", err)
	}

	k.certificate = &cert
	return k.certificate, nil
}
555337
func (sse ssec) UnsealObjectKey(h http.Header, metadata map[string]string, bucket, object string) (key ObjectKey, err error) {
	clientKey, err := sse.ParseHTTP(h)
	if err != nil {
		return
	}
	return unsealObjectKey(clientKey, metadata, bucket, object)
}
701983
func (ps *PrefixScanner) Keys() (keys [][]byte, err error) {
	pre := ps.Prefix
	err = ps.db.View(func(tx *bolt.Tx) error {
		c := tx.Bucket(ps.BucketName).Cursor()
		for k, _ := c.Seek(pre); bytes.HasPrefix(k, pre); k, _ = c.Next() {
			keys = append(keys, k)
		}
		return nil
	})
	if err != nil {
		return nil, err
	}
	return keys, err
}
513113
func (tr *Repo) RemoveBaseKeys(role data.RoleName, keyIDs ...string) error {
	if tr.Root == nil {
		return ErrNotLoaded{Role: data.CanonicalRootRole}
	}
	var keep []string
	toDelete := make(map[string]struct{})
	emptyStruct := struct{}{}
	// remove keys from specified role
	for _, k := range keyIDs {
		toDelete[k] = emptyStruct
	}

	oldKeyIDs := tr.Root.Signed.Roles[role].KeyIDs
	for _, rk := range oldKeyIDs {
		if _, ok := toDelete[rk]; !ok {
			keep = append(keep, rk)
		}
	}

	tr.Root.Signed.Roles[role].KeyIDs = keep

	// also, whichever role had keys removed needs to be re-signed
	// root has already been marked dirty.
	tr.markRoleDirty(role)

	// determine which keys are no longer in use by any roles
	for roleName, r := range tr.Root.Signed.Roles {
		if roleName == role {
			continue
		}
		for _, rk := range r.KeyIDs {
			if _, ok := toDelete[rk]; ok {
				delete(toDelete, rk)
			}
		}
	}

	// Remove keys no longer in use by any roles, except for root keys.
	// Root private keys must be kept in tr.cryptoService to be able to sign
	// for rotation, and root certificates must be kept in tr.Root.SignedKeys
	// because we are not necessarily storing them elsewhere (tuf.Repo does not
	// depend on certs.Manager, that is an upper layer), and without storing
	// the certificates in their x509 form we are not able to do the
	// util.CanonicalKeyID conversion.
	if role != data.CanonicalRootRole {
		for k := range toDelete {
			delete(tr.Root.Signed.Keys, k)
			tr.cryptoService.RemoveKey(k)
		}
	}

	tr.Root.Dirty = true
	return nil
}
351471
func loadKeyring(c *serf.Config, keys []string) error {
	keysDecoded := make([][]byte, len(keys))
	for i, key := range keys {
		keyBytes, err := base64.StdEncoding.DecodeString(key)
		if err != nil {
			return err
		}
		keysDecoded[i] = keyBytes
	}

	if len(keysDecoded) == 0 {
		return fmt.Errorf("no keys present in keyring: %s", c.KeyringFile)
	}

	keyring, err := memberlist.NewKeyring(keysDecoded, keysDecoded[0])
	if err != nil {
		return err
	}

	c.MemberlistConfig.Keyring = keyring
	return nil
}
688260
func LoadMasterKeys(public crypto.PublicKey, private crypto.PrivateKey) {
	mKeyLock.Lock()
	defer mKeyLock.Unlock()
	masterKeys = MasterKeys{public, private}
}
555349
func (c *Core) UnsealWithStoredKeys(ctx context.Context) error {
	c.unsealWithStoredKeysLock.Lock()
	defer c.unsealWithStoredKeysLock.Unlock()

	if !c.seal.StoredKeysSupported() {
		return nil
	}

	// Disallow auto-unsealing when migrating
	if c.IsInSealMigration() {
		return NewNonFatalError(errors.New("cannot auto-unseal during seal migration"))
	}

	sealed := c.Sealed()
	if !sealed {
		c.Logger().Warn("attempted unseal with stored keys, but vault is already unsealed")
		return nil
	}

	c.Logger().Info("stored unseal keys supported, attempting fetch")
	keys, err := c.seal.GetStoredKeys(ctx)
	if err != nil {
		return NewNonFatalError(errwrap.Wrapf("fetching stored unseal keys failed: {{err}}", err))
	}

	// This usually happens when auto-unseal is configured, but the servers have
	// not been initialized yet.
	if len(keys) == 0 {
		return NewNonFatalError(errors.New("stored unseal keys are supported, but none were found"))
	}

	unsealed := false
	keysUsed := 0
	for _, key := range keys {
		unsealed, err = c.Unseal(key)
		if err != nil {
			return NewNonFatalError(errwrap.Wrapf("unseal with stored key failed: {{err}}", err))
		}
		keysUsed++
		if unsealed {
			break
		}
	}

	if !unsealed {
		// This most likely means that the user configured Vault to only store a
		// subset of the required threshold of keys. We still consider this a
		// "success", since trying again would yield the same result.
		c.Logger().Warn("vault still sealed after using stored unseal keys", "stored_keys_used", keysUsed)
	} else {
		c.Logger().Info("unsealed with stored keys", "stored_keys_used", keysUsed)
	}

	return nil
}
1317484
func (k *Key) AsAgentKeys() ([]*agent.AddedKey, error) {
	// unmarshal certificate bytes into a ssh.PublicKey
	publicKey, _, _, _, err := ssh.ParseAuthorizedKey(k.Cert)
	if err != nil {
		return nil, trace.Wrap(err)
	}

	// unmarshal private key bytes into a *rsa.PrivateKey
	privateKey, err := ssh.ParseRawPrivateKey(k.Priv)
	if err != nil {
		return nil, trace.Wrap(err)
	}

	// put a teleport identifier along with the teleport user into the comment field
	comment := fmt.Sprintf("teleport:%v", publicKey.(*ssh.Certificate).KeyId)

	// On Windows, return the certificate with the private key embedded.
	if runtime.GOOS == teleport.WindowsOS {
		return []*agent.AddedKey{
			&agent.AddedKey{
				PrivateKey:       privateKey,
				Certificate:      publicKey.(*ssh.Certificate),
				Comment:          comment,
				LifetimeSecs:     0,
				ConfirmBeforeUse: false,
			},
		}, nil
	}

	// On Unix, return the certificate (with embedded private key) as well as
	// a private key.
	//
	// This is done because OpenSSH clients older than OpenSSH 7.3/7.3p1
	// (2016-08-01) have a bug in how they use certificates that have been loaded
	// in an agent. Specifically when you add a certificate to an agent, you can't
	// just embed the private key within the certificate, you have to add the
	// certificate and private key to the agent separately. Teleport works around
	// this behavior to ensure OpenSSH interoperability.
	//
	// For more details see the following: https://bugzilla.mindrot.org/show_bug.cgi?id=2550
	// WARNING: callers expect the returned slice to be __exactly as it is__
	return []*agent.AddedKey{
		&agent.AddedKey{
			PrivateKey:       privateKey,
			Certificate:      publicKey.(*ssh.Certificate),
			Comment:          comment,
			LifetimeSecs:     0,
			ConfirmBeforeUse: false,
		},
		&agent.AddedKey{
			PrivateKey:       privateKey,
			Certificate:      nil,
			Comment:          comment,
			LifetimeSecs:     0,
			ConfirmBeforeUse: false,
		},
	}, nil
}
1304598
func (k *KBPKIClient) GetCryptPublicKeys(
	ctx context.Context, uid keybase1.UID,
	offline keybase1.OfflineAvailability) (
	keys []kbfscrypto.CryptPublicKey, err error) {
	userInfo, err := k.loadUserPlusKeys(ctx, uid, "", offline)
	if err != nil {
		return nil, err
	}
	return userInfo.CryptPublicKeys, nil
}
1137237
func (key *Key) Unbind(data []byte) ([]byte, error) {
	var encdata C.TSS_HENCDATA
	var dataLen C.UINT32
	var cData *C.BYTE

	err := tspiError(C.Tspi_Context_CreateObject(key.context, C.TSS_OBJECT_TYPE_ENCDATA, C.TSS_ENCDATA_BIND, (*C.TSS_HOBJECT)(&encdata)))
	if err != nil {
		return nil, err
	}

	err = tspiError(C.Tspi_SetAttribData((C.TSS_HOBJECT)(encdata), C.TSS_TSPATTRIB_ENCDATA_BLOB, C.TSS_TSPATTRIB_ENCDATABLOB_BLOB, (C.UINT32)(len(data)), (*C.BYTE)(unsafe.Pointer(&data[0]))))
	if err != nil {
		return nil, err
	}

	err = tspiError(C.Tspi_Data_Unbind(encdata, key.handle, &dataLen, &cData))
	if err != nil {
		return nil, err
	}

	blob := C.GoBytes(unsafe.Pointer(cData), (C.int(dataLen)))
	C.Tspi_Context_FreeMemory(key.context, cData)
	return blob, nil
}
1187024
func keyKeys(xu *xgbutil.XUtil) []xgbutil.KeyKey {
	xu.KeybindsLck.RLock()
	defer xu.KeybindsLck.RUnlock()

	keys := make([]xgbutil.KeyKey, len(xu.Keybinds))
	i := 0
	for key, _ := range xu.Keybinds {
		keys[i] = key
		i++
	}
	return keys
}