...

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

View as plain text