bfe_tls

package
v1.2.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jun 21, 2021 License: Apache-2.0 Imports: 37 Imported by: 1

Documentation

Overview

Package tls partially implements TLS 1.2, as specified in RFC 5246.

Index

Examples

Constants

View Source
const (
	TLS_RSA_WITH_RC4_128_SHA                      uint16 = 0x0005
	TLS_RSA_WITH_3DES_EDE_CBC_SHA                 uint16 = 0x000a
	TLS_RSA_WITH_AES_128_CBC_SHA                  uint16 = 0x002f
	TLS_RSA_WITH_AES_256_CBC_SHA                  uint16 = 0x0035
	TLS_ECDHE_ECDSA_WITH_RC4_128_SHA              uint16 = 0xc007
	TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA          uint16 = 0xc009
	TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA          uint16 = 0xc00a
	TLS_ECDHE_RSA_WITH_RC4_128_SHA                uint16 = 0xc011
	TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA           uint16 = 0xc012
	TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA            uint16 = 0xc013
	TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA            uint16 = 0xc014
	TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256         uint16 = 0xc02f
	TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256       uint16 = 0xc02b
	TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256   uint16 = 0xcca8
	TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256 uint16 = 0xcca9
	TLS_RSA_WITH_SM4_SM3                          uint16 = 0xe019

	// TLS_FALLBACK_SCSV isn't a standard cipher suite but an indicator
	// that the client is doing version fallback. See
	// https://tools.ietf.org/html/draft-ietf-tls-downgrade-scsv-00.
	TLS_FALLBACK_SCSV uint16 = 0x5600

	// TLS_EMPTY_RENEGOTIATION_INFO_SCSV isn't a true cipher suite, it has
	// the same semantics as an empty "renegotation info" extension. See
	// https://tools.ietf.org/html/rfc5746#section-3.3
	TLS_EMPTY_RENEGOTIATION_INFO_SCSV = 0x00ff
)

A list of the possible cipher suite ids. Taken from http://www.iana.org/assignments/tls-parameters/tls-parameters.xml

View Source
const (
	VersionSSL30 = 0x0300
	VersionTLS10 = 0x0301
	VersionTLS11 = 0x0302
	VersionTLS12 = 0x0303
)
View Source
const (
	GradeAPlus = "A+"
	GradeA     = "A"
	GradeB     = "B"
	GradeC     = "C"
)

the following grade (A, B, C) is defined by www.ssllabs.com Grade A+: no ssl3, tls1.0, tls1.1 && no RC4 ciphers Grade A: no ssl3 && no RC4 ciphers Grade B: ssl3 is ok only with RC4 cipher, or

modern version(>=tls10) with no RC4 cipher

Grade C: ssl3 is ok only with RC4 cipher

Variables

This section is empty.

Functions

func CheckSuiteECDHE

func CheckSuiteECDHE(id uint16) bool

func CheckSuitePseudo

func CheckSuitePseudo(suite uint16) bool

func CheckSuiteRSA

func CheckSuiteRSA(id uint16) bool

CheckSuiteRSA checks whether cipher suite using RSA key argreement

func CipherSuiteText

func CipherSuiteText(suite uint16) string

func CipherSuiteTextForOpenSSL

func CipherSuiteTextForOpenSSL(suite uint16) string

func CurveForCurveID

func CurveForCurveID(id CurveID) (elliptic.Curve, bool)

func FilterCiphers

func FilterCiphers(cipherSuites []uint16, filter CipherFilter) ([]uint16, []uint16)

func IsEcdheCipherSuite

func IsEcdheCipherSuite(suite interface{}) bool

func Listen

func Listen(network, laddr string, config *Config) (net.Listener, error)

Listen creates a TLS listener accepting connections on the given network address using net.Listen. The configuration config must be non-nil and must have at least one certificate.

func NewListener

func NewListener(inner net.Listener, config *Config) net.Listener

NewListener creates a Listener which accepts connections from an inner Listener and wraps each connection with Server. The configuration config must be non-nil and must have at least one certificate.

func OcspTimeRangeCheck

func OcspTimeRangeCheck(parse *ocsp.Response) bool

OcspTimeRangeCheck check ocsp time update range

func PKCS5Padding

func PKCS5Padding(ciphertext []byte, blockSize int) []byte

func SetHelloRandomFormat

