Source file src/crypto/tls/common.go

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

View as plain text