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

View as plain text