github.com/ooni/psiphon/tunnel-core@v0.0.0-20230105123940-fe12a24c96ee/oovendor/qtls-go1-17/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-15 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  	// Deprected: 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  	// If zero, TLS 1.0 is currently taken as the minimum.
   677  	MinVersion uint16
   678  
   679  	// MaxVersion contains the maximum TLS version that is acceptable.
   680  	// If zero, the maximum version supported by this package is used,
   681  	// which is currently TLS 1.3.
   682  	MaxVersion uint16
   683  
   684  	// CurvePreferences contains the elliptic curves that will be used in
   685  	// an ECDHE handshake, in preference order. If empty, the default will
   686  	// be used. The client will use the first preference as the type for
   687  	// its key share in TLS 1.3. This may change in the future.
   688  	CurvePreferences []CurveID
   689  
   690  	// DynamicRecordSizingDisabled disables adaptive sizing of TLS records.
   691  	// When true, the largest possible TLS record size is always used. When
   692  	// false, the size of TLS records may be adjusted in an attempt to
   693  	// improve latency.
   694  	DynamicRecordSizingDisabled bool
   695  
   696  	// Renegotiation controls what types of renegotiation are supported.
   697  	// The default, none, is correct for the vast majority of applications.
   698  	Renegotiation RenegotiationSupport
   699  
   700  	// KeyLogWriter optionally specifies a destination for TLS master secrets
   701  	// in NSS key log format that can be used to allow external programs
   702  	// such as Wireshark to decrypt TLS connections.
   703  	// See https://developer.mozilla.org/en-US/docs/Mozilla/Projects/NSS/Key_Log_Format.
   704  	// Use of KeyLogWriter compromises security and should only be
   705  	// used for debugging.
   706  	KeyLogWriter io.Writer
   707  
   708  	// mutex protects sessionTicketKeys and autoSessionTicketKeys.
   709  	mutex sync.RWMutex
   710  	// sessionTicketKeys contains zero or more ticket keys. If set, it means the
   711  	// the keys were set with SessionTicketKey or SetSessionTicketKeys. The
   712  	// first key is used for new tickets and any subsequent keys can be used to
   713  	// decrypt old tickets. The slice contents are not protected by the mutex
   714  	// and are immutable.
   715  	sessionTicketKeys []ticketKey
   716  	// autoSessionTicketKeys is like sessionTicketKeys but is owned by the
   717  	// auto-rotation logic. See Config.ticketKeys.
   718  	autoSessionTicketKeys []ticketKey
   719  }
   720  
   721  // A RecordLayer handles encrypting and decrypting of TLS messages.
   722  type RecordLayer interface {
   723  	SetReadKey(encLevel EncryptionLevel, suite *CipherSuiteTLS13, trafficSecret []byte)
   724  	SetWriteKey(encLevel EncryptionLevel, suite *CipherSuiteTLS13, trafficSecret []byte)
   725  	ReadHandshakeMessage() ([]byte, error)
   726  	WriteRecord([]byte) (int, error)
   727  	SendAlert(uint8)
   728  }
   729  
   730  type ExtraConfig struct {
   731  	// GetExtensions, if not nil, is called before a message that allows
   732  	// sending of extensions is sent.
   733  	// Currently only implemented for the ClientHello message (for the client)
   734  	// and for the EncryptedExtensions message (for the server).
   735  	// Only valid for TLS 1.3.
   736  	GetExtensions func(handshakeMessageType uint8) []Extension
   737  
   738  	// ReceivedExtensions, if not nil, is called when a message that allows the
   739  	// inclusion of extensions is received.
   740  	// It is called with an empty slice of extensions, if the message didn't
   741  	// contain any extensions.
   742  	// Currently only implemented for the ClientHello message (sent by the
   743  	// client) and for the EncryptedExtensions message (sent by the server).
   744  	// Only valid for TLS 1.3.
   745  	ReceivedExtensions func(handshakeMessageType uint8, exts []Extension)
   746  
   747  	// AlternativeRecordLayer is used by QUIC
   748  	AlternativeRecordLayer RecordLayer
   749  
   750  	// Enforce the selection of a supported application protocol.
   751  	// Only works for TLS 1.3.
   752  	// If enabled, client and server have to agree on an application protocol.
   753  	// Otherwise, connection establishment fails.
   754  	EnforceNextProtoSelection bool
   755  
   756  	// If MaxEarlyData is greater than 0, the client will be allowed to send early
   757  	// data when resuming a session.
   758  	// Requires the AlternativeRecordLayer to be set.
   759  	//
   760  	// It has no meaning on the client.
   761  	MaxEarlyData uint32
   762  
   763  	// The Accept0RTT callback is called when the client offers 0-RTT.
   764  	// The server then has to decide if it wants to accept or reject 0-RTT.
   765  	// It is only used for servers.
   766  	Accept0RTT func(appData []byte) bool
   767  
   768  	// 0RTTRejected is called when the server rejectes 0-RTT.
   769  	// It is only used for clients.
   770  	Rejected0RTT func()
   771  
   772  	// If set, the client will export the 0-RTT key when resuming a session that
   773  	// allows sending of early data.
   774  	// Requires the AlternativeRecordLayer to be set.
   775  	//
   776  	// It has no meaning to the server.
   777  	Enable0RTT bool
   778  
   779  	// Is called when the client saves a session ticket to the session ticket.
   780  	// This gives the application the opportunity to save some data along with the ticket,
   781  	// which can be restored when the session ticket is used.
   782  	GetAppDataForSessionState func() []byte
   783  
   784  	// Is called when the client uses a session ticket.
   785  	// Restores the application data that was saved earlier on GetAppDataForSessionTicket.
   786  	SetAppDataFromSessionState func([]byte)
   787  
   788  	// [Psiphon]
   789  	// ClientHelloPRNG is used for Client Hello randomization and replay.
   790  	ClientHelloPRNG *prng.PRNG
   791  
   792  	// [Psiphon]
   793  	// GetClientHelloRandom is used to supply a specific value in the TLS
   794  	// Client Hello random field. This is used to send an anti-probing
   795  	// message, indistinguishable from random, that proves knowlegde of a
   796  	// shared secret key.
   797  	GetClientHelloRandom func() ([]byte, error)
   798  }
   799  
   800  // Clone clones.
   801  func (c *ExtraConfig) Clone() *ExtraConfig {
   802  	return &ExtraConfig{
   803  		GetExtensions:              c.GetExtensions,
   804  		ReceivedExtensions:         c.ReceivedExtensions,
   805  		AlternativeRecordLayer:     c.AlternativeRecordLayer,
   806  		EnforceNextProtoSelection:  c.EnforceNextProtoSelection,
   807  		MaxEarlyData:               c.MaxEarlyData,
   808  		Enable0RTT:                 c.Enable0RTT,
   809  		Accept0RTT:                 c.Accept0RTT,
   810  		Rejected0RTT:               c.Rejected0RTT,
   811  		GetAppDataForSessionState:  c.GetAppDataForSessionState,
   812  		SetAppDataFromSessionState: c.SetAppDataFromSessionState,
   813  	}
   814  }
   815  
   816  func (c *ExtraConfig) usesAlternativeRecordLayer() bool {
   817  	return c != nil && c.AlternativeRecordLayer != nil
   818  }
   819  
   820  const (
   821  	// ticketKeyNameLen is the number of bytes of identifier that is prepended to
   822  	// an encrypted session ticket in order to identify the key used to encrypt it.
   823  	ticketKeyNameLen = 16
   824  
   825  	// ticketKeyLifetime is how long a ticket key remains valid and can be used to
   826  	// resume a client connection.
   827  	ticketKeyLifetime = 7 * 24 * time.Hour // 7 days
   828  
   829  	// ticketKeyRotation is how often the server should rotate the session ticket key
   830  	// that is used for new tickets.
   831  	ticketKeyRotation = 24 * time.Hour
   832  )
   833  
   834  // ticketKey is the internal representation of a session ticket key.
   835  type ticketKey struct {
   836  	// keyName is an opaque byte string that serves to identify the session
   837  	// ticket key. It's exposed as plaintext in every session ticket.
   838  	keyName [ticketKeyNameLen]byte
   839  	aesKey  [16]byte
   840  	hmacKey [16]byte
   841  	// created is the time at which this ticket key was created. See Config.ticketKeys.
   842  	created time.Time
   843  }
   844  
   845  // ticketKeyFromBytes converts from the external representation of a session
   846  // ticket key to a ticketKey. Externally, session ticket keys are 32 random
   847  // bytes and this function expands that into sufficient name and key material.
   848  func (c *config) ticketKeyFromBytes(b [32]byte) (key ticketKey) {
   849  	hashed := sha512.Sum512(b[:])
   850  	copy(key.keyName[:], hashed[:ticketKeyNameLen])
   851  	copy(key.aesKey[:], hashed[ticketKeyNameLen:ticketKeyNameLen+16])
   852  	copy(key.hmacKey[:], hashed[ticketKeyNameLen+16:ticketKeyNameLen+32])
   853  	key.created = c.time()
   854  	return key
   855  }
   856  
   857  // maxSessionTicketLifetime is the maximum allowed lifetime of a TLS 1.3 session
   858  // ticket, and the lifetime we set for tickets we send.
   859  const maxSessionTicketLifetime = 7 * 24 * time.Hour
   860  
   861  // Clone returns a shallow clone of c or nil if c is nil. It is safe to clone a Config that is
   862  // being used concurrently by a TLS client or server.
   863  func (c *config) Clone() *config {
   864  	if c == nil {
   865  		return nil
   866  	}
   867  	c.mutex.RLock()
   868  	defer c.mutex.RUnlock()
   869  	return &config{
   870  		Rand:                        c.Rand,
   871  		Time:                        c.Time,
   872  		Certificates:                c.Certificates,
   873  		NameToCertificate:           c.NameToCertificate,
   874  		GetCertificate:              c.GetCertificate,
   875  		GetClientCertificate:        c.GetClientCertificate,
   876  		GetConfigForClient:          c.GetConfigForClient,
   877  		VerifyPeerCertificate:       c.VerifyPeerCertificate,
   878  		VerifyConnection:            c.VerifyConnection,
   879  		RootCAs:                     c.RootCAs,
   880  		NextProtos:                  c.NextProtos,
   881  		ServerName:                  c.ServerName,
   882  		ClientAuth:                  c.ClientAuth,
   883  		ClientCAs:                   c.ClientCAs,
   884  		InsecureSkipVerify:          c.InsecureSkipVerify,
   885  		CipherSuites:                c.CipherSuites,
   886  		PreferServerCipherSuites:    c.PreferServerCipherSuites,
   887  		SessionTicketsDisabled:      c.SessionTicketsDisabled,
   888  		SessionTicketKey:            c.SessionTicketKey,
   889  		ClientSessionCache:          c.ClientSessionCache,
   890  		MinVersion:                  c.MinVersion,
   891  		MaxVersion:                  c.MaxVersion,
   892  		CurvePreferences:            c.CurvePreferences,
   893  		DynamicRecordSizingDisabled: c.DynamicRecordSizingDisabled,
   894  		Renegotiation:               c.Renegotiation,
   895  		KeyLogWriter:                c.KeyLogWriter,
   896  		sessionTicketKeys:           c.sessionTicketKeys,
   897  		autoSessionTicketKeys:       c.autoSessionTicketKeys,
   898  	}
   899  }
   900  
   901  // deprecatedSessionTicketKey is set as the prefix of SessionTicketKey if it was
   902  // randomized for backwards compatibility but is not in use.
   903  var deprecatedSessionTicketKey = []byte("DEPRECATED")
   904  
   905  // initLegacySessionTicketKeyRLocked ensures the legacy SessionTicketKey field is
   906  // randomized if empty, and that sessionTicketKeys is populated from it otherwise.
   907  func (c *config) initLegacySessionTicketKeyRLocked() {
   908  	// Don't write if SessionTicketKey is already defined as our deprecated string,
   909  	// or if it is defined by the user but sessionTicketKeys is already set.
   910  	if c.SessionTicketKey != [32]byte{} &&
   911  		(bytes.HasPrefix(c.SessionTicketKey[:], deprecatedSessionTicketKey) || len(c.sessionTicketKeys) > 0) {
   912  		return
   913  	}
   914  
   915  	// We need to write some data, so get an exclusive lock and re-check any conditions.
   916  	c.mutex.RUnlock()
   917  	defer c.mutex.RLock()
   918  	c.mutex.Lock()
   919  	defer c.mutex.Unlock()
   920  	if c.SessionTicketKey == [32]byte{} {
   921  		if _, err := io.ReadFull(c.rand(), c.SessionTicketKey[:]); err != nil {
   922  			panic(fmt.Sprintf("tls: unable to generate random session ticket key: %v", err))
   923  		}
   924  		// Write the deprecated prefix at the beginning so we know we created
   925  		// it. This key with the DEPRECATED prefix isn't used as an actual
   926  		// session ticket key, and is only randomized in case the application
   927  		// reuses it for some reason.
   928  		copy(c.SessionTicketKey[:], deprecatedSessionTicketKey)
   929  	} else if !bytes.HasPrefix(c.SessionTicketKey[:], deprecatedSessionTicketKey) && len(c.sessionTicketKeys) == 0 {
   930  		c.sessionTicketKeys = []ticketKey{c.ticketKeyFromBytes(c.SessionTicketKey)}
   931  	}
   932  
   933  }
   934  
   935  // ticketKeys returns the ticketKeys for this connection.
   936  // If configForClient has explicitly set keys, those will
   937  // be returned. Otherwise, the keys on c will be used and
   938  // may be rotated if auto-managed.
   939  // During rotation, any expired session ticket keys are deleted from
   940  // c.sessionTicketKeys. If the session ticket key that is currently
   941  // encrypting tickets (ie. the first ticketKey in c.sessionTicketKeys)
   942  // is not fresh, then a new session ticket key will be
   943  // created and prepended to c.sessionTicketKeys.
   944  func (c *config) ticketKeys(configForClient *config) []ticketKey {
   945  	// If the ConfigForClient callback returned a Config with explicitly set
   946  	// keys, use those, otherwise just use the original Config.
   947  	if configForClient != nil {
   948  		configForClient.mutex.RLock()
   949  		if configForClient.SessionTicketsDisabled {
   950  			return nil
   951  		}
   952  		configForClient.initLegacySessionTicketKeyRLocked()
   953  		if len(configForClient.sessionTicketKeys) != 0 {
   954  			ret := configForClient.sessionTicketKeys
   955  			configForClient.mutex.RUnlock()
   956  			return ret
   957  		}
   958  		configForClient.mutex.RUnlock()
   959  	}
   960  
   961  	c.mutex.RLock()
   962  	defer c.mutex.RUnlock()
   963  	if c.SessionTicketsDisabled {
   964  		return nil
   965  	}
   966  	c.initLegacySessionTicketKeyRLocked()
   967  	if len(c.sessionTicketKeys) != 0 {
   968  		return c.sessionTicketKeys
   969  	}
   970  	// Fast path for the common case where the key is fresh enough.
   971  	if len(c.autoSessionTicketKeys) > 0 && c.time().Sub(c.autoSessionTicketKeys[0].created) < ticketKeyRotation {
   972  		return c.autoSessionTicketKeys
   973  	}
   974  
   975  	// autoSessionTicketKeys are managed by auto-rotation.
   976  	c.mutex.RUnlock()
   977  	defer c.mutex.RLock()
   978  	c.mutex.Lock()
   979  	defer c.mutex.Unlock()
   980  	// Re-check the condition in case it changed since obtaining the new lock.
   981  	if len(c.autoSessionTicketKeys) == 0 || c.time().Sub(c.autoSessionTicketKeys[0].created) >= ticketKeyRotation {
   982  		var newKey [32]byte
   983  		if _, err := io.ReadFull(c.rand(), newKey[:]); err != nil {
   984  			panic(fmt.Sprintf("unable to generate random session ticket key: %v", err))
   985  		}
   986  		valid := make([]ticketKey, 0, len(c.autoSessionTicketKeys)+1)
   987  		valid = append(valid, c.ticketKeyFromBytes(newKey))
   988  		for _, k := range c.autoSessionTicketKeys {
   989  			// While rotating the current key, also remove any expired ones.
   990  			if c.time().Sub(k.created) < ticketKeyLifetime {
   991  				valid = append(valid, k)
   992  			}
   993  		}
   994  		c.autoSessionTicketKeys = valid
   995  	}
   996  	return c.autoSessionTicketKeys
   997  }
   998  
   999  // SetSessionTicketKeys updates the session ticket keys for a server.
  1000  //
  1001  // The first key will be used when creating new tickets, while all keys can be
  1002  // used for decrypting tickets. It is safe to call this function while the
  1003  // server is running in order to rotate the session ticket keys. The function
  1004  // will panic if keys is empty.
  1005  //
  1006  // Calling this function will turn off automatic session ticket key rotation.
  1007  //
  1008  // If multiple servers are terminating connections for the same host they should
  1009  // all have the same session ticket keys. If the session ticket keys leaks,
  1010  // previously recorded and future TLS connections using those keys might be
  1011  // compromised.
  1012  func (c *config) SetSessionTicketKeys(keys [][32]byte) {
  1013  	if len(keys) == 0 {
  1014  		panic("tls: keys must have at least one key")
  1015  	}
  1016  
  1017  	newKeys := make([]ticketKey, len(keys))
  1018  	for i, bytes := range keys {
  1019  		newKeys[i] = c.ticketKeyFromBytes(bytes)
  1020  	}
  1021  
  1022  	c.mutex.Lock()
  1023  	c.sessionTicketKeys = newKeys
  1024  	c.mutex.Unlock()
  1025  }
  1026  
  1027  func (c *config) rand() io.Reader {
  1028  	r := c.Rand
  1029  	if r == nil {
  1030  		return rand.Reader
  1031  	}
  1032  	return r
  1033  }
  1034  
  1035  func (c *config) time() time.Time {
  1036  	t := c.Time
  1037  	if t == nil {
  1038  		t = time.Now
  1039  	}
  1040  	return t()
  1041  }
  1042  
  1043  func (c *config) cipherSuites() []uint16 {
  1044  	if c.CipherSuites != nil {
  1045  		return c.CipherSuites
  1046  	}
  1047  	return defaultCipherSuites
  1048  }
  1049  
  1050  var supportedVersions = []uint16{
  1051  	VersionTLS13,
  1052  	VersionTLS12,
  1053  	VersionTLS11,
  1054  	VersionTLS10,
  1055  }
  1056  
  1057  func (c *config) supportedVersions() []uint16 {
  1058  	versions := make([]uint16, 0, len(supportedVersions))
  1059  	for _, v := range supportedVersions {
  1060  		if c != nil && c.MinVersion != 0 && v < c.MinVersion {
  1061  			continue
  1062  		}
  1063  		if c != nil && c.MaxVersion != 0 && v > c.MaxVersion {
  1064  			continue
  1065  		}
  1066  		versions = append(versions, v)
  1067  	}
  1068  	return versions
  1069  }
  1070  
  1071  func (c *config) maxSupportedVersion() uint16 {
  1072  	supportedVersions := c.supportedVersions()
  1073  	if len(supportedVersions) == 0 {
  1074  		return 0
  1075  	}
  1076  	return supportedVersions[0]
  1077  }
  1078  
  1079  // supportedVersionsFromMax returns a list of supported versions derived from a
  1080  // legacy maximum version value. Note that only versions supported by this
  1081  // library are returned. Any newer peer will use supportedVersions anyway.
  1082  func supportedVersionsFromMax(maxVersion uint16) []uint16 {
  1083  	versions := make([]uint16, 0, len(supportedVersions))
  1084  	for _, v := range supportedVersions {
  1085  		if v > maxVersion {
  1086  			continue
  1087  		}
  1088  		versions = append(versions, v)
  1089  	}
  1090  	return versions
  1091  }
  1092  
  1093  var defaultCurvePreferences = []CurveID{X25519, CurveP256, CurveP384, CurveP521}
  1094  
  1095  func (c *config) curvePreferences() []CurveID {
  1096  	if c == nil || len(c.CurvePreferences) == 0 {
  1097  		return defaultCurvePreferences
  1098  	}
  1099  	return c.CurvePreferences
  1100  }
  1101  
  1102  func (c *config) supportsCurve(curve CurveID) bool {
  1103  	for _, cc := range c.curvePreferences() {
  1104  		if cc == curve {
  1105  			return true
  1106  		}
  1107  	}
  1108  	return false
  1109  }
  1110  
  1111  // mutualVersion returns the protocol version to use given the advertised
  1112  // versions of the peer. Priority is given to the peer preference order.
  1113  func (c *config) mutualVersion(peerVersions []uint16) (uint16, bool) {
  1114  	supportedVersions := c.supportedVersions()
  1115  	for _, peerVersion := range peerVersions {
  1116  		for _, v := range supportedVersions {
  1117  			if v == peerVersion {
  1118  				return v, true
  1119  			}
  1120  		}
  1121  	}
  1122  	return 0, false
  1123  }
  1124  
  1125  var errNoCertificates = errors.New("tls: no certificates configured")
  1126  
  1127  // getCertificate returns the best certificate for the given ClientHelloInfo,
  1128  // defaulting to the first element of c.Certificates.
  1129  func (c *config) getCertificate(clientHello *ClientHelloInfo) (*Certificate, error) {
  1130  	if c.GetCertificate != nil &&
  1131  		(len(c.Certificates) == 0 || len(clientHello.ServerName) > 0) {
  1132  		cert, err := c.GetCertificate(clientHello)
  1133  		if cert != nil || err != nil {
  1134  			return cert, err
  1135  		}
  1136  	}
  1137  
  1138  	if len(c.Certificates) == 0 {
  1139  		return nil, errNoCertificates
  1140  	}
  1141  
  1142  	if len(c.Certificates) == 1 {
  1143  		// There's only one choice, so no point doing any work.
  1144  		return &c.Certificates[0], nil
  1145  	}
  1146  
  1147  	if c.NameToCertificate != nil {
  1148  		name := strings.ToLower(clientHello.ServerName)
  1149  		if cert, ok := c.NameToCertificate[name]; ok {
  1150  			return cert, nil
  1151  		}
  1152  		if len(name) > 0 {
  1153  			labels := strings.Split(name, ".")
  1154  			labels[0] = "*"
  1155  			wildcardName := strings.Join(labels, ".")
  1156  			if cert, ok := c.NameToCertificate[wildcardName]; ok {
  1157  				return cert, nil
  1158  			}
  1159  		}
  1160  	}
  1161  
  1162  	for _, cert := range c.Certificates {
  1163  		if err := clientHello.SupportsCertificate(&cert); err == nil {
  1164  			return &cert, nil
  1165  		}
  1166  	}
  1167  
  1168  	// If nothing matches, return the first certificate.
  1169  	return &c.Certificates[0], nil
  1170  }
  1171  
  1172  // SupportsCertificate returns nil if the provided certificate is supported by
  1173  // the client that sent the ClientHello. Otherwise, it returns an error
  1174  // describing the reason for the incompatibility.
  1175  //
  1176  // If this ClientHelloInfo was passed to a GetConfigForClient or GetCertificate
  1177  // callback, this method will take into account the associated Config. Note that
  1178  // if GetConfigForClient returns a different Config, the change can't be
  1179  // accounted for by this method.
  1180  //
  1181  // This function will call x509.ParseCertificate unless c.Leaf is set, which can
  1182  // incur a significant performance cost.
  1183  func (chi *clientHelloInfo) SupportsCertificate(c *Certificate) error {
  1184  	// Note we don't currently support certificate_authorities nor
  1185  	// signature_algorithms_cert, and don't check the algorithms of the
  1186  	// signatures on the chain (which anyway are a SHOULD, see RFC 8446,
  1187  	// Section 4.4.2.2).
  1188  
  1189  	config := chi.config
  1190  	if config == nil {
  1191  		config = &Config{}
  1192  	}
  1193  	conf := fromConfig(config)
  1194  	vers, ok := conf.mutualVersion(chi.SupportedVersions)
  1195  	if !ok {
  1196  		return errors.New("no mutually supported protocol versions")
  1197  	}
  1198  
  1199  	// If the client specified the name they are trying to connect to, the
  1200  	// certificate needs to be valid for it.
  1201  	if chi.ServerName != "" {
  1202  		x509Cert, err := leafCertificate(c)
  1203  		if err != nil {
  1204  			return fmt.Errorf("failed to parse certificate: %w", err)
  1205  		}
  1206  		if err := x509Cert.VerifyHostname(chi.ServerName); err != nil {
  1207  			return fmt.Errorf("certificate is not valid for requested server name: %w", err)
  1208  		}
  1209  	}
  1210  
  1211  	// supportsRSAFallback returns nil if the certificate and connection support
  1212  	// the static RSA key exchange, and unsupported otherwise. The logic for
  1213  	// supporting static RSA is completely disjoint from the logic for
  1214  	// supporting signed key exchanges, so we just check it as a fallback.
  1215  	supportsRSAFallback := func(unsupported error) error {
  1216  		// TLS 1.3 dropped support for the static RSA key exchange.
  1217  		if vers == VersionTLS13 {
  1218  			return unsupported
  1219  		}
  1220  		// The static RSA key exchange works by decrypting a challenge with the
  1221  		// RSA private key, not by signing, so check the PrivateKey implements
  1222  		// crypto.Decrypter, like *rsa.PrivateKey does.
  1223  		if priv, ok := c.PrivateKey.(crypto.Decrypter); ok {
  1224  			if _, ok := priv.Public().(*rsa.PublicKey); !ok {
  1225  				return unsupported
  1226  			}
  1227  		} else {
  1228  			return unsupported
  1229  		}
  1230  		// Finally, there needs to be a mutual cipher suite that uses the static
  1231  		// RSA key exchange instead of ECDHE.
  1232  		rsaCipherSuite := selectCipherSuite(chi.CipherSuites, conf.cipherSuites(), func(c *cipherSuite) bool {
  1233  			if c.flags&suiteECDHE != 0 {
  1234  				return false
  1235  			}
  1236  			if vers < VersionTLS12 && c.flags&suiteTLS12 != 0 {
  1237  				return false
  1238  			}
  1239  			return true
  1240  		})
  1241  		if rsaCipherSuite == nil {
  1242  			return unsupported
  1243  		}
  1244  		return nil
  1245  	}
  1246  
  1247  	// If the client sent the signature_algorithms extension, ensure it supports
  1248  	// schemes we can use with this certificate and TLS version.
  1249  	if len(chi.SignatureSchemes) > 0 {
  1250  		if _, err := selectSignatureScheme(vers, c, chi.SignatureSchemes); err != nil {
  1251  			return supportsRSAFallback(err)
  1252  		}
  1253  	}
  1254  
  1255  	// In TLS 1.3 we are done because supported_groups is only relevant to the
  1256  	// ECDHE computation, point format negotiation is removed, cipher suites are
  1257  	// only relevant to the AEAD choice, and static RSA does not exist.
  1258  	if vers == VersionTLS13 {
  1259  		return nil
  1260  	}
  1261  
  1262  	// The only signed key exchange we support is ECDHE.
  1263  	if !supportsECDHE(conf, chi.SupportedCurves, chi.SupportedPoints) {
  1264  		return supportsRSAFallback(errors.New("client doesn't support ECDHE, can only use legacy RSA key exchange"))
  1265  	}
  1266  
  1267  	var ecdsaCipherSuite bool
  1268  	if priv, ok := c.PrivateKey.(crypto.Signer); ok {
  1269  		switch pub := priv.Public().(type) {
  1270  		case *ecdsa.PublicKey:
  1271  			var curve CurveID
  1272  			switch pub.Curve {
  1273  			case elliptic.P256():
  1274  				curve = CurveP256
  1275  			case elliptic.P384():
  1276  				curve = CurveP384
  1277  			case elliptic.P521():
  1278  				curve = CurveP521
  1279  			default:
  1280  				return supportsRSAFallback(unsupportedCertificateError(c))
  1281  			}
  1282  			var curveOk bool
  1283  			for _, c := range chi.SupportedCurves {
  1284  				if c == curve && conf.supportsCurve(c) {
  1285  					curveOk = true
  1286  					break
  1287  				}
  1288  			}
  1289  			if !curveOk {
  1290  				return errors.New("client doesn't support certificate curve")
  1291  			}
  1292  			ecdsaCipherSuite = true
  1293  		case ed25519.PublicKey:
  1294  			if vers < VersionTLS12 || len(chi.SignatureSchemes) == 0 {
  1295  				return errors.New("connection doesn't support Ed25519")
  1296  			}
  1297  			ecdsaCipherSuite = true
  1298  		case *rsa.PublicKey:
  1299  		default:
  1300  			return supportsRSAFallback(unsupportedCertificateError(c))
  1301  		}
  1302  	} else {
  1303  		return supportsRSAFallback(unsupportedCertificateError(c))
  1304  	}
  1305  
  1306  	// Make sure that there is a mutually supported cipher suite that works with
  1307  	// this certificate. Cipher suite selection will then apply the logic in
  1308  	// reverse to pick it. See also serverHandshakeState.cipherSuiteOk.
  1309  	cipherSuite := selectCipherSuite(chi.CipherSuites, conf.cipherSuites(), func(c *cipherSuite) bool {
  1310  		if c.flags&suiteECDHE == 0 {
  1311  			return false
  1312  		}
  1313  		if c.flags&suiteECSign != 0 {
  1314  			if !ecdsaCipherSuite {
  1315  				return false
  1316  			}
  1317  		} else {
  1318  			if ecdsaCipherSuite {
  1319  				return false
  1320  			}
  1321  		}
  1322  		if vers < VersionTLS12 && c.flags&suiteTLS12 != 0 {
  1323  			return false
  1324  		}
  1325  		return true
  1326  	})
  1327  	if cipherSuite == nil {
  1328  		return supportsRSAFallback(errors.New("client doesn't support any cipher suites compatible with the certificate"))
  1329  	}
  1330  
  1331  	return nil
  1332  }
  1333  
  1334  // BuildNameToCertificate parses c.Certificates and builds c.NameToCertificate
  1335  // from the CommonName and SubjectAlternateName fields of each of the leaf
  1336  // certificates.
  1337  //
  1338  // Deprecated: NameToCertificate only allows associating a single certificate
  1339  // with a given name. Leave that field nil to let the library select the first
  1340  // compatible chain from Certificates.
  1341  func (c *config) BuildNameToCertificate() {
  1342  	c.NameToCertificate = make(map[string]*Certificate)
  1343  	for i := range c.Certificates {
  1344  		cert := &c.Certificates[i]
  1345  		x509Cert, err := leafCertificate(cert)
  1346  		if err != nil {
  1347  			continue
  1348  		}
  1349  		// If SANs are *not* present, some clients will consider the certificate
  1350  		// valid for the name in the Common Name.
  1351  		if x509Cert.Subject.CommonName != "" && len(x509Cert.DNSNames) == 0 {
  1352  			c.NameToCertificate[x509Cert.Subject.CommonName] = cert
  1353  		}
  1354  		for _, san := range x509Cert.DNSNames {
  1355  			c.NameToCertificate[san] = cert
  1356  		}
  1357  	}
  1358  }
  1359  
  1360  const (
  1361  	keyLogLabelTLS12           = "CLIENT_RANDOM"
  1362  	keyLogLabelEarlyTraffic    = "CLIENT_EARLY_TRAFFIC_SECRET"
  1363  	keyLogLabelClientHandshake = "CLIENT_HANDSHAKE_TRAFFIC_SECRET"
  1364  	keyLogLabelServerHandshake = "SERVER_HANDSHAKE_TRAFFIC_SECRET"
  1365  	keyLogLabelClientTraffic   = "CLIENT_TRAFFIC_SECRET_0"
  1366  	keyLogLabelServerTraffic   = "SERVER_TRAFFIC_SECRET_0"
  1367  )
  1368  
  1369  func (c *config) writeKeyLog(label string, clientRandom, secret []byte) error {
  1370  	if c.KeyLogWriter == nil {
  1371  		return nil
  1372  	}
  1373  
  1374  	logLine := []byte(fmt.Sprintf("%s %x %x\n", label, clientRandom, secret))
  1375  
  1376  	writerMutex.Lock()
  1377  	_, err := c.KeyLogWriter.Write(logLine)
  1378  	writerMutex.Unlock()
  1379  
  1380  	return err
  1381  }
  1382  
  1383  // writerMutex protects all KeyLogWriters globally. It is rarely enabled,
  1384  // and is only for debugging, so a global mutex saves space.
  1385  var writerMutex sync.Mutex
  1386  
  1387  // A Certificate is a chain of one or more certificates, leaf first.
  1388  type Certificate = tls.Certificate
  1389  
  1390  // leaf returns the parsed leaf certificate, either from c.Leaf or by parsing
  1391  // the corresponding c.Certificate[0].
  1392  func leafCertificate(c *Certificate) (*x509.Certificate, error) {
  1393  	if c.Leaf != nil {
  1394  		return c.Leaf, nil
  1395  	}
  1396  	return x509.ParseCertificate(c.Certificate[0])
  1397  }
  1398  
  1399  type handshakeMessage interface {
  1400  	marshal() []byte
  1401  	unmarshal([]byte) bool
  1402  }
  1403  
  1404  // lruSessionCache is a ClientSessionCache implementation that uses an LRU
  1405  // caching strategy.
  1406  type lruSessionCache struct {
  1407  	sync.Mutex
  1408  
  1409  	m        map[string]*list.Element
  1410  	q        *list.List
  1411  	capacity int
  1412  }
  1413  
  1414  type lruSessionCacheEntry struct {
  1415  	sessionKey string
  1416  	state      *ClientSessionState
  1417  }
  1418  
  1419  // NewLRUClientSessionCache returns a ClientSessionCache with the given
  1420  // capacity that uses an LRU strategy. If capacity is < 1, a default capacity
  1421  // is used instead.
  1422  func NewLRUClientSessionCache(capacity int) ClientSessionCache {
  1423  	const defaultSessionCacheCapacity = 64
  1424  
  1425  	if capacity < 1 {
  1426  		capacity = defaultSessionCacheCapacity
  1427  	}
  1428  	return &lruSessionCache{
  1429  		m:        make(map[string]*list.Element),
  1430  		q:        list.New(),
  1431  		capacity: capacity,
  1432  	}
  1433  }
  1434  
  1435  // Put adds the provided (sessionKey, cs) pair to the cache. If cs is nil, the entry
  1436  // corresponding to sessionKey is removed from the cache instead.
  1437  func (c *lruSessionCache) Put(sessionKey string, cs *ClientSessionState) {
  1438  	c.Lock()
  1439  	defer c.Unlock()
  1440  
  1441  	if elem, ok := c.m[sessionKey]; ok {
  1442  		if cs == nil {
  1443  			c.q.Remove(elem)
  1444  			delete(c.m, sessionKey)
  1445  		} else {
  1446  			entry := elem.Value.(*lruSessionCacheEntry)
  1447  			entry.state = cs
  1448  			c.q.MoveToFront(elem)
  1449  		}
  1450  		return
  1451  	}
  1452  
  1453  	if c.q.Len() < c.capacity {
  1454  		entry := &lruSessionCacheEntry{sessionKey, cs}
  1455  		c.m[sessionKey] = c.q.PushFront(entry)
  1456  		return
  1457  	}
  1458  
  1459  	elem := c.q.Back()
  1460  	entry := elem.Value.(*lruSessionCacheEntry)
  1461  	delete(c.m, entry.sessionKey)
  1462  	entry.sessionKey = sessionKey
  1463  	entry.state = cs
  1464  	c.q.MoveToFront(elem)
  1465  	c.m[sessionKey] = elem
  1466  }
  1467  
  1468  // Get returns the ClientSessionState value associated with a given key. It
  1469  // returns (nil, false) if no value is found.
  1470  func (c *lruSessionCache) Get(sessionKey string) (*ClientSessionState, bool) {
  1471  	c.Lock()
  1472  	defer c.Unlock()
  1473  
  1474  	if elem, ok := c.m[sessionKey]; ok {
  1475  		c.q.MoveToFront(elem)
  1476  		return elem.Value.(*lruSessionCacheEntry).state, true
  1477  	}
  1478  	return nil, false
  1479  }
  1480  
  1481  var emptyConfig Config
  1482  
  1483  func defaultConfig() *Config {
  1484  	return &emptyConfig
  1485  }
  1486  
  1487  func unexpectedMessageError(wanted, got interface{}) error {
  1488  	return fmt.Errorf("tls: received unexpected handshake message of type %T when waiting for %T", got, wanted)
  1489  }
  1490  
  1491  func isSupportedSignatureAlgorithm(sigAlg SignatureScheme, supportedSignatureAlgorithms []SignatureScheme) bool {
  1492  	for _, s := range supportedSignatureAlgorithms {
  1493  		if s == sigAlg {
  1494  			return true
  1495  		}
  1496  	}
  1497  	return false
  1498  }