func SetHelloRandomFormat(format int)

func SetKeyPairLoader

func SetKeyPairLoader(loader KeyPairLoader)

func SetTlsMultiCertificate

func SetTlsMultiCertificate(m MultiCertificate)

func UpdateListener

func UpdateListener(ln net.Listener, conf *Config) error

UpdateListener - update config for tls listener * * Params: * - ln : a tls listener * - conf: a tls config * * Return: * - error * * Note: * 1. tls.listener will not modify tls.Config and just pass it * to accepted Connection. * 2. tls.Conn will just read tls.Config during handshake and * data transfer phase * 3. MUST specified a new tls.config when called

func VersionText

func VersionText(ver uint16) string

func VersionTextForOpenSSL

func VersionTextForOpenSSL(ver uint16) string

Types

type CRLPool

type CRLPool struct {
	// contains filtered or unexported fields
}

func NewCRLPool

func NewCRLPool() *CRLPool

func (*CRLPool) AddCRL

func (p *CRLPool) AddCRL(crl *pkix.CertificateList) error

func (*CRLPool) CheckCertRevoked

func (p *CRLPool) CheckCertRevoked(cert *x509.Certificate) bool

type Certificate

type Certificate struct {
	Certificate [][]byte
	PrivateKey  crypto.PrivateKey // supported types: *rsa.PrivateKey, *ecdsa.PrivateKey
	// OCSPStaple contains an optional OCSP response which will be served
	// to clients that request it.
	OCSPStaple []byte
	OCSPParse  *ocsp.Response // OCSPParse specify the details of ocsp response
	// Leaf is the parsed form of the leaf certificate, which may be
	// initialized using x509.ParseCertificate to reduce per-handshake
	// processing for TLS clients doing client authentication. If nil, the
	// leaf certificate will be parsed as needed.
	Leaf *x509.Certificate
	// contains filtered or unexported fields
}

A Certificate is a chain of one or more certificates, leaf first.

func LoadX509KeyPair

func LoadX509KeyPair(certFile, keyFile string) (cert Certificate, err error)

LoadX509KeyPair reads and parses a public/private key pair from a pair of files. The files must contain PEM encoded data.

func X509KeyPair

func X509KeyPair(certPEMBlock, keyPEMBlock []byte) (cert Certificate, err error)

X509KeyPair parses a public/private key pair from a pair of PEM encoded data.

type CipherFilter

type CipherFilter func(id uint16) bool

type ClientAuthType

type ClientAuthType int

ClientAuthType declares the policy the server will follow for TLS Client Authentication.

const (
	NoClientCert ClientAuthType = iota
	RequestClientCert
	RequireAnyClientCert
	VerifyClientCertIfGiven
	RequireAndVerifyClientCert
)

type ClientSessionCache

type ClientSessionCache interface {
	// Get searches for a ClientSessionState associated with the given key.
	// On return, ok is true if one was found.
	Get(sessionKey string) (session *ClientSessionState, ok bool)

	// Put adds the ClientSessionState to the cache with the given key.
	Put(sessionKey string, cs *ClientSessionState)
}

ClientSessionCache is a cache of ClientSessionState objects that can be used by a client to resume a TLS session with a given server. ClientSessionCache implementations should expect to be called concurrently from different goroutines.

func NewLRUClientSessionCache

func NewLRUClientSessionCache(capacity int) ClientSessionCache

NewLRUClientSessionCache returns a ClientSessionCache with the given capacity that uses an LRU strategy. If capacity is < 1, a default capacity is used instead.

type ClientSessionState

type ClientSessionState struct {
	// contains filtered or unexported fields
}

ClientSessionState contains the state needed by clients to resume TLS sessions.

type Config

