Documentation
¶
Overview ¶
Copyright (c) 2025 The BFE Authors.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
Copyright (c) 2025 The BFE Authors.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
Package bfe_tls partially implements TLS 1.2, as specified in RFC 5246.
Index ¶
- Constants
- func CheckSuiteECDHE(id uint16) bool
- func CheckSuitePseudo(suite uint16) bool
- func CheckSuiteRSA(id uint16) bool
- func CipherSuiteText(suite uint16) string
- func CipherSuiteTextForOpenSSL(suite uint16) string
- func CurveForCurveID(id CurveID) (elliptic.Curve, bool)
- func FilterCiphers(cipherSuites []uint16, filter CipherFilter) ([]uint16, []uint16)
- func IsEcdheCipherSuite(suite interface{}) bool
- func Listen(network, laddr string, config *Config) (net.Listener, error)
- func NewListener(inner net.Listener, config *Config) net.Listener
- func OcspTimeRangeCheck(parse *ocsp.Response) bool
- func PKCS5Padding(ciphertext []byte, blockSize int) []byte
- func SetHelloRandomFormat(format int)
- func SetKeyPairLoader(loader KeyPairLoader)
- func SetTlsMultiCertificate(m MultiCertificate)
- func UpdateListener(ln net.Listener, conf *Config) error
- func VersionText(ver uint16) string
- func VersionTextForOpenSSL(ver uint16) string
- type CRLPool
- type Certificate
- type CipherFilter
- type ClientAuthType
- type ClientSessionCache
- type ClientSessionState
- type Config
- type Conn
- func (c *Conn) Close() error
- func (c *Conn) ConnectionState() ConnectionState
- func (c *Conn) GetNetConn() net.Conn
- func (c *Conn) GetServerName() string
- func (c *Conn) GetVip() net.IP
- func (c *Conn) Handshake() error
- func (c *Conn) LocalAddr() net.Addr
- func (c *Conn) OCSPResponse() []byte
- func (c *Conn) Read(b []byte) (n int, err error)
- func (c *Conn) RemoteAddr() net.Addr
- func (c *Conn) SetConnParam(param ConnParam)
- func (c *Conn) SetDeadline(t time.Time) error
- func (c *Conn) SetReadDeadline(t time.Time) error
- func (c *Conn) SetWriteDeadline(t time.Time) error
- func (c *Conn) VerifyHostname(host string) error
- func (c *Conn) Write(b []byte) (int, error)
- type ConnParam
- type ConnectionState
- type CurveID
- type KeyPairLoader
- type MultiCertificate
- type NextProtoConf
- type Rule
- type ServerRule
- type ServerSessionCache
- type TestPemNameEnmu
- type TlsState
- type VerifyCertHook
- type VerifyPeerCertHooks
Examples ¶
Constants ¶
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 "renegotiation 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
const ( VersionSSL30 = 0x0300 VersionTLS10 = 0x0301 VersionTLS11 = 0x0302 VersionTLS12 = 0x0303 )
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 CheckSuitePseudo ¶
func CheckSuiteRSA ¶
CheckSuiteRSA checks whether cipher suite using RSA key argreement
func CipherSuiteText ¶
func FilterCiphers ¶
func FilterCiphers(cipherSuites []uint16, filter CipherFilter) ([]uint16, []uint16)
func IsEcdheCipherSuite ¶
func IsEcdheCipherSuite(suite interface{}) bool
func Listen ¶
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 ¶
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 ¶
OcspTimeRangeCheck check ocsp time update range
func PKCS5Padding ¶
func SetHelloRandomFormat ¶
func SetHelloRandomFormat(format int)
func SetKeyPairLoader ¶
func SetKeyPairLoader(loader KeyPairLoader)
func SetTlsMultiCertificate ¶
func SetTlsMultiCertificate(m MultiCertificate)
func UpdateListener ¶
UpdateListener updates 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 specify a new tls.config when called
func VersionText ¶
func VersionTextForOpenSSL ¶
Types ¶
type CRLPool ¶
type CRLPool struct {
// contains filtered or unexported fields
}
func NewCRLPool ¶
func NewCRLPool() *CRLPool
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 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
// VerifyPeerCertificate, if not nil, is called after normal
// certificate verification by either a TLS client or server. It
// receives the raw ASN.1 certificates provided by the peer and also
// any verified chains that normal processing found. If it returns a
// non-nil error, the handshake is aborted and that error results.
//
// If normal verification fails then the handshake will abort before
// considering this callback. If normal verification is disabled by
// setting InsecureSkipVerify, or (for a server) when ClientAuth is
// RequestClientCert or RequireAnyClientCert, then this callback will
// be considered but the verifiedChains argument will always be nil.
VerifyPeerCertificate func(rawCerts [][]byte, verifiedChains [][]*x509.Certificate) error
// 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.
type Conn ¶
type Conn struct {
// contains filtered or unexported fields
}
A Conn represents a secured connection. It implements the net.Conn interface.
func Client ¶
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 ¶
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 ¶
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 ¶
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) ConnectionState ¶
func (c *Conn) ConnectionState() ConnectionState
ConnectionState returns basic TLS details about the connection.
func (*Conn) GetNetConn ¶
GetNetConn returns the underlying connection.
func (*Conn) GetServerName ¶
GetServerName returns server name indicated by the client, if any.
func (*Conn) Handshake ¶
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) OCSPResponse ¶
OCSPResponse returns the stapled OCSP response from the TLS server, if any. (Only valid for client connections.)
func (*Conn) Read ¶
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 ¶
RemoteAddr returns the remote network address.
func (*Conn) SetConnParam ¶
func (*Conn) SetDeadline ¶
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 ¶
SetReadDeadline sets the read deadline on the underlying connection. A zero value for t means Read will not time out.
func (*Conn) SetWriteDeadline ¶
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 ¶
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.
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
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 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 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 TestPemNameEnmu ¶ added in v1.8.0
type TestPemNameEnmu string
const ( BFE_R_CA_CRT TestPemNameEnmu = "bfe_r_ca.crt" BFE_I_CA_CRT TestPemNameEnmu = "bfe_i_ca.crt" I_BFE_DEV_PRV TestPemNameEnmu = "i_bfe_dev_prv.pem" I_BFE_DEV_CRT TestPemNameEnmu = "i_bfe_dev.crt" I_CN_FOOBAR_ORG_PRV TestPemNameEnmu = "i_cn_foobar.org_prv.pem" I_CN_FOOBAR_ORG_CRT TestPemNameEnmu = "i_cn_foobar.org.crt" R_BFE_DEV_PRV TestPemNameEnmu = "r_bfe_dev_prv.pem" R_BFE_DEV_CRT TestPemNameEnmu = "r_bfe_dev.crt" R_SAN_EXAMPLE_ORG_PRV TestPemNameEnmu = "r_san_example.org_prv.pem" R_SAN_EXAMPLE_ORG_CRT TestPemNameEnmu = "r_san_example.org.crt" )
* Prefix Explanation
- I: Intermediate certificate issued
- R: Root certificate issued
Suffix Explanation
- CRT: x509 certificate
- PRV: Private key
func (TestPemNameEnmu) Bytes ¶ added in v1.8.0
func (t TestPemNameEnmu) Bytes() []byte
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
TlsHandshakeSslv2NotSupport *metrics.Counter
TlsHandshakeOcspTimeErr *metrics.Counter
TlsStatusRequestExtCount *metrics.Counter
TlsHandshakeZeroData *metrics.Counter
}
func GetTlsState ¶
func GetTlsState() *TlsState
type VerifyCertHook ¶ added in v1.8.0
type VerifyPeerCertHooks ¶ added in v1.8.0
type VerifyPeerCertHooks struct {
InsecureSkipVerify bool
Host string
CAs *x509.CertPool
// contains filtered or unexported fields
}
func NewVerifyPeerCertHooks ¶ added in v1.8.0
func NewVerifyPeerCertHooks(insecureSkipVerify bool, host string, cas *x509.CertPool) *VerifyPeerCertHooks
NewVerifyPeerCertHooks : build hooks for bef_tls.Config.VerifyPeerCertificate and wait callback
func (*VerifyPeerCertHooks) AppendHook ¶ added in v1.8.0
func (p *VerifyPeerCertHooks) AppendHook(fn VerifyCertHook) *VerifyPeerCertHooks
func (*VerifyPeerCertHooks) DisableDefaultHooks ¶ added in v1.8.0
func (p *VerifyPeerCertHooks) DisableDefaultHooks() *VerifyPeerCertHooks
func (*VerifyPeerCertHooks) Ready ¶ added in v1.8.0
func (p *VerifyPeerCertHooks) Ready() func(rawCerts [][]byte, verifiedChains [][]*x509.Certificate) error
Ready : ready to wait tls callback