github.com/x04/go/src@v0.0.0-20200202162449-3d481ceb3525/crypto/tls/common.go (about)

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