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/internal/cipherhw"
11	"crypto/rand"
12	"crypto/sha512"
13	"crypto/x509"
14	"errors"
15	"fmt"
16	"io"
17	"math/big"
18	"net"
19	"strings"
20	"sync"
21	"time"
22)
23
24const (
25	VersionSSL30 = 0x0300
26	VersionTLS10 = 0x0301
27	VersionTLS11 = 0x0302
28	VersionTLS12 = 0x0303
29)
30
31const (
32	maxPlaintext      = 16384        // maximum plaintext payload length
33	maxCiphertext     = 16384 + 2048 // maximum ciphertext payload length
34	recordHeaderLen   = 5            // record header length
35	maxHandshake      = 65536        // maximum handshake we support (protocol max is 16 MB)
36	maxWarnAlertCount = 5            // maximum number of consecutive warning alerts
37
38	minVersion = VersionTLS10
39	maxVersion = VersionTLS12
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	typeCertificate        uint8 = 11
59	typeServerKeyExchange  uint8 = 12
60	typeCertificateRequest uint8 = 13
61	typeServerHelloDone    uint8 = 14
62	typeCertificateVerify  uint8 = 15
63	typeClientKeyExchange  uint8 = 16
64	typeFinished           uint8 = 20
65	typeCertificateStatus  uint8 = 22
66	typeNextProtocol       uint8 = 67 // Not IANA assigned
67)
68
69// TLS compression types.
70const (
71	compressionNone uint8 = 0
72)
73
74// TLS extension numbers
75const (
76	extensionServerName          uint16 = 0
77	extensionStatusRequest       uint16 = 5
78	extensionSupportedCurves     uint16 = 10
79	extensionSupportedPoints     uint16 = 11
80	extensionSignatureAlgorithms uint16 = 13
81	extensionALPN                uint16 = 16
82	extensionSCT                 uint16 = 18 // https://tools.ietf.org/html/rfc6962#section-6
83	extensionSessionTicket       uint16 = 35
84	extensionNextProtoNeg        uint16 = 13172 // not IANA assigned
85	extensionRenegotiationInfo   uint16 = 0xff01
86)
87
88// TLS signaling cipher suite values
89const (
90	scsvRenegotiation uint16 = 0x00ff
91)
92
93// CurveID is the type of a TLS identifier for an elliptic curve. See
94// http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-8
95type CurveID uint16
96
97const (
98	CurveP256 CurveID = 23
99	CurveP384 CurveID = 24
100	CurveP521 CurveID = 25
101	X25519    CurveID = 29
102)
103
104// TLS Elliptic Curve Point Formats
105// http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-9
106const (
107	pointFormatUncompressed uint8 = 0
108)
109
110// TLS CertificateStatusType (RFC 3546)
111const (
112	statusTypeOCSP uint8 = 1
113)
114
115// Certificate types (for certificateRequestMsg)
116const (
117	certTypeRSASign    = 1 // A certificate containing an RSA key
118	certTypeDSSSign    = 2 // A certificate containing a DSA key
119	certTypeRSAFixedDH = 3 // A certificate containing a static DH key
120	certTypeDSSFixedDH = 4 // A certificate containing a static DH key
121
122	// See RFC 4492 sections 3 and 5.5.
123	certTypeECDSASign      = 64 // A certificate containing an ECDSA-capable public key, signed with ECDSA.
124	certTypeRSAFixedECDH   = 65 // A certificate containing an ECDH-capable public key, signed with RSA.
125	certTypeECDSAFixedECDH = 66 // A certificate containing an ECDH-capable public key, signed with ECDSA.
126
127	// Rest of these are reserved by the TLS spec
128)
129
130// Signature algorithms for TLS 1.2 (See RFC 5246, section A.4.1)
131const (
132	signatureRSA   uint8 = 1
133	signatureECDSA uint8 = 3
134)
135
136// supportedSignatureAlgorithms contains the signature and hash algorithms that
137// the code advertises as supported in a TLS 1.2 ClientHello and in a TLS 1.2
138// CertificateRequest. The two fields are merged to match with TLS 1.3.
139// Note that in TLS 1.2, the ECDSA algorithms are not constrained to P-256, etc.
140var supportedSignatureAlgorithms = []SignatureScheme{
141	PKCS1WithSHA256,
142	ECDSAWithP256AndSHA256,
143	PKCS1WithSHA384,
144	ECDSAWithP384AndSHA384,
145	PKCS1WithSHA512,
146	ECDSAWithP521AndSHA512,
147	PKCS1WithSHA1,
148	ECDSAWithSHA1,
149}
150
151// ConnectionState records basic TLS details about the connection.
152type ConnectionState struct {
153	Version                     uint16                // TLS version used by the connection (e.g. VersionTLS12)
154	HandshakeComplete           bool                  // TLS handshake is complete
155	DidResume                   bool                  // connection resumes a previous TLS connection
156	CipherSuite                 uint16                // cipher suite in use (TLS_RSA_WITH_RC4_128_SHA, ...)
157	NegotiatedProtocol          string                // negotiated next protocol (not guaranteed to be from Config.NextProtos)
158	NegotiatedProtocolIsMutual  bool                  // negotiated protocol was advertised by server (client side only)
159	ServerName                  string                // server name requested by client, if any (server side only)
160	PeerCertificates            []*x509.Certificate   // certificate chain presented by remote peer
161	VerifiedChains              [][]*x509.Certificate // verified chains built from PeerCertificates
162	SignedCertificateTimestamps [][]byte              // SCTs from the server, if any
163	OCSPResponse                []byte                // stapled OCSP response from server, if any
164
165	// TLSUnique contains the "tls-unique" channel binding value (see RFC
166	// 5929, section 3). For resumed sessions this value will be nil
167	// because resumption does not include enough context (see
168	// https://mitls.org/pages/attacks/3SHAKE#channelbindings). This will
169	// change in future versions of Go once the TLS master-secret fix has
170	// been standardized and implemented.
171	TLSUnique []byte
172}
173
174// ClientAuthType declares the policy the server will follow for
175// TLS Client Authentication.
176type ClientAuthType int
177
178const (
179	NoClientCert ClientAuthType = iota
180	RequestClientCert
181	RequireAnyClientCert
182	VerifyClientCertIfGiven
183	RequireAndVerifyClientCert
184)
185
186// ClientSessionState contains the state needed by clients to resume TLS
187// sessions.
188type ClientSessionState struct {
189	sessionTicket      []uint8               // Encrypted ticket used for session resumption with server
190	vers               uint16                // SSL/TLS version negotiated for the session
191	cipherSuite        uint16                // Ciphersuite negotiated for the session
192	masterSecret       []byte                // MasterSecret generated by client on a full handshake
193	serverCertificates []*x509.Certificate   // Certificate chain presented by the server
194	verifiedChains     [][]*x509.Certificate // Certificate chains we built for verification
195}
196
197// ClientSessionCache is a cache of ClientSessionState objects that can be used
198// by a client to resume a TLS session with a given server. ClientSessionCache
199// implementations should expect to be called concurrently from different
200// goroutines. Only ticket-based resumption is supported, not SessionID-based
201// resumption.
202type ClientSessionCache interface {
203	// Get searches for a ClientSessionState associated with the given key.
204	// On return, ok is true if one was found.
205	Get(sessionKey string) (session *ClientSessionState, ok bool)
206
207	// Put adds the ClientSessionState to the cache with the given key.
208	Put(sessionKey string, cs *ClientSessionState)
209}
210
211// SignatureScheme identifies a signature algorithm supported by TLS. See
212// https://tools.ietf.org/html/draft-ietf-tls-tls13-18#section-4.2.3.
213type SignatureScheme uint16
214
215const (
216	PKCS1WithSHA1   SignatureScheme = 0x0201
217	PKCS1WithSHA256 SignatureScheme = 0x0401
218	PKCS1WithSHA384 SignatureScheme = 0x0501
219	PKCS1WithSHA512 SignatureScheme = 0x0601
220
221	PSSWithSHA256 SignatureScheme = 0x0804
222	PSSWithSHA384 SignatureScheme = 0x0805
223	PSSWithSHA512 SignatureScheme = 0x0806
224
225	ECDSAWithP256AndSHA256 SignatureScheme = 0x0403
226	ECDSAWithP384AndSHA384 SignatureScheme = 0x0503
227	ECDSAWithP521AndSHA512 SignatureScheme = 0x0603
228
229	// Legacy signature and hash algorithms for TLS 1.2.
230	ECDSAWithSHA1 SignatureScheme = 0x0203
231)
232
233// ClientHelloInfo contains information from a ClientHello message in order to
234// guide certificate selection in the GetCertificate callback.
235type ClientHelloInfo struct {
236	// CipherSuites lists the CipherSuites supported by the client (e.g.
237	// TLS_RSA_WITH_RC4_128_SHA).
238	CipherSuites []uint16
239
240	// ServerName indicates the name of the server requested by the client
241	// in order to support virtual hosting. ServerName is only set if the
242	// client is using SNI (see
243	// http://tools.ietf.org/html/rfc4366#section-3.1).
244	ServerName string
245
246	// SupportedCurves lists the elliptic curves supported by the client.
247	// SupportedCurves is set only if the Supported Elliptic Curves
248	// Extension is being used (see
249	// http://tools.ietf.org/html/rfc4492#section-5.1.1).
250	SupportedCurves []CurveID
251
252	// SupportedPoints lists the point formats supported by the client.
253	// SupportedPoints is set only if the Supported Point Formats Extension
254	// is being used (see
255	// http://tools.ietf.org/html/rfc4492#section-5.1.2).
256	SupportedPoints []uint8
257
258	// SignatureSchemes lists the signature and hash schemes that the client
259	// is willing to verify. SignatureSchemes is set only if the Signature
260	// Algorithms Extension is being used (see
261	// https://tools.ietf.org/html/rfc5246#section-7.4.1.4.1).
262	SignatureSchemes []SignatureScheme
263
264	// SupportedProtos lists the application protocols supported by the client.
265	// SupportedProtos is set only if the Application-Layer Protocol
266	// Negotiation Extension is being used (see
267	// https://tools.ietf.org/html/rfc7301#section-3.1).
268	//
269	// Servers can select a protocol by setting Config.NextProtos in a
270	// GetConfigForClient return value.
271	SupportedProtos []string
272
273	// SupportedVersions lists the TLS versions supported by the client.
274	// For TLS versions less than 1.3, this is extrapolated from the max
275	// version advertised by the client, so values other than the greatest
276	// might be rejected if used.
277	SupportedVersions []uint16
278
279	// Conn is the underlying net.Conn for the connection. Do not read
280	// from, or write to, this connection; that will cause the TLS
281	// connection to fail.
282	Conn net.Conn
283}
284
285// CertificateRequestInfo contains information from a server's
286// CertificateRequest message, which is used to demand a certificate and proof
287// of control from a client.
288type CertificateRequestInfo struct {
289	// AcceptableCAs contains zero or more, DER-encoded, X.501
290	// Distinguished Names. These are the names of root or intermediate CAs
291	// that the server wishes the returned certificate to be signed by. An
292	// empty slice indicates that the server has no preference.
293	AcceptableCAs [][]byte
294
295	// SignatureSchemes lists the signature schemes that the server is
296	// willing to verify.
297	SignatureSchemes []SignatureScheme
298}
299
300// RenegotiationSupport enumerates the different levels of support for TLS
301// renegotiation. TLS renegotiation is the act of performing subsequent
302// handshakes on a connection after the first. This significantly complicates
303// the state machine and has been the source of numerous, subtle security
304// issues. Initiating a renegotiation is not supported, but support for
305// accepting renegotiation requests may be enabled.
306//
307// Even when enabled, the server may not change its identity between handshakes
308// (i.e. the leaf certificate must be the same). Additionally, concurrent
309// handshake and application data flow is not permitted so renegotiation can
310// only be used with protocols that synchronise with the renegotiation, such as
311// HTTPS.
312type RenegotiationSupport int
313
314const (
315	// RenegotiateNever disables renegotiation.
316	RenegotiateNever RenegotiationSupport = iota
317
318	// RenegotiateOnceAsClient allows a remote server to request
319	// renegotiation once per connection.
320	RenegotiateOnceAsClient
321
322	// RenegotiateFreelyAsClient allows a remote server to repeatedly
323	// request renegotiation.
324	RenegotiateFreelyAsClient
325)
326
327// A Config structure is used to configure a TLS client or server.
328// After one has been passed to a TLS function it must not be
329// modified. A Config may be reused; the tls package will also not
330// modify it.
331type Config struct {
332	// Rand provides the source of entropy for nonces and RSA blinding.
333	// If Rand is nil, TLS uses the cryptographic random reader in package
334	// crypto/rand.
335	// The Reader must be safe for use by multiple goroutines.
336	Rand io.Reader
337
338	// Time returns the current time as the number of seconds since the epoch.
339	// If Time is nil, TLS uses time.Now.
340	Time func() time.Time
341
342	// Certificates contains one or more certificate chains to present to
343	// the other side of the connection. Server configurations must include
344	// at least one certificate or else set GetCertificate. Clients doing
345	// client-authentication may set either Certificates or
346	// GetClientCertificate.
347	Certificates []Certificate
348
349	// NameToCertificate maps from a certificate name to an element of
350	// Certificates. Note that a certificate name can be of the form
351	// '*.example.com' and so doesn't have to be a domain name as such.
352	// See Config.BuildNameToCertificate
353	// The nil value causes the first element of Certificates to be used
354	// for all connections.
355	NameToCertificate map[string]*Certificate
356
357	// GetCertificate returns a Certificate based on the given
358	// ClientHelloInfo. It will only be called if the client supplies SNI
359	// information or if Certificates is empty.
360	//
361	// If GetCertificate is nil or returns nil, then the certificate is
362	// retrieved from NameToCertificate. If NameToCertificate is nil, the
363	// first element of Certificates will be used.
364	GetCertificate func(*ClientHelloInfo) (*Certificate, error)
365
366	// GetClientCertificate, if not nil, is called when a server requests a
367	// certificate from a client. If set, the contents of Certificates will
368	// be ignored.
369	//
370	// If GetClientCertificate returns an error, the handshake will be
371	// aborted and that error will be returned. Otherwise
372	// GetClientCertificate must return a non-nil Certificate. If
373	// Certificate.Certificate is empty then no certificate will be sent to
374	// the server. If this is unacceptable to the server then it may abort
375	// the handshake.
376	//
377	// GetClientCertificate may be called multiple times for the same
378	// connection if renegotiation occurs or if TLS 1.3 is in use.
379	GetClientCertificate func(*CertificateRequestInfo) (*Certificate, error)
380
381	// GetConfigForClient, if not nil, is called after a ClientHello is
382	// received from a client. It may return a non-nil Config in order to
383	// change the Config that will be used to handle this connection. If
384	// the returned Config is nil, the original Config will be used. The
385	// Config returned by this callback may not be subsequently modified.
386	//
387	// If GetConfigForClient is nil, the Config passed to Server() will be
388	// used for all connections.
389	//
390	// Uniquely for the fields in the returned Config, session ticket keys
391	// will be duplicated from the original Config if not set.
392	// Specifically, if SetSessionTicketKeys was called on the original
393	// config but not on the returned config then the ticket keys from the
394	// original config will be copied into the new config before use.
395	// Otherwise, if SessionTicketKey was set in the original config but
396	// not in the returned config then it will be copied into the returned
397	// config before use. If neither of those cases applies then the key
398	// material from the returned config will be used for session tickets.
399	GetConfigForClient func(*ClientHelloInfo) (*Config, error)
400
401	// VerifyPeerCertificate, if not nil, is called after normal
402	// certificate verification by either a TLS client or server. It
403	// receives the raw ASN.1 certificates provided by the peer and also
404	// any verified chains that normal processing found. If it returns a
405	// non-nil error, the handshake is aborted and that error results.
406	//
407	// If normal verification fails then the handshake will abort before
408	// considering this callback. If normal verification is disabled by
409	// setting InsecureSkipVerify, or (for a server) when ClientAuth is
410	// RequestClientCert or RequireAnyClientCert, then this callback will
411	// be considered but the verifiedChains argument will always be nil.
412	VerifyPeerCertificate func(rawCerts [][]byte, verifiedChains [][]*x509.Certificate) error
413
414	// RootCAs defines the set of root certificate authorities
415	// that clients use when verifying server certificates.
416	// If RootCAs is nil, TLS uses the host's root CA set.
417	RootCAs *x509.CertPool
418
419	// NextProtos is a list of supported, application level protocols.
420	NextProtos []string
421
422	// ServerName is used to verify the hostname on the returned
423	// certificates unless InsecureSkipVerify is given. It is also included
424	// in the client's handshake to support virtual hosting unless it is
425	// an IP address.
426	ServerName string
427
428	// ClientAuth determines the server's policy for
429	// TLS Client Authentication. The default is NoClientCert.
430	ClientAuth ClientAuthType
431
432	// ClientCAs defines the set of root certificate authorities
433	// that servers use if required to verify a client certificate
434	// by the policy in ClientAuth.
435	ClientCAs *x509.CertPool
436
437	// InsecureSkipVerify controls whether a client verifies the
438	// server's certificate chain and host name.
439	// If InsecureSkipVerify is true, TLS accepts any certificate
440	// presented by the server and any host name in that certificate.
441	// In this mode, TLS is susceptible to man-in-the-middle attacks.
442	// This should be used only for testing.
443	InsecureSkipVerify bool
444
445	// CipherSuites is a list of supported cipher suites. If CipherSuites
446	// is nil, TLS uses a list of suites supported by the implementation.
447	CipherSuites []uint16
448
449	// PreferServerCipherSuites controls whether the server selects the
450	// client's most preferred ciphersuite, or the server's most preferred
451	// ciphersuite. If true then the server's preference, as expressed in
452	// the order of elements in CipherSuites, is used.
453	PreferServerCipherSuites bool
454
455	// SessionTicketsDisabled may be set to true to disable session ticket
456	// (resumption) support.
457	SessionTicketsDisabled bool
458
459	// SessionTicketKey is used by TLS servers to provide session
460	// resumption. See RFC 5077. If zero, it will be filled with
461	// random data before the first server handshake.
462	//
463	// If multiple servers are terminating connections for the same host
464	// they should all have the same SessionTicketKey. If the
465	// SessionTicketKey leaks, previously recorded and future TLS
466	// connections using that key are compromised.
467	SessionTicketKey [32]byte
468
469	// ClientSessionCache is a cache of ClientSessionState entries for TLS
470	// session resumption.
471	ClientSessionCache ClientSessionCache
472
473	// MinVersion contains the minimum SSL/TLS version that is acceptable.
474	// If zero, then TLS 1.0 is taken as the minimum.
475	MinVersion uint16
476
477	// MaxVersion contains the maximum SSL/TLS version that is acceptable.
478	// If zero, then the maximum version supported by this package is used,
479	// which is currently TLS 1.2.
480	MaxVersion uint16
481
482	// CurvePreferences contains the elliptic curves that will be used in
483	// an ECDHE handshake, in preference order. If empty, the default will
484	// be used.
485	CurvePreferences []CurveID
486
487	// DynamicRecordSizingDisabled disables adaptive sizing of TLS records.
488	// When true, the largest possible TLS record size is always used. When
489	// false, the size of TLS records may be adjusted in an attempt to
490	// improve latency.
491	DynamicRecordSizingDisabled bool
492
493	// Renegotiation controls what types of renegotiation are supported.
494	// The default, none, is correct for the vast majority of applications.
495	Renegotiation RenegotiationSupport
496
497	// KeyLogWriter optionally specifies a destination for TLS master secrets
498	// in NSS key log format that can be used to allow external programs
499	// such as Wireshark to decrypt TLS connections.
500	// See https://developer.mozilla.org/en-US/docs/Mozilla/Projects/NSS/Key_Log_Format.
501	// Use of KeyLogWriter compromises security and should only be
502	// used for debugging.
503	KeyLogWriter io.Writer
504
505	serverInitOnce sync.Once // guards calling (*Config).serverInit
506
507	// mutex protects sessionTicketKeys.
508	mutex sync.RWMutex
509	// sessionTicketKeys contains zero or more ticket keys. If the length
510	// is zero, SessionTicketsDisabled must be true. The first key is used
511	// for new tickets and any subsequent keys can be used to decrypt old
512	// tickets.
513	sessionTicketKeys []ticketKey
514}
515
516// ticketKeyNameLen is the number of bytes of identifier that is prepended to
517// an encrypted session ticket in order to identify the key used to encrypt it.
518const ticketKeyNameLen = 16
519
520// ticketKey is the internal representation of a session ticket key.
521type ticketKey struct {
522	// keyName is an opaque byte string that serves to identify the session
523	// ticket key. It's exposed as plaintext in every session ticket.
524	keyName [ticketKeyNameLen]byte
525	aesKey  [16]byte
526	hmacKey [16]byte
527}
528
529// ticketKeyFromBytes converts from the external representation of a session
530// ticket key to a ticketKey. Externally, session ticket keys are 32 random
531// bytes and this function expands that into sufficient name and key material.
532func ticketKeyFromBytes(b [32]byte) (key ticketKey) {
533	hashed := sha512.Sum512(b[:])
534	copy(key.keyName[:], hashed[:ticketKeyNameLen])
535	copy(key.aesKey[:], hashed[ticketKeyNameLen:ticketKeyNameLen+16])
536	copy(key.hmacKey[:], hashed[ticketKeyNameLen+16:ticketKeyNameLen+32])
537	return key
538}
539
540// Clone returns a shallow clone of c. It is safe to clone a Config that is
541// being used concurrently by a TLS client or server.
542func (c *Config) Clone() *Config {
543	// Running serverInit ensures that it's safe to read
544	// SessionTicketsDisabled.
545	c.serverInitOnce.Do(func() { c.serverInit(nil) })
546
547	var sessionTicketKeys []ticketKey
548	c.mutex.RLock()
549	sessionTicketKeys = c.sessionTicketKeys
550	c.mutex.RUnlock()
551
552	return &Config{
553		Rand:                        c.Rand,
554		Time:                        c.Time,
555		Certificates:                c.Certificates,
556		NameToCertificate:           c.NameToCertificate,
557		GetCertificate:              c.GetCertificate,
558		GetClientCertificate:        c.GetClientCertificate,
559		GetConfigForClient:          c.GetConfigForClient,
560		VerifyPeerCertificate:       c.VerifyPeerCertificate,
561		RootCAs:                     c.RootCAs,
562		NextProtos:                  c.NextProtos,
563		ServerName:                  c.ServerName,
564		ClientAuth:                  c.ClientAuth,
565		ClientCAs:                   c.ClientCAs,
566		InsecureSkipVerify:          c.InsecureSkipVerify,
567		CipherSuites:                c.CipherSuites,
568		PreferServerCipherSuites:    c.PreferServerCipherSuites,
569		SessionTicketsDisabled:      c.SessionTicketsDisabled,
570		SessionTicketKey:            c.SessionTicketKey,
571		ClientSessionCache:          c.ClientSessionCache,
572		MinVersion:                  c.MinVersion,
573		MaxVersion:                  c.MaxVersion,
574		CurvePreferences:            c.CurvePreferences,
575		DynamicRecordSizingDisabled: c.DynamicRecordSizingDisabled,
576		Renegotiation:               c.Renegotiation,
577		KeyLogWriter:                c.KeyLogWriter,
578		sessionTicketKeys:           sessionTicketKeys,
579	}
580}
581
582// serverInit is run under c.serverInitOnce to do initialization of c. If c was
583// returned by a GetConfigForClient callback then the argument should be the
584// Config that was passed to Server, otherwise it should be nil.
585func (c *Config) serverInit(originalConfig *Config) {
586	if c.SessionTicketsDisabled || len(c.ticketKeys()) != 0 {
587		return
588	}
589
590	alreadySet := false
591	for _, b := range c.SessionTicketKey {
592		if b != 0 {
593			alreadySet = true
594			break
595		}
596	}
597
598	if !alreadySet {
599		if originalConfig != nil {
600			copy(c.SessionTicketKey[:], originalConfig.SessionTicketKey[:])
601		} else if _, err := io.ReadFull(c.rand(), c.SessionTicketKey[:]); err != nil {
602			c.SessionTicketsDisabled = true
603			return
604		}
605	}
606
607	if originalConfig != nil {
608		originalConfig.mutex.RLock()
609		c.sessionTicketKeys = originalConfig.sessionTicketKeys
610		originalConfig.mutex.RUnlock()
611	} else {
612		c.sessionTicketKeys = []ticketKey{ticketKeyFromBytes(c.SessionTicketKey)}
613	}
614}
615
616func (c *Config) ticketKeys() []ticketKey {
617	c.mutex.RLock()
618	// c.sessionTicketKeys is constant once created. SetSessionTicketKeys
619	// will only update it by replacing it with a new value.
620	ret := c.sessionTicketKeys
621	c.mutex.RUnlock()
622	return ret
623}
624
625// SetSessionTicketKeys updates the session ticket keys for a server. The first
626// key will be used when creating new tickets, while all keys can be used for
627// decrypting tickets. It is safe to call this function while the server is
628// running in order to rotate the session ticket keys. The function will panic
629// if keys is empty.
630func (c *Config) SetSessionTicketKeys(keys [][32]byte) {
631	if len(keys) == 0 {
632		panic("tls: keys must have at least one key")
633	}
634
635	newKeys := make([]ticketKey, len(keys))
636	for i, bytes := range keys {
637		newKeys[i] = ticketKeyFromBytes(bytes)
638	}
639
640	c.mutex.Lock()
641	c.sessionTicketKeys = newKeys
642	c.mutex.Unlock()
643}
644
645func (c *Config) rand() io.Reader {
646	r := c.Rand
647	if r == nil {
648		return rand.Reader
649	}
650	return r
651}
652
653func (c *Config) time() time.Time {
654	t := c.Time
655	if t == nil {
656		t = time.Now
657	}
658	return t()
659}
660
661func (c *Config) cipherSuites() []uint16 {
662	s := c.CipherSuites
663	if s == nil {
664		s = defaultCipherSuites()
665	}
666	return s
667}
668
669func (c *Config) minVersion() uint16 {
670	if c == nil || c.MinVersion == 0 {
671		return minVersion
672	}
673	return c.MinVersion
674}
675
676func (c *Config) maxVersion() uint16 {
677	if c == nil || c.MaxVersion == 0 {
678		return maxVersion
679	}
680	return c.MaxVersion
681}
682
683var defaultCurvePreferences = []CurveID{X25519, CurveP256, CurveP384, CurveP521}
684
685func (c *Config) curvePreferences() []CurveID {
686	if c == nil || len(c.CurvePreferences) == 0 {
687		return defaultCurvePreferences
688	}
689	return c.CurvePreferences
690}
691
692// mutualVersion returns the protocol version to use given the advertised
693// version of the peer.
694func (c *Config) mutualVersion(vers uint16) (uint16, bool) {
695	minVersion := c.minVersion()
696	maxVersion := c.maxVersion()
697
698	if vers < minVersion {
699		return 0, false
700	}
701	if vers > maxVersion {
702		vers = maxVersion
703	}
704	return vers, true
705}
706
707// getCertificate returns the best certificate for the given ClientHelloInfo,
708// defaulting to the first element of c.Certificates.
709func (c *Config) getCertificate(clientHello *ClientHelloInfo) (*Certificate, error) {
710	if c.GetCertificate != nil &&
711		(len(c.Certificates) == 0 || len(clientHello.ServerName) > 0) {
712		cert, err := c.GetCertificate(clientHello)
713		if cert != nil || err != nil {
714			return cert, err
715		}
716	}
717
718	if len(c.Certificates) == 0 {
719		return nil, errors.New("tls: no certificates configured")
720	}
721
722	if len(c.Certificates) == 1 || c.NameToCertificate == nil {
723		// There's only one choice, so no point doing any work.
724		return &c.Certificates[0], nil
725	}
726
727	name := strings.ToLower(clientHello.ServerName)
728	for len(name) > 0 && name[len(name)-1] == '.' {
729		name = name[:len(name)-1]
730	}
731
732	if cert, ok := c.NameToCertificate[name]; ok {
733		return cert, nil
734	}
735
736	// try replacing labels in the name with wildcards until we get a
737	// match.
738	labels := strings.Split(name, ".")
739	for i := range labels {
740		labels[i] = "*"
741		candidate := strings.Join(labels, ".")
742		if cert, ok := c.NameToCertificate[candidate]; ok {
743			return cert, nil
744		}
745	}
746
747	// If nothing matches, return the first certificate.
748	return &c.Certificates[0], nil
749}
750
751// BuildNameToCertificate parses c.Certificates and builds c.NameToCertificate
752// from the CommonName and SubjectAlternateName fields of each of the leaf
753// certificates.
754func (c *Config) BuildNameToCertificate() {
755	c.NameToCertificate = make(map[string]*Certificate)
756	for i := range c.Certificates {
757		cert := &c.Certificates[i]
758		x509Cert, err := x509.ParseCertificate(cert.Certificate[0])
759		if err != nil {
760			continue
761		}
762		if len(x509Cert.Subject.CommonName) > 0 {
763			c.NameToCertificate[x509Cert.Subject.CommonName] = cert
764		}
765		for _, san := range x509Cert.DNSNames {
766			c.NameToCertificate[san] = cert
767		}
768	}
769}
770
771// writeKeyLog logs client random and master secret if logging was enabled by
772// setting c.KeyLogWriter.
773func (c *Config) writeKeyLog(clientRandom, masterSecret []byte) error {
774	if c.KeyLogWriter == nil {
775		return nil
776	}
777
778	logLine := []byte(fmt.Sprintf("CLIENT_RANDOM %x %x\n", clientRandom, masterSecret))
779
780	writerMutex.Lock()
781	_, err := c.KeyLogWriter.Write(logLine)
782	writerMutex.Unlock()
783
784	return err
785}
786
787// writerMutex protects all KeyLogWriters globally. It is rarely enabled,
788// and is only for debugging, so a global mutex saves space.
789var writerMutex sync.Mutex
790
791// A Certificate is a chain of one or more certificates, leaf first.
792type Certificate struct {
793	Certificate [][]byte
794	// PrivateKey contains the private key corresponding to the public key
795	// in Leaf. For a server, this must implement crypto.Signer and/or
796	// crypto.Decrypter, with an RSA or ECDSA PublicKey. For a client
797	// (performing client authentication), this must be a crypto.Signer
798	// with an RSA or ECDSA PublicKey.
799	PrivateKey crypto.PrivateKey
800	// OCSPStaple contains an optional OCSP response which will be served
801	// to clients that request it.
802	OCSPStaple []byte
803	// SignedCertificateTimestamps contains an optional list of Signed
804	// Certificate Timestamps which will be served to clients that request it.
805	SignedCertificateTimestamps [][]byte
806	// Leaf is the parsed form of the leaf certificate, which may be
807	// initialized using x509.ParseCertificate to reduce per-handshake
808	// processing for TLS clients doing client authentication. If nil, the
809	// leaf certificate will be parsed as needed.
810	Leaf *x509.Certificate
811}
812
813type handshakeMessage interface {
814	marshal() []byte
815	unmarshal([]byte) bool
816}
817
818// lruSessionCache is a ClientSessionCache implementation that uses an LRU
819// caching strategy.
820type lruSessionCache struct {
821	sync.Mutex
822
823	m        map[string]*list.Element
824	q        *list.List
825	capacity int
826}
827
828type lruSessionCacheEntry struct {
829	sessionKey string
830	state      *ClientSessionState
831}
832
833// NewLRUClientSessionCache returns a ClientSessionCache with the given
834// capacity that uses an LRU strategy. If capacity is < 1, a default capacity
835// is used instead.
836func NewLRUClientSessionCache(capacity int) ClientSessionCache {
837	const defaultSessionCacheCapacity = 64
838
839	if capacity < 1 {
840		capacity = defaultSessionCacheCapacity
841	}
842	return &lruSessionCache{
843		m:        make(map[string]*list.Element),
844		q:        list.New(),
845		capacity: capacity,
846	}
847}
848
849// Put adds the provided (sessionKey, cs) pair to the cache.
850func (c *lruSessionCache) Put(sessionKey string, cs *ClientSessionState) {
851	c.Lock()
852	defer c.Unlock()
853
854	if elem, ok := c.m[sessionKey]; ok {
855		entry := elem.Value.(*lruSessionCacheEntry)
856		entry.state = cs
857		c.q.MoveToFront(elem)
858		return
859	}
860
861	if c.q.Len() < c.capacity {
862		entry := &lruSessionCacheEntry{sessionKey, cs}
863		c.m[sessionKey] = c.q.PushFront(entry)
864		return
865	}
866
867	elem := c.q.Back()
868	entry := elem.Value.(*lruSessionCacheEntry)
869	delete(c.m, entry.sessionKey)
870	entry.sessionKey = sessionKey
871	entry.state = cs
872	c.q.MoveToFront(elem)
873	c.m[sessionKey] = elem
874}
875
876// Get returns the ClientSessionState value associated with a given key. It
877// returns (nil, false) if no value is found.
878func (c *lruSessionCache) Get(sessionKey string) (*ClientSessionState, bool) {
879	c.Lock()
880	defer c.Unlock()
881
882	if elem, ok := c.m[sessionKey]; ok {
883		c.q.MoveToFront(elem)
884		return elem.Value.(*lruSessionCacheEntry).state, true
885	}
886	return nil, false
887}
888
889// TODO(jsing): Make these available to both crypto/x509 and crypto/tls.
890type dsaSignature struct {
891	R, S *big.Int
892}
893
894type ecdsaSignature dsaSignature
895
896var emptyConfig Config
897
898func defaultConfig() *Config {
899	return &emptyConfig
900}
901
902var (
903	once                   sync.Once
904	varDefaultCipherSuites []uint16
905)
906
907func defaultCipherSuites() []uint16 {
908	once.Do(initDefaultCipherSuites)
909	return varDefaultCipherSuites
910}
911
912func initDefaultCipherSuites() {
913	var topCipherSuites []uint16
914	if cipherhw.AESGCMSupport() {
915		// If AES-GCM hardware is provided then prioritise AES-GCM
916		// cipher suites.
917		topCipherSuites = []uint16{
918			TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
919			TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
920			TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
921			TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
922			TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305,
923			TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305,
924		}
925	} else {
926		// Without AES-GCM hardware, we put the ChaCha20-Poly1305
927		// cipher suites first.
928		topCipherSuites = []uint16{
929			TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305,
930			TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305,
931			TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
932			TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
933			TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
934			TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
935		}
936	}
937
938	varDefaultCipherSuites = make([]uint16, 0, len(cipherSuites))
939	varDefaultCipherSuites = append(varDefaultCipherSuites, topCipherSuites...)
940
941NextCipherSuite:
942	for _, suite := range cipherSuites {
943		if suite.flags&suiteDefaultOff != 0 {
944			continue
945		}
946		for _, existing := range varDefaultCipherSuites {
947			if existing == suite.id {
948				continue NextCipherSuite
949			}
950		}
951		varDefaultCipherSuites = append(varDefaultCipherSuites, suite.id)
952	}
953}
954
955func unexpectedMessageError(wanted, got interface{}) error {
956	return fmt.Errorf("tls: received unexpected handshake message of type %T when waiting for %T", got, wanted)
957}
958
959func isSupportedSignatureAlgorithm(sigAlg SignatureScheme, supportedSignatureAlgorithms []SignatureScheme) bool {
960	for _, s := range supportedSignatureAlgorithms {
961		if s == sigAlg {
962			return true
963		}
964	}
965	return false
966}
967
968// signatureFromSignatureScheme maps a signature algorithm to the underlying
969// signature method (without hash function).
970func signatureFromSignatureScheme(signatureAlgorithm SignatureScheme) uint8 {
971	switch signatureAlgorithm {
972	case PKCS1WithSHA1, PKCS1WithSHA256, PKCS1WithSHA384, PKCS1WithSHA512:
973		return signatureRSA
974	case ECDSAWithSHA1, ECDSAWithP256AndSHA256, ECDSAWithP384AndSHA384, ECDSAWithP521AndSHA512:
975		return signatureECDSA
976	default:
977		return 0
978	}
979}
980