common.mx raw

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