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

View as plain text