github.com/ooni/psiphon/tunnel-core@v0.0.0-20230105123940-fe12a24c96ee/oovendor/qtls-go1-16/common.go (about)

     1  // Copyright 2009 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package qtls
     6  
     7  import (
     8  	"bytes"
     9  	"container/list"
    10  	"crypto"
    11  	"crypto/ecdsa"
    12  	"crypto/ed25519"
    13  	"crypto/elliptic"
    14  	"crypto/rand"
    15  	"crypto/rsa"
    16  	"crypto/sha512"
    17  	"crypto/tls"
    18  	"crypto/x509"
    19  	"errors"
    20  	"fmt"
    21  	"io"
    22  	"net"
    23  	"runtime"
    24  	"sort"
    25  	"strings"
    26  	"sync"
    27  	"time"
    28  
    29  	"github.com/ooni/psiphon/tunnel-core/psiphon/common/prng"
    30  	"golang.org/x/sys/cpu"
    31  )
    32  
    33  const (
    34  	VersionTLS10 = 0x0301
    35  	VersionTLS11 = 0x0302
    36  	VersionTLS12 = 0x0303
    37  	VersionTLS13 = 0x0304
    38  
    39  	// Deprecated: SSLv3 is cryptographically broken, and is no longer
    40  	// supported by this package. See golang.org/issue/32716.
    41  	VersionSSL30 = 0x0300
    42  )
    43  
    44  const (
    45  	maxPlaintext       = 16384        // maximum plaintext payload length
    46  	maxCiphertext      = 16384 + 2048 // maximum ciphertext payload length
    47  	maxCiphertextTLS13 = 16384 + 256  // maximum ciphertext length in TLS 1.3
    48  	recordHeaderLen    = 5            // record header length
    49  	maxHandshake       = 65536        // maximum handshake we support (protocol max is 16 MB)
    50  	maxUselessRecords  = 16           // maximum number of consecutive non-advancing records
    51  )
    52  
    53  // TLS record types.
    54  type recordType uint8
    55  
    56  const (
    57  	recordTypeChangeCipherSpec recordType = 20
    58  	recordTypeAlert            recordType = 21
    59  	recordTypeHandshake        recordType = 22
    60  	recordTypeApplicationData  recordType = 23
    61  )
    62  
    63  // TLS handshake message types.
    64  const (
    65  	typeHelloRequest        uint8 = 0
    66  	typeClientHello         uint8 = 1
    67  	typeServerHello         uint8 = 2
    68  	typeNewSessionTicket    uint8 = 4
    69  	typeEndOfEarlyData      uint8 = 5
    70  	typeEncryptedExtensions uint8 = 8
    71  	typeCertificate         uint8 = 11
    72  	typeServerKeyExchange   uint8 = 12
    73  	typeCertificateRequest  uint8 = 13
    74  	typeServerHelloDone     uint8 = 14
    75  	typeCertificateVerify   uint8 = 15
    76  	typeClientKeyExchange   uint8 = 16
    77  	typeFinished            uint8 = 20
    78  	typeCertificateStatus   uint8 = 22
    79  	typeKeyUpdate           uint8 = 24
    80  	typeNextProtocol        uint8 = 67  // Not IANA assigned
    81  	typeMessageHash         uint8 = 254 // synthetic message
    82  )
    83  
    84  // TLS compression types.
    85  const (
    86  	compressionNone uint8 = 0
    87  )
    88  
    89  type Extension struct {
    90  	Type uint16
    91  	Data []byte
    92  }
    93  
    94  // TLS extension numbers
    95  const (
    96  	extensionServerName              uint16 = 0
    97  	extensionStatusRequest           uint16 = 5
    98  	extensionSupportedCurves         uint16 = 10 // supported_groups in TLS 1.3, see RFC 8446, Section 4.2.7
    99  	extensionSupportedPoints         uint16 = 11
   100  	extensionSignatureAlgorithms     uint16 = 13
   101  	extensionALPN                    uint16 = 16
   102  	extensionSCT                     uint16 = 18
   103  	extensionSessionTicket           uint16 = 35
   104  	extensionPreSharedKey            uint16 = 41
   105  	extensionEarlyData               uint16 = 42
   106  	extensionSupportedVersions       uint16 = 43
   107  	extensionCookie                  uint16 = 44
   108  	extensionPSKModes                uint16 = 45
   109  	extensionCertificateAuthorities  uint16 = 47
   110  	extensionSignatureAlgorithmsCert uint16 = 50
   111  	extensionKeyShare                uint16 = 51
   112  	extensionRenegotiationInfo       uint16 = 0xff01
   113  )
   114  
   115  // TLS signaling cipher suite values
   116  const (
   117  	scsvRenegotiation uint16 = 0x00ff
   118  )
   119  
   120  type EncryptionLevel uint8
   121  
   122  const (
   123  	EncryptionHandshake EncryptionLevel = iota
   124  	Encryption0RTT
   125  	EncryptionApplication
   126  )
   127  
   128  // CurveID is a tls.CurveID
   129  type CurveID = tls.CurveID
   130  
   131  const (
   132  	CurveP256 CurveID = 23
   133  	CurveP384 CurveID = 24
   134  	CurveP521 CurveID = 25
   135  	X25519    CurveID = 29
   136  )
   137  
   138  // TLS 1.3 Key Share. See RFC 8446, Section 4.2.8.
   139  type keyShare struct {
   140  	group CurveID
   141  	data  []byte
   142  }
   143  
   144  // TLS 1.3 PSK Key Exchange Modes. See RFC 8446, Section 4.2.9.
   145  const (
   146  	pskModePlain uint8 = 0
   147  	pskModeDHE   uint8 = 1
   148  )
   149  
   150  // TLS 1.3 PSK Identity. Can be a Session Ticket, or a reference to a saved
   151  // session. See RFC 8446, Section 4.2.11.
   152  type pskIdentity struct {
   153  	label               []byte
   154  	obfuscatedTicketAge uint32
   155  }
   156  
   157  // TLS Elliptic Curve Point Formats
   158  // https://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-9
   159  const (
   160  	pointFormatUncompressed uint8 = 0
   161  )
   162  
   163  // TLS CertificateStatusType (RFC 3546)
   164  const (
   165  	statusTypeOCSP uint8 = 1
   166  )
   167  
   168  // Certificate types (for certificateRequestMsg)
   169  const (
   170  	certTypeRSASign   = 1
   171  	certTypeECDSASign = 64 // ECDSA or EdDSA keys, see RFC 8422, Section 3.
   172  )
   173  
   174  // Signature algorithms (for internal signaling use). Starting at 225 to avoid overlap with
   175  // TLS 1.2 codepoints (RFC 5246, Appendix A.4.1), with which these have nothing to do.
   176  const (
   177  	signaturePKCS1v15 uint8 = iota + 225
   178  	signatureRSAPSS
   179  	signatureECDSA
   180  	signatureEd25519
   181  )
   182  
   183  // directSigning is a standard Hash value that signals that no pre-hashing
   184  // should be performed, and that the input should be signed directly. It is the
   185  // hash function associated with the Ed25519 signature scheme.
   186  var directSigning crypto.Hash = 0
   187  
   188  // supportedSignatureAlgorithms contains the signature and hash algorithms that
   189  // the code advertises as supported in a TLS 1.2+ ClientHello and in a TLS 1.2+
   190  // CertificateRequest. The two fields are merged to match with TLS 1.3.
   191  // Note that in TLS 1.2, the ECDSA algorithms are not constrained to P-256, etc.
   192  var supportedSignatureAlgorithms = []SignatureScheme{
   193  	PSSWithSHA256,
   194  	ECDSAWithP256AndSHA256,
   195  	Ed25519,
   196  	PSSWithSHA384,
   197  	PSSWithSHA512,
   198  	PKCS1WithSHA256,
   199  	PKCS1WithSHA384,
   200  	PKCS1WithSHA512,
   201  	ECDSAWithP384AndSHA384,
   202  	ECDSAWithP521AndSHA512,
   203  	PKCS1WithSHA1,
   204  	ECDSAWithSHA1,
   205  }
   206  
   207  // helloRetryRequestRandom is set as the Random value of a ServerHello
   208  // to signal that the message is actually a HelloRetryRequest.
   209  var helloRetryRequestRandom = []byte{ // See RFC 8446, Section 4.1.3.
   210  	0xCF, 0x21, 0xAD, 0x74, 0xE5, 0x9A, 0x61, 0x11,
   211  	0xBE, 0x1D, 0x8C, 0x02, 0x1E, 0x65, 0xB8, 0x91,
   212  	0xC2, 0xA2, 0x11, 0x16, 0x7A, 0xBB, 0x8C, 0x5E,
   213  	0x07, 0x9E, 0x09, 0xE2, 0xC8, 0xA8, 0x33, 0x9C,
   214  }
   215  
   216  const (
   217  	// downgradeCanaryTLS12 or downgradeCanaryTLS11 is embedded in the server
   218  	// random as a downgrade protection if the server would be capable of
   219  	// negotiating a higher version. See RFC 8446, Section 4.1.3.
   220  	downgradeCanaryTLS12 = "DOWNGRD\x01"
   221  	downgradeCanaryTLS11 = "DOWNGRD\x00"
   222  )
   223  
   224  // testingOnlyForceDowngradeCanary is set in tests to force the server side to
   225  // include downgrade canaries even if it's using its highers supported version.
   226  var testingOnlyForceDowngradeCanary bool
   227  
   228  type ConnectionState = tls.ConnectionState
   229  
   230  // ConnectionState records basic TLS details about the connection.
   231  type connectionState struct {
   232  	// Version is the TLS version used by the connection (e.g. VersionTLS12).
   233  	Version uint16
   234  
   235  	// HandshakeComplete is true if the handshake has concluded.
   236  	HandshakeComplete bool
   237  
   238  	// DidResume is true if this connection was successfully resumed from a
   239  	// previous session with a session ticket or similar mechanism.
   240  	DidResume bool
   241  
   242  	// CipherSuite is the cipher suite negotiated for the connection (e.g.
   243  	// TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, TLS_AES_128_GCM_SHA256).
   244  	CipherSuite uint16
   245  
   246  	// NegotiatedProtocol is the application protocol negotiated with ALPN.
   247  	NegotiatedProtocol string
   248  
   249  	// NegotiatedProtocolIsMutual used to indicate a mutual NPN negotiation.
   250  	//
   251  	// Deprecated: this value is always true.
   252  	NegotiatedProtocolIsMutual bool
   253  
   254  	// ServerName is the value of the Server Name Indication extension sent by
   255  	// the client. It's available both on the server and on the client side.
   256  	ServerName string
   257  
   258  	// PeerCertificates are the parsed certificates sent by the peer, in the
   259  	// order in which they were sent. The first element is the leaf certificate
   260  	// that the connection is verified against.
   261  	//
   262  	// On the client side, it can't be empty. On the server side, it can be
   263  	// empty if Config.ClientAuth is not RequireAnyClientCert or
   264  	// RequireAndVerifyClientCert.
   265  	PeerCertificates []*x509.Certificate
   266  
   267  	// VerifiedChains is a list of one or more chains where the first element is
   268  	// PeerCertificates[0] and the last element is from Config.RootCAs (on the
   269  	// client side) or Config.ClientCAs (on the server side).
   270  	//
   271  	// On the client side, it's set if Config.InsecureSkipVerify is false. On
   272  	// the server side, it's set if Config.ClientAuth is VerifyClientCertIfGiven
   273  	// (and the peer provided a certificate) or RequireAndVerifyClientCert.
   274  	VerifiedChains [][]*x509.Certificate
   275  
   276  	// SignedCertificateTimestamps is a list of SCTs provided by the peer
   277  	// through the TLS handshake for the leaf certificate, if any.
   278  	SignedCertificateTimestamps [][]byte
   279  
   280  	// OCSPResponse is a stapled Online Certificate Status Protocol (OCSP)
   281  	// response provided by the peer for the leaf certificate, if any.
   282  	OCSPResponse []byte
   283  
   284  	// TLSUnique contains the "tls-unique" channel binding value (see RFC 5929,
   285  	// Section 3). This value will be nil for TLS 1.3 connections and for all
   286  	// resumed connections.
   287  	//
   288  	// Deprecated: there are conditions in which this value might not be unique
   289  	// to a connection. See the Security Considerations sections of RFC 5705 and
   290  	// RFC 7627, and https://mitls.org/pages/attacks/3SHAKE#channelbindings.
   291  	TLSUnique []byte
   292  
   293  	// ekm is a closure exposed via ExportKeyingMaterial.
   294  	ekm func(label string, context []byte, length int) ([]byte, error)
   295  }
   296  
   297  type ConnectionStateWith0RTT struct {
   298  	ConnectionState
   299  
   300  	Used0RTT bool // true if 0-RTT was both offered and accepted
   301  }
   302  
   303  // ClientAuthType is tls.ClientAuthType
   304  type ClientAuthType = tls.ClientAuthType
   305  
   306  const (
   307  	NoClientCert               = tls.NoClientCert
   308  	RequestClientCert          = tls.RequestClientCert
   309  	RequireAnyClientCert       = tls.RequireAnyClientCert
   310  	VerifyClientCertIfGiven    = tls.VerifyClientCertIfGiven
   311  	RequireAndVerifyClientCert = tls.RequireAndVerifyClientCert
   312  )
   313  
   314  // requiresClientCert reports whether the ClientAuthType requires a client
   315  // certificate to be provided.
   316  func requiresClientCert(c ClientAuthType) bool {
   317  	switch c {
   318  	case RequireAnyClientCert, RequireAndVerifyClientCert:
   319  		return true
   320  	default:
   321  		return false
   322  	}
   323  }
   324  
   325  // ClientSessionState contains the state needed by clients to resume TLS
   326  // sessions.
   327  type ClientSessionState = tls.ClientSessionState
   328  
   329  type clientSessionState struct {
   330  	sessionTicket      []uint8               // Encrypted ticket used for session resumption with server
   331  	vers               uint16                // TLS version negotiated for the session
   332  	cipherSuite        uint16                // Ciphersuite negotiated for the session
   333  	masterSecret       []byte                // Full handshake MasterSecret, or TLS 1.3 resumption_master_secret
   334  	serverCertificates []*x509.Certificate   // Certificate chain presented by the server
   335  	verifiedChains     [][]*x509.Certificate // Certificate chains we built for verification
   336  	receivedAt         time.Time             // When the session ticket was received from the server
   337  	ocspResponse       []byte                // Stapled OCSP response presented by the server
   338  	scts               [][]byte              // SCTs presented by the server
   339  
   340  	// TLS 1.3 fields.
   341  	nonce  []byte    // Ticket nonce sent by the server, to derive PSK
   342  	useBy  time.Time // Expiration of the ticket lifetime as set by the server
   343  	ageAdd uint32    // Random obfuscation factor for sending the ticket age
   344  }
   345  
   346  // ClientSessionCache is a cache of ClientSessionState objects that can be used
   347  // by a client to resume a TLS session with a given server. ClientSessionCache
   348  // implementations should expect to be called concurrently from different
   349  // goroutines. Up to TLS 1.2, only ticket-based resumption is supported, not
   350  // SessionID-based resumption. In TLS 1.3 they were merged into PSK modes, which
   351  // are supported via this interface.
   352  //go:generate sh -c "mockgen -package qtls -destination mock_client_session_cache_test.go github.com/ooni/psiphon/tunnel-core/oovendor/qtls-go1-15 ClientSessionCache"
   353  type ClientSessionCache = tls.ClientSessionCache
   354  
   355  // SignatureScheme is a tls.SignatureScheme
   356  type SignatureScheme = tls.SignatureScheme
   357  
   358  const (
   359  	// RSASSA-PKCS1-v1_5 algorithms.
   360  	PKCS1WithSHA256 SignatureScheme = 0x0401
   361  	PKCS1WithSHA384 SignatureScheme = 0x0501
   362  	PKCS1WithSHA512 SignatureScheme = 0x0601
   363  
   364  	// RSASSA-PSS algorithms with public key OID rsaEncryption.
   365  	PSSWithSHA256 SignatureScheme = 0x0804
   366  	PSSWithSHA384 SignatureScheme = 0x0805
   367  	PSSWithSHA512 SignatureScheme = 0x0806
   368  
   369  	// ECDSA algorithms. Only constrained to a specific curve in TLS 1.3.
   370  	ECDSAWithP256AndSHA256 SignatureScheme = 0x0403
   371  	ECDSAWithP384AndSHA384 SignatureScheme = 0x0503
   372  	ECDSAWithP521AndSHA512 SignatureScheme = 0x0603
   373  
   374  	// EdDSA algorithms.
   375  	Ed25519 SignatureScheme = 0x0807
   376  
   377  	// Legacy signature and hash algorithms for TLS 1.2.
   378  	PKCS1WithSHA1 SignatureScheme = 0x0201
   379  	ECDSAWithSHA1 SignatureScheme = 0x0203
   380  )
   381  
   382  // ClientHelloInfo contains information from a ClientHello message in order to
   383  // guide application logic in the GetCertificate and GetConfigForClient callbacks.
   384  type ClientHelloInfo = tls.ClientHelloInfo
   385  
   386  type clientHelloInfo struct {
   387  	// CipherSuites lists the CipherSuites supported by the client (e.g.
   388  	// TLS_AES_128_GCM_SHA256, TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256).
   389  	CipherSuites []uint16
   390  
   391  	// ServerName indicates the name of the server requested by the client
   392  	// in order to support virtual hosting. ServerName is only set if the
   393  	// client is using SNI (see RFC 4366, Section 3.1).
   394  	ServerName string
   395  
   396  	// SupportedCurves lists the elliptic curves supported by the client.
   397  	// SupportedCurves is set only if the Supported Elliptic Curves
   398  	// Extension is being used (see RFC 4492, Section 5.1.1).
   399  	SupportedCurves []CurveID
   400  
   401  	// SupportedPoints lists the point formats supported by the client.
   402  	// SupportedPoints is set only if the Supported Point Formats Extension
   403  	// is being used (see RFC 4492, Section 5.1.2).
   404  	SupportedPoints []uint8
   405  
   406  	// SignatureSchemes lists the signature and hash schemes that the client
   407  	// is willing to verify. SignatureSchemes is set only if the Signature
   408  	// Algorithms Extension is being used (see RFC 5246, Section 7.4.1.4.1).
   409  	SignatureSchemes []SignatureScheme
   410  
   411  	// SupportedProtos lists the application protocols supported by the client.
   412  	// SupportedProtos is set only if the Application-Layer Protocol
   413  	// Negotiation Extension is being used (see RFC 7301, Section 3.1).
   414  	//
   415  	// Servers can select a protocol by setting Config.NextProtos in a
   416  	// GetConfigForClient return value.
   417  	SupportedProtos []string
   418  
   419  	// SupportedVersions lists the TLS versions supported by the client.
   420  	// For TLS versions less than 1.3, this is extrapolated from the max
   421  	// version advertised by the client, so values other than the greatest
   422  	// might be rejected if used.
   423  	SupportedVersions []uint16
   424  
   425  	// Conn is the underlying net.Conn for the connection. Do not read
   426  	// from, or write to, this connection; that will cause the TLS
   427  	// connection to fail.
   428  	Conn net.Conn
   429  
   430  	// config is embedded by the GetCertificate or GetConfigForClient caller,
   431  	// for use with SupportsCertificate.
   432  	config *Config
   433  }
   434  
   435  // CertificateRequestInfo contains information from a server's
   436  // CertificateRequest message, which is used to demand a certificate and proof
   437  // of control from a client.
   438  type CertificateRequestInfo = tls.CertificateRequestInfo
   439  
   440  type certificateRequestInfo struct {
   441  	// AcceptableCAs contains zero or more, DER-encoded, X.501
   442  	// Distinguished Names. These are the names of root or intermediate CAs
   443  	// that the server wishes the returned certificate to be signed by. An
   444  	// empty slice indicates that the server has no preference.
   445  	AcceptableCAs [][]byte
   446  
   447  	// SignatureSchemes lists the signature schemes that the server is
   448  	// willing to verify.
   449  	SignatureSchemes []SignatureScheme
   450  
   451  	// Version is the TLS version that was negotiated for this connection.
   452  	Version uint16
   453  }
   454  
   455  // RenegotiationSupport enumerates the different levels of support for TLS
   456  // renegotiation. TLS renegotiation is the act of performing subsequent
   457  // handshakes on a connection after the first. This significantly complicates
   458  // the state machine and has been the source of numerous, subtle security
   459  // issues. Initiating a renegotiation is not supported, but support for
   460  // accepting renegotiation requests may be enabled.
   461  //
   462  // Even when enabled, the server may not change its identity between handshakes
   463  // (i.e. the leaf certificate must be the same). Additionally, concurrent
   464  // handshake and application data flow is not permitted so renegotiation can
   465  // only be used with protocols that synchronise with the renegotiation, such as
   466  // HTTPS.
   467  //
   468  // Renegotiation is not defined in TLS 1.3.
   469  type RenegotiationSupport = tls.RenegotiationSupport
   470  
   471  const (
   472  	// RenegotiateNever disables renegotiation.
   473  	RenegotiateNever = tls.RenegotiateNever
   474  
   475  	// RenegotiateOnceAsClient allows a remote server to request
   476  	// renegotiation once per connection.
   477  	RenegotiateOnceAsClient = tls.RenegotiateOnceAsClient
   478  
   479  	// RenegotiateFreelyAsClient allows a remote server to repeatedly
   480  	// request renegotiation.
   481  	RenegotiateFreelyAsClient = tls.RenegotiateFreelyAsClient
   482  )
   483  
   484  // A Config structure is used to configure a TLS client or server.
   485  // After one has been passed to a TLS function it must not be
   486  // modified. A Config may be reused; the tls package will also not
   487  // modify it.
   488  type Config = tls.Config
   489  
   490  type config struct {
   491  	// Rand provides the source of entropy for nonces and RSA blinding.
   492  	// If Rand is nil, TLS uses the cryptographic random reader in package
   493  	// crypto/rand.
   494  	// The Reader must be safe for use by multiple goroutines.
   495  	Rand io.Reader
   496  
   497  	// Time returns the current time as the number of seconds since the epoch.
   498  	// If Time is nil, TLS uses time.Now.
   499  	Time func() time.Time
   500  
   501  	// Certificates contains one or more certificate chains to present to the
   502  	// other side of the connection. The first certificate compatible with the
   503  	// peer's requirements is selected automatically.
   504  	//
   505  	// Server configurations must set one of Certificates, GetCertificate or
   506  	// GetConfigForClient. Clients doing client-authentication may set either
   507  	// Certificates or GetClientCertificate.
   508  	//
   509  	// Note: if there are multiple Certificates, and they don't have the
   510  	// optional field Leaf set, certificate selection will incur a significant
   511  	// per-handshake performance cost.
   512  	Certificates []Certificate
   513  
   514  	// NameToCertificate maps from a certificate name to an element of
   515  	// Certificates. Note that a certificate name can be of the form
   516  	// '*.example.com' and so doesn't have to be a domain name as such.
   517  	//
   518  	// Deprecated: NameToCertificate only allows associating a single
   519  	// certificate with a given name. Leave this field nil to let the library
   520  	// select the first compatible chain from Certificates.
   521  	NameToCertificate map[string]*Certificate
   522  
   523  	// GetCertificate returns a Certificate based on the given
   524  	// ClientHelloInfo. It will only be called if the client supplies SNI
   525  	// information or if Certificates is empty.
   526  	//
   527  	// If GetCertificate is nil or returns nil, then the certificate is
   528  	// retrieved from NameToCertificate. If NameToCertificate is nil, the
   529  	// best element of Certificates will be used.
   530  	GetCertificate func(*ClientHelloInfo) (*Certificate, error)
   531  
   532  	// GetClientCertificate, if not nil, is called when a server requests a
   533  	// certificate from a client. If set, the contents of Certificates will
   534  	// be ignored.
   535  	//
   536  	// If GetClientCertificate returns an error, the handshake will be
   537  	// aborted and that error will be returned. Otherwise
   538  	// GetClientCertificate must return a non-nil Certificate. If
   539  	// Certificate.Certificate is empty then no certificate will be sent to
   540  	// the server. If this is unacceptable to the server then it may abort
   541  	// the handshake.
   542  	//
   543  	// GetClientCertificate may be called multiple times for the same
   544  	// connection if renegotiation occurs or if TLS 1.3 is in use.
   545  	GetClientCertificate func(*CertificateRequestInfo) (*Certificate, error)
   546  
   547  	// GetConfigForClient, if not nil, is called after a ClientHello is
   548  	// received from a client. It may return a non-nil Config in order to
   549  	// change the Config that will be used to handle this connection. If
   550  	// the returned Config is nil, the original Config will be used. The
   551  	// Config returned by this callback may not be subsequently modified.
   552  	//
   553  	// If GetConfigForClient is nil, the Config passed to Server() will be
   554  	// used for all connections.
   555  	//
   556  	// If SessionTicketKey was explicitly set on the returned Config, or if
   557  	// SetSessionTicketKeys was called on the returned Config, those keys will
   558  	// be used. Otherwise, the original Config keys will be used (and possibly
   559  	// rotated if they are automatically managed).
   560  	GetConfigForClient func(*ClientHelloInfo) (*Config, error)
   561  
   562  	// VerifyPeerCertificate, if not nil, is called after normal
   563  	// certificate verification by either a TLS client or server. It
   564  	// receives the raw ASN.1 certificates provided by the peer and also
   565  	// any verified chains that normal processing found. If it returns a
   566  	// non-nil error, the handshake is aborted and that error results.
   567  	//
   568  	// If normal verification fails then the handshake will abort before
   569  	// considering this callback. If normal verification is disabled by
   570  	// setting InsecureSkipVerify, or (for a server) when ClientAuth is
   571  	// RequestClientCert or RequireAnyClientCert, then this callback will
   572  	// be considered but the verifiedChains argument will always be nil.
   573  	VerifyPeerCertificate func(rawCerts [][]byte, verifiedChains [][]*x509.Certificate) error
   574  
   575  	// VerifyConnection, if not nil, is called after normal certificate
   576  	// verification and after VerifyPeerCertificate by either a TLS client
   577  	// or server. If it returns a non-nil error, the handshake is aborted
   578  	// and that error results.
   579  	//
   580  	// If normal verification fails then the handshake will abort before
   581  	// considering this callback. This callback will run for all connections
   582  	// regardless of InsecureSkipVerify or ClientAuth settings.
   583  	VerifyConnection func(ConnectionState) error
   584  
   585  	// RootCAs defines the set of root certificate authorities
   586  	// that clients use when verifying server certificates.
   587  	// If RootCAs is nil, TLS uses the host's root CA set.
   588  	RootCAs *x509.CertPool
   589  
   590  	// NextProtos is a list of supported application level protocols, in
   591  	// order of preference.
   592  	NextProtos []string
   593  
   594  	// ServerName is used to verify the hostname on the returned
   595  	// certificates unless InsecureSkipVerify is given. It is also included
   596  	// in the client's handshake to support virtual hosting unless it is
   597  	// an IP address.
   598  	ServerName string
   599  
   600  	// ClientAuth determines the server's policy for
   601  	// TLS Client Authentication. The default is NoClientCert.
   602  	ClientAuth ClientAuthType
   603  
   604  	// ClientCAs defines the set of root certificate authorities
   605  	// that servers use if required to verify a client certificate
   606  	// by the policy in ClientAuth.
   607  	ClientCAs *x509.CertPool
   608  
   609  	// InsecureSkipVerify controls whether a client verifies the server's
   610  	// certificate chain and host name. If InsecureSkipVerify is true, crypto/tls
   611  	// accepts any certificate presented by the server and any host name in that
   612  	// certificate. In this mode, TLS is susceptible to machine-in-the-middle
   613  	// attacks unless custom verification is used. This should be used only for
   614  	// testing or in combination with VerifyConnection or VerifyPeerCertificate.
   615  	InsecureSkipVerify bool
   616  
   617  	// CipherSuites is a list of supported cipher suites for TLS versions up to
   618  	// TLS 1.2. If CipherSuites is nil, a default list of secure cipher suites
   619  	// is used, with a preference order based on hardware performance. The
   620  	// default cipher suites might change over Go versions. Note that TLS 1.3
   621  	// ciphersuites are not configurable.
   622  	CipherSuites []uint16
   623  
   624  	// PreferServerCipherSuites controls whether the server selects the
   625  	// client's most preferred ciphersuite, or the server's most preferred
   626  	// ciphersuite. If true then the server's preference, as expressed in
   627  	// the order of elements in CipherSuites, is used.
   628  	PreferServerCipherSuites bool
   629  
   630  	// SessionTicketsDisabled may be set to true to disable session ticket and
   631  	// PSK (resumption) support. Note that on clients, session ticket support is
   632  	// also disabled if ClientSessionCache is nil.
   633  	SessionTicketsDisabled bool
   634  
   635  	// SessionTicketKey is used by TLS servers to provide session resumption.
   636  	// See RFC 5077 and the PSK mode of RFC 8446. If zero, it will be filled
   637  	// with random data before the first server handshake.
   638  	//
   639  	// Deprecated: if this field is left at zero, session ticket keys will be
   640  	// automatically rotated every day and dropped after seven days. For
   641  	// customizing the rotation schedule or synchronizing servers that are
   642  	// terminating connections for the same host, use SetSessionTicketKeys.
   643  	SessionTicketKey [32]byte
   644  
   645  	// ClientSessionCache is a cache of ClientSessionState entries for TLS
   646  	// session resumption. It is only used by clients.
   647  	ClientSessionCache ClientSessionCache
   648  
   649  	// MinVersion contains the minimum TLS version that is acceptable.
   650  	// If zero, TLS 1.0 is currently taken as the minimum.
   651  	MinVersion uint16
   652  
   653  	// MaxVersion contains the maximum TLS version that is acceptable.
   654  	// If zero, the maximum version supported by this package is used,
   655  	// which is currently TLS 1.3.
   656  	MaxVersion uint16
   657  
   658  	// CurvePreferences contains the elliptic curves that will be used in
   659  	// an ECDHE handshake, in preference order. If empty, the default will
   660  	// be used. The client will use the first preference as the type for
   661  	// its key share in TLS 1.3. This may change in the future.
   662  	CurvePreferences []CurveID
   663  
   664  	// DynamicRecordSizingDisabled disables adaptive sizing of TLS records.
   665  	// When true, the largest possible TLS record size is always used. When
   666  	// false, the size of TLS records may be adjusted in an attempt to
   667  	// improve latency.
   668  	DynamicRecordSizingDisabled bool
   669  
   670  	// Renegotiation controls what types of renegotiation are supported.
   671  	// The default, none, is correct for the vast majority of applications.
   672  	Renegotiation RenegotiationSupport
   673  
   674  	// KeyLogWriter optionally specifies a destination for TLS master secrets
   675  	// in NSS key log format that can be used to allow external programs
   676  	// such as Wireshark to decrypt TLS connections.
   677  	// See https://developer.mozilla.org/en-US/docs/Mozilla/Projects/NSS/Key_Log_Format.
   678  	// Use of KeyLogWriter compromises security and should only be
   679  	// used for debugging.
   680  	KeyLogWriter io.Writer
   681  
   682  	// mutex protects sessionTicketKeys and autoSessionTicketKeys.
   683  	mutex sync.RWMutex
   684  	// sessionTicketKeys contains zero or more ticket keys. If set, it means the
   685  	// the keys were set with SessionTicketKey or SetSessionTicketKeys. The
   686  	// first key is used for new tickets and any subsequent keys can be used to
   687  	// decrypt old tickets. The slice contents are not protected by the mutex
   688  	// and are immutable.
   689  	sessionTicketKeys []ticketKey
   690  	// autoSessionTicketKeys is like sessionTicketKeys but is owned by the
   691  	// auto-rotation logic. See Config.ticketKeys.
   692  	autoSessionTicketKeys []ticketKey
   693  }
   694  
   695  // A RecordLayer handles encrypting and decrypting of TLS messages.
   696  type RecordLayer interface {
   697  	SetReadKey(encLevel EncryptionLevel, suite *CipherSuiteTLS13, trafficSecret []byte)
   698  	SetWriteKey(encLevel EncryptionLevel, suite *CipherSuiteTLS13, trafficSecret []byte)
   699  	ReadHandshakeMessage() ([]byte, error)
   700  	WriteRecord([]byte) (int, error)
   701  	SendAlert(uint8)
   702  }
   703  
   704  type ExtraConfig struct {
   705  	// GetExtensions, if not nil, is called before a message that allows
   706  	// sending of extensions is sent.
   707  	// Currently only implemented for the ClientHello message (for the client)
   708  	// and for the EncryptedExtensions message (for the server).
   709  	// Only valid for TLS 1.3.
   710  	GetExtensions func(handshakeMessageType uint8) []Extension
   711  
   712  	// ReceivedExtensions, if not nil, is called when a message that allows the
   713  	// inclusion of extensions is received.
   714  	// It is called with an empty slice of extensions, if the message didn't
   715  	// contain any extensions.
   716  	// Currently only implemented for the ClientHello message (sent by the
   717  	// client) and for the EncryptedExtensions message (sent by the server).
   718  	// Only valid for TLS 1.3.
   719  	ReceivedExtensions func(handshakeMessageType uint8, exts []Extension)
   720  
   721  	// AlternativeRecordLayer is used by QUIC
   722  	AlternativeRecordLayer RecordLayer
   723  
   724  	// Enforce the selection of a supported application protocol.
   725  	// Only works for TLS 1.3.
   726  	// If enabled, client and server have to agree on an application protocol.
   727  	// Otherwise, connection establishment fails.
   728  	EnforceNextProtoSelection bool
   729  
   730  	// If MaxEarlyData is greater than 0, the client will be allowed to send early
   731  	// data when resuming a session.
   732  	// Requires the AlternativeRecordLayer to be set.
   733  	//
   734  	// It has no meaning on the client.
   735  	MaxEarlyData uint32
   736  
   737  	// The Accept0RTT callback is called when the client offers 0-RTT.
   738  	// The server then has to decide if it wants to accept or reject 0-RTT.
   739  	// It is only used for servers.
   740  	Accept0RTT func(appData []byte) bool
   741  
   742  	// 0RTTRejected is called when the server rejectes 0-RTT.
   743  	// It is only used for clients.
   744  	Rejected0RTT func()
   745  
   746  	// If set, the client will export the 0-RTT key when resuming a session that
   747  	// allows sending of early data.
   748  	// Requires the AlternativeRecordLayer to be set.
   749  	//
   750  	// It has no meaning to the server.
   751  	Enable0RTT bool
   752  
   753  	// Is called when the client saves a session ticket to the session ticket.
   754  	// This gives the application the opportunity to save some data along with the ticket,
   755  	// which can be restored when the session ticket is used.
   756  	GetAppDataForSessionState func() []byte
   757  
   758  	// Is called when the client uses a session ticket.
   759  	// Restores the application data that was saved earlier on GetAppDataForSessionTicket.
   760  	SetAppDataFromSessionState func([]byte)
   761  
   762  	// [Psiphon]
   763  	// ClientHelloPRNG is used for Client Hello randomization and replay.
   764  	ClientHelloPRNG *prng.PRNG
   765  
   766  	// [Psiphon]
   767  	// GetClientHelloRandom is used to supply a specific value in the TLS
   768  	// Client Hello random field. This is used to send an anti-probing
   769  	// message, indistinguishable from random, that proves knowlegde of a
   770  	// shared secret key.
   771  	GetClientHelloRandom func() ([]byte, error)
   772  }
   773  
   774  // Clone clones.
   775  func (c *ExtraConfig) Clone() *ExtraConfig {
   776  	return &ExtraConfig{
   777  		GetExtensions:              c.GetExtensions,
   778  		ReceivedExtensions:         c.ReceivedExtensions,
   779  		AlternativeRecordLayer:     c.AlternativeRecordLayer,
   780  		EnforceNextProtoSelection:  c.EnforceNextProtoSelection,
   781  		MaxEarlyData:               c.MaxEarlyData,
   782  		Enable0RTT:                 c.Enable0RTT,
   783  		Accept0RTT:                 c.Accept0RTT,
   784  		Rejected0RTT:               c.Rejected0RTT,
   785  		GetAppDataForSessionState:  c.GetAppDataForSessionState,
   786  		SetAppDataFromSessionState: c.SetAppDataFromSessionState,
   787  	}
   788  }
   789  
   790  func (c *ExtraConfig) usesAlternativeRecordLayer() bool {
   791  	return c != nil && c.AlternativeRecordLayer != nil
   792  }
   793  
   794  const (
   795  	// ticketKeyNameLen is the number of bytes of identifier that is prepended to
   796  	// an encrypted session ticket in order to identify the key used to encrypt it.
   797  	ticketKeyNameLen = 16
   798  
   799  	// ticketKeyLifetime is how long a ticket key remains valid and can be used to
   800  	// resume a client connection.
   801  	ticketKeyLifetime = 7 * 24 * time.Hour // 7 days
   802  
   803  	// ticketKeyRotation is how often the server should rotate the session ticket key
   804  	// that is used for new tickets.
   805  	ticketKeyRotation = 24 * time.Hour
   806  )
   807  
   808  // ticketKey is the internal representation of a session ticket key.
   809  type ticketKey struct {
   810  	// keyName is an opaque byte string that serves to identify the session
   811  	// ticket key. It's exposed as plaintext in every session ticket.
   812  	keyName [ticketKeyNameLen]byte
   813  	aesKey  [16]byte
   814  	hmacKey [16]byte
   815  	// created is the time at which this ticket key was created. See Config.ticketKeys.
   816  	created time.Time
   817  }
   818  
   819  // ticketKeyFromBytes converts from the external representation of a session
   820  // ticket key to a ticketKey. Externally, session ticket keys are 32 random
   821  // bytes and this function expands that into sufficient name and key material.
   822  func (c *config) ticketKeyFromBytes(b [32]byte) (key ticketKey) {
   823  	hashed := sha512.Sum512(b[:])
   824  	copy(key.keyName[:], hashed[:ticketKeyNameLen])
   825  	copy(key.aesKey[:], hashed[ticketKeyNameLen:ticketKeyNameLen+16])
   826  	copy(key.hmacKey[:], hashed[ticketKeyNameLen+16:ticketKeyNameLen+32])
   827  	key.created = c.time()
   828  	return key
   829  }
   830  
   831  // maxSessionTicketLifetime is the maximum allowed lifetime of a TLS 1.3 session
   832  // ticket, and the lifetime we set for tickets we send.
   833  const maxSessionTicketLifetime = 7 * 24 * time.Hour
   834  
   835  // Clone returns a shallow clone of c or nil if c is nil. It is safe to clone a Config that is
   836  // being used concurrently by a TLS client or server.
   837  func (c *config) Clone() *config {
   838  	if c == nil {
   839  		return nil
   840  	}
   841  	c.mutex.RLock()
   842  	defer c.mutex.RUnlock()
   843  	return &config{
   844  		Rand:                        c.Rand,
   845  		Time:                        c.Time,
   846  		Certificates:                c.Certificates,
   847  		NameToCertificate:           c.NameToCertificate,
   848  		GetCertificate:              c.GetCertificate,
   849  		GetClientCertificate:        c.GetClientCertificate,
   850  		GetConfigForClient:          c.GetConfigForClient,
   851  		VerifyPeerCertificate:       c.VerifyPeerCertificate,
   852  		VerifyConnection:            c.VerifyConnection,
   853  		RootCAs:                     c.RootCAs,
   854  		NextProtos:                  c.NextProtos,
   855  		ServerName:                  c.ServerName,
   856  		ClientAuth:                  c.ClientAuth,
   857  		ClientCAs:                   c.ClientCAs,
   858  		InsecureSkipVerify:          c.InsecureSkipVerify,
   859  		CipherSuites:                c.CipherSuites,
   860  		PreferServerCipherSuites:    c.PreferServerCipherSuites,
   861  		SessionTicketsDisabled:      c.SessionTicketsDisabled,
   862  		SessionTicketKey:            c.SessionTicketKey,
   863  		ClientSessionCache:          c.ClientSessionCache,
   864  		MinVersion:                  c.MinVersion,
   865  		MaxVersion:                  c.MaxVersion,
   866  		CurvePreferences:            c.CurvePreferences,
   867  		DynamicRecordSizingDisabled: c.DynamicRecordSizingDisabled,
   868  		Renegotiation:               c.Renegotiation,
   869  		KeyLogWriter:                c.KeyLogWriter,
   870  		sessionTicketKeys:           c.sessionTicketKeys,
   871  		autoSessionTicketKeys:       c.autoSessionTicketKeys,
   872  	}
   873  }
   874  
   875  // deprecatedSessionTicketKey is set as the prefix of SessionTicketKey if it was
   876  // randomized for backwards compatibility but is not in use.
   877  var deprecatedSessionTicketKey = []byte("DEPRECATED")
   878  
   879  // initLegacySessionTicketKeyRLocked ensures the legacy SessionTicketKey field is
   880  // randomized if empty, and that sessionTicketKeys is populated from it otherwise.
   881  func (c *config) initLegacySessionTicketKeyRLocked() {
   882  	// Don't write if SessionTicketKey is already defined as our deprecated string,
   883  	// or if it is defined by the user but sessionTicketKeys is already set.
   884  	if c.SessionTicketKey != [32]byte{} &&
   885  		(bytes.HasPrefix(c.SessionTicketKey[:], deprecatedSessionTicketKey) || len(c.sessionTicketKeys) > 0) {
   886  		return
   887  	}
   888  
   889  	// We need to write some data, so get an exclusive lock and re-check any conditions.
   890  	c.mutex.RUnlock()
   891  	defer c.mutex.RLock()
   892  	c.mutex.Lock()
   893  	defer c.mutex.Unlock()
   894  	if c.SessionTicketKey == [32]byte{} {
   895  		if _, err := io.ReadFull(c.rand(), c.SessionTicketKey[:]); err != nil {
   896  			panic(fmt.Sprintf("tls: unable to generate random session ticket key: %v", err))
   897  		}
   898  		// Write the deprecated prefix at the beginning so we know we created
   899  		// it. This key with the DEPRECATED prefix isn't used as an actual
   900  		// session ticket key, and is only randomized in case the application
   901  		// reuses it for some reason.
   902  		copy(c.SessionTicketKey[:], deprecatedSessionTicketKey)
   903  	} else if !bytes.HasPrefix(c.SessionTicketKey[:], deprecatedSessionTicketKey) && len(c.sessionTicketKeys) == 0 {
   904  		c.sessionTicketKeys = []ticketKey{c.ticketKeyFromBytes(c.SessionTicketKey)}
   905  	}
   906  
   907  }
   908  
   909  // ticketKeys returns the ticketKeys for this connection.
   910  // If configForClient has explicitly set keys, those will
   911  // be returned. Otherwise, the keys on c will be used and
   912  // may be rotated if auto-managed.
   913  // During rotation, any expired session ticket keys are deleted from
   914  // c.sessionTicketKeys. If the session ticket key that is currently
   915  // encrypting tickets (ie. the first ticketKey in c.sessionTicketKeys)
   916  // is not fresh, then a new session ticket key will be
   917  // created and prepended to c.sessionTicketKeys.
   918  func (c *config) ticketKeys(configForClient *config) []ticketKey {
   919  	// If the ConfigForClient callback returned a Config with explicitly set
   920  	// keys, use those, otherwise just use the original Config.
   921  	if configForClient != nil {
   922  		configForClient.mutex.RLock()
   923  		if configForClient.SessionTicketsDisabled {
   924  			return nil
   925  		}
   926  		configForClient.initLegacySessionTicketKeyRLocked()
   927  		if len(configForClient.sessionTicketKeys) != 0 {
   928  			ret := configForClient.sessionTicketKeys
   929  			configForClient.mutex.RUnlock()
   930  			return ret
   931  		}
   932  		configForClient.mutex.RUnlock()
   933  	}
   934  
   935  	c.mutex.RLock()
   936  	defer c.mutex.RUnlock()
   937  	if c.SessionTicketsDisabled {
   938  		return nil
   939  	}
   940  	c.initLegacySessionTicketKeyRLocked()
   941  	if len(c.sessionTicketKeys) != 0 {
   942  		return c.sessionTicketKeys
   943  	}
   944  	// Fast path for the common case where the key is fresh enough.
   945  	if len(c.autoSessionTicketKeys) > 0 && c.time().Sub(c.autoSessionTicketKeys[0].created) < ticketKeyRotation {
   946  		return c.autoSessionTicketKeys
   947  	}
   948  
   949  	// autoSessionTicketKeys are managed by auto-rotation.
   950  	c.mutex.RUnlock()
   951  	defer c.mutex.RLock()
   952  	c.mutex.Lock()
   953  	defer c.mutex.Unlock()
   954  	// Re-check the condition in case it changed since obtaining the new lock.
   955  	if len(c.autoSessionTicketKeys) == 0 || c.time().Sub(c.autoSessionTicketKeys[0].created) >= ticketKeyRotation {
   956  		var newKey [32]byte
   957  		if _, err := io.ReadFull(c.rand(), newKey[:]); err != nil {
   958  			panic(fmt.Sprintf("unable to generate random session ticket key: %v", err))
   959  		}
   960  		valid := make([]ticketKey, 0, len(c.autoSessionTicketKeys)+1)
   961  		valid = append(valid, c.ticketKeyFromBytes(newKey))
   962  		for _, k := range c.autoSessionTicketKeys {
   963  			// While rotating the current key, also remove any expired ones.
   964  			if c.time().Sub(k.created) < ticketKeyLifetime {
   965  				valid = append(valid, k)
   966  			}
   967  		}
   968  		c.autoSessionTicketKeys = valid
   969  	}
   970  	return c.autoSessionTicketKeys
   971  }
   972  
   973  // SetSessionTicketKeys updates the session ticket keys for a server.
   974  //
   975  // The first key will be used when creating new tickets, while all keys can be
   976  // used for decrypting tickets. It is safe to call this function while the
   977  // server is running in order to rotate the session ticket keys. The function
   978  // will panic if keys is empty.
   979  //
   980  // Calling this function will turn off automatic session ticket key rotation.
   981  //
   982  // If multiple servers are terminating connections for the same host they should
   983  // all have the same session ticket keys. If the session ticket keys leaks,
   984  // previously recorded and future TLS connections using those keys might be
   985  // compromised.
   986  func (c *config) SetSessionTicketKeys(keys [][32]byte) {
   987  	if len(keys) == 0 {
   988  		panic("tls: keys must have at least one key")
   989  	}
   990  
   991  	newKeys := make([]ticketKey, len(keys))
   992  	for i, bytes := range keys {
   993  		newKeys[i] = c.ticketKeyFromBytes(bytes)
   994  	}
   995  
   996  	c.mutex.Lock()
   997  	c.sessionTicketKeys = newKeys
   998  	c.mutex.Unlock()
   999  }
  1000  
  1001  func (c *config) rand() io.Reader {
  1002  	r := c.Rand
  1003  	if r == nil {
  1004  		return rand.Reader
  1005  	}
  1006  	return r
  1007  }
  1008  
  1009  func (c *config) time() time.Time {
  1010  	t := c.Time
  1011  	if t == nil {
  1012  		t = time.Now
  1013  	}
  1014  	return t()
  1015  }
  1016  
  1017  func (c *config) cipherSuites() []uint16 {
  1018  	s := c.CipherSuites
  1019  	if s == nil {
  1020  		s = defaultCipherSuites()
  1021  	}
  1022  	return s
  1023  }
  1024  
  1025  var supportedVersions = []uint16{
  1026  	VersionTLS13,
  1027  	VersionTLS12,
  1028  	VersionTLS11,
  1029  	VersionTLS10,
  1030  }
  1031  
  1032  func (c *config) supportedVersions() []uint16 {
  1033  	versions := make([]uint16, 0, len(supportedVersions))
  1034  	for _, v := range supportedVersions {
  1035  		if c != nil && c.MinVersion != 0 && v < c.MinVersion {
  1036  			continue
  1037  		}
  1038  		if c != nil && c.MaxVersion != 0 && v > c.MaxVersion {
  1039  			continue
  1040  		}
  1041  		versions = append(versions, v)
  1042  	}
  1043  	return versions
  1044  }
  1045  
  1046  func (c *config) maxSupportedVersion() uint16 {
  1047  	supportedVersions := c.supportedVersions()
  1048  	if len(supportedVersions) == 0 {
  1049  		return 0
  1050  	}
  1051  	return supportedVersions[0]
  1052  }
  1053  
  1054  // supportedVersionsFromMax returns a list of supported versions derived from a
  1055  // legacy maximum version value. Note that only versions supported by this
  1056  // library are returned. Any newer peer will use supportedVersions anyway.
  1057  func supportedVersionsFromMax(maxVersion uint16) []uint16 {
  1058  	versions := make([]uint16, 0, len(supportedVersions))
  1059  	for _, v := range supportedVersions {
  1060  		if v > maxVersion {
  1061  			continue
  1062  		}
  1063  		versions = append(versions, v)
  1064  	}
  1065  	return versions
  1066  }
  1067  
  1068  var defaultCurvePreferences = []CurveID{X25519, CurveP256, CurveP384, CurveP521}
  1069  
  1070  func (c *config) curvePreferences() []CurveID {
  1071  	if c == nil || len(c.CurvePreferences) == 0 {
  1072  		return defaultCurvePreferences
  1073  	}
  1074  	return c.CurvePreferences
  1075  }
  1076  
  1077  func (c *config) supportsCurve(curve CurveID) bool {
  1078  	for _, cc := range c.curvePreferences() {
  1079  		if cc == curve {
  1080  			return true
  1081  		}
  1082  	}
  1083  	return false
  1084  }
  1085  
  1086  // mutualVersion returns the protocol version to use given the advertised
  1087  // versions of the peer. Priority is given to the peer preference order.
  1088  func (c *config) mutualVersion(peerVersions []uint16) (uint16, bool) {
  1089  	supportedVersions := c.supportedVersions()
  1090  	for _, peerVersion := range peerVersions {
  1091  		for _, v := range supportedVersions {
  1092  			if v == peerVersion {
  1093  				return v, true
  1094  			}
  1095  		}
  1096  	}
  1097  	return 0, false
  1098  }
  1099  
  1100  var errNoCertificates = errors.New("tls: no certificates configured")
  1101  
  1102  // getCertificate returns the best certificate for the given ClientHelloInfo,
  1103  // defaulting to the first element of c.Certificates.
  1104  func (c *config) getCertificate(clientHello *ClientHelloInfo) (*Certificate, error) {
  1105  	if c.GetCertificate != nil &&
  1106  		(len(c.Certificates) == 0 || len(clientHello.ServerName) > 0) {
  1107  		cert, err := c.GetCertificate(clientHello)
  1108  		if cert != nil || err != nil {
  1109  			return cert, err
  1110  		}
  1111  	}
  1112  
  1113  	if len(c.Certificates) == 0 {
  1114  		return nil, errNoCertificates
  1115  	}
  1116  
  1117  	if len(c.Certificates) == 1 {
  1118  		// There's only one choice, so no point doing any work.
  1119  		return &c.Certificates[0], nil
  1120  	}
  1121  
  1122  	if c.NameToCertificate != nil {
  1123  		name := strings.ToLower(clientHello.ServerName)
  1124  		if cert, ok := c.NameToCertificate[name]; ok {
  1125  			return cert, nil
  1126  		}
  1127  		if len(name) > 0 {
  1128  			labels := strings.Split(name, ".")
  1129  			labels[0] = "*"
  1130  			wildcardName := strings.Join(labels, ".")
  1131  			if cert, ok := c.NameToCertificate[wildcardName]; ok {
  1132  				return cert, nil
  1133  			}
  1134  		}
  1135  	}
  1136  
  1137  	for _, cert := range c.Certificates {
  1138  		if err := clientHello.SupportsCertificate(&cert); err == nil {
  1139  			return &cert, nil
  1140  		}
  1141  	}
  1142  
  1143  	// If nothing matches, return the first certificate.
  1144  	return &c.Certificates[0], nil
  1145  }
  1146  
  1147  // SupportsCertificate returns nil if the provided certificate is supported by
  1148  // the client that sent the ClientHello. Otherwise, it returns an error
  1149  // describing the reason for the incompatibility.
  1150  //
  1151  // If this ClientHelloInfo was passed to a GetConfigForClient or GetCertificate
  1152  // callback, this method will take into account the associated Config. Note that
  1153  // if GetConfigForClient returns a different Config, the change can't be
  1154  // accounted for by this method.
  1155  //
  1156  // This function will call x509.ParseCertificate unless c.Leaf is set, which can
  1157  // incur a significant performance cost.
  1158  func (chi *clientHelloInfo) SupportsCertificate(c *Certificate) error {
  1159  	// Note we don't currently support certificate_authorities nor
  1160  	// signature_algorithms_cert, and don't check the algorithms of the
  1161  	// signatures on the chain (which anyway are a SHOULD, see RFC 8446,
  1162  	// Section 4.4.2.2).
  1163  
  1164  	config := chi.config
  1165  	if config == nil {
  1166  		config = &Config{}
  1167  	}
  1168  	conf := fromConfig(config)
  1169  	vers, ok := conf.mutualVersion(chi.SupportedVersions)
  1170  	if !ok {
  1171  		return errors.New("no mutually supported protocol versions")
  1172  	}
  1173  
  1174  	// If the client specified the name they are trying to connect to, the
  1175  	// certificate needs to be valid for it.
  1176  	if chi.ServerName != "" {
  1177  		x509Cert, err := leafCertificate(c)
  1178  		if err != nil {
  1179  			return fmt.Errorf("failed to parse certificate: %w", err)
  1180  		}
  1181  		if err := x509Cert.VerifyHostname(chi.ServerName); err != nil {
  1182  			return fmt.Errorf("certificate is not valid for requested server name: %w", err)
  1183  		}
  1184  	}
  1185  
  1186  	// supportsRSAFallback returns nil if the certificate and connection support
  1187  	// the static RSA key exchange, and unsupported otherwise. The logic for
  1188  	// supporting static RSA is completely disjoint from the logic for
  1189  	// supporting signed key exchanges, so we just check it as a fallback.
  1190  	supportsRSAFallback := func(unsupported error) error {
  1191  		// TLS 1.3 dropped support for the static RSA key exchange.
  1192  		if vers == VersionTLS13 {
  1193  			return unsupported
  1194  		}
  1195  		// The static RSA key exchange works by decrypting a challenge with the
  1196  		// RSA private key, not by signing, so check the PrivateKey implements
  1197  		// crypto.Decrypter, like *rsa.PrivateKey does.
  1198  		if priv, ok := c.PrivateKey.(crypto.Decrypter); ok {
  1199  			if _, ok := priv.Public().(*rsa.PublicKey); !ok {
  1200  				return unsupported
  1201  			}
  1202  		} else {
  1203  			return unsupported
  1204  		}
  1205  		// Finally, there needs to be a mutual cipher suite that uses the static
  1206  		// RSA key exchange instead of ECDHE.
  1207  		rsaCipherSuite := selectCipherSuite(chi.CipherSuites, conf.cipherSuites(), func(c *cipherSuite) bool {
  1208  			if c.flags&suiteECDHE != 0 {
  1209  				return false
  1210  			}
  1211  			if vers < VersionTLS12 && c.flags&suiteTLS12 != 0 {
  1212  				return false
  1213  			}
  1214  			return true
  1215  		})
  1216  		if rsaCipherSuite == nil {
  1217  			return unsupported
  1218  		}
  1219  		return nil
  1220  	}
  1221  
  1222  	// If the client sent the signature_algorithms extension, ensure it supports
  1223  	// schemes we can use with this certificate and TLS version.
  1224  	if len(chi.SignatureSchemes) > 0 {
  1225  		if _, err := selectSignatureScheme(vers, c, chi.SignatureSchemes); err != nil {
  1226  			return supportsRSAFallback(err)
  1227  		}
  1228  	}
  1229  
  1230  	// In TLS 1.3 we are done because supported_groups is only relevant to the
  1231  	// ECDHE computation, point format negotiation is removed, cipher suites are
  1232  	// only relevant to the AEAD choice, and static RSA does not exist.
  1233  	if vers == VersionTLS13 {
  1234  		return nil
  1235  	}
  1236  
  1237  	// The only signed key exchange we support is ECDHE.
  1238  	if !supportsECDHE(conf, chi.SupportedCurves, chi.SupportedPoints) {
  1239  		return supportsRSAFallback(errors.New("client doesn't support ECDHE, can only use legacy RSA key exchange"))
  1240  	}
  1241  
  1242  	var ecdsaCipherSuite bool
  1243  	if priv, ok := c.PrivateKey.(crypto.Signer); ok {
  1244  		switch pub := priv.Public().(type) {
  1245  		case *ecdsa.PublicKey:
  1246  			var curve CurveID
  1247  			switch pub.Curve {
  1248  			case elliptic.P256():
  1249  				curve = CurveP256
  1250  			case elliptic.P384():
  1251  				curve = CurveP384
  1252  			case elliptic.P521():
  1253  				curve = CurveP521
  1254  			default:
  1255  				return supportsRSAFallback(unsupportedCertificateError(c))
  1256  			}
  1257  			var curveOk bool
  1258  			for _, c := range chi.SupportedCurves {
  1259  				if c == curve && conf.supportsCurve(c) {
  1260  					curveOk = true
  1261  					break
  1262  				}
  1263  			}
  1264  			if !curveOk {
  1265  				return errors.New("client doesn't support certificate curve")
  1266  			}
  1267  			ecdsaCipherSuite = true
  1268  		case ed25519.PublicKey:
  1269  			if vers < VersionTLS12 || len(chi.SignatureSchemes) == 0 {
  1270  				return errors.New("connection doesn't support Ed25519")
  1271  			}
  1272  			ecdsaCipherSuite = true
  1273  		case *rsa.PublicKey:
  1274  		default:
  1275  			return supportsRSAFallback(unsupportedCertificateError(c))
  1276  		}
  1277  	} else {
  1278  		return supportsRSAFallback(unsupportedCertificateError(c))
  1279  	}
  1280  
  1281  	// Make sure that there is a mutually supported cipher suite that works with
  1282  	// this certificate. Cipher suite selection will then apply the logic in
  1283  	// reverse to pick it. See also serverHandshakeState.cipherSuiteOk.
  1284  	cipherSuite := selectCipherSuite(chi.CipherSuites, conf.cipherSuites(), func(c *cipherSuite) bool {
  1285  		if c.flags&suiteECDHE == 0 {
  1286  			return false
  1287  		}
  1288  		if c.flags&suiteECSign != 0 {
  1289  			if !ecdsaCipherSuite {
  1290  				return false
  1291  			}
  1292  		} else {
  1293  			if ecdsaCipherSuite {
  1294  				return false
  1295  			}
  1296  		}
  1297  		if vers < VersionTLS12 && c.flags&suiteTLS12 != 0 {
  1298  			return false
  1299  		}
  1300  		return true
  1301  	})
  1302  	if cipherSuite == nil {
  1303  		return supportsRSAFallback(errors.New("client doesn't support any cipher suites compatible with the certificate"))
  1304  	}
  1305  
  1306  	return nil
  1307  }
  1308  
  1309  // BuildNameToCertificate parses c.Certificates and builds c.NameToCertificate
  1310  // from the CommonName and SubjectAlternateName fields of each of the leaf
  1311  // certificates.
  1312  //
  1313  // Deprecated: NameToCertificate only allows associating a single certificate
  1314  // with a given name. Leave that field nil to let the library select the first
  1315  // compatible chain from Certificates.
  1316  func (c *config) BuildNameToCertificate() {
  1317  	c.NameToCertificate = make(map[string]*Certificate)
  1318  	for i := range c.Certificates {
  1319  		cert := &c.Certificates[i]
  1320  		x509Cert, err := leafCertificate(cert)
  1321  		if err != nil {
  1322  			continue
  1323  		}
  1324  		// If SANs are *not* present, some clients will consider the certificate
  1325  		// valid for the name in the Common Name.
  1326  		if x509Cert.Subject.CommonName != "" && len(x509Cert.DNSNames) == 0 {
  1327  			c.NameToCertificate[x509Cert.Subject.CommonName] = cert
  1328  		}
  1329  		for _, san := range x509Cert.DNSNames {
  1330  			c.NameToCertificate[san] = cert
  1331  		}
  1332  	}
  1333  }
  1334  
  1335  const (
  1336  	keyLogLabelTLS12           = "CLIENT_RANDOM"
  1337  	keyLogLabelEarlyTraffic    = "CLIENT_EARLY_TRAFFIC_SECRET"
  1338  	keyLogLabelClientHandshake = "CLIENT_HANDSHAKE_TRAFFIC_SECRET"
  1339  	keyLogLabelServerHandshake = "SERVER_HANDSHAKE_TRAFFIC_SECRET"
  1340  	keyLogLabelClientTraffic   = "CLIENT_TRAFFIC_SECRET_0"
  1341  	keyLogLabelServerTraffic   = "SERVER_TRAFFIC_SECRET_0"
  1342  )
  1343  
  1344  func (c *config) writeKeyLog(label string, clientRandom, secret []byte) error {
  1345  	if c.KeyLogWriter == nil {
  1346  		return nil
  1347  	}
  1348  
  1349  	logLine := []byte(fmt.Sprintf("%s %x %x\n", label, clientRandom, secret))
  1350  
  1351  	writerMutex.Lock()
  1352  	_, err := c.KeyLogWriter.Write(logLine)
  1353  	writerMutex.Unlock()
  1354  
  1355  	return err
  1356  }
  1357  
  1358  // writerMutex protects all KeyLogWriters globally. It is rarely enabled,
  1359  // and is only for debugging, so a global mutex saves space.
  1360  var writerMutex sync.Mutex
  1361  
  1362  // A Certificate is a chain of one or more certificates, leaf first.
  1363  type Certificate = tls.Certificate
  1364  
  1365  // leaf returns the parsed leaf certificate, either from c.Leaf or by parsing
  1366  // the corresponding c.Certificate[0].
  1367  func leafCertificate(c *Certificate) (*x509.Certificate, error) {
  1368  	if c.Leaf != nil {
  1369  		return c.Leaf, nil
  1370  	}
  1371  	return x509.ParseCertificate(c.Certificate[0])
  1372  }
  1373  
  1374  type handshakeMessage interface {
  1375  	marshal() []byte
  1376  	unmarshal([]byte) bool
  1377  }
  1378  
  1379  // lruSessionCache is a ClientSessionCache implementation that uses an LRU
  1380  // caching strategy.
  1381  type lruSessionCache struct {
  1382  	sync.Mutex
  1383  
  1384  	m        map[string]*list.Element
  1385  	q        *list.List
  1386  	capacity int
  1387  }
  1388  
  1389  type lruSessionCacheEntry struct {
  1390  	sessionKey string
  1391  	state      *ClientSessionState
  1392  }
  1393  
  1394  // NewLRUClientSessionCache returns a ClientSessionCache with the given
  1395  // capacity that uses an LRU strategy. If capacity is < 1, a default capacity
  1396  // is used instead.
  1397  func NewLRUClientSessionCache(capacity int) ClientSessionCache {
  1398  	const defaultSessionCacheCapacity = 64
  1399  
  1400  	if capacity < 1 {
  1401  		capacity = defaultSessionCacheCapacity
  1402  	}
  1403  	return &lruSessionCache{
  1404  		m:        make(map[string]*list.Element),
  1405  		q:        list.New(),
  1406  		capacity: capacity,
  1407  	}
  1408  }
  1409  
  1410  // Put adds the provided (sessionKey, cs) pair to the cache. If cs is nil, the entry
  1411  // corresponding to sessionKey is removed from the cache instead.
  1412  func (c *lruSessionCache) Put(sessionKey string, cs *ClientSessionState) {
  1413  	c.Lock()
  1414  	defer c.Unlock()
  1415  
  1416  	if elem, ok := c.m[sessionKey]; ok {
  1417  		if cs == nil {
  1418  			c.q.Remove(elem)
  1419  			delete(c.m, sessionKey)
  1420  		} else {
  1421  			entry := elem.Value.(*lruSessionCacheEntry)
  1422  			entry.state = cs
  1423  			c.q.MoveToFront(elem)
  1424  		}
  1425  		return
  1426  	}
  1427  
  1428  	if c.q.Len() < c.capacity {
  1429  		entry := &lruSessionCacheEntry{sessionKey, cs}
  1430  		c.m[sessionKey] = c.q.PushFront(entry)
  1431  		return
  1432  	}
  1433  
  1434  	elem := c.q.Back()
  1435  	entry := elem.Value.(*lruSessionCacheEntry)
  1436  	delete(c.m, entry.sessionKey)
  1437  	entry.sessionKey = sessionKey
  1438  	entry.state = cs
  1439  	c.q.MoveToFront(elem)
  1440  	c.m[sessionKey] = elem
  1441  }
  1442  
  1443  // Get returns the ClientSessionState value associated with a given key. It
  1444  // returns (nil, false) if no value is found.
  1445  func (c *lruSessionCache) Get(sessionKey string) (*ClientSessionState, bool) {
  1446  	c.Lock()
  1447  	defer c.Unlock()
  1448  
  1449  	if elem, ok := c.m[sessionKey]; ok {
  1450  		c.q.MoveToFront(elem)
  1451  		return elem.Value.(*lruSessionCacheEntry).state, true
  1452  	}
  1453  	return nil, false
  1454  }
  1455  
  1456  var emptyConfig Config
  1457  
  1458  func defaultConfig() *Config {
  1459  	return &emptyConfig
  1460  }
  1461  
  1462  var (
  1463  	once                        sync.Once
  1464  	varDefaultCipherSuites      []uint16
  1465  	varDefaultCipherSuitesTLS13 []uint16
  1466  )
  1467  
  1468  func defaultCipherSuites() []uint16 {
  1469  	once.Do(initDefaultCipherSuites)
  1470  	return varDefaultCipherSuites
  1471  }
  1472  
  1473  func defaultCipherSuitesTLS13() []uint16 {
  1474  	once.Do(initDefaultCipherSuites)
  1475  	return varDefaultCipherSuitesTLS13
  1476  }
  1477  
  1478  var (
  1479  	hasGCMAsmAMD64 = cpu.X86.HasAES && cpu.X86.HasPCLMULQDQ
  1480  	hasGCMAsmARM64 = cpu.ARM64.HasAES && cpu.ARM64.HasPMULL
  1481  	// Keep in sync with crypto/aes/cipher_s390x.go.
  1482  	hasGCMAsmS390X = cpu.S390X.HasAES && cpu.S390X.HasAESCBC && cpu.S390X.HasAESCTR && (cpu.S390X.HasGHASH || cpu.S390X.HasAESGCM)
  1483  
  1484  	hasAESGCMHardwareSupport = runtime.GOARCH == "amd64" && hasGCMAsmAMD64 ||
  1485  		runtime.GOARCH == "arm64" && hasGCMAsmARM64 ||
  1486  		runtime.GOARCH == "s390x" && hasGCMAsmS390X
  1487  )
  1488  
  1489  func initDefaultCipherSuites() {
  1490  	var topCipherSuites []uint16
  1491  
  1492  	if hasAESGCMHardwareSupport {
  1493  		// If AES-GCM hardware is provided then prioritise AES-GCM
  1494  		// cipher suites.
  1495  		topCipherSuites = []uint16{
  1496  			TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
  1497  			TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
  1498  			TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
  1499  			TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
  1500  			TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305,
  1501  			TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305,
  1502  		}
  1503  		varDefaultCipherSuitesTLS13 = []uint16{
  1504  			TLS_AES_128_GCM_SHA256,
  1505  			TLS_CHACHA20_POLY1305_SHA256,
  1506  			TLS_AES_256_GCM_SHA384,
  1507  		}
  1508  	} else {
  1509  		// Without AES-GCM hardware, we put the ChaCha20-Poly1305
  1510  		// cipher suites first.
  1511  		topCipherSuites = []uint16{
  1512  			TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305,
  1513  			TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305,
  1514  			TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
  1515  			TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
  1516  			TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
  1517  			TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
  1518  		}
  1519  		varDefaultCipherSuitesTLS13 = []uint16{
  1520  			TLS_CHACHA20_POLY1305_SHA256,
  1521  			TLS_AES_128_GCM_SHA256,
  1522  			TLS_AES_256_GCM_SHA384,
  1523  		}
  1524  	}
  1525  
  1526  	varDefaultCipherSuites = make([]uint16, 0, len(cipherSuites))
  1527  	varDefaultCipherSuites = append(varDefaultCipherSuites, topCipherSuites...)
  1528  
  1529  NextCipherSuite:
  1530  	for _, suite := range cipherSuites {
  1531  		if suite.flags&suiteDefaultOff != 0 {
  1532  			continue
  1533  		}
  1534  		for _, existing := range varDefaultCipherSuites {
  1535  			if existing == suite.id {
  1536  				continue NextCipherSuite
  1537  			}
  1538  		}
  1539  		varDefaultCipherSuites = append(varDefaultCipherSuites, suite.id)
  1540  	}
  1541  }
  1542  
  1543  func unexpectedMessageError(wanted, got interface{}) error {
  1544  	return fmt.Errorf("tls: received unexpected handshake message of type %T when waiting for %T", got, wanted)
  1545  }
  1546  
  1547  func isSupportedSignatureAlgorithm(sigAlg SignatureScheme, supportedSignatureAlgorithms []SignatureScheme) bool {
  1548  	for _, s := range supportedSignatureAlgorithms {
  1549  		if s == sigAlg {
  1550  			return true
  1551  		}
  1552  	}
  1553  	return false
  1554  }
  1555  
  1556  var aesgcmCiphers = map[uint16]bool{
  1557  	// 1.2
  1558  	TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256:   true,
  1559  	TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384:   true,
  1560  	TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256: true,
  1561  	TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384: true,
  1562  	// 1.3
  1563  	TLS_AES_128_GCM_SHA256: true,
  1564  	TLS_AES_256_GCM_SHA384: true,
  1565  }
  1566  
  1567  var nonAESGCMAEADCiphers = map[uint16]bool{
  1568  	// 1.2
  1569  	TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305:   true,
  1570  	TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305: true,
  1571  	// 1.3
  1572  	TLS_CHACHA20_POLY1305_SHA256: true,
  1573  }
  1574  
  1575  // aesgcmPreferred returns whether the first valid cipher in the preference list
  1576  // is an AES-GCM cipher, implying the peer has hardware support for it.
  1577  func aesgcmPreferred(ciphers []uint16) bool {
  1578  	for _, cID := range ciphers {
  1579  		c := cipherSuiteByID(cID)
  1580  		if c == nil {
  1581  			c13 := cipherSuiteTLS13ByID(cID)
  1582  			if c13 == nil {
  1583  				continue
  1584  			}
  1585  			return aesgcmCiphers[cID]
  1586  		}
  1587  		return aesgcmCiphers[cID]
  1588  	}
  1589  	return false
  1590  }
  1591  
  1592  // deprioritizeAES reorders cipher preference lists by rearranging
  1593  // adjacent AEAD ciphers such that AES-GCM based ciphers are moved
  1594  // after other AEAD ciphers. It returns a fresh slice.
  1595  func deprioritizeAES(ciphers []uint16) []uint16 {
  1596  	reordered := make([]uint16, len(ciphers))
  1597  	copy(reordered, ciphers)
  1598  	sort.SliceStable(reordered, func(i, j int) bool {
  1599  		return nonAESGCMAEADCiphers[reordered[i]] && aesgcmCiphers[reordered[j]]
  1600  	})
  1601  	return reordered
  1602  }