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