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