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

View as plain text