// IncomingTLSConfig generates a TLS configuration for incoming requests
765530
func (c *Config) IncomingTLSConfig() (*tls.Config, error) {
	// Create the tlsConfig
	tlsConfig := &tls.Config{
		ClientCAs:                x509.NewCertPool(),
		ClientAuth:               tls.NoClientCert,
		CipherSuites:             c.CipherSuites,
		MinVersion:               c.MinVersion,
		PreferServerCipherSuites: c.PreferServerCipherSuites,
	}

	// Parse the CA cert if any
	err := c.AppendCA(tlsConfig.ClientCAs)
	if err != nil {
		return nil, err
	}

	// Add cert/key
	cert, err := c.LoadKeyPair()
	if err != nil {
		return nil, err
	} else if cert != nil {
		tlsConfig.GetCertificate = c.KeyLoader.GetOutgoingCertificate
	}

	// Check if we require verification
	if c.VerifyIncoming {
		tlsConfig.ClientAuth = tls.RequireAndVerifyClientCert
		if c.CAFile == "" {
			return nil, fmt.Errorf("VerifyIncoming set, and no CA certificate provided!")
		}
		if cert == nil {
			return nil, fmt.Errorf("VerifyIncoming set, and no Cert/Key pair provided!")
		}
	}

	return tlsConfig, nil
}
252170
func (s *DefaultService) tlsConfig(hostname string) (*tls.Config, error) {
	return newTLSConfig(hostname, isSecureIndex(s.config, hostname))
}
1114761
func MakeTLSConfig(configs []*Config) (*tls.Config, error) {
	if len(configs) == 0 {
		return nil, nil
	}

	config := new(tls.Config)
	ciphersAdded := make(map[uint16]struct{})
	curvesAdded := make(map[tls.CurveID]struct{})
	configMap := make(configGroup)

	for i, cfg := range configs {
		if cfg == nil {
			// avoid nil pointer dereference below
			configs[i] = new(Config)
			continue
		}

		// Key this config by its hostname; this
		// overwrites configs with the same hostname
		configMap[cfg.Hostname] = cfg

		// Can't serve TLS and not-TLS on same port
		if i > 0 && cfg.Enabled != configs[i-1].Enabled {
			thisConfProto, lastConfProto := "not TLS", "not TLS"
			if cfg.Enabled {
				thisConfProto = "TLS"
			}
			if configs[i-1].Enabled {
				lastConfProto = "TLS"
			}
			return nil, fmt.Errorf("cannot multiplex %s (%s) and %s (%s) on same listener",
				configs[i-1].Hostname, lastConfProto, cfg.Hostname, thisConfProto)
		}

		if !cfg.Enabled {
			continue
		}

		// Union cipher suites
		for _, ciph := range cfg.Ciphers {
			if _, ok := ciphersAdded[ciph]; !ok {
				ciphersAdded[ciph] = struct{}{}
				config.CipherSuites = append(config.CipherSuites, ciph)
			}
		}

		// Can't resolve conflicting PreferServerCipherSuites settings
		if i > 0 && cfg.PreferServerCipherSuites != configs[i-1].PreferServerCipherSuites {
			return nil, fmt.Errorf("cannot both PreferServerCipherSuites and not prefer them")
		}
		config.PreferServerCipherSuites = cfg.PreferServerCipherSuites

		// Union curves
		for _, curv := range cfg.CurvePreferences {
			if _, ok := curvesAdded[curv]; !ok {
				curvesAdded[curv] = struct{}{}
				config.CurvePreferences = append(config.CurvePreferences, curv)
			}
		}

		// Go with the widest range of protocol versions
		if config.MinVersion == 0 || cfg.ProtocolMinVersion < config.MinVersion {
			config.MinVersion = cfg.ProtocolMinVersion
		}
		if cfg.ProtocolMaxVersion > config.MaxVersion {
			config.MaxVersion = cfg.ProtocolMaxVersion
		}

		// Go with the strictest ClientAuth type
		if cfg.ClientAuth > config.ClientAuth {
			config.ClientAuth = cfg.ClientAuth
		}
	}

	// Is TLS disabled? If so, we're done here.
	// By now, we know that all configs agree
	// whether it is or not, so we can just look
	// at the first one.
	if len(configs) == 0 || !configs[0].Enabled {
		return nil, nil
	}

	// Default cipher suites
	if len(config.CipherSuites) == 0 {
		config.CipherSuites = defaultCiphers
	}

	// For security, ensure TLS_FALLBACK_SCSV is always included first
	if len(config.CipherSuites) == 0 || config.CipherSuites[0] != tls.TLS_FALLBACK_SCSV {
		config.CipherSuites = append([]uint16{tls.TLS_FALLBACK_SCSV}, config.CipherSuites...)
	}

	// Set up client authentication if enabled
	if config.ClientAuth != tls.NoClientCert {
		pool := x509.NewCertPool()
		clientCertsAdded := make(map[string]struct{})
		for _, cfg := range configs {
			for _, caFile := range cfg.ClientCerts {
				// don't add cert to pool more than once
				if _, ok := clientCertsAdded[caFile]; ok {
					continue
				}
				clientCertsAdded[caFile] = struct{}{}

				// Any client with a certificate from this CA will be allowed to connect
				caCrt, err := ioutil.ReadFile(caFile)
				if err != nil {
					return nil, err
				}

				if !pool.AppendCertsFromPEM(caCrt) {
					return nil, fmt.Errorf("error loading client certificate '%s': no certificates were successfully parsed", caFile)
				}
			}
		}
		config.ClientCAs = pool
	}

	// Associate the GetCertificate callback, or almost nothing we just did will work
	config.GetCertificate = configMap.GetCertificate

	return config, nil
}
485856
func (c *Configurator) IncomingRPCConfig() *tls.Config {
	c.log("IncomingRPCConfig")
	config := c.commonTLSConfig(c.verifyIncomingRPC())
	config.GetConfigForClient = func(*tls.ClientHelloInfo) (*tls.Config, error) {
		return c.IncomingRPCConfig(), nil
	}
	return config
}
1154920
func (c *MutableTLSCreds) Config() *tls.Config {
	c.Lock()
	defer c.Unlock()

	return c.config
}
5807
func RegisterTLSConfig(key string, config *tls.Config) error {
	tlsConfigLock.Lock()
	if tlsConfigRegistry == nil {
		tlsConfigRegistry = make(map[string]*tls.Config)
	}

	tlsConfigRegistry[key] = config
	tlsConfigLock.Unlock()
	return nil
}
385567
func (c *Config) OutgoingTLSConfig() (*tls.Config, error) {
	// If VerifyServerHostname is true, that implies VerifyOutgoing
	if c.VerifyServerHostname {
		c.VerifyOutgoing = true
	}
	if !c.VerifyOutgoing {
		return nil, nil
	}
	// Create the tlsConfig
	tlsConfig := &tls.Config{
		RootCAs:                  x509.NewCertPool(),
		InsecureSkipVerify:       true,
		CipherSuites:             c.CipherSuites,
		MinVersion:               c.MinVersion,
		PreferServerCipherSuites: c.PreferServerCipherSuites,
	}
	if c.VerifyServerHostname {
		tlsConfig.InsecureSkipVerify = false
	}

	// Ensure we have a CA if VerifyOutgoing is set
	if c.VerifyOutgoing && c.CAFile == "" {
		return nil, fmt.Errorf("VerifyOutgoing set, and no CA certificate provided!")
	}

	// Parse the CA cert if any
	err := c.AppendCA(tlsConfig.RootCAs)
	if err != nil {
		return nil, err
	}

	cert, err := c.LoadKeyPair()
	if err != nil {
		return nil, err
	} else if cert != nil {
		tlsConfig.GetCertificate = c.KeyLoader.GetOutgoingCertificate
		tlsConfig.GetClientCertificate = c.KeyLoader.GetClientCertificate
	}

	return tlsConfig, nil
}
1153631
func (c *Client) reloadTLSConnections(newConfig *nconfig.TLSConfig) error {
	var tlsWrap tlsutil.RegionWrapper
	if newConfig != nil && newConfig.EnableRPC {
		tw, err := tlsutil.NewTLSConfiguration(newConfig, true, true)
		if err != nil {
			return err
		}

		twWrap, err := tw.OutgoingTLSWrapper()
		if err != nil {
			return err
		}
		tlsWrap = twWrap
	}

	// Store the new tls wrapper.
	c.tlsWrapLock.Lock()
	c.tlsWrap = tlsWrap
	c.tlsWrapLock.Unlock()

	// Keep the client configuration up to date as we use configuration values to
	// decide on what type of connections to accept
	c.configLock.Lock()
	c.config.TLSConfig = newConfig
	c.configLock.Unlock()

	c.connPool.ReloadTLS(tlsWrap)

	return nil
}
1280020
func (s *Security) ToTLSConfig() (*tls.Config, error) {
	var tlsConfig *tls.Config
	if len(s.ClusterSSLCA) != 0 {
		var certificates = make([]tls.Certificate, 0)
		if len(s.ClusterSSLCert) != 0 && len(s.ClusterSSLKey) != 0 {
			// Load the client certificates from disk
			certificate, err := tls.LoadX509KeyPair(s.ClusterSSLCert, s.ClusterSSLKey)
			if err != nil {
				return nil, errors.Errorf("could not load client key pair: %s", err)
			}
			certificates = append(certificates, certificate)
		}

		// Create a certificate pool from the certificate authority
		certPool := x509.NewCertPool()
		ca, err := ioutil.ReadFile(s.ClusterSSLCA)
		if err != nil {
			return nil, errors.Errorf("could not read ca certificate: %s", err)
		}

		// Append the certificates from the CA
		if !certPool.AppendCertsFromPEM(ca) {
			return nil, errors.New("failed to append ca certs")
		}

		tlsConfig = &tls.Config{
			Certificates: certificates,
			RootCAs:      certPool,
		}
	}

	return tlsConfig, nil
}
11652
func NewTLSConfig(s *TLSSettings) (*tls.Config, error) {
	// Parse min and max TLS versions
	var min, max uint16
	var err error

	if s.MinVersion == "" {
		min = tls.VersionTLS10
	} else if min, err = ParseTLSVersion(s.MinVersion); err != nil {
		return nil, err
	}

	if s.MaxVersion == "" {
		max = tls.VersionTLS12
	} else if max, err = ParseTLSVersion(s.MaxVersion); err != nil {
		return nil, err
	}

	var css []uint16
	if len(s.CipherSuites) == 0 {
		css = []uint16{
			tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
			tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,

			tls.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA,
			tls.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,

			tls.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA,
			tls.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA,

			tls.TLS_RSA_WITH_AES_256_CBC_SHA,
			tls.TLS_RSA_WITH_AES_128_CBC_SHA,
		}
	} else {
		css = make([]uint16, len(s.CipherSuites))
		for i, suite := range s.CipherSuites {
			cs, err := ParseCipherSuite(suite)
			if err != nil {
				return nil, err
			}
			css[i] = cs
		}
	}

	var cache tls.ClientSessionCache
	if !s.SessionTicketsDisabled {
		cache, err = NewTLSSessionCache(&s.SessionCache)
		if err != nil {
			return nil, err
		}
	}

	return &tls.Config{
		MinVersion: min,
		MaxVersion: max,

		SessionTicketsDisabled: s.SessionTicketsDisabled,
		ClientSessionCache:     cache,

		PreferServerCipherSuites: s.PreferServerCipherSuites,
		CipherSuites:             css,

		InsecureSkipVerify: s.InsecureSkipVerify,
	}, nil
}
45442
func (c *Config) OutgoingTLSWrapper() (RegionWrapper, error) {
	// Get the TLS config
	tlsConfig, err := c.OutgoingTLSConfig()
	if err != nil {
		return nil, err
	}

	// Check if TLS is not enabled
	if tlsConfig == nil {
		return nil, nil
	}

	// Generate the wrapper based on hostname verification
	if c.VerifyServerHostname {
		wrapper := func(region string, conn net.Conn) (net.Conn, error) {
			conf := tlsConfig.Clone()
			conf.ServerName = "server." + region + ".nomad"
			return WrapTLSClient(conn, conf)
		}
		return wrapper, nil
	} else {
		wrapper := func(dc string, c net.Conn) (net.Conn, error) {
			return WrapTLSClient(c, tlsConfig)
		}
		return wrapper, nil
	}

}
1324759
func (cl *Listener) TLSConfig(ctx context.Context) (*tls.Config, error) {
	serverLookup := func(clientHello *tls.ClientHelloInfo) (*tls.Certificate, error) {
		cl.logger.Debug("performing server cert lookup")

		cl.l.RLock()
		defer cl.l.RUnlock()
		for _, v := range clientHello.SupportedProtos {
			if handler, ok := cl.handlers[v]; ok {
				return handler.ServerLookup(ctx, clientHello)
			}
		}

		cl.logger.Warn("no TLS certs found for ALPN", "ALPN", clientHello.SupportedProtos)
		return nil, errors.New("unsupported protocol")
	}

	clientLookup := func(requestInfo *tls.CertificateRequestInfo) (*tls.Certificate, error) {
		cl.logger.Debug("performing client cert lookup")

		cl.l.RLock()
		defer cl.l.RUnlock()
		for _, client := range cl.clients {
			cert, err := client.ClientLookup(ctx, requestInfo)
			if err == nil && cert != nil {
				return cert, nil
			}
		}

		cl.logger.Warn("no client information found")
		return nil, errors.New("no client cert found")
	}

	serverConfigLookup := func(clientHello *tls.ClientHelloInfo) (*tls.Config, error) {
		caPool := x509.NewCertPool()

		ret := &tls.Config{
			ClientAuth:           tls.RequireAndVerifyClientCert,
			GetCertificate:       serverLookup,
			GetClientCertificate: clientLookup,
			MinVersion:           tls.VersionTLS12,
			RootCAs:              caPool,
			ClientCAs:            caPool,
			NextProtos:           clientHello.SupportedProtos,
			CipherSuites:         cl.cipherSuites,
		}

		cl.l.RLock()
		defer cl.l.RUnlock()
		for _, v := range clientHello.SupportedProtos {
			if handler, ok := cl.handlers[v]; ok {
				ca, err := handler.CALookup(ctx)
				if err != nil {
					return nil, err
				}

				caPool.AddCert(ca)
				return ret, nil
			}
		}

		cl.logger.Warn("no TLS config found for ALPN", "ALPN", clientHello.SupportedProtos)
		return nil, errors.New("unsupported protocol")
	}

	return &tls.Config{
		ClientAuth:           tls.RequireAndVerifyClientCert,
		GetCertificate:       serverLookup,
		GetClientCertificate: clientLookup,
		GetConfigForClient:   serverConfigLookup,
		MinVersion:           tls.VersionTLS12,
		CipherSuites:         cl.cipherSuites,
	}, nil
}
1347746
func (p *Proxy) SetTLSConfig(cfg *tls.Config) {
	p.transport.SetTLSConfig(cfg)
	p.health.SetTLSConfig(cfg)
}
1126933
func (c *Client) getTLSConfig() (*tls.Config, error) {
	transport, err := c.getTransport()
	if err != nil {
		return nil, err
	}
	if transport.TLSClientConfig == nil {
		transport.TLSClientConfig = &tls.Config{}
	}
	return transport.TLSClientConfig, nil
}
790640
func createTLSConfig() (tlsConfig *tls.Config, err error) {
	tlsConfig = &tls.Config{}

	// use stronger TLS settings if enabled
	// TODO: perhaps this should be default setting
	if os.Getenv(envTLSHardening) == "true" {
		tlsConfig.InsecureSkipVerify = false
		tlsConfig.MinVersion = hardenedMinVersion
		tlsConfig.CipherSuites = hardenedCiphers
		tlsConfig.CurvePreferences = hardenedCurvePreferences
	}

	// load possible TLS CA chain(s) for server certificate validation
	// starting with an empty pool
	tlsConfig.RootCAs = x509.NewCertPool()

	// load system root CA trust store by default, unless configured not to
	// if we cannot, then it's fatal.
	// NOTE that we ONLY fail if SystemCertPool returns an error,
	// not if our system trust store is empty or doesn't exist!
	if os.Getenv(envDisableSystemRoots) != "true" {
		tlsConfig.RootCAs, err = x509.SystemCertPool()
		if err != nil {
			return
		}
	}

	// load custom certificates specified by configuration:
	// we expect a comma separated list of certificate file paths
	// if we fail to load a certificate, we should treat this to be fatal
	// as the user may not wish to send logs through an untrusted TLS connection
	// also note that each file specified above can contain one or more certificates
	// and we also _DO NOT_ check if they are CA certificates (in case of self-signed)
	if certsEnv := os.Getenv(envCaCerts); certsEnv != "" {
		certFilePaths := strings.Split(certsEnv, ",")
		for _, certFilePath := range certFilePaths {
			// each pem file may contain more than one certficate
			var certBytes []byte
			certBytes, err = ioutil.ReadFile(certFilePath)
			if err != nil {
				return
			}
			if !tlsConfig.RootCAs.AppendCertsFromPEM(certBytes) {
				err = fmt.Errorf("failed to load CA certificate(s): %s", certFilePath)
				return
			}
		}
	}

	// load a client certificate and key if enabled
	// we should only attempt this if BOTH cert and key are defined
	clientCertFilePath := os.Getenv(envClientCert)
	clientKeyFilePath := os.Getenv(envClientKey)
	if clientCertFilePath != "" && clientKeyFilePath != "" {
		var clientCert tls.Certificate
		clientCert, err = tls.LoadX509KeyPair(clientCertFilePath, clientKeyFilePath)
		// we should fail if unable to load the keypair since the user intended mutual authentication
		if err != nil {
			return
		}
		// according to TLS spec (RFC 5246 appendix F.1.1) the certificate message
		// must provide a valid certificate chain leading to an acceptable certificate authority.
		// We will make this optional; the client cert pem file can contain more than one certificate
		tlsConfig.Certificates = []tls.Certificate{clientCert}
	}
	return
}
896867
func GenTLSConfig(tc *TLSConfigOpts) (*tls.Config, error) {

	// Now load in cert and private key
	cert, err := tls.LoadX509KeyPair(tc.CertFile, tc.KeyFile)
	if err != nil {
		return nil, fmt.Errorf("error parsing X509 certificate/key pair: %v", err)
	}
	cert.Leaf, err = x509.ParseCertificate(cert.Certificate[0])
	if err != nil {
		return nil, fmt.Errorf("error parsing certificate: %v", err)
	}

	// Create the tls.Config from our options.
	// We will determine the cipher suites that we prefer.
	// FIXME(dlc) change if ARM based.
	config := tls.Config{
		MinVersion:               tls.VersionTLS12,
		CipherSuites:             tc.Ciphers,
		PreferServerCipherSuites: true,
		CurvePreferences:         tc.CurvePreferences,
		Certificates:             []tls.Certificate{cert},
		InsecureSkipVerify:       tc.Insecure,
	}

	// Require client certificates as needed
	if tc.Verify {
		config.ClientAuth = tls.RequireAndVerifyClientCert
	}
	// Add in CAs if applicable.
	if tc.CaFile != "" {
		rootPEM, err := ioutil.ReadFile(tc.CaFile)
		if err != nil || rootPEM == nil {
			return nil, err
		}
		pool := x509.NewCertPool()
		ok := pool.AppendCertsFromPEM(rootPEM)
		if !ok {
			return nil, fmt.Errorf("failed to parse root ca certificate")
		}
		config.ClientCAs = pool
	}

	return &config, nil
}
580429
func NewTLSConfig(certPath, keyPath, caPath string) (*tls.Config, error) {
	cert, err := tls.LoadX509KeyPair(certPath, keyPath)
	if err != nil {
		return nil, fmt.Errorf("could not load TLS cert: %s", err)
	}

	roots, err := loadRoots(caPath)
	if err != nil {
		return nil, err
	}

	return &tls.Config{Certificates: []tls.Certificate{cert}, RootCAs: roots}, nil
}