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