type Config struct {
	// Rand provides the source of entropy for nonces and RSA blinding.
	// If Rand is nil, TLS uses the cryptographic random reader in package
	// crypto/rand.
	// The Reader must be safe for use by multiple goroutines.
	Rand io.Reader

	// Time returns the current time as the number of seconds since the epoch.
	// If Time is nil, TLS uses time.Now.
	Time func() time.Time

	// Certificates contains one or more certificate chains
	// to present to the other side of the connection.
	// Server configurations must include at least one certificate.
	Certificates []Certificate

	// NameToCertificate maps from a certificate name to an element of
	// Certificates. Note that a certificate name can be of the form
	// '*.example.com' and so doesn't have to be a domain name as such.
	// See Config.BuildNameToCertificate
	// The nil value causes the first element of Certificates to be used
	// for all connections.
	NameToCertificate map[string]*Certificate

	// default multiply certificates policy for tls server
	MultiCert MultiCertificate

	// RootCAs defines the set of root certificate authorities
	// that clients use when verifying server certificates.
	// If RootCAs is nil, TLS uses the host's root CA set.
	RootCAs *x509.CertPool

	// NextProtos is a list of supported, application level protocols.
	NextProtos []string

	// ServerName is used to verify the hostname on the returned
	// certificates unless InsecureSkipVerify is given. It is also included
	// in the client's handshake to support virtual hosting.
	ServerName string

	// ClientAuth determines the server's global policy for
	// TLS Client Authentication. The default is NoClientCert.
	ClientAuth ClientAuthType

	// ClientCAs defines the set of root certificate authorities
	// that servers use if required to verify a client certificate
	// by the policy in ClientAuth.
	ClientCAs *x509.CertPool

	// InsecureSkipVerify controls whether a client verifies the
	// server's certificate chain and host name.
	// If InsecureSkipVerify is true, TLS accepts any certificate
	// presented by the server and any host name in that certificate.
	// In this mode, TLS is susceptible to man-in-the-middle attacks.
	// This should be used only for testing.
	InsecureSkipVerify bool

	// CipherSuites is a list of supported cipher suites. If CipherSuites
	// is nil, TLS uses a list of suites supported by the implementation.
	CipherSuites []uint16

	// Priority of cipher suites in server side. If PreferServerCipherSuites
	// is false, CipherSuitesPriority should be ignored during cipher suite
	// negotiation
	CipherSuitesPriority []uint16

	// PreferServerCipherSuites controls whether the server selects the
	// client's most preferred ciphersuite, or the server's most preferred
	// ciphersuite. If true then the server's preference, as expressed in
	// the order of elements in CipherSuites, is used.
	PreferServerCipherSuites bool

	// here prohibit poodle attack by allow RC4 cipher only used with ssl3.0
	Ssl3PoodleProofed bool

	// SessionTicketsDisabled may be set to true to disable session ticket
	// (resumption) support.
	SessionTicketsDisabled bool

	// SessionTicketKey is used by TLS servers to provide session
	// resumption. See RFC 5077. If zero, it will be filled with
	// random data before the first server handshake.
	//
	// If multiple servers are terminating connections for the same host
	// they should all have the same SessionTicketKey. If the
	// SessionTicketKey leaks, previously recorded and future TLS
	// connections using that key are compromised.
	SessionTicketKey [32]byte

	// SessionTicketKeyName is used as an identifier for SessionTicketKey
	// in SessionTicket
	SessionTicketKeyName [16]byte

	// SessionCache is a cache of ClientSessionState entries for TLS session
	// resumption.
	ClientSessionCache ClientSessionCache

	// SessionCache is a cache of sessionState entries for TLS session
	// resumption.
	ServerSessionCache ServerSessionCache

	// SessionCacheDisabled may be set to true to disable session cache
	// (resumption) support.
	SessionCacheDisabled bool

	// MinVersion contains the minimum SSL/TLS version that is acceptable.
	// If zero, then SSLv3 is taken as the minimum.
	MinVersion uint16

	// MaxVersion contains the maximum SSL/TLS version that is acceptable.
	// If zero, then the maximum version supported by this package is used,
	// which is currently TLS 1.2.
	MaxVersion uint16

	// CurvePreferences contains the elliptic curves that will be used in
	// an ECDHE handshake, in preference order. If empty, the default will
	// be used.
	CurvePreferences []CurveID

	// Support SSLv2 ClientHello for backward compatibility with ancient
	// TLS-capable clients.
	EnableSslv2ClientHello bool

	// customized config for server side
	ServerRule ServerRule
	// contains filtered or unexported fields
}

A Config structure is used to configure a TLS client or server. After one has been passed to a TLS function it must not be modified. A Config may be reused; the tls package will also not modify it.

func (*Config) BuildNameToCertificate

func (c *Config) BuildNameToCertificate()

BuildNameToCertificate parses c.Certificates and builds c.NameToCertificate from the CommonName and SubjectAlternateName fields of each of the leaf certificates.

