// GetKeyLoader returns the keyloader for a TLSConfig object. If the keyloader
// has not been initialized, it will first do so.
9674
func (t *TLSConfig) GetKeyLoader() *KeyLoader {
	t.keyloaderLock.Lock()
	defer t.keyloaderLock.Unlock()

	// If the keyloader has not yet been initialized, do it here
	if t.KeyLoader == nil {
		t.KeyLoader = &KeyLoader{}
	}
	return t.KeyLoader
}
1293809
func (fs *FSLocalKeyStore) GetKey(proxyHost string, username string) (*Key, error) {
	dirPath, err := fs.dirFor(proxyHost, false)
	if err != nil {
		return nil, trace.Wrap(err)
	}
	_, err = ioutil.ReadDir(dirPath)
	if err != nil {
		return nil, trace.NotFound("no session keys for %v in %v", username, proxyHost)
	}

	certFile := filepath.Join(dirPath, username+fileExtCert)
	cert, err := ioutil.ReadFile(certFile)
	if err != nil {
		fs.log.Error(err)
		return nil, trace.Wrap(err)
	}
	tlsCertFile := filepath.Join(dirPath, username+fileExtTLSCert)
	tlsCert, err := ioutil.ReadFile(tlsCertFile)
	if err != nil {
		fs.log.Error(err)
		return nil, trace.Wrap(err)
	}
	pub, err := ioutil.ReadFile(filepath.Join(dirPath, username+fileExtPub))
	if err != nil {
		fs.log.Error(err)
		return nil, trace.Wrap(err)
	}
	priv, err := ioutil.ReadFile(filepath.Join(dirPath, username))
	if err != nil {
		fs.log.Error(err)
		return nil, trace.Wrap(err)
	}

	key := &Key{Pub: pub, Priv: priv, Cert: cert, ProxyHost: proxyHost, TLSCert: tlsCert}

	// Validate the key loaded from disk.
	err = key.CheckCert()
	if err != nil {
		// KeyStore should return expired certificates as well
		if !utils.IsCertExpiredError(err) {
			return nil, trace.Wrap(err)
		}
	}
	sshCertExpiration, err := key.CertValidBefore()
	if err != nil {
		return nil, trace.Wrap(err)
	}
	tlsCertExpiration, err := key.TLSCertValidBefore()
	if err != nil {
		return nil, trace.Wrap(err)
	}

	// Note, we may be returning expired certificates here, that is okay. If the
	// certificates is expired, it's the responsibility of the TeleportClient to
	// perform cleanup of the certificates and the profile.
	fs.log.Debugf("Returning SSH certificate %q valid until %q, TLS certificate %q valid until %q.",
		certFile, sshCertExpiration, tlsCertFile, tlsCertExpiration)

	return key, nil
}
550772
func (c *ConfigLocal) KeyManager() KeyManager {
	c.lock.RLock()
	defer c.lock.RUnlock()
	return c.keyman
}
362408
func GetLogger(ctx context.Context) *logger.Logger {
	return ctx.Value(logKey).(*logger.Logger)
}
584837
func (km *KeyManagerStandard) GetTLFCryptKeyForBlockDecryption(
	ctx context.Context, kmd libkey.KeyMetadata, blockPtr data.BlockPointer) (
	tlfCryptKey kbfscrypto.TLFCryptKey, err error) {
	return km.getTLFCryptKeyUsingCurrentDevice(ctx, kmd, blockPtr.KeyGen, true)
}
1258257
func (s *GenericKeyStore) GetKey(keyID string) (data.PrivateKey, data.RoleName, error) {
	s.Lock()
	defer s.Unlock()

	cachedKeyEntry, ok := s.cachedKeys[keyID]
	if ok {
		return cachedKeyEntry.key, cachedKeyEntry.role, nil
	}

	role, err := getKeyRole(s.store, keyID)
	if err != nil {
		return nil, "", err
	}

	keyBytes, err := s.store.Get(keyID)
	if err != nil {
		return nil, "", err
	}

	// See if the key is encrypted. If its encrypted we'll fail to parse the private key
	privKey, err := utils.ParsePEMPrivateKey(keyBytes, "")
	if err != nil {
		privKey, _, err = GetPasswdDecryptBytes(s.PassRetriever, keyBytes, keyID, string(role))
		if err != nil {
			return nil, "", err
		}
	}
	s.cachedKeys[keyID] = &cachedKey{role: role, key: privKey}
	return privKey, role, nil
}
248802
func (ks *KeyServerLocal) GetTLFCryptKeyServerHalf(
	ctx context.Context, serverHalfID kbfscrypto.TLFCryptKeyServerHalfID,
	key kbfscrypto.CryptPublicKey) (
	serverHalf kbfscrypto.TLFCryptKeyServerHalf, err error) {
	if err := checkContext(ctx); err != nil {
		return kbfscrypto.TLFCryptKeyServerHalf{}, err
	}

	ks.shutdownLock.RLock()
	defer ks.shutdownLock.RUnlock()
	if *ks.shutdown {
		err = errors.New("Key server already shut down")
	}

	buf, err := ks.db.Get(serverHalfID.ID.Bytes(), nil)
	if err != nil {
		return
	}

	err = ks.config.Codec().Decode(buf, &serverHalf)
	if err != nil {
		return kbfscrypto.TLFCryptKeyServerHalf{}, err
	}

	session, err := ks.config.KBPKI().GetCurrentSession(ctx)
	if err != nil {
		return kbfscrypto.TLFCryptKeyServerHalf{}, err
	}

	err = kbfscrypto.VerifyTLFCryptKeyServerHalfID(
		serverHalfID, session.UID, key, serverHalf)
	if err != nil {
		ks.log.CDebugf(ctx, "error verifying server half ID: %+v", err)
		return kbfscrypto.TLFCryptKeyServerHalf{},
			kbfsmd.ServerErrorUnauthorized{Err: err}
	}
	return serverHalf, nil
}
1340024
func (c *Config) KeyPair() (*tls.Certificate, error) {
	return loadKeyPair(c.CertFile, c.KeyFile)
}
1009035
func (con *Connection) getDecrypter() crypto.Decrypter {
	session := con.context.GetSessionForConnection(con.connection)
	if session != nil {
		return session.Decrypter()
	}

	return nil
}
291257
func (p *ParsedCSRBundle) getSigner() (crypto.Signer, error) {
	var signer crypto.Signer
	var err error

	if p.PrivateKeyBytes == nil || len(p.PrivateKeyBytes) == 0 {
		return nil, errutil.UserError{Err: "Given parsed cert bundle does not have private key information"}
	}

	switch p.PrivateKeyType {
	case ECPrivateKey:
		signer, err = x509.ParseECPrivateKey(p.PrivateKeyBytes)
		if err != nil {
			return nil, errutil.UserError{Err: fmt.Sprintf("Unable to parse CA's private EC key: %s", err)}
		}

	case RSAPrivateKey:
		signer, err = x509.ParsePKCS1PrivateKey(p.PrivateKeyBytes)
		if err != nil {
			return nil, errutil.UserError{Err: fmt.Sprintf("Unable to parse CA's private RSA key: %s", err)}
		}

	default:
		return nil, errutil.UserError{Err: "Unable to determine type of private key; only RSA and EC are supported"}
	}
	return signer, nil
}
263368
func (c *ConfigLocal) Signer() kbfscrypto.Signer {
	c.lock.RLock()
	defer c.lock.RUnlock()
	return c.crypto
}
210874
func (dcp *diskCertProvider) loadCertAndKey() error {
	cert, err := tls.LoadX509KeyPair(dcp.certPath, dcp.keyPath)
	if err != nil {
		return err
	}

	dcp.Lock()
	defer dcp.Unlock()

	dcp.cert = &cert
	return nil
}
1064878
func (f *PluginAPIClientMeta) GetTLSConfig() *TLSConfig {
	// If we need custom TLS configuration, then set it
	if f.flagCACert != "" || f.flagCAPath != "" || f.flagClientCert != "" || f.flagClientKey != "" || f.flagInsecure {
		t := &TLSConfig{
			CACert:        f.flagCACert,
			CAPath:        f.flagCAPath,
			ClientCert:    f.flagClientCert,
			ClientKey:     f.flagClientKey,
			TLSServerName: "",
			Insecure:      f.flagInsecure,
		}

		return t
	}

	return nil
}
1368773
func (md *RootMetadataV3) GetTLFCryptKeyParams(
	keyGen KeyGen, user keybase1.UID,
	key kbfscrypto.CryptPublicKey, extra ExtraMetadata) (
	kbfscrypto.TLFEphemeralPublicKey,
	kbfscrypto.EncryptedTLFCryptKeyClientHalf,
	kbfscrypto.TLFCryptKeyServerHalfID, bool, error) {
	if keyGen != md.LatestKeyGeneration() {
		return kbfscrypto.TLFEphemeralPublicKey{},
			kbfscrypto.EncryptedTLFCryptKeyClientHalf{},
			kbfscrypto.TLFCryptKeyServerHalfID{}, false,
			TLFCryptKeyNotPerDeviceEncrypted{md.TlfID(), keyGen}
	}
	wkb, rkb, err := md.getTLFKeyBundles(extra)
	if err != nil {
		return kbfscrypto.TLFEphemeralPublicKey{},
			kbfscrypto.EncryptedTLFCryptKeyClientHalf{},
			kbfscrypto.TLFCryptKeyServerHalfID{}, false, err
	}
	isWriter := true
	dkim := wkb.Keys[user]
	if dkim == nil {
		dkim = rkb.Keys[user]
		if dkim == nil {
			return kbfscrypto.TLFEphemeralPublicKey{},
				kbfscrypto.EncryptedTLFCryptKeyClientHalf{},
				kbfscrypto.TLFCryptKeyServerHalfID{}, false, nil
		}
		isWriter = false
	}
	info, ok := dkim[key]
	if !ok {
		return kbfscrypto.TLFEphemeralPublicKey{},
			kbfscrypto.EncryptedTLFCryptKeyClientHalf{},
			kbfscrypto.TLFCryptKeyServerHalfID{}, false, nil
	}

	var publicKeys kbfscrypto.TLFEphemeralPublicKeys
	var keyType string
	if isWriter {
		publicKeys = wkb.TLFEphemeralPublicKeys
		keyType = "writer"
	} else {
		publicKeys = rkb.TLFEphemeralPublicKeys
		keyType = "reader"
	}
	keyCount := len(publicKeys)
	index := info.EPubKeyIndex
	if index >= keyCount {
		return kbfscrypto.TLFEphemeralPublicKey{},
			kbfscrypto.EncryptedTLFCryptKeyClientHalf{},
			kbfscrypto.TLFCryptKeyServerHalfID{}, false,
			errors.Errorf("Invalid %s key index %d >= %d",
				keyType, index, keyCount)
	}
	return publicKeys[index], info.ClientHalf, info.ServerHalfID, true, nil
}
539708
func (k *KeyCacheStandard) GetTLFCryptKey(tlf tlf.ID, keyGen kbfsmd.KeyGen) (
	kbfscrypto.TLFCryptKey, error) {
	cacheKey := keyCacheKey{tlf, keyGen}
	if entry, ok := k.lru.Get(cacheKey); ok {
		if key, ok := entry.(kbfscrypto.TLFCryptKey); ok {
			return key, nil
		}
		// shouldn't really be possible
		return kbfscrypto.TLFCryptKey{}, KeyCacheHitError{tlf, keyGen}
	}
	return kbfscrypto.TLFCryptKey{}, KeyCacheMissError{tlf, keyGen}
}
1318982
func (m *MockCryptoSetup) GetOpener(arg0 protocol.EncryptionLevel) (handshake.Opener, error) {
	m.ctrl.T.Helper()
	ret := m.ctrl.Call(m, "GetOpener", arg0)
	ret0, _ := ret[0].(handshake.Opener)
	ret1, _ := ret[1].(error)
	return ret0, ret1
}
452699
func loadX509KeyPair(certFile, keyFile string) (tls.Certificate, error) {
	certPEMBlock, err := ioutil.ReadFile(certFile)
	if err != nil {
		return tls.Certificate{}, uiErrSSLUnexpectedError(err)
	}
	keyPEMBlock, err := ioutil.ReadFile(keyFile)
	if err != nil {
		return tls.Certificate{}, uiErrSSLUnexpectedError(err)
	}
	key, rest := pem.Decode(keyPEMBlock)
	if len(rest) > 0 {
		return tls.Certificate{}, uiErrSSLUnexpectedData(nil).Msg("The private key contains additional data")
	}
	if x509.IsEncryptedPEMBlock(key) {
		password, ok := os.LookupEnv(TLSPrivateKeyPassword)
		if !ok {
			return tls.Certificate{}, uiErrSSLNoPassword(nil)
		}
		decryptedKey, decErr := x509.DecryptPEMBlock(key, []byte(password))
		if decErr != nil {
			return tls.Certificate{}, uiErrSSLWrongPassword(decErr)
		}
		keyPEMBlock = pem.EncodeToMemory(&pem.Block{Type: key.Type, Bytes: decryptedKey})
	}
	cert, err := tls.X509KeyPair(certPEMBlock, keyPEMBlock)
	if err != nil {
		return tls.Certificate{}, uiErrSSLUnexpectedData(nil).Msg(err.Error())
	}
	// Ensure that the private key is not a P-384 or P-521 EC key.
	// The Go TLS stack does not provide constant-time implementations of P-384 and P-521.
	if priv, ok := cert.PrivateKey.(crypto.Signer); ok {
		if pub, ok := priv.Public().(*ecdsa.PublicKey); ok {
			if name := pub.Params().Name; name == "P-384" || name == "P-521" { // unfortunately there is no cleaner way to check
				return tls.Certificate{}, uiErrSSLUnexpectedData(nil).Msg("tls: the ECDSA curve '%s' is not supported", name)
			}
		}
	}
	return cert, nil
}