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