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

View as plain text