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