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