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