...

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  // 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  	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  	// Deprected: 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  	// If zero, TLS 1.0 is currently taken as the minimum.
	 686  	MinVersion uint16
	 687  
	 688  	// MaxVersion contains the maximum TLS version that is acceptable.
	 689  	// If zero, the maximum version supported by this package is used,
	 690  	// which is currently TLS 1.3.
	 691  	MaxVersion uint16
	 692  
	 693  	// CurvePreferences contains the elliptic curves that will be used in
	 694  	// an ECDHE handshake, in preference order. If empty, the default will
	 695  	// be used. The client will use the first preference as the type for
	 696  	// its key share in TLS 1.3. This may change in the future.
	 697  	CurvePreferences []CurveID
	 698  
	 699  	// DynamicRecordSizingDisabled disables adaptive sizing of TLS records.
	 700  	// When true, the largest possible TLS record size is always used. When
	 701  	// false, the size of TLS records may be adjusted in an attempt to
	 702  	// improve latency.
	 703  	DynamicRecordSizingDisabled bool
	 704  
	 705  	// Renegotiation controls what types of renegotiation are supported.
	 706  	// The default, none, is correct for the vast majority of applications.
	 707  	Renegotiation RenegotiationSupport
	 708  
	 709  	// KeyLogWriter optionally specifies a destination for TLS master secrets
	 710  	// in NSS key log format that can be used to allow external programs
	 711  	// such as Wireshark to decrypt TLS connections.
	 712  	// See https://developer.mozilla.org/en-US/docs/Mozilla/Projects/NSS/Key_Log_Format.
	 713  	// Use of KeyLogWriter compromises security and should only be
	 714  	// used for debugging.
	 715  	KeyLogWriter io.Writer
	 716  
	 717  	// mutex protects sessionTicketKeys and autoSessionTicketKeys.
	 718  	mutex sync.RWMutex
	 719  	// sessionTicketKeys contains zero or more ticket keys. If set, it means the
	 720  	// the keys were set with SessionTicketKey or SetSessionTicketKeys. The
	 721  	// first key is used for new tickets and any subsequent keys can be used to
	 722  	// decrypt old tickets. The slice contents are not protected by the mutex
	 723  	// and are immutable.
	 724  	sessionTicketKeys []ticketKey
	 725  	// autoSessionTicketKeys is like sessionTicketKeys but is owned by the
	 726  	// auto-rotation logic. See Config.ticketKeys.
	 727  	autoSessionTicketKeys []ticketKey
	 728  }
	 729  
	 730  const (
	 731  	// ticketKeyNameLen is the number of bytes of identifier that is prepended to
	 732  	// an encrypted session ticket in order to identify the key used to encrypt it.
	 733  	ticketKeyNameLen = 16
	 734  
	 735  	// ticketKeyLifetime is how long a ticket key remains valid and can be used to
	 736  	// resume a client connection.
	 737  	ticketKeyLifetime = 7 * 24 * time.Hour // 7 days
	 738  
	 739  	// ticketKeyRotation is how often the server should rotate the session ticket key
	 740  	// that is used for new tickets.
	 741  	ticketKeyRotation = 24 * time.Hour
	 742  )
	 743  
	 744  // ticketKey is the internal representation of a session ticket key.
	 745  type ticketKey struct {
	 746  	// keyName is an opaque byte string that serves to identify the session
	 747  	// ticket key. It's exposed as plaintext in every session ticket.
	 748  	keyName [ticketKeyNameLen]byte
	 749  	aesKey	[16]byte
	 750  	hmacKey [16]byte
	 751  	// created is the time at which this ticket key was created. See Config.ticketKeys.
	 752  	created time.Time
	 753  }
	 754  
	 755  // ticketKeyFromBytes converts from the external representation of a session
	 756  // ticket key to a ticketKey. Externally, session ticket keys are 32 random
	 757  // bytes and this function expands that into sufficient name and key material.
	 758  func (c *Config) ticketKeyFromBytes(b [32]byte) (key ticketKey) {
	 759  	hashed := sha512.Sum512(b[:])
	 760  	copy(key.keyName[:], hashed[:ticketKeyNameLen])
	 761  	copy(key.aesKey[:], hashed[ticketKeyNameLen:ticketKeyNameLen+16])
	 762  	copy(key.hmacKey[:], hashed[ticketKeyNameLen+16:ticketKeyNameLen+32])
	 763  	key.created = c.time()
	 764  	return key
	 765  }
	 766  
	 767  // maxSessionTicketLifetime is the maximum allowed lifetime of a TLS 1.3 session
	 768  // ticket, and the lifetime we set for tickets we send.
	 769  const maxSessionTicketLifetime = 7 * 24 * time.Hour
	 770  
	 771  // Clone returns a shallow clone of c or nil if c is nil. It is safe to clone a Config that is
	 772  // being used concurrently by a TLS client or server.
	 773  func (c *Config) Clone() *Config {
	 774  	if c == nil {
	 775  		return nil
	 776  	}
	 777  	c.mutex.RLock()
	 778  	defer c.mutex.RUnlock()
	 779  	return &Config{
	 780  		Rand:												c.Rand,
	 781  		Time:												c.Time,
	 782  		Certificates:								c.Certificates,
	 783  		NameToCertificate:					 c.NameToCertificate,
	 784  		GetCertificate:							c.GetCertificate,
	 785  		GetClientCertificate:				c.GetClientCertificate,
	 786  		GetConfigForClient:					c.GetConfigForClient,
	 787  		VerifyPeerCertificate:			 c.VerifyPeerCertificate,
	 788  		VerifyConnection:						c.VerifyConnection,
	 789  		RootCAs:										 c.RootCAs,
	 790  		NextProtos:									c.NextProtos,
	 791  		ServerName:									c.ServerName,
	 792  		ClientAuth:									c.ClientAuth,
	 793  		ClientCAs:									 c.ClientCAs,
	 794  		InsecureSkipVerify:					c.InsecureSkipVerify,
	 795  		CipherSuites:								c.CipherSuites,
	 796  		PreferServerCipherSuites:		c.PreferServerCipherSuites,
	 797  		SessionTicketsDisabled:			c.SessionTicketsDisabled,
	 798  		SessionTicketKey:						c.SessionTicketKey,
	 799  		ClientSessionCache:					c.ClientSessionCache,
	 800  		MinVersion:									c.MinVersion,
	 801  		MaxVersion:									c.MaxVersion,
	 802  		CurvePreferences:						c.CurvePreferences,
	 803  		DynamicRecordSizingDisabled: c.DynamicRecordSizingDisabled,
	 804  		Renegotiation:							 c.Renegotiation,
	 805  		KeyLogWriter:								c.KeyLogWriter,
	 806  		sessionTicketKeys:					 c.sessionTicketKeys,
	 807  		autoSessionTicketKeys:			 c.autoSessionTicketKeys,
	 808  	}
	 809  }
	 810  
	 811  // deprecatedSessionTicketKey is set as the prefix of SessionTicketKey if it was
	 812  // randomized for backwards compatibility but is not in use.
	 813  var deprecatedSessionTicketKey = []byte("DEPRECATED")
	 814  
	 815  // initLegacySessionTicketKeyRLocked ensures the legacy SessionTicketKey field is
	 816  // randomized if empty, and that sessionTicketKeys is populated from it otherwise.
	 817  func (c *Config) initLegacySessionTicketKeyRLocked() {
	 818  	// Don't write if SessionTicketKey is already defined as our deprecated string,
	 819  	// or if it is defined by the user but sessionTicketKeys is already set.
	 820  	if c.SessionTicketKey != [32]byte{} &&
	 821  		(bytes.HasPrefix(c.SessionTicketKey[:], deprecatedSessionTicketKey) || len(c.sessionTicketKeys) > 0) {
	 822  		return
	 823  	}
	 824  
	 825  	// We need to write some data, so get an exclusive lock and re-check any conditions.
	 826  	c.mutex.RUnlock()
	 827  	defer c.mutex.RLock()
	 828  	c.mutex.Lock()
	 829  	defer c.mutex.Unlock()
	 830  	if c.SessionTicketKey == [32]byte{} {
	 831  		if _, err := io.ReadFull(c.rand(), c.SessionTicketKey[:]); err != nil {
	 832  			panic(fmt.Sprintf("tls: unable to generate random session ticket key: %v", err))
	 833  		}
	 834  		// Write the deprecated prefix at the beginning so we know we created
	 835  		// it. This key with the DEPRECATED prefix isn't used as an actual
	 836  		// session ticket key, and is only randomized in case the application
	 837  		// reuses it for some reason.
	 838  		copy(c.SessionTicketKey[:], deprecatedSessionTicketKey)
	 839  	} else if !bytes.HasPrefix(c.SessionTicketKey[:], deprecatedSessionTicketKey) && len(c.sessionTicketKeys) == 0 {
	 840  		c.sessionTicketKeys = []ticketKey{c.ticketKeyFromBytes(c.SessionTicketKey)}
	 841  	}
	 842  
	 843  }
	 844  
	 845  // ticketKeys returns the ticketKeys for this connection.
	 846  // If configForClient has explicitly set keys, those will
	 847  // be returned. Otherwise, the keys on c will be used and
	 848  // may be rotated if auto-managed.
	 849  // During rotation, any expired session ticket keys are deleted from
	 850  // c.sessionTicketKeys. If the session ticket key that is currently
	 851  // encrypting tickets (ie. the first ticketKey in c.sessionTicketKeys)
	 852  // is not fresh, then a new session ticket key will be
	 853  // created and prepended to c.sessionTicketKeys.
	 854  func (c *Config) ticketKeys(configForClient *Config) []ticketKey {
	 855  	// If the ConfigForClient callback returned a Config with explicitly set
	 856  	// keys, use those, otherwise just use the original Config.
	 857  	if configForClient != nil {
	 858  		configForClient.mutex.RLock()
	 859  		if configForClient.SessionTicketsDisabled {
	 860  			return nil
	 861  		}
	 862  		configForClient.initLegacySessionTicketKeyRLocked()
	 863  		if len(configForClient.sessionTicketKeys) != 0 {
	 864  			ret := configForClient.sessionTicketKeys
	 865  			configForClient.mutex.RUnlock()
	 866  			return ret
	 867  		}
	 868  		configForClient.mutex.RUnlock()
	 869  	}
	 870  
	 871  	c.mutex.RLock()
	 872  	defer c.mutex.RUnlock()
	 873  	if c.SessionTicketsDisabled {
	 874  		return nil
	 875  	}
	 876  	c.initLegacySessionTicketKeyRLocked()
	 877  	if len(c.sessionTicketKeys) != 0 {
	 878  		return c.sessionTicketKeys
	 879  	}
	 880  	// Fast path for the common case where the key is fresh enough.
	 881  	if len(c.autoSessionTicketKeys) > 0 && c.time().Sub(c.autoSessionTicketKeys[0].created) < ticketKeyRotation {
	 882  		return c.autoSessionTicketKeys
	 883  	}
	 884  
	 885  	// autoSessionTicketKeys are managed by auto-rotation.
	 886  	c.mutex.RUnlock()
	 887  	defer c.mutex.RLock()
	 888  	c.mutex.Lock()
	 889  	defer c.mutex.Unlock()
	 890  	// Re-check the condition in case it changed since obtaining the new lock.
	 891  	if len(c.autoSessionTicketKeys) == 0 || c.time().Sub(c.autoSessionTicketKeys[0].created) >= ticketKeyRotation {
	 892  		var newKey [32]byte
	 893  		if _, err := io.ReadFull(c.rand(), newKey[:]); err != nil {
	 894  			panic(fmt.Sprintf("unable to generate random session ticket key: %v", err))
	 895  		}
	 896  		valid := make([]ticketKey, 0, len(c.autoSessionTicketKeys)+1)
	 897  		valid = append(valid, c.ticketKeyFromBytes(newKey))
	 898  		for _, k := range c.autoSessionTicketKeys {
	 899  			// While rotating the current key, also remove any expired ones.
	 900  			if c.time().Sub(k.created) < ticketKeyLifetime {
	 901  				valid = append(valid, k)
	 902  			}
	 903  		}
	 904  		c.autoSessionTicketKeys = valid
	 905  	}
	 906  	return c.autoSessionTicketKeys
	 907  }
	 908  
	 909  // SetSessionTicketKeys updates the session ticket keys for a server.
	 910  //
	 911  // The first key will be used when creating new tickets, while all keys can be
	 912  // used for decrypting tickets. It is safe to call this function while the
	 913  // server is running in order to rotate the session ticket keys. The function
	 914  // will panic if keys is empty.
	 915  //
	 916  // Calling this function will turn off automatic session ticket key rotation.
	 917  //
	 918  // If multiple servers are terminating connections for the same host they should
	 919  // all have the same session ticket keys. If the session ticket keys leaks,
	 920  // previously recorded and future TLS connections using those keys might be
	 921  // compromised.
	 922  func (c *Config) SetSessionTicketKeys(keys [][32]byte) {
	 923  	if len(keys) == 0 {
	 924  		panic("tls: keys must have at least one key")
	 925  	}
	 926  
	 927  	newKeys := make([]ticketKey, len(keys))
	 928  	for i, bytes := range keys {
	 929  		newKeys[i] = c.ticketKeyFromBytes(bytes)
	 930  	}
	 931  
	 932  	c.mutex.Lock()
	 933  	c.sessionTicketKeys = newKeys
	 934  	c.mutex.Unlock()
	 935  }
	 936  
	 937  func (c *Config) rand() io.Reader {
	 938  	r := c.Rand
	 939  	if r == nil {
	 940  		return rand.Reader
	 941  	}
	 942  	return r
	 943  }
	 944  
	 945  func (c *Config) time() time.Time {
	 946  	t := c.Time
	 947  	if t == nil {
	 948  		t = time.Now
	 949  	}
	 950  	return t()
	 951  }
	 952  
	 953  func (c *Config) cipherSuites() []uint16 {
	 954  	if c.CipherSuites != nil {
	 955  		return c.CipherSuites
	 956  	}
	 957  	return defaultCipherSuites
	 958  }
	 959  
	 960  var supportedVersions = []uint16{
	 961  	VersionTLS13,
	 962  	VersionTLS12,
	 963  	VersionTLS11,
	 964  	VersionTLS10,
	 965  }
	 966  
	 967  func (c *Config) supportedVersions() []uint16 {
	 968  	versions := make([]uint16, 0, len(supportedVersions))
	 969  	for _, v := range supportedVersions {
	 970  		if c != nil && c.MinVersion != 0 && v < c.MinVersion {
	 971  			continue
	 972  		}
	 973  		if c != nil && c.MaxVersion != 0 && v > c.MaxVersion {
	 974  			continue
	 975  		}
	 976  		versions = append(versions, v)
	 977  	}
	 978  	return versions
	 979  }
	 980  
	 981  func (c *Config) maxSupportedVersion() uint16 {
	 982  	supportedVersions := c.supportedVersions()
	 983  	if len(supportedVersions) == 0 {
	 984  		return 0
	 985  	}
	 986  	return supportedVersions[0]
	 987  }
	 988  
	 989  // supportedVersionsFromMax returns a list of supported versions derived from a
	 990  // legacy maximum version value. Note that only versions supported by this
	 991  // library are returned. Any newer peer will use supportedVersions anyway.
	 992  func supportedVersionsFromMax(maxVersion uint16) []uint16 {
	 993  	versions := make([]uint16, 0, len(supportedVersions))
	 994  	for _, v := range supportedVersions {
	 995  		if v > maxVersion {
	 996  			continue
	 997  		}
	 998  		versions = append(versions, v)
	 999  	}
	1000  	return versions
	1001  }
	1002  
	1003  var defaultCurvePreferences = []CurveID{X25519, CurveP256, CurveP384, CurveP521}
	1004  
	1005  func (c *Config) curvePreferences() []CurveID {
	1006  	if c == nil || len(c.CurvePreferences) == 0 {
	1007  		return defaultCurvePreferences
	1008  	}
	1009  	return c.CurvePreferences
	1010  }
	1011  
	1012  func (c *Config) supportsCurve(curve CurveID) bool {
	1013  	for _, cc := range c.curvePreferences() {
	1014  		if cc == curve {
	1015  			return true
	1016  		}
	1017  	}
	1018  	return false
	1019  }
	1020  
	1021  // mutualVersion returns the protocol version to use given the advertised
	1022  // versions of the peer. Priority is given to the peer preference order.
	1023  func (c *Config) mutualVersion(peerVersions []uint16) (uint16, bool) {
	1024  	supportedVersions := c.supportedVersions()
	1025  	for _, peerVersion := range peerVersions {
	1026  		for _, v := range supportedVersions {
	1027  			if v == peerVersion {
	1028  				return v, true
	1029  			}
	1030  		}
	1031  	}
	1032  	return 0, false
	1033  }
	1034  
	1035  var errNoCertificates = errors.New("tls: no certificates configured")
	1036  
	1037  // getCertificate returns the best certificate for the given ClientHelloInfo,
	1038  // defaulting to the first element of c.Certificates.
	1039  func (c *Config) getCertificate(clientHello *ClientHelloInfo) (*Certificate, error) {
	1040  	if c.GetCertificate != nil &&
	1041  		(len(c.Certificates) == 0 || len(clientHello.ServerName) > 0) {
	1042  		cert, err := c.GetCertificate(clientHello)
	1043  		if cert != nil || err != nil {
	1044  			return cert, err
	1045  		}
	1046  	}
	1047  
	1048  	if len(c.Certificates) == 0 {
	1049  		return nil, errNoCertificates
	1050  	}
	1051  
	1052  	if len(c.Certificates) == 1 {
	1053  		// There's only one choice, so no point doing any work.
	1054  		return &c.Certificates[0], nil
	1055  	}
	1056  
	1057  	if c.NameToCertificate != nil {
	1058  		name := strings.ToLower(clientHello.ServerName)
	1059  		if cert, ok := c.NameToCertificate[name]; ok {
	1060  			return cert, nil
	1061  		}
	1062  		if len(name) > 0 {
	1063  			labels := strings.Split(name, ".")
	1064  			labels[0] = "*"
	1065  			wildcardName := strings.Join(labels, ".")
	1066  			if cert, ok := c.NameToCertificate[wildcardName]; ok {
	1067  				return cert, nil
	1068  			}
	1069  		}
	1070  	}
	1071  
	1072  	for _, cert := range c.Certificates {
	1073  		if err := clientHello.SupportsCertificate(&cert); err == nil {
	1074  			return &cert, nil
	1075  		}
	1076  	}
	1077  
	1078  	// If nothing matches, return the first certificate.
	1079  	return &c.Certificates[0], nil
	1080  }
	1081  
	1082  // SupportsCertificate returns nil if the provided certificate is supported by
	1083  // the client that sent the ClientHello. Otherwise, it returns an error
	1084  // describing the reason for the incompatibility.
	1085  //
	1086  // If this ClientHelloInfo was passed to a GetConfigForClient or GetCertificate
	1087  // callback, this method will take into account the associated Config. Note that
	1088  // if GetConfigForClient returns a different Config, the change can't be
	1089  // accounted for by this method.
	1090  //
	1091  // This function will call x509.ParseCertificate unless c.Leaf is set, which can
	1092  // incur a significant performance cost.
	1093  func (chi *ClientHelloInfo) SupportsCertificate(c *Certificate) error {
	1094  	// Note we don't currently support certificate_authorities nor
	1095  	// signature_algorithms_cert, and don't check the algorithms of the
	1096  	// signatures on the chain (which anyway are a SHOULD, see RFC 8446,
	1097  	// Section 4.4.2.2).
	1098  
	1099  	config := chi.config
	1100  	if config == nil {
	1101  		config = &Config{}
	1102  	}
	1103  	vers, ok := config.mutualVersion(chi.SupportedVersions)
	1104  	if !ok {
	1105  		return errors.New("no mutually supported protocol versions")
	1106  	}
	1107  
	1108  	// If the client specified the name they are trying to connect to, the
	1109  	// certificate needs to be valid for it.
	1110  	if chi.ServerName != "" {
	1111  		x509Cert, err := c.leaf()
	1112  		if err != nil {
	1113  			return fmt.Errorf("failed to parse certificate: %w", err)
	1114  		}
	1115  		if err := x509Cert.VerifyHostname(chi.ServerName); err != nil {
	1116  			return fmt.Errorf("certificate is not valid for requested server name: %w", err)
	1117  		}
	1118  	}
	1119  
	1120  	// supportsRSAFallback returns nil if the certificate and connection support
	1121  	// the static RSA key exchange, and unsupported otherwise. The logic for
	1122  	// supporting static RSA is completely disjoint from the logic for
	1123  	// supporting signed key exchanges, so we just check it as a fallback.
	1124  	supportsRSAFallback := func(unsupported error) error {
	1125  		// TLS 1.3 dropped support for the static RSA key exchange.
	1126  		if vers == VersionTLS13 {
	1127  			return unsupported
	1128  		}
	1129  		// The static RSA key exchange works by decrypting a challenge with the
	1130  		// RSA private key, not by signing, so check the PrivateKey implements
	1131  		// crypto.Decrypter, like *rsa.PrivateKey does.
	1132  		if priv, ok := c.PrivateKey.(crypto.Decrypter); ok {
	1133  			if _, ok := priv.Public().(*rsa.PublicKey); !ok {
	1134  				return unsupported
	1135  			}
	1136  		} else {
	1137  			return unsupported
	1138  		}
	1139  		// Finally, there needs to be a mutual cipher suite that uses the static
	1140  		// RSA key exchange instead of ECDHE.
	1141  		rsaCipherSuite := selectCipherSuite(chi.CipherSuites, config.cipherSuites(), func(c *cipherSuite) bool {
	1142  			if c.flags&suiteECDHE != 0 {
	1143  				return false
	1144  			}
	1145  			if vers < VersionTLS12 && c.flags&suiteTLS12 != 0 {
	1146  				return false
	1147  			}
	1148  			return true
	1149  		})
	1150  		if rsaCipherSuite == nil {
	1151  			return unsupported
	1152  		}
	1153  		return nil
	1154  	}
	1155  
	1156  	// If the client sent the signature_algorithms extension, ensure it supports
	1157  	// schemes we can use with this certificate and TLS version.
	1158  	if len(chi.SignatureSchemes) > 0 {
	1159  		if _, err := selectSignatureScheme(vers, c, chi.SignatureSchemes); err != nil {
	1160  			return supportsRSAFallback(err)
	1161  		}
	1162  	}
	1163  
	1164  	// In TLS 1.3 we are done because supported_groups is only relevant to the
	1165  	// ECDHE computation, point format negotiation is removed, cipher suites are
	1166  	// only relevant to the AEAD choice, and static RSA does not exist.
	1167  	if vers == VersionTLS13 {
	1168  		return nil
	1169  	}
	1170  
	1171  	// The only signed key exchange we support is ECDHE.
	1172  	if !supportsECDHE(config, chi.SupportedCurves, chi.SupportedPoints) {
	1173  		return supportsRSAFallback(errors.New("client doesn't support ECDHE, can only use legacy RSA key exchange"))
	1174  	}
	1175  
	1176  	var ecdsaCipherSuite bool
	1177  	if priv, ok := c.PrivateKey.(crypto.Signer); ok {
	1178  		switch pub := priv.Public().(type) {
	1179  		case *ecdsa.PublicKey:
	1180  			var curve CurveID
	1181  			switch pub.Curve {
	1182  			case elliptic.P256():
	1183  				curve = CurveP256
	1184  			case elliptic.P384():
	1185  				curve = CurveP384
	1186  			case elliptic.P521():
	1187  				curve = CurveP521
	1188  			default:
	1189  				return supportsRSAFallback(unsupportedCertificateError(c))
	1190  			}
	1191  			var curveOk bool
	1192  			for _, c := range chi.SupportedCurves {
	1193  				if c == curve && config.supportsCurve(c) {
	1194  					curveOk = true
	1195  					break
	1196  				}
	1197  			}
	1198  			if !curveOk {
	1199  				return errors.New("client doesn't support certificate curve")
	1200  			}
	1201  			ecdsaCipherSuite = true
	1202  		case ed25519.PublicKey:
	1203  			if vers < VersionTLS12 || len(chi.SignatureSchemes) == 0 {
	1204  				return errors.New("connection doesn't support Ed25519")
	1205  			}
	1206  			ecdsaCipherSuite = true
	1207  		case *rsa.PublicKey:
	1208  		default:
	1209  			return supportsRSAFallback(unsupportedCertificateError(c))
	1210  		}
	1211  	} else {
	1212  		return supportsRSAFallback(unsupportedCertificateError(c))
	1213  	}
	1214  
	1215  	// Make sure that there is a mutually supported cipher suite that works with
	1216  	// this certificate. Cipher suite selection will then apply the logic in
	1217  	// reverse to pick it. See also serverHandshakeState.cipherSuiteOk.
	1218  	cipherSuite := selectCipherSuite(chi.CipherSuites, config.cipherSuites(), func(c *cipherSuite) bool {
	1219  		if c.flags&suiteECDHE == 0 {
	1220  			return false
	1221  		}
	1222  		if c.flags&suiteECSign != 0 {
	1223  			if !ecdsaCipherSuite {
	1224  				return false
	1225  			}
	1226  		} else {
	1227  			if ecdsaCipherSuite {
	1228  				return false
	1229  			}
	1230  		}
	1231  		if vers < VersionTLS12 && c.flags&suiteTLS12 != 0 {
	1232  			return false
	1233  		}
	1234  		return true
	1235  	})
	1236  	if cipherSuite == nil {
	1237  		return supportsRSAFallback(errors.New("client doesn't support any cipher suites compatible with the certificate"))
	1238  	}
	1239  
	1240  	return nil
	1241  }
	1242  
	1243  // SupportsCertificate returns nil if the provided certificate is supported by
	1244  // the server that sent the CertificateRequest. Otherwise, it returns an error
	1245  // describing the reason for the incompatibility.
	1246  func (cri *CertificateRequestInfo) SupportsCertificate(c *Certificate) error {
	1247  	if _, err := selectSignatureScheme(cri.Version, c, cri.SignatureSchemes); err != nil {
	1248  		return err
	1249  	}
	1250  
	1251  	if len(cri.AcceptableCAs) == 0 {
	1252  		return nil
	1253  	}
	1254  
	1255  	for j, cert := range c.Certificate {
	1256  		x509Cert := c.Leaf
	1257  		// Parse the certificate if this isn't the leaf node, or if
	1258  		// chain.Leaf was nil.
	1259  		if j != 0 || x509Cert == nil {
	1260  			var err error
	1261  			if x509Cert, err = x509.ParseCertificate(cert); err != nil {
	1262  				return fmt.Errorf("failed to parse certificate #%d in the chain: %w", j, err)
	1263  			}
	1264  		}
	1265  
	1266  		for _, ca := range cri.AcceptableCAs {
	1267  			if bytes.Equal(x509Cert.RawIssuer, ca) {
	1268  				return nil
	1269  			}
	1270  		}
	1271  	}
	1272  	return errors.New("chain is not signed by an acceptable CA")
	1273  }
	1274  
	1275  // BuildNameToCertificate parses c.Certificates and builds c.NameToCertificate
	1276  // from the CommonName and SubjectAlternateName fields of each of the leaf
	1277  // certificates.
	1278  //
	1279  // Deprecated: NameToCertificate only allows associating a single certificate
	1280  // with a given name. Leave that field nil to let the library select the first
	1281  // compatible chain from Certificates.
	1282  func (c *Config) BuildNameToCertificate() {
	1283  	c.NameToCertificate = make(map[string]*Certificate)
	1284  	for i := range c.Certificates {
	1285  		cert := &c.Certificates[i]
	1286  		x509Cert, err := cert.leaf()
	1287  		if err != nil {
	1288  			continue
	1289  		}
	1290  		// If SANs are *not* present, some clients will consider the certificate
	1291  		// valid for the name in the Common Name.
	1292  		if x509Cert.Subject.CommonName != "" && len(x509Cert.DNSNames) == 0 {
	1293  			c.NameToCertificate[x509Cert.Subject.CommonName] = cert
	1294  		}
	1295  		for _, san := range x509Cert.DNSNames {
	1296  			c.NameToCertificate[san] = cert
	1297  		}
	1298  	}
	1299  }
	1300  
	1301  const (
	1302  	keyLogLabelTLS12					 = "CLIENT_RANDOM"
	1303  	keyLogLabelClientHandshake = "CLIENT_HANDSHAKE_TRAFFIC_SECRET"
	1304  	keyLogLabelServerHandshake = "SERVER_HANDSHAKE_TRAFFIC_SECRET"
	1305  	keyLogLabelClientTraffic	 = "CLIENT_TRAFFIC_SECRET_0"
	1306  	keyLogLabelServerTraffic	 = "SERVER_TRAFFIC_SECRET_0"
	1307  )
	1308  
	1309  func (c *Config) writeKeyLog(label string, clientRandom, secret []byte) error {
	1310  	if c.KeyLogWriter == nil {
	1311  		return nil
	1312  	}
	1313  
	1314  	logLine := []byte(fmt.Sprintf("%s %x %x\n", label, clientRandom, secret))
	1315  
	1316  	writerMutex.Lock()
	1317  	_, err := c.KeyLogWriter.Write(logLine)
	1318  	writerMutex.Unlock()
	1319  
	1320  	return err
	1321  }
	1322  
	1323  // writerMutex protects all KeyLogWriters globally. It is rarely enabled,
	1324  // and is only for debugging, so a global mutex saves space.
	1325  var writerMutex sync.Mutex
	1326  
	1327  // A Certificate is a chain of one or more certificates, leaf first.
	1328  type Certificate struct {
	1329  	Certificate [][]byte
	1330  	// PrivateKey contains the private key corresponding to the public key in
	1331  	// Leaf. This must implement crypto.Signer with an RSA, ECDSA or Ed25519 PublicKey.
	1332  	// For a server up to TLS 1.2, it can also implement crypto.Decrypter with
	1333  	// an RSA PublicKey.
	1334  	PrivateKey crypto.PrivateKey
	1335  	// SupportedSignatureAlgorithms is an optional list restricting what
	1336  	// signature algorithms the PrivateKey can be used for.
	1337  	SupportedSignatureAlgorithms []SignatureScheme
	1338  	// OCSPStaple contains an optional OCSP response which will be served
	1339  	// to clients that request it.
	1340  	OCSPStaple []byte
	1341  	// SignedCertificateTimestamps contains an optional list of Signed
	1342  	// Certificate Timestamps which will be served to clients that request it.
	1343  	SignedCertificateTimestamps [][]byte
	1344  	// Leaf is the parsed form of the leaf certificate, which may be initialized
	1345  	// using x509.ParseCertificate to reduce per-handshake processing. If nil,
	1346  	// the leaf certificate will be parsed as needed.
	1347  	Leaf *x509.Certificate
	1348  }
	1349  
	1350  // leaf returns the parsed leaf certificate, either from c.Leaf or by parsing
	1351  // the corresponding c.Certificate[0].
	1352  func (c *Certificate) leaf() (*x509.Certificate, error) {
	1353  	if c.Leaf != nil {
	1354  		return c.Leaf, nil
	1355  	}
	1356  	return x509.ParseCertificate(c.Certificate[0])
	1357  }
	1358  
	1359  type handshakeMessage interface {
	1360  	marshal() []byte
	1361  	unmarshal([]byte) bool
	1362  }
	1363  
	1364  // lruSessionCache is a ClientSessionCache implementation that uses an LRU
	1365  // caching strategy.
	1366  type lruSessionCache struct {
	1367  	sync.Mutex
	1368  
	1369  	m				map[string]*list.Element
	1370  	q				*list.List
	1371  	capacity int
	1372  }
	1373  
	1374  type lruSessionCacheEntry struct {
	1375  	sessionKey string
	1376  	state			*ClientSessionState
	1377  }
	1378  
	1379  // NewLRUClientSessionCache returns a ClientSessionCache with the given
	1380  // capacity that uses an LRU strategy. If capacity is < 1, a default capacity
	1381  // is used instead.
	1382  func NewLRUClientSessionCache(capacity int) ClientSessionCache {
	1383  	const defaultSessionCacheCapacity = 64
	1384  
	1385  	if capacity < 1 {
	1386  		capacity = defaultSessionCacheCapacity
	1387  	}
	1388  	return &lruSessionCache{
	1389  		m:				make(map[string]*list.Element),
	1390  		q:				list.New(),
	1391  		capacity: capacity,
	1392  	}
	1393  }
	1394  
	1395  // Put adds the provided (sessionKey, cs) pair to the cache. If cs is nil, the entry
	1396  // corresponding to sessionKey is removed from the cache instead.
	1397  func (c *lruSessionCache) Put(sessionKey string, cs *ClientSessionState) {
	1398  	c.Lock()
	1399  	defer c.Unlock()
	1400  
	1401  	if elem, ok := c.m[sessionKey]; ok {
	1402  		if cs == nil {
	1403  			c.q.Remove(elem)
	1404  			delete(c.m, sessionKey)
	1405  		} else {
	1406  			entry := elem.Value.(*lruSessionCacheEntry)
	1407  			entry.state = cs
	1408  			c.q.MoveToFront(elem)
	1409  		}
	1410  		return
	1411  	}
	1412  
	1413  	if c.q.Len() < c.capacity {
	1414  		entry := &lruSessionCacheEntry{sessionKey, cs}
	1415  		c.m[sessionKey] = c.q.PushFront(entry)
	1416  		return
	1417  	}
	1418  
	1419  	elem := c.q.Back()
	1420  	entry := elem.Value.(*lruSessionCacheEntry)
	1421  	delete(c.m, entry.sessionKey)
	1422  	entry.sessionKey = sessionKey
	1423  	entry.state = cs
	1424  	c.q.MoveToFront(elem)
	1425  	c.m[sessionKey] = elem
	1426  }
	1427  
	1428  // Get returns the ClientSessionState value associated with a given key. It
	1429  // returns (nil, false) if no value is found.
	1430  func (c *lruSessionCache) Get(sessionKey string) (*ClientSessionState, bool) {
	1431  	c.Lock()
	1432  	defer c.Unlock()
	1433  
	1434  	if elem, ok := c.m[sessionKey]; ok {
	1435  		c.q.MoveToFront(elem)
	1436  		return elem.Value.(*lruSessionCacheEntry).state, true
	1437  	}
	1438  	return nil, false
	1439  }
	1440  
	1441  var emptyConfig Config
	1442  
	1443  func defaultConfig() *Config {
	1444  	return &emptyConfig
	1445  }
	1446  
	1447  func unexpectedMessageError(wanted, got interface{}) error {
	1448  	return fmt.Errorf("tls: received unexpected handshake message of type %T when waiting for %T", got, wanted)
	1449  }
	1450  
	1451  func isSupportedSignatureAlgorithm(sigAlg SignatureScheme, supportedSignatureAlgorithms []SignatureScheme) bool {
	1452  	for _, s := range supportedSignatureAlgorithms {
	1453  		if s == sigAlg {
	1454  			return true
	1455  		}
	1456  	}
	1457  	return false
	1458  }
	1459  

View as plain text