func (*Config) Clone

func (c *Config) Clone() *Config

Clone returns a shallow clone of c. It is safe to clone a Config that is being used concurrently by a TLS client or server.

type Conn

type Conn struct {
	// contains filtered or unexported fields
}

A Conn represents a secured connection. It implements the net.Conn interface.

func Client

func Client(conn net.Conn, config *Config) *Conn

Client returns a new TLS client side connection using conn as the underlying transport. The config cannot be nil: users must set either ServerName or InsecureSkipVerify in the config.

func Dial

func Dial(network, addr string, config *Config) (*Conn, error)

Dial connects to the given network address using net.Dial and then initiates a TLS handshake, returning the resulting TLS connection. Dial interprets a nil configuration as equivalent to the zero configuration; see the documentation of Config for the defaults.

Example
// Copyright 2013 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package main

import (
	"bufio"
	"crypto/tls"
	"crypto/x509"
	"encoding/hex"
	"errors"
	"flag"
	"fmt"
	"io"
	"io/ioutil"
	"net"
	"strconv"
	"strings"
	"sync"
)

// TLS reference tests run a connection against a reference implementation
// (OpenSSL) of TLS and record the bytes of the resulting connection. The Go
// code, during a test, is configured with deterministic randomness and so the
// reference test can be reproduced exactly in the future.
//
// In order to save everyone who wishes to run the tests from needing the
// reference implementation installed, the reference connections are saved in
// files in the testdata directory. Thus running the tests involves nothing
// external, but creating and updating them requires the reference
// implementation.
//
// Tests can be updated by running them with the -update flag. This will cause
// the test files. Generally one should combine the -update flag with -test.run
// to updated a specific test. Since the reference implementation will always
// generate fresh random numbers, large parts of the reference connection will
// always change.

var update = flag.Bool("update", false, "update golden files on disk")

// recordingConn is a net.Conn that records the traffic that passes through it.
// WriteTo can be used to produce output that can be later be loaded with
// ParseTestData.
type recordingConn struct {
	net.Conn
	sync.Mutex
	flows   [][]byte
	reading bool
}

func (r *recordingConn) Read(b []byte) (n int, err error) {
	if n, err = r.Conn.Read(b); n == 0 {
		return
	}
	b = b[:n]

	r.Lock()
	defer r.Unlock()

	if l := len(r.flows); l == 0 || !r.reading {
		buf := make([]byte, len(b))
		copy(buf, b)
		r.flows = append(r.flows, buf)
	} else {
		r.flows[l-1] = append(r.flows[l-1], b[:n]...)
	}
	r.reading = true
	return
}

func (r *recordingConn) Write(b []byte) (n int, err error) {
	if n, err = r.Conn.Write(b); n == 0 {
		return
	}
	b = b[:n]

	r.Lock()
	defer r.Unlock()

	if l := len(r.flows); l == 0 || r.reading {
		buf := make([]byte, len(b))
		copy(buf, b)
		r.flows = append(r.flows, buf)
	} else {
		r.flows[l-1] = append(r.flows[l-1], b[:n]...)
	}
	r.reading = false
	return
}

// WriteTo writes Go source code to w that contains the recorded traffic.
func (r *recordingConn) WriteTo(w io.Writer) (int64, error) {
	// TLS always starts with a client to server flow.
	clientToServer := true
	var written int64

	for i, flow := range r.flows {
		source, dest := "client", "server"
		if !clientToServer {
			source, dest = dest, source
		}
		n, err := fmt.Fprintf(w, ">>> Flow %d (%s to %s)\n", i+1, source, dest)
		written += int64(n)
		if err != nil {
			return written, err
		}
		dumper := hex.Dumper(w)
		n, err = dumper.Write(flow)
		written += int64(n)
		if err != nil {
			return written, err
		}
		err = dumper.Close()
		if err != nil {
			return written, err
		}
		clientToServer = !clientToServer
	}
	return written, nil
}

