Black Lives Matter. Support the Equal Justice Initiative.

Source file src/crypto/tls/common.go

Documentation: crypto/tls

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

View as plain text