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 main
6
7import (
8	"container/list"
9	"crypto"
10	"crypto/ecdsa"
11	"crypto/rand"
12	"crypto/x509"
13	"fmt"
14	"io"
15	"math/big"
16	"strings"
17	"sync"
18	"time"
19)
20
21const (
22	VersionSSL30 = 0x0300
23	VersionTLS10 = 0x0301
24	VersionTLS11 = 0x0302
25	VersionTLS12 = 0x0303
26)
27
28const (
29	maxPlaintext        = 16384        // maximum plaintext payload length
30	maxCiphertext       = 16384 + 2048 // maximum ciphertext payload length
31	tlsRecordHeaderLen  = 5            // record header length
32	dtlsRecordHeaderLen = 13
33	maxHandshake        = 65536 // maximum handshake we support (protocol max is 16 MB)
34
35	minVersion = VersionSSL30
36	maxVersion = VersionTLS12
37)
38
39// TLS record types.
40type recordType uint8
41
42const (
43	recordTypeChangeCipherSpec recordType = 20
44	recordTypeAlert            recordType = 21
45	recordTypeHandshake        recordType = 22
46	recordTypeApplicationData  recordType = 23
47)
48
49// TLS handshake message types.
50const (
51	typeHelloRequest        uint8 = 0
52	typeClientHello         uint8 = 1
53	typeServerHello         uint8 = 2
54	typeHelloVerifyRequest  uint8 = 3
55	typeNewSessionTicket    uint8 = 4
56	typeCertificate         uint8 = 11
57	typeServerKeyExchange   uint8 = 12
58	typeCertificateRequest  uint8 = 13
59	typeServerHelloDone     uint8 = 14
60	typeCertificateVerify   uint8 = 15
61	typeClientKeyExchange   uint8 = 16
62	typeFinished            uint8 = 20
63	typeCertificateStatus   uint8 = 22
64	typeNextProtocol        uint8 = 67  // Not IANA assigned
65	typeEncryptedExtensions uint8 = 203 // Not IANA assigned
66)
67
68// TLS compression types.
69const (
70	compressionNone uint8 = 0
71)
72
73// TLS extension numbers
74const (
75	extensionServerName                 uint16 = 0
76	extensionStatusRequest              uint16 = 5
77	extensionSupportedCurves            uint16 = 10
78	extensionSupportedPoints            uint16 = 11
79	extensionSignatureAlgorithms        uint16 = 13
80	extensionUseSRTP                    uint16 = 14
81	extensionALPN                       uint16 = 16
82	extensionSignedCertificateTimestamp uint16 = 18
83	extensionExtendedMasterSecret       uint16 = 23
84	extensionSessionTicket              uint16 = 35
85	extensionNextProtoNeg               uint16 = 13172 // not IANA assigned
86	extensionRenegotiationInfo          uint16 = 0xff01
87	extensionChannelID                  uint16 = 30032 // not IANA assigned
88)
89
90// TLS signaling cipher suite values
91const (
92	scsvRenegotiation uint16 = 0x00ff
93)
94
95// CurveID is the type of a TLS identifier for an elliptic curve. See
96// http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-8
97type CurveID uint16
98
99const (
100	CurveP224 CurveID = 21
101	CurveP256 CurveID = 23
102	CurveP384 CurveID = 24
103	CurveP521 CurveID = 25
104)
105
106// TLS Elliptic Curve Point Formats
107// http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-9
108const (
109	pointFormatUncompressed uint8 = 0
110)
111
112// TLS CertificateStatusType (RFC 3546)
113const (
114	statusTypeOCSP uint8 = 1
115)
116
117// Certificate types (for certificateRequestMsg)
118const (
119	CertTypeRSASign    = 1 // A certificate containing an RSA key
120	CertTypeDSSSign    = 2 // A certificate containing a DSA key
121	CertTypeRSAFixedDH = 3 // A certificate containing a static DH key
122	CertTypeDSSFixedDH = 4 // A certificate containing a static DH key
123
124	// See RFC4492 sections 3 and 5.5.
125	CertTypeECDSASign      = 64 // A certificate containing an ECDSA-capable public key, signed with ECDSA.
126	CertTypeRSAFixedECDH   = 65 // A certificate containing an ECDH-capable public key, signed with RSA.
127	CertTypeECDSAFixedECDH = 66 // A certificate containing an ECDH-capable public key, signed with ECDSA.
128
129	// Rest of these are reserved by the TLS spec
130)
131
132// Hash functions for TLS 1.2 (See RFC 5246, section A.4.1)
133const (
134	hashMD5    uint8 = 1
135	hashSHA1   uint8 = 2
136	hashSHA224 uint8 = 3
137	hashSHA256 uint8 = 4
138	hashSHA384 uint8 = 5
139	hashSHA512 uint8 = 6
140)
141
142// Signature algorithms for TLS 1.2 (See RFC 5246, section A.4.1)
143const (
144	signatureRSA   uint8 = 1
145	signatureECDSA uint8 = 3
146)
147
148// signatureAndHash mirrors the TLS 1.2, SignatureAndHashAlgorithm struct. See
149// RFC 5246, section A.4.1.
150type signatureAndHash struct {
151	signature, hash uint8
152}
153
154// supportedSKXSignatureAlgorithms contains the signature and hash algorithms
155// that the code advertises as supported in a TLS 1.2 ClientHello.
156var supportedSKXSignatureAlgorithms = []signatureAndHash{
157	{signatureRSA, hashSHA256},
158	{signatureECDSA, hashSHA256},
159	{signatureRSA, hashSHA1},
160	{signatureECDSA, hashSHA1},
161}
162
163// supportedClientCertSignatureAlgorithms contains the signature and hash
164// algorithms that the code advertises as supported in a TLS 1.2
165// CertificateRequest.
166var supportedClientCertSignatureAlgorithms = []signatureAndHash{
167	{signatureRSA, hashSHA256},
168	{signatureECDSA, hashSHA256},
169}
170
171// SRTP protection profiles (See RFC 5764, section 4.1.2)
172const (
173	SRTP_AES128_CM_HMAC_SHA1_80 uint16 = 0x0001
174	SRTP_AES128_CM_HMAC_SHA1_32        = 0x0002
175)
176
177// ConnectionState records basic TLS details about the connection.
178type ConnectionState struct {
179	Version                    uint16                // TLS version used by the connection (e.g. VersionTLS12)
180	HandshakeComplete          bool                  // TLS handshake is complete
181	DidResume                  bool                  // connection resumes a previous TLS connection
182	CipherSuite                uint16                // cipher suite in use (TLS_RSA_WITH_RC4_128_SHA, ...)
183	NegotiatedProtocol         string                // negotiated next protocol (from Config.NextProtos)
184	NegotiatedProtocolIsMutual bool                  // negotiated protocol was advertised by server
185	NegotiatedProtocolFromALPN bool                  // protocol negotiated with ALPN
186	ServerName                 string                // server name requested by client, if any (server side only)
187	PeerCertificates           []*x509.Certificate   // certificate chain presented by remote peer
188	VerifiedChains             [][]*x509.Certificate // verified chains built from PeerCertificates
189	ChannelID                  *ecdsa.PublicKey      // the channel ID for this connection
190	SRTPProtectionProfile      uint16                // the negotiated DTLS-SRTP protection profile
191	TLSUnique                  []byte
192}
193
194// ClientAuthType declares the policy the server will follow for
195// TLS Client Authentication.
196type ClientAuthType int
197
198const (
199	NoClientCert ClientAuthType = iota
200	RequestClientCert
201	RequireAnyClientCert
202	VerifyClientCertIfGiven
203	RequireAndVerifyClientCert
204)
205
206// ClientSessionState contains the state needed by clients to resume TLS
207// sessions.
208type ClientSessionState struct {
209	sessionId            []uint8             // Session ID supplied by the server. nil if the session has a ticket.
210	sessionTicket        []uint8             // Encrypted ticket used for session resumption with server
211	vers                 uint16              // SSL/TLS version negotiated for the session
212	cipherSuite          uint16              // Ciphersuite negotiated for the session
213	masterSecret         []byte              // MasterSecret generated by client on a full handshake
214	handshakeHash        []byte              // Handshake hash for Channel ID purposes.
215	serverCertificates   []*x509.Certificate // Certificate chain presented by the server
216	extendedMasterSecret bool                // Whether an extended master secret was used to generate the session
217}
218
219// ClientSessionCache is a cache of ClientSessionState objects that can be used
220// by a client to resume a TLS session with a given server. ClientSessionCache
221// implementations should expect to be called concurrently from different
222// goroutines.
223type ClientSessionCache interface {
224	// Get searches for a ClientSessionState associated with the given key.
225	// On return, ok is true if one was found.
226	Get(sessionKey string) (session *ClientSessionState, ok bool)
227
228	// Put adds the ClientSessionState to the cache with the given key.
229	Put(sessionKey string, cs *ClientSessionState)
230}
231
232// ServerSessionCache is a cache of sessionState objects that can be used by a
233// client to resume a TLS session with a given server. ServerSessionCache
234// implementations should expect to be called concurrently from different
235// goroutines.
236type ServerSessionCache interface {
237	// Get searches for a sessionState associated with the given session
238	// ID. On return, ok is true if one was found.
239	Get(sessionId string) (session *sessionState, ok bool)
240
241	// Put adds the sessionState to the cache with the given session ID.
242	Put(sessionId string, session *sessionState)
243}
244
245// A Config structure is used to configure a TLS client or server.
246// After one has been passed to a TLS function it must not be
247// modified. A Config may be reused; the tls package will also not
248// modify it.
249type Config struct {
250	// Rand provides the source of entropy for nonces and RSA blinding.
251	// If Rand is nil, TLS uses the cryptographic random reader in package
252	// crypto/rand.
253	// The Reader must be safe for use by multiple goroutines.
254	Rand io.Reader
255
256	// Time returns the current time as the number of seconds since the epoch.
257	// If Time is nil, TLS uses time.Now.
258	Time func() time.Time
259
260	// Certificates contains one or more certificate chains
261	// to present to the other side of the connection.
262	// Server configurations must include at least one certificate.
263	Certificates []Certificate
264
265	// NameToCertificate maps from a certificate name to an element of
266	// Certificates. Note that a certificate name can be of the form
267	// '*.example.com' and so doesn't have to be a domain name as such.
268	// See Config.BuildNameToCertificate
269	// The nil value causes the first element of Certificates to be used
270	// for all connections.
271	NameToCertificate map[string]*Certificate
272
273	// RootCAs defines the set of root certificate authorities
274	// that clients use when verifying server certificates.
275	// If RootCAs is nil, TLS uses the host's root CA set.
276	RootCAs *x509.CertPool
277
278	// NextProtos is a list of supported, application level protocols.
279	NextProtos []string
280
281	// ServerName is used to verify the hostname on the returned
282	// certificates unless InsecureSkipVerify is given. It is also included
283	// in the client's handshake to support virtual hosting.
284	ServerName string
285
286	// ClientAuth determines the server's policy for
287	// TLS Client Authentication. The default is NoClientCert.
288	ClientAuth ClientAuthType
289
290	// ClientCAs defines the set of root certificate authorities
291	// that servers use if required to verify a client certificate
292	// by the policy in ClientAuth.
293	ClientCAs *x509.CertPool
294
295	// ClientCertificateTypes defines the set of allowed client certificate
296	// types. The default is CertTypeRSASign and CertTypeECDSASign.
297	ClientCertificateTypes []byte
298
299	// InsecureSkipVerify controls whether a client verifies the
300	// server's certificate chain and host name.
301	// If InsecureSkipVerify is true, TLS accepts any certificate
302	// presented by the server and any host name in that certificate.
303	// In this mode, TLS is susceptible to man-in-the-middle attacks.
304	// This should be used only for testing.
305	InsecureSkipVerify bool
306
307	// CipherSuites is a list of supported cipher suites. If CipherSuites
308	// is nil, TLS uses a list of suites supported by the implementation.
309	CipherSuites []uint16
310
311	// PreferServerCipherSuites controls whether the server selects the
312	// client's most preferred ciphersuite, or the server's most preferred
313	// ciphersuite. If true then the server's preference, as expressed in
314	// the order of elements in CipherSuites, is used.
315	PreferServerCipherSuites bool
316
317	// SessionTicketsDisabled may be set to true to disable session ticket
318	// (resumption) support.
319	SessionTicketsDisabled bool
320
321	// SessionTicketKey is used by TLS servers to provide session
322	// resumption. See RFC 5077. If zero, it will be filled with
323	// random data before the first server handshake.
324	//
325	// If multiple servers are terminating connections for the same host
326	// they should all have the same SessionTicketKey. If the
327	// SessionTicketKey leaks, previously recorded and future TLS
328	// connections using that key are compromised.
329	SessionTicketKey [32]byte
330
331	// ClientSessionCache is a cache of ClientSessionState entries
332	// for TLS session resumption.
333	ClientSessionCache ClientSessionCache
334
335	// ServerSessionCache is a cache of sessionState entries for TLS session
336	// resumption.
337	ServerSessionCache ServerSessionCache
338
339	// MinVersion contains the minimum SSL/TLS version that is acceptable.
340	// If zero, then SSLv3 is taken as the minimum.
341	MinVersion uint16
342
343	// MaxVersion contains the maximum SSL/TLS version that is acceptable.
344	// If zero, then the maximum version supported by this package is used,
345	// which is currently TLS 1.2.
346	MaxVersion uint16
347
348	// CurvePreferences contains the elliptic curves that will be used in
349	// an ECDHE handshake, in preference order. If empty, the default will
350	// be used.
351	CurvePreferences []CurveID
352
353	// ChannelID contains the ECDSA key for the client to use as
354	// its TLS Channel ID.
355	ChannelID *ecdsa.PrivateKey
356
357	// RequestChannelID controls whether the server requests a TLS
358	// Channel ID. If negotiated, the client's public key is
359	// returned in the ConnectionState.
360	RequestChannelID bool
361
362	// PreSharedKey, if not nil, is the pre-shared key to use with
363	// the PSK cipher suites.
364	PreSharedKey []byte
365
366	// PreSharedKeyIdentity, if not empty, is the identity to use
367	// with the PSK cipher suites.
368	PreSharedKeyIdentity string
369
370	// SRTPProtectionProfiles, if not nil, is the list of SRTP
371	// protection profiles to offer in DTLS-SRTP.
372	SRTPProtectionProfiles []uint16
373
374	// SignatureAndHashes, if not nil, overrides the default set of
375	// supported signature and hash algorithms to advertise in
376	// CertificateRequest.
377	SignatureAndHashes []signatureAndHash
378
379	// Bugs specifies optional misbehaviour to be used for testing other
380	// implementations.
381	Bugs ProtocolBugs
382
383	serverInitOnce sync.Once // guards calling (*Config).serverInit
384}
385
386type BadValue int
387
388const (
389	BadValueNone BadValue = iota
390	BadValueNegative
391	BadValueZero
392	BadValueLimit
393	BadValueLarge
394	NumBadValues
395)
396
397type ProtocolBugs struct {
398	// InvalidSKXSignature specifies that the signature in a
399	// ServerKeyExchange message should be invalid.
400	InvalidSKXSignature bool
401
402	// InvalidSKXCurve causes the curve ID in the ServerKeyExchange message
403	// to be wrong.
404	InvalidSKXCurve bool
405
406	// BadECDSAR controls ways in which the 'r' value of an ECDSA signature
407	// can be invalid.
408	BadECDSAR BadValue
409	BadECDSAS BadValue
410
411	// MaxPadding causes CBC records to have the maximum possible padding.
412	MaxPadding bool
413	// PaddingFirstByteBad causes the first byte of the padding to be
414	// incorrect.
415	PaddingFirstByteBad bool
416	// PaddingFirstByteBadIf255 causes the first byte of padding to be
417	// incorrect if there's a maximum amount of padding (i.e. 255 bytes).
418	PaddingFirstByteBadIf255 bool
419
420	// FailIfNotFallbackSCSV causes a server handshake to fail if the
421	// client doesn't send the fallback SCSV value.
422	FailIfNotFallbackSCSV bool
423
424	// DuplicateExtension causes an extra empty extension of bogus type to
425	// be emitted in either the ClientHello or the ServerHello.
426	DuplicateExtension bool
427
428	// UnauthenticatedECDH causes the server to pretend ECDHE_RSA
429	// and ECDHE_ECDSA cipher suites are actually ECDH_anon. No
430	// Certificate message is sent and no signature is added to
431	// ServerKeyExchange.
432	UnauthenticatedECDH bool
433
434	// SkipHelloVerifyRequest causes a DTLS server to skip the
435	// HelloVerifyRequest message.
436	SkipHelloVerifyRequest bool
437
438	// SkipCertificateStatus, if true, causes the server to skip the
439	// CertificateStatus message. This is legal because CertificateStatus is
440	// optional, even with a status_request in ServerHello.
441	SkipCertificateStatus bool
442
443	// SkipServerKeyExchange causes the server to skip sending
444	// ServerKeyExchange messages.
445	SkipServerKeyExchange bool
446
447	// SkipNewSessionTicket causes the server to skip sending the
448	// NewSessionTicket message despite promising to in ServerHello.
449	SkipNewSessionTicket bool
450
451	// SkipChangeCipherSpec causes the implementation to skip
452	// sending the ChangeCipherSpec message (and adjusting cipher
453	// state accordingly for the Finished message).
454	SkipChangeCipherSpec bool
455
456	// SkipFinished causes the implementation to skip sending the Finished
457	// message.
458	SkipFinished bool
459
460	// EarlyChangeCipherSpec causes the client to send an early
461	// ChangeCipherSpec message before the ClientKeyExchange. A value of
462	// zero disables this behavior. One and two configure variants for 0.9.8
463	// and 1.0.1 modes, respectively.
464	EarlyChangeCipherSpec int
465
466	// FragmentAcrossChangeCipherSpec causes the implementation to fragment
467	// the Finished (or NextProto) message around the ChangeCipherSpec
468	// messages.
469	FragmentAcrossChangeCipherSpec bool
470
471	// SendV2ClientHello causes the client to send a V2ClientHello
472	// instead of a normal ClientHello.
473	SendV2ClientHello bool
474
475	// SendFallbackSCSV causes the client to include
476	// TLS_FALLBACK_SCSV in the ClientHello.
477	SendFallbackSCSV bool
478
479	// MaxHandshakeRecordLength, if non-zero, is the maximum size of a
480	// handshake record. Handshake messages will be split into multiple
481	// records at the specified size, except that the client_version will
482	// never be fragmented. For DTLS, it is the maximum handshake fragment
483	// size, not record size; DTLS allows multiple handshake fragments in a
484	// single handshake record. See |PackHandshakeFragments|.
485	MaxHandshakeRecordLength int
486
487	// FragmentClientVersion will allow MaxHandshakeRecordLength to apply to
488	// the first 6 bytes of the ClientHello.
489	FragmentClientVersion bool
490
491	// FragmentAlert will cause all alerts to be fragmented across
492	// two records.
493	FragmentAlert bool
494
495	// SendSpuriousAlert, if non-zero, will cause an spurious, unwanted
496	// alert to be sent.
497	SendSpuriousAlert alert
498
499	// RsaClientKeyExchangeVersion, if non-zero, causes the client to send a
500	// ClientKeyExchange with the specified version rather than the
501	// client_version when performing the RSA key exchange.
502	RsaClientKeyExchangeVersion uint16
503
504	// RenewTicketOnResume causes the server to renew the session ticket and
505	// send a NewSessionTicket message during an abbreviated handshake.
506	RenewTicketOnResume bool
507
508	// SendClientVersion, if non-zero, causes the client to send a different
509	// TLS version in the ClientHello than the maximum supported version.
510	SendClientVersion uint16
511
512	// ExpectFalseStart causes the server to, on full handshakes,
513	// expect the peer to False Start; the server Finished message
514	// isn't sent until we receive an application data record
515	// from the peer.
516	ExpectFalseStart bool
517
518	// AlertBeforeFalseStartTest, if non-zero, causes the server to, on full
519	// handshakes, send an alert just before reading the application data
520	// record to test False Start. This can be used in a negative False
521	// Start test to determine whether the peer processed the alert (and
522	// closed the connection) before or after sending app data.
523	AlertBeforeFalseStartTest alert
524
525	// SSL3RSAKeyExchange causes the client to always send an RSA
526	// ClientKeyExchange message without the two-byte length
527	// prefix, as if it were SSL3.
528	SSL3RSAKeyExchange bool
529
530	// SkipCipherVersionCheck causes the server to negotiate
531	// TLS 1.2 ciphers in earlier versions of TLS.
532	SkipCipherVersionCheck bool
533
534	// ExpectServerName, if not empty, is the hostname the client
535	// must specify in the server_name extension.
536	ExpectServerName string
537
538	// SwapNPNAndALPN switches the relative order between NPN and
539	// ALPN on the server. This is to test that server preference
540	// of ALPN works regardless of their relative order.
541	SwapNPNAndALPN bool
542
543	// AllowSessionVersionMismatch causes the server to resume sessions
544	// regardless of the version associated with the session.
545	AllowSessionVersionMismatch bool
546
547	// CorruptTicket causes a client to corrupt a session ticket before
548	// sending it in a resume handshake.
549	CorruptTicket bool
550
551	// OversizedSessionId causes the session id that is sent with a ticket
552	// resumption attempt to be too large (33 bytes).
553	OversizedSessionId bool
554
555	// RequireExtendedMasterSecret, if true, requires that the peer support
556	// the extended master secret option.
557	RequireExtendedMasterSecret bool
558
559	// NoExtendedMasterSecret causes the client and server to behave as if
560	// they didn't support an extended master secret.
561	NoExtendedMasterSecret bool
562
563	// EmptyRenegotiationInfo causes the renegotiation extension to be
564	// empty in a renegotiation handshake.
565	EmptyRenegotiationInfo bool
566
567	// BadRenegotiationInfo causes the renegotiation extension value in a
568	// renegotiation handshake to be incorrect.
569	BadRenegotiationInfo bool
570
571	// NoRenegotiationInfo causes the client to behave as if it
572	// didn't support the renegotiation info extension.
573	NoRenegotiationInfo bool
574
575	// SequenceNumberIncrement, if non-zero, causes outgoing sequence
576	// numbers in DTLS to increment by that value rather by 1. This is to
577	// stress the replay bitmap window by simulating extreme packet loss and
578	// retransmit at the record layer.
579	SequenceNumberIncrement uint64
580
581	// RSAEphemeralKey, if true, causes the server to send a
582	// ServerKeyExchange message containing an ephemeral key (as in
583	// RSA_EXPORT) in the plain RSA key exchange.
584	RSAEphemeralKey bool
585
586	// SRTPMasterKeyIdentifer, if not empty, is the SRTP MKI value that the
587	// client offers when negotiating SRTP. MKI support is still missing so
588	// the peer must still send none.
589	SRTPMasterKeyIdentifer string
590
591	// SendSRTPProtectionProfile, if non-zero, is the SRTP profile that the
592	// server sends in the ServerHello instead of the negotiated one.
593	SendSRTPProtectionProfile uint16
594
595	// NoSignatureAndHashes, if true, causes the client to omit the
596	// signature and hashes extension.
597	//
598	// For a server, it will cause an empty list to be sent in the
599	// CertificateRequest message. None the less, the configured set will
600	// still be enforced.
601	NoSignatureAndHashes bool
602
603	// NoSupportedCurves, if true, causes the client to omit the
604	// supported_curves extension.
605	NoSupportedCurves bool
606
607	// RequireSameRenegoClientVersion, if true, causes the server
608	// to require that all ClientHellos match in offered version
609	// across a renego.
610	RequireSameRenegoClientVersion bool
611
612	// RequireFastradioPadding, if true, requires that ClientHello messages
613	// be at least 1000 bytes long.
614	RequireFastradioPadding bool
615
616	// ExpectInitialRecordVersion, if non-zero, is the expected
617	// version of the records before the version is determined.
618	ExpectInitialRecordVersion uint16
619
620	// MaxPacketLength, if non-zero, is the maximum acceptable size for a
621	// packet.
622	MaxPacketLength int
623
624	// SendCipherSuite, if non-zero, is the cipher suite value that the
625	// server will send in the ServerHello. This does not affect the cipher
626	// the server believes it has actually negotiated.
627	SendCipherSuite uint16
628
629	// AppDataAfterChangeCipherSpec, if not null, causes application data to
630	// be sent immediately after ChangeCipherSpec.
631	AppDataAfterChangeCipherSpec []byte
632
633	// AlertAfterChangeCipherSpec, if non-zero, causes an alert to be sent
634	// immediately after ChangeCipherSpec.
635	AlertAfterChangeCipherSpec alert
636
637	// TimeoutSchedule is the schedule of packet drops and simulated
638	// timeouts for before each handshake leg from the peer.
639	TimeoutSchedule []time.Duration
640
641	// PacketAdaptor is the packetAdaptor to use to simulate timeouts.
642	PacketAdaptor *packetAdaptor
643
644	// ReorderHandshakeFragments, if true, causes handshake fragments in
645	// DTLS to overlap and be sent in the wrong order. It also causes
646	// pre-CCS flights to be sent twice. (Post-CCS flights consist of
647	// Finished and will trigger a spurious retransmit.)
648	ReorderHandshakeFragments bool
649
650	// MixCompleteMessageWithFragments, if true, causes handshake
651	// messages in DTLS to redundantly both fragment the message
652	// and include a copy of the full one.
653	MixCompleteMessageWithFragments bool
654
655	// SendInvalidRecordType, if true, causes a record with an invalid
656	// content type to be sent immediately following the handshake.
657	SendInvalidRecordType bool
658
659	// WrongCertificateMessageType, if true, causes Certificate message to
660	// be sent with the wrong message type.
661	WrongCertificateMessageType bool
662
663	// FragmentMessageTypeMismatch, if true, causes all non-initial
664	// handshake fragments in DTLS to have the wrong message type.
665	FragmentMessageTypeMismatch bool
666
667	// FragmentMessageLengthMismatch, if true, causes all non-initial
668	// handshake fragments in DTLS to have the wrong message length.
669	FragmentMessageLengthMismatch bool
670
671	// SplitFragmentHeader, if true, causes the handshake fragments in DTLS
672	// to be split across two records.
673	SplitFragmentHeader bool
674
675	// SplitFragmentBody, if true, causes the handshake bodies in DTLS to be
676	// split across two records.
677	//
678	// TODO(davidben): There's one final split to test: when the header and
679	// body are split across two records. But those are (incorrectly)
680	// accepted right now.
681	SplitFragmentBody bool
682
683	// SendEmptyFragments, if true, causes handshakes to include empty
684	// fragments in DTLS.
685	SendEmptyFragments bool
686
687	// SendSplitAlert, if true, causes an alert to be sent with the header
688	// and record body split across multiple packets. The peer should
689	// discard these packets rather than process it.
690	SendSplitAlert bool
691
692	// FailIfResumeOnRenego, if true, causes renegotiations to fail if the
693	// client offers a resumption or the server accepts one.
694	FailIfResumeOnRenego bool
695
696	// IgnorePeerCipherPreferences, if true, causes the peer's cipher
697	// preferences to be ignored.
698	IgnorePeerCipherPreferences bool
699
700	// IgnorePeerSignatureAlgorithmPreferences, if true, causes the peer's
701	// signature algorithm preferences to be ignored.
702	IgnorePeerSignatureAlgorithmPreferences bool
703
704	// IgnorePeerCurvePreferences, if true, causes the peer's curve
705	// preferences to be ignored.
706	IgnorePeerCurvePreferences bool
707
708	// SendWarningAlerts, if non-zero, causes every record to be prefaced by
709	// a warning alert.
710	SendWarningAlerts alert
711
712	// BadFinished, if true, causes the Finished hash to be broken.
713	BadFinished bool
714
715	// DHGroupPrime, if not nil, is used to define the (finite field)
716	// Diffie-Hellman group. The generator used is always two.
717	DHGroupPrime *big.Int
718
719	// PackHandshakeFragments, if true, causes handshake fragments to be
720	// packed into individual handshake records, up to the specified record
721	// size.
722	PackHandshakeFragments int
723
724	// PackHandshakeRecords, if true, causes handshake records to be packed
725	// into individual packets, up to the specified packet size.
726	PackHandshakeRecords int
727
728	// EnableAllCiphersInDTLS, if true, causes RC4 to be enabled in DTLS.
729	EnableAllCiphersInDTLS bool
730}
731
732func (c *Config) serverInit() {
733	if c.SessionTicketsDisabled {
734		return
735	}
736
737	// If the key has already been set then we have nothing to do.
738	for _, b := range c.SessionTicketKey {
739		if b != 0 {
740			return
741		}
742	}
743
744	if _, err := io.ReadFull(c.rand(), c.SessionTicketKey[:]); err != nil {
745		c.SessionTicketsDisabled = true
746	}
747}
748
749func (c *Config) rand() io.Reader {
750	r := c.Rand
751	if r == nil {
752		return rand.Reader
753	}
754	return r
755}
756
757func (c *Config) time() time.Time {
758	t := c.Time
759	if t == nil {
760		t = time.Now
761	}
762	return t()
763}
764
765func (c *Config) cipherSuites() []uint16 {
766	s := c.CipherSuites
767	if s == nil {
768		s = defaultCipherSuites()
769	}
770	return s
771}
772
773func (c *Config) minVersion() uint16 {
774	if c == nil || c.MinVersion == 0 {
775		return minVersion
776	}
777	return c.MinVersion
778}
779
780func (c *Config) maxVersion() uint16 {
781	if c == nil || c.MaxVersion == 0 {
782		return maxVersion
783	}
784	return c.MaxVersion
785}
786
787var defaultCurvePreferences = []CurveID{CurveP256, CurveP384, CurveP521}
788
789func (c *Config) curvePreferences() []CurveID {
790	if c == nil || len(c.CurvePreferences) == 0 {
791		return defaultCurvePreferences
792	}
793	return c.CurvePreferences
794}
795
796// mutualVersion returns the protocol version to use given the advertised
797// version of the peer.
798func (c *Config) mutualVersion(vers uint16) (uint16, bool) {
799	minVersion := c.minVersion()
800	maxVersion := c.maxVersion()
801
802	if vers < minVersion {
803		return 0, false
804	}
805	if vers > maxVersion {
806		vers = maxVersion
807	}
808	return vers, true
809}
810
811// getCertificateForName returns the best certificate for the given name,
812// defaulting to the first element of c.Certificates if there are no good
813// options.
814func (c *Config) getCertificateForName(name string) *Certificate {
815	if len(c.Certificates) == 1 || c.NameToCertificate == nil {
816		// There's only one choice, so no point doing any work.
817		return &c.Certificates[0]
818	}
819
820	name = strings.ToLower(name)
821	for len(name) > 0 && name[len(name)-1] == '.' {
822		name = name[:len(name)-1]
823	}
824
825	if cert, ok := c.NameToCertificate[name]; ok {
826		return cert
827	}
828
829	// try replacing labels in the name with wildcards until we get a
830	// match.
831	labels := strings.Split(name, ".")
832	for i := range labels {
833		labels[i] = "*"
834		candidate := strings.Join(labels, ".")
835		if cert, ok := c.NameToCertificate[candidate]; ok {
836			return cert
837		}
838	}
839
840	// If nothing matches, return the first certificate.
841	return &c.Certificates[0]
842}
843
844func (c *Config) signatureAndHashesForServer() []signatureAndHash {
845	if c != nil && c.SignatureAndHashes != nil {
846		return c.SignatureAndHashes
847	}
848	return supportedClientCertSignatureAlgorithms
849}
850
851func (c *Config) signatureAndHashesForClient() []signatureAndHash {
852	if c != nil && c.SignatureAndHashes != nil {
853		return c.SignatureAndHashes
854	}
855	return supportedSKXSignatureAlgorithms
856}
857
858// BuildNameToCertificate parses c.Certificates and builds c.NameToCertificate
859// from the CommonName and SubjectAlternateName fields of each of the leaf
860// certificates.
861func (c *Config) BuildNameToCertificate() {
862	c.NameToCertificate = make(map[string]*Certificate)
863	for i := range c.Certificates {
864		cert := &c.Certificates[i]
865		x509Cert, err := x509.ParseCertificate(cert.Certificate[0])
866		if err != nil {
867			continue
868		}
869		if len(x509Cert.Subject.CommonName) > 0 {
870			c.NameToCertificate[x509Cert.Subject.CommonName] = cert
871		}
872		for _, san := range x509Cert.DNSNames {
873			c.NameToCertificate[san] = cert
874		}
875	}
876}
877
878// A Certificate is a chain of one or more certificates, leaf first.
879type Certificate struct {
880	Certificate [][]byte
881	PrivateKey  crypto.PrivateKey // supported types: *rsa.PrivateKey, *ecdsa.PrivateKey
882	// OCSPStaple contains an optional OCSP response which will be served
883	// to clients that request it.
884	OCSPStaple []byte
885	// SignedCertificateTimestampList contains an optional encoded
886	// SignedCertificateTimestampList structure which will be
887	// served to clients that request it.
888	SignedCertificateTimestampList []byte
889	// Leaf is the parsed form of the leaf certificate, which may be
890	// initialized using x509.ParseCertificate to reduce per-handshake
891	// processing for TLS clients doing client authentication. If nil, the
892	// leaf certificate will be parsed as needed.
893	Leaf *x509.Certificate
894}
895
896// A TLS record.
897type record struct {
898	contentType  recordType
899	major, minor uint8
900	payload      []byte
901}
902
903type handshakeMessage interface {
904	marshal() []byte
905	unmarshal([]byte) bool
906}
907
908// lruSessionCache is a client or server session cache implementation
909// that uses an LRU caching strategy.
910type lruSessionCache struct {
911	sync.Mutex
912
913	m        map[string]*list.Element
914	q        *list.List
915	capacity int
916}
917
918type lruSessionCacheEntry struct {
919	sessionKey string
920	state      interface{}
921}
922
923// Put adds the provided (sessionKey, cs) pair to the cache.
924func (c *lruSessionCache) Put(sessionKey string, cs interface{}) {
925	c.Lock()
926	defer c.Unlock()
927
928	if elem, ok := c.m[sessionKey]; ok {
929		entry := elem.Value.(*lruSessionCacheEntry)
930		entry.state = cs
931		c.q.MoveToFront(elem)
932		return
933	}
934
935	if c.q.Len() < c.capacity {
936		entry := &lruSessionCacheEntry{sessionKey, cs}
937		c.m[sessionKey] = c.q.PushFront(entry)
938		return
939	}
940
941	elem := c.q.Back()
942	entry := elem.Value.(*lruSessionCacheEntry)
943	delete(c.m, entry.sessionKey)
944	entry.sessionKey = sessionKey
945	entry.state = cs
946	c.q.MoveToFront(elem)
947	c.m[sessionKey] = elem
948}
949
950// Get returns the value associated with a given key. It returns (nil,
951// false) if no value is found.
952func (c *lruSessionCache) Get(sessionKey string) (interface{}, bool) {
953	c.Lock()
954	defer c.Unlock()
955
956	if elem, ok := c.m[sessionKey]; ok {
957		c.q.MoveToFront(elem)
958		return elem.Value.(*lruSessionCacheEntry).state, true
959	}
960	return nil, false
961}
962
963// lruClientSessionCache is a ClientSessionCache implementation that
964// uses an LRU caching strategy.
965type lruClientSessionCache struct {
966	lruSessionCache
967}
968
969func (c *lruClientSessionCache) Put(sessionKey string, cs *ClientSessionState) {
970	c.lruSessionCache.Put(sessionKey, cs)
971}
972
973func (c *lruClientSessionCache) Get(sessionKey string) (*ClientSessionState, bool) {
974	cs, ok := c.lruSessionCache.Get(sessionKey)
975	if !ok {
976		return nil, false
977	}
978	return cs.(*ClientSessionState), true
979}
980
981// lruServerSessionCache is a ServerSessionCache implementation that
982// uses an LRU caching strategy.
983type lruServerSessionCache struct {
984	lruSessionCache
985}
986
987func (c *lruServerSessionCache) Put(sessionId string, session *sessionState) {
988	c.lruSessionCache.Put(sessionId, session)
989}
990
991func (c *lruServerSessionCache) Get(sessionId string) (*sessionState, bool) {
992	cs, ok := c.lruSessionCache.Get(sessionId)
993	if !ok {
994		return nil, false
995	}
996	return cs.(*sessionState), true
997}
998
999// NewLRUClientSessionCache returns a ClientSessionCache with the given
1000// capacity that uses an LRU strategy. If capacity is < 1, a default capacity
1001// is used instead.
1002func NewLRUClientSessionCache(capacity int) ClientSessionCache {
1003	const defaultSessionCacheCapacity = 64
1004
1005	if capacity < 1 {
1006		capacity = defaultSessionCacheCapacity
1007	}
1008	return &lruClientSessionCache{
1009		lruSessionCache{
1010			m:        make(map[string]*list.Element),
1011			q:        list.New(),
1012			capacity: capacity,
1013		},
1014	}
1015}
1016
1017// NewLRUServerSessionCache returns a ServerSessionCache with the given
1018// capacity that uses an LRU strategy. If capacity is < 1, a default capacity
1019// is used instead.
1020func NewLRUServerSessionCache(capacity int) ServerSessionCache {
1021	const defaultSessionCacheCapacity = 64
1022
1023	if capacity < 1 {
1024		capacity = defaultSessionCacheCapacity
1025	}
1026	return &lruServerSessionCache{
1027		lruSessionCache{
1028			m:        make(map[string]*list.Element),
1029			q:        list.New(),
1030			capacity: capacity,
1031		},
1032	}
1033}
1034
1035// TODO(jsing): Make these available to both crypto/x509 and crypto/tls.
1036type dsaSignature struct {
1037	R, S *big.Int
1038}
1039
1040type ecdsaSignature dsaSignature
1041
1042var emptyConfig Config
1043
1044func defaultConfig() *Config {
1045	return &emptyConfig
1046}
1047
1048var (
1049	once                   sync.Once
1050	varDefaultCipherSuites []uint16
1051)
1052
1053func defaultCipherSuites() []uint16 {
1054	once.Do(initDefaultCipherSuites)
1055	return varDefaultCipherSuites
1056}
1057
1058func initDefaultCipherSuites() {
1059	for _, suite := range cipherSuites {
1060		if suite.flags&suitePSK == 0 {
1061			varDefaultCipherSuites = append(varDefaultCipherSuites, suite.id)
1062		}
1063	}
1064}
1065
1066func unexpectedMessageError(wanted, got interface{}) error {
1067	return fmt.Errorf("tls: received unexpected handshake message of type %T when waiting for %T", got, wanted)
1068}
1069
1070func isSupportedSignatureAndHash(sigHash signatureAndHash, sigHashes []signatureAndHash) bool {
1071	for _, s := range sigHashes {
1072		if s == sigHash {
1073			return true
1074		}
1075	}
1076	return false
1077}
1078