// ClientLookup satisfies the ClusterClient interface and returns the ha tls
// client certs.
2971
func (c *requestForwardingClusterClient) ClientLookup(ctx context.Context, requestInfo *tls.CertificateRequestInfo) (*tls.Certificate, error) {
	parsedCert := c.core.localClusterParsedCert.Load().(*x509.Certificate)
	if parsedCert == nil {
		return nil, nil
	}
	currCert := c.core.localClusterCert.Load().([]byte)
	if len(currCert) == 0 {
		return nil, nil
	}
	localCert := make([]byte, len(currCert))
	copy(localCert, currCert)

	for _, subj := range requestInfo.AcceptableCAs {
		if bytes.Equal(subj, parsedCert.RawIssuer) {
			return &tls.Certificate{
				Certificate: [][]byte{localCert},
				PrivateKey:  c.core.localClusterPrivateKey.Load().(*ecdsa.PrivateKey),
				Leaf:        c.core.localClusterParsedCert.Load().(*x509.Certificate),
			}, nil
		}
	}

	return nil, nil
}
1095595
func (c *client) zkLookup(ctx context.Context, resource zk.ResourceName) (string, error) {
	// We make this a buffered channel so that if we stop waiting due to a
	// timeout, we won't block the zkLookupSync() that we start in a
	// separate goroutine.
	reschan := make(chan zkResult, 1)
	go func() {
		addr, err := c.zkClient.LocateResource(resource.Prepend(c.zkRoot))
		// This is guaranteed to never block as the channel is always buffered.
		reschan <- zkResult{addr, err}
	}()
	select {
	case res := <-reschan:
		return res.addr, res.err
	case <-ctx.Done():
		return "", ctx.Err()
	}
}
420214
func (ens *NetpluginNameServer) NsLookup(nsq []byte, vrfPtr *string) ([]byte, error) {
	tenant := *vrfPtr
	req := new(dns.Msg)
	err := req.Unpack(nsq)
	if err != nil {
		ens.incTenantStats(tenant, "invalidQuery")
		return nil, err
	}

	// no fancy requests
	if req.Response {
		ens.incTenantStats(tenant, "invalidQuery")
		return nil, errors.New("")
	}

	if req.IsTsig() != nil {
		ens.incTenantStats(tenant, "invalidQuery")
		return nil, errors.New("")
	}

	d, err := ens.serveNameRecord(tenant, req)
	if err != nil {
		logrus.Infof("no name record: %s", err)
		ens.incTenantStats(tenant, "noNameRecord")
		return nil, err
	}

	ens.incTenantStats(tenant, "foundNameRecord")
	return d, err

}
1321132
func (t *TLSServer) GetConfigForClient(info *tls.ClientHelloInfo) (*tls.Config, error) {
	var clusterName string
	var err error
	if info.ServerName != "" {
		clusterName, err = auth.DecodeClusterName(info.ServerName)
		if err != nil {
			if !trace.IsNotFound(err) {
				log.Debugf("Ignoring unsupported cluster name name %q.", info.ServerName)
				clusterName = ""
			}
		}
	}
	pool, err := auth.ClientCertPool(t.AccessPoint, clusterName)
	if err != nil {
		log.Errorf("failed to retrieve client pool: %v", trace.DebugReport(err))
		// this falls back to the default config
		return nil, nil
	}
	tlsCopy := t.TLS.Clone()
	tlsCopy.ClientCAs = pool
	return tlsCopy, nil
}
259092
func (o *LoginOptions) getClientConfig() (*restclient.Config, error) {
	if o.Config != nil {
		return o.Config, nil
	}

	if len(o.Server) == 0 {
		// we need to have a server to talk to
		if kterm.IsTerminal(o.In) {
			for !o.serverProvided() {
				defaultServer := defaultClusterURL
				promptMsg := fmt.Sprintf("Server [%s]: ", defaultServer)
				o.Server = term.PromptForStringWithDefault(o.In, o.Out, defaultServer, promptMsg)
			}
		}
	}

	clientConfig := &restclient.Config{}

	// ensure clientConfig has timeout option
	if o.RequestTimeout > 0 {
		clientConfig.Timeout = o.RequestTimeout
	}

	// normalize the provided server to a format expected by config
	serverNormalized, err := config.NormalizeServerURL(o.Server)
	if err != nil {
		return nil, err
	}
	o.Server = serverNormalized
	clientConfig.Host = o.Server

	// use specified CA or find existing CA
	if len(o.CAFile) > 0 {
		clientConfig.CAFile = o.CAFile
		clientConfig.CAData = nil
	} else if caFile, caData, ok := findExistingClientCA(clientConfig.Host, *o.StartingKubeConfig); ok {
		clientConfig.CAFile = caFile
		clientConfig.CAData = caData
	}

	// try to TCP connect to the server to make sure it's reachable, and discover
	// about the need of certificates or insecure TLS
	if err := dialToServer(*clientConfig); err != nil {
		switch err.(type) {
		// certificate authority unknown, check or prompt if we want an insecure
		// connection or if we already have a cluster stanza that tells us to
		// connect to this particular server insecurely
		case x509.UnknownAuthorityError, x509.HostnameError, x509.CertificateInvalidError:
			if o.InsecureTLS ||
				hasExistingInsecureCluster(*clientConfig, *o.StartingKubeConfig) ||
				promptForInsecureTLS(o.In, o.Out, err) {
				clientConfig.Insecure = true
				clientConfig.CAFile = ""
				clientConfig.CAData = nil
			} else {
				return nil, getPrettyErrorForServer(err, o.Server)
			}
		// TLS record header errors, like oversized record which usually means
		// the server only supports "http"
		case tls.RecordHeaderError:
			return nil, getPrettyErrorForServer(err, o.Server)
		default:
			if _, ok := err.(*net.OpError); ok {
				return nil, fmt.Errorf("%v - verify you have provided the correct host and port and that the server is currently running.", err)
			}
			return nil, err
		}
	}

	o.Config = clientConfig

	return o.Config, nil
}
1369911
func (a *Client) DeleteLookupsID(params *DeleteLookupsIDParams, authInfo runtime.ClientAuthInfoWriter) (*DeleteLookupsIDOK, error) {
	// TODO: Validate the params before sending
	if params == nil {
		params = NewDeleteLookupsIDParams()
	}

	result, err := a.transport.Submit(&runtime.ClientOperation{
		ID:                 "DeleteLookupsID",
		Method:             "DELETE",
		PathPattern:        "/lookups/{id}",
		ProducesMediaTypes: []string{"application/json", "application/x-gzip"},
		ConsumesMediaTypes: []string{"application/json"},
		Schemes:            []string{"http", "https"},
		Params:             params,
		Reader:             &DeleteLookupsIDReader{formats: a.formats},
		AuthInfo:           authInfo,
	})
	if err != nil {
		return nil, err
	}
	return result.(*DeleteLookupsIDOK), nil
}
504880
func NewCluster(policy *ClientPolicy, hosts []*Host) (*Cluster, error) {
	// Default TLS names when TLS enabled.
	newHosts := make([]*Host, 0, len(hosts))
	if policy.TlsConfig != nil && !policy.TlsConfig.InsecureSkipVerify {
		useClusterName := len(policy.ClusterName) > 0

		for _, host := range hosts {
			nh := *host
			if nh.TLSName == "" {
				if useClusterName {
					nh.TLSName = policy.ClusterName
				} else {
					nh.TLSName = host.Name
				}
			}
			newHosts = append(newHosts, &nh)
		}
		hosts = newHosts
	}

	newCluster := &Cluster{
		clientPolicy: *policy,
		infoPolicy:   InfoPolicy{Timeout: policy.Timeout},
		tendChannel:  make(chan struct{}),

		seeds:    NewSyncVal(hosts),
		aliases:  NewSyncVal(make(map[Host]*Node)),
		nodesMap: NewSyncVal(make(map[string]*Node)),
		nodes:    NewSyncVal([]*Node{}),
		stats:    map[string]*nodeStats{},

		password: NewSyncVal(nil),

		supportsFloat:       NewAtomicBool(false),
		supportsBatchIndex:  NewAtomicBool(false),
		supportsReplicasAll: NewAtomicBool(false),
		supportsGeo:         NewAtomicBool(false),
	}

	newCluster.partitionWriteMap.Store(make(partitionMap))

	// setup auth info for cluster
	if policy.RequiresAuthentication() {
		if policy.AuthMode == AuthModeExternal && policy.TlsConfig == nil {
			return nil, errors.New("External Authentication requires TLS configuration to be set, because it sends clear password on the wire.")
		}

		newCluster.user = policy.User
		hashedPass, err := hashPassword(policy.Password)
		if err != nil {
			return nil, err
		}
		newCluster.password = NewSyncVal(hashedPass)
	}

	// try to seed connections for first use
	err := newCluster.waitTillStabilized()

	// apply policy rules
	if policy.FailIfNotConnected && !newCluster.IsConnected() {
		if err != nil {
			return nil, err
		}
		return nil, fmt.Errorf("Failed to connect to host(s): %v. The network connection(s) to cluster nodes may have timed out, or the cluster may be in a state of flux.", hosts)
	}

	// start up cluster maintenance go routine
	newCluster.wgTend.Add(1)
	go newCluster.clusterBoss(&newCluster.clientPolicy)

	if err == nil {
		Logger.Debug("New cluster initialized and ready to be used...")
	} else {
		Logger.Error("New cluster was not initialized successfully, but the client will keep trying to connect to the database. Error: %s", err.Error())
	}

	return newCluster, err
}
767075
func NewLookupService() *LookupService {
	return &LookupService{
		NameFn: func(ctx context.Context, resource platform.ResourceType, id platform.ID) (string, error) {
			return "", nil
		},
	}
}
1124336
func sslClientCertificates(tlsConf *tls.Config, o values) {
	sslkey := o.Get("sslkey")
	sslcert := o.Get("sslcert")

	var cinfo, kinfo os.FileInfo
	var err error

	if sslcert != "" && sslkey != "" {
		// Check that both files exist. Note that we don't do any more extensive
		// checks than this (such as checking that the paths aren't directories);
		// LoadX509KeyPair() will take care of the rest.
		cinfo, err = os.Stat(sslcert)
		if err != nil {
			panic(err)
		}

		kinfo, err = os.Stat(sslkey)
		if err != nil {
			panic(err)
		}
	} else {
		// Automatically find certificates from ~/.postgresql
		sslcert, sslkey, cinfo, kinfo = sslHomeCertificates()

		if cinfo == nil || kinfo == nil {
			// No certificates to load
			return
		}
	}

	// The files must also have the correct permissions
	sslCertificatePermissions(cinfo, kinfo)

	cert, err := tls.LoadX509KeyPair(sslcert, sslkey)
	if err != nil {
		panic(err)
	}
	tlsConf.Certificates = []tls.Certificate{cert}
}
1214133
func (r *Consumer) queryLookupd() {
	retries := 0

retry:
	endpoint := r.nextLookupdEndpoint()

	r.log(LogLevelInfo, "querying nsqlookupd %s", endpoint)

	var data lookupResp
	err := apiRequestNegotiateV1("GET", endpoint, nil, &data)
	if err != nil {
		r.log(LogLevelError, "error querying nsqlookupd (%s) - %s", endpoint, err)
		retries++
		if retries < 3 {
			r.log(LogLevelInfo, "retrying with next nsqlookupd")
			goto retry
		}
		return
	}

	var nsqdAddrs []string
	for _, producer := range data.Producers {
		broadcastAddress := producer.BroadcastAddress
		port := producer.TCPPort
		joined := net.JoinHostPort(broadcastAddress, strconv.Itoa(port))
		nsqdAddrs = append(nsqdAddrs, joined)
	}
	// apply filter
	if discoveryFilter, ok := r.behaviorDelegate.(DiscoveryFilter); ok {
		nsqdAddrs = discoveryFilter.Filter(nsqdAddrs)
	}
	for _, addr := range nsqdAddrs {
		err = r.ConnectToNSQD(addr)
		if err != nil && err != ErrAlreadyConnected {
			r.log(LogLevelError, "(%s) error connecting to nsqd - %s", addr, err)
			continue
		}
	}
}
1343786
func (a *Client) GetLookups(params *GetLookupsParams, authInfo runtime.ClientAuthInfoWriter) (*GetLookupsOK, error) {
	// TODO: Validate the params before sending
	if params == nil {
		params = NewGetLookupsParams()
	}

	result, err := a.transport.Submit(&runtime.ClientOperation{
		ID:                 "GetLookups",
		Method:             "GET",
		PathPattern:        "/lookups",
		ProducesMediaTypes: []string{"application/json", "application/x-gzip"},
		ConsumesMediaTypes: []string{"application/json"},
		Schemes:            []string{"http", "https"},
		Params:             params,
		Reader:             &GetLookupsReader{formats: a.formats},
		AuthInfo:           authInfo,
	})
	if err != nil {
		return nil, err
	}
	return result.(*GetLookupsOK), nil
}
1367351
func (client *GRPCClient) Certificate() tls.Certificate {
	cert := tls.Certificate{}
	if client.tlsConfig != nil && len(client.tlsConfig.Certificates) > 0 {
		cert = client.tlsConfig.Certificates[0]
	}
	return cert
}
1152904
func (k *Key) ClientTLSConfig() (*tls.Config, error) {
	// Because Teleport clients can't be configured (yet), they take the default
	// list of cipher suites from Go.
	tlsConfig := utils.TLSConfig(nil)

	pool := x509.NewCertPool()
	for _, ca := range k.TrustedCA {
		for _, certPEM := range ca.TLSCertificates {
			if !pool.AppendCertsFromPEM(certPEM) {
				return nil, trace.BadParameter("failed to parse certificate received from the proxy")
			}
		}
	}
	tlsConfig.RootCAs = pool
	tlsCert, err := tls.X509KeyPair(k.TLSCert, k.Priv)
	if err != nil {
		return nil, trace.Wrap(err, "failed to parse TLS cert and key")
	}
	tlsConfig.Certificates = append(tlsConfig.Certificates, tlsCert)
	return tlsConfig, nil
}
273032
func (tr *Transport) TLSClientAuthServerConfig() (*tls.Config, error) {
	cert, err := tr.getCertificate()
	if err != nil {
		return nil, err
	}

	return &tls.Config{
		Certificates: []tls.Certificate{cert},
		RootCAs:      tr.TrustStore.Pool(),
		ClientCAs:    tr.ClientTrustStore.Pool(),
		ClientAuth:   tls.RequireAndVerifyClientCert,
		CipherSuites: core.CipherSuites,
		MinVersion:   tls.VersionTLS12,
	}, nil
}
1105195
func (a *API) FeedsLookup(ctx context.Context, query *feed.Query) ([]byte, error) {
	_, err := a.feed.Lookup(ctx, query)
	if err != nil {
		return nil, err
	}
	var data []byte
	_, data, err = a.feed.GetContent(&query.Feed)
	if err != nil {
		return nil, err
	}
	return data, nil
}
30133
func (s *CreateHsmClientCertificateInput) SetHsmClientCertificateIdentifier(v string) *CreateHsmClientCertificateInput {
	s.HsmClientCertificateIdentifier = &v
	return s
}
327059
func getMatchingClusters(clientConfig restclient.Config, kubeconfig clientcmdapi.Config) sets.String {
	ret := sets.String{}

	for key, cluster := range kubeconfig.Clusters {
		if (cluster.Server == clientConfig.Host) && (cluster.InsecureSkipTLSVerify == clientConfig.Insecure) && (cluster.CertificateAuthority == clientConfig.CAFile) && (bytes.Compare(cluster.CertificateAuthorityData, clientConfig.CAData) == 0) {
			ret.Insert(key)
		}
	}

	return ret
}