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