func parseTestData(r io.Reader) (flows [][]byte, err error) {
	var currentFlow []byte

	scanner := bufio.NewScanner(r)
	for scanner.Scan() {
		line := scanner.Text()
		// If the line starts with ">>> " then it marks the beginning
		// of a new flow.
		if strings.HasPrefix(line, ">>> ") {
			if len(currentFlow) > 0 || len(flows) > 0 {
				flows = append(flows, currentFlow)
				currentFlow = nil
			}
			continue
		}

		// Otherwise the line is a line of hex dump that looks like:
		// 00000170  fc f5 06 bf (...)  |.....X{&?......!|
		// (Some bytes have been omitted from the middle section.)

		if i := strings.IndexByte(line, ' '); i >= 0 {
			line = line[i:]
		} else {
			return nil, errors.New("invalid test data")
		}

		if i := strings.IndexByte(line, '|'); i >= 0 {
			line = line[:i]
		} else {
			return nil, errors.New("invalid test data")
		}

		hexBytes := strings.Fields(line)
		for _, hexByte := range hexBytes {
			val, err := strconv.ParseUint(hexByte, 16, 8)
			if err != nil {
				return nil, errors.New("invalid hex byte in test data: " + err.Error())
			}
			currentFlow = append(currentFlow, byte(val))
		}
	}

	if len(currentFlow) > 0 {
		flows = append(flows, currentFlow)
	}

	return flows, nil
}

// tempFile creates a temp file containing contents and returns its path.
func tempFile(contents string) string {
	file, err := ioutil.TempFile("", "go-tls-test")
	if err != nil {
		panic("failed to create temp file: " + err.Error())
	}
	path := file.Name()
	file.WriteString(contents)
	file.Close()
	return path
}

func main() {
	// Connecting with a custom root-certificate set.

	const rootPEM = `
-----BEGIN CERTIFICATE-----
MIIEBDCCAuygAwIBAgIDAjppMA0GCSqGSIb3DQEBBQUAMEIxCzAJBgNVBAYTAlVT
MRYwFAYDVQQKEw1HZW9UcnVzdCBJbmMuMRswGQYDVQQDExJHZW9UcnVzdCBHbG9i
YWwgQ0EwHhcNMTMwNDA1MTUxNTU1WhcNMTUwNDA0MTUxNTU1WjBJMQswCQYDVQQG
EwJVUzETMBEGA1UEChMKR29vZ2xlIEluYzElMCMGA1UEAxMcR29vZ2xlIEludGVy
bmV0IEF1dGhvcml0eSBHMjCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEB
AJwqBHdc2FCROgajguDYUEi8iT/xGXAaiEZ+4I/F8YnOIe5a/mENtzJEiaB0C1NP
VaTOgmKV7utZX8bhBYASxF6UP7xbSDj0U/ck5vuR6RXEz/RTDfRK/J9U3n2+oGtv
h8DQUB8oMANA2ghzUWx//zo8pzcGjr1LEQTrfSTe5vn8MXH7lNVg8y5Kr0LSy+rE
ahqyzFPdFUuLH8gZYR/Nnag+YyuENWllhMgZxUYi+FOVvuOAShDGKuy6lyARxzmZ
EASg8GF6lSWMTlJ14rbtCMoU/M4iarNOz0YDl5cDfsCx3nuvRTPPuj5xt970JSXC
DTWJnZ37DhF5iR43xa+OcmkCAwEAAaOB+zCB+DAfBgNVHSMEGDAWgBTAephojYn7
qwVkDBF9qn1luMrMTjAdBgNVHQ4EFgQUSt0GFhu89mi1dvWBtrtiGrpagS8wEgYD
VR0TAQH/BAgwBgEB/wIBADAOBgNVHQ8BAf8EBAMCAQYwOgYDVR0fBDMwMTAvoC2g
K4YpaHR0cDovL2NybC5nZW90cnVzdC5jb20vY3Jscy9ndGdsb2JhbC5jcmwwPQYI
KwYBBQUHAQEEMTAvMC0GCCsGAQUFBzABhiFodHRwOi8vZ3RnbG9iYWwtb2NzcC5n
ZW90cnVzdC5jb20wFwYDVR0gBBAwDjAMBgorBgEEAdZ5AgUBMA0GCSqGSIb3DQEB
BQUAA4IBAQA21waAESetKhSbOHezI6B1WLuxfoNCunLaHtiONgaX4PCVOzf9G0JY
/iLIa704XtE7JW4S615ndkZAkNoUyHgN7ZVm2o6Gb4ChulYylYbc3GrKBIxbf/a/
zG+FA1jDaFETzf3I93k9mTXwVqO94FntT0QJo544evZG0R0SnU++0ED8Vf4GXjza
HFa9llF7b1cq26KqltyMdMKVvvBulRP/F/A8rLIQjcxz++iPAsbw+zOzlTvjwsto
WHPbqCRiOwY1nQ2pM714A5AuTHhdUDqB1O6gyHA43LL5Z/qHQF1hwFGPa4NrzQU6
yuGnBXj8ytqU0CwIPX4WecigUCAkVDNx
-----END CERTIFICATE-----`

	// First, create the set of root certificates. For this example we only
	// have one. It's also possible to omit this in order to use the
	// default root set of the current operating system.
	roots := x509.NewCertPool()
	ok := roots.AppendCertsFromPEM([]byte(rootPEM))
	if !ok {
		panic("failed to parse root certificate")
	}

	conn, err := tls.Dial("tcp", "mail.google.com:443", &tls.Config{
		RootCAs: roots,
	})
	if err != nil {
		panic("failed to connect: " + err.Error())
	}
	conn.Close()
}
Output:

