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