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	VersionTLS13 = 0x0304
27)
28
29const (
30	VersionDTLS10 = 0xfeff
31	VersionDTLS12 = 0xfefd
32)
33
34var allTLSWireVersions = []uint16{
35	VersionTLS13,
36	VersionTLS12,
37	VersionTLS11,
38	VersionTLS10,
39	VersionSSL30,
40}
41
42var allDTLSWireVersions = []uint16{
43	VersionDTLS12,
44	VersionDTLS10,
45}
46
47const (
48	maxPlaintext        = 16384        // maximum plaintext payload length
49	maxCiphertext       = 16384 + 2048 // maximum ciphertext payload length
50	tlsRecordHeaderLen  = 5            // record header length
51	dtlsRecordHeaderLen = 13
52	maxHandshake        = 65536 // maximum handshake we support (protocol max is 16 MB)
53
54	minVersion = VersionSSL30
55	maxVersion = VersionTLS13
56)
57
58// TLS record types.
59type recordType uint8
60
61const (
62	recordTypeChangeCipherSpec   recordType = 20
63	recordTypeAlert              recordType = 21
64	recordTypeHandshake          recordType = 22
65	recordTypeApplicationData    recordType = 23
66	recordTypePlaintextHandshake recordType = 24
67)
68
69// TLS handshake message types.
70const (
71	typeHelloRequest          uint8 = 0
72	typeClientHello           uint8 = 1
73	typeServerHello           uint8 = 2
74	typeHelloVerifyRequest    uint8 = 3
75	typeNewSessionTicket      uint8 = 4
76	typeEndOfEarlyData        uint8 = 5
77	typeHelloRetryRequest     uint8 = 6
78	typeEncryptedExtensions   uint8 = 8
79	typeCertificate           uint8 = 11
80	typeServerKeyExchange     uint8 = 12
81	typeCertificateRequest    uint8 = 13
82	typeServerHelloDone       uint8 = 14
83	typeCertificateVerify     uint8 = 15
84	typeClientKeyExchange     uint8 = 16
85	typeFinished              uint8 = 20
86	typeCertificateStatus     uint8 = 22
87	typeKeyUpdate             uint8 = 24
88	typeCompressedCertificate uint8 = 25  // Not IANA assigned
89	typeNextProtocol          uint8 = 67  // Not IANA assigned
90	typeChannelID             uint8 = 203 // Not IANA assigned
91	typeMessageHash           uint8 = 254
92)
93
94// TLS compression types.
95const (
96	compressionNone uint8 = 0
97)
98
99// TLS extension numbers
100const (
101	extensionServerName                 uint16 = 0
102	extensionStatusRequest              uint16 = 5
103	extensionSupportedCurves            uint16 = 10
104	extensionSupportedPoints            uint16 = 11
105	extensionSignatureAlgorithms        uint16 = 13
106	extensionUseSRTP                    uint16 = 14
107	extensionALPN                       uint16 = 16
108	extensionSignedCertificateTimestamp uint16 = 18
109	extensionPadding                    uint16 = 21
110	extensionExtendedMasterSecret       uint16 = 23
111	extensionTokenBinding               uint16 = 24
112	extensionCompressedCertAlgs         uint16 = 27
113	extensionSessionTicket              uint16 = 35
114	extensionPreSharedKey               uint16 = 41
115	extensionEarlyData                  uint16 = 42
116	extensionSupportedVersions          uint16 = 43
117	extensionCookie                     uint16 = 44
118	extensionPSKKeyExchangeModes        uint16 = 45
119	extensionCertificateAuthorities     uint16 = 47
120	extensionSignatureAlgorithmsCert    uint16 = 50
121	extensionKeyShare                   uint16 = 51
122	extensionCustom                     uint16 = 1234  // not IANA assigned
123	extensionNextProtoNeg               uint16 = 13172 // not IANA assigned
124	extensionApplicationSettings        uint16 = 17513 // not IANA assigned
125	extensionRenegotiationInfo          uint16 = 0xff01
126	extensionQUICTransportParams        uint16 = 0xffa5 // draft-ietf-quic-tls-13
127	extensionChannelID                  uint16 = 30032  // not IANA assigned
128	extensionDelegatedCredentials       uint16 = 0x22   // draft-ietf-tls-subcerts-06
129	extensionDuplicate                  uint16 = 0xffff // not IANA assigned
130)
131
132// TLS signaling cipher suite values
133const (
134	scsvRenegotiation uint16 = 0x00ff
135)
136
137var tls13HelloRetryRequest = []uint8{
138	0xcf, 0x21, 0xad, 0x74, 0xe5, 0x9a, 0x61, 0x11, 0xbe, 0x1d, 0x8c,
139	0x02, 0x1e, 0x65, 0xb8, 0x91, 0xc2, 0xa2, 0x11, 0x16, 0x7a, 0xbb,
140	0x8c, 0x5e, 0x07, 0x9e, 0x09, 0xe2, 0xc8, 0xa8, 0x33, 0x9c,
141}
142
143// CurveID is the type of a TLS identifier for an elliptic curve. See
144// http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-8
145type CurveID uint16
146
147const (
148	CurveP224   CurveID = 21
149	CurveP256   CurveID = 23
150	CurveP384   CurveID = 24
151	CurveP521   CurveID = 25
152	CurveX25519 CurveID = 29
153	CurveCECPQ2 CurveID = 16696
154)
155
156// TLS Elliptic Curve Point Formats
157// http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-9
158const (
159	pointFormatUncompressed    uint8 = 0
160	pointFormatCompressedPrime uint8 = 1
161)
162
163// TLS CertificateStatusType (RFC 3546)
164const (
165	statusTypeOCSP uint8 = 1
166)
167
168// Certificate types (for certificateRequestMsg)
169const (
170	CertTypeRSASign    = 1 // A certificate containing an RSA key
171	CertTypeDSSSign    = 2 // A certificate containing a DSA key
172	CertTypeRSAFixedDH = 3 // A certificate containing a static DH key
173	CertTypeDSSFixedDH = 4 // A certificate containing a static DH key
174
175	// See RFC4492 sections 3 and 5.5.
176	CertTypeECDSASign      = 64 // A certificate containing an ECDSA-capable public key, signed with ECDSA.
177	CertTypeRSAFixedECDH   = 65 // A certificate containing an ECDH-capable public key, signed with RSA.
178	CertTypeECDSAFixedECDH = 66 // A certificate containing an ECDH-capable public key, signed with ECDSA.
179
180	// Rest of these are reserved by the TLS spec
181)
182
183// signatureAlgorithm corresponds to a SignatureScheme value from TLS 1.3. Note
184// that TLS 1.3 names the production 'SignatureScheme' to avoid colliding with
185// TLS 1.2's SignatureAlgorithm but otherwise refers to them as 'signature
186// algorithms' throughout. We match the latter.
187type signatureAlgorithm uint16
188
189const (
190	// RSASSA-PKCS1-v1_5 algorithms
191	signatureRSAPKCS1WithMD5    signatureAlgorithm = 0x0101
192	signatureRSAPKCS1WithSHA1   signatureAlgorithm = 0x0201
193	signatureRSAPKCS1WithSHA256 signatureAlgorithm = 0x0401
194	signatureRSAPKCS1WithSHA384 signatureAlgorithm = 0x0501
195	signatureRSAPKCS1WithSHA512 signatureAlgorithm = 0x0601
196
197	// ECDSA algorithms
198	signatureECDSAWithSHA1          signatureAlgorithm = 0x0203
199	signatureECDSAWithP256AndSHA256 signatureAlgorithm = 0x0403
200	signatureECDSAWithP384AndSHA384 signatureAlgorithm = 0x0503
201	signatureECDSAWithP521AndSHA512 signatureAlgorithm = 0x0603
202
203	// RSASSA-PSS algorithms
204	signatureRSAPSSWithSHA256 signatureAlgorithm = 0x0804
205	signatureRSAPSSWithSHA384 signatureAlgorithm = 0x0805
206	signatureRSAPSSWithSHA512 signatureAlgorithm = 0x0806
207
208	// EdDSA algorithms
209	signatureEd25519 signatureAlgorithm = 0x0807
210	signatureEd448   signatureAlgorithm = 0x0808
211)
212
213// supportedSignatureAlgorithms contains the default supported signature
214// algorithms.
215var supportedSignatureAlgorithms = []signatureAlgorithm{
216	signatureRSAPSSWithSHA256,
217	signatureRSAPKCS1WithSHA256,
218	signatureECDSAWithP256AndSHA256,
219	signatureRSAPKCS1WithSHA1,
220	signatureECDSAWithSHA1,
221	signatureEd25519,
222}
223
224// SRTP protection profiles (See RFC 5764, section 4.1.2)
225const (
226	SRTP_AES128_CM_HMAC_SHA1_80 uint16 = 0x0001
227	SRTP_AES128_CM_HMAC_SHA1_32        = 0x0002
228)
229
230// PskKeyExchangeMode values (see RFC 8446, section 4.2.9)
231const (
232	pskKEMode    = 0
233	pskDHEKEMode = 1
234)
235
236// KeyUpdateRequest values (see RFC 8446, section 4.6.3)
237const (
238	keyUpdateNotRequested = 0
239	keyUpdateRequested    = 1
240)
241
242// ConnectionState records basic TLS details about the connection.
243type ConnectionState struct {
244	Version                    uint16                // TLS version used by the connection (e.g. VersionTLS12)
245	HandshakeComplete          bool                  // TLS handshake is complete
246	DidResume                  bool                  // connection resumes a previous TLS connection
247	CipherSuite                uint16                // cipher suite in use (TLS_RSA_WITH_RC4_128_SHA, ...)
248	NegotiatedProtocol         string                // negotiated next protocol (from Config.NextProtos)
249	NegotiatedProtocolIsMutual bool                  // negotiated protocol was advertised by server
250	NegotiatedProtocolFromALPN bool                  // protocol negotiated with ALPN
251	ServerName                 string                // server name requested by client, if any (server side only)
252	PeerCertificates           []*x509.Certificate   // certificate chain presented by remote peer
253	VerifiedChains             [][]*x509.Certificate // verified chains built from PeerCertificates
254	OCSPResponse               []byte                // stapled OCSP response from the peer, if any
255	ChannelID                  *ecdsa.PublicKey      // the channel ID for this connection
256	TokenBindingNegotiated     bool                  // whether Token Binding was negotiated
257	TokenBindingParam          uint8                 // the negotiated Token Binding key parameter
258	SRTPProtectionProfile      uint16                // the negotiated DTLS-SRTP protection profile
259	TLSUnique                  []byte                // the tls-unique channel binding
260	SCTList                    []byte                // signed certificate timestamp list
261	PeerSignatureAlgorithm     signatureAlgorithm    // algorithm used by the peer in the handshake
262	CurveID                    CurveID               // the curve used in ECDHE
263	QUICTransportParams        []byte                // the QUIC transport params received from the peer
264	HasApplicationSettings     bool                  // whether ALPS was negotiated
265	PeerApplicationSettings    []byte                // application settings received from the peer
266}
267
268// ClientAuthType declares the policy the server will follow for
269// TLS Client Authentication.
270type ClientAuthType int
271
272const (
273	NoClientCert ClientAuthType = iota
274	RequestClientCert
275	RequireAnyClientCert
276	VerifyClientCertIfGiven
277	RequireAndVerifyClientCert
278)
279
280// ClientSessionState contains the state needed by clients to resume TLS
281// sessions.
282type ClientSessionState struct {
283	sessionId                []uint8             // Session ID supplied by the server. nil if the session has a ticket.
284	sessionTicket            []uint8             // Encrypted ticket used for session resumption with server
285	vers                     uint16              // SSL/TLS version negotiated for the session
286	wireVersion              uint16              // Wire SSL/TLS version negotiated for the session
287	cipherSuite              uint16              // Ciphersuite negotiated for the session
288	masterSecret             []byte              // MasterSecret generated by client on a full handshake
289	handshakeHash            []byte              // Handshake hash for Channel ID purposes.
290	serverCertificates       []*x509.Certificate // Certificate chain presented by the server
291	extendedMasterSecret     bool                // Whether an extended master secret was used to generate the session
292	sctList                  []byte
293	ocspResponse             []byte
294	earlyALPN                string
295	ticketCreationTime       time.Time
296	ticketExpiration         time.Time
297	ticketAgeAdd             uint32
298	maxEarlyDataSize         uint32
299	hasApplicationSettings   bool
300	localApplicationSettings []byte
301	peerApplicationSettings  []byte
302}
303
304// ClientSessionCache is a cache of ClientSessionState objects that can be used
305// by a client to resume a TLS session with a given server. ClientSessionCache
306// implementations should expect to be called concurrently from different
307// goroutines.
308type ClientSessionCache interface {
309	// Get searches for a ClientSessionState associated with the given key.
310	// On return, ok is true if one was found.
311	Get(sessionKey string) (session *ClientSessionState, ok bool)
312
313	// Put adds the ClientSessionState to the cache with the given key.
314	Put(sessionKey string, cs *ClientSessionState)
315}
316
317// ServerSessionCache is a cache of sessionState objects that can be used by a
318// client to resume a TLS session with a given server. ServerSessionCache
319// implementations should expect to be called concurrently from different
320// goroutines.
321type ServerSessionCache interface {
322	// Get searches for a sessionState associated with the given session
323	// ID. On return, ok is true if one was found.
324	Get(sessionId string) (session *sessionState, ok bool)
325
326	// Put adds the sessionState to the cache with the given session ID.
327	Put(sessionId string, session *sessionState)
328}
329
330// CertCompressionAlg is a certificate compression algorithm, specified as a
331// pair of functions for compressing and decompressing certificates.
332type CertCompressionAlg struct {
333	// Compress returns a compressed representation of the input.
334	Compress func([]byte) []byte
335	// Decompress depresses the contents of in and writes the result to out, which
336	// will be the correct size. It returns true on success and false otherwise.
337	Decompress func(out, in []byte) bool
338}
339
340// A Config structure is used to configure a TLS client or server.
341// After one has been passed to a TLS function it must not be
342// modified. A Config may be reused; the tls package will also not
343// modify it.
344type Config struct {
345	// Rand provides the source of entropy for nonces and RSA blinding.
346	// If Rand is nil, TLS uses the cryptographic random reader in package
347	// crypto/rand.
348	// The Reader must be safe for use by multiple goroutines.
349	Rand io.Reader
350
351	// Time returns the current time as the number of seconds since the epoch.
352	// If Time is nil, TLS uses time.Now.
353	Time func() time.Time
354
355	// Certificates contains one or more certificate chains
356	// to present to the other side of the connection.
357	// Server configurations must include at least one certificate.
358	Certificates []Certificate
359
360	// NameToCertificate maps from a certificate name to an element of
361	// Certificates. Note that a certificate name can be of the form
362	// '*.example.com' and so doesn't have to be a domain name as such.
363	// See Config.BuildNameToCertificate
364	// The nil value causes the first element of Certificates to be used
365	// for all connections.
366	NameToCertificate map[string]*Certificate
367
368	// RootCAs defines the set of root certificate authorities
369	// that clients use when verifying server certificates.
370	// If RootCAs is nil, TLS uses the host's root CA set.
371	RootCAs *x509.CertPool
372
373	// NextProtos is a list of supported, application level protocols.
374	NextProtos []string
375
376	// ApplicationSettings is a set of application settings to use which each
377	// application protocol.
378	ApplicationSettings map[string][]byte
379
380	// ServerName is used to verify the hostname on the returned
381	// certificates unless InsecureSkipVerify is given. It is also included
382	// in the client's handshake to support virtual hosting.
383	ServerName string
384
385	// ClientAuth determines the server's policy for
386	// TLS Client Authentication. The default is NoClientCert.
387	ClientAuth ClientAuthType
388
389	// ClientCAs defines the set of root certificate authorities
390	// that servers use if required to verify a client certificate
391	// by the policy in ClientAuth.
392	ClientCAs *x509.CertPool
393
394	// ClientCertificateTypes defines the set of allowed client certificate
395	// types. The default is CertTypeRSASign and CertTypeECDSASign.
396	ClientCertificateTypes []byte
397
398	// InsecureSkipVerify controls whether a client verifies the
399	// server's certificate chain and host name.
400	// If InsecureSkipVerify is true, TLS accepts any certificate
401	// presented by the server and any host name in that certificate.
402	// In this mode, TLS is susceptible to man-in-the-middle attacks.
403	// This should be used only for testing.
404	InsecureSkipVerify bool
405
406	// CipherSuites is a list of supported cipher suites. If CipherSuites
407	// is nil, TLS uses a list of suites supported by the implementation.
408	CipherSuites []uint16
409
410	// PreferServerCipherSuites controls whether the server selects the
411	// client's most preferred ciphersuite, or the server's most preferred
412	// ciphersuite. If true then the server's preference, as expressed in
413	// the order of elements in CipherSuites, is used.
414	PreferServerCipherSuites bool
415
416	// SessionTicketsDisabled may be set to true to disable session ticket
417	// (resumption) support.
418	SessionTicketsDisabled bool
419
420	// SessionTicketKey is used by TLS servers to provide session
421	// resumption. See RFC 5077. If zero, it will be filled with
422	// random data before the first server handshake.
423	//
424	// If multiple servers are terminating connections for the same host
425	// they should all have the same SessionTicketKey. If the
426	// SessionTicketKey leaks, previously recorded and future TLS
427	// connections using that key are compromised.
428	SessionTicketKey [32]byte
429
430	// ClientSessionCache is a cache of ClientSessionState entries
431	// for TLS session resumption.
432	ClientSessionCache ClientSessionCache
433
434	// ServerSessionCache is a cache of sessionState entries for TLS session
435	// resumption.
436	ServerSessionCache ServerSessionCache
437
438	// MinVersion contains the minimum SSL/TLS version that is acceptable.
439	// If zero, then SSLv3 is taken as the minimum.
440	MinVersion uint16
441
442	// MaxVersion contains the maximum SSL/TLS version that is acceptable.
443	// If zero, then the maximum version supported by this package is used,
444	// which is currently TLS 1.2.
445	MaxVersion uint16
446
447	// CurvePreferences contains the elliptic curves that will be used in
448	// an ECDHE handshake, in preference order. If empty, the default will
449	// be used.
450	CurvePreferences []CurveID
451
452	// DefaultCurves contains the elliptic curves for which public values will
453	// be sent in the ClientHello's KeyShare extension. If this value is nil,
454	// all supported curves will have public values sent. This field is ignored
455	// on servers.
456	DefaultCurves []CurveID
457
458	// ChannelID contains the ECDSA key for the client to use as
459	// its TLS Channel ID.
460	ChannelID *ecdsa.PrivateKey
461
462	// RequestChannelID controls whether the server requests a TLS
463	// Channel ID. If negotiated, the client's public key is
464	// returned in the ConnectionState.
465	RequestChannelID bool
466
467	// TokenBindingParams contains a list of TokenBindingKeyParameters
468	// (draft-ietf-tokbind-protocol-16) to attempt to negotiate. If
469	// nil, Token Binding will not be negotiated.
470	TokenBindingParams []byte
471
472	// TokenBindingVersion contains the serialized ProtocolVersion to
473	// use when negotiating Token Binding.
474	TokenBindingVersion uint16
475
476	// ExpectTokenBindingParams is checked by a server that the client
477	// sent ExpectTokenBindingParams as its list of Token Binding
478	// paramters.
479	ExpectTokenBindingParams []byte
480
481	// PreSharedKey, if not nil, is the pre-shared key to use with
482	// the PSK cipher suites.
483	PreSharedKey []byte
484
485	// PreSharedKeyIdentity, if not empty, is the identity to use
486	// with the PSK cipher suites.
487	PreSharedKeyIdentity string
488
489	// MaxEarlyDataSize controls the maximum number of bytes that the
490	// server will accept in early data and advertise in a
491	// NewSessionTicketMsg. If 0, no early data will be accepted and
492	// the early_data extension in the NewSessionTicketMsg will be omitted.
493	MaxEarlyDataSize uint32
494
495	// SRTPProtectionProfiles, if not nil, is the list of SRTP
496	// protection profiles to offer in DTLS-SRTP.
497	SRTPProtectionProfiles []uint16
498
499	// SignSignatureAlgorithms, if not nil, overrides the default set of
500	// supported signature algorithms to sign with.
501	SignSignatureAlgorithms []signatureAlgorithm
502
503	// VerifySignatureAlgorithms, if not nil, overrides the default set of
504	// supported signature algorithms that are accepted.
505	VerifySignatureAlgorithms []signatureAlgorithm
506
507	// QUICTransportParams, if not empty, will be sent in the QUIC
508	// transport parameters extension.
509	QUICTransportParams []byte
510
511	CertCompressionAlgs map[uint16]CertCompressionAlg
512
513	// Bugs specifies optional misbehaviour to be used for testing other
514	// implementations.
515	Bugs ProtocolBugs
516
517	serverInitOnce sync.Once // guards calling (*Config).serverInit
518}
519
520type BadValue int
521
522const (
523	BadValueNone BadValue = iota
524	BadValueNegative
525	BadValueZero
526	BadValueLimit
527	BadValueLarge
528	NumBadValues
529)
530
531type RSABadValue int
532
533const (
534	RSABadValueNone RSABadValue = iota
535	RSABadValueCorrupt
536	RSABadValueTooLong
537	RSABadValueTooShort
538	RSABadValueWrongVersion1
539	RSABadValueWrongVersion2
540	RSABadValueWrongBlockType
541	RSABadValueWrongLeadingByte
542	RSABadValueNoZero
543	NumRSABadValues
544)
545
546type ProtocolBugs struct {
547	// InvalidSignature specifies that the signature in a ServerKeyExchange
548	// or CertificateVerify message should be invalid.
549	InvalidSignature bool
550
551	// SendCurve, if non-zero, causes the server to send the specified curve
552	// ID in ServerKeyExchange (TLS 1.2) or ServerHello (TLS 1.3) rather
553	// than the negotiated one.
554	SendCurve CurveID
555
556	// InvalidECDHPoint, if true, causes the ECC points in
557	// ServerKeyExchange or ClientKeyExchange messages to be invalid.
558	InvalidECDHPoint bool
559
560	// BadECDSAR controls ways in which the 'r' value of an ECDSA signature
561	// can be invalid.
562	BadECDSAR BadValue
563	BadECDSAS BadValue
564
565	// MaxPadding causes CBC records to have the maximum possible padding.
566	MaxPadding bool
567	// PaddingFirstByteBad causes the first byte of the padding to be
568	// incorrect.
569	PaddingFirstByteBad bool
570	// PaddingFirstByteBadIf255 causes the first byte of padding to be
571	// incorrect if there's a maximum amount of padding (i.e. 255 bytes).
572	PaddingFirstByteBadIf255 bool
573
574	// FailIfNotFallbackSCSV causes a server handshake to fail if the
575	// client doesn't send the fallback SCSV value.
576	FailIfNotFallbackSCSV bool
577
578	// DuplicateExtension causes an extra empty extension of bogus type to
579	// be emitted in either the ClientHello or the ServerHello.
580	DuplicateExtension bool
581
582	// UnauthenticatedECDH causes the server to pretend ECDHE_RSA
583	// and ECDHE_ECDSA cipher suites are actually ECDH_anon. No
584	// Certificate message is sent and no signature is added to
585	// ServerKeyExchange.
586	UnauthenticatedECDH bool
587
588	// SkipHelloVerifyRequest causes a DTLS server to skip the
589	// HelloVerifyRequest message.
590	SkipHelloVerifyRequest bool
591
592	// SkipCertificateStatus, if true, causes the server to skip the
593	// CertificateStatus message. This is legal because CertificateStatus is
594	// optional, even with a status_request in ServerHello.
595	SkipCertificateStatus bool
596
597	// SkipServerKeyExchange causes the server to skip sending
598	// ServerKeyExchange messages.
599	SkipServerKeyExchange bool
600
601	// SkipNewSessionTicket causes the server to skip sending the
602	// NewSessionTicket message despite promising to in ServerHello.
603	SkipNewSessionTicket bool
604
605	// UseFirstSessionTicket causes the client to cache only the first session
606	// ticket received.
607	UseFirstSessionTicket bool
608
609	// SkipClientCertificate causes the client to skip the Certificate
610	// message.
611	SkipClientCertificate bool
612
613	// SkipChangeCipherSpec causes the implementation to skip
614	// sending the ChangeCipherSpec message (and adjusting cipher
615	// state accordingly for the Finished message).
616	SkipChangeCipherSpec bool
617
618	// SkipFinished causes the implementation to skip sending the Finished
619	// message.
620	SkipFinished bool
621
622	// SkipEndOfEarlyData causes the implementation to skip
623	// end_of_early_data.
624	SkipEndOfEarlyData bool
625
626	// NonEmptyEndOfEarlyData causes the implementation to end an extra byte in the
627	// EndOfEarlyData.
628	NonEmptyEndOfEarlyData bool
629
630	// SkipCertificateVerify, if true causes peer to skip sending a
631	// CertificateVerify message after the Certificate message.
632	SkipCertificateVerify bool
633
634	// EarlyChangeCipherSpec causes the client to send an early
635	// ChangeCipherSpec message before the ClientKeyExchange. A value of
636	// zero disables this behavior. One and two configure variants for
637	// 1.0.1 and 0.9.8 modes, respectively.
638	EarlyChangeCipherSpec int
639
640	// StrayChangeCipherSpec causes every pre-ChangeCipherSpec handshake
641	// message in DTLS to be prefaced by stray ChangeCipherSpec record. This
642	// may be used to test DTLS's handling of reordered ChangeCipherSpec.
643	StrayChangeCipherSpec bool
644
645	// ReorderChangeCipherSpec causes the ChangeCipherSpec message to be
646	// sent at start of each flight in DTLS. Unlike EarlyChangeCipherSpec,
647	// the cipher change happens at the usual time.
648	ReorderChangeCipherSpec bool
649
650	// FragmentAcrossChangeCipherSpec causes the implementation to fragment
651	// the Finished (or NextProto) message around the ChangeCipherSpec
652	// messages.
653	FragmentAcrossChangeCipherSpec bool
654
655	// SendExtraChangeCipherSpec causes the implementation to send extra
656	// ChangeCipherSpec messages.
657	SendExtraChangeCipherSpec int
658
659	// SendPostHandshakeChangeCipherSpec causes the implementation to send
660	// a ChangeCipherSpec record before every application data record.
661	SendPostHandshakeChangeCipherSpec bool
662
663	// SendUnencryptedFinished, if true, causes the Finished message to be
664	// send unencrypted before ChangeCipherSpec rather than after it.
665	SendUnencryptedFinished bool
666
667	// PartialEncryptedExtensionsWithServerHello, if true, causes the TLS
668	// 1.3 server to send part of EncryptedExtensions unencrypted
669	// in the same record as ServerHello.
670	PartialEncryptedExtensionsWithServerHello bool
671
672	// PartialClientFinishedWithClientHello, if true, causes the TLS 1.2
673	// or TLS 1.3 client to send part of Finished unencrypted in the same
674	// record as ClientHello.
675	PartialClientFinishedWithClientHello bool
676
677	// PartialClientFinishedWithSecondClientHello, if true, causes the
678	// TLS 1.3 client to send part of Finished unencrypted in the same
679	// record as the second ClientHello.
680	PartialClientFinishedWithSecondClientHello bool
681
682	// PartialEndOfEarlyDataWithClientHello, if true, causes the TLS 1.3
683	// client to send part of EndOfEarlyData unencrypted in the same record
684	// as ClientHello.
685	PartialEndOfEarlyDataWithClientHello bool
686
687	// PartialSecondClientHelloAfterFirst, if true, causes the TLS 1.3 client
688	// to send part of the second ClientHello in the same record as the first
689	// one.
690	PartialSecondClientHelloAfterFirst bool
691
692	// PartialClientKeyExchangeWithClientHello, if true, causes the TLS 1.2
693	// client to send part of the ClientKeyExchange in the same record as
694	// the ClientHello.
695	PartialClientKeyExchangeWithClientHello bool
696
697	// PartialNewSessionTicketWithServerHelloDone, if true, causes the TLS 1.2
698	// server to send part of the NewSessionTicket in the same record as
699	// ServerHelloDone.
700	PartialNewSessionTicketWithServerHelloDone bool
701
702	// PartialNewSessionTicketWithServerHelloDone, if true, causes the TLS 1.2
703	// server to send part of the Finshed in the same record as ServerHelloDone.
704	PartialFinishedWithServerHelloDone bool
705
706	// PartialServerHelloWithHelloRetryRequest, if true, causes the TLS 1.3
707	// server to send part of the ServerHello in the same record as
708	// HelloRetryRequest.
709	PartialServerHelloWithHelloRetryRequest bool
710
711	// TrailingDataWithFinished, if true, causes the record containing the
712	// Finished message to include an extra byte of data at the end.
713	TrailingDataWithFinished bool
714
715	// SendV2ClientHello causes the client to send a V2ClientHello
716	// instead of a normal ClientHello.
717	SendV2ClientHello bool
718
719	// SendFallbackSCSV causes the client to include
720	// TLS_FALLBACK_SCSV in the ClientHello.
721	SendFallbackSCSV bool
722
723	// SendRenegotiationSCSV causes the client to include the renegotiation
724	// SCSV in the ClientHello.
725	SendRenegotiationSCSV bool
726
727	// MaxHandshakeRecordLength, if non-zero, is the maximum size of a
728	// handshake record. Handshake messages will be split into multiple
729	// records at the specified size, except that the client_version will
730	// never be fragmented. For DTLS, it is the maximum handshake fragment
731	// size, not record size; DTLS allows multiple handshake fragments in a
732	// single handshake record. See |PackHandshakeFragments|.
733	MaxHandshakeRecordLength int
734
735	// FragmentClientVersion will allow MaxHandshakeRecordLength to apply to
736	// the first 6 bytes of the ClientHello.
737	FragmentClientVersion bool
738
739	// FragmentAlert will cause all alerts to be fragmented across
740	// two records.
741	FragmentAlert bool
742
743	// DoubleAlert will cause all alerts to be sent as two copies packed
744	// within one record.
745	DoubleAlert bool
746
747	// SendSpuriousAlert, if non-zero, will cause an spurious, unwanted
748	// alert to be sent.
749	SendSpuriousAlert alert
750
751	// BadRSAClientKeyExchange causes the client to send a corrupted RSA
752	// ClientKeyExchange which would not pass padding checks.
753	BadRSAClientKeyExchange RSABadValue
754
755	// RenewTicketOnResume causes the server to renew the session ticket and
756	// send a NewSessionTicket message during an abbreviated handshake.
757	RenewTicketOnResume bool
758
759	// SendClientVersion, if non-zero, causes the client to send the
760	// specified value in the ClientHello version field.
761	SendClientVersion uint16
762
763	// OmitSupportedVersions, if true, causes the client to omit the
764	// supported versions extension.
765	OmitSupportedVersions bool
766
767	// SendSupportedVersions, if non-empty, causes the client to send a
768	// supported versions extension with the values from array.
769	SendSupportedVersions []uint16
770
771	// NegotiateVersion, if non-zero, causes the server to negotiate the
772	// specifed wire version rather than the version supported by either
773	// peer.
774	NegotiateVersion uint16
775
776	// NegotiateVersionOnRenego, if non-zero, causes the server to negotiate
777	// the specified wire version on renegotiation rather than retaining it.
778	NegotiateVersionOnRenego uint16
779
780	// ExpectFalseStart causes the server to, on full handshakes,
781	// expect the peer to False Start; the server Finished message
782	// isn't sent until we receive an application data record
783	// from the peer.
784	ExpectFalseStart bool
785
786	// AlertBeforeFalseStartTest, if non-zero, causes the server to, on full
787	// handshakes, send an alert just before reading the application data
788	// record to test False Start. This can be used in a negative False
789	// Start test to determine whether the peer processed the alert (and
790	// closed the connection) before or after sending app data.
791	AlertBeforeFalseStartTest alert
792
793	// ExpectServerName, if not empty, is the hostname the client
794	// must specify in the server_name extension.
795	ExpectServerName string
796
797	// SwapNPNAndALPN switches the relative order between NPN and ALPN in
798	// both ClientHello and ServerHello.
799	SwapNPNAndALPN bool
800
801	// ALPNProtocol, if not nil, sets the ALPN protocol that a server will
802	// return.
803	ALPNProtocol *string
804
805	// AlwaysNegotiateApplicationSettings, if true, causes the server to
806	// negotiate ALPS for a protocol even if the client did not support it or
807	// the version is wrong.
808	AlwaysNegotiateApplicationSettings bool
809
810	// SendApplicationSettingsWithEarlyData, if true, causes the client and
811	// server to send the application_settings extension with early data,
812	// rather than letting them implicitly carry over.
813	SendApplicationSettingsWithEarlyData bool
814
815	// AlwaysSendClientEncryptedExtension, if true, causes the client to always
816	// send a, possibly empty, client EncryptedExtensions message.
817	AlwaysSendClientEncryptedExtensions bool
818
819	// OmitClientEncryptedExtensions, if true, causes the client to omit the
820	// client EncryptedExtensions message.
821	OmitClientEncryptedExtensions bool
822
823	// OmitClientApplicationSettings, if true, causes the client to omit the
824	// application_settings extension but still send EncryptedExtensions.
825	OmitClientApplicationSettings bool
826
827	// SendExtraClientEncryptedExtension, if true, causes the client to
828	// include an unsolicited extension in the client EncryptedExtensions
829	// message.
830	SendExtraClientEncryptedExtension bool
831
832	// AcceptAnySession causes the server to resume sessions regardless of
833	// the version associated with the session or cipher suite. It also
834	// causes the server to look in both TLS 1.2 and 1.3 extensions to
835	// process a ticket.
836	AcceptAnySession bool
837
838	// SendBothTickets, if true, causes the client to send tickets in both
839	// TLS 1.2 and 1.3 extensions.
840	SendBothTickets bool
841
842	// FilterTicket, if not nil, causes the client to modify a session
843	// ticket before sending it in a resume handshake.
844	FilterTicket func([]byte) ([]byte, error)
845
846	// TicketSessionIDLength, if non-zero, is the length of the session ID
847	// to send with a ticket resumption offer.
848	TicketSessionIDLength int
849
850	// EmptyTicketSessionID, if true, causes the client to send an empty
851	// session ID with a ticket resumption offer. For simplicity, this will
852	// also cause the client to interpret a ServerHello with empty session
853	// ID as a resumption. (A client which sends empty session ID is
854	// normally expected to look ahead for ChangeCipherSpec.)
855	EmptyTicketSessionID bool
856
857	// SendClientHelloSessionID, if not nil, is the session ID sent in the
858	// ClientHello.
859	SendClientHelloSessionID []byte
860
861	// ExpectClientHelloSessionID, if true, causes the server to fail the
862	// connection if there is not a session ID in the ClientHello.
863	ExpectClientHelloSessionID bool
864
865	// EchoSessionIDInFullHandshake, if true, causes the server to echo the
866	// ClientHello session ID, even in TLS 1.2 full handshakes.
867	EchoSessionIDInFullHandshake bool
868
869	// ExpectNoTLS12Session, if true, causes the server to fail the
870	// connection if either a session ID or TLS 1.2 ticket is offered.
871	ExpectNoTLS12Session bool
872
873	// ExpectNoTLS13PSK, if true, causes the server to fail the connection
874	// if a TLS 1.3 PSK is offered.
875	ExpectNoTLS13PSK bool
876
877	// ExpectNoTLS13PSKAfterHRR, if true, causes the server to fail the connection
878	// if a TLS 1.3 PSK is offered after HRR.
879	ExpectNoTLS13PSKAfterHRR bool
880
881	// RequireExtendedMasterSecret, if true, requires that the peer support
882	// the extended master secret option.
883	RequireExtendedMasterSecret bool
884
885	// NoExtendedMasterSecret causes the client and server to behave as if
886	// they didn't support an extended master secret in the initial
887	// handshake.
888	NoExtendedMasterSecret bool
889
890	// NoExtendedMasterSecretOnRenegotiation causes the client and server to
891	// behave as if they didn't support an extended master secret in
892	// renegotiation handshakes.
893	NoExtendedMasterSecretOnRenegotiation bool
894
895	// EmptyRenegotiationInfo causes the renegotiation extension to be
896	// empty in a renegotiation handshake.
897	EmptyRenegotiationInfo bool
898
899	// BadRenegotiationInfo causes the renegotiation extension value in a
900	// renegotiation handshake to be incorrect at the start.
901	BadRenegotiationInfo bool
902
903	// BadRenegotiationInfoEnd causes the renegotiation extension value in
904	// a renegotiation handshake to be incorrect at the end.
905	BadRenegotiationInfoEnd bool
906
907	// NoRenegotiationInfo disables renegotiation info support in all
908	// handshakes.
909	NoRenegotiationInfo bool
910
911	// NoRenegotiationInfoInInitial disables renegotiation info support in
912	// the initial handshake.
913	NoRenegotiationInfoInInitial bool
914
915	// NoRenegotiationInfoAfterInitial disables renegotiation info support
916	// in renegotiation handshakes.
917	NoRenegotiationInfoAfterInitial bool
918
919	// RequireRenegotiationInfo, if true, causes the client to return an
920	// error if the server doesn't reply with the renegotiation extension.
921	RequireRenegotiationInfo bool
922
923	// SequenceNumberMapping, if non-nil, is the mapping function to apply
924	// to the sequence number of outgoing packets. For both TLS and DTLS,
925	// the two most-significant bytes in the resulting sequence number are
926	// ignored so that the DTLS epoch cannot be changed.
927	SequenceNumberMapping func(uint64) uint64
928
929	// RSAEphemeralKey, if true, causes the server to send a
930	// ServerKeyExchange message containing an ephemeral key (as in
931	// RSA_EXPORT) in the plain RSA key exchange.
932	RSAEphemeralKey bool
933
934	// SRTPMasterKeyIdentifer, if not empty, is the SRTP MKI value that the
935	// client offers when negotiating SRTP. MKI support is still missing so
936	// the peer must still send none.
937	SRTPMasterKeyIdentifer string
938
939	// SendSRTPProtectionProfile, if non-zero, is the SRTP profile that the
940	// server sends in the ServerHello instead of the negotiated one.
941	SendSRTPProtectionProfile uint16
942
943	// NoSignatureAlgorithms, if true, causes the client to omit the
944	// signature and hashes extension.
945	//
946	// For a server, it will cause an empty list to be sent in the
947	// CertificateRequest message. None the less, the configured set will
948	// still be enforced.
949	NoSignatureAlgorithms bool
950
951	// NoSupportedCurves, if true, causes the client to omit the
952	// supported_curves extension.
953	NoSupportedCurves bool
954
955	// RequireSameRenegoClientVersion, if true, causes the server
956	// to require that all ClientHellos match in offered version
957	// across a renego.
958	RequireSameRenegoClientVersion bool
959
960	// ExpectInitialRecordVersion, if non-zero, is the expected value of
961	// record-layer version field before the protocol version is determined.
962	ExpectInitialRecordVersion uint16
963
964	// SendRecordVersion, if non-zero, is the value to send as the
965	// record-layer version.
966	SendRecordVersion uint16
967
968	// SendInitialRecordVersion, if non-zero, is the value to send as the
969	// record-layer version before the protocol version is determined.
970	SendInitialRecordVersion uint16
971
972	// MaxPacketLength, if non-zero, is the maximum acceptable size for a
973	// packet.
974	MaxPacketLength int
975
976	// SendCipherSuite, if non-zero, is the cipher suite value that the
977	// server will send in the ServerHello. This does not affect the cipher
978	// the server believes it has actually negotiated.
979	SendCipherSuite uint16
980
981	// SendCipherSuites, if not nil, is the cipher suite list that the
982	// client will send in the ClientHello. This does not affect the cipher
983	// the client believes it has actually offered.
984	SendCipherSuites []uint16
985
986	// AppDataBeforeHandshake, if not nil, causes application data to be
987	// sent immediately before the first handshake message.
988	AppDataBeforeHandshake []byte
989
990	// AppDataAfterChangeCipherSpec, if not nil, causes application data to
991	// be sent immediately after ChangeCipherSpec.
992	AppDataAfterChangeCipherSpec []byte
993
994	// AlertAfterChangeCipherSpec, if non-zero, causes an alert to be sent
995	// immediately after ChangeCipherSpec.
996	AlertAfterChangeCipherSpec alert
997
998	// TimeoutSchedule is the schedule of packet drops and simulated
999	// timeouts for before each handshake leg from the peer.
1000	TimeoutSchedule []time.Duration
1001
1002	// PacketAdaptor is the packetAdaptor to use to simulate timeouts.
1003	PacketAdaptor *packetAdaptor
1004
1005	// MockQUICTransport is the mockQUICTransport used when testing
1006	// QUIC interfaces.
1007	MockQUICTransport *mockQUICTransport
1008
1009	// ReorderHandshakeFragments, if true, causes handshake fragments in
1010	// DTLS to overlap and be sent in the wrong order. It also causes
1011	// pre-CCS flights to be sent twice. (Post-CCS flights consist of
1012	// Finished and will trigger a spurious retransmit.)
1013	ReorderHandshakeFragments bool
1014
1015	// ReverseHandshakeFragments, if true, causes handshake fragments in
1016	// DTLS to be reversed within a flight.
1017	ReverseHandshakeFragments bool
1018
1019	// MixCompleteMessageWithFragments, if true, causes handshake
1020	// messages in DTLS to redundantly both fragment the message
1021	// and include a copy of the full one.
1022	MixCompleteMessageWithFragments bool
1023
1024	// RetransmitFinished, if true, causes the DTLS Finished message to be
1025	// sent twice.
1026	RetransmitFinished bool
1027
1028	// SendInvalidRecordType, if true, causes a record with an invalid
1029	// content type to be sent immediately following the handshake.
1030	SendInvalidRecordType bool
1031
1032	// SendWrongMessageType, if non-zero, causes messages of the specified
1033	// type to be sent with the wrong value.
1034	SendWrongMessageType byte
1035
1036	// SendTrailingMessageData, if non-zero, causes messages of the
1037	// specified type to be sent with trailing data.
1038	SendTrailingMessageData byte
1039
1040	// FragmentMessageTypeMismatch, if true, causes all non-initial
1041	// handshake fragments in DTLS to have the wrong message type.
1042	FragmentMessageTypeMismatch bool
1043
1044	// FragmentMessageLengthMismatch, if true, causes all non-initial
1045	// handshake fragments in DTLS to have the wrong message length.
1046	FragmentMessageLengthMismatch bool
1047
1048	// SplitFragments, if non-zero, causes the handshake fragments in DTLS
1049	// to be split across two records. The value of |SplitFragments| is the
1050	// number of bytes in the first fragment.
1051	SplitFragments int
1052
1053	// SendEmptyFragments, if true, causes handshakes to include empty
1054	// fragments in DTLS.
1055	SendEmptyFragments bool
1056
1057	// SendSplitAlert, if true, causes an alert to be sent with the header
1058	// and record body split across multiple packets. The peer should
1059	// discard these packets rather than process it.
1060	SendSplitAlert bool
1061
1062	// FailIfResumeOnRenego, if true, causes renegotiations to fail if the
1063	// client offers a resumption or the server accepts one.
1064	FailIfResumeOnRenego bool
1065
1066	// IgnorePeerCipherPreferences, if true, causes the peer's cipher
1067	// preferences to be ignored.
1068	IgnorePeerCipherPreferences bool
1069
1070	// IgnorePeerSignatureAlgorithmPreferences, if true, causes the peer's
1071	// signature algorithm preferences to be ignored.
1072	IgnorePeerSignatureAlgorithmPreferences bool
1073
1074	// IgnorePeerCurvePreferences, if true, causes the peer's curve
1075	// preferences to be ignored.
1076	IgnorePeerCurvePreferences bool
1077
1078	// BadFinished, if true, causes the Finished hash to be broken.
1079	BadFinished bool
1080
1081	// PackHandshakeFragments, if true, causes handshake fragments in DTLS
1082	// to be packed into individual handshake records, up to the specified
1083	// record size.
1084	PackHandshakeFragments int
1085
1086	// PackHandshakeRecords, if non-zero, causes handshake and
1087	// ChangeCipherSpec records in DTLS to be packed into individual
1088	// packets, up to the specified packet size.
1089	PackHandshakeRecords int
1090
1091	// PackAppDataWithHandshake, if true, extends PackHandshakeRecords to
1092	// additionally include the first application data record sent after the
1093	// final Finished message in a handshake. (If the final Finished message
1094	// is sent by the peer, this option has no effect.) This requires that
1095	// the runner rather than shim speak first in a given test.
1096	PackAppDataWithHandshake bool
1097
1098	// SplitAndPackAppData, if true, causes application data in DTLS to be
1099	// split into two records each and packed into one packet.
1100	SplitAndPackAppData bool
1101
1102	// PackHandshakeFlight, if true, causes each handshake flight in TLS to
1103	// be packed into records, up to the largest size record available.
1104	PackHandshakeFlight bool
1105
1106	// AdvertiseAllConfiguredCiphers, if true, causes the client to
1107	// advertise all configured cipher suite values.
1108	AdvertiseAllConfiguredCiphers bool
1109
1110	// EmptyCertificateList, if true, causes the server to send an empty
1111	// certificate list in the Certificate message.
1112	EmptyCertificateList bool
1113
1114	// ExpectNewTicket, if true, causes the client to abort if it does not
1115	// receive a new ticket.
1116	ExpectNewTicket bool
1117
1118	// RequireClientHelloSize, if not zero, is the required length in bytes
1119	// of the ClientHello /record/. This is checked by the server.
1120	RequireClientHelloSize int
1121
1122	// CustomExtension, if not empty, contains the contents of an extension
1123	// that will be added to client/server hellos.
1124	CustomExtension string
1125
1126	// CustomUnencryptedExtension, if not empty, contains the contents of
1127	// an extension that will be added to ServerHello in TLS 1.3.
1128	CustomUnencryptedExtension string
1129
1130	// ExpectedCustomExtension, if not nil, contains the expected contents
1131	// of a custom extension.
1132	ExpectedCustomExtension *string
1133
1134	// CustomTicketExtension, if not empty, contains the contents of an
1135	// extension what will be added to NewSessionTicket in TLS 1.3.
1136	CustomTicketExtension string
1137
1138	// CustomTicketExtension, if not empty, contains the contents of an
1139	// extension what will be added to HelloRetryRequest in TLS 1.3.
1140	CustomHelloRetryRequestExtension string
1141
1142	// NoCloseNotify, if true, causes the close_notify alert to be skipped
1143	// on connection shutdown.
1144	NoCloseNotify bool
1145
1146	// SendAlertOnShutdown, if non-zero, is the alert to send instead of
1147	// close_notify on shutdown.
1148	SendAlertOnShutdown alert
1149
1150	// ExpectCloseNotify, if true, requires a close_notify from the peer on
1151	// shutdown. Records from the peer received after close_notify is sent
1152	// are not discard.
1153	ExpectCloseNotify bool
1154
1155	// SendLargeRecords, if true, allows outgoing records to be sent
1156	// arbitrarily large.
1157	SendLargeRecords bool
1158
1159	// NegotiateALPNAndNPN, if true, causes the server to negotiate both
1160	// ALPN and NPN in the same connetion.
1161	NegotiateALPNAndNPN bool
1162
1163	// SendALPN, if non-empty, causes the server to send the specified
1164	// string in the ALPN extension regardless of the content or presence of
1165	// the client offer.
1166	SendALPN string
1167
1168	// SendUnencryptedALPN, if non-empty, causes the server to send the
1169	// specified string in a ServerHello ALPN extension in TLS 1.3.
1170	SendUnencryptedALPN string
1171
1172	// SendEmptySessionTicket, if true, causes the server to send an empty
1173	// session ticket.
1174	SendEmptySessionTicket bool
1175
1176	// SendPSKKeyExchangeModes, if present, determines the PSK key exchange modes
1177	// to send.
1178	SendPSKKeyExchangeModes []byte
1179
1180	// ExpectNoNewSessionTicket, if present, means that the client will fail upon
1181	// receipt of a NewSessionTicket message.
1182	ExpectNoNewSessionTicket bool
1183
1184	// DuplicateTicketEarlyData causes an extra empty extension of early_data to
1185	// be sent in NewSessionTicket.
1186	DuplicateTicketEarlyData bool
1187
1188	// ExpectTicketEarlyData, if true, means that the client will fail upon
1189	// absence of the early_data extension.
1190	ExpectTicketEarlyData bool
1191
1192	// ExpectTicketAge, if non-zero, is the expected age of the ticket that the
1193	// server receives from the client.
1194	ExpectTicketAge time.Duration
1195
1196	// SendTicketAge, if non-zero, is the ticket age to be sent by the
1197	// client.
1198	SendTicketAge time.Duration
1199
1200	// FailIfSessionOffered, if true, causes the server to fail any
1201	// connections where the client offers a non-empty session ID or session
1202	// ticket.
1203	FailIfSessionOffered bool
1204
1205	// SendHelloRequestBeforeEveryAppDataRecord, if true, causes a
1206	// HelloRequest handshake message to be sent before each application
1207	// data record. This only makes sense for a server.
1208	SendHelloRequestBeforeEveryAppDataRecord bool
1209
1210	// SendHelloRequestBeforeEveryHandshakeMessage, if true, causes a
1211	// HelloRequest handshake message to be sent before each handshake
1212	// message. This only makes sense for a server.
1213	SendHelloRequestBeforeEveryHandshakeMessage bool
1214
1215	// BadChangeCipherSpec, if not nil, is the body to be sent in
1216	// ChangeCipherSpec records instead of {1}.
1217	BadChangeCipherSpec []byte
1218
1219	// BadHelloRequest, if not nil, is what to send instead of a
1220	// HelloRequest.
1221	BadHelloRequest []byte
1222
1223	// RequireSessionTickets, if true, causes the client to require new
1224	// sessions use session tickets instead of session IDs.
1225	RequireSessionTickets bool
1226
1227	// RequireSessionIDs, if true, causes the client to require new sessions use
1228	// session IDs instead of session tickets.
1229	RequireSessionIDs bool
1230
1231	// NullAllCiphers, if true, causes every cipher to behave like the null
1232	// cipher.
1233	NullAllCiphers bool
1234
1235	// SendSCTListOnResume, if not nil, causes the server to send the
1236	// supplied SCT list in resumption handshakes.
1237	SendSCTListOnResume []byte
1238
1239	// SendSCTListOnRenegotiation, if not nil, causes the server to send the
1240	// supplied SCT list on renegotiation.
1241	SendSCTListOnRenegotiation []byte
1242
1243	// SendOCSPResponseOnResume, if not nil, causes the server to advertise
1244	// OCSP stapling in resumption handshakes and, if applicable, send the
1245	// supplied stapled response.
1246	SendOCSPResponseOnResume []byte
1247
1248	// SendOCSPResponseOnResume, if not nil, causes the server to send the
1249	// supplied OCSP response on renegotiation.
1250	SendOCSPResponseOnRenegotiation []byte
1251
1252	// SendExtensionOnCertificate, if not nil, causes the runner to send the
1253	// supplied bytes in the extensions on the Certificate message.
1254	SendExtensionOnCertificate []byte
1255
1256	// SendOCSPOnIntermediates, if not nil, causes the server to send the
1257	// supplied OCSP on intermediate certificates in the Certificate message.
1258	SendOCSPOnIntermediates []byte
1259
1260	// SendSCTOnIntermediates, if not nil, causes the server to send the
1261	// supplied SCT on intermediate certificates in the Certificate message.
1262	SendSCTOnIntermediates []byte
1263
1264	// SendDuplicateCertExtensions, if true, causes the server to send an extra
1265	// copy of the OCSP/SCT extensions in the Certificate message.
1266	SendDuplicateCertExtensions bool
1267
1268	// ExpectNoExtensionsOnIntermediate, if true, causes the client to
1269	// reject extensions on intermediate certificates.
1270	ExpectNoExtensionsOnIntermediate bool
1271
1272	// RecordPadding is the number of bytes of padding to add to each
1273	// encrypted record in TLS 1.3.
1274	RecordPadding int
1275
1276	// OmitRecordContents, if true, causes encrypted records in TLS 1.3 to
1277	// be missing their body and content type. Padding, if configured, is
1278	// still added.
1279	OmitRecordContents bool
1280
1281	// OuterRecordType, if non-zero, is the outer record type to use instead
1282	// of application data.
1283	OuterRecordType recordType
1284
1285	// SendSignatureAlgorithm, if non-zero, causes all signatures to be sent
1286	// with the given signature algorithm rather than the one negotiated.
1287	SendSignatureAlgorithm signatureAlgorithm
1288
1289	// SkipECDSACurveCheck, if true, causes all ECDSA curve checks to be
1290	// skipped.
1291	SkipECDSACurveCheck bool
1292
1293	// IgnoreSignatureVersionChecks, if true, causes all signature
1294	// algorithms to be enabled at all TLS versions.
1295	IgnoreSignatureVersionChecks bool
1296
1297	// NegotiateRenegotiationInfoAtAllVersions, if true, causes
1298	// Renegotiation Info to be negotiated at all versions.
1299	NegotiateRenegotiationInfoAtAllVersions bool
1300
1301	// NegotiateNPNAtAllVersions, if true, causes NPN to be negotiated at
1302	// all versions.
1303	NegotiateNPNAtAllVersions bool
1304
1305	// NegotiateEMSAtAllVersions, if true, causes EMS to be negotiated at
1306	// all versions.
1307	NegotiateEMSAtAllVersions bool
1308
1309	// AdvertiseTicketExtension, if true, causes the ticket extension to be
1310	// advertised in server extensions
1311	AdvertiseTicketExtension bool
1312
1313	// NegotiatePSKResumption, if true, causes the server to attempt pure PSK
1314	// resumption.
1315	NegotiatePSKResumption bool
1316
1317	// AlwaysSelectPSKIdentity, if true, causes the server in TLS 1.3 to
1318	// always acknowledge a session, regardless of one was offered.
1319	AlwaysSelectPSKIdentity bool
1320
1321	// SelectPSKIdentityOnResume, if non-zero, causes the server to select
1322	// the specified PSK identity index rather than the actual value.
1323	SelectPSKIdentityOnResume uint16
1324
1325	// ExtraPSKIdentity, if true, causes the client to send an extra PSK
1326	// identity.
1327	ExtraPSKIdentity bool
1328
1329	// MissingKeyShare, if true, causes the TLS 1.3 implementation to skip
1330	// sending a key_share extension and use the zero ECDHE secret
1331	// instead.
1332	MissingKeyShare bool
1333
1334	// SecondClientHelloMissingKeyShare, if true, causes the second TLS 1.3
1335	// ClientHello to skip sending a key_share extension and use the zero
1336	// ECDHE secret instead.
1337	SecondClientHelloMissingKeyShare bool
1338
1339	// MisinterpretHelloRetryRequestCurve, if non-zero, causes the TLS 1.3
1340	// client to pretend the server requested a HelloRetryRequest with the
1341	// given curve rather than the actual one.
1342	MisinterpretHelloRetryRequestCurve CurveID
1343
1344	// DuplicateKeyShares, if true, causes the TLS 1.3 client to send two
1345	// copies of each KeyShareEntry.
1346	DuplicateKeyShares bool
1347
1348	// SendEarlyAlert, if true, sends a fatal alert after the ClientHello.
1349	SendEarlyAlert bool
1350
1351	// SendFakeEarlyDataLength, if non-zero, is the amount of early data to
1352	// send after the ClientHello.
1353	SendFakeEarlyDataLength int
1354
1355	// SendStrayEarlyHandshake, if non-zero, causes the client to send a stray
1356	// handshake record before sending end of early data.
1357	SendStrayEarlyHandshake bool
1358
1359	// OmitEarlyDataExtension, if true, causes the early data extension to
1360	// be omitted in the ClientHello.
1361	OmitEarlyDataExtension bool
1362
1363	// SendEarlyDataOnSecondClientHello, if true, causes the TLS 1.3 client to
1364	// send early data after the second ClientHello.
1365	SendEarlyDataOnSecondClientHello bool
1366
1367	// InterleaveEarlyData, if true, causes the TLS 1.3 client to send early
1368	// data interleaved with the second ClientHello and the client Finished.
1369	InterleaveEarlyData bool
1370
1371	// SendEarlyData causes a TLS 1.3 client to send the provided data
1372	// in application data records immediately after the ClientHello,
1373	// provided that the client offers a TLS 1.3 session. It will do this
1374	// whether or not the server advertised early data for the ticket.
1375	SendEarlyData [][]byte
1376
1377	// ExpectEarlyDataAccepted causes a TLS 1.3 client to check that early data
1378	// was accepted by the server.
1379	ExpectEarlyDataAccepted bool
1380
1381	// AlwaysAcceptEarlyData causes a TLS 1.3 server to always accept early data
1382	// regardless of ALPN mismatch.
1383	AlwaysAcceptEarlyData bool
1384
1385	// AlwaysRejectEarlyData causes a TLS 1.3 server to always reject early data.
1386	AlwaysRejectEarlyData bool
1387
1388	// SendEarlyDataExtension, if true, causes a TLS 1.3 server to send the
1389	// early_data extension in EncryptedExtensions, independent of whether
1390	// it was accepted.
1391	SendEarlyDataExtension bool
1392
1393	// ExpectEarlyData causes a TLS 1.3 server to read application
1394	// data after the ClientHello (assuming the server is able to
1395	// derive the key under which the data is encrypted) before it
1396	// sends a ServerHello. It checks that the application data it
1397	// reads matches what is provided in ExpectEarlyData and errors if
1398	// the number of records or their content do not match.
1399	ExpectEarlyData [][]byte
1400
1401	// ExpectLateEarlyData causes a TLS 1.3 server to read application
1402	// data after the ServerFinished (assuming the server is able to
1403	// derive the key under which the data is encrypted) before it
1404	// sends the ClientFinished. It checks that the application data it
1405	// reads matches what is provided in ExpectLateEarlyData and errors if
1406	// the number of records or their content do not match.
1407	ExpectLateEarlyData [][]byte
1408
1409	// SendHalfRTTData causes a TLS 1.3 server to send the provided
1410	// data in application data records before reading the client's
1411	// Finished message.
1412	SendHalfRTTData [][]byte
1413
1414	// ExpectHalfRTTData causes a TLS 1.3 client, if 0-RTT was accepted, to
1415	// read application data after reading the server's Finished message and
1416	// before sending any subsequent handshake messages. It checks that the
1417	// application data it reads matches what is provided in
1418	// ExpectHalfRTTData and errors if the number of records or their
1419	// content do not match.
1420	ExpectHalfRTTData [][]byte
1421
1422	// EmptyEncryptedExtensions, if true, causes the TLS 1.3 server to
1423	// emit an empty EncryptedExtensions block.
1424	EmptyEncryptedExtensions bool
1425
1426	// EncryptedExtensionsWithKeyShare, if true, causes the TLS 1.3 server to
1427	// include the KeyShare extension in the EncryptedExtensions block.
1428	EncryptedExtensionsWithKeyShare bool
1429
1430	// AlwaysSendHelloRetryRequest, if true, causes a HelloRetryRequest to
1431	// be sent by the server, even if empty.
1432	AlwaysSendHelloRetryRequest bool
1433
1434	// SecondHelloRetryRequest, if true, causes the TLS 1.3 server to send
1435	// two HelloRetryRequests instead of one.
1436	SecondHelloRetryRequest bool
1437
1438	// SendHelloRetryRequestCurve, if non-zero, causes the server to send
1439	// the specified curve in a HelloRetryRequest.
1440	SendHelloRetryRequestCurve CurveID
1441
1442	// SendHelloRetryRequestCipherSuite, if non-zero, causes the server to send
1443	// the specified cipher suite in a HelloRetryRequest.
1444	SendHelloRetryRequestCipherSuite uint16
1445
1446	// SendHelloRetryRequestCookie, if not nil, contains a cookie to be
1447	// sent by the server in HelloRetryRequest.
1448	SendHelloRetryRequestCookie []byte
1449
1450	// DuplicateHelloRetryRequestExtensions, if true, causes all
1451	// HelloRetryRequest extensions to be sent twice.
1452	DuplicateHelloRetryRequestExtensions bool
1453
1454	// SendServerHelloVersion, if non-zero, causes the server to send the
1455	// specified value in ServerHello version field.
1456	SendServerHelloVersion uint16
1457
1458	// SendServerSupportedVersionExtension, if non-zero, causes the server to send
1459	// the specified value in supported_versions extension in the ServerHello (but
1460	// not the HelloRetryRequest).
1461	SendServerSupportedVersionExtension uint16
1462
1463	// OmitServerSupportedVersionExtension, if true, causes the server to
1464	// omit the supported_versions extension in the ServerHello (but not the
1465	// HelloRetryRequest)
1466	OmitServerSupportedVersionExtension bool
1467
1468	// SkipHelloRetryRequest, if true, causes the TLS 1.3 server to not send
1469	// HelloRetryRequest.
1470	SkipHelloRetryRequest bool
1471
1472	// PackHelloRequestWithFinished, if true, causes the TLS server to send
1473	// HelloRequest in the same record as Finished.
1474	PackHelloRequestWithFinished bool
1475
1476	// ExpectMissingKeyShare, if true, causes the TLS server to fail the
1477	// connection if the selected curve appears in the client's initial
1478	// ClientHello. That is, it requires that a HelloRetryRequest be sent.
1479	ExpectMissingKeyShare bool
1480
1481	// SendExtraFinished, if true, causes an extra Finished message to be
1482	// sent.
1483	SendExtraFinished bool
1484
1485	// SendRequestContext, if not empty, is the request context to send in
1486	// a TLS 1.3 CertificateRequest.
1487	SendRequestContext []byte
1488
1489	// OmitCertificateRequestAlgorithms, if true, omits the signature_algorithm
1490	// extension in a TLS 1.3 CertificateRequest.
1491	OmitCertificateRequestAlgorithms bool
1492
1493	// SendCustomCertificateRequest, if non-zero, send an additional custom
1494	// extension in a TLS 1.3 CertificateRequest.
1495	SendCustomCertificateRequest uint16
1496
1497	// SendSNIWarningAlert, if true, causes the server to send an
1498	// unrecognized_name alert before the ServerHello.
1499	SendSNIWarningAlert bool
1500
1501	// SendCompressionMethods, if not nil, is the compression method list to
1502	// send in the ClientHello.
1503	SendCompressionMethods []byte
1504
1505	// SendCompressionMethod is the compression method to send in the
1506	// ServerHello.
1507	SendCompressionMethod byte
1508
1509	// AlwaysSendPreSharedKeyIdentityHint, if true, causes the server to
1510	// always send a ServerKeyExchange for PSK ciphers, even if the identity
1511	// hint is empty.
1512	AlwaysSendPreSharedKeyIdentityHint bool
1513
1514	// TrailingKeyShareData, if true, causes the client key share list to
1515	// include a trailing byte.
1516	TrailingKeyShareData bool
1517
1518	// InvalidChannelIDSignature, if true, causes the client to generate an
1519	// invalid Channel ID signature.
1520	InvalidChannelIDSignature bool
1521
1522	// ExpectGREASE, if true, causes messages without GREASE values to be
1523	// rejected. See draft-davidben-tls-grease-01.
1524	ExpectGREASE bool
1525
1526	// OmitPSKsOnSecondClientHello, if true, causes the client to omit the
1527	// PSK extension on the second ClientHello.
1528	OmitPSKsOnSecondClientHello bool
1529
1530	// OnlyCorruptSecondPSKBinder, if true, causes the options below to
1531	// only apply to the second PSK binder.
1532	OnlyCorruptSecondPSKBinder bool
1533
1534	// SendShortPSKBinder, if true, causes the client to send a PSK binder
1535	// that is one byte shorter than it should be.
1536	SendShortPSKBinder bool
1537
1538	// SendInvalidPSKBinder, if true, causes the client to send an invalid
1539	// PSK binder.
1540	SendInvalidPSKBinder bool
1541
1542	// SendNoPSKBinder, if true, causes the client to send no PSK binders.
1543	SendNoPSKBinder bool
1544
1545	// SendExtraPSKBinder, if true, causes the client to send an extra PSK
1546	// binder.
1547	SendExtraPSKBinder bool
1548
1549	// PSKBinderFirst, if true, causes the client to send the PSK Binder
1550	// extension as the first extension instead of the last extension.
1551	PSKBinderFirst bool
1552
1553	// NoOCSPStapling, if true, causes the client to not request OCSP
1554	// stapling.
1555	NoOCSPStapling bool
1556
1557	// NoSignedCertificateTimestamps, if true, causes the client to not
1558	// request signed certificate timestamps.
1559	NoSignedCertificateTimestamps bool
1560
1561	// SendSupportedPointFormats, if not nil, is the list of supported point
1562	// formats to send in ClientHello or ServerHello. If set to a non-nil
1563	// empty slice, no extension will be sent.
1564	SendSupportedPointFormats []byte
1565
1566	// SendServerSupportedCurves, if true, causes the server to send its
1567	// supported curves list in the ServerHello (TLS 1.2) or
1568	// EncryptedExtensions (TLS 1.3) message. This is invalid in TLS 1.2 and
1569	// valid in TLS 1.3.
1570	SendServerSupportedCurves bool
1571
1572	// MaxReceivePlaintext, if non-zero, is the maximum plaintext record
1573	// length accepted from the peer.
1574	MaxReceivePlaintext int
1575
1576	// ExpectPackedEncryptedHandshake, if non-zero, requires that the peer maximally
1577	// pack their encrypted handshake messages, fitting at most the
1578	// specified number of plaintext bytes per record.
1579	ExpectPackedEncryptedHandshake int
1580
1581	// SendTicketLifetime, if non-zero, is the ticket lifetime to send in
1582	// NewSessionTicket messages.
1583	SendTicketLifetime time.Duration
1584
1585	// SendServerNameAck, if true, causes the server to acknowledge the SNI
1586	// extension.
1587	SendServerNameAck bool
1588
1589	// ExpectCertificateReqNames, if not nil, contains the list of X.509
1590	// names that must be sent in a CertificateRequest from the server.
1591	ExpectCertificateReqNames [][]byte
1592
1593	// RenegotiationCertificate, if not nil, is the certificate to use on
1594	// renegotiation handshakes.
1595	RenegotiationCertificate *Certificate
1596
1597	// ExpectNoCertificateAuthoritiesExtension, if true, causes the client to
1598	// reject CertificateRequest with the CertificateAuthorities extension.
1599	ExpectNoCertificateAuthoritiesExtension bool
1600
1601	// UseLegacySigningAlgorithm, if non-zero, is the signature algorithm
1602	// to use when signing in TLS 1.1 and earlier where algorithms are not
1603	// negotiated.
1604	UseLegacySigningAlgorithm signatureAlgorithm
1605
1606	// SendServerHelloAsHelloRetryRequest, if true, causes the server to
1607	// send ServerHello messages with a HelloRetryRequest type field.
1608	SendServerHelloAsHelloRetryRequest bool
1609
1610	// RejectUnsolicitedKeyUpdate, if true, causes all unsolicited
1611	// KeyUpdates from the peer to be rejected.
1612	RejectUnsolicitedKeyUpdate bool
1613
1614	// OmitExtensions, if true, causes the extensions field in ClientHello
1615	// and ServerHello messages to be omitted.
1616	OmitExtensions bool
1617
1618	// EmptyExtensions, if true, causes the extensions field in ClientHello
1619	// and ServerHello messages to be present, but empty.
1620	EmptyExtensions bool
1621
1622	// ExpectOmitExtensions, if true, causes the client to reject
1623	// ServerHello messages that do not omit extensions.
1624	ExpectOmitExtensions bool
1625
1626	// ExpectRecordSplitting, if true, causes application records to only be
1627	// accepted if they follow a 1/n-1 record split.
1628	ExpectRecordSplitting bool
1629
1630	// PadClientHello, if non-zero, pads the ClientHello to a multiple of
1631	// that many bytes.
1632	PadClientHello int
1633
1634	// SendTLS13DowngradeRandom, if true, causes the server to send the
1635	// TLS 1.3 anti-downgrade signal.
1636	SendTLS13DowngradeRandom bool
1637
1638	// CheckTLS13DowngradeRandom, if true, causes the client to check the
1639	// TLS 1.3 anti-downgrade signal regardless of its variant.
1640	CheckTLS13DowngradeRandom bool
1641
1642	// IgnoreTLS13DowngradeRandom, if true, causes the client to ignore the
1643	// TLS 1.3 anti-downgrade signal.
1644	IgnoreTLS13DowngradeRandom bool
1645
1646	// SendCompressedCoordinates, if true, causes ECDH key shares over NIST
1647	// curves to use compressed coordinates.
1648	SendCompressedCoordinates bool
1649
1650	// SetX25519HighBit, if true, causes X25519 key shares to set their
1651	// high-order bit.
1652	SetX25519HighBit bool
1653
1654	// DuplicateCompressedCertAlgs, if true, causes two, equal, certificate
1655	// compression algorithm IDs to be sent.
1656	DuplicateCompressedCertAlgs bool
1657
1658	// ExpectedCompressedCert specifies the compression algorithm ID that must be
1659	// used on this connection, or zero if there are no special requirements.
1660	ExpectedCompressedCert uint16
1661
1662	// SendCertCompressionAlgId, if not zero, sets the algorithm ID that will be
1663	// sent in the compressed certificate message.
1664	SendCertCompressionAlgId uint16
1665
1666	// SendCertUncompressedLength, if not zero, sets the uncompressed length that
1667	// will be sent in the compressed certificate message.
1668	SendCertUncompressedLength uint32
1669
1670	// SendClientHelloWithFixes, if not nil, sends the specified byte string
1671	// instead of the ClientHello. This string is incorporated into the
1672	// transcript as if it were the real ClientHello, but the handshake will
1673	// otherwise behave as if this was not sent in terms of what ciphers it
1674	// will accept, etc.
1675	//
1676	// The input is modified to match key share entries. DefaultCurves must
1677	// be configured to match. The random and session ID fields are
1678	// extracted from the ClientHello.
1679	SendClientHelloWithFixes []byte
1680
1681	// SendJDK11DowngradeRandom, if true, causes the server to send the JDK
1682	// 11 downgrade signal.
1683	SendJDK11DowngradeRandom bool
1684
1685	// ExpectJDK11DowngradeRandom is whether the client should expect the
1686	// server to send the JDK 11 downgrade signal.
1687	ExpectJDK11DowngradeRandom bool
1688
1689	// FailIfHelloRetryRequested causes a handshake failure if a server requests a
1690	// hello retry.
1691	FailIfHelloRetryRequested bool
1692
1693	// FailedIfCECPQ2Offered will cause a server to reject a ClientHello if CECPQ2
1694	// is supported.
1695	FailIfCECPQ2Offered bool
1696
1697	// ExpectKeyShares, if not nil, lists (in order) the curves that a ClientHello
1698	// should have key shares for.
1699	ExpectedKeyShares []CurveID
1700
1701	// ExpectDelegatedCredentials, if true, requires that the handshake present
1702	// delegated credentials.
1703	ExpectDelegatedCredentials bool
1704
1705	// FailIfDelegatedCredentials, if true, causes a handshake failure if the
1706	// server returns delegated credentials.
1707	FailIfDelegatedCredentials bool
1708
1709	// DisableDelegatedCredentials, if true, disables client support for delegated
1710	// credentials.
1711	DisableDelegatedCredentials bool
1712
1713	// CompatModeWithQUIC, if true, enables TLS 1.3 compatibility mode
1714	// when running over QUIC.
1715	CompatModeWithQUIC bool
1716}
1717
1718func (c *Config) serverInit() {
1719	if c.SessionTicketsDisabled {
1720		return
1721	}
1722
1723	// If the key has already been set then we have nothing to do.
1724	for _, b := range c.SessionTicketKey {
1725		if b != 0 {
1726			return
1727		}
1728	}
1729
1730	if _, err := io.ReadFull(c.rand(), c.SessionTicketKey[:]); err != nil {
1731		c.SessionTicketsDisabled = true
1732	}
1733}
1734
1735func (c *Config) rand() io.Reader {
1736	r := c.Rand
1737	if r == nil {
1738		return rand.Reader
1739	}
1740	return r
1741}
1742
1743func (c *Config) time() time.Time {
1744	t := c.Time
1745	if t == nil {
1746		t = time.Now
1747	}
1748	return t()
1749}
1750
1751func (c *Config) cipherSuites() []uint16 {
1752	s := c.CipherSuites
1753	if s == nil {
1754		s = defaultCipherSuites()
1755	}
1756	return s
1757}
1758
1759func (c *Config) minVersion(isDTLS bool) uint16 {
1760	ret := uint16(minVersion)
1761	if c != nil && c.MinVersion != 0 {
1762		ret = c.MinVersion
1763	}
1764	if isDTLS {
1765		// The lowest version of DTLS is 1.0. There is no DSSL 3.0.
1766		if ret < VersionTLS10 {
1767			return VersionTLS10
1768		}
1769		// There is no such thing as DTLS 1.1.
1770		if ret == VersionTLS11 {
1771			return VersionTLS12
1772		}
1773	}
1774	return ret
1775}
1776
1777func (c *Config) maxVersion(isDTLS bool) uint16 {
1778	ret := uint16(maxVersion)
1779	if c != nil && c.MaxVersion != 0 {
1780		ret = c.MaxVersion
1781	}
1782	if isDTLS {
1783		// We only implement up to DTLS 1.2.
1784		if ret > VersionTLS12 {
1785			return VersionTLS12
1786		}
1787		// There is no such thing as DTLS 1.1.
1788		if ret == VersionTLS11 {
1789			return VersionTLS10
1790		}
1791	}
1792	return ret
1793}
1794
1795var defaultCurvePreferences = []CurveID{CurveCECPQ2, CurveX25519, CurveP256, CurveP384, CurveP521}
1796
1797func (c *Config) curvePreferences() []CurveID {
1798	if c == nil || len(c.CurvePreferences) == 0 {
1799		return defaultCurvePreferences
1800	}
1801	return c.CurvePreferences
1802}
1803
1804func (c *Config) defaultCurves() map[CurveID]bool {
1805	defaultCurves := make(map[CurveID]bool)
1806	curves := c.DefaultCurves
1807	if c == nil || c.DefaultCurves == nil {
1808		curves = c.curvePreferences()
1809	}
1810	for _, curveID := range curves {
1811		defaultCurves[curveID] = true
1812	}
1813	return defaultCurves
1814}
1815
1816func wireToVersion(vers uint16, isDTLS bool) (uint16, bool) {
1817	if isDTLS {
1818		switch vers {
1819		case VersionDTLS12:
1820			return VersionTLS12, true
1821		case VersionDTLS10:
1822			return VersionTLS10, true
1823		}
1824	} else {
1825		switch vers {
1826		case VersionSSL30, VersionTLS10, VersionTLS11, VersionTLS12, VersionTLS13:
1827			return vers, true
1828		}
1829	}
1830
1831	return 0, false
1832}
1833
1834// isSupportedVersion checks if the specified wire version is acceptable. If so,
1835// it returns true and the corresponding protocol version. Otherwise, it returns
1836// false.
1837func (c *Config) isSupportedVersion(wireVers uint16, isDTLS bool) (uint16, bool) {
1838	vers, ok := wireToVersion(wireVers, isDTLS)
1839	if !ok || c.minVersion(isDTLS) > vers || vers > c.maxVersion(isDTLS) {
1840		return 0, false
1841	}
1842	return vers, true
1843}
1844
1845func (c *Config) supportedVersions(isDTLS bool) []uint16 {
1846	versions := allTLSWireVersions
1847	if isDTLS {
1848		versions = allDTLSWireVersions
1849	}
1850	var ret []uint16
1851	for _, vers := range versions {
1852		if _, ok := c.isSupportedVersion(vers, isDTLS); ok {
1853			ret = append(ret, vers)
1854		}
1855	}
1856	return ret
1857}
1858
1859// getCertificateForName returns the best certificate for the given name,
1860// defaulting to the first element of c.Certificates if there are no good
1861// options.
1862func (c *Config) getCertificateForName(name string) *Certificate {
1863	if len(c.Certificates) == 1 || c.NameToCertificate == nil {
1864		// There's only one choice, so no point doing any work.
1865		return &c.Certificates[0]
1866	}
1867
1868	name = strings.ToLower(name)
1869	for len(name) > 0 && name[len(name)-1] == '.' {
1870		name = name[:len(name)-1]
1871	}
1872
1873	if cert, ok := c.NameToCertificate[name]; ok {
1874		return cert
1875	}
1876
1877	// try replacing labels in the name with wildcards until we get a
1878	// match.
1879	labels := strings.Split(name, ".")
1880	for i := range labels {
1881		labels[i] = "*"
1882		candidate := strings.Join(labels, ".")
1883		if cert, ok := c.NameToCertificate[candidate]; ok {
1884			return cert
1885		}
1886	}
1887
1888	// If nothing matches, return the first certificate.
1889	return &c.Certificates[0]
1890}
1891
1892func (c *Config) signSignatureAlgorithms() []signatureAlgorithm {
1893	if c != nil && c.SignSignatureAlgorithms != nil {
1894		return c.SignSignatureAlgorithms
1895	}
1896	return supportedSignatureAlgorithms
1897}
1898
1899func (c *Config) verifySignatureAlgorithms() []signatureAlgorithm {
1900	if c != nil && c.VerifySignatureAlgorithms != nil {
1901		return c.VerifySignatureAlgorithms
1902	}
1903	return supportedSignatureAlgorithms
1904}
1905
1906// BuildNameToCertificate parses c.Certificates and builds c.NameToCertificate
1907// from the CommonName and SubjectAlternateName fields of each of the leaf
1908// certificates.
1909func (c *Config) BuildNameToCertificate() {
1910	c.NameToCertificate = make(map[string]*Certificate)
1911	for i := range c.Certificates {
1912		cert := &c.Certificates[i]
1913		x509Cert, err := x509.ParseCertificate(cert.Certificate[0])
1914		if err != nil {
1915			continue
1916		}
1917		if len(x509Cert.Subject.CommonName) > 0 {
1918			c.NameToCertificate[x509Cert.Subject.CommonName] = cert
1919		}
1920		for _, san := range x509Cert.DNSNames {
1921			c.NameToCertificate[san] = cert
1922		}
1923	}
1924}
1925
1926// A Certificate is a chain of one or more certificates, leaf first.
1927type Certificate struct {
1928	Certificate [][]byte
1929	PrivateKey  crypto.PrivateKey // supported types: *rsa.PrivateKey, *ecdsa.PrivateKey
1930	// OCSPStaple contains an optional OCSP response which will be served
1931	// to clients that request it.
1932	OCSPStaple []byte
1933	// SignedCertificateTimestampList contains an optional encoded
1934	// SignedCertificateTimestampList structure which will be
1935	// served to clients that request it.
1936	SignedCertificateTimestampList []byte
1937	// Leaf is the parsed form of the leaf certificate, which may be
1938	// initialized using x509.ParseCertificate to reduce per-handshake
1939	// processing for TLS clients doing client authentication. If nil, the
1940	// leaf certificate will be parsed as needed.
1941	Leaf *x509.Certificate
1942}
1943
1944// A TLS record.
1945type record struct {
1946	contentType  recordType
1947	major, minor uint8
1948	payload      []byte
1949}
1950
1951type handshakeMessage interface {
1952	marshal() []byte
1953	unmarshal([]byte) bool
1954}
1955
1956// lruSessionCache is a client or server session cache implementation
1957// that uses an LRU caching strategy.
1958type lruSessionCache struct {
1959	sync.Mutex
1960
1961	m        map[string]*list.Element
1962	q        *list.List
1963	capacity int
1964}
1965
1966type lruSessionCacheEntry struct {
1967	sessionKey string
1968	state      interface{}
1969}
1970
1971// Put adds the provided (sessionKey, cs) pair to the cache.
1972func (c *lruSessionCache) Put(sessionKey string, cs interface{}) {
1973	c.Lock()
1974	defer c.Unlock()
1975
1976	if elem, ok := c.m[sessionKey]; ok {
1977		entry := elem.Value.(*lruSessionCacheEntry)
1978		entry.state = cs
1979		c.q.MoveToFront(elem)
1980		return
1981	}
1982
1983	if c.q.Len() < c.capacity {
1984		entry := &lruSessionCacheEntry{sessionKey, cs}
1985		c.m[sessionKey] = c.q.PushFront(entry)
1986		return
1987	}
1988
1989	elem := c.q.Back()
1990	entry := elem.Value.(*lruSessionCacheEntry)
1991	delete(c.m, entry.sessionKey)
1992	entry.sessionKey = sessionKey
1993	entry.state = cs
1994	c.q.MoveToFront(elem)
1995	c.m[sessionKey] = elem
1996}
1997
1998// Get returns the value associated with a given key. It returns (nil,
1999// false) if no value is found.
2000func (c *lruSessionCache) Get(sessionKey string) (interface{}, bool) {
2001	c.Lock()
2002	defer c.Unlock()
2003
2004	if elem, ok := c.m[sessionKey]; ok {
2005		c.q.MoveToFront(elem)
2006		return elem.Value.(*lruSessionCacheEntry).state, true
2007	}
2008	return nil, false
2009}
2010
2011// lruClientSessionCache is a ClientSessionCache implementation that
2012// uses an LRU caching strategy.
2013type lruClientSessionCache struct {
2014	lruSessionCache
2015}
2016
2017func (c *lruClientSessionCache) Put(sessionKey string, cs *ClientSessionState) {
2018	c.lruSessionCache.Put(sessionKey, cs)
2019}
2020
2021func (c *lruClientSessionCache) Get(sessionKey string) (*ClientSessionState, bool) {
2022	cs, ok := c.lruSessionCache.Get(sessionKey)
2023	if !ok {
2024		return nil, false
2025	}
2026	return cs.(*ClientSessionState), true
2027}
2028
2029// lruServerSessionCache is a ServerSessionCache implementation that
2030// uses an LRU caching strategy.
2031type lruServerSessionCache struct {
2032	lruSessionCache
2033}
2034
2035func (c *lruServerSessionCache) Put(sessionId string, session *sessionState) {
2036	c.lruSessionCache.Put(sessionId, session)
2037}
2038
2039func (c *lruServerSessionCache) Get(sessionId string) (*sessionState, bool) {
2040	cs, ok := c.lruSessionCache.Get(sessionId)
2041	if !ok {
2042		return nil, false
2043	}
2044	return cs.(*sessionState), true
2045}
2046
2047// NewLRUClientSessionCache returns a ClientSessionCache with the given
2048// capacity that uses an LRU strategy. If capacity is < 1, a default capacity
2049// is used instead.
2050func NewLRUClientSessionCache(capacity int) ClientSessionCache {
2051	const defaultSessionCacheCapacity = 64
2052
2053	if capacity < 1 {
2054		capacity = defaultSessionCacheCapacity
2055	}
2056	return &lruClientSessionCache{
2057		lruSessionCache{
2058			m:        make(map[string]*list.Element),
2059			q:        list.New(),
2060			capacity: capacity,
2061		},
2062	}
2063}
2064
2065// NewLRUServerSessionCache returns a ServerSessionCache with the given
2066// capacity that uses an LRU strategy. If capacity is < 1, a default capacity
2067// is used instead.
2068func NewLRUServerSessionCache(capacity int) ServerSessionCache {
2069	const defaultSessionCacheCapacity = 64
2070
2071	if capacity < 1 {
2072		capacity = defaultSessionCacheCapacity
2073	}
2074	return &lruServerSessionCache{
2075		lruSessionCache{
2076			m:        make(map[string]*list.Element),
2077			q:        list.New(),
2078			capacity: capacity,
2079		},
2080	}
2081}
2082
2083// TODO(jsing): Make these available to both crypto/x509 and crypto/tls.
2084type dsaSignature struct {
2085	R, S *big.Int
2086}
2087
2088type ecdsaSignature dsaSignature
2089
2090var emptyConfig Config
2091
2092func defaultConfig() *Config {
2093	return &emptyConfig
2094}
2095
2096var (
2097	once                   sync.Once
2098	varDefaultCipherSuites []uint16
2099)
2100
2101func defaultCipherSuites() []uint16 {
2102	once.Do(initDefaultCipherSuites)
2103	return varDefaultCipherSuites
2104}
2105
2106func initDefaultCipherSuites() {
2107	for _, suite := range cipherSuites {
2108		if suite.flags&suitePSK == 0 {
2109			varDefaultCipherSuites = append(varDefaultCipherSuites, suite.id)
2110		}
2111	}
2112}
2113
2114func unexpectedMessageError(wanted, got interface{}) error {
2115	return fmt.Errorf("tls: received unexpected handshake message of type %T when waiting for %T", got, wanted)
2116}
2117
2118func isSupportedSignatureAlgorithm(sigAlg signatureAlgorithm, sigAlgs []signatureAlgorithm) bool {
2119	for _, s := range sigAlgs {
2120		if s == sigAlg {
2121			return true
2122		}
2123	}
2124	return false
2125}
2126
2127var (
2128	// See RFC 8446, section 4.1.3.
2129	downgradeTLS13 = []byte{0x44, 0x4f, 0x57, 0x4e, 0x47, 0x52, 0x44, 0x01}
2130	downgradeTLS12 = []byte{0x44, 0x4f, 0x57, 0x4e, 0x47, 0x52, 0x44, 0x00}
2131
2132	// This is a non-standard randomly-generated value.
2133	downgradeJDK11 = []byte{0xed, 0xbf, 0xb4, 0xa8, 0xc2, 0x47, 0x10, 0xff}
2134)
2135
2136func containsGREASE(values []uint16) bool {
2137	for _, v := range values {
2138		if isGREASEValue(v) {
2139			return true
2140		}
2141	}
2142	return false
2143}
2144