// makeTeleportClientConfig creates default teleport client configuration
// that is used to initiate an SSH terminal session or SCP file transfer
433264
func makeTeleportClientConfig(ctx *SessionContext) (*client.Config, error) {
	agent, cert, err := ctx.GetAgent()
	if err != nil {
		return nil, trace.BadParameter("failed to get user credentials: %v", err)
	}

	signers, err := agent.Signers()
	if err != nil {
		return nil, trace.BadParameter("failed to get user credentials: %v", err)
	}

	tlsConfig, err := ctx.ClientTLSConfig()
	if err != nil {
		return nil, trace.BadParameter("failed to get client TLS config: %v", err)
	}

	config := &client.Config{
		Username:         ctx.user,
		Agent:            agent,
		SkipLocalAuth:    true,
		TLS:              tlsConfig,
		AuthMethods:      []ssh.AuthMethod{ssh.PublicKeys(signers...)},
		DefaultPrincipal: cert.ValidPrincipals[0],
		HostKeyCallback:  func(string, net.Addr, ssh.PublicKey) error { return nil },
	}

	return config, nil
}
70394
func AnonymousClientConfig(config *Config) *Config {
	// copy only known safe fields
	return &Config{
		Host:          config.Host,
		APIPath:       config.APIPath,
		ContentConfig: config.ContentConfig,
		TLSClientConfig: TLSClientConfig{
			Insecure:   config.Insecure,
			ServerName: config.ServerName,
			CAFile:     config.TLSClientConfig.CAFile,
			CAData:     config.TLSClientConfig.CAData,
		},
		RateLimiter: config.RateLimiter,
		UserAgent:   config.UserAgent,
		QPS:         config.QPS,
		Burst:       config.Burst,
		Timeout:     config.Timeout,
		Dial:        config.Dial,
	}
}
85243
func (api *PublicWhisperAPI) MakeLightClient(ctx context.Context) bool {
	api.w.SetLightClientMode(true)
	return api.w.LightClientMode()
}
287916
func (config *DeferredLoadingClientConfig) ClientConfig() (*client.Config, error) {
	mergedClientConfig, err := config.createClientConfig()
	if err != nil {
		return nil, err
	}
	mergedConfig, err := mergedClientConfig.ClientConfig()
	if err != nil {
		return nil, err
	}
	// Are we running in a cluster and were no other configs found? If so, use the in-cluster-config.
	icc := inClusterClientConfig{}
	defaultConfig, err := DefaultClientConfig.ClientConfig()
	if icc.Possible() && err == nil && reflect.DeepEqual(mergedConfig, defaultConfig) {
		glog.V(2).Info("No kubeconfig could be created, falling back to service account.")
		return icc.ClientConfig()
	}

	return mergedConfig, nil
}
1007938
func MakeSampleFileConfig() (fc *FileConfig) {
	conf := service.MakeDefaultConfig()

	// sample global config:
	var g Global
	g.NodeName = conf.Hostname
	g.AuthToken = "cluster-join-token"
	g.Logger.Output = "stderr"
	g.Logger.Severity = "INFO"
	g.AuthServers = []string{defaults.AuthListenAddr().Addr}
	g.Limits.MaxConnections = defaults.LimiterMaxConnections
	g.Limits.MaxUsers = defaults.LimiterMaxConcurrentUsers
	g.DataDir = defaults.DataDir
	g.PIDFile = "/var/run/teleport.pid"

	// sample SSH config:
	var s SSH
	s.EnabledFlag = "yes"
	s.ListenAddress = conf.SSH.Addr.Addr
	s.Commands = []CommandLabel{
		{
			Name:    "hostname",
			Command: []string{"/usr/bin/hostname"},
			Period:  time.Minute,
		},
		{
			Name:    "arch",
			Command: []string{"/usr/bin/uname", "-p"},
			Period:  time.Hour,
		},
	}
	s.Labels = map[string]string{
		"db_type": "postgres",
		"db_role": "master",
	}

	// sample Auth config:
	var a Auth
	a.ListenAddress = conf.Auth.SSHAddr.Addr
	a.EnabledFlag = "yes"
	a.StaticTokens = []StaticToken{"proxy,node:cluster-join-token"}

	// sample proxy config:
	var p Proxy
	p.EnabledFlag = "yes"
	p.ListenAddress = conf.Proxy.SSHAddr.Addr
	p.WebAddr = conf.Proxy.WebAddr.Addr
	p.TunAddr = conf.Proxy.ReverseTunnelListenAddr.Addr
	p.CertFile = "/var/lib/teleport/webproxy_cert.pem"
	p.KeyFile = "/var/lib/teleport/webproxy_key.pem"

	fc = &FileConfig{
		Global: g,
		Proxy:  p,
		SSH:    s,
		Auth:   a,
	}
	return fc
}
1197747
func ClientConfig() *plugin.ClientConfig {
	return &plugin.ClientConfig{
		HandshakeConfig: handshakeConfig,
		Plugins: map[string]plugin.Plugin{
			Name: &ProviderPlugin{},
		},
	}
}
392606
func NewClientFromConfig(clientCtx context.Context, conf *cloudstorage.Config) (*Client, error) {

	var sshConfig *ssh.ClientConfig
	var err error

	switch conf.AuthMethod {
	case AuthUserKey: //"userkey"
		sshConfig, err = ConfigUserKey(conf.Settings.String(ConfKeyUser), conf.Settings.String(ConfKeyPrivateKey))
		if err != nil {
			gou.WarnCtx(clientCtx, "error configuring private key %v", err)
			return nil, err
		}
	case AuthUserPass: //"userpass"
		sshConfig = ConfigUserPass(conf.Settings.String(ConfKeyUser), conf.Settings.String(ConfKeyPassword))
	default:
		err := fmt.Errorf("invalid config.AuthMethod %q", conf.AuthMethod)
		gou.WarnCtx(clientCtx, "%v", err)
		return nil, err
	}

	// optional
	host := conf.Settings.String(ConfKeyHost)
	folder := conf.Settings.String(ConfKeyFolder)
	port := conf.Settings.Int(ConfKeyPort)

	return NewClient(clientCtx, conf, host, port, folder, sshConfig)
}
106191
func (config DirectClientConfig) ClientConfig() (*client.Config, error) {
	if err := config.ConfirmUsable(); err != nil {
		return nil, err
	}

	configAuthInfo := config.getAuthInfo()
	configClusterInfo := config.getCluster()

	clientConfig := &client.Config{}
	clientConfig.Host = configClusterInfo.Server
	if u, err := url.ParseRequestURI(clientConfig.Host); err == nil && u.Opaque == "" && len(u.Path) > 1 {
		clientConfig.Prefix = u.Path
		u.Path = ""
		u.RawQuery = ""
		u.Fragment = ""
		clientConfig.Host = u.String()
	}
	if len(configClusterInfo.APIVersion) != 0 {
		gv, err := unversioned.ParseGroupVersion(configClusterInfo.APIVersion)
		if err != nil {
			return nil, err
		}
		clientConfig.GroupVersion = &gv
	}

	// only try to read the auth information if we are secure
	if client.IsConfigTransportTLS(*clientConfig) {
		var err error

		// mergo is a first write wins for map value and a last writing wins for interface values
		userAuthPartialConfig, err := getUserIdentificationPartialConfig(configAuthInfo, config.fallbackReader)
		if err != nil {
			return nil, err
		}
		mergo.Merge(clientConfig, userAuthPartialConfig)

		serverAuthPartialConfig, err := getServerIdentificationPartialConfig(configAuthInfo, configClusterInfo)
		if err != nil {
			return nil, err
		}
		mergo.Merge(clientConfig, serverAuthPartialConfig)
	}

	return clientConfig, nil
}
701583
func createClientTLSConfig(certBytes []byte, key *ecdsa.PrivateKey) (*tls.Config, error) {
	clientCert, err := x509.ParseCertificate(certBytes)
	if err != nil {
		return nil, errwrap.Wrapf("error parsing generated plugin certificate: {{err}}", err)
	}

	cert := tls.Certificate{
		Certificate: [][]byte{certBytes},
		PrivateKey:  key,
		Leaf:        clientCert,
	}

	clientCertPool := x509.NewCertPool()
	clientCertPool.AddCert(clientCert)

	tlsConfig := &tls.Config{
		Certificates: []tls.Certificate{cert},
		RootCAs:      clientCertPool,
		ClientCAs:    clientCertPool,
		ClientAuth:   tls.RequireAndVerifyClientCert,
		ServerName:   clientCert.Subject.CommonName,
		MinVersion:   tls.VersionTLS12,
	}

	tlsConfig.BuildNameToCertificate()

	return tlsConfig, nil
}
1047254
func createGrpcClient(cfg *ConnectionConfig, tlsEnabled bool) (*comm.GRPCClient, error) {
	clientConfig := comm.ClientConfig{Timeout: time.Second}

	if tlsEnabled {
		if cfg.TlsRootCertFile == "" {
			return nil, errors.New("missing TlsRootCertFile in client config")
		}
		caPEM, err := ioutil.ReadFile(cfg.TlsRootCertFile)
		if err != nil {
			return nil, errors.WithMessage(err, fmt.Sprintf("unable to load TLS cert from %s", cfg.TlsRootCertFile))
		}
		secOpts := &comm.SecureOptions{
			UseTLS:            true,
			ServerRootCAs:     [][]byte{caPEM},
			RequireClientCert: false,
		}
		clientConfig.SecOpts = secOpts
	}

	return comm.NewGRPCClient(clientConfig)
}
844058
func NewGRPCConnection(hostname string, port string, tlsConfig *tls.Config) (*grpc.ClientConn, error) {
	var opts []grpc.DialOption
	netAddr := net.JoinHostPort(hostname, port)
	creds := credentials.NewTLS(tlsConfig)
	opts = append(opts, grpc.WithTransportCredentials(creds))
	return grpc.Dial(netAddr, opts...)
}
767941
func makeHTTPClient(remoteAddr string) (string, *http.Client) {
	address, dialer := makeHTTPDialer(remoteAddr)
	return "http://" + address, &http.Client{
		Transport: &http.Transport{
			Dial: dialer,
		},
	}
}
212634
func (s *Service) CreateTelegrafConfig(ctx context.Context, tc *influxdb.TelegrafConfig, userID influxdb.ID) error {
	return s.kv.Update(ctx, func(tx Tx) error {
		return s.createTelegrafConfig(ctx, tx, tc, userID)
	})
}
669577
func makeHTTPClient(config *Config) (*http.Client, error) {
	tlsConfig := &tls.Config{}

	if config.TLSClientCAPath != "" {
		ca, err := ioutil.ReadFile(config.TLSClientCAPath)
		if err != nil {
			return nil, err
		}
		caCertPool := x509.NewCertPool()
		caCertPool.AppendCertsFromPEM(ca)
		tlsConfig.RootCAs = caCertPool
	}

	if config.TLSCertPath != "" && config.TLSPrivateKeyPath != "" {
		certs, err := tls.LoadX509KeyPair(config.TLSCertPath, config.TLSPrivateKeyPath)
		if err != nil {
			return nil, err
		}
		tlsConfig.Certificates = []tls.Certificate{certs}
	}
	tlsConfig.BuildNameToCertificate()

	return &http.Client{
		Timeout: 10 * time.Second,
		Transport: &http.Transport{
			Dial:                (&net.Dialer{Timeout: 5 * time.Second}).Dial,
			TLSHandshakeTimeout: 5 * time.Second,
			TLSClientConfig:     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
}
1018792
func NewClientWithConfig(uri, key string, config Config) (Client, error) {
	if config.Pin == nil {
		return NewClient(uri, key)
	}
	d := &pinned.Config{Pin: config.Pin}
	if config.Domain != "" {
		d.Config = &tls.Config{ServerName: config.Domain}
	}
	httpClient := &http.Client{Transport: &http.Transport{DialTLS: d.Dial}}
	c := newClient(key, uri, httpClient)
	c.Host = config.Domain
	c.HijackDial = d.Dial
	return c, nil
}
1362990
func CreateSSHClient(params *SSHClientParams) (*ssh.Client, error) {

	// collect file info
	fileExists := false
	if params.PrivateKeyPath != "" {
		_, err := os.Stat(params.PrivateKeyPath)
		fileExists = err == nil
	}

	// collect option
	strOpt := ""
	if fileExists {
		strOpt = fmt.Sprintf(" -i %s", params.PrivateKeyPath)
	}

	if !params.Quiet {
		// output connect info
		fmt.Fprintf(params.Out, "\nconnecting server...\n\tcommand: ssh %s@%s%s\n\n", params.UserName, params.TargetHost(), strOpt)
	}
	cnf := &ssh.ClientConfig{
		User:    params.UserName,
		Timeout: 10 * time.Second,
	}

	// build auth methods
	var authMethods []ssh.AuthMethod

	// add ssh-agent
	//sshSock := os.ExpandEnv("$SSH_AUTH_SOCK")
	//if sshSock != "" {
	//	addr, _ := net.ResolveUnixAddr("unix", sshSock)
	//	agentConn, _ := net.DialUnix("unix", nil, addr)
	//	ag := agent.NewClient(agentConn)
	//	authMethods = append(authMethods, ssh.PublicKeysCallback(ag.Signers))
	//}

	// private key

	if fileExists {
		signer, err := getSigners(params.PrivateKeyPath, params.Password)
		if err != nil {
			return nil, fmt.Errorf("parse private-key(%s) is failed: %s", params.PrivateKeyPath, err)
		}
		authMethods = append(authMethods, ssh.PublicKeys(signer...))
	}

	// password prompt
	authMethods = append(authMethods, ssh.PasswordCallback(func() (string, error) {
		if params.Password == "" {
			prefix := ""
			if params.DisplayName != "" {
				prefix = fmt.Sprintf("%s | ", params.DisplayName)
			}
			return pprompt(fmt.Sprintf("%spassword: ", prefix))
		}
		return params.Password, nil
	}))

	cnf.Auth = authMethods
	var conn *ssh.Client

	conn, err := ssh.Dial("tcp", params.TargetHost(), cnf)
	if err != nil {
		return nil, fmt.Errorf("connecting(%s) is failed: %s", params.TargetHost(), err)
	}

	return conn, nil
}