func DialWithDialer

func DialWithDialer(dialer *net.Dialer, network, addr string, config *Config) (*Conn, error)

DialWithDialer connects to the given network address using dialer.Dial and then initiates a TLS handshake, returning the resulting TLS connection. Any timeout or deadline given in the dialer apply to connection and TLS handshake as a whole.

DialWithDialer interprets a nil configuration as equivalent to the zero configuration; see the documentation of Config for the defaults.

func Server

func Server(conn net.Conn, config *Config) *Conn

Server returns a new TLS server side connection using conn as the underlying transport. The configuration config must be non-nil and must have at least one certificate.

func (*Conn) Close

func (c *Conn) Close() error

Close closes the connection.

func (*Conn) ConnectionState

func (c *Conn) ConnectionState() ConnectionState

ConnectionState returns basic TLS details about the connection.

func (*Conn) GetNetConn

func (c *Conn) GetNetConn() net.Conn

GetNetConn returns the underlying connection.

func (*Conn) GetServerName

func (c *Conn) GetServerName() string

GetServerName returns server name indicated by the client, if any.

func (*Conn) GetVip

func (c *Conn) GetVip() net.IP

GetVip return the vip for underlying connection.

func (*Conn) Handshake

func (c *Conn) Handshake() error

Handshake runs the client or server handshake protocol if it has not yet been run. Most uses of this package need not call Handshake explicitly: the first Read or Write will call it automatically.

func (*Conn) LocalAddr

func (c *Conn) LocalAddr() net.Addr

LocalAddr returns the local network address.

func (*Conn) OCSPResponse

func (c *Conn) OCSPResponse() []byte

OCSPResponse returns the stapled OCSP response from the TLS server, if any. (Only valid for client connections.)

func (*Conn) Read

func (c *Conn) Read(b []byte) (n int, err error)

Read can be made to time out and return a net.Error with Timeout() == true after a fixed time limit; see SetDeadline and SetReadDeadline.

func (*Conn) RemoteAddr

func (c *Conn) RemoteAddr() net.Addr

RemoteAddr returns the remote network address.

func (*Conn) SetConnParam

func (c *Conn) SetConnParam(param ConnParam)

func (*Conn) SetDeadline

func (c *Conn) SetDeadline(t time.Time) error

SetDeadline sets the read and write deadlines associated with the connection. A zero value for t means Read and Write will not time out. After a Write has timed out, the TLS state is corrupt and all future writes will return the same error.

func (*Conn) SetReadDeadline

func (c *Conn) SetReadDeadline(t time.Time) error

SetReadDeadline sets the read deadline on the underlying connection. A zero value for t means Read will not time out.

func (*Conn) SetWriteDeadline

func (c *Conn) SetWriteDeadline(t time.Time) error

SetWriteDeadline sets the write deadline on the underlying connection. A zero value for t means Write will not time out. After a Write has timed out, the TLS state is corrupt and all future writes will return the same error.

func (*Conn) VerifyHostname

func (c *Conn) VerifyHostname(host string) error

VerifyHostname checks that the peer certificate chain is valid for connecting to host. If so, it returns nil; if not, it returns an error describing the problem.

func (*Conn) Write

func (c *Conn) Write(b []byte) (int, error)

Write writes data to the connection.

type ConnParam

type ConnParam interface {
	// Get virtual ip for current conn
	GetVip() net.IP
}

type ConnectionState

