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