// TLS matches HTTPS requests.
//
// By default, any TLS handshake packet is matched. An optional whitelist
// of versions can be passed in to restrict the matcher, for example:
//  TLS(tls.VersionTLS11, tls.VersionTLS12)
480237
func TLS(versions ...int) Matcher {
	if len(versions) == 0 {
		versions = []int{
			tls.VersionSSL30,
			tls.VersionTLS10,
			tls.VersionTLS11,
			tls.VersionTLS12,
		}
	}
	prefixes := [][]byte{}
	for _, v := range versions {
		prefixes = append(prefixes, []byte{22, byte(v >> 8 & 0xff), byte(v & 0xff)})
	}
	return prefixByteMatcher(prefixes...)
}
1011837
func (n *Network) listTLSCACertificates() []string {
	fileName2Path := make(map[string]string)
	filepath.Walk(filepath.Join(n.RootDir, "crypto"), func(path string, info os.FileInfo, err error) error {
		// File starts with "tlsca" and has "-cert.pem" in it
		if strings.HasPrefix(info.Name(), "tlsca") && strings.Contains(info.Name(), "-cert.pem") {
			fileName2Path[info.Name()] = path
		}
		return nil
	})

	var tlsCACertificates []string
	for _, path := range fileName2Path {
		tlsCACertificates = append(tlsCACertificates, path)
	}
	return tlsCACertificates
}
793225
func matchProtocols(protocols []Protocol, caps []Cap, rw MsgReadWriter) map[string]*protoRW {
	sort.Sort(capsByNameAndVersion(caps))
	offset := baseProtocolLength
	result := make(map[string]*protoRW)

outer:
	for _, cap := range caps {
		for _, proto := range protocols {
			if proto.Name == cap.Name && proto.Version == cap.Version {
				// If an old protocol version matched, revert it
				if old := result[cap.Name]; old != nil {
					offset -= old.Length
				}
				// Assign the new match
				result[cap.Name] = &protoRW{Protocol: proto, offset: offset, in: make(chan Msg), w: rw}
				offset += proto.Length

				continue outer
			}
		}
	}
	return result
}
445839
func TLSDial(ctx context.Context, dial DialWithContextFunc, network, addr string, tlsConfig *tls.Config) (*tls.Conn, error) {
	if tlsConfig == nil {
		tlsConfig = &tls.Config{}
	}

	plainConn, err := dial(ctx, network, addr)
	if err != nil {
		return nil, trace.Wrap(err)
	}

	colonPos := strings.LastIndex(addr, ":")
	if colonPos == -1 {
		colonPos = len(addr)
	}
	hostname := addr[:colonPos]

	// If no ServerName is set, infer the ServerName
	// from the hostname we're connecting to.
	if tlsConfig.ServerName == "" {
		// Make a copy to avoid polluting argument or default.
		c := tlsConfig.Clone()
		c.ServerName = hostname
		tlsConfig = c
	}

	conn := tls.Client(plainConn, tlsConfig)
	errC := make(chan error, 1)
	go func() {
		err := conn.Handshake()
		errC <- err
	}()

	select {
	case err := <-errC:
		if err != nil {
			plainConn.Close()
			return nil, trace.Wrap(err)
		}
	case <-ctx.Done():
		plainConn.Close()
		return nil, trace.BadParameter("tls handshake has been cancelled due to timeout")
	}

	if tlsConfig.InsecureSkipVerify {
		return conn, nil
	}

	if err := conn.VerifyHostname(tlsConfig.ServerName); err != nil {
		plainConn.Close()
		return nil, trace.Wrap(err)
	}

	return conn, nil
}
799161
func TLSConfigFor(config *Config) (*tls.Config, error) {
	cfg, err := config.TransportConfig()
	if err != nil {
		return nil, err
	}
	return transport.TLSConfigFor(cfg)
}
355415
func (sc *serverCreds) ServerHandshake(rawConn net.Conn) (net.Conn, credentials.AuthInfo, error) {
	conn := tls.Server(rawConn, sc.serverConfig)
	if err := conn.Handshake(); err != nil {
		if sc.logger != nil {
			sc.logger.With("remote address",
				conn.RemoteAddr().String()).Errorf("TLS handshake failed with error %s", err)
		}
		return nil, nil, err
	}
	return conn, credentials.TLSInfo{State: conn.ConnectionState()}, nil
}
1228197
func MatchHeaders(req *http.Request, ereq *Request) (bool, error) {
	for key, value := range ereq.Header {
		var err error
		var match bool

		for _, field := range req.Header[key] {
			match, err = regexp.MatchString(value[0], field)
			if err != nil {
				return false, err
			}
			if match {
				break
			}
		}

		if !match {
			return false, nil
		}
	}
	return true, nil
}
603447
func (tr *Transport) TLSServerConfig() (*tls.Config, error) {
	cert, err := tr.getCertificate()
	if err != nil {
		return nil, err
	}

	return &tls.Config{
		Certificates: []tls.Certificate{cert},
		CipherSuites: core.CipherSuites,
		MinVersion:   tls.VersionTLS12,
	}, nil
}
515623
func TLSCertInfo(cert *tls.Certificate) string {
	x509cert, err := x509.ParseCertificate(cert.Certificate[0])
	if err != nil {
		return err.Error()
	}
	return CertInfo(x509cert)
}
1037517
func (l *tlsHelloListener) Accept() (net.Conn, error) {
	conn, err := l.Listener.Accept()
	if err != nil {
		return nil, err
	}
	buf := bufpool.Get().(*bytes.Buffer)
	buf.Reset()
	helloConn := &clientHelloConn{Conn: conn, listener: l, buf: buf}
	return tls.Server(helloConn, l.config), nil
}
238877
func (s *SimpleRule) Match(r *http.Request) bool {
	matches := regexpMatches(s.Regexp, "/", r.URL.Path)
	if s.Negate {
		return len(matches) == 0
	}
	return len(matches) > 0
}
1248284
func (fw *Framework) TLSConfig() (tlsc *tls.Config, err error) {
	return fw.security.TLSConfig()
}
744157
func (s *ServerTLS) Serve(l net.Listener) error {
	s.m.Lock()

	if s.tlsConfig != nil {
		l = tls.NewListener(l, s.tlsConfig)
	}

	// Only fill out the TCP server for this one.
	s.server[tcp] = &dns.Server{Listener: l, Net: "tcp-tls", Handler: dns.HandlerFunc(func(w dns.ResponseWriter, r *dns.Msg) {
		ctx := context.Background()
		s.ServeDNS(ctx, w, r)
	})}
	s.m.Unlock()

	return s.server[tcp].ActivateAndServe()
}
1362889
func (t TypeMatcher) Match(r *Request) bool {
	return r.Header.Type == Type(t)
}
48127
func TlsConfigWithHttp2Enabled(config *tls.Config) (*tls.Config, error) {
	// mostly based on http2 code in the standards library.
	if config.CipherSuites != nil {
		// If they already provided a CipherSuite list, return
		// an error if it has a bad order or is missing
		// ECDHE_RSA_WITH_AES_128_GCM_SHA256.
		const requiredCipher = tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256
		haveRequired := false
		for _, cs := range config.CipherSuites {
			if cs == requiredCipher {
				haveRequired = true
			}
		}
		if !haveRequired {
			return nil, fmt.Errorf("http2: TLSConfig.CipherSuites is missing HTTP/2-required TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256")
		}
	}

	config.PreferServerCipherSuites = true

	haveNPN := false
	for _, p := range config.NextProtos {
		if p == "h2" {
			haveNPN = true
			break
		}
	}
	if !haveNPN {
		config.NextProtos = append(config.NextProtos, "h2")
	}
	config.NextProtos = append(config.NextProtos, "h2-14")
	// make sure http 1.1 is *after* all of the other ones.
	config.NextProtos = append(config.NextProtos, "http/1.1")
	return config, nil
}
390324
func Secure(tls ...*tls.Config) Option {
	return func(o *Options) error {
		o.Secure = true
		// Use of variadic just simplifies testing scenarios. We only take the first one.
		if len(tls) > 1 {
			return ErrMultipleTLSConfigs
		}
		if len(tls) == 1 {
			o.TLSConfig = tls[0]
		}
		return nil
	}
}
418356
func TLSListeners(tlsConfig *tls.Config) ([]net.Listener, error) {
	listeners, err := Listeners()

	if listeners == nil || err != nil {
		return nil, err
	}

	if tlsConfig != nil && err == nil {
		for i, l := range listeners {
			// Activate TLS only for TCP sockets
			if l.Addr().Network() == "tcp" {
				listeners[i] = tls.NewListener(l, tlsConfig)
			}
		}
	}

	return listeners, err
}