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