type ConnectionState struct {
	Version                    uint16                // TLS version used by the connection (e.g. VersionTLS12)
	HandshakeComplete          bool                  // TLS handshake is complete
	DidResume                  bool                  // connection resumes a previous TLS connection
	CipherSuite                uint16                // cipher suite in use (TLS_RSA_WITH_RC4_128_SHA, ...)
	OcspStaple                 bool                  // use ocsp staple (in server side)
	NegotiatedProtocolIsMutual bool                  // negotiated protocol was advertised by server
	NegotiatedProtocol         string                // negotiated next protocol (from Config.NextProtos)
	ServerName                 string                // server name requested by client, if any (server side only)
	HandshakeTime              time.Duration         // TLS handshake time (in server side)
	PeerCertificates           []*x509.Certificate   // certificate chain presented by remote peer
	VerifiedChains             [][]*x509.Certificate // verified chains built from PeerCertificates
	ClientRandom               []byte                // random in client hello
	ServerRandom               []byte                // random in server hello
	MasterSecret               []byte                // master secret used by the connection
	ClientCiphers              []uint16              // ciphers supported by client
	ClientAuth                 bool                  // enable TLS Client Authentication
	ClientCAName               string                // TLS client CA name
	JA3Raw                     string                // JA3 fingerprint string for TLS Client
	JA3Hash                    string                // JA3 fingerprint hash for TLS Client
}

ConnectionState records basic TLS details about the connection.

type CurveID

type CurveID uint16

CurveID is the type of a TLS identifier for an elliptic curve. See http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-8

const (
	CurveP256 CurveID = 23
	CurveP384 CurveID = 24
	CurveP521 CurveID = 25
)

type KeyPairLoader

type KeyPairLoader interface {
	LoadX509KeyPair(certFile, keyFile string) (cert Certificate, err error)
}

type MultiCertificate

type MultiCertificate interface {
	// Get certificate for the given conn
	Get(c *Conn) *Certificate
}

type NextProtoConf

type NextProtoConf interface {
	// Get next protos for the given conn
	Get(c *Conn) []string
}

type Rule

type Rule struct {
	// NextProtos is a list of supported, application level protocols.
	NextProtos NextProtoConf

	// Security Grade
	Grade string

	// enable TLS Client Authentication
	ClientAuth bool

	// client CA certificate
	ClientCAs *x509.CertPool

	// client CA name
	ClientCAName string

	// client CRL pool
	ClientCRLPool *CRLPool

	// enable Chacha20-poly1305 cipher suites
	Chacha20 bool

	// enable Dynamic TLS record size
	DynamicRecord bool
}

Rule represents customized tls config for specific conn in server side

type ServerRule

type ServerRule interface {
	// Get tls rule for the given conn
	Get(c *Conn) *Rule
}

type ServerSessionCache

type ServerSessionCache interface {
	// Get searches for a sessionState associated with the given key.
	// On return, ok is true if one was found.
	Get(sessionKey string) (sessionState []byte, ok bool)

	// Put adds the sessionState to the cache with the given key.
	Put(sessionKey string, sessionState []byte) error
}

type TlsState

type TlsState struct {
	TlsHandshakeReadClientHelloErr        *metrics.Counter
	TlsHandshakeFullAll                   *metrics.Counter
	TlsHandshakeFullSucc                  *metrics.Counter
	TlsHandshakeResumeAll                 *metrics.Counter
	TlsHandshakeResumeSucc                *metrics.Counter
	TlsHandshakeCheckResumeSessionTicket  *metrics.Counter
	TlsHandshakeShouldResumeSessionTicket *metrics.Counter
	TlsHandshakeCheckResumeSessionCache   *metrics.Counter
	TlsHandshakeShouldResumeSessionCache  *metrics.Counter
	TlsHandshakeAcceptSslv2ClientHello    *metrics.Counter
	TlsHandshakeAcceptEcdheWithoutExt     *metrics.Counter
	TlsHandshakeNoSharedCipherSuite       *metrics.Counter
	TlsHandshakeSslv2NotSupport           *metrics.Counter
	TlsHandshakeOcspTimeErr               *metrics.Counter
	TlsStatusRequestExtCount              *metrics.Counter
	TlsHandshakeZeroData                  *metrics.Counter
}

func GetTlsState

func GetTlsState() *TlsState

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL