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

View as plain text