• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1// Copyright (c) 2016, Google Inc.
2//
3// Permission to use, copy, modify, and/or distribute this software for any
4// purpose with or without fee is hereby granted, provided that the above
5// copyright notice and this permission notice appear in all copies.
6//
7// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
8// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
9// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
10// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
11// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
12// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
13// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
14
15package runner
16
17import (
18	"bytes"
19	"crypto/ecdsa"
20	"crypto/elliptic"
21	"crypto/rand"
22	"crypto/x509"
23	"crypto/x509/pkix"
24	"encoding/base64"
25	"encoding/hex"
26	"encoding/json"
27	"encoding/pem"
28	"errors"
29	"flag"
30	"fmt"
31	"io"
32	"io/ioutil"
33	"math/big"
34	"net"
35	"os"
36	"os/exec"
37	"path"
38	"path/filepath"
39	"runtime"
40	"strconv"
41	"strings"
42	"sync"
43	"syscall"
44	"time"
45)
46
47var (
48	useValgrind        = flag.Bool("valgrind", false, "If true, run code under valgrind")
49	useGDB             = flag.Bool("gdb", false, "If true, run BoringSSL code under gdb")
50	useLLDB            = flag.Bool("lldb", false, "If true, run BoringSSL code under lldb")
51	flagDebug          = flag.Bool("debug", false, "Hexdump the contents of the connection")
52	mallocTest         = flag.Int64("malloc-test", -1, "If non-negative, run each test with each malloc in turn failing from the given number onwards.")
53	mallocTestDebug    = flag.Bool("malloc-test-debug", false, "If true, ask bssl_shim to abort rather than fail a malloc. This can be used with a specific value for --malloc-test to identity the malloc failing that is causing problems.")
54	jsonOutput         = flag.String("json-output", "", "The file to output JSON results to.")
55	pipe               = flag.Bool("pipe", false, "If true, print status output suitable for piping into another program.")
56	testToRun          = flag.String("test", "", "The pattern to filter tests to run, or empty to run all tests")
57	numWorkers         = flag.Int("num-workers", runtime.NumCPU(), "The number of workers to run in parallel.")
58	shimPath           = flag.String("shim-path", "../../../build/ssl/test/bssl_shim", "The location of the shim binary.")
59	resourceDir        = flag.String("resource-dir", ".", "The directory in which to find certificate and key files.")
60	fuzzer             = flag.Bool("fuzzer", false, "If true, tests against a BoringSSL built in fuzzer mode.")
61	transcriptDir      = flag.String("transcript-dir", "", "The directory in which to write transcripts.")
62	idleTimeout        = flag.Duration("idle-timeout", 15*time.Second, "The number of seconds to wait for a read or write to bssl_shim.")
63	deterministic      = flag.Bool("deterministic", false, "If true, uses a deterministic PRNG in the runner.")
64	allowUnimplemented = flag.Bool("allow-unimplemented", false, "If true, report pass even if some tests are unimplemented.")
65	looseErrors        = flag.Bool("loose-errors", false, "If true, allow shims to report an untranslated error code.")
66	shimConfigFile     = flag.String("shim-config", "", "A config file to use to configure the tests for this shim.")
67	includeDisabled    = flag.Bool("include-disabled", false, "If true, also runs disabled tests.")
68	repeatUntilFailure = flag.Bool("repeat-until-failure", false, "If true, the first selected test will be run repeatedly until failure.")
69)
70
71// ShimConfigurations is used with the “json” package and represents a shim
72// config file.
73type ShimConfiguration struct {
74	// DisabledTests maps from a glob-based pattern to a freeform string.
75	// The glob pattern is used to exclude tests from being run and the
76	// freeform string is unparsed but expected to explain why the test is
77	// disabled.
78	DisabledTests map[string]string
79
80	// ErrorMap maps from expected error strings to the correct error
81	// string for the shim in question. For example, it might map
82	// “:NO_SHARED_CIPHER:” (a BoringSSL error string) to something
83	// like “SSL_ERROR_NO_CYPHER_OVERLAP”.
84	ErrorMap map[string]string
85
86	// HalfRTTTickets is the number of half-RTT tickets the client should
87	// expect before half-RTT data when testing 0-RTT.
88	HalfRTTTickets int
89}
90
91// Setup shimConfig defaults aligning with BoringSSL.
92var shimConfig ShimConfiguration = ShimConfiguration{
93	HalfRTTTickets: 2,
94}
95
96type testCert int
97
98const (
99	testCertRSA testCert = iota
100	testCertRSA1024
101	testCertRSAChain
102	testCertECDSAP224
103	testCertECDSAP256
104	testCertECDSAP384
105	testCertECDSAP521
106	testCertEd25519
107)
108
109const (
110	rsaCertificateFile       = "cert.pem"
111	rsa1024CertificateFile   = "rsa_1024_cert.pem"
112	rsaChainCertificateFile  = "rsa_chain_cert.pem"
113	ecdsaP224CertificateFile = "ecdsa_p224_cert.pem"
114	ecdsaP256CertificateFile = "ecdsa_p256_cert.pem"
115	ecdsaP384CertificateFile = "ecdsa_p384_cert.pem"
116	ecdsaP521CertificateFile = "ecdsa_p521_cert.pem"
117	ed25519CertificateFile   = "ed25519_cert.pem"
118)
119
120const (
121	rsaKeyFile       = "key.pem"
122	rsa1024KeyFile   = "rsa_1024_key.pem"
123	rsaChainKeyFile  = "rsa_chain_key.pem"
124	ecdsaP224KeyFile = "ecdsa_p224_key.pem"
125	ecdsaP256KeyFile = "ecdsa_p256_key.pem"
126	ecdsaP384KeyFile = "ecdsa_p384_key.pem"
127	ecdsaP521KeyFile = "ecdsa_p521_key.pem"
128	ed25519KeyFile   = "ed25519_key.pem"
129	channelIDKeyFile = "channel_id_key.pem"
130)
131
132var (
133	rsaCertificate       Certificate
134	rsa1024Certificate   Certificate
135	rsaChainCertificate  Certificate
136	ecdsaP224Certificate Certificate
137	ecdsaP256Certificate Certificate
138	ecdsaP384Certificate Certificate
139	ecdsaP521Certificate Certificate
140	ed25519Certificate   Certificate
141)
142
143var testCerts = []struct {
144	id                testCert
145	certFile, keyFile string
146	cert              *Certificate
147}{
148	{
149		id:       testCertRSA,
150		certFile: rsaCertificateFile,
151		keyFile:  rsaKeyFile,
152		cert:     &rsaCertificate,
153	},
154	{
155		id:       testCertRSA1024,
156		certFile: rsa1024CertificateFile,
157		keyFile:  rsa1024KeyFile,
158		cert:     &rsa1024Certificate,
159	},
160	{
161		id:       testCertRSAChain,
162		certFile: rsaChainCertificateFile,
163		keyFile:  rsaChainKeyFile,
164		cert:     &rsaChainCertificate,
165	},
166	{
167		id:       testCertECDSAP224,
168		certFile: ecdsaP224CertificateFile,
169		keyFile:  ecdsaP224KeyFile,
170		cert:     &ecdsaP224Certificate,
171	},
172	{
173		id:       testCertECDSAP256,
174		certFile: ecdsaP256CertificateFile,
175		keyFile:  ecdsaP256KeyFile,
176		cert:     &ecdsaP256Certificate,
177	},
178	{
179		id:       testCertECDSAP384,
180		certFile: ecdsaP384CertificateFile,
181		keyFile:  ecdsaP384KeyFile,
182		cert:     &ecdsaP384Certificate,
183	},
184	{
185		id:       testCertECDSAP521,
186		certFile: ecdsaP521CertificateFile,
187		keyFile:  ecdsaP521KeyFile,
188		cert:     &ecdsaP521Certificate,
189	},
190	{
191		id:       testCertEd25519,
192		certFile: ed25519CertificateFile,
193		keyFile:  ed25519KeyFile,
194		cert:     &ed25519Certificate,
195	},
196}
197
198var channelIDKey *ecdsa.PrivateKey
199var channelIDBytes []byte
200
201var testOCSPResponse = []byte{1, 2, 3, 4}
202var testOCSPResponse2 = []byte{5, 6, 7, 8}
203var testSCTList = []byte{0, 6, 0, 4, 5, 6, 7, 8}
204var testSCTList2 = []byte{0, 6, 0, 4, 1, 2, 3, 4}
205
206var testOCSPExtension = append([]byte{byte(extensionStatusRequest) >> 8, byte(extensionStatusRequest), 0, 8, statusTypeOCSP, 0, 0, 4}, testOCSPResponse...)
207var testSCTExtension = append([]byte{byte(extensionSignedCertificateTimestamp) >> 8, byte(extensionSignedCertificateTimestamp), 0, byte(len(testSCTList))}, testSCTList...)
208
209func initCertificates() {
210	for i := range testCerts {
211		cert, err := LoadX509KeyPair(path.Join(*resourceDir, testCerts[i].certFile), path.Join(*resourceDir, testCerts[i].keyFile))
212		if err != nil {
213			panic(err)
214		}
215		cert.OCSPStaple = testOCSPResponse
216		cert.SignedCertificateTimestampList = testSCTList
217		*testCerts[i].cert = cert
218	}
219
220	channelIDPEMBlock, err := ioutil.ReadFile(path.Join(*resourceDir, channelIDKeyFile))
221	if err != nil {
222		panic(err)
223	}
224	channelIDDERBlock, _ := pem.Decode(channelIDPEMBlock)
225	if channelIDDERBlock.Type != "EC PRIVATE KEY" {
226		panic("bad key type")
227	}
228	channelIDKey, err = x509.ParseECPrivateKey(channelIDDERBlock.Bytes)
229	if err != nil {
230		panic(err)
231	}
232	if channelIDKey.Curve != elliptic.P256() {
233		panic("bad curve")
234	}
235
236	channelIDBytes = make([]byte, 64)
237	writeIntPadded(channelIDBytes[:32], channelIDKey.X)
238	writeIntPadded(channelIDBytes[32:], channelIDKey.Y)
239}
240
241func getRunnerCertificate(t testCert) Certificate {
242	for _, cert := range testCerts {
243		if cert.id == t {
244			return *cert.cert
245		}
246	}
247	panic("Unknown test certificate")
248}
249
250func getShimCertificate(t testCert) string {
251	for _, cert := range testCerts {
252		if cert.id == t {
253			return cert.certFile
254		}
255	}
256	panic("Unknown test certificate")
257}
258
259func getShimKey(t testCert) string {
260	for _, cert := range testCerts {
261		if cert.id == t {
262			return cert.keyFile
263		}
264	}
265	panic("Unknown test certificate")
266}
267
268// recordVersionToWire maps a record-layer protocol version to its wire
269// representation.
270func recordVersionToWire(vers uint16, protocol protocol) uint16 {
271	if protocol == dtls {
272		switch vers {
273		case VersionTLS12:
274			return VersionDTLS12
275		case VersionTLS10:
276			return VersionDTLS10
277		}
278	} else {
279		switch vers {
280		case VersionSSL30, VersionTLS10, VersionTLS11, VersionTLS12:
281			return vers
282		}
283	}
284
285	panic("unknown version")
286}
287
288// encodeDERValues encodes a series of bytestrings in comma-separated-hex form.
289func encodeDERValues(values [][]byte) string {
290	var ret string
291	for i, v := range values {
292		if i > 0 {
293			ret += ","
294		}
295		ret += hex.EncodeToString(v)
296	}
297
298	return ret
299}
300
301type testType int
302
303const (
304	clientTest testType = iota
305	serverTest
306)
307
308type protocol int
309
310const (
311	tls protocol = iota
312	dtls
313)
314
315const (
316	alpn = 1
317	npn  = 2
318)
319
320type testCase struct {
321	testType      testType
322	protocol      protocol
323	name          string
324	config        Config
325	shouldFail    bool
326	expectedError string
327	// expectedLocalError, if not empty, contains a substring that must be
328	// found in the local error.
329	expectedLocalError string
330	// expectedVersion, if non-zero, specifies the TLS version that must be
331	// negotiated.
332	expectedVersion uint16
333	// expectedResumeVersion, if non-zero, specifies the TLS version that
334	// must be negotiated on resumption. If zero, expectedVersion is used.
335	expectedResumeVersion uint16
336	// expectedCipher, if non-zero, specifies the TLS cipher suite that
337	// should be negotiated.
338	expectedCipher uint16
339	// expectChannelID controls whether the connection should have
340	// negotiated a Channel ID with channelIDKey.
341	expectChannelID bool
342	// expectedNextProto controls whether the connection should
343	// negotiate a next protocol via NPN or ALPN.
344	expectedNextProto string
345	// expectNoNextProto, if true, means that no next protocol should be
346	// negotiated.
347	expectNoNextProto bool
348	// expectedNextProtoType, if non-zero, is the expected next
349	// protocol negotiation mechanism.
350	expectedNextProtoType int
351	// expectedSRTPProtectionProfile is the DTLS-SRTP profile that
352	// should be negotiated. If zero, none should be negotiated.
353	expectedSRTPProtectionProfile uint16
354	// expectedOCSPResponse, if not nil, is the expected OCSP response to be received.
355	expectedOCSPResponse []uint8
356	// expectedSCTList, if not nil, is the expected SCT list to be received.
357	expectedSCTList []uint8
358	// expectedPeerSignatureAlgorithm, if not zero, is the signature
359	// algorithm that the peer should have used in the handshake.
360	expectedPeerSignatureAlgorithm signatureAlgorithm
361	// expectedCurveID, if not zero, is the curve that the handshake should
362	// have used.
363	expectedCurveID CurveID
364	// messageLen is the length, in bytes, of the test message that will be
365	// sent.
366	messageLen int
367	// messageCount is the number of test messages that will be sent.
368	messageCount int
369	// certFile is the path to the certificate to use for the server.
370	certFile string
371	// keyFile is the path to the private key to use for the server.
372	keyFile string
373	// resumeSession controls whether a second connection should be tested
374	// which attempts to resume the first session.
375	resumeSession bool
376	// resumeRenewedSession controls whether a third connection should be
377	// tested which attempts to resume the second connection's session.
378	resumeRenewedSession bool
379	// expectResumeRejected, if true, specifies that the attempted
380	// resumption must be rejected by the client. This is only valid for a
381	// serverTest.
382	expectResumeRejected bool
383	// resumeConfig, if not nil, points to a Config to be used on
384	// resumption. Unless newSessionsOnResume is set,
385	// SessionTicketKey, ServerSessionCache, and
386	// ClientSessionCache are copied from the initial connection's
387	// config. If nil, the initial connection's config is used.
388	resumeConfig *Config
389	// newSessionsOnResume, if true, will cause resumeConfig to
390	// use a different session resumption context.
391	newSessionsOnResume bool
392	// noSessionCache, if true, will cause the server to run without a
393	// session cache.
394	noSessionCache bool
395	// sendPrefix sends a prefix on the socket before actually performing a
396	// handshake.
397	sendPrefix string
398	// shimWritesFirst controls whether the shim sends an initial "hello"
399	// message before doing a roundtrip with the runner.
400	shimWritesFirst bool
401	// readWithUnfinishedWrite behaves like shimWritesFirst, but the shim
402	// does not complete the write until responding to the first runner
403	// message.
404	readWithUnfinishedWrite bool
405	// shimShutsDown, if true, runs a test where the shim shuts down the
406	// connection immediately after the handshake rather than echoing
407	// messages from the runner.
408	shimShutsDown bool
409	// renegotiate indicates the number of times the connection should be
410	// renegotiated during the exchange.
411	renegotiate int
412	// sendHalfHelloRequest, if true, causes the server to send half a
413	// HelloRequest when the handshake completes.
414	sendHalfHelloRequest bool
415	// renegotiateCiphers is a list of ciphersuite ids that will be
416	// switched in just before renegotiation.
417	renegotiateCiphers []uint16
418	// replayWrites, if true, configures the underlying transport
419	// to replay every write it makes in DTLS tests.
420	replayWrites bool
421	// damageFirstWrite, if true, configures the underlying transport to
422	// damage the final byte of the first application data write.
423	damageFirstWrite bool
424	// exportKeyingMaterial, if non-zero, configures the test to exchange
425	// keying material and verify they match.
426	exportKeyingMaterial int
427	exportLabel          string
428	exportContext        string
429	useExportContext     bool
430	// flags, if not empty, contains a list of command-line flags that will
431	// be passed to the shim program.
432	flags []string
433	// testTLSUnique, if true, causes the shim to send the tls-unique value
434	// which will be compared against the expected value.
435	testTLSUnique bool
436	// sendEmptyRecords is the number of consecutive empty records to send
437	// before each test message.
438	sendEmptyRecords int
439	// sendWarningAlerts is the number of consecutive warning alerts to send
440	// before each test message.
441	sendWarningAlerts int
442	// sendBogusAlertType, if true, causes a bogus alert of invalid type to
443	// be sent before each test message.
444	sendBogusAlertType bool
445	// sendKeyUpdates is the number of consecutive key updates to send
446	// before and after the test message.
447	sendKeyUpdates int
448	// keyUpdateRequest is the KeyUpdateRequest value to send in KeyUpdate messages.
449	keyUpdateRequest byte
450	// expectMessageDropped, if true, means the test message is expected to
451	// be dropped by the client rather than echoed back.
452	expectMessageDropped bool
453	// expectPeerCertificate, if not nil, is the certificate chain the peer
454	// is expected to send.
455	expectPeerCertificate *Certificate
456	// shimPrefix is the prefix that the shim will send to the server.
457	shimPrefix string
458	// resumeShimPrefix is the prefix that the shim will send to the server on a
459	// resumption.
460	resumeShimPrefix string
461	// tls13Variant, if non-zero, causes both runner and shim to be
462	// configured with the specified TLS 1.3 variant. This is a convenience
463	// option for configuring both concurrently.
464	tls13Variant int
465}
466
467var testCases []testCase
468
469func writeTranscript(test *testCase, path string, data []byte) {
470	if len(data) == 0 {
471		return
472	}
473
474	settings, err := ioutil.ReadFile(path)
475	if err != nil {
476		fmt.Fprintf(os.Stderr, "Error reading %s: %s.\n", path, err)
477		return
478	}
479
480	settings = append(settings, data...)
481	if err := ioutil.WriteFile(path, settings, 0644); err != nil {
482		fmt.Fprintf(os.Stderr, "Error writing %s: %s\n", path, err)
483	}
484}
485
486// A timeoutConn implements an idle timeout on each Read and Write operation.
487type timeoutConn struct {
488	net.Conn
489	timeout time.Duration
490}
491
492func (t *timeoutConn) Read(b []byte) (int, error) {
493	if err := t.SetReadDeadline(time.Now().Add(t.timeout)); err != nil {
494		return 0, err
495	}
496	return t.Conn.Read(b)
497}
498
499func (t *timeoutConn) Write(b []byte) (int, error) {
500	if err := t.SetWriteDeadline(time.Now().Add(t.timeout)); err != nil {
501		return 0, err
502	}
503	return t.Conn.Write(b)
504}
505
506func doExchange(test *testCase, config *Config, conn net.Conn, isResume bool, transcriptPrefix string, num int) error {
507	if !test.noSessionCache {
508		if config.ClientSessionCache == nil {
509			config.ClientSessionCache = NewLRUClientSessionCache(1)
510		}
511		if config.ServerSessionCache == nil {
512			config.ServerSessionCache = NewLRUServerSessionCache(1)
513		}
514	}
515	if test.testType == clientTest {
516		if len(config.Certificates) == 0 {
517			config.Certificates = []Certificate{rsaCertificate}
518		}
519	} else {
520		// Supply a ServerName to ensure a constant session cache key,
521		// rather than falling back to net.Conn.RemoteAddr.
522		if len(config.ServerName) == 0 {
523			config.ServerName = "test"
524		}
525	}
526	if *fuzzer {
527		config.Bugs.NullAllCiphers = true
528	}
529	if *deterministic {
530		config.Time = func() time.Time { return time.Unix(1234, 1234) }
531	}
532
533	conn = &timeoutConn{conn, *idleTimeout}
534
535	if test.protocol == dtls {
536		config.Bugs.PacketAdaptor = newPacketAdaptor(conn)
537		conn = config.Bugs.PacketAdaptor
538	}
539
540	if *flagDebug || len(*transcriptDir) != 0 {
541		local, peer := "client", "server"
542		if test.testType == clientTest {
543			local, peer = peer, local
544		}
545		connDebug := &recordingConn{
546			Conn:       conn,
547			isDatagram: test.protocol == dtls,
548			local:      local,
549			peer:       peer,
550		}
551		conn = connDebug
552		if *flagDebug {
553			defer connDebug.WriteTo(os.Stdout)
554		}
555		if len(transcriptPrefix) != 0 {
556			defer func() {
557				path := transcriptPrefix + strconv.Itoa(num)
558				writeTranscript(test, path, connDebug.Transcript())
559			}()
560		}
561
562		if config.Bugs.PacketAdaptor != nil {
563			config.Bugs.PacketAdaptor.debug = connDebug
564		}
565	}
566
567	if test.replayWrites {
568		conn = newReplayAdaptor(conn)
569	}
570
571	var connDamage *damageAdaptor
572	if test.damageFirstWrite {
573		connDamage = newDamageAdaptor(conn)
574		conn = connDamage
575	}
576
577	if test.sendPrefix != "" {
578		if _, err := conn.Write([]byte(test.sendPrefix)); err != nil {
579			return err
580		}
581	}
582
583	var tlsConn *Conn
584	if test.testType == clientTest {
585		if test.protocol == dtls {
586			tlsConn = DTLSServer(conn, config)
587		} else {
588			tlsConn = Server(conn, config)
589		}
590	} else {
591		config.InsecureSkipVerify = true
592		if test.protocol == dtls {
593			tlsConn = DTLSClient(conn, config)
594		} else {
595			tlsConn = Client(conn, config)
596		}
597	}
598	defer tlsConn.Close()
599
600	if err := tlsConn.Handshake(); err != nil {
601		return err
602	}
603
604	// TODO(davidben): move all per-connection expectations into a dedicated
605	// expectations struct that can be specified separately for the two
606	// legs.
607	expectedVersion := test.expectedVersion
608	if isResume && test.expectedResumeVersion != 0 {
609		expectedVersion = test.expectedResumeVersion
610	}
611	connState := tlsConn.ConnectionState()
612	if vers := connState.Version; expectedVersion != 0 && vers != expectedVersion {
613		return fmt.Errorf("got version %x, expected %x", vers, expectedVersion)
614	}
615
616	if cipher := connState.CipherSuite; test.expectedCipher != 0 && cipher != test.expectedCipher {
617		return fmt.Errorf("got cipher %x, expected %x", cipher, test.expectedCipher)
618	}
619	if didResume := connState.DidResume; isResume && didResume == test.expectResumeRejected {
620		return fmt.Errorf("didResume is %t, but we expected the opposite", didResume)
621	}
622
623	if test.expectChannelID {
624		channelID := connState.ChannelID
625		if channelID == nil {
626			return fmt.Errorf("no channel ID negotiated")
627		}
628		if channelID.Curve != channelIDKey.Curve ||
629			channelIDKey.X.Cmp(channelIDKey.X) != 0 ||
630			channelIDKey.Y.Cmp(channelIDKey.Y) != 0 {
631			return fmt.Errorf("incorrect channel ID")
632		}
633	} else if connState.ChannelID != nil {
634		return fmt.Errorf("channel ID unexpectedly negotiated")
635	}
636
637	if expected := test.expectedNextProto; expected != "" {
638		if actual := connState.NegotiatedProtocol; actual != expected {
639			return fmt.Errorf("next proto mismatch: got %s, wanted %s", actual, expected)
640		}
641	}
642
643	if test.expectNoNextProto {
644		if actual := connState.NegotiatedProtocol; actual != "" {
645			return fmt.Errorf("got unexpected next proto %s", actual)
646		}
647	}
648
649	if test.expectedNextProtoType != 0 {
650		if (test.expectedNextProtoType == alpn) != connState.NegotiatedProtocolFromALPN {
651			return fmt.Errorf("next proto type mismatch")
652		}
653	}
654
655	if p := connState.SRTPProtectionProfile; p != test.expectedSRTPProtectionProfile {
656		return fmt.Errorf("SRTP profile mismatch: got %d, wanted %d", p, test.expectedSRTPProtectionProfile)
657	}
658
659	if test.expectedOCSPResponse != nil && !bytes.Equal(test.expectedOCSPResponse, tlsConn.OCSPResponse()) {
660		return fmt.Errorf("OCSP Response mismatch: got %x, wanted %x", tlsConn.OCSPResponse(), test.expectedOCSPResponse)
661	}
662
663	if test.expectedSCTList != nil && !bytes.Equal(test.expectedSCTList, connState.SCTList) {
664		return fmt.Errorf("SCT list mismatch")
665	}
666
667	if expected := test.expectedPeerSignatureAlgorithm; expected != 0 && expected != connState.PeerSignatureAlgorithm {
668		return fmt.Errorf("expected peer to use signature algorithm %04x, but got %04x", expected, connState.PeerSignatureAlgorithm)
669	}
670
671	if expected := test.expectedCurveID; expected != 0 && expected != connState.CurveID {
672		return fmt.Errorf("expected peer to use curve %04x, but got %04x", expected, connState.CurveID)
673	}
674
675	if test.expectPeerCertificate != nil {
676		if len(connState.PeerCertificates) != len(test.expectPeerCertificate.Certificate) {
677			return fmt.Errorf("expected peer to send %d certificates, but got %d", len(connState.PeerCertificates), len(test.expectPeerCertificate.Certificate))
678		}
679		for i, cert := range connState.PeerCertificates {
680			if !bytes.Equal(cert.Raw, test.expectPeerCertificate.Certificate[i]) {
681				return fmt.Errorf("peer certificate %d did not match", i+1)
682			}
683		}
684	}
685
686	if test.exportKeyingMaterial > 0 {
687		actual := make([]byte, test.exportKeyingMaterial)
688		if _, err := io.ReadFull(tlsConn, actual); err != nil {
689			return err
690		}
691		expected, err := tlsConn.ExportKeyingMaterial(test.exportKeyingMaterial, []byte(test.exportLabel), []byte(test.exportContext), test.useExportContext)
692		if err != nil {
693			return err
694		}
695		if !bytes.Equal(actual, expected) {
696			return fmt.Errorf("keying material mismatch")
697		}
698	}
699
700	if test.testTLSUnique {
701		var peersValue [12]byte
702		if _, err := io.ReadFull(tlsConn, peersValue[:]); err != nil {
703			return err
704		}
705		expected := tlsConn.ConnectionState().TLSUnique
706		if !bytes.Equal(peersValue[:], expected) {
707			return fmt.Errorf("tls-unique mismatch: peer sent %x, but %x was expected", peersValue[:], expected)
708		}
709	}
710
711	if test.sendHalfHelloRequest {
712		tlsConn.SendHalfHelloRequest()
713	}
714
715	shimPrefix := test.shimPrefix
716	if isResume {
717		shimPrefix = test.resumeShimPrefix
718	}
719	if test.shimWritesFirst || test.readWithUnfinishedWrite {
720		shimPrefix = "hello"
721	}
722	if test.renegotiate > 0 {
723		// If readWithUnfinishedWrite is set, the shim prefix will be
724		// available later.
725		if shimPrefix != "" && !test.readWithUnfinishedWrite {
726			var buf = make([]byte, len(shimPrefix))
727			_, err := io.ReadFull(tlsConn, buf)
728			if err != nil {
729				return err
730			}
731			if string(buf) != shimPrefix {
732				return fmt.Errorf("bad initial message %v vs %v", string(buf), shimPrefix)
733			}
734			shimPrefix = ""
735		}
736
737		if test.renegotiateCiphers != nil {
738			config.CipherSuites = test.renegotiateCiphers
739		}
740		for i := 0; i < test.renegotiate; i++ {
741			if err := tlsConn.Renegotiate(); err != nil {
742				return err
743			}
744		}
745	} else if test.renegotiateCiphers != nil {
746		panic("renegotiateCiphers without renegotiate")
747	}
748
749	if test.damageFirstWrite {
750		connDamage.setDamage(true)
751		tlsConn.Write([]byte("DAMAGED WRITE"))
752		connDamage.setDamage(false)
753	}
754
755	messageLen := test.messageLen
756	if messageLen < 0 {
757		if test.protocol == dtls {
758			return fmt.Errorf("messageLen < 0 not supported for DTLS tests")
759		}
760		// Read until EOF.
761		_, err := io.Copy(ioutil.Discard, tlsConn)
762		return err
763	}
764	if messageLen == 0 {
765		messageLen = 32
766	}
767
768	messageCount := test.messageCount
769	if messageCount == 0 {
770		messageCount = 1
771	}
772
773	for j := 0; j < messageCount; j++ {
774		for i := 0; i < test.sendKeyUpdates; i++ {
775			tlsConn.SendKeyUpdate(test.keyUpdateRequest)
776		}
777
778		for i := 0; i < test.sendEmptyRecords; i++ {
779			tlsConn.Write(nil)
780		}
781
782		for i := 0; i < test.sendWarningAlerts; i++ {
783			tlsConn.SendAlert(alertLevelWarning, alertUnexpectedMessage)
784		}
785
786		if test.sendBogusAlertType {
787			tlsConn.SendAlert(0x42, alertUnexpectedMessage)
788		}
789
790		testMessage := make([]byte, messageLen)
791		for i := range testMessage {
792			testMessage[i] = 0x42 ^ byte(j)
793		}
794		tlsConn.Write(testMessage)
795
796		// Consume the shim prefix if needed.
797		if shimPrefix != "" {
798			var buf = make([]byte, len(shimPrefix))
799			_, err := io.ReadFull(tlsConn, buf)
800			if err != nil {
801				return err
802			}
803			if string(buf) != shimPrefix {
804				return fmt.Errorf("bad initial message %v vs %v", string(buf), shimPrefix)
805			}
806			shimPrefix = ""
807		}
808
809		if test.shimShutsDown || test.expectMessageDropped {
810			// The shim will not respond.
811			continue
812		}
813
814		// Process the KeyUpdate ACK. However many KeyUpdates the runner
815		// sends, the shim should respond only once.
816		if test.sendKeyUpdates > 0 && test.keyUpdateRequest == keyUpdateRequested {
817			if err := tlsConn.ReadKeyUpdateACK(); err != nil {
818				return err
819			}
820		}
821
822		buf := make([]byte, len(testMessage))
823		if test.protocol == dtls {
824			bufTmp := make([]byte, len(buf)+1)
825			n, err := tlsConn.Read(bufTmp)
826			if err != nil {
827				return err
828			}
829			if n != len(buf) {
830				return fmt.Errorf("bad reply; length mismatch (%d vs %d)", n, len(buf))
831			}
832			copy(buf, bufTmp)
833		} else {
834			_, err := io.ReadFull(tlsConn, buf)
835			if err != nil {
836				return err
837			}
838		}
839
840		for i, v := range buf {
841			if v != testMessage[i]^0xff {
842				return fmt.Errorf("bad reply contents at byte %d", i)
843			}
844		}
845	}
846
847	return nil
848}
849
850func valgrindOf(dbAttach bool, path string, args ...string) *exec.Cmd {
851	valgrindArgs := []string{"--error-exitcode=99", "--track-origins=yes", "--leak-check=full", "--quiet"}
852	if dbAttach {
853		valgrindArgs = append(valgrindArgs, "--db-attach=yes", "--db-command=xterm -e gdb -nw %f %p")
854	}
855	valgrindArgs = append(valgrindArgs, path)
856	valgrindArgs = append(valgrindArgs, args...)
857
858	return exec.Command("valgrind", valgrindArgs...)
859}
860
861func gdbOf(path string, args ...string) *exec.Cmd {
862	xtermArgs := []string{"-e", "gdb", "--args"}
863	xtermArgs = append(xtermArgs, path)
864	xtermArgs = append(xtermArgs, args...)
865
866	return exec.Command("xterm", xtermArgs...)
867}
868
869func lldbOf(path string, args ...string) *exec.Cmd {
870	xtermArgs := []string{"-e", "lldb", "--"}
871	xtermArgs = append(xtermArgs, path)
872	xtermArgs = append(xtermArgs, args...)
873
874	return exec.Command("xterm", xtermArgs...)
875}
876
877var (
878	errMoreMallocs   = errors.New("child process did not exhaust all allocation calls")
879	errUnimplemented = errors.New("child process does not implement needed flags")
880)
881
882// accept accepts a connection from listener, unless waitChan signals a process
883// exit first.
884func acceptOrWait(listener *net.TCPListener, waitChan chan error) (net.Conn, error) {
885	type connOrError struct {
886		conn               net.Conn
887		err                error
888		startTime, endTime time.Time
889	}
890	connChan := make(chan connOrError, 1)
891	go func() {
892		startTime := time.Now()
893		listener.SetDeadline(time.Now().Add(*idleTimeout))
894		conn, err := listener.Accept()
895		endTime := time.Now()
896		connChan <- connOrError{conn, err, startTime, endTime}
897		close(connChan)
898	}()
899	select {
900	case result := <-connChan:
901		if result.err != nil {
902			// TODO(davidben): Remove this logging when
903			// https://crbug.com/boringssl/199 is resolved.
904			fmt.Fprintf(os.Stderr, "acceptOrWait failed, startTime=%v, endTime=%v\n", result.startTime, result.endTime)
905		}
906		return result.conn, result.err
907	case childErr := <-waitChan:
908		waitChan <- childErr
909		return nil, fmt.Errorf("child exited early: %s", childErr)
910	}
911}
912
913func translateExpectedError(errorStr string) string {
914	if translated, ok := shimConfig.ErrorMap[errorStr]; ok {
915		return translated
916	}
917
918	if *looseErrors {
919		return ""
920	}
921
922	return errorStr
923}
924
925func runTest(test *testCase, shimPath string, mallocNumToFail int64) error {
926	// Help debugging panics on the Go side.
927	defer func() {
928		if r := recover(); r != nil {
929			fmt.Fprintf(os.Stderr, "Test '%s' panicked.\n", test.name)
930			panic(r)
931		}
932	}()
933
934	if !test.shouldFail && (len(test.expectedError) > 0 || len(test.expectedLocalError) > 0) {
935		panic("Error expected without shouldFail in " + test.name)
936	}
937
938	if test.expectResumeRejected && !test.resumeSession {
939		panic("expectResumeRejected without resumeSession in " + test.name)
940	}
941
942	for _, ver := range tlsVersions {
943		if !strings.Contains("-"+test.name+"-", "-"+ver.name+"-") {
944			continue
945		}
946
947		if test.config.MaxVersion == 0 && test.config.MinVersion == 0 && test.expectedVersion == 0 {
948			panic(fmt.Sprintf("The name of test %q suggests that it's version specific, but min/max version in the Config is %x/%x. One of them should probably be %x", test.name, test.config.MinVersion, test.config.MaxVersion, ver.version))
949		}
950
951		if ver.tls13Variant != 0 {
952			var foundFlag bool
953			for _, flag := range test.flags {
954				if flag == "-tls13-variant" {
955					foundFlag = true
956					break
957				}
958			}
959			if !foundFlag && test.config.TLS13Variant != ver.tls13Variant && test.tls13Variant != ver.tls13Variant {
960				panic(fmt.Sprintf("The name of test %q suggests that uses an experimental TLS 1.3 variant, but neither the shim nor the runner configures it", test.name))
961			}
962		}
963
964	}
965
966	listener, err := net.ListenTCP("tcp", &net.TCPAddr{IP: net.IPv6loopback})
967	if err != nil {
968		listener, err = net.ListenTCP("tcp4", &net.TCPAddr{IP: net.IP{127, 0, 0, 1}})
969	}
970	if err != nil {
971		panic(err)
972	}
973	defer func() {
974		if listener != nil {
975			listener.Close()
976		}
977	}()
978
979	flags := []string{"-port", strconv.Itoa(listener.Addr().(*net.TCPAddr).Port)}
980	if test.testType == serverTest {
981		flags = append(flags, "-server")
982
983		flags = append(flags, "-key-file")
984		if test.keyFile == "" {
985			flags = append(flags, path.Join(*resourceDir, rsaKeyFile))
986		} else {
987			flags = append(flags, path.Join(*resourceDir, test.keyFile))
988		}
989
990		flags = append(flags, "-cert-file")
991		if test.certFile == "" {
992			flags = append(flags, path.Join(*resourceDir, rsaCertificateFile))
993		} else {
994			flags = append(flags, path.Join(*resourceDir, test.certFile))
995		}
996	}
997
998	if test.protocol == dtls {
999		flags = append(flags, "-dtls")
1000	}
1001
1002	var resumeCount int
1003	if test.resumeSession {
1004		resumeCount++
1005		if test.resumeRenewedSession {
1006			resumeCount++
1007		}
1008	}
1009
1010	if resumeCount > 0 {
1011		flags = append(flags, "-resume-count", strconv.Itoa(resumeCount))
1012	}
1013
1014	if test.shimWritesFirst {
1015		flags = append(flags, "-shim-writes-first")
1016	}
1017
1018	if test.readWithUnfinishedWrite {
1019		flags = append(flags, "-read-with-unfinished-write")
1020	}
1021
1022	if test.shimShutsDown {
1023		flags = append(flags, "-shim-shuts-down")
1024	}
1025
1026	if test.exportKeyingMaterial > 0 {
1027		flags = append(flags, "-export-keying-material", strconv.Itoa(test.exportKeyingMaterial))
1028		flags = append(flags, "-export-label", test.exportLabel)
1029		flags = append(flags, "-export-context", test.exportContext)
1030		if test.useExportContext {
1031			flags = append(flags, "-use-export-context")
1032		}
1033	}
1034	if test.expectResumeRejected {
1035		flags = append(flags, "-expect-session-miss")
1036	}
1037
1038	if test.testTLSUnique {
1039		flags = append(flags, "-tls-unique")
1040	}
1041
1042	if test.tls13Variant != 0 {
1043		test.config.TLS13Variant = test.tls13Variant
1044		flags = append(flags, "-tls13-variant", strconv.Itoa(test.tls13Variant))
1045	}
1046
1047	var transcriptPrefix string
1048	if len(*transcriptDir) != 0 {
1049		protocol := "tls"
1050		if test.protocol == dtls {
1051			protocol = "dtls"
1052		}
1053
1054		side := "client"
1055		if test.testType == serverTest {
1056			side = "server"
1057		}
1058
1059		dir := filepath.Join(*transcriptDir, protocol, side)
1060		if err := os.MkdirAll(dir, 0755); err != nil {
1061			return err
1062		}
1063		transcriptPrefix = filepath.Join(dir, test.name+"-")
1064		flags = append(flags, "-write-settings", transcriptPrefix)
1065	}
1066
1067	flags = append(flags, test.flags...)
1068
1069	var shim *exec.Cmd
1070	if *useValgrind {
1071		shim = valgrindOf(false, shimPath, flags...)
1072	} else if *useGDB {
1073		shim = gdbOf(shimPath, flags...)
1074	} else if *useLLDB {
1075		shim = lldbOf(shimPath, flags...)
1076	} else {
1077		shim = exec.Command(shimPath, flags...)
1078	}
1079	shim.Stdin = os.Stdin
1080	var stdoutBuf, stderrBuf bytes.Buffer
1081	shim.Stdout = &stdoutBuf
1082	shim.Stderr = &stderrBuf
1083	if mallocNumToFail >= 0 {
1084		shim.Env = os.Environ()
1085		shim.Env = append(shim.Env, "MALLOC_NUMBER_TO_FAIL="+strconv.FormatInt(mallocNumToFail, 10))
1086		if *mallocTestDebug {
1087			shim.Env = append(shim.Env, "MALLOC_BREAK_ON_FAIL=1")
1088		}
1089		shim.Env = append(shim.Env, "_MALLOC_CHECK=1")
1090	}
1091
1092	if err := shim.Start(); err != nil {
1093		panic(err)
1094	}
1095	waitChan := make(chan error, 1)
1096	go func() { waitChan <- shim.Wait() }()
1097
1098	config := test.config
1099
1100	if *deterministic {
1101		config.Rand = &deterministicRand{}
1102	}
1103
1104	conn, err := acceptOrWait(listener, waitChan)
1105	if err == nil {
1106		err = doExchange(test, &config, conn, false /* not a resumption */, transcriptPrefix, 0)
1107		conn.Close()
1108	}
1109
1110	for i := 0; err == nil && i < resumeCount; i++ {
1111		var resumeConfig Config
1112		if test.resumeConfig != nil {
1113			resumeConfig = *test.resumeConfig
1114			if !test.newSessionsOnResume {
1115				resumeConfig.SessionTicketKey = config.SessionTicketKey
1116				resumeConfig.ClientSessionCache = config.ClientSessionCache
1117				resumeConfig.ServerSessionCache = config.ServerSessionCache
1118			}
1119			resumeConfig.Rand = config.Rand
1120		} else {
1121			resumeConfig = config
1122		}
1123		var connResume net.Conn
1124		connResume, err = acceptOrWait(listener, waitChan)
1125		if err == nil {
1126			err = doExchange(test, &resumeConfig, connResume, true /* resumption */, transcriptPrefix, i+1)
1127			connResume.Close()
1128		}
1129	}
1130
1131	// Close the listener now. This is to avoid hangs should the shim try to
1132	// open more connections than expected.
1133	listener.Close()
1134	listener = nil
1135
1136	var shimKilledLock sync.Mutex
1137	var shimKilled bool
1138	waitTimeout := time.AfterFunc(*idleTimeout, func() {
1139		shimKilledLock.Lock()
1140		shimKilled = true
1141		shimKilledLock.Unlock()
1142		shim.Process.Kill()
1143	})
1144	childErr := <-waitChan
1145	waitTimeout.Stop()
1146	shimKilledLock.Lock()
1147	if shimKilled && err == nil {
1148		err = errors.New("timeout waiting for the shim to exit.")
1149	}
1150	shimKilledLock.Unlock()
1151	var isValgrindError bool
1152	if exitError, ok := childErr.(*exec.ExitError); ok {
1153		switch exitError.Sys().(syscall.WaitStatus).ExitStatus() {
1154		case 88:
1155			return errMoreMallocs
1156		case 89:
1157			return errUnimplemented
1158		case 99:
1159			isValgrindError = true
1160		}
1161	}
1162
1163	// Account for Windows line endings.
1164	stdout := strings.Replace(string(stdoutBuf.Bytes()), "\r\n", "\n", -1)
1165	stderr := strings.Replace(string(stderrBuf.Bytes()), "\r\n", "\n", -1)
1166
1167	// Separate the errors from the shim and those from tools like
1168	// AddressSanitizer.
1169	var extraStderr string
1170	if stderrParts := strings.SplitN(stderr, "--- DONE ---\n", 2); len(stderrParts) == 2 {
1171		stderr = stderrParts[0]
1172		extraStderr = stderrParts[1]
1173	}
1174
1175	failed := err != nil || childErr != nil
1176	expectedError := translateExpectedError(test.expectedError)
1177	correctFailure := len(expectedError) == 0 || strings.Contains(stderr, expectedError)
1178
1179	localError := "none"
1180	if err != nil {
1181		localError = err.Error()
1182	}
1183	if len(test.expectedLocalError) != 0 {
1184		correctFailure = correctFailure && strings.Contains(localError, test.expectedLocalError)
1185	}
1186
1187	if failed != test.shouldFail || failed && !correctFailure {
1188		childError := "none"
1189		if childErr != nil {
1190			childError = childErr.Error()
1191		}
1192
1193		var msg string
1194		switch {
1195		case failed && !test.shouldFail:
1196			msg = "unexpected failure"
1197		case !failed && test.shouldFail:
1198			msg = "unexpected success"
1199		case failed && !correctFailure:
1200			msg = "bad error (wanted '" + expectedError + "' / '" + test.expectedLocalError + "')"
1201		default:
1202			panic("internal error")
1203		}
1204
1205		return fmt.Errorf("%s: local error '%s', child error '%s', stdout:\n%s\nstderr:\n%s\n%s", msg, localError, childError, stdout, stderr, extraStderr)
1206	}
1207
1208	if len(extraStderr) > 0 || (!failed && len(stderr) > 0) {
1209		return fmt.Errorf("unexpected error output:\n%s\n%s", stderr, extraStderr)
1210	}
1211
1212	if *useValgrind && isValgrindError {
1213		return fmt.Errorf("valgrind error:\n%s\n%s", stderr, extraStderr)
1214	}
1215
1216	return nil
1217}
1218
1219type tlsVersion struct {
1220	name string
1221	// version is the protocol version.
1222	version uint16
1223	// excludeFlag is the legacy shim flag to disable the version.
1224	excludeFlag string
1225	hasDTLS     bool
1226	// versionDTLS, if non-zero, is the DTLS-specific representation of the version.
1227	versionDTLS uint16
1228	// versionWire, if non-zero, is the wire representation of the
1229	// version. Otherwise the wire version is the protocol version or
1230	// versionDTLS.
1231	versionWire  uint16
1232	tls13Variant int
1233}
1234
1235func (vers tlsVersion) shimFlag(protocol protocol) string {
1236	// The shim uses the protocol version in its public API, but uses the
1237	// DTLS-specific version if it exists.
1238	if protocol == dtls && vers.versionDTLS != 0 {
1239		return strconv.Itoa(int(vers.versionDTLS))
1240	}
1241	return strconv.Itoa(int(vers.version))
1242}
1243
1244func (vers tlsVersion) wire(protocol protocol) uint16 {
1245	if protocol == dtls && vers.versionDTLS != 0 {
1246		return vers.versionDTLS
1247	}
1248	if vers.versionWire != 0 {
1249		return vers.versionWire
1250	}
1251	return vers.version
1252}
1253
1254var tlsVersions = []tlsVersion{
1255	{
1256		name:        "SSL3",
1257		version:     VersionSSL30,
1258		excludeFlag: "-no-ssl3",
1259	},
1260	{
1261		name:        "TLS1",
1262		version:     VersionTLS10,
1263		excludeFlag: "-no-tls1",
1264		hasDTLS:     true,
1265		versionDTLS: VersionDTLS10,
1266	},
1267	{
1268		name:        "TLS11",
1269		version:     VersionTLS11,
1270		excludeFlag: "-no-tls11",
1271	},
1272	{
1273		name:        "TLS12",
1274		version:     VersionTLS12,
1275		excludeFlag: "-no-tls12",
1276		hasDTLS:     true,
1277		versionDTLS: VersionDTLS12,
1278	},
1279	{
1280		name:         "TLS13",
1281		version:      VersionTLS13,
1282		excludeFlag:  "-no-tls13",
1283		versionWire:  tls13DraftVersion,
1284		tls13Variant: TLS13Default,
1285	},
1286	{
1287		name:         "TLS13Experiment",
1288		version:      VersionTLS13,
1289		excludeFlag:  "-no-tls13",
1290		versionWire:  tls13ExperimentVersion,
1291		tls13Variant: TLS13Experiment,
1292	},
1293	{
1294		name:         "TLS13RecordTypeExperiment",
1295		version:      VersionTLS13,
1296		excludeFlag:  "-no-tls13",
1297		versionWire:  tls13RecordTypeExperimentVersion,
1298		tls13Variant: TLS13RecordTypeExperiment,
1299	},
1300}
1301
1302func allVersions(protocol protocol) []tlsVersion {
1303	if protocol == tls {
1304		return tlsVersions
1305	}
1306
1307	var ret []tlsVersion
1308	for _, vers := range tlsVersions {
1309		if vers.hasDTLS {
1310			ret = append(ret, vers)
1311		}
1312	}
1313	return ret
1314}
1315
1316type testCipherSuite struct {
1317	name string
1318	id   uint16
1319}
1320
1321var testCipherSuites = []testCipherSuite{
1322	{"3DES-SHA", TLS_RSA_WITH_3DES_EDE_CBC_SHA},
1323	{"AES128-GCM", TLS_RSA_WITH_AES_128_GCM_SHA256},
1324	{"AES128-SHA", TLS_RSA_WITH_AES_128_CBC_SHA},
1325	{"AES128-SHA256", TLS_RSA_WITH_AES_128_CBC_SHA256},
1326	{"AES256-GCM", TLS_RSA_WITH_AES_256_GCM_SHA384},
1327	{"AES256-SHA", TLS_RSA_WITH_AES_256_CBC_SHA},
1328	{"AES256-SHA256", TLS_RSA_WITH_AES_256_CBC_SHA256},
1329	{"ECDHE-ECDSA-AES128-GCM", TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256},
1330	{"ECDHE-ECDSA-AES128-SHA", TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA},
1331	{"ECDHE-ECDSA-AES128-SHA256", TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256},
1332	{"ECDHE-ECDSA-AES256-GCM", TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384},
1333	{"ECDHE-ECDSA-AES256-SHA", TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA},
1334	{"ECDHE-ECDSA-AES256-SHA384", TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384},
1335	{"ECDHE-ECDSA-CHACHA20-POLY1305", TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256},
1336	{"ECDHE-RSA-AES128-GCM", TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256},
1337	{"ECDHE-RSA-AES128-SHA", TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA},
1338	{"ECDHE-RSA-AES128-SHA256", TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256},
1339	{"ECDHE-RSA-AES256-GCM", TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384},
1340	{"ECDHE-RSA-AES256-SHA", TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA},
1341	{"ECDHE-RSA-AES256-SHA384", TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384},
1342	{"ECDHE-RSA-CHACHA20-POLY1305", TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256},
1343	{"PSK-AES128-CBC-SHA", TLS_PSK_WITH_AES_128_CBC_SHA},
1344	{"PSK-AES256-CBC-SHA", TLS_PSK_WITH_AES_256_CBC_SHA},
1345	{"ECDHE-PSK-AES128-CBC-SHA", TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA},
1346	{"ECDHE-PSK-AES256-CBC-SHA", TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA},
1347	{"ECDHE-PSK-CHACHA20-POLY1305", TLS_ECDHE_PSK_WITH_CHACHA20_POLY1305_SHA256},
1348	{"AEAD-CHACHA20-POLY1305", TLS_CHACHA20_POLY1305_SHA256},
1349	{"AEAD-AES128-GCM-SHA256", TLS_AES_128_GCM_SHA256},
1350	{"AEAD-AES256-GCM-SHA384", TLS_AES_256_GCM_SHA384},
1351	{"NULL-SHA", TLS_RSA_WITH_NULL_SHA},
1352}
1353
1354func hasComponent(suiteName, component string) bool {
1355	return strings.Contains("-"+suiteName+"-", "-"+component+"-")
1356}
1357
1358func isTLS12Only(suiteName string) bool {
1359	return hasComponent(suiteName, "GCM") ||
1360		hasComponent(suiteName, "SHA256") ||
1361		hasComponent(suiteName, "SHA384") ||
1362		hasComponent(suiteName, "POLY1305")
1363}
1364
1365func isTLS13Suite(suiteName string) bool {
1366	return strings.HasPrefix(suiteName, "AEAD-")
1367}
1368
1369func isDTLSCipher(suiteName string) bool {
1370	return !hasComponent(suiteName, "RC4") && !hasComponent(suiteName, "NULL")
1371}
1372
1373func bigFromHex(hex string) *big.Int {
1374	ret, ok := new(big.Int).SetString(hex, 16)
1375	if !ok {
1376		panic("failed to parse hex number 0x" + hex)
1377	}
1378	return ret
1379}
1380
1381func addBasicTests() {
1382	basicTests := []testCase{
1383		{
1384			name: "NoFallbackSCSV",
1385			config: Config{
1386				Bugs: ProtocolBugs{
1387					FailIfNotFallbackSCSV: true,
1388				},
1389			},
1390			shouldFail:         true,
1391			expectedLocalError: "no fallback SCSV found",
1392		},
1393		{
1394			name: "SendFallbackSCSV",
1395			config: Config{
1396				Bugs: ProtocolBugs{
1397					FailIfNotFallbackSCSV: true,
1398				},
1399			},
1400			flags: []string{"-fallback-scsv"},
1401		},
1402		{
1403			name: "ClientCertificateTypes",
1404			config: Config{
1405				MaxVersion: VersionTLS12,
1406				ClientAuth: RequestClientCert,
1407				ClientCertificateTypes: []byte{
1408					CertTypeDSSSign,
1409					CertTypeRSASign,
1410					CertTypeECDSASign,
1411				},
1412			},
1413			flags: []string{
1414				"-expect-certificate-types",
1415				base64.StdEncoding.EncodeToString([]byte{
1416					CertTypeDSSSign,
1417					CertTypeRSASign,
1418					CertTypeECDSASign,
1419				}),
1420			},
1421		},
1422		{
1423			name: "UnauthenticatedECDH",
1424			config: Config{
1425				MaxVersion:   VersionTLS12,
1426				CipherSuites: []uint16{TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256},
1427				Bugs: ProtocolBugs{
1428					UnauthenticatedECDH: true,
1429				},
1430			},
1431			shouldFail:    true,
1432			expectedError: ":UNEXPECTED_MESSAGE:",
1433		},
1434		{
1435			name: "SkipCertificateStatus",
1436			config: Config{
1437				MaxVersion:   VersionTLS12,
1438				CipherSuites: []uint16{TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256},
1439				Bugs: ProtocolBugs{
1440					SkipCertificateStatus: true,
1441				},
1442			},
1443			flags: []string{
1444				"-enable-ocsp-stapling",
1445			},
1446		},
1447		{
1448			name: "SkipServerKeyExchange",
1449			config: Config{
1450				MaxVersion:   VersionTLS12,
1451				CipherSuites: []uint16{TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256},
1452				Bugs: ProtocolBugs{
1453					SkipServerKeyExchange: true,
1454				},
1455			},
1456			shouldFail:    true,
1457			expectedError: ":UNEXPECTED_MESSAGE:",
1458		},
1459		{
1460			testType: serverTest,
1461			name:     "Alert",
1462			config: Config{
1463				Bugs: ProtocolBugs{
1464					SendSpuriousAlert: alertRecordOverflow,
1465				},
1466			},
1467			shouldFail:    true,
1468			expectedError: ":TLSV1_ALERT_RECORD_OVERFLOW:",
1469		},
1470		{
1471			protocol: dtls,
1472			testType: serverTest,
1473			name:     "Alert-DTLS",
1474			config: Config{
1475				Bugs: ProtocolBugs{
1476					SendSpuriousAlert: alertRecordOverflow,
1477				},
1478			},
1479			shouldFail:    true,
1480			expectedError: ":TLSV1_ALERT_RECORD_OVERFLOW:",
1481		},
1482		{
1483			testType: serverTest,
1484			name:     "FragmentAlert",
1485			config: Config{
1486				Bugs: ProtocolBugs{
1487					FragmentAlert:     true,
1488					SendSpuriousAlert: alertRecordOverflow,
1489				},
1490			},
1491			shouldFail:    true,
1492			expectedError: ":BAD_ALERT:",
1493		},
1494		{
1495			protocol: dtls,
1496			testType: serverTest,
1497			name:     "FragmentAlert-DTLS",
1498			config: Config{
1499				Bugs: ProtocolBugs{
1500					FragmentAlert:     true,
1501					SendSpuriousAlert: alertRecordOverflow,
1502				},
1503			},
1504			shouldFail:    true,
1505			expectedError: ":BAD_ALERT:",
1506		},
1507		{
1508			testType: serverTest,
1509			name:     "DoubleAlert",
1510			config: Config{
1511				Bugs: ProtocolBugs{
1512					DoubleAlert:       true,
1513					SendSpuriousAlert: alertRecordOverflow,
1514				},
1515			},
1516			shouldFail:    true,
1517			expectedError: ":BAD_ALERT:",
1518		},
1519		{
1520			protocol: dtls,
1521			testType: serverTest,
1522			name:     "DoubleAlert-DTLS",
1523			config: Config{
1524				Bugs: ProtocolBugs{
1525					DoubleAlert:       true,
1526					SendSpuriousAlert: alertRecordOverflow,
1527				},
1528			},
1529			shouldFail:    true,
1530			expectedError: ":BAD_ALERT:",
1531		},
1532		{
1533			name: "SkipNewSessionTicket",
1534			config: Config{
1535				MaxVersion: VersionTLS12,
1536				Bugs: ProtocolBugs{
1537					SkipNewSessionTicket: true,
1538				},
1539			},
1540			shouldFail:    true,
1541			expectedError: ":UNEXPECTED_RECORD:",
1542		},
1543		{
1544			testType: serverTest,
1545			name:     "FallbackSCSV",
1546			config: Config{
1547				MaxVersion: VersionTLS11,
1548				Bugs: ProtocolBugs{
1549					SendFallbackSCSV: true,
1550				},
1551			},
1552			shouldFail:         true,
1553			expectedError:      ":INAPPROPRIATE_FALLBACK:",
1554			expectedLocalError: "remote error: inappropriate fallback",
1555		},
1556		{
1557			testType: serverTest,
1558			name:     "FallbackSCSV-VersionMatch-TLS13",
1559			config: Config{
1560				MaxVersion: VersionTLS13,
1561				Bugs: ProtocolBugs{
1562					SendFallbackSCSV: true,
1563				},
1564			},
1565		},
1566		{
1567			testType: serverTest,
1568			name:     "FallbackSCSV-VersionMatch-TLS12",
1569			config: Config{
1570				MaxVersion: VersionTLS12,
1571				Bugs: ProtocolBugs{
1572					SendFallbackSCSV: true,
1573				},
1574			},
1575			flags: []string{"-max-version", strconv.Itoa(VersionTLS12)},
1576		},
1577		{
1578			testType: serverTest,
1579			name:     "FragmentedClientVersion",
1580			config: Config{
1581				Bugs: ProtocolBugs{
1582					MaxHandshakeRecordLength: 1,
1583					FragmentClientVersion:    true,
1584				},
1585			},
1586			expectedVersion: VersionTLS13,
1587		},
1588		{
1589			testType:      serverTest,
1590			name:          "HttpGET",
1591			sendPrefix:    "GET / HTTP/1.0\n",
1592			shouldFail:    true,
1593			expectedError: ":HTTP_REQUEST:",
1594		},
1595		{
1596			testType:      serverTest,
1597			name:          "HttpPOST",
1598			sendPrefix:    "POST / HTTP/1.0\n",
1599			shouldFail:    true,
1600			expectedError: ":HTTP_REQUEST:",
1601		},
1602		{
1603			testType:      serverTest,
1604			name:          "HttpHEAD",
1605			sendPrefix:    "HEAD / HTTP/1.0\n",
1606			shouldFail:    true,
1607			expectedError: ":HTTP_REQUEST:",
1608		},
1609		{
1610			testType:      serverTest,
1611			name:          "HttpPUT",
1612			sendPrefix:    "PUT / HTTP/1.0\n",
1613			shouldFail:    true,
1614			expectedError: ":HTTP_REQUEST:",
1615		},
1616		{
1617			testType:      serverTest,
1618			name:          "HttpCONNECT",
1619			sendPrefix:    "CONNECT www.google.com:443 HTTP/1.0\n",
1620			shouldFail:    true,
1621			expectedError: ":HTTPS_PROXY_REQUEST:",
1622		},
1623		{
1624			testType:      serverTest,
1625			name:          "Garbage",
1626			sendPrefix:    "blah",
1627			shouldFail:    true,
1628			expectedError: ":WRONG_VERSION_NUMBER:",
1629		},
1630		{
1631			name: "RSAEphemeralKey",
1632			config: Config{
1633				MaxVersion:   VersionTLS12,
1634				CipherSuites: []uint16{TLS_RSA_WITH_AES_128_CBC_SHA},
1635				Bugs: ProtocolBugs{
1636					RSAEphemeralKey: true,
1637				},
1638			},
1639			shouldFail:    true,
1640			expectedError: ":UNEXPECTED_MESSAGE:",
1641		},
1642		{
1643			name:          "DisableEverything",
1644			flags:         []string{"-no-tls13", "-no-tls12", "-no-tls11", "-no-tls1", "-no-ssl3"},
1645			shouldFail:    true,
1646			expectedError: ":NO_SUPPORTED_VERSIONS_ENABLED:",
1647		},
1648		{
1649			protocol:      dtls,
1650			name:          "DisableEverything-DTLS",
1651			flags:         []string{"-no-tls12", "-no-tls1"},
1652			shouldFail:    true,
1653			expectedError: ":NO_SUPPORTED_VERSIONS_ENABLED:",
1654		},
1655		{
1656			protocol: dtls,
1657			testType: serverTest,
1658			name:     "MTU",
1659			config: Config{
1660				Bugs: ProtocolBugs{
1661					MaxPacketLength: 256,
1662				},
1663			},
1664			flags: []string{"-mtu", "256"},
1665		},
1666		{
1667			protocol: dtls,
1668			testType: serverTest,
1669			name:     "MTUExceeded",
1670			config: Config{
1671				Bugs: ProtocolBugs{
1672					MaxPacketLength: 255,
1673				},
1674			},
1675			flags:              []string{"-mtu", "256"},
1676			shouldFail:         true,
1677			expectedLocalError: "dtls: exceeded maximum packet length",
1678		},
1679		{
1680			name: "EmptyCertificateList",
1681			config: Config{
1682				MaxVersion: VersionTLS12,
1683				Bugs: ProtocolBugs{
1684					EmptyCertificateList: true,
1685				},
1686			},
1687			shouldFail:    true,
1688			expectedError: ":DECODE_ERROR:",
1689		},
1690		{
1691			name: "EmptyCertificateList-TLS13",
1692			config: Config{
1693				MaxVersion: VersionTLS13,
1694				Bugs: ProtocolBugs{
1695					EmptyCertificateList: true,
1696				},
1697			},
1698			shouldFail:    true,
1699			expectedError: ":PEER_DID_NOT_RETURN_A_CERTIFICATE:",
1700		},
1701		{
1702			name:             "TLSFatalBadPackets",
1703			damageFirstWrite: true,
1704			shouldFail:       true,
1705			expectedError:    ":DECRYPTION_FAILED_OR_BAD_RECORD_MAC:",
1706		},
1707		{
1708			protocol:         dtls,
1709			name:             "DTLSIgnoreBadPackets",
1710			damageFirstWrite: true,
1711		},
1712		{
1713			protocol:         dtls,
1714			name:             "DTLSIgnoreBadPackets-Async",
1715			damageFirstWrite: true,
1716			flags:            []string{"-async"},
1717		},
1718		{
1719			name: "AppDataBeforeHandshake",
1720			config: Config{
1721				Bugs: ProtocolBugs{
1722					AppDataBeforeHandshake: []byte("TEST MESSAGE"),
1723				},
1724			},
1725			shouldFail:    true,
1726			expectedError: ":APPLICATION_DATA_INSTEAD_OF_HANDSHAKE:",
1727		},
1728		{
1729			name: "AppDataBeforeHandshake-Empty",
1730			config: Config{
1731				Bugs: ProtocolBugs{
1732					AppDataBeforeHandshake: []byte{},
1733				},
1734			},
1735			shouldFail:    true,
1736			expectedError: ":APPLICATION_DATA_INSTEAD_OF_HANDSHAKE:",
1737		},
1738		{
1739			protocol: dtls,
1740			name:     "AppDataBeforeHandshake-DTLS",
1741			config: Config{
1742				Bugs: ProtocolBugs{
1743					AppDataBeforeHandshake: []byte("TEST MESSAGE"),
1744				},
1745			},
1746			shouldFail:    true,
1747			expectedError: ":UNEXPECTED_RECORD:",
1748		},
1749		{
1750			protocol: dtls,
1751			name:     "AppDataBeforeHandshake-DTLS-Empty",
1752			config: Config{
1753				Bugs: ProtocolBugs{
1754					AppDataBeforeHandshake: []byte{},
1755				},
1756			},
1757			shouldFail:    true,
1758			expectedError: ":UNEXPECTED_RECORD:",
1759		},
1760		{
1761			name: "AppDataAfterChangeCipherSpec",
1762			config: Config{
1763				MaxVersion: VersionTLS12,
1764				Bugs: ProtocolBugs{
1765					AppDataAfterChangeCipherSpec: []byte("TEST MESSAGE"),
1766				},
1767			},
1768			shouldFail:    true,
1769			expectedError: ":UNEXPECTED_RECORD:",
1770		},
1771		{
1772			name: "AppDataAfterChangeCipherSpec-Empty",
1773			config: Config{
1774				MaxVersion: VersionTLS12,
1775				Bugs: ProtocolBugs{
1776					AppDataAfterChangeCipherSpec: []byte{},
1777				},
1778			},
1779			shouldFail:    true,
1780			expectedError: ":UNEXPECTED_RECORD:",
1781		},
1782		{
1783			protocol: dtls,
1784			name:     "AppDataAfterChangeCipherSpec-DTLS",
1785			config: Config{
1786				MaxVersion: VersionTLS12,
1787				Bugs: ProtocolBugs{
1788					AppDataAfterChangeCipherSpec: []byte("TEST MESSAGE"),
1789				},
1790			},
1791			// BoringSSL's DTLS implementation will drop the out-of-order
1792			// application data.
1793		},
1794		{
1795			protocol: dtls,
1796			name:     "AppDataAfterChangeCipherSpec-DTLS-Empty",
1797			config: Config{
1798				MaxVersion: VersionTLS12,
1799				Bugs: ProtocolBugs{
1800					AppDataAfterChangeCipherSpec: []byte{},
1801				},
1802			},
1803			// BoringSSL's DTLS implementation will drop the out-of-order
1804			// application data.
1805		},
1806		{
1807			name: "AlertAfterChangeCipherSpec",
1808			config: Config{
1809				MaxVersion: VersionTLS12,
1810				Bugs: ProtocolBugs{
1811					AlertAfterChangeCipherSpec: alertRecordOverflow,
1812				},
1813			},
1814			shouldFail:    true,
1815			expectedError: ":TLSV1_ALERT_RECORD_OVERFLOW:",
1816		},
1817		{
1818			protocol: dtls,
1819			name:     "AlertAfterChangeCipherSpec-DTLS",
1820			config: Config{
1821				MaxVersion: VersionTLS12,
1822				Bugs: ProtocolBugs{
1823					AlertAfterChangeCipherSpec: alertRecordOverflow,
1824				},
1825			},
1826			shouldFail:    true,
1827			expectedError: ":TLSV1_ALERT_RECORD_OVERFLOW:",
1828		},
1829		{
1830			protocol: dtls,
1831			name:     "ReorderHandshakeFragments-Small-DTLS",
1832			config: Config{
1833				Bugs: ProtocolBugs{
1834					ReorderHandshakeFragments: true,
1835					// Small enough that every handshake message is
1836					// fragmented.
1837					MaxHandshakeRecordLength: 2,
1838				},
1839			},
1840		},
1841		{
1842			protocol: dtls,
1843			name:     "ReorderHandshakeFragments-Large-DTLS",
1844			config: Config{
1845				Bugs: ProtocolBugs{
1846					ReorderHandshakeFragments: true,
1847					// Large enough that no handshake message is
1848					// fragmented.
1849					MaxHandshakeRecordLength: 2048,
1850				},
1851			},
1852		},
1853		{
1854			protocol: dtls,
1855			name:     "MixCompleteMessageWithFragments-DTLS",
1856			config: Config{
1857				Bugs: ProtocolBugs{
1858					ReorderHandshakeFragments:       true,
1859					MixCompleteMessageWithFragments: true,
1860					MaxHandshakeRecordLength:        2,
1861				},
1862			},
1863		},
1864		{
1865			name: "SendInvalidRecordType",
1866			config: Config{
1867				Bugs: ProtocolBugs{
1868					SendInvalidRecordType: true,
1869				},
1870			},
1871			shouldFail:    true,
1872			expectedError: ":UNEXPECTED_RECORD:",
1873		},
1874		{
1875			protocol: dtls,
1876			name:     "SendInvalidRecordType-DTLS",
1877			config: Config{
1878				Bugs: ProtocolBugs{
1879					SendInvalidRecordType: true,
1880				},
1881			},
1882			shouldFail:    true,
1883			expectedError: ":UNEXPECTED_RECORD:",
1884		},
1885		{
1886			name: "FalseStart-SkipServerSecondLeg",
1887			config: Config{
1888				MaxVersion:   VersionTLS12,
1889				CipherSuites: []uint16{TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256},
1890				NextProtos:   []string{"foo"},
1891				Bugs: ProtocolBugs{
1892					SkipNewSessionTicket: true,
1893					SkipChangeCipherSpec: true,
1894					SkipFinished:         true,
1895					ExpectFalseStart:     true,
1896				},
1897			},
1898			flags: []string{
1899				"-false-start",
1900				"-handshake-never-done",
1901				"-advertise-alpn", "\x03foo",
1902				"-expect-alpn", "foo",
1903			},
1904			shimWritesFirst: true,
1905			shouldFail:      true,
1906			expectedError:   ":APPLICATION_DATA_INSTEAD_OF_HANDSHAKE:",
1907		},
1908		{
1909			name: "FalseStart-SkipServerSecondLeg-Implicit",
1910			config: Config{
1911				MaxVersion:   VersionTLS12,
1912				CipherSuites: []uint16{TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256},
1913				NextProtos:   []string{"foo"},
1914				Bugs: ProtocolBugs{
1915					SkipNewSessionTicket: true,
1916					SkipChangeCipherSpec: true,
1917					SkipFinished:         true,
1918				},
1919			},
1920			flags: []string{
1921				"-implicit-handshake",
1922				"-false-start",
1923				"-handshake-never-done",
1924				"-advertise-alpn", "\x03foo",
1925			},
1926			shouldFail:    true,
1927			expectedError: ":APPLICATION_DATA_INSTEAD_OF_HANDSHAKE:",
1928		},
1929		{
1930			testType:           serverTest,
1931			name:               "FailEarlyCallback",
1932			flags:              []string{"-fail-early-callback"},
1933			shouldFail:         true,
1934			expectedError:      ":CONNECTION_REJECTED:",
1935			expectedLocalError: "remote error: handshake failure",
1936		},
1937		{
1938			name: "FailCertCallback-Client-TLS12",
1939			config: Config{
1940				MaxVersion: VersionTLS12,
1941				ClientAuth: RequestClientCert,
1942			},
1943			flags:              []string{"-fail-cert-callback"},
1944			shouldFail:         true,
1945			expectedError:      ":CERT_CB_ERROR:",
1946			expectedLocalError: "remote error: internal error",
1947		},
1948		{
1949			testType: serverTest,
1950			name:     "FailCertCallback-Server-TLS12",
1951			config: Config{
1952				MaxVersion: VersionTLS12,
1953			},
1954			flags:              []string{"-fail-cert-callback"},
1955			shouldFail:         true,
1956			expectedError:      ":CERT_CB_ERROR:",
1957			expectedLocalError: "remote error: internal error",
1958		},
1959		{
1960			name: "FailCertCallback-Client-TLS13",
1961			config: Config{
1962				MaxVersion: VersionTLS13,
1963				ClientAuth: RequestClientCert,
1964			},
1965			flags:              []string{"-fail-cert-callback"},
1966			shouldFail:         true,
1967			expectedError:      ":CERT_CB_ERROR:",
1968			expectedLocalError: "remote error: internal error",
1969		},
1970		{
1971			testType: serverTest,
1972			name:     "FailCertCallback-Server-TLS13",
1973			config: Config{
1974				MaxVersion: VersionTLS13,
1975			},
1976			flags:              []string{"-fail-cert-callback"},
1977			shouldFail:         true,
1978			expectedError:      ":CERT_CB_ERROR:",
1979			expectedLocalError: "remote error: internal error",
1980		},
1981		{
1982			protocol: dtls,
1983			name:     "FragmentMessageTypeMismatch-DTLS",
1984			config: Config{
1985				Bugs: ProtocolBugs{
1986					MaxHandshakeRecordLength:    2,
1987					FragmentMessageTypeMismatch: true,
1988				},
1989			},
1990			shouldFail:    true,
1991			expectedError: ":FRAGMENT_MISMATCH:",
1992		},
1993		{
1994			protocol: dtls,
1995			name:     "FragmentMessageLengthMismatch-DTLS",
1996			config: Config{
1997				Bugs: ProtocolBugs{
1998					MaxHandshakeRecordLength:      2,
1999					FragmentMessageLengthMismatch: true,
2000				},
2001			},
2002			shouldFail:    true,
2003			expectedError: ":FRAGMENT_MISMATCH:",
2004		},
2005		{
2006			protocol: dtls,
2007			name:     "SplitFragments-Header-DTLS",
2008			config: Config{
2009				Bugs: ProtocolBugs{
2010					SplitFragments: 2,
2011				},
2012			},
2013			shouldFail:    true,
2014			expectedError: ":BAD_HANDSHAKE_RECORD:",
2015		},
2016		{
2017			protocol: dtls,
2018			name:     "SplitFragments-Boundary-DTLS",
2019			config: Config{
2020				Bugs: ProtocolBugs{
2021					SplitFragments: dtlsRecordHeaderLen,
2022				},
2023			},
2024			shouldFail:    true,
2025			expectedError: ":BAD_HANDSHAKE_RECORD:",
2026		},
2027		{
2028			protocol: dtls,
2029			name:     "SplitFragments-Body-DTLS",
2030			config: Config{
2031				Bugs: ProtocolBugs{
2032					SplitFragments: dtlsRecordHeaderLen + 1,
2033				},
2034			},
2035			shouldFail:    true,
2036			expectedError: ":BAD_HANDSHAKE_RECORD:",
2037		},
2038		{
2039			protocol: dtls,
2040			name:     "SendEmptyFragments-DTLS",
2041			config: Config{
2042				Bugs: ProtocolBugs{
2043					SendEmptyFragments: true,
2044				},
2045			},
2046		},
2047		{
2048			name: "BadFinished-Client",
2049			config: Config{
2050				MaxVersion: VersionTLS12,
2051				Bugs: ProtocolBugs{
2052					BadFinished: true,
2053				},
2054			},
2055			shouldFail:    true,
2056			expectedError: ":DIGEST_CHECK_FAILED:",
2057		},
2058		{
2059			name: "BadFinished-Client-TLS13",
2060			config: Config{
2061				MaxVersion: VersionTLS13,
2062				Bugs: ProtocolBugs{
2063					BadFinished: true,
2064				},
2065			},
2066			shouldFail:    true,
2067			expectedError: ":DIGEST_CHECK_FAILED:",
2068		},
2069		{
2070			testType: serverTest,
2071			name:     "BadFinished-Server",
2072			config: Config{
2073				MaxVersion: VersionTLS12,
2074				Bugs: ProtocolBugs{
2075					BadFinished: true,
2076				},
2077			},
2078			shouldFail:    true,
2079			expectedError: ":DIGEST_CHECK_FAILED:",
2080		},
2081		{
2082			testType: serverTest,
2083			name:     "BadFinished-Server-TLS13",
2084			config: Config{
2085				MaxVersion: VersionTLS13,
2086				Bugs: ProtocolBugs{
2087					BadFinished: true,
2088				},
2089			},
2090			shouldFail:    true,
2091			expectedError: ":DIGEST_CHECK_FAILED:",
2092		},
2093		{
2094			name: "FalseStart-BadFinished",
2095			config: Config{
2096				MaxVersion:   VersionTLS12,
2097				CipherSuites: []uint16{TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256},
2098				NextProtos:   []string{"foo"},
2099				Bugs: ProtocolBugs{
2100					BadFinished:      true,
2101					ExpectFalseStart: true,
2102				},
2103			},
2104			flags: []string{
2105				"-false-start",
2106				"-handshake-never-done",
2107				"-advertise-alpn", "\x03foo",
2108				"-expect-alpn", "foo",
2109			},
2110			shimWritesFirst: true,
2111			shouldFail:      true,
2112			expectedError:   ":DIGEST_CHECK_FAILED:",
2113		},
2114		{
2115			name: "NoFalseStart-NoALPN",
2116			config: Config{
2117				MaxVersion:   VersionTLS12,
2118				CipherSuites: []uint16{TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256},
2119				Bugs: ProtocolBugs{
2120					ExpectFalseStart:          true,
2121					AlertBeforeFalseStartTest: alertAccessDenied,
2122				},
2123			},
2124			flags: []string{
2125				"-false-start",
2126			},
2127			shimWritesFirst:    true,
2128			shouldFail:         true,
2129			expectedError:      ":TLSV1_ALERT_ACCESS_DENIED:",
2130			expectedLocalError: "tls: peer did not false start: EOF",
2131		},
2132		{
2133			name: "NoFalseStart-NoAEAD",
2134			config: Config{
2135				MaxVersion:   VersionTLS12,
2136				CipherSuites: []uint16{TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA},
2137				NextProtos:   []string{"foo"},
2138				Bugs: ProtocolBugs{
2139					ExpectFalseStart:          true,
2140					AlertBeforeFalseStartTest: alertAccessDenied,
2141				},
2142			},
2143			flags: []string{
2144				"-false-start",
2145				"-advertise-alpn", "\x03foo",
2146			},
2147			shimWritesFirst:    true,
2148			shouldFail:         true,
2149			expectedError:      ":TLSV1_ALERT_ACCESS_DENIED:",
2150			expectedLocalError: "tls: peer did not false start: EOF",
2151		},
2152		{
2153			name: "NoFalseStart-RSA",
2154			config: Config{
2155				MaxVersion:   VersionTLS12,
2156				CipherSuites: []uint16{TLS_RSA_WITH_AES_128_GCM_SHA256},
2157				NextProtos:   []string{"foo"},
2158				Bugs: ProtocolBugs{
2159					ExpectFalseStart:          true,
2160					AlertBeforeFalseStartTest: alertAccessDenied,
2161				},
2162			},
2163			flags: []string{
2164				"-false-start",
2165				"-advertise-alpn", "\x03foo",
2166			},
2167			shimWritesFirst:    true,
2168			shouldFail:         true,
2169			expectedError:      ":TLSV1_ALERT_ACCESS_DENIED:",
2170			expectedLocalError: "tls: peer did not false start: EOF",
2171		},
2172		{
2173			protocol: dtls,
2174			name:     "SendSplitAlert-Sync",
2175			config: Config{
2176				Bugs: ProtocolBugs{
2177					SendSplitAlert: true,
2178				},
2179			},
2180		},
2181		{
2182			protocol: dtls,
2183			name:     "SendSplitAlert-Async",
2184			config: Config{
2185				Bugs: ProtocolBugs{
2186					SendSplitAlert: true,
2187				},
2188			},
2189			flags: []string{"-async"},
2190		},
2191		{
2192			protocol: dtls,
2193			name:     "PackDTLSHandshake",
2194			config: Config{
2195				Bugs: ProtocolBugs{
2196					MaxHandshakeRecordLength: 2,
2197					PackHandshakeFragments:   20,
2198					PackHandshakeRecords:     200,
2199				},
2200			},
2201		},
2202		{
2203			name:             "SendEmptyRecords-Pass",
2204			sendEmptyRecords: 32,
2205		},
2206		{
2207			name:             "SendEmptyRecords",
2208			sendEmptyRecords: 33,
2209			shouldFail:       true,
2210			expectedError:    ":TOO_MANY_EMPTY_FRAGMENTS:",
2211		},
2212		{
2213			name:             "SendEmptyRecords-Async",
2214			sendEmptyRecords: 33,
2215			flags:            []string{"-async"},
2216			shouldFail:       true,
2217			expectedError:    ":TOO_MANY_EMPTY_FRAGMENTS:",
2218		},
2219		{
2220			name: "SendWarningAlerts-Pass",
2221			config: Config{
2222				MaxVersion: VersionTLS12,
2223			},
2224			sendWarningAlerts: 4,
2225		},
2226		{
2227			protocol: dtls,
2228			name:     "SendWarningAlerts-DTLS-Pass",
2229			config: Config{
2230				MaxVersion: VersionTLS12,
2231			},
2232			sendWarningAlerts: 4,
2233		},
2234		{
2235			name: "SendWarningAlerts-TLS13",
2236			config: Config{
2237				MaxVersion: VersionTLS13,
2238			},
2239			sendWarningAlerts:  4,
2240			shouldFail:         true,
2241			expectedError:      ":BAD_ALERT:",
2242			expectedLocalError: "remote error: error decoding message",
2243		},
2244		{
2245			name: "SendWarningAlerts",
2246			config: Config{
2247				MaxVersion: VersionTLS12,
2248			},
2249			sendWarningAlerts: 5,
2250			shouldFail:        true,
2251			expectedError:     ":TOO_MANY_WARNING_ALERTS:",
2252		},
2253		{
2254			name: "SendWarningAlerts-Async",
2255			config: Config{
2256				MaxVersion: VersionTLS12,
2257			},
2258			sendWarningAlerts: 5,
2259			flags:             []string{"-async"},
2260			shouldFail:        true,
2261			expectedError:     ":TOO_MANY_WARNING_ALERTS:",
2262		},
2263		{
2264			name:               "SendBogusAlertType",
2265			sendBogusAlertType: true,
2266			shouldFail:         true,
2267			expectedError:      ":UNKNOWN_ALERT_TYPE:",
2268			expectedLocalError: "remote error: illegal parameter",
2269		},
2270		{
2271			protocol:           dtls,
2272			name:               "SendBogusAlertType-DTLS",
2273			sendBogusAlertType: true,
2274			shouldFail:         true,
2275			expectedError:      ":UNKNOWN_ALERT_TYPE:",
2276			expectedLocalError: "remote error: illegal parameter",
2277		},
2278		{
2279			name: "TooManyKeyUpdates",
2280			config: Config{
2281				MaxVersion: VersionTLS13,
2282			},
2283			sendKeyUpdates:   33,
2284			keyUpdateRequest: keyUpdateNotRequested,
2285			shouldFail:       true,
2286			expectedError:    ":TOO_MANY_KEY_UPDATES:",
2287		},
2288		{
2289			name: "EmptySessionID",
2290			config: Config{
2291				MaxVersion:             VersionTLS12,
2292				SessionTicketsDisabled: true,
2293			},
2294			noSessionCache: true,
2295			flags:          []string{"-expect-no-session"},
2296		},
2297		{
2298			name: "Unclean-Shutdown",
2299			config: Config{
2300				Bugs: ProtocolBugs{
2301					NoCloseNotify:     true,
2302					ExpectCloseNotify: true,
2303				},
2304			},
2305			shimShutsDown: true,
2306			flags:         []string{"-check-close-notify"},
2307			shouldFail:    true,
2308			expectedError: "Unexpected SSL_shutdown result: -1 != 1",
2309		},
2310		{
2311			name: "Unclean-Shutdown-Ignored",
2312			config: Config{
2313				Bugs: ProtocolBugs{
2314					NoCloseNotify: true,
2315				},
2316			},
2317			shimShutsDown: true,
2318		},
2319		{
2320			name: "Unclean-Shutdown-Alert",
2321			config: Config{
2322				Bugs: ProtocolBugs{
2323					SendAlertOnShutdown: alertDecompressionFailure,
2324					ExpectCloseNotify:   true,
2325				},
2326			},
2327			shimShutsDown: true,
2328			flags:         []string{"-check-close-notify"},
2329			shouldFail:    true,
2330			expectedError: ":SSLV3_ALERT_DECOMPRESSION_FAILURE:",
2331		},
2332		{
2333			name: "LargePlaintext",
2334			config: Config{
2335				Bugs: ProtocolBugs{
2336					SendLargeRecords: true,
2337				},
2338			},
2339			messageLen:    maxPlaintext + 1,
2340			shouldFail:    true,
2341			expectedError: ":DATA_LENGTH_TOO_LONG:",
2342		},
2343		{
2344			protocol: dtls,
2345			name:     "LargePlaintext-DTLS",
2346			config: Config{
2347				Bugs: ProtocolBugs{
2348					SendLargeRecords: true,
2349				},
2350			},
2351			messageLen:    maxPlaintext + 1,
2352			shouldFail:    true,
2353			expectedError: ":DATA_LENGTH_TOO_LONG:",
2354		},
2355		{
2356			name: "LargeCiphertext",
2357			config: Config{
2358				Bugs: ProtocolBugs{
2359					SendLargeRecords: true,
2360				},
2361			},
2362			messageLen:    maxPlaintext * 2,
2363			shouldFail:    true,
2364			expectedError: ":ENCRYPTED_LENGTH_TOO_LONG:",
2365		},
2366		{
2367			protocol: dtls,
2368			name:     "LargeCiphertext-DTLS",
2369			config: Config{
2370				Bugs: ProtocolBugs{
2371					SendLargeRecords: true,
2372				},
2373			},
2374			messageLen: maxPlaintext * 2,
2375			// Unlike the other four cases, DTLS drops records which
2376			// are invalid before authentication, so the connection
2377			// does not fail.
2378			expectMessageDropped: true,
2379		},
2380		{
2381			name:        "BadHelloRequest-1",
2382			renegotiate: 1,
2383			config: Config{
2384				MaxVersion: VersionTLS12,
2385				Bugs: ProtocolBugs{
2386					BadHelloRequest: []byte{typeHelloRequest, 0, 0, 1, 1},
2387				},
2388			},
2389			flags: []string{
2390				"-renegotiate-freely",
2391				"-expect-total-renegotiations", "1",
2392			},
2393			shouldFail:    true,
2394			expectedError: ":EXCESSIVE_MESSAGE_SIZE:",
2395		},
2396		{
2397			name:        "BadHelloRequest-2",
2398			renegotiate: 1,
2399			config: Config{
2400				MaxVersion: VersionTLS12,
2401				Bugs: ProtocolBugs{
2402					BadHelloRequest: []byte{typeServerKeyExchange, 0, 0, 0},
2403				},
2404			},
2405			flags: []string{
2406				"-renegotiate-freely",
2407				"-expect-total-renegotiations", "1",
2408			},
2409			shouldFail:    true,
2410			expectedError: ":BAD_HELLO_REQUEST:",
2411		},
2412		{
2413			testType: serverTest,
2414			name:     "SupportTicketsWithSessionID",
2415			config: Config{
2416				MaxVersion:             VersionTLS12,
2417				SessionTicketsDisabled: true,
2418			},
2419			resumeConfig: &Config{
2420				MaxVersion: VersionTLS12,
2421			},
2422			resumeSession: true,
2423		},
2424		{
2425			protocol: dtls,
2426			name:     "DTLS-SendExtraFinished",
2427			config: Config{
2428				Bugs: ProtocolBugs{
2429					SendExtraFinished: true,
2430				},
2431			},
2432			shouldFail:    true,
2433			expectedError: ":UNEXPECTED_RECORD:",
2434		},
2435		{
2436			protocol: dtls,
2437			name:     "DTLS-SendExtraFinished-Reordered",
2438			config: Config{
2439				Bugs: ProtocolBugs{
2440					MaxHandshakeRecordLength:  2,
2441					ReorderHandshakeFragments: true,
2442					SendExtraFinished:         true,
2443				},
2444			},
2445			shouldFail:    true,
2446			expectedError: ":UNEXPECTED_RECORD:",
2447		},
2448		{
2449			testType: serverTest,
2450			name:     "V2ClientHello-EmptyRecordPrefix",
2451			config: Config{
2452				// Choose a cipher suite that does not involve
2453				// elliptic curves, so no extensions are
2454				// involved.
2455				MaxVersion:   VersionTLS12,
2456				CipherSuites: []uint16{TLS_RSA_WITH_3DES_EDE_CBC_SHA},
2457				Bugs: ProtocolBugs{
2458					SendV2ClientHello: true,
2459				},
2460			},
2461			sendPrefix: string([]byte{
2462				byte(recordTypeHandshake),
2463				3, 1, // version
2464				0, 0, // length
2465			}),
2466			// A no-op empty record may not be sent before V2ClientHello.
2467			shouldFail:    true,
2468			expectedError: ":WRONG_VERSION_NUMBER:",
2469		},
2470		{
2471			testType: serverTest,
2472			name:     "V2ClientHello-WarningAlertPrefix",
2473			config: Config{
2474				// Choose a cipher suite that does not involve
2475				// elliptic curves, so no extensions are
2476				// involved.
2477				MaxVersion:   VersionTLS12,
2478				CipherSuites: []uint16{TLS_RSA_WITH_3DES_EDE_CBC_SHA},
2479				Bugs: ProtocolBugs{
2480					SendV2ClientHello: true,
2481				},
2482			},
2483			sendPrefix: string([]byte{
2484				byte(recordTypeAlert),
2485				3, 1, // version
2486				0, 2, // length
2487				alertLevelWarning, byte(alertDecompressionFailure),
2488			}),
2489			// A no-op warning alert may not be sent before V2ClientHello.
2490			shouldFail:    true,
2491			expectedError: ":WRONG_VERSION_NUMBER:",
2492		},
2493		{
2494			name: "KeyUpdate-Client",
2495			config: Config{
2496				MaxVersion: VersionTLS13,
2497			},
2498			sendKeyUpdates:   1,
2499			keyUpdateRequest: keyUpdateNotRequested,
2500		},
2501		{
2502			testType: serverTest,
2503			name:     "KeyUpdate-Server",
2504			config: Config{
2505				MaxVersion: VersionTLS13,
2506			},
2507			sendKeyUpdates:   1,
2508			keyUpdateRequest: keyUpdateNotRequested,
2509		},
2510		{
2511			name: "KeyUpdate-InvalidRequestMode",
2512			config: Config{
2513				MaxVersion: VersionTLS13,
2514			},
2515			sendKeyUpdates:   1,
2516			keyUpdateRequest: 42,
2517			shouldFail:       true,
2518			expectedError:    ":DECODE_ERROR:",
2519		},
2520		{
2521			// Test that KeyUpdates are acknowledged properly.
2522			name: "KeyUpdate-RequestACK",
2523			config: Config{
2524				MaxVersion: VersionTLS13,
2525				Bugs: ProtocolBugs{
2526					RejectUnsolicitedKeyUpdate: true,
2527				},
2528			},
2529			// Test the shim receiving many KeyUpdates in a row.
2530			sendKeyUpdates:   5,
2531			messageCount:     5,
2532			keyUpdateRequest: keyUpdateRequested,
2533		},
2534		{
2535			// Test that KeyUpdates are acknowledged properly if the
2536			// peer's KeyUpdate is discovered while a write is
2537			// pending.
2538			name: "KeyUpdate-RequestACK-UnfinishedWrite",
2539			config: Config{
2540				MaxVersion: VersionTLS13,
2541				Bugs: ProtocolBugs{
2542					RejectUnsolicitedKeyUpdate: true,
2543				},
2544			},
2545			// Test the shim receiving many KeyUpdates in a row.
2546			sendKeyUpdates:          5,
2547			messageCount:            5,
2548			keyUpdateRequest:        keyUpdateRequested,
2549			readWithUnfinishedWrite: true,
2550			flags: []string{"-async"},
2551		},
2552		{
2553			name: "SendSNIWarningAlert",
2554			config: Config{
2555				MaxVersion: VersionTLS12,
2556				Bugs: ProtocolBugs{
2557					SendSNIWarningAlert: true,
2558				},
2559			},
2560		},
2561		{
2562			testType: serverTest,
2563			name:     "ExtraCompressionMethods-TLS12",
2564			config: Config{
2565				MaxVersion: VersionTLS12,
2566				Bugs: ProtocolBugs{
2567					SendCompressionMethods: []byte{1, 2, 3, compressionNone, 4, 5, 6},
2568				},
2569			},
2570		},
2571		{
2572			testType: serverTest,
2573			name:     "ExtraCompressionMethods-TLS13",
2574			config: Config{
2575				MaxVersion: VersionTLS13,
2576				Bugs: ProtocolBugs{
2577					SendCompressionMethods: []byte{1, 2, 3, compressionNone, 4, 5, 6},
2578				},
2579			},
2580			shouldFail:         true,
2581			expectedError:      ":INVALID_COMPRESSION_LIST:",
2582			expectedLocalError: "remote error: illegal parameter",
2583		},
2584		{
2585			testType: serverTest,
2586			name:     "NoNullCompression-TLS12",
2587			config: Config{
2588				MaxVersion: VersionTLS12,
2589				Bugs: ProtocolBugs{
2590					SendCompressionMethods: []byte{1, 2, 3, 4, 5, 6},
2591				},
2592			},
2593			shouldFail:         true,
2594			expectedError:      ":INVALID_COMPRESSION_LIST:",
2595			expectedLocalError: "remote error: illegal parameter",
2596		},
2597		{
2598			testType: serverTest,
2599			name:     "NoNullCompression-TLS13",
2600			config: Config{
2601				MaxVersion: VersionTLS13,
2602				Bugs: ProtocolBugs{
2603					SendCompressionMethods: []byte{1, 2, 3, 4, 5, 6},
2604				},
2605			},
2606			shouldFail:         true,
2607			expectedError:      ":INVALID_COMPRESSION_LIST:",
2608			expectedLocalError: "remote error: illegal parameter",
2609		},
2610		// Test that the client rejects invalid compression methods
2611		// from the server.
2612		{
2613			testType: clientTest,
2614			name:     "InvalidCompressionMethod",
2615			config: Config{
2616				MaxVersion: VersionTLS12,
2617				Bugs: ProtocolBugs{
2618					SendCompressionMethod: 1,
2619				},
2620			},
2621			shouldFail:         true,
2622			expectedError:      ":UNSUPPORTED_COMPRESSION_ALGORITHM:",
2623			expectedLocalError: "remote error: illegal parameter",
2624		},
2625		{
2626			name: "GREASE-Client-TLS12",
2627			config: Config{
2628				MaxVersion: VersionTLS12,
2629				Bugs: ProtocolBugs{
2630					ExpectGREASE: true,
2631				},
2632			},
2633			flags: []string{"-enable-grease"},
2634		},
2635		{
2636			name: "GREASE-Client-TLS13",
2637			config: Config{
2638				MaxVersion: VersionTLS13,
2639				Bugs: ProtocolBugs{
2640					ExpectGREASE: true,
2641				},
2642			},
2643			flags: []string{"-enable-grease"},
2644		},
2645		{
2646			testType: serverTest,
2647			name:     "GREASE-Server-TLS13",
2648			config: Config{
2649				MaxVersion: VersionTLS13,
2650				Bugs: ProtocolBugs{
2651					// TLS 1.3 servers are expected to
2652					// always enable GREASE. TLS 1.3 is new,
2653					// so there is no existing ecosystem to
2654					// worry about.
2655					ExpectGREASE: true,
2656				},
2657			},
2658		},
2659		{
2660			// Test the server so there is a large certificate as
2661			// well as application data.
2662			testType: serverTest,
2663			name:     "MaxSendFragment",
2664			config: Config{
2665				Bugs: ProtocolBugs{
2666					MaxReceivePlaintext: 512,
2667				},
2668			},
2669			messageLen: 1024,
2670			flags: []string{
2671				"-max-send-fragment", "512",
2672				"-read-size", "1024",
2673			},
2674		},
2675		{
2676			// Test the server so there is a large certificate as
2677			// well as application data.
2678			testType: serverTest,
2679			name:     "MaxSendFragment-TooLarge",
2680			config: Config{
2681				Bugs: ProtocolBugs{
2682					// Ensure that some of the records are
2683					// 512.
2684					MaxReceivePlaintext: 511,
2685				},
2686			},
2687			messageLen: 1024,
2688			flags: []string{
2689				"-max-send-fragment", "512",
2690				"-read-size", "1024",
2691			},
2692			shouldFail:         true,
2693			expectedLocalError: "local error: record overflow",
2694		},
2695	}
2696	testCases = append(testCases, basicTests...)
2697
2698	// Test that very large messages can be received.
2699	cert := rsaCertificate
2700	for i := 0; i < 50; i++ {
2701		cert.Certificate = append(cert.Certificate, cert.Certificate[0])
2702	}
2703	testCases = append(testCases, testCase{
2704		name: "LargeMessage",
2705		config: Config{
2706			Certificates: []Certificate{cert},
2707		},
2708	})
2709	testCases = append(testCases, testCase{
2710		protocol: dtls,
2711		name:     "LargeMessage-DTLS",
2712		config: Config{
2713			Certificates: []Certificate{cert},
2714		},
2715	})
2716
2717	// They are rejected if the maximum certificate chain length is capped.
2718	testCases = append(testCases, testCase{
2719		name: "LargeMessage-Reject",
2720		config: Config{
2721			Certificates: []Certificate{cert},
2722		},
2723		flags:         []string{"-max-cert-list", "16384"},
2724		shouldFail:    true,
2725		expectedError: ":EXCESSIVE_MESSAGE_SIZE:",
2726	})
2727	testCases = append(testCases, testCase{
2728		protocol: dtls,
2729		name:     "LargeMessage-Reject-DTLS",
2730		config: Config{
2731			Certificates: []Certificate{cert},
2732		},
2733		flags:         []string{"-max-cert-list", "16384"},
2734		shouldFail:    true,
2735		expectedError: ":EXCESSIVE_MESSAGE_SIZE:",
2736	})
2737}
2738
2739func addTestForCipherSuite(suite testCipherSuite, ver tlsVersion, protocol protocol) {
2740	const psk = "12345"
2741	const pskIdentity = "luggage combo"
2742
2743	var prefix string
2744	if protocol == dtls {
2745		if !ver.hasDTLS {
2746			return
2747		}
2748		prefix = "D"
2749	}
2750
2751	var cert Certificate
2752	var certFile string
2753	var keyFile string
2754	if hasComponent(suite.name, "ECDSA") {
2755		cert = ecdsaP256Certificate
2756		certFile = ecdsaP256CertificateFile
2757		keyFile = ecdsaP256KeyFile
2758	} else {
2759		cert = rsaCertificate
2760		certFile = rsaCertificateFile
2761		keyFile = rsaKeyFile
2762	}
2763
2764	var flags []string
2765	if hasComponent(suite.name, "PSK") {
2766		flags = append(flags,
2767			"-psk", psk,
2768			"-psk-identity", pskIdentity)
2769	}
2770	if hasComponent(suite.name, "NULL") {
2771		// NULL ciphers must be explicitly enabled.
2772		flags = append(flags, "-cipher", "DEFAULT:NULL-SHA")
2773	}
2774
2775	var shouldServerFail, shouldClientFail bool
2776	if hasComponent(suite.name, "ECDHE") && ver.version == VersionSSL30 {
2777		// BoringSSL clients accept ECDHE on SSLv3, but
2778		// a BoringSSL server will never select it
2779		// because the extension is missing.
2780		shouldServerFail = true
2781	}
2782	if isTLS12Only(suite.name) && ver.version < VersionTLS12 {
2783		shouldClientFail = true
2784		shouldServerFail = true
2785	}
2786	if !isTLS13Suite(suite.name) && ver.version >= VersionTLS13 {
2787		shouldClientFail = true
2788		shouldServerFail = true
2789	}
2790	if isTLS13Suite(suite.name) && ver.version < VersionTLS13 {
2791		shouldClientFail = true
2792		shouldServerFail = true
2793	}
2794	if !isDTLSCipher(suite.name) && protocol == dtls {
2795		shouldClientFail = true
2796		shouldServerFail = true
2797	}
2798
2799	var sendCipherSuite uint16
2800	var expectedServerError, expectedClientError string
2801	serverCipherSuites := []uint16{suite.id}
2802	if shouldServerFail {
2803		expectedServerError = ":NO_SHARED_CIPHER:"
2804	}
2805	if shouldClientFail {
2806		expectedClientError = ":WRONG_CIPHER_RETURNED:"
2807		// Configure the server to select ciphers as normal but
2808		// select an incompatible cipher in ServerHello.
2809		serverCipherSuites = nil
2810		sendCipherSuite = suite.id
2811	}
2812
2813	// For cipher suites and versions where exporters are defined, verify
2814	// that they interoperate.
2815	var exportKeyingMaterial int
2816	if ver.version > VersionSSL30 {
2817		exportKeyingMaterial = 1024
2818	}
2819
2820	testCases = append(testCases, testCase{
2821		testType: serverTest,
2822		protocol: protocol,
2823		name:     prefix + ver.name + "-" + suite.name + "-server",
2824		config: Config{
2825			MinVersion:           ver.version,
2826			MaxVersion:           ver.version,
2827			CipherSuites:         []uint16{suite.id},
2828			Certificates:         []Certificate{cert},
2829			PreSharedKey:         []byte(psk),
2830			PreSharedKeyIdentity: pskIdentity,
2831			Bugs: ProtocolBugs{
2832				AdvertiseAllConfiguredCiphers: true,
2833			},
2834		},
2835		tls13Variant:         ver.tls13Variant,
2836		certFile:             certFile,
2837		keyFile:              keyFile,
2838		flags:                flags,
2839		resumeSession:        true,
2840		shouldFail:           shouldServerFail,
2841		expectedError:        expectedServerError,
2842		exportKeyingMaterial: exportKeyingMaterial,
2843	})
2844
2845	testCases = append(testCases, testCase{
2846		testType: clientTest,
2847		protocol: protocol,
2848		name:     prefix + ver.name + "-" + suite.name + "-client",
2849		config: Config{
2850			MinVersion:           ver.version,
2851			MaxVersion:           ver.version,
2852			CipherSuites:         serverCipherSuites,
2853			Certificates:         []Certificate{cert},
2854			PreSharedKey:         []byte(psk),
2855			PreSharedKeyIdentity: pskIdentity,
2856			Bugs: ProtocolBugs{
2857				IgnorePeerCipherPreferences: shouldClientFail,
2858				SendCipherSuite:             sendCipherSuite,
2859			},
2860		},
2861		tls13Variant:         ver.tls13Variant,
2862		flags:                flags,
2863		resumeSession:        true,
2864		shouldFail:           shouldClientFail,
2865		expectedError:        expectedClientError,
2866		exportKeyingMaterial: exportKeyingMaterial,
2867	})
2868
2869	if shouldClientFail {
2870		return
2871	}
2872
2873	// Ensure the maximum record size is accepted.
2874	testCases = append(testCases, testCase{
2875		protocol: protocol,
2876		name:     prefix + ver.name + "-" + suite.name + "-LargeRecord",
2877		config: Config{
2878			MinVersion:           ver.version,
2879			MaxVersion:           ver.version,
2880			CipherSuites:         []uint16{suite.id},
2881			Certificates:         []Certificate{cert},
2882			PreSharedKey:         []byte(psk),
2883			PreSharedKeyIdentity: pskIdentity,
2884		},
2885		tls13Variant: ver.tls13Variant,
2886		flags:        flags,
2887		messageLen:   maxPlaintext,
2888	})
2889
2890	// Test bad records for all ciphers. Bad records are fatal in TLS
2891	// and ignored in DTLS.
2892	var shouldFail bool
2893	var expectedError string
2894	if protocol == tls {
2895		shouldFail = true
2896		expectedError = ":DECRYPTION_FAILED_OR_BAD_RECORD_MAC:"
2897	}
2898
2899	testCases = append(testCases, testCase{
2900		protocol: protocol,
2901		name:     prefix + ver.name + "-" + suite.name + "-BadRecord",
2902		config: Config{
2903			MinVersion:           ver.version,
2904			MaxVersion:           ver.version,
2905			CipherSuites:         []uint16{suite.id},
2906			Certificates:         []Certificate{cert},
2907			PreSharedKey:         []byte(psk),
2908			PreSharedKeyIdentity: pskIdentity,
2909		},
2910		tls13Variant:     ver.tls13Variant,
2911		flags:            flags,
2912		damageFirstWrite: true,
2913		messageLen:       maxPlaintext,
2914		shouldFail:       shouldFail,
2915		expectedError:    expectedError,
2916	})
2917}
2918
2919func addCipherSuiteTests() {
2920	const bogusCipher = 0xfe00
2921
2922	for _, suite := range testCipherSuites {
2923		for _, ver := range tlsVersions {
2924			for _, protocol := range []protocol{tls, dtls} {
2925				addTestForCipherSuite(suite, ver, protocol)
2926			}
2927		}
2928	}
2929
2930	testCases = append(testCases, testCase{
2931		name: "NoSharedCipher",
2932		config: Config{
2933			MaxVersion:   VersionTLS12,
2934			CipherSuites: []uint16{},
2935		},
2936		shouldFail:    true,
2937		expectedError: ":HANDSHAKE_FAILURE_ON_CLIENT_HELLO:",
2938	})
2939
2940	testCases = append(testCases, testCase{
2941		name: "NoSharedCipher-TLS13",
2942		config: Config{
2943			MaxVersion:   VersionTLS13,
2944			CipherSuites: []uint16{},
2945		},
2946		shouldFail:    true,
2947		expectedError: ":HANDSHAKE_FAILURE_ON_CLIENT_HELLO:",
2948	})
2949
2950	testCases = append(testCases, testCase{
2951		name: "UnsupportedCipherSuite",
2952		config: Config{
2953			MaxVersion:   VersionTLS12,
2954			CipherSuites: []uint16{TLS_RSA_WITH_AES_128_CBC_SHA},
2955			Bugs: ProtocolBugs{
2956				IgnorePeerCipherPreferences: true,
2957			},
2958		},
2959		flags:         []string{"-cipher", "DEFAULT:!AES"},
2960		shouldFail:    true,
2961		expectedError: ":WRONG_CIPHER_RETURNED:",
2962	})
2963
2964	testCases = append(testCases, testCase{
2965		name: "ServerHelloBogusCipher",
2966		config: Config{
2967			MaxVersion: VersionTLS12,
2968			Bugs: ProtocolBugs{
2969				SendCipherSuite: bogusCipher,
2970			},
2971		},
2972		shouldFail:    true,
2973		expectedError: ":UNKNOWN_CIPHER_RETURNED:",
2974	})
2975	testCases = append(testCases, testCase{
2976		name: "ServerHelloBogusCipher-TLS13",
2977		config: Config{
2978			MaxVersion: VersionTLS13,
2979			Bugs: ProtocolBugs{
2980				SendCipherSuite: bogusCipher,
2981			},
2982		},
2983		shouldFail:    true,
2984		expectedError: ":UNKNOWN_CIPHER_RETURNED:",
2985	})
2986
2987	// The server must be tolerant to bogus ciphers.
2988	testCases = append(testCases, testCase{
2989		testType: serverTest,
2990		name:     "UnknownCipher",
2991		config: Config{
2992			MaxVersion:   VersionTLS12,
2993			CipherSuites: []uint16{bogusCipher, TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256},
2994			Bugs: ProtocolBugs{
2995				AdvertiseAllConfiguredCiphers: true,
2996			},
2997		},
2998	})
2999
3000	// The server must be tolerant to bogus ciphers.
3001	testCases = append(testCases, testCase{
3002		testType: serverTest,
3003		name:     "UnknownCipher-TLS13",
3004		config: Config{
3005			MaxVersion:   VersionTLS13,
3006			CipherSuites: []uint16{bogusCipher, TLS_AES_128_GCM_SHA256},
3007			Bugs: ProtocolBugs{
3008				AdvertiseAllConfiguredCiphers: true,
3009			},
3010		},
3011	})
3012
3013	// Test empty ECDHE_PSK identity hints work as expected.
3014	testCases = append(testCases, testCase{
3015		name: "EmptyECDHEPSKHint",
3016		config: Config{
3017			MaxVersion:   VersionTLS12,
3018			CipherSuites: []uint16{TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA},
3019			PreSharedKey: []byte("secret"),
3020		},
3021		flags: []string{"-psk", "secret"},
3022	})
3023
3024	// Test empty PSK identity hints work as expected, even if an explicit
3025	// ServerKeyExchange is sent.
3026	testCases = append(testCases, testCase{
3027		name: "ExplicitEmptyPSKHint",
3028		config: Config{
3029			MaxVersion:   VersionTLS12,
3030			CipherSuites: []uint16{TLS_PSK_WITH_AES_128_CBC_SHA},
3031			PreSharedKey: []byte("secret"),
3032			Bugs: ProtocolBugs{
3033				AlwaysSendPreSharedKeyIdentityHint: true,
3034			},
3035		},
3036		flags: []string{"-psk", "secret"},
3037	})
3038
3039	// Test that clients enforce that the server-sent certificate and cipher
3040	// suite match in TLS 1.2.
3041	testCases = append(testCases, testCase{
3042		name: "CertificateCipherMismatch-RSA",
3043		config: Config{
3044			MaxVersion:   VersionTLS12,
3045			CipherSuites: []uint16{TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256},
3046			Certificates: []Certificate{rsaCertificate},
3047			Bugs: ProtocolBugs{
3048				SendCipherSuite: TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
3049			},
3050		},
3051		shouldFail:    true,
3052		expectedError: ":WRONG_CERTIFICATE_TYPE:",
3053	})
3054	testCases = append(testCases, testCase{
3055		name: "CertificateCipherMismatch-ECDSA",
3056		config: Config{
3057			MaxVersion:   VersionTLS12,
3058			CipherSuites: []uint16{TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256},
3059			Certificates: []Certificate{ecdsaP256Certificate},
3060			Bugs: ProtocolBugs{
3061				SendCipherSuite: TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
3062			},
3063		},
3064		shouldFail:    true,
3065		expectedError: ":WRONG_CERTIFICATE_TYPE:",
3066	})
3067	testCases = append(testCases, testCase{
3068		name: "CertificateCipherMismatch-Ed25519",
3069		config: Config{
3070			MaxVersion:   VersionTLS12,
3071			CipherSuites: []uint16{TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256},
3072			Certificates: []Certificate{ed25519Certificate},
3073			Bugs: ProtocolBugs{
3074				SendCipherSuite: TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
3075			},
3076		},
3077		shouldFail:    true,
3078		expectedError: ":WRONG_CERTIFICATE_TYPE:",
3079	})
3080
3081	// Test that servers decline to select a cipher suite which is
3082	// inconsistent with their configured certificate.
3083	testCases = append(testCases, testCase{
3084		testType: serverTest,
3085		name:     "ServerCipherFilter-RSA",
3086		config: Config{
3087			MaxVersion:   VersionTLS12,
3088			CipherSuites: []uint16{TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256},
3089		},
3090		flags: []string{
3091			"-cert-file", path.Join(*resourceDir, rsaCertificateFile),
3092			"-key-file", path.Join(*resourceDir, rsaKeyFile),
3093		},
3094		shouldFail:    true,
3095		expectedError: ":NO_SHARED_CIPHER:",
3096	})
3097	testCases = append(testCases, testCase{
3098		testType: serverTest,
3099		name:     "ServerCipherFilter-ECDSA",
3100		config: Config{
3101			MaxVersion:   VersionTLS12,
3102			CipherSuites: []uint16{TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256},
3103		},
3104		flags: []string{
3105			"-cert-file", path.Join(*resourceDir, ecdsaP256CertificateFile),
3106			"-key-file", path.Join(*resourceDir, ecdsaP256KeyFile),
3107		},
3108		shouldFail:    true,
3109		expectedError: ":NO_SHARED_CIPHER:",
3110	})
3111	testCases = append(testCases, testCase{
3112		testType: serverTest,
3113		name:     "ServerCipherFilter-Ed25519",
3114		config: Config{
3115			MaxVersion:   VersionTLS12,
3116			CipherSuites: []uint16{TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256},
3117		},
3118		flags: []string{
3119			"-cert-file", path.Join(*resourceDir, ed25519CertificateFile),
3120			"-key-file", path.Join(*resourceDir, ed25519KeyFile),
3121		},
3122		shouldFail:    true,
3123		expectedError: ":NO_SHARED_CIPHER:",
3124	})
3125
3126	// Test cipher suite negotiation works as expected. Configure a
3127	// complicated cipher suite configuration.
3128	const negotiationTestCiphers = "" +
3129		"TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256:" +
3130		"[TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384|TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256|TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA]:" +
3131		"TLS_RSA_WITH_AES_128_GCM_SHA256:" +
3132		"TLS_RSA_WITH_AES_128_CBC_SHA:" +
3133		"[TLS_RSA_WITH_AES_256_GCM_SHA384|TLS_RSA_WITH_AES_256_CBC_SHA]"
3134	negotiationTests := []struct {
3135		ciphers  []uint16
3136		expected uint16
3137	}{
3138		// Server preferences are honored, including when
3139		// equipreference groups are involved.
3140		{
3141			[]uint16{
3142				TLS_RSA_WITH_AES_256_GCM_SHA384,
3143				TLS_RSA_WITH_AES_128_CBC_SHA,
3144				TLS_RSA_WITH_AES_128_GCM_SHA256,
3145				TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA,
3146				TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
3147			},
3148			TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
3149		},
3150		{
3151			[]uint16{
3152				TLS_RSA_WITH_AES_256_GCM_SHA384,
3153				TLS_RSA_WITH_AES_128_CBC_SHA,
3154				TLS_RSA_WITH_AES_128_GCM_SHA256,
3155				TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA,
3156			},
3157			TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA,
3158		},
3159		{
3160			[]uint16{
3161				TLS_RSA_WITH_AES_256_GCM_SHA384,
3162				TLS_RSA_WITH_AES_128_CBC_SHA,
3163				TLS_RSA_WITH_AES_128_GCM_SHA256,
3164			},
3165			TLS_RSA_WITH_AES_128_GCM_SHA256,
3166		},
3167		{
3168			[]uint16{
3169				TLS_RSA_WITH_AES_256_GCM_SHA384,
3170				TLS_RSA_WITH_AES_128_CBC_SHA,
3171			},
3172			TLS_RSA_WITH_AES_128_CBC_SHA,
3173		},
3174		// Equipreference groups use the client preference.
3175		{
3176			[]uint16{
3177				TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA,
3178				TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256,
3179				TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
3180			},
3181			TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA,
3182		},
3183		{
3184			[]uint16{
3185				TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256,
3186				TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
3187			},
3188			TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256,
3189		},
3190		{
3191			[]uint16{
3192				TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
3193				TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256,
3194			},
3195			TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
3196		},
3197		{
3198			[]uint16{
3199				TLS_RSA_WITH_AES_256_GCM_SHA384,
3200				TLS_RSA_WITH_AES_256_CBC_SHA,
3201			},
3202			TLS_RSA_WITH_AES_256_GCM_SHA384,
3203		},
3204		{
3205			[]uint16{
3206				TLS_RSA_WITH_AES_256_CBC_SHA,
3207				TLS_RSA_WITH_AES_256_GCM_SHA384,
3208			},
3209			TLS_RSA_WITH_AES_256_CBC_SHA,
3210		},
3211		// If there are two equipreference groups, the preferred one
3212		// takes precedence.
3213		{
3214			[]uint16{
3215				TLS_RSA_WITH_AES_256_GCM_SHA384,
3216				TLS_RSA_WITH_AES_256_CBC_SHA,
3217				TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
3218				TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256,
3219			},
3220			TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
3221		},
3222	}
3223	for i, t := range negotiationTests {
3224		testCases = append(testCases, testCase{
3225			testType: serverTest,
3226			name:     "CipherNegotiation-" + strconv.Itoa(i),
3227			config: Config{
3228				MaxVersion:   VersionTLS12,
3229				CipherSuites: t.ciphers,
3230			},
3231			flags:          []string{"-cipher", negotiationTestCiphers},
3232			expectedCipher: t.expected,
3233		})
3234	}
3235}
3236
3237func addBadECDSASignatureTests() {
3238	for badR := BadValue(1); badR < NumBadValues; badR++ {
3239		for badS := BadValue(1); badS < NumBadValues; badS++ {
3240			testCases = append(testCases, testCase{
3241				name: fmt.Sprintf("BadECDSA-%d-%d", badR, badS),
3242				config: Config{
3243					MaxVersion:   VersionTLS12,
3244					CipherSuites: []uint16{TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256},
3245					Certificates: []Certificate{ecdsaP256Certificate},
3246					Bugs: ProtocolBugs{
3247						BadECDSAR: badR,
3248						BadECDSAS: badS,
3249					},
3250				},
3251				shouldFail:    true,
3252				expectedError: ":BAD_SIGNATURE:",
3253			})
3254			testCases = append(testCases, testCase{
3255				name: fmt.Sprintf("BadECDSA-%d-%d-TLS13", badR, badS),
3256				config: Config{
3257					MaxVersion:   VersionTLS13,
3258					Certificates: []Certificate{ecdsaP256Certificate},
3259					Bugs: ProtocolBugs{
3260						BadECDSAR: badR,
3261						BadECDSAS: badS,
3262					},
3263				},
3264				shouldFail:    true,
3265				expectedError: ":BAD_SIGNATURE:",
3266			})
3267		}
3268	}
3269}
3270
3271func addCBCPaddingTests() {
3272	testCases = append(testCases, testCase{
3273		name: "MaxCBCPadding",
3274		config: Config{
3275			MaxVersion:   VersionTLS12,
3276			CipherSuites: []uint16{TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA},
3277			Bugs: ProtocolBugs{
3278				MaxPadding: true,
3279			},
3280		},
3281		messageLen: 12, // 20 bytes of SHA-1 + 12 == 0 % block size
3282	})
3283	testCases = append(testCases, testCase{
3284		name: "BadCBCPadding",
3285		config: Config{
3286			MaxVersion:   VersionTLS12,
3287			CipherSuites: []uint16{TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA},
3288			Bugs: ProtocolBugs{
3289				PaddingFirstByteBad: true,
3290			},
3291		},
3292		shouldFail:    true,
3293		expectedError: ":DECRYPTION_FAILED_OR_BAD_RECORD_MAC:",
3294	})
3295	// OpenSSL previously had an issue where the first byte of padding in
3296	// 255 bytes of padding wasn't checked.
3297	testCases = append(testCases, testCase{
3298		name: "BadCBCPadding255",
3299		config: Config{
3300			MaxVersion:   VersionTLS12,
3301			CipherSuites: []uint16{TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA},
3302			Bugs: ProtocolBugs{
3303				MaxPadding:               true,
3304				PaddingFirstByteBadIf255: true,
3305			},
3306		},
3307		messageLen:    12, // 20 bytes of SHA-1 + 12 == 0 % block size
3308		shouldFail:    true,
3309		expectedError: ":DECRYPTION_FAILED_OR_BAD_RECORD_MAC:",
3310	})
3311}
3312
3313func addCBCSplittingTests() {
3314	var cbcCiphers = []struct {
3315		name   string
3316		cipher uint16
3317	}{
3318		{"3DES", TLS_RSA_WITH_3DES_EDE_CBC_SHA},
3319		{"AES128", TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA},
3320		{"AES256", TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA},
3321	}
3322	for _, t := range cbcCiphers {
3323		testCases = append(testCases, testCase{
3324			name: "CBCRecordSplitting-" + t.name,
3325			config: Config{
3326				MaxVersion:   VersionTLS10,
3327				MinVersion:   VersionTLS10,
3328				CipherSuites: []uint16{t.cipher},
3329			},
3330			messageLen:    -1, // read until EOF
3331			resumeSession: true,
3332			flags: []string{
3333				"-async",
3334				"-write-different-record-sizes",
3335				"-cbc-record-splitting",
3336			},
3337		})
3338		testCases = append(testCases, testCase{
3339			name: "CBCRecordSplittingPartialWrite-" + t.name,
3340			config: Config{
3341				MaxVersion:   VersionTLS10,
3342				MinVersion:   VersionTLS10,
3343				CipherSuites: []uint16{t.cipher},
3344			},
3345			messageLen: -1, // read until EOF
3346			flags: []string{
3347				"-async",
3348				"-write-different-record-sizes",
3349				"-cbc-record-splitting",
3350				"-partial-write",
3351			},
3352		})
3353	}
3354}
3355
3356func addClientAuthTests() {
3357	// Add a dummy cert pool to stress certificate authority parsing.
3358	certPool := x509.NewCertPool()
3359	for _, cert := range []Certificate{rsaCertificate, rsa1024Certificate} {
3360		cert, err := x509.ParseCertificate(cert.Certificate[0])
3361		if err != nil {
3362			panic(err)
3363		}
3364		certPool.AddCert(cert)
3365	}
3366	caNames := certPool.Subjects()
3367
3368	for _, ver := range tlsVersions {
3369		testCases = append(testCases, testCase{
3370			testType: clientTest,
3371			name:     ver.name + "-Client-ClientAuth-RSA",
3372			config: Config{
3373				MinVersion: ver.version,
3374				MaxVersion: ver.version,
3375				ClientAuth: RequireAnyClientCert,
3376				ClientCAs:  certPool,
3377			},
3378			tls13Variant: ver.tls13Variant,
3379			flags: []string{
3380				"-cert-file", path.Join(*resourceDir, rsaCertificateFile),
3381				"-key-file", path.Join(*resourceDir, rsaKeyFile),
3382			},
3383		})
3384		testCases = append(testCases, testCase{
3385			testType: serverTest,
3386			name:     ver.name + "-Server-ClientAuth-RSA",
3387			config: Config{
3388				MinVersion:   ver.version,
3389				MaxVersion:   ver.version,
3390				Certificates: []Certificate{rsaCertificate},
3391			},
3392			tls13Variant: ver.tls13Variant,
3393			flags:        []string{"-require-any-client-certificate"},
3394		})
3395		if ver.version != VersionSSL30 {
3396			testCases = append(testCases, testCase{
3397				testType: serverTest,
3398				name:     ver.name + "-Server-ClientAuth-ECDSA",
3399				config: Config{
3400					MinVersion:   ver.version,
3401					MaxVersion:   ver.version,
3402					Certificates: []Certificate{ecdsaP256Certificate},
3403				},
3404				tls13Variant: ver.tls13Variant,
3405				flags:        []string{"-require-any-client-certificate"},
3406			})
3407			testCases = append(testCases, testCase{
3408				testType: clientTest,
3409				name:     ver.name + "-Client-ClientAuth-ECDSA",
3410				config: Config{
3411					MinVersion: ver.version,
3412					MaxVersion: ver.version,
3413					ClientAuth: RequireAnyClientCert,
3414					ClientCAs:  certPool,
3415				},
3416				tls13Variant: ver.tls13Variant,
3417				flags: []string{
3418					"-cert-file", path.Join(*resourceDir, ecdsaP256CertificateFile),
3419					"-key-file", path.Join(*resourceDir, ecdsaP256KeyFile),
3420				},
3421			})
3422		}
3423
3424		testCases = append(testCases, testCase{
3425			name: "NoClientCertificate-" + ver.name,
3426			config: Config{
3427				MinVersion: ver.version,
3428				MaxVersion: ver.version,
3429				ClientAuth: RequireAnyClientCert,
3430			},
3431			tls13Variant:       ver.tls13Variant,
3432			shouldFail:         true,
3433			expectedLocalError: "client didn't provide a certificate",
3434		})
3435
3436		testCases = append(testCases, testCase{
3437			// Even if not configured to expect a certificate, OpenSSL will
3438			// return X509_V_OK as the verify_result.
3439			testType: serverTest,
3440			name:     "NoClientCertificateRequested-Server-" + ver.name,
3441			config: Config{
3442				MinVersion: ver.version,
3443				MaxVersion: ver.version,
3444			},
3445			tls13Variant: ver.tls13Variant,
3446			flags: []string{
3447				"-expect-verify-result",
3448			},
3449			resumeSession: true,
3450		})
3451
3452		testCases = append(testCases, testCase{
3453			// If a client certificate is not provided, OpenSSL will still
3454			// return X509_V_OK as the verify_result.
3455			testType: serverTest,
3456			name:     "NoClientCertificate-Server-" + ver.name,
3457			config: Config{
3458				MinVersion: ver.version,
3459				MaxVersion: ver.version,
3460			},
3461			tls13Variant: ver.tls13Variant,
3462			flags: []string{
3463				"-expect-verify-result",
3464				"-verify-peer",
3465			},
3466			resumeSession: true,
3467		})
3468
3469		certificateRequired := "remote error: certificate required"
3470		if ver.version < VersionTLS13 {
3471			// Prior to TLS 1.3, the generic handshake_failure alert
3472			// was used.
3473			certificateRequired = "remote error: handshake failure"
3474		}
3475		testCases = append(testCases, testCase{
3476			testType: serverTest,
3477			name:     "RequireAnyClientCertificate-" + ver.name,
3478			config: Config{
3479				MinVersion: ver.version,
3480				MaxVersion: ver.version,
3481			},
3482			flags:              []string{"-require-any-client-certificate"},
3483			tls13Variant:       ver.tls13Variant,
3484			shouldFail:         true,
3485			expectedError:      ":PEER_DID_NOT_RETURN_A_CERTIFICATE:",
3486			expectedLocalError: certificateRequired,
3487		})
3488
3489		if ver.version != VersionSSL30 {
3490			testCases = append(testCases, testCase{
3491				testType: serverTest,
3492				name:     "SkipClientCertificate-" + ver.name,
3493				config: Config{
3494					MinVersion: ver.version,
3495					MaxVersion: ver.version,
3496					Bugs: ProtocolBugs{
3497						SkipClientCertificate: true,
3498					},
3499				},
3500				// Setting SSL_VERIFY_PEER allows anonymous clients.
3501				flags:         []string{"-verify-peer"},
3502				tls13Variant:  ver.tls13Variant,
3503				shouldFail:    true,
3504				expectedError: ":UNEXPECTED_MESSAGE:",
3505			})
3506
3507			testCases = append(testCases, testCase{
3508				testType: serverTest,
3509				name:     "VerifyPeerIfNoOBC-NoChannelID-" + ver.name,
3510				config: Config{
3511					MinVersion: ver.version,
3512					MaxVersion: ver.version,
3513				},
3514				flags: []string{
3515					"-enable-channel-id",
3516					"-verify-peer-if-no-obc",
3517				},
3518				tls13Variant:       ver.tls13Variant,
3519				shouldFail:         true,
3520				expectedError:      ":PEER_DID_NOT_RETURN_A_CERTIFICATE:",
3521				expectedLocalError: certificateRequired,
3522			})
3523
3524			testCases = append(testCases, testCase{
3525				testType: serverTest,
3526				name:     "VerifyPeerIfNoOBC-ChannelID-" + ver.name,
3527				config: Config{
3528					MinVersion: ver.version,
3529					MaxVersion: ver.version,
3530					ChannelID:  channelIDKey,
3531				},
3532				expectChannelID: true,
3533				tls13Variant:    ver.tls13Variant,
3534				flags: []string{
3535					"-enable-channel-id",
3536					"-verify-peer-if-no-obc",
3537				},
3538			})
3539		}
3540
3541		testCases = append(testCases, testCase{
3542			testType: serverTest,
3543			name:     ver.name + "-Server-CertReq-CA-List",
3544			config: Config{
3545				MinVersion:   ver.version,
3546				MaxVersion:   ver.version,
3547				Certificates: []Certificate{rsaCertificate},
3548				Bugs: ProtocolBugs{
3549					ExpectCertificateReqNames: caNames,
3550				},
3551			},
3552			tls13Variant: ver.tls13Variant,
3553			flags: []string{
3554				"-require-any-client-certificate",
3555				"-use-client-ca-list", encodeDERValues(caNames),
3556			},
3557		})
3558
3559		testCases = append(testCases, testCase{
3560			testType: clientTest,
3561			name:     ver.name + "-Client-CertReq-CA-List",
3562			config: Config{
3563				MinVersion:   ver.version,
3564				MaxVersion:   ver.version,
3565				Certificates: []Certificate{rsaCertificate},
3566				ClientAuth:   RequireAnyClientCert,
3567				ClientCAs:    certPool,
3568			},
3569			tls13Variant: ver.tls13Variant,
3570			flags: []string{
3571				"-cert-file", path.Join(*resourceDir, rsaCertificateFile),
3572				"-key-file", path.Join(*resourceDir, rsaKeyFile),
3573				"-expect-client-ca-list", encodeDERValues(caNames),
3574			},
3575		})
3576	}
3577
3578	// Client auth is only legal in certificate-based ciphers.
3579	testCases = append(testCases, testCase{
3580		testType: clientTest,
3581		name:     "ClientAuth-PSK",
3582		config: Config{
3583			MaxVersion:   VersionTLS12,
3584			CipherSuites: []uint16{TLS_PSK_WITH_AES_128_CBC_SHA},
3585			PreSharedKey: []byte("secret"),
3586			ClientAuth:   RequireAnyClientCert,
3587		},
3588		flags: []string{
3589			"-cert-file", path.Join(*resourceDir, rsaCertificateFile),
3590			"-key-file", path.Join(*resourceDir, rsaKeyFile),
3591			"-psk", "secret",
3592		},
3593		shouldFail:    true,
3594		expectedError: ":UNEXPECTED_MESSAGE:",
3595	})
3596	testCases = append(testCases, testCase{
3597		testType: clientTest,
3598		name:     "ClientAuth-ECDHE_PSK",
3599		config: Config{
3600			MaxVersion:   VersionTLS12,
3601			CipherSuites: []uint16{TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA},
3602			PreSharedKey: []byte("secret"),
3603			ClientAuth:   RequireAnyClientCert,
3604		},
3605		flags: []string{
3606			"-cert-file", path.Join(*resourceDir, rsaCertificateFile),
3607			"-key-file", path.Join(*resourceDir, rsaKeyFile),
3608			"-psk", "secret",
3609		},
3610		shouldFail:    true,
3611		expectedError: ":UNEXPECTED_MESSAGE:",
3612	})
3613
3614	// Regression test for a bug where the client CA list, if explicitly
3615	// set to NULL, was mis-encoded.
3616	testCases = append(testCases, testCase{
3617		testType: serverTest,
3618		name:     "Null-Client-CA-List",
3619		config: Config{
3620			MaxVersion:   VersionTLS12,
3621			Certificates: []Certificate{rsaCertificate},
3622			Bugs: ProtocolBugs{
3623				ExpectCertificateReqNames: [][]byte{},
3624			},
3625		},
3626		flags: []string{
3627			"-require-any-client-certificate",
3628			"-use-client-ca-list", "<NULL>",
3629		},
3630	})
3631}
3632
3633func addExtendedMasterSecretTests() {
3634	const expectEMSFlag = "-expect-extended-master-secret"
3635
3636	for _, with := range []bool{false, true} {
3637		prefix := "No"
3638		if with {
3639			prefix = ""
3640		}
3641
3642		for _, isClient := range []bool{false, true} {
3643			suffix := "-Server"
3644			testType := serverTest
3645			if isClient {
3646				suffix = "-Client"
3647				testType = clientTest
3648			}
3649
3650			for _, ver := range tlsVersions {
3651				// In TLS 1.3, the extension is irrelevant and
3652				// always reports as enabled.
3653				var flags []string
3654				if with || ver.version >= VersionTLS13 {
3655					flags = []string{expectEMSFlag}
3656				}
3657
3658				test := testCase{
3659					testType: testType,
3660					name:     prefix + "ExtendedMasterSecret-" + ver.name + suffix,
3661					config: Config{
3662						MinVersion: ver.version,
3663						MaxVersion: ver.version,
3664						Bugs: ProtocolBugs{
3665							NoExtendedMasterSecret:      !with,
3666							RequireExtendedMasterSecret: with,
3667						},
3668					},
3669					tls13Variant: ver.tls13Variant,
3670					flags:        flags,
3671					shouldFail:   ver.version == VersionSSL30 && with,
3672				}
3673				if test.shouldFail {
3674					test.expectedLocalError = "extended master secret required but not supported by peer"
3675				}
3676				testCases = append(testCases, test)
3677			}
3678		}
3679	}
3680
3681	for _, isClient := range []bool{false, true} {
3682		for _, supportedInFirstConnection := range []bool{false, true} {
3683			for _, supportedInResumeConnection := range []bool{false, true} {
3684				boolToWord := func(b bool) string {
3685					if b {
3686						return "Yes"
3687					}
3688					return "No"
3689				}
3690				suffix := boolToWord(supportedInFirstConnection) + "To" + boolToWord(supportedInResumeConnection) + "-"
3691				if isClient {
3692					suffix += "Client"
3693				} else {
3694					suffix += "Server"
3695				}
3696
3697				supportedConfig := Config{
3698					MaxVersion: VersionTLS12,
3699					Bugs: ProtocolBugs{
3700						RequireExtendedMasterSecret: true,
3701					},
3702				}
3703
3704				noSupportConfig := Config{
3705					MaxVersion: VersionTLS12,
3706					Bugs: ProtocolBugs{
3707						NoExtendedMasterSecret: true,
3708					},
3709				}
3710
3711				test := testCase{
3712					name:          "ExtendedMasterSecret-" + suffix,
3713					resumeSession: true,
3714				}
3715
3716				if !isClient {
3717					test.testType = serverTest
3718				}
3719
3720				if supportedInFirstConnection {
3721					test.config = supportedConfig
3722				} else {
3723					test.config = noSupportConfig
3724				}
3725
3726				if supportedInResumeConnection {
3727					test.resumeConfig = &supportedConfig
3728				} else {
3729					test.resumeConfig = &noSupportConfig
3730				}
3731
3732				switch suffix {
3733				case "YesToYes-Client", "YesToYes-Server":
3734					// When a session is resumed, it should
3735					// still be aware that its master
3736					// secret was generated via EMS and
3737					// thus it's safe to use tls-unique.
3738					test.flags = []string{expectEMSFlag}
3739				case "NoToYes-Server":
3740					// If an original connection did not
3741					// contain EMS, but a resumption
3742					// handshake does, then a server should
3743					// not resume the session.
3744					test.expectResumeRejected = true
3745				case "YesToNo-Server":
3746					// Resuming an EMS session without the
3747					// EMS extension should cause the
3748					// server to abort the connection.
3749					test.shouldFail = true
3750					test.expectedError = ":RESUMED_EMS_SESSION_WITHOUT_EMS_EXTENSION:"
3751				case "NoToYes-Client":
3752					// A client should abort a connection
3753					// where the server resumed a non-EMS
3754					// session but echoed the EMS
3755					// extension.
3756					test.shouldFail = true
3757					test.expectedError = ":RESUMED_NON_EMS_SESSION_WITH_EMS_EXTENSION:"
3758				case "YesToNo-Client":
3759					// A client should abort a connection
3760					// where the server didn't echo EMS
3761					// when the session used it.
3762					test.shouldFail = true
3763					test.expectedError = ":RESUMED_EMS_SESSION_WITHOUT_EMS_EXTENSION:"
3764				}
3765
3766				testCases = append(testCases, test)
3767			}
3768		}
3769	}
3770
3771	// Switching EMS on renegotiation is forbidden.
3772	testCases = append(testCases, testCase{
3773		name: "ExtendedMasterSecret-Renego-NoEMS",
3774		config: Config{
3775			MaxVersion: VersionTLS12,
3776			Bugs: ProtocolBugs{
3777				NoExtendedMasterSecret:                true,
3778				NoExtendedMasterSecretOnRenegotiation: true,
3779			},
3780		},
3781		renegotiate: 1,
3782		flags: []string{
3783			"-renegotiate-freely",
3784			"-expect-total-renegotiations", "1",
3785		},
3786	})
3787
3788	testCases = append(testCases, testCase{
3789		name: "ExtendedMasterSecret-Renego-Upgrade",
3790		config: Config{
3791			MaxVersion: VersionTLS12,
3792			Bugs: ProtocolBugs{
3793				NoExtendedMasterSecret: true,
3794			},
3795		},
3796		renegotiate: 1,
3797		flags: []string{
3798			"-renegotiate-freely",
3799			"-expect-total-renegotiations", "1",
3800		},
3801		shouldFail:    true,
3802		expectedError: ":RENEGOTIATION_EMS_MISMATCH:",
3803	})
3804
3805	testCases = append(testCases, testCase{
3806		name: "ExtendedMasterSecret-Renego-Downgrade",
3807		config: Config{
3808			MaxVersion: VersionTLS12,
3809			Bugs: ProtocolBugs{
3810				NoExtendedMasterSecretOnRenegotiation: true,
3811			},
3812		},
3813		renegotiate: 1,
3814		flags: []string{
3815			"-renegotiate-freely",
3816			"-expect-total-renegotiations", "1",
3817		},
3818		shouldFail:    true,
3819		expectedError: ":RENEGOTIATION_EMS_MISMATCH:",
3820	})
3821}
3822
3823type stateMachineTestConfig struct {
3824	protocol            protocol
3825	async               bool
3826	splitHandshake      bool
3827	packHandshakeFlight bool
3828	implicitHandshake   bool
3829}
3830
3831// Adds tests that try to cover the range of the handshake state machine, under
3832// various conditions. Some of these are redundant with other tests, but they
3833// only cover the synchronous case.
3834func addAllStateMachineCoverageTests() {
3835	for _, async := range []bool{false, true} {
3836		for _, protocol := range []protocol{tls, dtls} {
3837			addStateMachineCoverageTests(stateMachineTestConfig{
3838				protocol: protocol,
3839				async:    async,
3840			})
3841			addStateMachineCoverageTests(stateMachineTestConfig{
3842				protocol:          protocol,
3843				async:             async,
3844				implicitHandshake: true,
3845			})
3846			addStateMachineCoverageTests(stateMachineTestConfig{
3847				protocol:       protocol,
3848				async:          async,
3849				splitHandshake: true,
3850			})
3851			if protocol == tls {
3852				addStateMachineCoverageTests(stateMachineTestConfig{
3853					protocol:            protocol,
3854					async:               async,
3855					packHandshakeFlight: true,
3856				})
3857			}
3858		}
3859	}
3860}
3861
3862func addStateMachineCoverageTests(config stateMachineTestConfig) {
3863	var tests []testCase
3864
3865	// Basic handshake, with resumption. Client and server,
3866	// session ID and session ticket.
3867	tests = append(tests, testCase{
3868		name: "Basic-Client",
3869		config: Config{
3870			MaxVersion: VersionTLS12,
3871		},
3872		resumeSession: true,
3873		// Ensure session tickets are used, not session IDs.
3874		noSessionCache: true,
3875	})
3876	tests = append(tests, testCase{
3877		name: "Basic-Client-RenewTicket",
3878		config: Config{
3879			MaxVersion: VersionTLS12,
3880			Bugs: ProtocolBugs{
3881				RenewTicketOnResume: true,
3882			},
3883		},
3884		flags:                []string{"-expect-ticket-renewal"},
3885		resumeSession:        true,
3886		resumeRenewedSession: true,
3887	})
3888	tests = append(tests, testCase{
3889		name: "Basic-Client-NoTicket",
3890		config: Config{
3891			MaxVersion:             VersionTLS12,
3892			SessionTicketsDisabled: true,
3893		},
3894		resumeSession: true,
3895	})
3896	tests = append(tests, testCase{
3897		testType: serverTest,
3898		name:     "Basic-Server",
3899		config: Config{
3900			MaxVersion: VersionTLS12,
3901			Bugs: ProtocolBugs{
3902				RequireSessionTickets: true,
3903			},
3904		},
3905		resumeSession: true,
3906		flags:         []string{"-expect-no-session-id"},
3907	})
3908	tests = append(tests, testCase{
3909		testType: serverTest,
3910		name:     "Basic-Server-NoTickets",
3911		config: Config{
3912			MaxVersion:             VersionTLS12,
3913			SessionTicketsDisabled: true,
3914		},
3915		resumeSession: true,
3916		flags:         []string{"-expect-session-id"},
3917	})
3918	tests = append(tests, testCase{
3919		testType: serverTest,
3920		name:     "Basic-Server-EarlyCallback",
3921		config: Config{
3922			MaxVersion: VersionTLS12,
3923		},
3924		flags:         []string{"-use-early-callback"},
3925		resumeSession: true,
3926	})
3927
3928	// TLS 1.3 basic handshake shapes.
3929	if config.protocol == tls {
3930		tests = append(tests, testCase{
3931			name: "TLS13-1RTT-Client",
3932			config: Config{
3933				MaxVersion: VersionTLS13,
3934				MinVersion: VersionTLS13,
3935			},
3936			resumeSession:        true,
3937			resumeRenewedSession: true,
3938		})
3939
3940		tests = append(tests, testCase{
3941			testType: serverTest,
3942			name:     "TLS13-1RTT-Server",
3943			config: Config{
3944				MaxVersion: VersionTLS13,
3945				MinVersion: VersionTLS13,
3946			},
3947			resumeSession:        true,
3948			resumeRenewedSession: true,
3949			// TLS 1.3 uses tickets, so the session should not be
3950			// cached statefully.
3951			flags: []string{"-expect-no-session-id"},
3952		})
3953
3954		tests = append(tests, testCase{
3955			name: "TLS13-HelloRetryRequest-Client",
3956			config: Config{
3957				MaxVersion: VersionTLS13,
3958				MinVersion: VersionTLS13,
3959				// P-384 requires a HelloRetryRequest against BoringSSL's default
3960				// configuration. Assert this with ExpectMissingKeyShare.
3961				CurvePreferences: []CurveID{CurveP384},
3962				Bugs: ProtocolBugs{
3963					ExpectMissingKeyShare: true,
3964				},
3965			},
3966			// Cover HelloRetryRequest during an ECDHE-PSK resumption.
3967			resumeSession: true,
3968		})
3969
3970		tests = append(tests, testCase{
3971			testType: serverTest,
3972			name:     "TLS13-HelloRetryRequest-Server",
3973			config: Config{
3974				MaxVersion: VersionTLS13,
3975				MinVersion: VersionTLS13,
3976				// Require a HelloRetryRequest for every curve.
3977				DefaultCurves: []CurveID{},
3978			},
3979			// Cover HelloRetryRequest during an ECDHE-PSK resumption.
3980			resumeSession: true,
3981		})
3982
3983		tests = append(tests, testCase{
3984			testType: clientTest,
3985			name:     "TLS13-EarlyData-Client",
3986			config: Config{
3987				MaxVersion:       VersionTLS13,
3988				MinVersion:       VersionTLS13,
3989				MaxEarlyDataSize: 16384,
3990			},
3991			resumeConfig: &Config{
3992				MaxVersion:       VersionTLS13,
3993				MinVersion:       VersionTLS13,
3994				MaxEarlyDataSize: 16384,
3995				Bugs: ProtocolBugs{
3996					ExpectEarlyData: [][]byte{{'h', 'e', 'l', 'l', 'o'}},
3997				},
3998			},
3999			resumeSession: true,
4000			flags: []string{
4001				"-enable-early-data",
4002				"-expect-early-data-info",
4003				"-expect-accept-early-data",
4004				"-on-resume-shim-writes-first",
4005			},
4006		})
4007
4008		tests = append(tests, testCase{
4009			testType: clientTest,
4010			name:     "TLS13Experiment-EarlyData-Client",
4011			config: Config{
4012				MaxVersion:       VersionTLS13,
4013				MinVersion:       VersionTLS13,
4014				TLS13Variant:     TLS13Experiment,
4015				MaxEarlyDataSize: 16384,
4016			},
4017			resumeConfig: &Config{
4018				MaxVersion:       VersionTLS13,
4019				MinVersion:       VersionTLS13,
4020				TLS13Variant:     TLS13Experiment,
4021				MaxEarlyDataSize: 16384,
4022				Bugs: ProtocolBugs{
4023					ExpectEarlyData: [][]byte{{'h', 'e', 'l', 'l', 'o'}},
4024				},
4025			},
4026			resumeSession: true,
4027			flags: []string{
4028				"-enable-early-data",
4029				"-expect-early-data-info",
4030				"-expect-accept-early-data",
4031				"-on-resume-shim-writes-first",
4032				"-tls13-variant", "1",
4033			},
4034		})
4035
4036		tests = append(tests, testCase{
4037			testType: clientTest,
4038			name:     "TLS13RecordTypeExperiment-EarlyData-Client",
4039			config: Config{
4040				MaxVersion:       VersionTLS13,
4041				MinVersion:       VersionTLS13,
4042				TLS13Variant:     TLS13RecordTypeExperiment,
4043				MaxEarlyDataSize: 16384,
4044			},
4045			resumeConfig: &Config{
4046				MaxVersion:       VersionTLS13,
4047				MinVersion:       VersionTLS13,
4048				TLS13Variant:     TLS13RecordTypeExperiment,
4049				MaxEarlyDataSize: 16384,
4050				Bugs: ProtocolBugs{
4051					ExpectEarlyData: [][]byte{{'h', 'e', 'l', 'l', 'o'}},
4052				},
4053			},
4054			resumeSession: true,
4055			flags: []string{
4056				"-enable-early-data",
4057				"-expect-early-data-info",
4058				"-expect-accept-early-data",
4059				"-on-resume-shim-writes-first",
4060				"-tls13-variant", "2",
4061			},
4062		})
4063
4064		tests = append(tests, testCase{
4065			testType: clientTest,
4066			name:     "TLS13-EarlyData-TooMuchData-Client",
4067			config: Config{
4068				MaxVersion:       VersionTLS13,
4069				MinVersion:       VersionTLS13,
4070				MaxEarlyDataSize: 2,
4071			},
4072			resumeConfig: &Config{
4073				MaxVersion:       VersionTLS13,
4074				MinVersion:       VersionTLS13,
4075				MaxEarlyDataSize: 2,
4076				Bugs: ProtocolBugs{
4077					ExpectEarlyData: [][]byte{{'h', 'e'}},
4078				},
4079			},
4080			resumeShimPrefix: "llo",
4081			resumeSession:    true,
4082			flags: []string{
4083				"-enable-early-data",
4084				"-expect-early-data-info",
4085				"-expect-accept-early-data",
4086				"-on-resume-shim-writes-first",
4087			},
4088		})
4089
4090		// Unfinished writes can only be tested when operations are async. EarlyData
4091		// can't be tested as part of an ImplicitHandshake in this case since
4092		// otherwise the early data will be sent as normal data.
4093		if config.async && !config.implicitHandshake {
4094			tests = append(tests, testCase{
4095				testType: clientTest,
4096				name:     "TLS13-EarlyData-UnfinishedWrite-Client",
4097				config: Config{
4098					MaxVersion:       VersionTLS13,
4099					MinVersion:       VersionTLS13,
4100					MaxEarlyDataSize: 16384,
4101				},
4102				resumeConfig: &Config{
4103					MaxVersion:       VersionTLS13,
4104					MinVersion:       VersionTLS13,
4105					MaxEarlyDataSize: 16384,
4106					Bugs: ProtocolBugs{
4107						ExpectLateEarlyData: [][]byte{{'h', 'e', 'l', 'l', 'o'}},
4108					},
4109				},
4110				resumeSession: true,
4111				flags: []string{
4112					"-enable-early-data",
4113					"-expect-early-data-info",
4114					"-expect-accept-early-data",
4115					"-on-resume-read-with-unfinished-write",
4116					"-on-resume-shim-writes-first",
4117				},
4118			})
4119
4120			// Rejected unfinished writes are discarded (from the
4121			// perspective of the calling application) on 0-RTT
4122			// reject.
4123			tests = append(tests, testCase{
4124				testType: clientTest,
4125				name:     "TLS13-EarlyData-RejectUnfinishedWrite-Client",
4126				config: Config{
4127					MaxVersion:       VersionTLS13,
4128					MinVersion:       VersionTLS13,
4129					MaxEarlyDataSize: 16384,
4130				},
4131				resumeConfig: &Config{
4132					MaxVersion:       VersionTLS13,
4133					MinVersion:       VersionTLS13,
4134					MaxEarlyDataSize: 16384,
4135					Bugs: ProtocolBugs{
4136						AlwaysRejectEarlyData: true,
4137					},
4138				},
4139				resumeSession: true,
4140				flags: []string{
4141					"-enable-early-data",
4142					"-expect-early-data-info",
4143					"-expect-reject-early-data",
4144					"-on-resume-read-with-unfinished-write",
4145					"-on-resume-shim-writes-first",
4146				},
4147			})
4148		}
4149
4150		tests = append(tests, testCase{
4151			testType: serverTest,
4152			name:     "TLS13-EarlyData-Server",
4153			config: Config{
4154				MaxVersion: VersionTLS13,
4155				MinVersion: VersionTLS13,
4156				Bugs: ProtocolBugs{
4157					SendEarlyData:           [][]byte{{1, 2, 3, 4}},
4158					ExpectEarlyDataAccepted: true,
4159					ExpectHalfRTTData:       [][]byte{{254, 253, 252, 251}},
4160				},
4161			},
4162			messageCount:  2,
4163			resumeSession: true,
4164			flags: []string{
4165				"-enable-early-data",
4166				"-expect-accept-early-data",
4167			},
4168		})
4169
4170		tests = append(tests, testCase{
4171			testType: serverTest,
4172			name:     "TLS13Experiment-EarlyData-Server",
4173			config: Config{
4174				MaxVersion:   VersionTLS13,
4175				MinVersion:   VersionTLS13,
4176				TLS13Variant: TLS13Experiment,
4177				Bugs: ProtocolBugs{
4178					SendEarlyData:           [][]byte{{1, 2, 3, 4}},
4179					ExpectEarlyDataAccepted: true,
4180					ExpectHalfRTTData:       [][]byte{{254, 253, 252, 251}},
4181				},
4182			},
4183			messageCount:  2,
4184			resumeSession: true,
4185			flags: []string{
4186				"-enable-early-data",
4187				"-expect-accept-early-data",
4188				"-tls13-variant", "1",
4189			},
4190		})
4191
4192		tests = append(tests, testCase{
4193			testType: serverTest,
4194			name:     "TLS13RecordTypeExperiment-EarlyData-Server",
4195			config: Config{
4196				MaxVersion:   VersionTLS13,
4197				MinVersion:   VersionTLS13,
4198				TLS13Variant: TLS13RecordTypeExperiment,
4199				Bugs: ProtocolBugs{
4200					SendEarlyData:           [][]byte{{1, 2, 3, 4}},
4201					ExpectEarlyDataAccepted: true,
4202					ExpectHalfRTTData:       [][]byte{{254, 253, 252, 251}},
4203				},
4204			},
4205			messageCount:  2,
4206			resumeSession: true,
4207			flags: []string{
4208				"-enable-early-data",
4209				"-expect-accept-early-data",
4210				"-tls13-variant", "2",
4211			},
4212		})
4213
4214		tests = append(tests, testCase{
4215			testType: serverTest,
4216			name:     "TLS13-MaxEarlyData-Server",
4217			config: Config{
4218				MaxVersion: VersionTLS13,
4219				MinVersion: VersionTLS13,
4220				Bugs: ProtocolBugs{
4221					SendEarlyData:           [][]byte{bytes.Repeat([]byte{1}, 14336+1)},
4222					ExpectEarlyDataAccepted: true,
4223				},
4224			},
4225			messageCount:  2,
4226			resumeSession: true,
4227			flags: []string{
4228				"-enable-early-data",
4229				"-expect-accept-early-data",
4230			},
4231			shouldFail:    true,
4232			expectedError: ":TOO_MUCH_READ_EARLY_DATA:",
4233		})
4234	}
4235
4236	// TLS client auth.
4237	tests = append(tests, testCase{
4238		testType: clientTest,
4239		name:     "ClientAuth-NoCertificate-Client",
4240		config: Config{
4241			MaxVersion: VersionTLS12,
4242			ClientAuth: RequestClientCert,
4243		},
4244	})
4245	tests = append(tests, testCase{
4246		testType: serverTest,
4247		name:     "ClientAuth-NoCertificate-Server",
4248		config: Config{
4249			MaxVersion: VersionTLS12,
4250		},
4251		// Setting SSL_VERIFY_PEER allows anonymous clients.
4252		flags: []string{"-verify-peer"},
4253	})
4254	if config.protocol == tls {
4255		tests = append(tests, testCase{
4256			testType: clientTest,
4257			name:     "ClientAuth-NoCertificate-Client-SSL3",
4258			config: Config{
4259				MaxVersion: VersionSSL30,
4260				ClientAuth: RequestClientCert,
4261			},
4262		})
4263		tests = append(tests, testCase{
4264			testType: serverTest,
4265			name:     "ClientAuth-NoCertificate-Server-SSL3",
4266			config: Config{
4267				MaxVersion: VersionSSL30,
4268			},
4269			// Setting SSL_VERIFY_PEER allows anonymous clients.
4270			flags: []string{"-verify-peer"},
4271		})
4272		tests = append(tests, testCase{
4273			testType: clientTest,
4274			name:     "ClientAuth-NoCertificate-Client-TLS13",
4275			config: Config{
4276				MaxVersion: VersionTLS13,
4277				ClientAuth: RequestClientCert,
4278			},
4279		})
4280		tests = append(tests, testCase{
4281			testType: serverTest,
4282			name:     "ClientAuth-NoCertificate-Server-TLS13",
4283			config: Config{
4284				MaxVersion: VersionTLS13,
4285			},
4286			// Setting SSL_VERIFY_PEER allows anonymous clients.
4287			flags: []string{"-verify-peer"},
4288		})
4289	}
4290	tests = append(tests, testCase{
4291		testType: clientTest,
4292		name:     "ClientAuth-RSA-Client",
4293		config: Config{
4294			MaxVersion: VersionTLS12,
4295			ClientAuth: RequireAnyClientCert,
4296		},
4297		flags: []string{
4298			"-cert-file", path.Join(*resourceDir, rsaCertificateFile),
4299			"-key-file", path.Join(*resourceDir, rsaKeyFile),
4300		},
4301	})
4302	tests = append(tests, testCase{
4303		testType: clientTest,
4304		name:     "ClientAuth-RSA-Client-TLS13",
4305		config: Config{
4306			MaxVersion: VersionTLS13,
4307			ClientAuth: RequireAnyClientCert,
4308		},
4309		flags: []string{
4310			"-cert-file", path.Join(*resourceDir, rsaCertificateFile),
4311			"-key-file", path.Join(*resourceDir, rsaKeyFile),
4312		},
4313	})
4314	tests = append(tests, testCase{
4315		testType: clientTest,
4316		name:     "ClientAuth-ECDSA-Client",
4317		config: Config{
4318			MaxVersion: VersionTLS12,
4319			ClientAuth: RequireAnyClientCert,
4320		},
4321		flags: []string{
4322			"-cert-file", path.Join(*resourceDir, ecdsaP256CertificateFile),
4323			"-key-file", path.Join(*resourceDir, ecdsaP256KeyFile),
4324		},
4325	})
4326	tests = append(tests, testCase{
4327		testType: clientTest,
4328		name:     "ClientAuth-ECDSA-Client-TLS13",
4329		config: Config{
4330			MaxVersion: VersionTLS13,
4331			ClientAuth: RequireAnyClientCert,
4332		},
4333		flags: []string{
4334			"-cert-file", path.Join(*resourceDir, ecdsaP256CertificateFile),
4335			"-key-file", path.Join(*resourceDir, ecdsaP256KeyFile),
4336		},
4337	})
4338	tests = append(tests, testCase{
4339		testType: clientTest,
4340		name:     "ClientAuth-NoCertificate-OldCallback",
4341		config: Config{
4342			MaxVersion: VersionTLS12,
4343			ClientAuth: RequestClientCert,
4344		},
4345		flags: []string{"-use-old-client-cert-callback"},
4346	})
4347	tests = append(tests, testCase{
4348		testType: clientTest,
4349		name:     "ClientAuth-NoCertificate-OldCallback-TLS13",
4350		config: Config{
4351			MaxVersion: VersionTLS13,
4352			ClientAuth: RequestClientCert,
4353		},
4354		flags: []string{"-use-old-client-cert-callback"},
4355	})
4356	tests = append(tests, testCase{
4357		testType: clientTest,
4358		name:     "ClientAuth-OldCallback",
4359		config: Config{
4360			MaxVersion: VersionTLS12,
4361			ClientAuth: RequireAnyClientCert,
4362		},
4363		flags: []string{
4364			"-cert-file", path.Join(*resourceDir, rsaCertificateFile),
4365			"-key-file", path.Join(*resourceDir, rsaKeyFile),
4366			"-use-old-client-cert-callback",
4367		},
4368	})
4369	tests = append(tests, testCase{
4370		testType: clientTest,
4371		name:     "ClientAuth-OldCallback-TLS13",
4372		config: Config{
4373			MaxVersion: VersionTLS13,
4374			ClientAuth: RequireAnyClientCert,
4375		},
4376		flags: []string{
4377			"-cert-file", path.Join(*resourceDir, rsaCertificateFile),
4378			"-key-file", path.Join(*resourceDir, rsaKeyFile),
4379			"-use-old-client-cert-callback",
4380		},
4381	})
4382	tests = append(tests, testCase{
4383		testType: serverTest,
4384		name:     "ClientAuth-Server",
4385		config: Config{
4386			MaxVersion:   VersionTLS12,
4387			Certificates: []Certificate{rsaCertificate},
4388		},
4389		flags: []string{"-require-any-client-certificate"},
4390	})
4391	tests = append(tests, testCase{
4392		testType: serverTest,
4393		name:     "ClientAuth-Server-TLS13",
4394		config: Config{
4395			MaxVersion:   VersionTLS13,
4396			Certificates: []Certificate{rsaCertificate},
4397		},
4398		flags: []string{"-require-any-client-certificate"},
4399	})
4400
4401	// Test each key exchange on the server side for async keys.
4402	tests = append(tests, testCase{
4403		testType: serverTest,
4404		name:     "Basic-Server-RSA",
4405		config: Config{
4406			MaxVersion:   VersionTLS12,
4407			CipherSuites: []uint16{TLS_RSA_WITH_AES_128_GCM_SHA256},
4408		},
4409		flags: []string{
4410			"-cert-file", path.Join(*resourceDir, rsaCertificateFile),
4411			"-key-file", path.Join(*resourceDir, rsaKeyFile),
4412		},
4413	})
4414	tests = append(tests, testCase{
4415		testType: serverTest,
4416		name:     "Basic-Server-ECDHE-RSA",
4417		config: Config{
4418			MaxVersion:   VersionTLS12,
4419			CipherSuites: []uint16{TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256},
4420		},
4421		flags: []string{
4422			"-cert-file", path.Join(*resourceDir, rsaCertificateFile),
4423			"-key-file", path.Join(*resourceDir, rsaKeyFile),
4424		},
4425	})
4426	tests = append(tests, testCase{
4427		testType: serverTest,
4428		name:     "Basic-Server-ECDHE-ECDSA",
4429		config: Config{
4430			MaxVersion:   VersionTLS12,
4431			CipherSuites: []uint16{TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256},
4432		},
4433		flags: []string{
4434			"-cert-file", path.Join(*resourceDir, ecdsaP256CertificateFile),
4435			"-key-file", path.Join(*resourceDir, ecdsaP256KeyFile),
4436		},
4437	})
4438	tests = append(tests, testCase{
4439		testType: serverTest,
4440		name:     "Basic-Server-Ed25519",
4441		config: Config{
4442			MaxVersion:   VersionTLS12,
4443			CipherSuites: []uint16{TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256},
4444		},
4445		flags: []string{
4446			"-cert-file", path.Join(*resourceDir, ed25519CertificateFile),
4447			"-key-file", path.Join(*resourceDir, ed25519KeyFile),
4448			"-enable-ed25519",
4449		},
4450	})
4451
4452	// No session ticket support; server doesn't send NewSessionTicket.
4453	tests = append(tests, testCase{
4454		name: "SessionTicketsDisabled-Client",
4455		config: Config{
4456			MaxVersion:             VersionTLS12,
4457			SessionTicketsDisabled: true,
4458		},
4459	})
4460	tests = append(tests, testCase{
4461		testType: serverTest,
4462		name:     "SessionTicketsDisabled-Server",
4463		config: Config{
4464			MaxVersion:             VersionTLS12,
4465			SessionTicketsDisabled: true,
4466		},
4467	})
4468
4469	// Skip ServerKeyExchange in PSK key exchange if there's no
4470	// identity hint.
4471	tests = append(tests, testCase{
4472		name: "EmptyPSKHint-Client",
4473		config: Config{
4474			MaxVersion:   VersionTLS12,
4475			CipherSuites: []uint16{TLS_PSK_WITH_AES_128_CBC_SHA},
4476			PreSharedKey: []byte("secret"),
4477		},
4478		flags: []string{"-psk", "secret"},
4479	})
4480	tests = append(tests, testCase{
4481		testType: serverTest,
4482		name:     "EmptyPSKHint-Server",
4483		config: Config{
4484			MaxVersion:   VersionTLS12,
4485			CipherSuites: []uint16{TLS_PSK_WITH_AES_128_CBC_SHA},
4486			PreSharedKey: []byte("secret"),
4487		},
4488		flags: []string{"-psk", "secret"},
4489	})
4490
4491	// OCSP stapling tests.
4492	tests = append(tests, testCase{
4493		testType: clientTest,
4494		name:     "OCSPStapling-Client",
4495		config: Config{
4496			MaxVersion: VersionTLS12,
4497		},
4498		flags: []string{
4499			"-enable-ocsp-stapling",
4500			"-expect-ocsp-response",
4501			base64.StdEncoding.EncodeToString(testOCSPResponse),
4502			"-verify-peer",
4503		},
4504		resumeSession: true,
4505	})
4506	tests = append(tests, testCase{
4507		testType: serverTest,
4508		name:     "OCSPStapling-Server",
4509		config: Config{
4510			MaxVersion: VersionTLS12,
4511		},
4512		expectedOCSPResponse: testOCSPResponse,
4513		flags: []string{
4514			"-ocsp-response",
4515			base64.StdEncoding.EncodeToString(testOCSPResponse),
4516		},
4517		resumeSession: true,
4518	})
4519	tests = append(tests, testCase{
4520		testType: clientTest,
4521		name:     "OCSPStapling-Client-TLS13",
4522		config: Config{
4523			MaxVersion: VersionTLS13,
4524		},
4525		flags: []string{
4526			"-enable-ocsp-stapling",
4527			"-expect-ocsp-response",
4528			base64.StdEncoding.EncodeToString(testOCSPResponse),
4529			"-verify-peer",
4530		},
4531		resumeSession: true,
4532	})
4533	tests = append(tests, testCase{
4534		testType: serverTest,
4535		name:     "OCSPStapling-Server-TLS13",
4536		config: Config{
4537			MaxVersion: VersionTLS13,
4538		},
4539		expectedOCSPResponse: testOCSPResponse,
4540		flags: []string{
4541			"-ocsp-response",
4542			base64.StdEncoding.EncodeToString(testOCSPResponse),
4543		},
4544		resumeSession: true,
4545	})
4546
4547	// Certificate verification tests.
4548	for _, vers := range tlsVersions {
4549		if config.protocol == dtls && !vers.hasDTLS {
4550			continue
4551		}
4552		for _, testType := range []testType{clientTest, serverTest} {
4553			suffix := "-Client"
4554			if testType == serverTest {
4555				suffix = "-Server"
4556			}
4557			suffix += "-" + vers.name
4558
4559			flag := "-verify-peer"
4560			if testType == serverTest {
4561				flag = "-require-any-client-certificate"
4562			}
4563
4564			tests = append(tests, testCase{
4565				testType: testType,
4566				name:     "CertificateVerificationSucceed" + suffix,
4567				config: Config{
4568					MaxVersion:   vers.version,
4569					Certificates: []Certificate{rsaCertificate},
4570				},
4571				tls13Variant: vers.tls13Variant,
4572				flags: []string{
4573					flag,
4574					"-expect-verify-result",
4575				},
4576				resumeSession: true,
4577			})
4578			tests = append(tests, testCase{
4579				testType: testType,
4580				name:     "CertificateVerificationFail" + suffix,
4581				config: Config{
4582					MaxVersion:   vers.version,
4583					Certificates: []Certificate{rsaCertificate},
4584				},
4585				tls13Variant: vers.tls13Variant,
4586				flags: []string{
4587					flag,
4588					"-verify-fail",
4589				},
4590				shouldFail:    true,
4591				expectedError: ":CERTIFICATE_VERIFY_FAILED:",
4592			})
4593		}
4594
4595		// By default, the client is in a soft fail mode where the peer
4596		// certificate is verified but failures are non-fatal.
4597		tests = append(tests, testCase{
4598			testType: clientTest,
4599			name:     "CertificateVerificationSoftFail-" + vers.name,
4600			config: Config{
4601				MaxVersion:   vers.version,
4602				Certificates: []Certificate{rsaCertificate},
4603			},
4604			tls13Variant: vers.tls13Variant,
4605			flags: []string{
4606				"-verify-fail",
4607				"-expect-verify-result",
4608			},
4609			resumeSession: true,
4610		})
4611	}
4612
4613	tests = append(tests, testCase{
4614		name:               "ShimSendAlert",
4615		flags:              []string{"-send-alert"},
4616		shimWritesFirst:    true,
4617		shouldFail:         true,
4618		expectedLocalError: "remote error: decompression failure",
4619	})
4620
4621	if config.protocol == tls {
4622		tests = append(tests, testCase{
4623			name: "Renegotiate-Client",
4624			config: Config{
4625				MaxVersion: VersionTLS12,
4626			},
4627			renegotiate: 1,
4628			flags: []string{
4629				"-renegotiate-freely",
4630				"-expect-total-renegotiations", "1",
4631			},
4632		})
4633
4634		tests = append(tests, testCase{
4635			name: "SendHalfHelloRequest",
4636			config: Config{
4637				MaxVersion: VersionTLS12,
4638				Bugs: ProtocolBugs{
4639					PackHelloRequestWithFinished: config.packHandshakeFlight,
4640				},
4641			},
4642			sendHalfHelloRequest: true,
4643			flags:                []string{"-renegotiate-ignore"},
4644			shouldFail:           true,
4645			expectedError:        ":UNEXPECTED_RECORD:",
4646		})
4647
4648		// NPN on client and server; results in post-handshake message.
4649		tests = append(tests, testCase{
4650			name: "NPN-Client",
4651			config: Config{
4652				MaxVersion: VersionTLS12,
4653				NextProtos: []string{"foo"},
4654			},
4655			flags:                 []string{"-select-next-proto", "foo"},
4656			resumeSession:         true,
4657			expectedNextProto:     "foo",
4658			expectedNextProtoType: npn,
4659		})
4660		tests = append(tests, testCase{
4661			testType: serverTest,
4662			name:     "NPN-Server",
4663			config: Config{
4664				MaxVersion: VersionTLS12,
4665				NextProtos: []string{"bar"},
4666			},
4667			flags: []string{
4668				"-advertise-npn", "\x03foo\x03bar\x03baz",
4669				"-expect-next-proto", "bar",
4670			},
4671			resumeSession:         true,
4672			expectedNextProto:     "bar",
4673			expectedNextProtoType: npn,
4674		})
4675
4676		// TODO(davidben): Add tests for when False Start doesn't trigger.
4677
4678		// Client does False Start and negotiates NPN.
4679		tests = append(tests, testCase{
4680			name: "FalseStart",
4681			config: Config{
4682				MaxVersion:   VersionTLS12,
4683				CipherSuites: []uint16{TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256},
4684				NextProtos:   []string{"foo"},
4685				Bugs: ProtocolBugs{
4686					ExpectFalseStart: true,
4687				},
4688			},
4689			flags: []string{
4690				"-false-start",
4691				"-select-next-proto", "foo",
4692			},
4693			shimWritesFirst: true,
4694			resumeSession:   true,
4695		})
4696
4697		// Client does False Start and negotiates ALPN.
4698		tests = append(tests, testCase{
4699			name: "FalseStart-ALPN",
4700			config: Config{
4701				MaxVersion:   VersionTLS12,
4702				CipherSuites: []uint16{TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256},
4703				NextProtos:   []string{"foo"},
4704				Bugs: ProtocolBugs{
4705					ExpectFalseStart: true,
4706				},
4707			},
4708			flags: []string{
4709				"-false-start",
4710				"-advertise-alpn", "\x03foo",
4711				"-expect-alpn", "foo",
4712			},
4713			shimWritesFirst: true,
4714			resumeSession:   true,
4715		})
4716
4717		// False Start without session tickets.
4718		tests = append(tests, testCase{
4719			name: "FalseStart-SessionTicketsDisabled",
4720			config: Config{
4721				MaxVersion:             VersionTLS12,
4722				CipherSuites:           []uint16{TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256},
4723				NextProtos:             []string{"foo"},
4724				SessionTicketsDisabled: true,
4725				Bugs: ProtocolBugs{
4726					ExpectFalseStart: true,
4727				},
4728			},
4729			flags: []string{
4730				"-false-start",
4731				"-select-next-proto", "foo",
4732			},
4733			shimWritesFirst: true,
4734		})
4735
4736		// Server parses a V2ClientHello.
4737		tests = append(tests, testCase{
4738			testType: serverTest,
4739			name:     "SendV2ClientHello",
4740			config: Config{
4741				// Choose a cipher suite that does not involve
4742				// elliptic curves, so no extensions are
4743				// involved.
4744				MaxVersion:   VersionTLS12,
4745				CipherSuites: []uint16{TLS_RSA_WITH_3DES_EDE_CBC_SHA},
4746				Bugs: ProtocolBugs{
4747					SendV2ClientHello: true,
4748				},
4749			},
4750		})
4751
4752		// Test Channel ID
4753		for _, ver := range tlsVersions {
4754			if ver.version < VersionTLS10 {
4755				continue
4756			}
4757			// Client sends a Channel ID.
4758			tests = append(tests, testCase{
4759				name: "ChannelID-Client-" + ver.name,
4760				config: Config{
4761					MaxVersion:       ver.version,
4762					RequestChannelID: true,
4763				},
4764				tls13Variant:    ver.tls13Variant,
4765				flags:           []string{"-send-channel-id", path.Join(*resourceDir, channelIDKeyFile)},
4766				resumeSession:   true,
4767				expectChannelID: true,
4768			})
4769
4770			// Server accepts a Channel ID.
4771			tests = append(tests, testCase{
4772				testType: serverTest,
4773				name:     "ChannelID-Server-" + ver.name,
4774				config: Config{
4775					MaxVersion: ver.version,
4776					ChannelID:  channelIDKey,
4777				},
4778				tls13Variant: ver.tls13Variant,
4779				flags: []string{
4780					"-expect-channel-id",
4781					base64.StdEncoding.EncodeToString(channelIDBytes),
4782				},
4783				resumeSession:   true,
4784				expectChannelID: true,
4785			})
4786
4787			tests = append(tests, testCase{
4788				testType: serverTest,
4789				name:     "InvalidChannelIDSignature-" + ver.name,
4790				config: Config{
4791					MaxVersion: ver.version,
4792					ChannelID:  channelIDKey,
4793					Bugs: ProtocolBugs{
4794						InvalidChannelIDSignature: true,
4795					},
4796				},
4797				tls13Variant:  ver.tls13Variant,
4798				flags:         []string{"-enable-channel-id"},
4799				shouldFail:    true,
4800				expectedError: ":CHANNEL_ID_SIGNATURE_INVALID:",
4801			})
4802
4803			if ver.version < VersionTLS13 {
4804				// Channel ID requires ECDHE ciphers.
4805				tests = append(tests, testCase{
4806					testType: serverTest,
4807					name:     "ChannelID-NoECDHE-" + ver.name,
4808					config: Config{
4809						MaxVersion:   ver.version,
4810						CipherSuites: []uint16{TLS_RSA_WITH_AES_128_CBC_SHA},
4811						ChannelID:    channelIDKey,
4812					},
4813					expectChannelID: false,
4814					flags:           []string{"-enable-channel-id"},
4815				})
4816
4817				// Sanity-check setting expectChannelID false works.
4818				tests = append(tests, testCase{
4819					testType: serverTest,
4820					name:     "ChannelID-ECDHE-" + ver.name,
4821					config: Config{
4822						MaxVersion:   ver.version,
4823						CipherSuites: []uint16{TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA},
4824						ChannelID:    channelIDKey,
4825					},
4826					expectChannelID:    false,
4827					flags:              []string{"-enable-channel-id"},
4828					shouldFail:         true,
4829					expectedLocalError: "channel ID unexpectedly negotiated",
4830				})
4831			}
4832		}
4833
4834		// Channel ID and NPN at the same time, to ensure their relative
4835		// ordering is correct.
4836		tests = append(tests, testCase{
4837			name: "ChannelID-NPN-Client",
4838			config: Config{
4839				MaxVersion:       VersionTLS12,
4840				RequestChannelID: true,
4841				NextProtos:       []string{"foo"},
4842			},
4843			flags: []string{
4844				"-send-channel-id", path.Join(*resourceDir, channelIDKeyFile),
4845				"-select-next-proto", "foo",
4846			},
4847			resumeSession:         true,
4848			expectChannelID:       true,
4849			expectedNextProto:     "foo",
4850			expectedNextProtoType: npn,
4851		})
4852		tests = append(tests, testCase{
4853			testType: serverTest,
4854			name:     "ChannelID-NPN-Server",
4855			config: Config{
4856				MaxVersion: VersionTLS12,
4857				ChannelID:  channelIDKey,
4858				NextProtos: []string{"bar"},
4859			},
4860			flags: []string{
4861				"-expect-channel-id",
4862				base64.StdEncoding.EncodeToString(channelIDBytes),
4863				"-advertise-npn", "\x03foo\x03bar\x03baz",
4864				"-expect-next-proto", "bar",
4865			},
4866			resumeSession:         true,
4867			expectChannelID:       true,
4868			expectedNextProto:     "bar",
4869			expectedNextProtoType: npn,
4870		})
4871
4872		// Bidirectional shutdown with the runner initiating.
4873		tests = append(tests, testCase{
4874			name: "Shutdown-Runner",
4875			config: Config{
4876				Bugs: ProtocolBugs{
4877					ExpectCloseNotify: true,
4878				},
4879			},
4880			flags: []string{"-check-close-notify"},
4881		})
4882
4883		if !config.implicitHandshake {
4884			// Bidirectional shutdown with the shim initiating. The runner,
4885			// in the meantime, sends garbage before the close_notify which
4886			// the shim must ignore. This test is disabled under implicit
4887			// handshake tests because the shim never reads or writes.
4888			tests = append(tests, testCase{
4889				name: "Shutdown-Shim",
4890				config: Config{
4891					MaxVersion: VersionTLS12,
4892					Bugs: ProtocolBugs{
4893						ExpectCloseNotify: true,
4894					},
4895				},
4896				shimShutsDown:     true,
4897				sendEmptyRecords:  1,
4898				sendWarningAlerts: 1,
4899				flags:             []string{"-check-close-notify"},
4900			})
4901		}
4902	} else {
4903		// TODO(davidben): DTLS 1.3 will want a similar thing for
4904		// HelloRetryRequest.
4905		tests = append(tests, testCase{
4906			name: "SkipHelloVerifyRequest",
4907			config: Config{
4908				MaxVersion: VersionTLS12,
4909				Bugs: ProtocolBugs{
4910					SkipHelloVerifyRequest: true,
4911				},
4912			},
4913		})
4914	}
4915
4916	for _, test := range tests {
4917		test.protocol = config.protocol
4918		if config.protocol == dtls {
4919			test.name += "-DTLS"
4920		}
4921		if config.async {
4922			test.name += "-Async"
4923			test.flags = append(test.flags, "-async")
4924		} else {
4925			test.name += "-Sync"
4926		}
4927		if config.splitHandshake {
4928			test.name += "-SplitHandshakeRecords"
4929			test.config.Bugs.MaxHandshakeRecordLength = 1
4930			if config.protocol == dtls {
4931				test.config.Bugs.MaxPacketLength = 256
4932				test.flags = append(test.flags, "-mtu", "256")
4933			}
4934		}
4935		if config.packHandshakeFlight {
4936			test.name += "-PackHandshakeFlight"
4937			test.config.Bugs.PackHandshakeFlight = true
4938		}
4939		if config.implicitHandshake {
4940			test.name += "-ImplicitHandshake"
4941			test.flags = append(test.flags, "-implicit-handshake")
4942		}
4943		testCases = append(testCases, test)
4944	}
4945}
4946
4947func addDDoSCallbackTests() {
4948	// DDoS callback.
4949	for _, resume := range []bool{false, true} {
4950		suffix := "Resume"
4951		if resume {
4952			suffix = "No" + suffix
4953		}
4954
4955		testCases = append(testCases, testCase{
4956			testType: serverTest,
4957			name:     "Server-DDoS-OK-" + suffix,
4958			config: Config{
4959				MaxVersion: VersionTLS12,
4960			},
4961			flags:         []string{"-install-ddos-callback"},
4962			resumeSession: resume,
4963		})
4964		testCases = append(testCases, testCase{
4965			testType: serverTest,
4966			name:     "Server-DDoS-OK-" + suffix + "-TLS13",
4967			config: Config{
4968				MaxVersion: VersionTLS13,
4969			},
4970			flags:         []string{"-install-ddos-callback"},
4971			resumeSession: resume,
4972		})
4973
4974		failFlag := "-fail-ddos-callback"
4975		if resume {
4976			failFlag = "-fail-second-ddos-callback"
4977		}
4978		testCases = append(testCases, testCase{
4979			testType: serverTest,
4980			name:     "Server-DDoS-Reject-" + suffix,
4981			config: Config{
4982				MaxVersion: VersionTLS12,
4983			},
4984			flags:              []string{"-install-ddos-callback", failFlag},
4985			resumeSession:      resume,
4986			shouldFail:         true,
4987			expectedError:      ":CONNECTION_REJECTED:",
4988			expectedLocalError: "remote error: internal error",
4989		})
4990		testCases = append(testCases, testCase{
4991			testType: serverTest,
4992			name:     "Server-DDoS-Reject-" + suffix + "-TLS13",
4993			config: Config{
4994				MaxVersion: VersionTLS13,
4995			},
4996			flags:              []string{"-install-ddos-callback", failFlag},
4997			resumeSession:      resume,
4998			shouldFail:         true,
4999			expectedError:      ":CONNECTION_REJECTED:",
5000			expectedLocalError: "remote error: internal error",
5001		})
5002	}
5003}
5004
5005func addVersionNegotiationTests() {
5006	for _, protocol := range []protocol{tls, dtls} {
5007		for _, shimVers := range allVersions(protocol) {
5008			// Assemble flags to disable all newer versions on the shim.
5009			var flags []string
5010			for _, vers := range allVersions(protocol) {
5011				if vers.version > shimVers.version {
5012					flags = append(flags, vers.excludeFlag)
5013				}
5014			}
5015
5016			flags2 := []string{"-max-version", shimVers.shimFlag(protocol)}
5017
5018			if shimVers.tls13Variant != 0 {
5019				flags = append(flags, "-tls13-variant", strconv.Itoa(shimVers.tls13Variant))
5020				flags2 = append(flags2, "-tls13-variant", strconv.Itoa(shimVers.tls13Variant))
5021			}
5022
5023			// Test configuring the runner's maximum version.
5024			for _, runnerVers := range allVersions(protocol) {
5025				expectedVersion := shimVers.version
5026				if runnerVers.version < shimVers.version {
5027					expectedVersion = runnerVers.version
5028				}
5029				// When running and shim have different TLS 1.3 variants enabled,
5030				// shim clients are expected to fall back to TLS 1.2, while shim
5031				// servers support both variants when enabled when the experiment is
5032				// enabled.
5033				expectedServerVersion := expectedVersion
5034				expectedClientVersion := expectedVersion
5035				if expectedVersion == VersionTLS13 && runnerVers.tls13Variant != shimVers.tls13Variant {
5036					expectedClientVersion = VersionTLS12
5037					expectedServerVersion = VersionTLS12
5038					if shimVers.tls13Variant != TLS13Default {
5039						expectedServerVersion = VersionTLS13
5040					}
5041				}
5042
5043				suffix := shimVers.name + "-" + runnerVers.name
5044				if protocol == dtls {
5045					suffix += "-DTLS"
5046				}
5047
5048				// Determine the expected initial record-layer versions.
5049				clientVers := shimVers.version
5050				if clientVers > VersionTLS10 {
5051					clientVers = VersionTLS10
5052				}
5053				clientVers = recordVersionToWire(clientVers, protocol)
5054				serverVers := expectedServerVersion
5055				if expectedServerVersion >= VersionTLS13 {
5056					serverVers = VersionTLS10
5057				}
5058				serverVers = recordVersionToWire(serverVers, protocol)
5059
5060				testCases = append(testCases, testCase{
5061					protocol: protocol,
5062					testType: clientTest,
5063					name:     "VersionNegotiation-Client-" + suffix,
5064					config: Config{
5065						MaxVersion:   runnerVers.version,
5066						TLS13Variant: runnerVers.tls13Variant,
5067						Bugs: ProtocolBugs{
5068							ExpectInitialRecordVersion: clientVers,
5069						},
5070					},
5071					flags:           flags,
5072					expectedVersion: expectedClientVersion,
5073				})
5074				testCases = append(testCases, testCase{
5075					protocol: protocol,
5076					testType: clientTest,
5077					name:     "VersionNegotiation-Client2-" + suffix,
5078					config: Config{
5079						MaxVersion:   runnerVers.version,
5080						TLS13Variant: runnerVers.tls13Variant,
5081						Bugs: ProtocolBugs{
5082							ExpectInitialRecordVersion: clientVers,
5083						},
5084					},
5085					flags:           flags2,
5086					expectedVersion: expectedClientVersion,
5087				})
5088
5089				testCases = append(testCases, testCase{
5090					protocol: protocol,
5091					testType: serverTest,
5092					name:     "VersionNegotiation-Server-" + suffix,
5093					config: Config{
5094						MaxVersion:   runnerVers.version,
5095						TLS13Variant: runnerVers.tls13Variant,
5096						Bugs: ProtocolBugs{
5097							ExpectInitialRecordVersion: serverVers,
5098						},
5099					},
5100					flags:           flags,
5101					expectedVersion: expectedServerVersion,
5102				})
5103				testCases = append(testCases, testCase{
5104					protocol: protocol,
5105					testType: serverTest,
5106					name:     "VersionNegotiation-Server2-" + suffix,
5107					config: Config{
5108						MaxVersion:   runnerVers.version,
5109						TLS13Variant: runnerVers.tls13Variant,
5110						Bugs: ProtocolBugs{
5111							ExpectInitialRecordVersion: serverVers,
5112						},
5113					},
5114					flags:           flags2,
5115					expectedVersion: expectedServerVersion,
5116				})
5117			}
5118		}
5119	}
5120
5121	// Test the version extension at all versions.
5122	for _, vers := range tlsVersions {
5123		protocols := []protocol{tls}
5124		if vers.hasDTLS {
5125			protocols = append(protocols, dtls)
5126		}
5127		for _, protocol := range protocols {
5128			suffix := vers.name
5129			if protocol == dtls {
5130				suffix += "-DTLS"
5131			}
5132
5133			testCases = append(testCases, testCase{
5134				protocol: protocol,
5135				testType: serverTest,
5136				name:     "VersionNegotiationExtension-" + suffix,
5137				config: Config{
5138					TLS13Variant: vers.tls13Variant,
5139					Bugs: ProtocolBugs{
5140						SendSupportedVersions: []uint16{0x1111, vers.wire(protocol), 0x2222},
5141					},
5142				},
5143				expectedVersion: vers.version,
5144				flags:           []string{"-tls13-variant", strconv.Itoa(vers.tls13Variant)},
5145			})
5146		}
5147	}
5148
5149	// If all versions are unknown, negotiation fails.
5150	testCases = append(testCases, testCase{
5151		testType: serverTest,
5152		name:     "NoSupportedVersions",
5153		config: Config{
5154			Bugs: ProtocolBugs{
5155				SendSupportedVersions: []uint16{0x1111},
5156			},
5157		},
5158		shouldFail:    true,
5159		expectedError: ":UNSUPPORTED_PROTOCOL:",
5160	})
5161	testCases = append(testCases, testCase{
5162		protocol: dtls,
5163		testType: serverTest,
5164		name:     "NoSupportedVersions-DTLS",
5165		config: Config{
5166			Bugs: ProtocolBugs{
5167				SendSupportedVersions: []uint16{0x1111},
5168			},
5169		},
5170		shouldFail:    true,
5171		expectedError: ":UNSUPPORTED_PROTOCOL:",
5172	})
5173
5174	testCases = append(testCases, testCase{
5175		testType: serverTest,
5176		name:     "ClientHelloVersionTooHigh",
5177		config: Config{
5178			MaxVersion: VersionTLS13,
5179			Bugs: ProtocolBugs{
5180				SendClientVersion:     0x0304,
5181				OmitSupportedVersions: true,
5182			},
5183		},
5184		expectedVersion: VersionTLS12,
5185	})
5186
5187	testCases = append(testCases, testCase{
5188		testType: serverTest,
5189		name:     "ConflictingVersionNegotiation",
5190		config: Config{
5191			Bugs: ProtocolBugs{
5192				SendClientVersion:     VersionTLS12,
5193				SendSupportedVersions: []uint16{VersionTLS11},
5194			},
5195		},
5196		// The extension takes precedence over the ClientHello version.
5197		expectedVersion: VersionTLS11,
5198	})
5199
5200	testCases = append(testCases, testCase{
5201		testType: serverTest,
5202		name:     "ConflictingVersionNegotiation-2",
5203		config: Config{
5204			Bugs: ProtocolBugs{
5205				SendClientVersion:     VersionTLS11,
5206				SendSupportedVersions: []uint16{VersionTLS12},
5207			},
5208		},
5209		// The extension takes precedence over the ClientHello version.
5210		expectedVersion: VersionTLS12,
5211	})
5212
5213	testCases = append(testCases, testCase{
5214		testType: serverTest,
5215		name:     "RejectFinalTLS13",
5216		config: Config{
5217			Bugs: ProtocolBugs{
5218				SendSupportedVersions: []uint16{VersionTLS13, VersionTLS12},
5219			},
5220		},
5221		// We currently implement a draft TLS 1.3 version. Ensure that
5222		// the true TLS 1.3 value is ignored for now.
5223		expectedVersion: VersionTLS12,
5224	})
5225
5226	// Test that TLS 1.2 isn't negotiated by the supported_versions extension in
5227	// the ServerHello.
5228	testCases = append(testCases, testCase{
5229		testType: clientTest,
5230		name:     "SupportedVersionSelection-TLS12",
5231		config: Config{
5232			MaxVersion: VersionTLS12,
5233			Bugs: ProtocolBugs{
5234				SendServerSupportedExtensionVersion: VersionTLS12,
5235			},
5236		},
5237		shouldFail:    true,
5238		expectedError: ":UNEXPECTED_EXTENSION:",
5239	})
5240
5241	// Test that the non-experimental TLS 1.3 isn't negotiated by the
5242	// supported_versions extension in the ServerHello.
5243	testCases = append(testCases, testCase{
5244		testType: clientTest,
5245		name:     "SupportedVersionSelection-TLS13",
5246		config: Config{
5247			MaxVersion: VersionTLS13,
5248			Bugs: ProtocolBugs{
5249				SendServerSupportedExtensionVersion: tls13DraftVersion,
5250			},
5251		},
5252		shouldFail:    true,
5253		expectedError: ":UNEXPECTED_EXTENSION:",
5254	})
5255
5256	// Test that the maximum version is selected regardless of the
5257	// client-sent order.
5258	testCases = append(testCases, testCase{
5259		testType: serverTest,
5260		name:     "IgnoreClientVersionOrder",
5261		config: Config{
5262			Bugs: ProtocolBugs{
5263				SendSupportedVersions: []uint16{VersionTLS12, tls13DraftVersion},
5264			},
5265		},
5266		expectedVersion: VersionTLS13,
5267	})
5268
5269	// Test for version tolerance.
5270	testCases = append(testCases, testCase{
5271		testType: serverTest,
5272		name:     "MinorVersionTolerance",
5273		config: Config{
5274			Bugs: ProtocolBugs{
5275				SendClientVersion:     0x03ff,
5276				OmitSupportedVersions: true,
5277			},
5278		},
5279		expectedVersion: VersionTLS12,
5280	})
5281	testCases = append(testCases, testCase{
5282		testType: serverTest,
5283		name:     "MajorVersionTolerance",
5284		config: Config{
5285			Bugs: ProtocolBugs{
5286				SendClientVersion:     0x0400,
5287				OmitSupportedVersions: true,
5288			},
5289		},
5290		// TLS 1.3 must be negotiated with the supported_versions
5291		// extension, not ClientHello.version.
5292		expectedVersion: VersionTLS12,
5293	})
5294	testCases = append(testCases, testCase{
5295		testType: serverTest,
5296		name:     "VersionTolerance-TLS13",
5297		config: Config{
5298			Bugs: ProtocolBugs{
5299				// Although TLS 1.3 does not use
5300				// ClientHello.version, it still tolerates high
5301				// values there.
5302				SendClientVersion: 0x0400,
5303			},
5304		},
5305		expectedVersion: VersionTLS13,
5306	})
5307
5308	testCases = append(testCases, testCase{
5309		protocol: dtls,
5310		testType: serverTest,
5311		name:     "MinorVersionTolerance-DTLS",
5312		config: Config{
5313			Bugs: ProtocolBugs{
5314				SendClientVersion:     0xfe00,
5315				OmitSupportedVersions: true,
5316			},
5317		},
5318		expectedVersion: VersionTLS12,
5319	})
5320	testCases = append(testCases, testCase{
5321		protocol: dtls,
5322		testType: serverTest,
5323		name:     "MajorVersionTolerance-DTLS",
5324		config: Config{
5325			Bugs: ProtocolBugs{
5326				SendClientVersion:     0xfdff,
5327				OmitSupportedVersions: true,
5328			},
5329		},
5330		expectedVersion: VersionTLS12,
5331	})
5332
5333	// Test that versions below 3.0 are rejected.
5334	testCases = append(testCases, testCase{
5335		testType: serverTest,
5336		name:     "VersionTooLow",
5337		config: Config{
5338			Bugs: ProtocolBugs{
5339				SendClientVersion:     0x0200,
5340				OmitSupportedVersions: true,
5341			},
5342		},
5343		shouldFail:    true,
5344		expectedError: ":UNSUPPORTED_PROTOCOL:",
5345	})
5346	testCases = append(testCases, testCase{
5347		protocol: dtls,
5348		testType: serverTest,
5349		name:     "VersionTooLow-DTLS",
5350		config: Config{
5351			Bugs: ProtocolBugs{
5352				SendClientVersion: 0xffff,
5353			},
5354		},
5355		shouldFail:    true,
5356		expectedError: ":UNSUPPORTED_PROTOCOL:",
5357	})
5358
5359	testCases = append(testCases, testCase{
5360		name: "ServerBogusVersion",
5361		config: Config{
5362			Bugs: ProtocolBugs{
5363				SendServerHelloVersion: 0x1234,
5364			},
5365		},
5366		shouldFail:    true,
5367		expectedError: ":UNSUPPORTED_PROTOCOL:",
5368	})
5369
5370	// Test TLS 1.3's downgrade signal.
5371	testCases = append(testCases, testCase{
5372		name: "Downgrade-TLS12-Client",
5373		config: Config{
5374			Bugs: ProtocolBugs{
5375				NegotiateVersion: VersionTLS12,
5376			},
5377		},
5378		expectedVersion: VersionTLS12,
5379		// TODO(davidben): This test should fail once TLS 1.3 is final
5380		// and the fallback signal restored.
5381	})
5382	testCases = append(testCases, testCase{
5383		testType: serverTest,
5384		name:     "Downgrade-TLS12-Server",
5385		config: Config{
5386			Bugs: ProtocolBugs{
5387				SendSupportedVersions: []uint16{VersionTLS12},
5388			},
5389		},
5390		expectedVersion: VersionTLS12,
5391		// TODO(davidben): This test should fail once TLS 1.3 is final
5392		// and the fallback signal restored.
5393	})
5394}
5395
5396func addMinimumVersionTests() {
5397	for _, protocol := range []protocol{tls, dtls} {
5398		for _, shimVers := range allVersions(protocol) {
5399			// Assemble flags to disable all older versions on the shim.
5400			var flags []string
5401			for _, vers := range allVersions(protocol) {
5402				if vers.version < shimVers.version {
5403					flags = append(flags, vers.excludeFlag)
5404				}
5405			}
5406
5407			flags2 := []string{"-min-version", shimVers.shimFlag(protocol)}
5408
5409			if shimVers.tls13Variant != 0 {
5410				flags = append(flags, "-tls13-variant", strconv.Itoa(shimVers.tls13Variant))
5411				flags2 = append(flags2, "-tls13-variant", strconv.Itoa(shimVers.tls13Variant))
5412			}
5413
5414			for _, runnerVers := range allVersions(protocol) {
5415				// Different TLS 1.3 variants are incompatible with each other and don't
5416				// produce consistent minimum versions.
5417				//
5418				// TODO(davidben): Fold these tests (the main value is in the
5419				// NegotiateVersion bug) into addVersionNegotiationTests and test based
5420				// on intended shim behavior, not the shim + runner combination.
5421				if shimVers.tls13Variant != runnerVers.tls13Variant {
5422					continue
5423				}
5424
5425				suffix := shimVers.name + "-" + runnerVers.name
5426				if protocol == dtls {
5427					suffix += "-DTLS"
5428				}
5429
5430				var expectedVersion uint16
5431				var shouldFail bool
5432				var expectedError, expectedLocalError string
5433				if runnerVers.version >= shimVers.version {
5434					expectedVersion = runnerVers.version
5435				} else {
5436					shouldFail = true
5437					expectedError = ":UNSUPPORTED_PROTOCOL:"
5438					expectedLocalError = "remote error: protocol version not supported"
5439				}
5440
5441				testCases = append(testCases, testCase{
5442					protocol: protocol,
5443					testType: clientTest,
5444					name:     "MinimumVersion-Client-" + suffix,
5445					config: Config{
5446						MaxVersion:   runnerVers.version,
5447						TLS13Variant: runnerVers.tls13Variant,
5448						Bugs: ProtocolBugs{
5449							// Ensure the server does not decline to
5450							// select a version (versions extension) or
5451							// cipher (some ciphers depend on versions).
5452							NegotiateVersion:            runnerVers.wire(protocol),
5453							IgnorePeerCipherPreferences: shouldFail,
5454						},
5455					},
5456					flags:              flags,
5457					expectedVersion:    expectedVersion,
5458					shouldFail:         shouldFail,
5459					expectedError:      expectedError,
5460					expectedLocalError: expectedLocalError,
5461				})
5462				testCases = append(testCases, testCase{
5463					protocol: protocol,
5464					testType: clientTest,
5465					name:     "MinimumVersion-Client2-" + suffix,
5466					config: Config{
5467						MaxVersion:   runnerVers.version,
5468						TLS13Variant: runnerVers.tls13Variant,
5469						Bugs: ProtocolBugs{
5470							// Ensure the server does not decline to
5471							// select a version (versions extension) or
5472							// cipher (some ciphers depend on versions).
5473							NegotiateVersion:            runnerVers.wire(protocol),
5474							IgnorePeerCipherPreferences: shouldFail,
5475						},
5476					},
5477					flags:              flags2,
5478					expectedVersion:    expectedVersion,
5479					shouldFail:         shouldFail,
5480					expectedError:      expectedError,
5481					expectedLocalError: expectedLocalError,
5482				})
5483
5484				testCases = append(testCases, testCase{
5485					protocol: protocol,
5486					testType: serverTest,
5487					name:     "MinimumVersion-Server-" + suffix,
5488					config: Config{
5489						MaxVersion:   runnerVers.version,
5490						TLS13Variant: runnerVers.tls13Variant,
5491					},
5492					flags:              flags,
5493					expectedVersion:    expectedVersion,
5494					shouldFail:         shouldFail,
5495					expectedError:      expectedError,
5496					expectedLocalError: expectedLocalError,
5497				})
5498				testCases = append(testCases, testCase{
5499					protocol: protocol,
5500					testType: serverTest,
5501					name:     "MinimumVersion-Server2-" + suffix,
5502					config: Config{
5503						MaxVersion:   runnerVers.version,
5504						TLS13Variant: runnerVers.tls13Variant,
5505					},
5506					flags:              flags2,
5507					expectedVersion:    expectedVersion,
5508					shouldFail:         shouldFail,
5509					expectedError:      expectedError,
5510					expectedLocalError: expectedLocalError,
5511				})
5512			}
5513		}
5514	}
5515}
5516
5517func addExtensionTests() {
5518	// TODO(davidben): Extensions, where applicable, all move their server
5519	// halves to EncryptedExtensions in TLS 1.3. Duplicate each of these
5520	// tests for both. Also test interaction with 0-RTT when implemented.
5521
5522	// Repeat extensions tests all versions except SSL 3.0.
5523	for _, ver := range tlsVersions {
5524		if ver.version == VersionSSL30 {
5525			continue
5526		}
5527
5528		// Test that duplicate extensions are rejected.
5529		testCases = append(testCases, testCase{
5530			testType: clientTest,
5531			name:     "DuplicateExtensionClient-" + ver.name,
5532			config: Config{
5533				MaxVersion: ver.version,
5534				Bugs: ProtocolBugs{
5535					DuplicateExtension: true,
5536				},
5537			},
5538			tls13Variant:       ver.tls13Variant,
5539			shouldFail:         true,
5540			expectedLocalError: "remote error: error decoding message",
5541		})
5542		testCases = append(testCases, testCase{
5543			testType: serverTest,
5544			name:     "DuplicateExtensionServer-" + ver.name,
5545			config: Config{
5546				MaxVersion: ver.version,
5547				Bugs: ProtocolBugs{
5548					DuplicateExtension: true,
5549				},
5550			},
5551			tls13Variant:       ver.tls13Variant,
5552			shouldFail:         true,
5553			expectedLocalError: "remote error: error decoding message",
5554		})
5555
5556		// Test SNI.
5557		testCases = append(testCases, testCase{
5558			testType: clientTest,
5559			name:     "ServerNameExtensionClient-" + ver.name,
5560			config: Config{
5561				MaxVersion: ver.version,
5562				Bugs: ProtocolBugs{
5563					ExpectServerName: "example.com",
5564				},
5565			},
5566			tls13Variant: ver.tls13Variant,
5567			flags:        []string{"-host-name", "example.com"},
5568		})
5569		testCases = append(testCases, testCase{
5570			testType: clientTest,
5571			name:     "ServerNameExtensionClientMismatch-" + ver.name,
5572			config: Config{
5573				MaxVersion: ver.version,
5574				Bugs: ProtocolBugs{
5575					ExpectServerName: "mismatch.com",
5576				},
5577			},
5578			flags:              []string{"-host-name", "example.com"},
5579			tls13Variant:       ver.tls13Variant,
5580			shouldFail:         true,
5581			expectedLocalError: "tls: unexpected server name",
5582		})
5583		testCases = append(testCases, testCase{
5584			testType: clientTest,
5585			name:     "ServerNameExtensionClientMissing-" + ver.name,
5586			config: Config{
5587				MaxVersion: ver.version,
5588				Bugs: ProtocolBugs{
5589					ExpectServerName: "missing.com",
5590				},
5591			},
5592			tls13Variant:       ver.tls13Variant,
5593			shouldFail:         true,
5594			expectedLocalError: "tls: unexpected server name",
5595		})
5596		testCases = append(testCases, testCase{
5597			testType: clientTest,
5598			name:     "TolerateServerNameAck-" + ver.name,
5599			config: Config{
5600				MaxVersion: ver.version,
5601				Bugs: ProtocolBugs{
5602					SendServerNameAck: true,
5603				},
5604			},
5605			tls13Variant:  ver.tls13Variant,
5606			flags:         []string{"-host-name", "example.com"},
5607			resumeSession: true,
5608		})
5609		testCases = append(testCases, testCase{
5610			testType: clientTest,
5611			name:     "UnsolicitedServerNameAck-" + ver.name,
5612			config: Config{
5613				MaxVersion: ver.version,
5614				Bugs: ProtocolBugs{
5615					SendServerNameAck: true,
5616				},
5617			},
5618			tls13Variant:       ver.tls13Variant,
5619			shouldFail:         true,
5620			expectedError:      ":UNEXPECTED_EXTENSION:",
5621			expectedLocalError: "remote error: unsupported extension",
5622		})
5623		testCases = append(testCases, testCase{
5624			testType: serverTest,
5625			name:     "ServerNameExtensionServer-" + ver.name,
5626			config: Config{
5627				MaxVersion: ver.version,
5628				ServerName: "example.com",
5629			},
5630			tls13Variant:  ver.tls13Variant,
5631			flags:         []string{"-expect-server-name", "example.com"},
5632			resumeSession: true,
5633		})
5634
5635		// Test ALPN.
5636		testCases = append(testCases, testCase{
5637			testType: clientTest,
5638			name:     "ALPNClient-" + ver.name,
5639			config: Config{
5640				MaxVersion: ver.version,
5641				NextProtos: []string{"foo"},
5642			},
5643			flags: []string{
5644				"-advertise-alpn", "\x03foo\x03bar\x03baz",
5645				"-expect-alpn", "foo",
5646			},
5647			tls13Variant:          ver.tls13Variant,
5648			expectedNextProto:     "foo",
5649			expectedNextProtoType: alpn,
5650			resumeSession:         true,
5651		})
5652		testCases = append(testCases, testCase{
5653			testType: clientTest,
5654			name:     "ALPNClient-RejectUnknown-" + ver.name,
5655			config: Config{
5656				MaxVersion: ver.version,
5657				Bugs: ProtocolBugs{
5658					SendALPN: "baz",
5659				},
5660			},
5661			flags: []string{
5662				"-advertise-alpn", "\x03foo\x03bar",
5663			},
5664			tls13Variant:       ver.tls13Variant,
5665			shouldFail:         true,
5666			expectedError:      ":INVALID_ALPN_PROTOCOL:",
5667			expectedLocalError: "remote error: illegal parameter",
5668		})
5669		testCases = append(testCases, testCase{
5670			testType: clientTest,
5671			name:     "ALPNClient-AllowUnknown-" + ver.name,
5672			config: Config{
5673				MaxVersion: ver.version,
5674				Bugs: ProtocolBugs{
5675					SendALPN: "baz",
5676				},
5677			},
5678			flags: []string{
5679				"-advertise-alpn", "\x03foo\x03bar",
5680				"-allow-unknown-alpn-protos",
5681				"-expect-alpn", "baz",
5682			},
5683			tls13Variant: ver.tls13Variant,
5684		})
5685		testCases = append(testCases, testCase{
5686			testType: serverTest,
5687			name:     "ALPNServer-" + ver.name,
5688			config: Config{
5689				MaxVersion: ver.version,
5690				NextProtos: []string{"foo", "bar", "baz"},
5691			},
5692			flags: []string{
5693				"-expect-advertised-alpn", "\x03foo\x03bar\x03baz",
5694				"-select-alpn", "foo",
5695			},
5696			tls13Variant:          ver.tls13Variant,
5697			expectedNextProto:     "foo",
5698			expectedNextProtoType: alpn,
5699			resumeSession:         true,
5700		})
5701		testCases = append(testCases, testCase{
5702			testType: serverTest,
5703			name:     "ALPNServer-Decline-" + ver.name,
5704			config: Config{
5705				MaxVersion: ver.version,
5706				NextProtos: []string{"foo", "bar", "baz"},
5707			},
5708			flags:             []string{"-decline-alpn"},
5709			tls13Variant:      ver.tls13Variant,
5710			expectNoNextProto: true,
5711			resumeSession:     true,
5712		})
5713
5714		// Test ALPN in async mode as well to ensure that extensions callbacks are only
5715		// called once.
5716		testCases = append(testCases, testCase{
5717			testType: serverTest,
5718			name:     "ALPNServer-Async-" + ver.name,
5719			config: Config{
5720				MaxVersion: ver.version,
5721				NextProtos: []string{"foo", "bar", "baz"},
5722				// Prior to TLS 1.3, exercise the asynchronous session callback.
5723				SessionTicketsDisabled: ver.version < VersionTLS13,
5724			},
5725			flags: []string{
5726				"-expect-advertised-alpn", "\x03foo\x03bar\x03baz",
5727				"-select-alpn", "foo",
5728				"-async",
5729			},
5730			tls13Variant:          ver.tls13Variant,
5731			expectedNextProto:     "foo",
5732			expectedNextProtoType: alpn,
5733			resumeSession:         true,
5734		})
5735
5736		var emptyString string
5737		testCases = append(testCases, testCase{
5738			testType: clientTest,
5739			name:     "ALPNClient-EmptyProtocolName-" + ver.name,
5740			config: Config{
5741				MaxVersion: ver.version,
5742				NextProtos: []string{""},
5743				Bugs: ProtocolBugs{
5744					// A server returning an empty ALPN protocol
5745					// should be rejected.
5746					ALPNProtocol: &emptyString,
5747				},
5748			},
5749			flags: []string{
5750				"-advertise-alpn", "\x03foo",
5751			},
5752			tls13Variant:  ver.tls13Variant,
5753			shouldFail:    true,
5754			expectedError: ":PARSE_TLSEXT:",
5755		})
5756		testCases = append(testCases, testCase{
5757			testType: serverTest,
5758			name:     "ALPNServer-EmptyProtocolName-" + ver.name,
5759			config: Config{
5760				MaxVersion: ver.version,
5761				// A ClientHello containing an empty ALPN protocol
5762				// should be rejected.
5763				NextProtos: []string{"foo", "", "baz"},
5764			},
5765			flags: []string{
5766				"-select-alpn", "foo",
5767			},
5768			tls13Variant:  ver.tls13Variant,
5769			shouldFail:    true,
5770			expectedError: ":PARSE_TLSEXT:",
5771		})
5772
5773		// Test NPN and the interaction with ALPN.
5774		if ver.version < VersionTLS13 {
5775			// Test that the server prefers ALPN over NPN.
5776			testCases = append(testCases, testCase{
5777				testType: serverTest,
5778				name:     "ALPNServer-Preferred-" + ver.name,
5779				config: Config{
5780					MaxVersion: ver.version,
5781					NextProtos: []string{"foo", "bar", "baz"},
5782				},
5783				flags: []string{
5784					"-expect-advertised-alpn", "\x03foo\x03bar\x03baz",
5785					"-select-alpn", "foo",
5786					"-advertise-npn", "\x03foo\x03bar\x03baz",
5787				},
5788				tls13Variant:          ver.tls13Variant,
5789				expectedNextProto:     "foo",
5790				expectedNextProtoType: alpn,
5791				resumeSession:         true,
5792			})
5793			testCases = append(testCases, testCase{
5794				testType: serverTest,
5795				name:     "ALPNServer-Preferred-Swapped-" + ver.name,
5796				config: Config{
5797					MaxVersion: ver.version,
5798					NextProtos: []string{"foo", "bar", "baz"},
5799					Bugs: ProtocolBugs{
5800						SwapNPNAndALPN: true,
5801					},
5802				},
5803				flags: []string{
5804					"-expect-advertised-alpn", "\x03foo\x03bar\x03baz",
5805					"-select-alpn", "foo",
5806					"-advertise-npn", "\x03foo\x03bar\x03baz",
5807				},
5808				tls13Variant:          ver.tls13Variant,
5809				expectedNextProto:     "foo",
5810				expectedNextProtoType: alpn,
5811				resumeSession:         true,
5812			})
5813
5814			// Test that negotiating both NPN and ALPN is forbidden.
5815			testCases = append(testCases, testCase{
5816				name: "NegotiateALPNAndNPN-" + ver.name,
5817				config: Config{
5818					MaxVersion: ver.version,
5819					NextProtos: []string{"foo", "bar", "baz"},
5820					Bugs: ProtocolBugs{
5821						NegotiateALPNAndNPN: true,
5822					},
5823				},
5824				flags: []string{
5825					"-advertise-alpn", "\x03foo",
5826					"-select-next-proto", "foo",
5827				},
5828				tls13Variant:  ver.tls13Variant,
5829				shouldFail:    true,
5830				expectedError: ":NEGOTIATED_BOTH_NPN_AND_ALPN:",
5831			})
5832			testCases = append(testCases, testCase{
5833				name: "NegotiateALPNAndNPN-Swapped-" + ver.name,
5834				config: Config{
5835					MaxVersion: ver.version,
5836					NextProtos: []string{"foo", "bar", "baz"},
5837					Bugs: ProtocolBugs{
5838						NegotiateALPNAndNPN: true,
5839						SwapNPNAndALPN:      true,
5840					},
5841				},
5842				flags: []string{
5843					"-advertise-alpn", "\x03foo",
5844					"-select-next-proto", "foo",
5845				},
5846				tls13Variant:  ver.tls13Variant,
5847				shouldFail:    true,
5848				expectedError: ":NEGOTIATED_BOTH_NPN_AND_ALPN:",
5849			})
5850		}
5851
5852		// Test ticket behavior.
5853
5854		// Resume with a corrupt ticket.
5855		testCases = append(testCases, testCase{
5856			testType: serverTest,
5857			name:     "CorruptTicket-" + ver.name,
5858			config: Config{
5859				MaxVersion: ver.version,
5860				Bugs: ProtocolBugs{
5861					FilterTicket: func(in []byte) ([]byte, error) {
5862						in[len(in)-1] ^= 1
5863						return in, nil
5864					},
5865				},
5866			},
5867			tls13Variant:         ver.tls13Variant,
5868			resumeSession:        true,
5869			expectResumeRejected: true,
5870		})
5871		// Test the ticket callback, with and without renewal.
5872		testCases = append(testCases, testCase{
5873			testType: serverTest,
5874			name:     "TicketCallback-" + ver.name,
5875			config: Config{
5876				MaxVersion: ver.version,
5877			},
5878			tls13Variant:  ver.tls13Variant,
5879			resumeSession: true,
5880			flags:         []string{"-use-ticket-callback"},
5881		})
5882		testCases = append(testCases, testCase{
5883			testType: serverTest,
5884			name:     "TicketCallback-Renew-" + ver.name,
5885			config: Config{
5886				MaxVersion: ver.version,
5887				Bugs: ProtocolBugs{
5888					ExpectNewTicket: true,
5889				},
5890			},
5891			tls13Variant:  ver.tls13Variant,
5892			flags:         []string{"-use-ticket-callback", "-renew-ticket"},
5893			resumeSession: true,
5894		})
5895
5896		// Test that the ticket callback is only called once when everything before
5897		// it in the ClientHello is asynchronous. This corrupts the ticket so
5898		// certificate selection callbacks run.
5899		testCases = append(testCases, testCase{
5900			testType: serverTest,
5901			name:     "TicketCallback-SingleCall-" + ver.name,
5902			config: Config{
5903				MaxVersion: ver.version,
5904				Bugs: ProtocolBugs{
5905					FilterTicket: func(in []byte) ([]byte, error) {
5906						in[len(in)-1] ^= 1
5907						return in, nil
5908					},
5909				},
5910			},
5911			tls13Variant:         ver.tls13Variant,
5912			resumeSession:        true,
5913			expectResumeRejected: true,
5914			flags: []string{
5915				"-use-ticket-callback",
5916				"-async",
5917			},
5918		})
5919
5920		// Resume with various lengths of ticket session id.
5921		if ver.version < VersionTLS13 {
5922			testCases = append(testCases, testCase{
5923				testType: serverTest,
5924				name:     "TicketSessionIDLength-0-" + ver.name,
5925				config: Config{
5926					MaxVersion: ver.version,
5927					Bugs: ProtocolBugs{
5928						EmptyTicketSessionID: true,
5929					},
5930				},
5931				resumeSession: true,
5932			})
5933			testCases = append(testCases, testCase{
5934				testType: serverTest,
5935				name:     "TicketSessionIDLength-16-" + ver.name,
5936				config: Config{
5937					MaxVersion: ver.version,
5938					Bugs: ProtocolBugs{
5939						TicketSessionIDLength: 16,
5940					},
5941				},
5942				resumeSession: true,
5943			})
5944			testCases = append(testCases, testCase{
5945				testType: serverTest,
5946				name:     "TicketSessionIDLength-32-" + ver.name,
5947				config: Config{
5948					MaxVersion: ver.version,
5949					Bugs: ProtocolBugs{
5950						TicketSessionIDLength: 32,
5951					},
5952				},
5953				resumeSession: true,
5954			})
5955			testCases = append(testCases, testCase{
5956				testType: serverTest,
5957				name:     "TicketSessionIDLength-33-" + ver.name,
5958				config: Config{
5959					MaxVersion: ver.version,
5960					Bugs: ProtocolBugs{
5961						TicketSessionIDLength: 33,
5962					},
5963				},
5964				resumeSession: true,
5965				shouldFail:    true,
5966				// The maximum session ID length is 32.
5967				expectedError: ":DECODE_ERROR:",
5968			})
5969		}
5970
5971		// Basic DTLS-SRTP tests. Include fake profiles to ensure they
5972		// are ignored.
5973		if ver.hasDTLS {
5974			testCases = append(testCases, testCase{
5975				protocol: dtls,
5976				name:     "SRTP-Client-" + ver.name,
5977				config: Config{
5978					MaxVersion:             ver.version,
5979					SRTPProtectionProfiles: []uint16{40, SRTP_AES128_CM_HMAC_SHA1_80, 42},
5980				},
5981				flags: []string{
5982					"-srtp-profiles",
5983					"SRTP_AES128_CM_SHA1_80:SRTP_AES128_CM_SHA1_32",
5984				},
5985				expectedSRTPProtectionProfile: SRTP_AES128_CM_HMAC_SHA1_80,
5986			})
5987			testCases = append(testCases, testCase{
5988				protocol: dtls,
5989				testType: serverTest,
5990				name:     "SRTP-Server-" + ver.name,
5991				config: Config{
5992					MaxVersion:             ver.version,
5993					SRTPProtectionProfiles: []uint16{40, SRTP_AES128_CM_HMAC_SHA1_80, 42},
5994				},
5995				flags: []string{
5996					"-srtp-profiles",
5997					"SRTP_AES128_CM_SHA1_80:SRTP_AES128_CM_SHA1_32",
5998				},
5999				expectedSRTPProtectionProfile: SRTP_AES128_CM_HMAC_SHA1_80,
6000			})
6001			// Test that the MKI is ignored.
6002			testCases = append(testCases, testCase{
6003				protocol: dtls,
6004				testType: serverTest,
6005				name:     "SRTP-Server-IgnoreMKI-" + ver.name,
6006				config: Config{
6007					MaxVersion:             ver.version,
6008					SRTPProtectionProfiles: []uint16{SRTP_AES128_CM_HMAC_SHA1_80},
6009					Bugs: ProtocolBugs{
6010						SRTPMasterKeyIdentifer: "bogus",
6011					},
6012				},
6013				flags: []string{
6014					"-srtp-profiles",
6015					"SRTP_AES128_CM_SHA1_80:SRTP_AES128_CM_SHA1_32",
6016				},
6017				expectedSRTPProtectionProfile: SRTP_AES128_CM_HMAC_SHA1_80,
6018			})
6019			// Test that SRTP isn't negotiated on the server if there were
6020			// no matching profiles.
6021			testCases = append(testCases, testCase{
6022				protocol: dtls,
6023				testType: serverTest,
6024				name:     "SRTP-Server-NoMatch-" + ver.name,
6025				config: Config{
6026					MaxVersion:             ver.version,
6027					SRTPProtectionProfiles: []uint16{100, 101, 102},
6028				},
6029				flags: []string{
6030					"-srtp-profiles",
6031					"SRTP_AES128_CM_SHA1_80:SRTP_AES128_CM_SHA1_32",
6032				},
6033				expectedSRTPProtectionProfile: 0,
6034			})
6035			// Test that the server returning an invalid SRTP profile is
6036			// flagged as an error by the client.
6037			testCases = append(testCases, testCase{
6038				protocol: dtls,
6039				name:     "SRTP-Client-NoMatch-" + ver.name,
6040				config: Config{
6041					MaxVersion: ver.version,
6042					Bugs: ProtocolBugs{
6043						SendSRTPProtectionProfile: SRTP_AES128_CM_HMAC_SHA1_32,
6044					},
6045				},
6046				flags: []string{
6047					"-srtp-profiles",
6048					"SRTP_AES128_CM_SHA1_80",
6049				},
6050				shouldFail:    true,
6051				expectedError: ":BAD_SRTP_PROTECTION_PROFILE_LIST:",
6052			})
6053		}
6054
6055		// Test SCT list.
6056		testCases = append(testCases, testCase{
6057			name:     "SignedCertificateTimestampList-Client-" + ver.name,
6058			testType: clientTest,
6059			config: Config{
6060				MaxVersion: ver.version,
6061			},
6062			flags: []string{
6063				"-enable-signed-cert-timestamps",
6064				"-expect-signed-cert-timestamps",
6065				base64.StdEncoding.EncodeToString(testSCTList),
6066			},
6067			tls13Variant:  ver.tls13Variant,
6068			resumeSession: true,
6069		})
6070
6071		var differentSCTList []byte
6072		differentSCTList = append(differentSCTList, testSCTList...)
6073		differentSCTList[len(differentSCTList)-1] ^= 1
6074
6075		// The SCT extension did not specify that it must only be sent on resumption as it
6076		// should have, so test that we tolerate but ignore it.
6077		testCases = append(testCases, testCase{
6078			name: "SendSCTListOnResume-" + ver.name,
6079			config: Config{
6080				MaxVersion: ver.version,
6081				Bugs: ProtocolBugs{
6082					SendSCTListOnResume: differentSCTList,
6083				},
6084			},
6085			flags: []string{
6086				"-enable-signed-cert-timestamps",
6087				"-expect-signed-cert-timestamps",
6088				base64.StdEncoding.EncodeToString(testSCTList),
6089			},
6090			tls13Variant:  ver.tls13Variant,
6091			resumeSession: true,
6092		})
6093
6094		testCases = append(testCases, testCase{
6095			name:     "SignedCertificateTimestampList-Server-" + ver.name,
6096			testType: serverTest,
6097			config: Config{
6098				MaxVersion: ver.version,
6099			},
6100			flags: []string{
6101				"-signed-cert-timestamps",
6102				base64.StdEncoding.EncodeToString(testSCTList),
6103			},
6104			tls13Variant:    ver.tls13Variant,
6105			expectedSCTList: testSCTList,
6106			resumeSession:   true,
6107		})
6108
6109		emptySCTListCert := *testCerts[0].cert
6110		emptySCTListCert.SignedCertificateTimestampList = []byte{0, 0}
6111
6112		// Test empty SCT list.
6113		testCases = append(testCases, testCase{
6114			name:     "SignedCertificateTimestampListEmpty-Client-" + ver.name,
6115			testType: clientTest,
6116			config: Config{
6117				MaxVersion:   ver.version,
6118				Certificates: []Certificate{emptySCTListCert},
6119			},
6120			flags: []string{
6121				"-enable-signed-cert-timestamps",
6122			},
6123			tls13Variant:  ver.tls13Variant,
6124			shouldFail:    true,
6125			expectedError: ":ERROR_PARSING_EXTENSION:",
6126		})
6127
6128		emptySCTCert := *testCerts[0].cert
6129		emptySCTCert.SignedCertificateTimestampList = []byte{0, 6, 0, 2, 1, 2, 0, 0}
6130
6131		// Test empty SCT in non-empty list.
6132		testCases = append(testCases, testCase{
6133			name:     "SignedCertificateTimestampListEmptySCT-Client-" + ver.name,
6134			testType: clientTest,
6135			config: Config{
6136				MaxVersion:   ver.version,
6137				Certificates: []Certificate{emptySCTCert},
6138			},
6139			flags: []string{
6140				"-enable-signed-cert-timestamps",
6141			},
6142			tls13Variant:  ver.tls13Variant,
6143			shouldFail:    true,
6144			expectedError: ":ERROR_PARSING_EXTENSION:",
6145		})
6146
6147		// Test that certificate-related extensions are not sent unsolicited.
6148		testCases = append(testCases, testCase{
6149			testType: serverTest,
6150			name:     "UnsolicitedCertificateExtensions-" + ver.name,
6151			config: Config{
6152				MaxVersion: ver.version,
6153				Bugs: ProtocolBugs{
6154					NoOCSPStapling:                true,
6155					NoSignedCertificateTimestamps: true,
6156				},
6157			},
6158			tls13Variant: ver.tls13Variant,
6159			flags: []string{
6160				"-ocsp-response",
6161				base64.StdEncoding.EncodeToString(testOCSPResponse),
6162				"-signed-cert-timestamps",
6163				base64.StdEncoding.EncodeToString(testSCTList),
6164			},
6165		})
6166	}
6167
6168	testCases = append(testCases, testCase{
6169		testType: clientTest,
6170		name:     "ClientHelloPadding",
6171		config: Config{
6172			Bugs: ProtocolBugs{
6173				RequireClientHelloSize: 512,
6174			},
6175		},
6176		// This hostname just needs to be long enough to push the
6177		// ClientHello into F5's danger zone between 256 and 511 bytes
6178		// long.
6179		flags: []string{"-host-name", "01234567890123456789012345678901234567890123456789012345678901234567890123456789.com"},
6180	})
6181
6182	// Extensions should not function in SSL 3.0.
6183	testCases = append(testCases, testCase{
6184		testType: serverTest,
6185		name:     "SSLv3Extensions-NoALPN",
6186		config: Config{
6187			MaxVersion: VersionSSL30,
6188			NextProtos: []string{"foo", "bar", "baz"},
6189		},
6190		flags: []string{
6191			"-select-alpn", "foo",
6192		},
6193		expectNoNextProto: true,
6194	})
6195
6196	// Test session tickets separately as they follow a different codepath.
6197	testCases = append(testCases, testCase{
6198		testType: serverTest,
6199		name:     "SSLv3Extensions-NoTickets",
6200		config: Config{
6201			MaxVersion: VersionSSL30,
6202			Bugs: ProtocolBugs{
6203				// Historically, session tickets in SSL 3.0
6204				// failed in different ways depending on whether
6205				// the client supported renegotiation_info.
6206				NoRenegotiationInfo: true,
6207			},
6208		},
6209		resumeSession: true,
6210	})
6211	testCases = append(testCases, testCase{
6212		testType: serverTest,
6213		name:     "SSLv3Extensions-NoTickets2",
6214		config: Config{
6215			MaxVersion: VersionSSL30,
6216		},
6217		resumeSession: true,
6218	})
6219
6220	// But SSL 3.0 does send and process renegotiation_info.
6221	testCases = append(testCases, testCase{
6222		testType: serverTest,
6223		name:     "SSLv3Extensions-RenegotiationInfo",
6224		config: Config{
6225			MaxVersion: VersionSSL30,
6226			Bugs: ProtocolBugs{
6227				RequireRenegotiationInfo: true,
6228			},
6229		},
6230		flags: []string{"-expect-secure-renegotiation"},
6231	})
6232	testCases = append(testCases, testCase{
6233		testType: serverTest,
6234		name:     "SSLv3Extensions-RenegotiationInfo-SCSV",
6235		config: Config{
6236			MaxVersion: VersionSSL30,
6237			Bugs: ProtocolBugs{
6238				NoRenegotiationInfo:      true,
6239				SendRenegotiationSCSV:    true,
6240				RequireRenegotiationInfo: true,
6241			},
6242		},
6243		flags: []string{"-expect-secure-renegotiation"},
6244	})
6245
6246	// Test that illegal extensions in TLS 1.3 are rejected by the client if
6247	// in ServerHello.
6248	testCases = append(testCases, testCase{
6249		name: "NPN-Forbidden-TLS13",
6250		config: Config{
6251			MaxVersion: VersionTLS13,
6252			NextProtos: []string{"foo"},
6253			Bugs: ProtocolBugs{
6254				NegotiateNPNAtAllVersions: true,
6255			},
6256		},
6257		flags:         []string{"-select-next-proto", "foo"},
6258		shouldFail:    true,
6259		expectedError: ":ERROR_PARSING_EXTENSION:",
6260	})
6261	testCases = append(testCases, testCase{
6262		name: "EMS-Forbidden-TLS13",
6263		config: Config{
6264			MaxVersion: VersionTLS13,
6265			Bugs: ProtocolBugs{
6266				NegotiateEMSAtAllVersions: true,
6267			},
6268		},
6269		shouldFail:    true,
6270		expectedError: ":ERROR_PARSING_EXTENSION:",
6271	})
6272	testCases = append(testCases, testCase{
6273		name: "RenegotiationInfo-Forbidden-TLS13",
6274		config: Config{
6275			MaxVersion: VersionTLS13,
6276			Bugs: ProtocolBugs{
6277				NegotiateRenegotiationInfoAtAllVersions: true,
6278			},
6279		},
6280		shouldFail:    true,
6281		expectedError: ":ERROR_PARSING_EXTENSION:",
6282	})
6283	testCases = append(testCases, testCase{
6284		name: "Ticket-Forbidden-TLS13",
6285		config: Config{
6286			MaxVersion: VersionTLS12,
6287		},
6288		resumeConfig: &Config{
6289			MaxVersion: VersionTLS13,
6290			Bugs: ProtocolBugs{
6291				AdvertiseTicketExtension: true,
6292			},
6293		},
6294		resumeSession: true,
6295		shouldFail:    true,
6296		expectedError: ":ERROR_PARSING_EXTENSION:",
6297	})
6298
6299	// Test that illegal extensions in TLS 1.3 are declined by the server if
6300	// offered in ClientHello. The runner's server will fail if this occurs,
6301	// so we exercise the offering path. (EMS and Renegotiation Info are
6302	// implicit in every test.)
6303	testCases = append(testCases, testCase{
6304		testType: serverTest,
6305		name:     "NPN-Declined-TLS13",
6306		config: Config{
6307			MaxVersion: VersionTLS13,
6308			NextProtos: []string{"bar"},
6309		},
6310		flags: []string{"-advertise-npn", "\x03foo\x03bar\x03baz"},
6311	})
6312
6313	// OpenSSL sends the status_request extension on resumption in TLS 1.2. Test that this is
6314	// tolerated.
6315	testCases = append(testCases, testCase{
6316		name: "SendOCSPResponseOnResume-TLS12",
6317		config: Config{
6318			MaxVersion: VersionTLS12,
6319			Bugs: ProtocolBugs{
6320				SendOCSPResponseOnResume: []byte("bogus"),
6321			},
6322		},
6323		flags: []string{
6324			"-enable-ocsp-stapling",
6325			"-expect-ocsp-response",
6326			base64.StdEncoding.EncodeToString(testOCSPResponse),
6327		},
6328		resumeSession: true,
6329	})
6330
6331	testCases = append(testCases, testCase{
6332		name: "SendUnsolicitedOCSPOnCertificate-TLS13",
6333		config: Config{
6334			MaxVersion: VersionTLS13,
6335			Bugs: ProtocolBugs{
6336				SendExtensionOnCertificate: testOCSPExtension,
6337			},
6338		},
6339		shouldFail:    true,
6340		expectedError: ":UNEXPECTED_EXTENSION:",
6341	})
6342
6343	testCases = append(testCases, testCase{
6344		name: "SendUnsolicitedSCTOnCertificate-TLS13",
6345		config: Config{
6346			MaxVersion: VersionTLS13,
6347			Bugs: ProtocolBugs{
6348				SendExtensionOnCertificate: testSCTExtension,
6349			},
6350		},
6351		shouldFail:    true,
6352		expectedError: ":UNEXPECTED_EXTENSION:",
6353	})
6354
6355	// Test that extensions on client certificates are never accepted.
6356	testCases = append(testCases, testCase{
6357		name:     "SendExtensionOnClientCertificate-TLS13",
6358		testType: serverTest,
6359		config: Config{
6360			MaxVersion:   VersionTLS13,
6361			Certificates: []Certificate{rsaCertificate},
6362			Bugs: ProtocolBugs{
6363				SendExtensionOnCertificate: testOCSPExtension,
6364			},
6365		},
6366		flags: []string{
6367			"-enable-ocsp-stapling",
6368			"-require-any-client-certificate",
6369		},
6370		shouldFail:    true,
6371		expectedError: ":UNEXPECTED_EXTENSION:",
6372	})
6373
6374	testCases = append(testCases, testCase{
6375		name: "SendUnknownExtensionOnCertificate-TLS13",
6376		config: Config{
6377			MaxVersion: VersionTLS13,
6378			Bugs: ProtocolBugs{
6379				SendExtensionOnCertificate: []byte{0x00, 0x7f, 0, 0},
6380			},
6381		},
6382		shouldFail:    true,
6383		expectedError: ":UNEXPECTED_EXTENSION:",
6384	})
6385
6386	// Test that extensions on intermediates are allowed but ignored.
6387	testCases = append(testCases, testCase{
6388		name: "IgnoreExtensionsOnIntermediates-TLS13",
6389		config: Config{
6390			MaxVersion:   VersionTLS13,
6391			Certificates: []Certificate{rsaChainCertificate},
6392			Bugs: ProtocolBugs{
6393				// Send different values on the intermediate. This tests
6394				// the intermediate's extensions do not override the
6395				// leaf's.
6396				SendOCSPOnIntermediates: testOCSPResponse2,
6397				SendSCTOnIntermediates:  testSCTList2,
6398			},
6399		},
6400		flags: []string{
6401			"-enable-ocsp-stapling",
6402			"-expect-ocsp-response",
6403			base64.StdEncoding.EncodeToString(testOCSPResponse),
6404			"-enable-signed-cert-timestamps",
6405			"-expect-signed-cert-timestamps",
6406			base64.StdEncoding.EncodeToString(testSCTList),
6407		},
6408		resumeSession: true,
6409	})
6410
6411	// Test that extensions are not sent on intermediates when configured
6412	// only for a leaf.
6413	testCases = append(testCases, testCase{
6414		testType: serverTest,
6415		name:     "SendNoExtensionsOnIntermediate-TLS13",
6416		config: Config{
6417			MaxVersion: VersionTLS13,
6418			Bugs: ProtocolBugs{
6419				ExpectNoExtensionsOnIntermediate: true,
6420			},
6421		},
6422		flags: []string{
6423			"-cert-file", path.Join(*resourceDir, rsaChainCertificateFile),
6424			"-key-file", path.Join(*resourceDir, rsaChainKeyFile),
6425			"-ocsp-response",
6426			base64.StdEncoding.EncodeToString(testOCSPResponse),
6427			"-signed-cert-timestamps",
6428			base64.StdEncoding.EncodeToString(testSCTList),
6429		},
6430	})
6431
6432	// Test that extensions are not sent on client certificates.
6433	testCases = append(testCases, testCase{
6434		name: "SendNoClientCertificateExtensions-TLS13",
6435		config: Config{
6436			MaxVersion: VersionTLS13,
6437			ClientAuth: RequireAnyClientCert,
6438		},
6439		flags: []string{
6440			"-cert-file", path.Join(*resourceDir, rsaCertificateFile),
6441			"-key-file", path.Join(*resourceDir, rsaKeyFile),
6442			"-ocsp-response",
6443			base64.StdEncoding.EncodeToString(testOCSPResponse),
6444			"-signed-cert-timestamps",
6445			base64.StdEncoding.EncodeToString(testSCTList),
6446		},
6447	})
6448
6449	testCases = append(testCases, testCase{
6450		name: "SendDuplicateExtensionsOnCerts-TLS13",
6451		config: Config{
6452			MaxVersion: VersionTLS13,
6453			Bugs: ProtocolBugs{
6454				SendDuplicateCertExtensions: true,
6455			},
6456		},
6457		flags: []string{
6458			"-enable-ocsp-stapling",
6459			"-enable-signed-cert-timestamps",
6460		},
6461		resumeSession: true,
6462		shouldFail:    true,
6463		expectedError: ":DUPLICATE_EXTENSION:",
6464	})
6465
6466	testCases = append(testCases, testCase{
6467		name:     "SignedCertificateTimestampListInvalid-Server",
6468		testType: serverTest,
6469		flags: []string{
6470			"-signed-cert-timestamps",
6471			base64.StdEncoding.EncodeToString([]byte{0, 0}),
6472		},
6473		shouldFail:    true,
6474		expectedError: ":INVALID_SCT_LIST:",
6475	})
6476}
6477
6478func addResumptionVersionTests() {
6479	for _, sessionVers := range tlsVersions {
6480		for _, resumeVers := range tlsVersions {
6481			// SSL 3.0 does not have tickets and TLS 1.3 does not
6482			// have session IDs, so skip their cross-resumption
6483			// tests.
6484			if (sessionVers.version >= VersionTLS13 && resumeVers.version == VersionSSL30) ||
6485				(resumeVers.version >= VersionTLS13 && sessionVers.version == VersionSSL30) {
6486				continue
6487			}
6488
6489			protocols := []protocol{tls}
6490			if sessionVers.hasDTLS && resumeVers.hasDTLS {
6491				protocols = append(protocols, dtls)
6492			}
6493			for _, protocol := range protocols {
6494				suffix := "-" + sessionVers.name + "-" + resumeVers.name
6495				if protocol == dtls {
6496					suffix += "-DTLS"
6497				}
6498
6499				// We can't resume across TLS 1.3 variants and error out earlier in the
6500				// session resumption.
6501				if sessionVers.tls13Variant != resumeVers.tls13Variant {
6502					continue
6503				}
6504
6505				if sessionVers.version == resumeVers.version {
6506					testCases = append(testCases, testCase{
6507						protocol:      protocol,
6508						name:          "Resume-Client" + suffix,
6509						resumeSession: true,
6510						config: Config{
6511							MaxVersion:   sessionVers.version,
6512							TLS13Variant: sessionVers.tls13Variant,
6513							Bugs: ProtocolBugs{
6514								ExpectNoTLS12Session: sessionVers.version >= VersionTLS13,
6515								ExpectNoTLS13PSK:     sessionVers.version < VersionTLS13,
6516							},
6517						},
6518						expectedVersion:       sessionVers.version,
6519						expectedResumeVersion: resumeVers.version,
6520						flags: []string{
6521							"-tls13-variant", strconv.Itoa(sessionVers.tls13Variant),
6522						},
6523					})
6524				} else {
6525					error := ":OLD_SESSION_VERSION_NOT_RETURNED:"
6526
6527					// Offering a TLS 1.3 session sends an empty session ID, so
6528					// there is no way to convince a non-lookahead client the
6529					// session was resumed. It will appear to the client that a
6530					// stray ChangeCipherSpec was sent.
6531					if resumeVers.version < VersionTLS13 && sessionVers.version >= VersionTLS13 {
6532						error = ":UNEXPECTED_RECORD:"
6533					}
6534
6535					testCases = append(testCases, testCase{
6536						protocol:      protocol,
6537						name:          "Resume-Client-Mismatch" + suffix,
6538						resumeSession: true,
6539						config: Config{
6540							MaxVersion:   sessionVers.version,
6541							TLS13Variant: sessionVers.tls13Variant,
6542						},
6543						expectedVersion: sessionVers.version,
6544						resumeConfig: &Config{
6545							MaxVersion:   resumeVers.version,
6546							TLS13Variant: resumeVers.tls13Variant,
6547							Bugs: ProtocolBugs{
6548								AcceptAnySession: true,
6549							},
6550						},
6551						expectedResumeVersion: resumeVers.version,
6552						shouldFail:            true,
6553						expectedError:         error,
6554						flags: []string{
6555							"-on-initial-tls13-variant", strconv.Itoa(sessionVers.tls13Variant),
6556							"-on-resume-tls13-variant", strconv.Itoa(resumeVers.tls13Variant),
6557						},
6558					})
6559				}
6560
6561				testCases = append(testCases, testCase{
6562					protocol:      protocol,
6563					name:          "Resume-Client-NoResume" + suffix,
6564					resumeSession: true,
6565					config: Config{
6566						MaxVersion:   sessionVers.version,
6567						TLS13Variant: sessionVers.tls13Variant,
6568					},
6569					expectedVersion: sessionVers.version,
6570					resumeConfig: &Config{
6571						MaxVersion:   resumeVers.version,
6572						TLS13Variant: resumeVers.tls13Variant,
6573					},
6574					newSessionsOnResume:   true,
6575					expectResumeRejected:  true,
6576					expectedResumeVersion: resumeVers.version,
6577					flags: []string{
6578						"-on-initial-tls13-variant", strconv.Itoa(sessionVers.tls13Variant),
6579						"-on-resume-tls13-variant", strconv.Itoa(resumeVers.tls13Variant),
6580					},
6581				})
6582
6583				testCases = append(testCases, testCase{
6584					protocol:      protocol,
6585					testType:      serverTest,
6586					name:          "Resume-Server" + suffix,
6587					resumeSession: true,
6588					config: Config{
6589						MaxVersion:   sessionVers.version,
6590						TLS13Variant: sessionVers.tls13Variant,
6591					},
6592					expectedVersion:      sessionVers.version,
6593					expectResumeRejected: sessionVers != resumeVers,
6594					resumeConfig: &Config{
6595						MaxVersion:   resumeVers.version,
6596						TLS13Variant: resumeVers.tls13Variant,
6597						Bugs: ProtocolBugs{
6598							SendBothTickets: true,
6599						},
6600					},
6601					expectedResumeVersion: resumeVers.version,
6602					flags: []string{
6603						"-on-initial-tls13-variant", strconv.Itoa(sessionVers.tls13Variant),
6604						"-on-resume-tls13-variant", strconv.Itoa(resumeVers.tls13Variant),
6605					},
6606				})
6607			}
6608		}
6609	}
6610
6611	// Make sure shim ticket mutations are functional.
6612	testCases = append(testCases, testCase{
6613		testType:      serverTest,
6614		name:          "ShimTicketRewritable",
6615		resumeSession: true,
6616		config: Config{
6617			MaxVersion:   VersionTLS12,
6618			CipherSuites: []uint16{TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256},
6619			Bugs: ProtocolBugs{
6620				FilterTicket: func(in []byte) ([]byte, error) {
6621					in, err := SetShimTicketVersion(in, VersionTLS12)
6622					if err != nil {
6623						return nil, err
6624					}
6625					return SetShimTicketCipherSuite(in, TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256)
6626				},
6627			},
6628		},
6629		flags: []string{
6630			"-ticket-key",
6631			base64.StdEncoding.EncodeToString(TestShimTicketKey),
6632		},
6633	})
6634
6635	// Resumptions are declined if the version does not match.
6636	testCases = append(testCases, testCase{
6637		testType:      serverTest,
6638		name:          "Resume-Server-DeclineCrossVersion",
6639		resumeSession: true,
6640		config: Config{
6641			MaxVersion: VersionTLS12,
6642			Bugs: ProtocolBugs{
6643				ExpectNewTicket: true,
6644				FilterTicket: func(in []byte) ([]byte, error) {
6645					return SetShimTicketVersion(in, VersionTLS13)
6646				},
6647			},
6648		},
6649		flags: []string{
6650			"-ticket-key",
6651			base64.StdEncoding.EncodeToString(TestShimTicketKey),
6652		},
6653		expectResumeRejected: true,
6654	})
6655
6656	testCases = append(testCases, testCase{
6657		testType:      serverTest,
6658		name:          "Resume-Server-DeclineCrossVersion-TLS13",
6659		resumeSession: true,
6660		config: Config{
6661			MaxVersion: VersionTLS13,
6662			Bugs: ProtocolBugs{
6663				FilterTicket: func(in []byte) ([]byte, error) {
6664					return SetShimTicketVersion(in, VersionTLS12)
6665				},
6666			},
6667		},
6668		flags: []string{
6669			"-ticket-key",
6670			base64.StdEncoding.EncodeToString(TestShimTicketKey),
6671		},
6672		expectResumeRejected: true,
6673	})
6674
6675	// Resumptions are declined if the cipher is invalid or disabled.
6676	testCases = append(testCases, testCase{
6677		testType:      serverTest,
6678		name:          "Resume-Server-DeclineBadCipher",
6679		resumeSession: true,
6680		config: Config{
6681			MaxVersion: VersionTLS12,
6682			Bugs: ProtocolBugs{
6683				ExpectNewTicket: true,
6684				FilterTicket: func(in []byte) ([]byte, error) {
6685					return SetShimTicketCipherSuite(in, TLS_AES_128_GCM_SHA256)
6686				},
6687			},
6688		},
6689		flags: []string{
6690			"-ticket-key",
6691			base64.StdEncoding.EncodeToString(TestShimTicketKey),
6692		},
6693		expectResumeRejected: true,
6694	})
6695
6696	testCases = append(testCases, testCase{
6697		testType:      serverTest,
6698		name:          "Resume-Server-DeclineBadCipher-2",
6699		resumeSession: true,
6700		config: Config{
6701			MaxVersion: VersionTLS12,
6702			Bugs: ProtocolBugs{
6703				ExpectNewTicket: true,
6704				FilterTicket: func(in []byte) ([]byte, error) {
6705					return SetShimTicketCipherSuite(in, TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384)
6706				},
6707			},
6708		},
6709		flags: []string{
6710			"-cipher", "AES128",
6711			"-ticket-key",
6712			base64.StdEncoding.EncodeToString(TestShimTicketKey),
6713		},
6714		expectResumeRejected: true,
6715	})
6716
6717	// Sessions are not resumed if they do not use the preferred cipher.
6718	testCases = append(testCases, testCase{
6719		testType:      serverTest,
6720		name:          "Resume-Server-CipherNotPreferred",
6721		resumeSession: true,
6722		config: Config{
6723			MaxVersion: VersionTLS12,
6724			Bugs: ProtocolBugs{
6725				ExpectNewTicket: true,
6726				FilterTicket: func(in []byte) ([]byte, error) {
6727					return SetShimTicketCipherSuite(in, TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA)
6728				},
6729			},
6730		},
6731		flags: []string{
6732			"-ticket-key",
6733			base64.StdEncoding.EncodeToString(TestShimTicketKey),
6734		},
6735		shouldFail:           false,
6736		expectResumeRejected: true,
6737	})
6738
6739	// TLS 1.3 allows sessions to be resumed at a different cipher if their
6740	// PRF hashes match, but BoringSSL will always decline such resumptions.
6741	testCases = append(testCases, testCase{
6742		testType:      serverTest,
6743		name:          "Resume-Server-CipherNotPreferred-TLS13",
6744		resumeSession: true,
6745		config: Config{
6746			MaxVersion:   VersionTLS13,
6747			CipherSuites: []uint16{TLS_CHACHA20_POLY1305_SHA256, TLS_AES_128_GCM_SHA256},
6748			Bugs: ProtocolBugs{
6749				FilterTicket: func(in []byte) ([]byte, error) {
6750					// If the client (runner) offers ChaCha20-Poly1305 first, the
6751					// server (shim) always prefers it. Switch it to AES-GCM.
6752					return SetShimTicketCipherSuite(in, TLS_AES_128_GCM_SHA256)
6753				},
6754			},
6755		},
6756		flags: []string{
6757			"-ticket-key",
6758			base64.StdEncoding.EncodeToString(TestShimTicketKey),
6759		},
6760		shouldFail:           false,
6761		expectResumeRejected: true,
6762	})
6763
6764	// Sessions may not be resumed if they contain another version's cipher.
6765	testCases = append(testCases, testCase{
6766		testType:      serverTest,
6767		name:          "Resume-Server-DeclineBadCipher-TLS13",
6768		resumeSession: true,
6769		config: Config{
6770			MaxVersion: VersionTLS13,
6771			Bugs: ProtocolBugs{
6772				FilterTicket: func(in []byte) ([]byte, error) {
6773					return SetShimTicketCipherSuite(in, TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256)
6774				},
6775			},
6776		},
6777		flags: []string{
6778			"-ticket-key",
6779			base64.StdEncoding.EncodeToString(TestShimTicketKey),
6780		},
6781		expectResumeRejected: true,
6782	})
6783
6784	// If the client does not offer the cipher from the session, decline to
6785	// resume. Clients are forbidden from doing this, but BoringSSL selects
6786	// the cipher first, so we only decline.
6787	testCases = append(testCases, testCase{
6788		testType:      serverTest,
6789		name:          "Resume-Server-UnofferedCipher",
6790		resumeSession: true,
6791		config: Config{
6792			MaxVersion:   VersionTLS12,
6793			CipherSuites: []uint16{TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256},
6794		},
6795		resumeConfig: &Config{
6796			MaxVersion:   VersionTLS12,
6797			CipherSuites: []uint16{TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256},
6798			Bugs: ProtocolBugs{
6799				SendCipherSuites: []uint16{TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256},
6800			},
6801		},
6802		expectResumeRejected: true,
6803	})
6804
6805	// In TLS 1.3, clients may advertise a cipher list which does not
6806	// include the selected cipher. Test that we tolerate this. Servers may
6807	// resume at another cipher if the PRF matches and are not doing 0-RTT, but
6808	// BoringSSL will always decline.
6809	testCases = append(testCases, testCase{
6810		testType:      serverTest,
6811		name:          "Resume-Server-UnofferedCipher-TLS13",
6812		resumeSession: true,
6813		config: Config{
6814			MaxVersion:   VersionTLS13,
6815			CipherSuites: []uint16{TLS_CHACHA20_POLY1305_SHA256},
6816		},
6817		resumeConfig: &Config{
6818			MaxVersion:   VersionTLS13,
6819			CipherSuites: []uint16{TLS_CHACHA20_POLY1305_SHA256},
6820			Bugs: ProtocolBugs{
6821				SendCipherSuites: []uint16{TLS_AES_128_GCM_SHA256},
6822			},
6823		},
6824		expectResumeRejected: true,
6825	})
6826
6827	// Sessions may not be resumed at a different cipher.
6828	testCases = append(testCases, testCase{
6829		name:          "Resume-Client-CipherMismatch",
6830		resumeSession: true,
6831		config: Config{
6832			MaxVersion:   VersionTLS12,
6833			CipherSuites: []uint16{TLS_RSA_WITH_AES_128_GCM_SHA256},
6834		},
6835		resumeConfig: &Config{
6836			MaxVersion:   VersionTLS12,
6837			CipherSuites: []uint16{TLS_RSA_WITH_AES_128_GCM_SHA256},
6838			Bugs: ProtocolBugs{
6839				SendCipherSuite: TLS_RSA_WITH_AES_128_CBC_SHA,
6840			},
6841		},
6842		shouldFail:    true,
6843		expectedError: ":OLD_SESSION_CIPHER_NOT_RETURNED:",
6844	})
6845
6846	// Session resumption in TLS 1.3 may change the cipher suite if the PRF
6847	// matches.
6848	testCases = append(testCases, testCase{
6849		name:          "Resume-Client-CipherMismatch-TLS13",
6850		resumeSession: true,
6851		config: Config{
6852			MaxVersion:   VersionTLS13,
6853			CipherSuites: []uint16{TLS_AES_128_GCM_SHA256},
6854		},
6855		resumeConfig: &Config{
6856			MaxVersion:   VersionTLS13,
6857			CipherSuites: []uint16{TLS_CHACHA20_POLY1305_SHA256},
6858		},
6859	})
6860
6861	// Session resumption in TLS 1.3 is forbidden if the PRF does not match.
6862	testCases = append(testCases, testCase{
6863		name:          "Resume-Client-PRFMismatch-TLS13",
6864		resumeSession: true,
6865		config: Config{
6866			MaxVersion:   VersionTLS13,
6867			CipherSuites: []uint16{TLS_AES_128_GCM_SHA256},
6868		},
6869		resumeConfig: &Config{
6870			MaxVersion:   VersionTLS13,
6871			CipherSuites: []uint16{TLS_AES_128_GCM_SHA256},
6872			Bugs: ProtocolBugs{
6873				SendCipherSuite: TLS_AES_256_GCM_SHA384,
6874			},
6875		},
6876		shouldFail:    true,
6877		expectedError: ":OLD_SESSION_PRF_HASH_MISMATCH:",
6878	})
6879
6880	testCases = append(testCases, testCase{
6881		testType:      serverTest,
6882		name:          "Resume-Server-BinderWrongLength",
6883		resumeSession: true,
6884		config: Config{
6885			MaxVersion: VersionTLS13,
6886			Bugs: ProtocolBugs{
6887				SendShortPSKBinder: true,
6888			},
6889		},
6890		shouldFail:         true,
6891		expectedLocalError: "remote error: error decrypting message",
6892		expectedError:      ":DIGEST_CHECK_FAILED:",
6893	})
6894
6895	testCases = append(testCases, testCase{
6896		testType:      serverTest,
6897		name:          "Resume-Server-NoPSKBinder",
6898		resumeSession: true,
6899		config: Config{
6900			MaxVersion: VersionTLS13,
6901			Bugs: ProtocolBugs{
6902				SendNoPSKBinder: true,
6903			},
6904		},
6905		shouldFail:         true,
6906		expectedLocalError: "remote error: error decoding message",
6907		expectedError:      ":DECODE_ERROR:",
6908	})
6909
6910	testCases = append(testCases, testCase{
6911		testType:      serverTest,
6912		name:          "Resume-Server-ExtraPSKBinder",
6913		resumeSession: true,
6914		config: Config{
6915			MaxVersion: VersionTLS13,
6916			Bugs: ProtocolBugs{
6917				SendExtraPSKBinder: true,
6918			},
6919		},
6920		shouldFail:         true,
6921		expectedLocalError: "remote error: illegal parameter",
6922		expectedError:      ":PSK_IDENTITY_BINDER_COUNT_MISMATCH:",
6923	})
6924
6925	testCases = append(testCases, testCase{
6926		testType:      serverTest,
6927		name:          "Resume-Server-ExtraIdentityNoBinder",
6928		resumeSession: true,
6929		config: Config{
6930			MaxVersion: VersionTLS13,
6931			Bugs: ProtocolBugs{
6932				ExtraPSKIdentity: true,
6933			},
6934		},
6935		shouldFail:         true,
6936		expectedLocalError: "remote error: illegal parameter",
6937		expectedError:      ":PSK_IDENTITY_BINDER_COUNT_MISMATCH:",
6938	})
6939
6940	testCases = append(testCases, testCase{
6941		testType:      serverTest,
6942		name:          "Resume-Server-InvalidPSKBinder",
6943		resumeSession: true,
6944		config: Config{
6945			MaxVersion: VersionTLS13,
6946			Bugs: ProtocolBugs{
6947				SendInvalidPSKBinder: true,
6948			},
6949		},
6950		shouldFail:         true,
6951		expectedLocalError: "remote error: error decrypting message",
6952		expectedError:      ":DIGEST_CHECK_FAILED:",
6953	})
6954
6955	testCases = append(testCases, testCase{
6956		testType:      serverTest,
6957		name:          "Resume-Server-PSKBinderFirstExtension",
6958		resumeSession: true,
6959		config: Config{
6960			MaxVersion: VersionTLS13,
6961			Bugs: ProtocolBugs{
6962				PSKBinderFirst: true,
6963			},
6964		},
6965		shouldFail:         true,
6966		expectedLocalError: "remote error: illegal parameter",
6967		expectedError:      ":PRE_SHARED_KEY_MUST_BE_LAST:",
6968	})
6969}
6970
6971func addRenegotiationTests() {
6972	// Servers cannot renegotiate.
6973	testCases = append(testCases, testCase{
6974		testType: serverTest,
6975		name:     "Renegotiate-Server-Forbidden",
6976		config: Config{
6977			MaxVersion: VersionTLS12,
6978		},
6979		renegotiate:        1,
6980		shouldFail:         true,
6981		expectedError:      ":NO_RENEGOTIATION:",
6982		expectedLocalError: "remote error: no renegotiation",
6983	})
6984	// The server shouldn't echo the renegotiation extension unless
6985	// requested by the client.
6986	testCases = append(testCases, testCase{
6987		testType: serverTest,
6988		name:     "Renegotiate-Server-NoExt",
6989		config: Config{
6990			MaxVersion: VersionTLS12,
6991			Bugs: ProtocolBugs{
6992				NoRenegotiationInfo:      true,
6993				RequireRenegotiationInfo: true,
6994			},
6995		},
6996		shouldFail:         true,
6997		expectedLocalError: "renegotiation extension missing",
6998	})
6999	// The renegotiation SCSV should be sufficient for the server to echo
7000	// the extension.
7001	testCases = append(testCases, testCase{
7002		testType: serverTest,
7003		name:     "Renegotiate-Server-NoExt-SCSV",
7004		config: Config{
7005			MaxVersion: VersionTLS12,
7006			Bugs: ProtocolBugs{
7007				NoRenegotiationInfo:      true,
7008				SendRenegotiationSCSV:    true,
7009				RequireRenegotiationInfo: true,
7010			},
7011		},
7012	})
7013	testCases = append(testCases, testCase{
7014		name: "Renegotiate-Client",
7015		config: Config{
7016			MaxVersion: VersionTLS12,
7017			Bugs: ProtocolBugs{
7018				FailIfResumeOnRenego: true,
7019			},
7020		},
7021		renegotiate: 1,
7022		flags: []string{
7023			"-renegotiate-freely",
7024			"-expect-total-renegotiations", "1",
7025			"-expect-secure-renegotiation",
7026		},
7027	})
7028	testCases = append(testCases, testCase{
7029		name:        "Renegotiate-Client-EmptyExt",
7030		renegotiate: 1,
7031		config: Config{
7032			MaxVersion: VersionTLS12,
7033			Bugs: ProtocolBugs{
7034				EmptyRenegotiationInfo: true,
7035			},
7036		},
7037		flags:         []string{"-renegotiate-freely"},
7038		shouldFail:    true,
7039		expectedError: ":RENEGOTIATION_MISMATCH:",
7040	})
7041	testCases = append(testCases, testCase{
7042		name:        "Renegotiate-Client-BadExt",
7043		renegotiate: 1,
7044		config: Config{
7045			MaxVersion: VersionTLS12,
7046			Bugs: ProtocolBugs{
7047				BadRenegotiationInfo: true,
7048			},
7049		},
7050		flags:         []string{"-renegotiate-freely"},
7051		shouldFail:    true,
7052		expectedError: ":RENEGOTIATION_MISMATCH:",
7053	})
7054	testCases = append(testCases, testCase{
7055		name:        "Renegotiate-Client-BadExt2",
7056		renegotiate: 1,
7057		config: Config{
7058			MaxVersion: VersionTLS12,
7059			Bugs: ProtocolBugs{
7060				BadRenegotiationInfoEnd: true,
7061			},
7062		},
7063		flags:         []string{"-renegotiate-freely"},
7064		shouldFail:    true,
7065		expectedError: ":RENEGOTIATION_MISMATCH:",
7066	})
7067	testCases = append(testCases, testCase{
7068		name:        "Renegotiate-Client-Downgrade",
7069		renegotiate: 1,
7070		config: Config{
7071			MaxVersion: VersionTLS12,
7072			Bugs: ProtocolBugs{
7073				NoRenegotiationInfoAfterInitial: true,
7074			},
7075		},
7076		flags:         []string{"-renegotiate-freely"},
7077		shouldFail:    true,
7078		expectedError: ":RENEGOTIATION_MISMATCH:",
7079	})
7080	testCases = append(testCases, testCase{
7081		name:        "Renegotiate-Client-Upgrade",
7082		renegotiate: 1,
7083		config: Config{
7084			MaxVersion: VersionTLS12,
7085			Bugs: ProtocolBugs{
7086				NoRenegotiationInfoInInitial: true,
7087			},
7088		},
7089		flags:         []string{"-renegotiate-freely"},
7090		shouldFail:    true,
7091		expectedError: ":RENEGOTIATION_MISMATCH:",
7092	})
7093	testCases = append(testCases, testCase{
7094		name:        "Renegotiate-Client-NoExt-Allowed",
7095		renegotiate: 1,
7096		config: Config{
7097			MaxVersion: VersionTLS12,
7098			Bugs: ProtocolBugs{
7099				NoRenegotiationInfo: true,
7100			},
7101		},
7102		flags: []string{
7103			"-renegotiate-freely",
7104			"-expect-total-renegotiations", "1",
7105			"-expect-no-secure-renegotiation",
7106		},
7107	})
7108
7109	// Test that the server may switch ciphers on renegotiation without
7110	// problems.
7111	testCases = append(testCases, testCase{
7112		name:        "Renegotiate-Client-SwitchCiphers",
7113		renegotiate: 1,
7114		config: Config{
7115			MaxVersion:   VersionTLS12,
7116			CipherSuites: []uint16{TLS_RSA_WITH_3DES_EDE_CBC_SHA},
7117		},
7118		renegotiateCiphers: []uint16{TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256},
7119		flags: []string{
7120			"-renegotiate-freely",
7121			"-expect-total-renegotiations", "1",
7122		},
7123	})
7124	testCases = append(testCases, testCase{
7125		name:        "Renegotiate-Client-SwitchCiphers2",
7126		renegotiate: 1,
7127		config: Config{
7128			MaxVersion:   VersionTLS12,
7129			CipherSuites: []uint16{TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256},
7130		},
7131		renegotiateCiphers: []uint16{TLS_RSA_WITH_3DES_EDE_CBC_SHA},
7132		flags: []string{
7133			"-renegotiate-freely",
7134			"-expect-total-renegotiations", "1",
7135		},
7136	})
7137
7138	// Test that the server may not switch versions on renegotiation.
7139	testCases = append(testCases, testCase{
7140		name: "Renegotiate-Client-SwitchVersion",
7141		config: Config{
7142			MaxVersion: VersionTLS12,
7143			// Pick a cipher which exists at both versions.
7144			CipherSuites: []uint16{TLS_RSA_WITH_AES_128_CBC_SHA},
7145			Bugs: ProtocolBugs{
7146				NegotiateVersionOnRenego: VersionTLS11,
7147				// Avoid failing early at the record layer.
7148				SendRecordVersion: VersionTLS12,
7149			},
7150		},
7151		renegotiate: 1,
7152		flags: []string{
7153			"-renegotiate-freely",
7154			"-expect-total-renegotiations", "1",
7155		},
7156		shouldFail:    true,
7157		expectedError: ":WRONG_SSL_VERSION:",
7158	})
7159
7160	testCases = append(testCases, testCase{
7161		name:        "Renegotiate-SameClientVersion",
7162		renegotiate: 1,
7163		config: Config{
7164			MaxVersion: VersionTLS10,
7165			Bugs: ProtocolBugs{
7166				RequireSameRenegoClientVersion: true,
7167			},
7168		},
7169		flags: []string{
7170			"-renegotiate-freely",
7171			"-expect-total-renegotiations", "1",
7172		},
7173	})
7174	testCases = append(testCases, testCase{
7175		name:        "Renegotiate-FalseStart",
7176		renegotiate: 1,
7177		config: Config{
7178			MaxVersion:   VersionTLS12,
7179			CipherSuites: []uint16{TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256},
7180			NextProtos:   []string{"foo"},
7181		},
7182		flags: []string{
7183			"-false-start",
7184			"-select-next-proto", "foo",
7185			"-renegotiate-freely",
7186			"-expect-total-renegotiations", "1",
7187		},
7188		shimWritesFirst: true,
7189	})
7190
7191	// Client-side renegotiation controls.
7192	testCases = append(testCases, testCase{
7193		name: "Renegotiate-Client-Forbidden-1",
7194		config: Config{
7195			MaxVersion: VersionTLS12,
7196		},
7197		renegotiate:        1,
7198		shouldFail:         true,
7199		expectedError:      ":NO_RENEGOTIATION:",
7200		expectedLocalError: "remote error: no renegotiation",
7201	})
7202	testCases = append(testCases, testCase{
7203		name: "Renegotiate-Client-Once-1",
7204		config: Config{
7205			MaxVersion: VersionTLS12,
7206		},
7207		renegotiate: 1,
7208		flags: []string{
7209			"-renegotiate-once",
7210			"-expect-total-renegotiations", "1",
7211		},
7212	})
7213	testCases = append(testCases, testCase{
7214		name: "Renegotiate-Client-Freely-1",
7215		config: Config{
7216			MaxVersion: VersionTLS12,
7217		},
7218		renegotiate: 1,
7219		flags: []string{
7220			"-renegotiate-freely",
7221			"-expect-total-renegotiations", "1",
7222		},
7223	})
7224	testCases = append(testCases, testCase{
7225		name: "Renegotiate-Client-Once-2",
7226		config: Config{
7227			MaxVersion: VersionTLS12,
7228		},
7229		renegotiate:        2,
7230		flags:              []string{"-renegotiate-once"},
7231		shouldFail:         true,
7232		expectedError:      ":NO_RENEGOTIATION:",
7233		expectedLocalError: "remote error: no renegotiation",
7234	})
7235	testCases = append(testCases, testCase{
7236		name: "Renegotiate-Client-Freely-2",
7237		config: Config{
7238			MaxVersion: VersionTLS12,
7239		},
7240		renegotiate: 2,
7241		flags: []string{
7242			"-renegotiate-freely",
7243			"-expect-total-renegotiations", "2",
7244		},
7245	})
7246	testCases = append(testCases, testCase{
7247		name: "Renegotiate-Client-NoIgnore",
7248		config: Config{
7249			MaxVersion: VersionTLS12,
7250			Bugs: ProtocolBugs{
7251				SendHelloRequestBeforeEveryAppDataRecord: true,
7252			},
7253		},
7254		shouldFail:    true,
7255		expectedError: ":NO_RENEGOTIATION:",
7256	})
7257	testCases = append(testCases, testCase{
7258		name: "Renegotiate-Client-Ignore",
7259		config: Config{
7260			MaxVersion: VersionTLS12,
7261			Bugs: ProtocolBugs{
7262				SendHelloRequestBeforeEveryAppDataRecord: true,
7263			},
7264		},
7265		flags: []string{
7266			"-renegotiate-ignore",
7267			"-expect-total-renegotiations", "0",
7268		},
7269	})
7270
7271	// Renegotiation is not allowed at SSL 3.0.
7272	testCases = append(testCases, testCase{
7273		name: "Renegotiate-Client-SSL3",
7274		config: Config{
7275			MaxVersion: VersionSSL30,
7276		},
7277		renegotiate: 1,
7278		flags: []string{
7279			"-renegotiate-freely",
7280			"-expect-total-renegotiations", "1",
7281		},
7282		shouldFail:         true,
7283		expectedError:      ":NO_RENEGOTIATION:",
7284		expectedLocalError: "remote error: no renegotiation",
7285	})
7286
7287	// Renegotiation is not allowed when there is an unfinished write.
7288	testCases = append(testCases, testCase{
7289		name: "Renegotiate-Client-UnfinishedWrite",
7290		config: Config{
7291			MaxVersion: VersionTLS12,
7292		},
7293		renegotiate:             1,
7294		readWithUnfinishedWrite: true,
7295		flags: []string{
7296			"-async",
7297			"-renegotiate-freely",
7298		},
7299		shouldFail:    true,
7300		expectedError: ":NO_RENEGOTIATION:",
7301		// We do not successfully send the no_renegotiation alert in
7302		// this case. https://crbug.com/boringssl/130
7303	})
7304
7305	// We reject stray HelloRequests during the handshake in TLS 1.2.
7306	testCases = append(testCases, testCase{
7307		name: "StrayHelloRequest",
7308		config: Config{
7309			MaxVersion: VersionTLS12,
7310			Bugs: ProtocolBugs{
7311				SendHelloRequestBeforeEveryHandshakeMessage: true,
7312			},
7313		},
7314		shouldFail:    true,
7315		expectedError: ":UNEXPECTED_MESSAGE:",
7316	})
7317	testCases = append(testCases, testCase{
7318		name: "StrayHelloRequest-Packed",
7319		config: Config{
7320			MaxVersion: VersionTLS12,
7321			Bugs: ProtocolBugs{
7322				PackHandshakeFlight:                         true,
7323				SendHelloRequestBeforeEveryHandshakeMessage: true,
7324			},
7325		},
7326		shouldFail:    true,
7327		expectedError: ":UNEXPECTED_MESSAGE:",
7328	})
7329
7330	// Test renegotiation works if HelloRequest and server Finished come in
7331	// the same record.
7332	testCases = append(testCases, testCase{
7333		name: "Renegotiate-Client-Packed",
7334		config: Config{
7335			MaxVersion: VersionTLS12,
7336			Bugs: ProtocolBugs{
7337				PackHandshakeFlight:          true,
7338				PackHelloRequestWithFinished: true,
7339			},
7340		},
7341		renegotiate: 1,
7342		flags: []string{
7343			"-renegotiate-freely",
7344			"-expect-total-renegotiations", "1",
7345		},
7346	})
7347
7348	// Renegotiation is forbidden in TLS 1.3.
7349	testCases = append(testCases, testCase{
7350		name: "Renegotiate-Client-TLS13",
7351		config: Config{
7352			MaxVersion: VersionTLS13,
7353			Bugs: ProtocolBugs{
7354				SendHelloRequestBeforeEveryAppDataRecord: true,
7355			},
7356		},
7357		flags: []string{
7358			"-renegotiate-freely",
7359		},
7360		shouldFail:    true,
7361		expectedError: ":UNEXPECTED_MESSAGE:",
7362	})
7363
7364	// Stray HelloRequests during the handshake are forbidden in TLS 1.3.
7365	testCases = append(testCases, testCase{
7366		name: "StrayHelloRequest-TLS13",
7367		config: Config{
7368			MaxVersion: VersionTLS13,
7369			Bugs: ProtocolBugs{
7370				SendHelloRequestBeforeEveryHandshakeMessage: true,
7371			},
7372		},
7373		shouldFail:    true,
7374		expectedError: ":UNEXPECTED_MESSAGE:",
7375	})
7376
7377	// The renegotiation_info extension is not sent in TLS 1.3, but TLS 1.3
7378	// always reads as supporting it, regardless of whether it was
7379	// negotiated.
7380	testCases = append(testCases, testCase{
7381		name: "AlwaysReportRenegotiationInfo-TLS13",
7382		config: Config{
7383			MaxVersion: VersionTLS13,
7384			Bugs: ProtocolBugs{
7385				NoRenegotiationInfo: true,
7386			},
7387		},
7388		flags: []string{
7389			"-expect-secure-renegotiation",
7390		},
7391	})
7392
7393	// Certificates may not change on renegotiation.
7394	testCases = append(testCases, testCase{
7395		name: "Renegotiation-CertificateChange",
7396		config: Config{
7397			MaxVersion:   VersionTLS12,
7398			Certificates: []Certificate{rsaCertificate},
7399			Bugs: ProtocolBugs{
7400				RenegotiationCertificate: &rsaChainCertificate,
7401			},
7402		},
7403		renegotiate:   1,
7404		flags:         []string{"-renegotiate-freely"},
7405		shouldFail:    true,
7406		expectedError: ":SERVER_CERT_CHANGED:",
7407	})
7408	testCases = append(testCases, testCase{
7409		name: "Renegotiation-CertificateChange-2",
7410		config: Config{
7411			MaxVersion:   VersionTLS12,
7412			Certificates: []Certificate{rsaCertificate},
7413			Bugs: ProtocolBugs{
7414				RenegotiationCertificate: &rsa1024Certificate,
7415			},
7416		},
7417		renegotiate:   1,
7418		flags:         []string{"-renegotiate-freely"},
7419		shouldFail:    true,
7420		expectedError: ":SERVER_CERT_CHANGED:",
7421	})
7422
7423	// We do not negotiate ALPN after the initial handshake. This is
7424	// error-prone and only risks bugs in consumers.
7425	testCases = append(testCases, testCase{
7426		testType: clientTest,
7427		name:     "Renegotiation-ForbidALPN",
7428		config: Config{
7429			MaxVersion: VersionTLS12,
7430			Bugs: ProtocolBugs{
7431				// Forcibly negotiate ALPN on both initial and
7432				// renegotiation handshakes. The test stack will
7433				// internally check the client does not offer
7434				// it.
7435				SendALPN: "foo",
7436			},
7437		},
7438		flags: []string{
7439			"-advertise-alpn", "\x03foo\x03bar\x03baz",
7440			"-expect-alpn", "foo",
7441			"-renegotiate-freely",
7442		},
7443		renegotiate:   1,
7444		shouldFail:    true,
7445		expectedError: ":UNEXPECTED_EXTENSION:",
7446	})
7447
7448	// The server may send different stapled OCSP responses or SCT lists on
7449	// renegotiation, but BoringSSL ignores this and reports the old values.
7450	// Also test that non-fatal verify results are preserved.
7451	testCases = append(testCases, testCase{
7452		testType: clientTest,
7453		name:     "Renegotiation-ChangeAuthProperties",
7454		config: Config{
7455			MaxVersion: VersionTLS12,
7456			Bugs: ProtocolBugs{
7457				SendOCSPResponseOnRenegotiation: testOCSPResponse2,
7458				SendSCTListOnRenegotiation:      testSCTList2,
7459			},
7460		},
7461		renegotiate: 1,
7462		flags: []string{
7463			"-renegotiate-freely",
7464			"-expect-total-renegotiations", "1",
7465			"-enable-ocsp-stapling",
7466			"-expect-ocsp-response",
7467			base64.StdEncoding.EncodeToString(testOCSPResponse),
7468			"-enable-signed-cert-timestamps",
7469			"-expect-signed-cert-timestamps",
7470			base64.StdEncoding.EncodeToString(testSCTList),
7471			"-verify-fail",
7472			"-expect-verify-result",
7473		},
7474	})
7475}
7476
7477func addDTLSReplayTests() {
7478	// Test that sequence number replays are detected.
7479	testCases = append(testCases, testCase{
7480		protocol:     dtls,
7481		name:         "DTLS-Replay",
7482		messageCount: 200,
7483		replayWrites: true,
7484	})
7485
7486	// Test the incoming sequence number skipping by values larger
7487	// than the retransmit window.
7488	testCases = append(testCases, testCase{
7489		protocol: dtls,
7490		name:     "DTLS-Replay-LargeGaps",
7491		config: Config{
7492			Bugs: ProtocolBugs{
7493				SequenceNumberMapping: func(in uint64) uint64 {
7494					return in * 127
7495				},
7496			},
7497		},
7498		messageCount: 200,
7499		replayWrites: true,
7500	})
7501
7502	// Test the incoming sequence number changing non-monotonically.
7503	testCases = append(testCases, testCase{
7504		protocol: dtls,
7505		name:     "DTLS-Replay-NonMonotonic",
7506		config: Config{
7507			Bugs: ProtocolBugs{
7508				SequenceNumberMapping: func(in uint64) uint64 {
7509					return in ^ 31
7510				},
7511			},
7512		},
7513		messageCount: 200,
7514		replayWrites: true,
7515	})
7516}
7517
7518var testSignatureAlgorithms = []struct {
7519	name string
7520	id   signatureAlgorithm
7521	cert testCert
7522}{
7523	{"RSA-PKCS1-SHA1", signatureRSAPKCS1WithSHA1, testCertRSA},
7524	{"RSA-PKCS1-SHA256", signatureRSAPKCS1WithSHA256, testCertRSA},
7525	{"RSA-PKCS1-SHA384", signatureRSAPKCS1WithSHA384, testCertRSA},
7526	{"RSA-PKCS1-SHA512", signatureRSAPKCS1WithSHA512, testCertRSA},
7527	{"ECDSA-SHA1", signatureECDSAWithSHA1, testCertECDSAP256},
7528	// The “P256” in the following line is not a mistake. In TLS 1.2 the
7529	// hash function doesn't have to match the curve and so the same
7530	// signature algorithm works with P-224.
7531	{"ECDSA-P224-SHA256", signatureECDSAWithP256AndSHA256, testCertECDSAP224},
7532	{"ECDSA-P256-SHA256", signatureECDSAWithP256AndSHA256, testCertECDSAP256},
7533	{"ECDSA-P384-SHA384", signatureECDSAWithP384AndSHA384, testCertECDSAP384},
7534	{"ECDSA-P521-SHA512", signatureECDSAWithP521AndSHA512, testCertECDSAP521},
7535	{"RSA-PSS-SHA256", signatureRSAPSSWithSHA256, testCertRSA},
7536	{"RSA-PSS-SHA384", signatureRSAPSSWithSHA384, testCertRSA},
7537	{"RSA-PSS-SHA512", signatureRSAPSSWithSHA512, testCertRSA},
7538	{"Ed25519", signatureEd25519, testCertEd25519},
7539	// Tests for key types prior to TLS 1.2.
7540	{"RSA", 0, testCertRSA},
7541	{"ECDSA", 0, testCertECDSAP256},
7542}
7543
7544const fakeSigAlg1 signatureAlgorithm = 0x2a01
7545const fakeSigAlg2 signatureAlgorithm = 0xff01
7546
7547func addSignatureAlgorithmTests() {
7548	// Not all ciphers involve a signature. Advertise a list which gives all
7549	// versions a signing cipher.
7550	signingCiphers := []uint16{
7551		TLS_AES_128_GCM_SHA256,
7552		TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
7553		TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
7554		TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA,
7555		TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,
7556	}
7557
7558	var allAlgorithms []signatureAlgorithm
7559	for _, alg := range testSignatureAlgorithms {
7560		if alg.id != 0 {
7561			allAlgorithms = append(allAlgorithms, alg.id)
7562		}
7563	}
7564
7565	// Make sure each signature algorithm works. Include some fake values in
7566	// the list and ensure they're ignored.
7567	for _, alg := range testSignatureAlgorithms {
7568		for _, ver := range tlsVersions {
7569			if (ver.version < VersionTLS12) != (alg.id == 0) {
7570				continue
7571			}
7572
7573			// TODO(davidben): Support ECDSA in SSL 3.0 in Go for testing
7574			// or remove it in C.
7575			if ver.version == VersionSSL30 && alg.cert != testCertRSA {
7576				continue
7577			}
7578
7579			var shouldSignFail, shouldVerifyFail bool
7580			// ecdsa_sha1 does not exist in TLS 1.3.
7581			if ver.version >= VersionTLS13 && alg.id == signatureECDSAWithSHA1 {
7582				shouldSignFail = true
7583				shouldVerifyFail = true
7584			}
7585			// RSA-PKCS1 does not exist in TLS 1.3.
7586			if ver.version >= VersionTLS13 && hasComponent(alg.name, "PKCS1") {
7587				shouldSignFail = true
7588				shouldVerifyFail = true
7589			}
7590			// SHA-224 has been removed from TLS 1.3 and, in 1.3,
7591			// the curve has to match the hash size.
7592			if ver.version >= VersionTLS13 && alg.cert == testCertECDSAP224 {
7593				shouldSignFail = true
7594				shouldVerifyFail = true
7595			}
7596
7597			// BoringSSL will sign SHA-1 and SHA-512 with ECDSA but not accept them.
7598			if alg.id == signatureECDSAWithSHA1 || alg.id == signatureECDSAWithP521AndSHA512 {
7599				shouldVerifyFail = true
7600			}
7601
7602			var signError, verifyError string
7603			if shouldSignFail {
7604				signError = ":NO_COMMON_SIGNATURE_ALGORITHMS:"
7605			}
7606			if shouldVerifyFail {
7607				verifyError = ":WRONG_SIGNATURE_TYPE:"
7608			}
7609
7610			suffix := "-" + alg.name + "-" + ver.name
7611
7612			testCases = append(testCases, testCase{
7613				name: "ClientAuth-Sign" + suffix,
7614				config: Config{
7615					MaxVersion: ver.version,
7616					ClientAuth: RequireAnyClientCert,
7617					VerifySignatureAlgorithms: []signatureAlgorithm{
7618						fakeSigAlg1,
7619						alg.id,
7620						fakeSigAlg2,
7621					},
7622				},
7623				flags: []string{
7624					"-cert-file", path.Join(*resourceDir, getShimCertificate(alg.cert)),
7625					"-key-file", path.Join(*resourceDir, getShimKey(alg.cert)),
7626					"-enable-all-curves",
7627					"-enable-ed25519",
7628				},
7629				tls13Variant:                   ver.tls13Variant,
7630				shouldFail:                     shouldSignFail,
7631				expectedError:                  signError,
7632				expectedPeerSignatureAlgorithm: alg.id,
7633			})
7634
7635			testCases = append(testCases, testCase{
7636				testType: serverTest,
7637				name:     "ClientAuth-Verify" + suffix,
7638				config: Config{
7639					MaxVersion:   ver.version,
7640					Certificates: []Certificate{getRunnerCertificate(alg.cert)},
7641					SignSignatureAlgorithms: []signatureAlgorithm{
7642						alg.id,
7643					},
7644					Bugs: ProtocolBugs{
7645						SkipECDSACurveCheck:          shouldVerifyFail,
7646						IgnoreSignatureVersionChecks: shouldVerifyFail,
7647						// Some signature algorithms may not be advertised.
7648						IgnorePeerSignatureAlgorithmPreferences: shouldVerifyFail,
7649					},
7650				},
7651				tls13Variant: ver.tls13Variant,
7652				flags: []string{
7653					"-require-any-client-certificate",
7654					"-expect-peer-signature-algorithm", strconv.Itoa(int(alg.id)),
7655					"-enable-all-curves",
7656					"-enable-ed25519",
7657				},
7658				// Resume the session to assert the peer signature
7659				// algorithm is reported on both handshakes.
7660				resumeSession: !shouldVerifyFail,
7661				shouldFail:    shouldVerifyFail,
7662				expectedError: verifyError,
7663			})
7664
7665			// No signing cipher for SSL 3.0.
7666			if ver.version > VersionSSL30 {
7667				testCases = append(testCases, testCase{
7668					testType: serverTest,
7669					name:     "ServerAuth-Sign" + suffix,
7670					config: Config{
7671						MaxVersion:   ver.version,
7672						CipherSuites: signingCiphers,
7673						VerifySignatureAlgorithms: []signatureAlgorithm{
7674							fakeSigAlg1,
7675							alg.id,
7676							fakeSigAlg2,
7677						},
7678					},
7679					tls13Variant: ver.tls13Variant,
7680					flags: []string{
7681						"-cert-file", path.Join(*resourceDir, getShimCertificate(alg.cert)),
7682						"-key-file", path.Join(*resourceDir, getShimKey(alg.cert)),
7683						"-enable-all-curves",
7684						"-enable-ed25519",
7685					},
7686					shouldFail:                     shouldSignFail,
7687					expectedError:                  signError,
7688					expectedPeerSignatureAlgorithm: alg.id,
7689				})
7690			}
7691
7692			testCases = append(testCases, testCase{
7693				name: "ServerAuth-Verify" + suffix,
7694				config: Config{
7695					MaxVersion:   ver.version,
7696					Certificates: []Certificate{getRunnerCertificate(alg.cert)},
7697					CipherSuites: signingCiphers,
7698					SignSignatureAlgorithms: []signatureAlgorithm{
7699						alg.id,
7700					},
7701					Bugs: ProtocolBugs{
7702						SkipECDSACurveCheck:          shouldVerifyFail,
7703						IgnoreSignatureVersionChecks: shouldVerifyFail,
7704						// Some signature algorithms may not be advertised.
7705						IgnorePeerSignatureAlgorithmPreferences: shouldVerifyFail,
7706					},
7707				},
7708				tls13Variant: ver.tls13Variant,
7709				flags: []string{
7710					"-expect-peer-signature-algorithm", strconv.Itoa(int(alg.id)),
7711					"-enable-all-curves",
7712					"-enable-ed25519",
7713				},
7714				// Resume the session to assert the peer signature
7715				// algorithm is reported on both handshakes.
7716				resumeSession: !shouldVerifyFail,
7717				shouldFail:    shouldVerifyFail,
7718				expectedError: verifyError,
7719			})
7720
7721			if !shouldVerifyFail {
7722				testCases = append(testCases, testCase{
7723					testType: serverTest,
7724					name:     "ClientAuth-InvalidSignature" + suffix,
7725					config: Config{
7726						MaxVersion:   ver.version,
7727						Certificates: []Certificate{getRunnerCertificate(alg.cert)},
7728						SignSignatureAlgorithms: []signatureAlgorithm{
7729							alg.id,
7730						},
7731						Bugs: ProtocolBugs{
7732							InvalidSignature: true,
7733						},
7734					},
7735					tls13Variant: ver.tls13Variant,
7736					flags: []string{
7737						"-require-any-client-certificate",
7738						"-enable-all-curves",
7739						"-enable-ed25519",
7740					},
7741					shouldFail:    true,
7742					expectedError: ":BAD_SIGNATURE:",
7743				})
7744
7745				testCases = append(testCases, testCase{
7746					name: "ServerAuth-InvalidSignature" + suffix,
7747					config: Config{
7748						MaxVersion:   ver.version,
7749						Certificates: []Certificate{getRunnerCertificate(alg.cert)},
7750						CipherSuites: signingCiphers,
7751						SignSignatureAlgorithms: []signatureAlgorithm{
7752							alg.id,
7753						},
7754						Bugs: ProtocolBugs{
7755							InvalidSignature: true,
7756						},
7757					},
7758					tls13Variant: ver.tls13Variant,
7759					flags: []string{
7760						"-enable-all-curves",
7761						"-enable-ed25519",
7762					},
7763					shouldFail:    true,
7764					expectedError: ":BAD_SIGNATURE:",
7765				})
7766			}
7767
7768			if ver.version >= VersionTLS12 && !shouldSignFail {
7769				testCases = append(testCases, testCase{
7770					name: "ClientAuth-Sign-Negotiate" + suffix,
7771					config: Config{
7772						MaxVersion:                ver.version,
7773						ClientAuth:                RequireAnyClientCert,
7774						VerifySignatureAlgorithms: allAlgorithms,
7775					},
7776					tls13Variant: ver.tls13Variant,
7777					flags: []string{
7778						"-cert-file", path.Join(*resourceDir, getShimCertificate(alg.cert)),
7779						"-key-file", path.Join(*resourceDir, getShimKey(alg.cert)),
7780						"-enable-all-curves",
7781						"-enable-ed25519",
7782						"-signing-prefs", strconv.Itoa(int(alg.id)),
7783					},
7784					expectedPeerSignatureAlgorithm: alg.id,
7785				})
7786
7787				testCases = append(testCases, testCase{
7788					testType: serverTest,
7789					name:     "ServerAuth-Sign-Negotiate" + suffix,
7790					config: Config{
7791						MaxVersion:                ver.version,
7792						CipherSuites:              signingCiphers,
7793						VerifySignatureAlgorithms: allAlgorithms,
7794					},
7795					tls13Variant: ver.tls13Variant,
7796					flags: []string{
7797						"-cert-file", path.Join(*resourceDir, getShimCertificate(alg.cert)),
7798						"-key-file", path.Join(*resourceDir, getShimKey(alg.cert)),
7799						"-enable-all-curves",
7800						"-enable-ed25519",
7801						"-signing-prefs", strconv.Itoa(int(alg.id)),
7802					},
7803					expectedPeerSignatureAlgorithm: alg.id,
7804				})
7805			}
7806		}
7807	}
7808
7809	// Test that algorithm selection takes the key type into account.
7810	testCases = append(testCases, testCase{
7811		name: "ClientAuth-SignatureType",
7812		config: Config{
7813			ClientAuth: RequireAnyClientCert,
7814			MaxVersion: VersionTLS12,
7815			VerifySignatureAlgorithms: []signatureAlgorithm{
7816				signatureECDSAWithP521AndSHA512,
7817				signatureRSAPKCS1WithSHA384,
7818				signatureECDSAWithSHA1,
7819			},
7820		},
7821		flags: []string{
7822			"-cert-file", path.Join(*resourceDir, rsaCertificateFile),
7823			"-key-file", path.Join(*resourceDir, rsaKeyFile),
7824		},
7825		expectedPeerSignatureAlgorithm: signatureRSAPKCS1WithSHA384,
7826	})
7827
7828	testCases = append(testCases, testCase{
7829		name: "ClientAuth-SignatureType-TLS13",
7830		config: Config{
7831			ClientAuth: RequireAnyClientCert,
7832			MaxVersion: VersionTLS13,
7833			VerifySignatureAlgorithms: []signatureAlgorithm{
7834				signatureECDSAWithP521AndSHA512,
7835				signatureRSAPKCS1WithSHA384,
7836				signatureRSAPSSWithSHA384,
7837				signatureECDSAWithSHA1,
7838			},
7839		},
7840		flags: []string{
7841			"-cert-file", path.Join(*resourceDir, rsaCertificateFile),
7842			"-key-file", path.Join(*resourceDir, rsaKeyFile),
7843		},
7844		expectedPeerSignatureAlgorithm: signatureRSAPSSWithSHA384,
7845	})
7846
7847	testCases = append(testCases, testCase{
7848		testType: serverTest,
7849		name:     "ServerAuth-SignatureType",
7850		config: Config{
7851			MaxVersion:   VersionTLS12,
7852			CipherSuites: []uint16{TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256},
7853			VerifySignatureAlgorithms: []signatureAlgorithm{
7854				signatureECDSAWithP521AndSHA512,
7855				signatureRSAPKCS1WithSHA384,
7856				signatureECDSAWithSHA1,
7857			},
7858		},
7859		expectedPeerSignatureAlgorithm: signatureRSAPKCS1WithSHA384,
7860	})
7861
7862	testCases = append(testCases, testCase{
7863		testType: serverTest,
7864		name:     "ServerAuth-SignatureType-TLS13",
7865		config: Config{
7866			MaxVersion: VersionTLS13,
7867			VerifySignatureAlgorithms: []signatureAlgorithm{
7868				signatureECDSAWithP521AndSHA512,
7869				signatureRSAPKCS1WithSHA384,
7870				signatureRSAPSSWithSHA384,
7871				signatureECDSAWithSHA1,
7872			},
7873		},
7874		expectedPeerSignatureAlgorithm: signatureRSAPSSWithSHA384,
7875	})
7876
7877	// Test that signature verification takes the key type into account.
7878	testCases = append(testCases, testCase{
7879		testType: serverTest,
7880		name:     "Verify-ClientAuth-SignatureType",
7881		config: Config{
7882			MaxVersion:   VersionTLS12,
7883			Certificates: []Certificate{rsaCertificate},
7884			SignSignatureAlgorithms: []signatureAlgorithm{
7885				signatureRSAPKCS1WithSHA256,
7886			},
7887			Bugs: ProtocolBugs{
7888				SendSignatureAlgorithm: signatureECDSAWithP256AndSHA256,
7889			},
7890		},
7891		flags: []string{
7892			"-require-any-client-certificate",
7893		},
7894		shouldFail:    true,
7895		expectedError: ":WRONG_SIGNATURE_TYPE:",
7896	})
7897
7898	testCases = append(testCases, testCase{
7899		testType: serverTest,
7900		name:     "Verify-ClientAuth-SignatureType-TLS13",
7901		config: Config{
7902			MaxVersion:   VersionTLS13,
7903			Certificates: []Certificate{rsaCertificate},
7904			SignSignatureAlgorithms: []signatureAlgorithm{
7905				signatureRSAPSSWithSHA256,
7906			},
7907			Bugs: ProtocolBugs{
7908				SendSignatureAlgorithm: signatureECDSAWithP256AndSHA256,
7909			},
7910		},
7911		flags: []string{
7912			"-require-any-client-certificate",
7913		},
7914		shouldFail:    true,
7915		expectedError: ":WRONG_SIGNATURE_TYPE:",
7916	})
7917
7918	testCases = append(testCases, testCase{
7919		name: "Verify-ServerAuth-SignatureType",
7920		config: Config{
7921			MaxVersion:   VersionTLS12,
7922			CipherSuites: []uint16{TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256},
7923			SignSignatureAlgorithms: []signatureAlgorithm{
7924				signatureRSAPKCS1WithSHA256,
7925			},
7926			Bugs: ProtocolBugs{
7927				SendSignatureAlgorithm: signatureECDSAWithP256AndSHA256,
7928			},
7929		},
7930		shouldFail:    true,
7931		expectedError: ":WRONG_SIGNATURE_TYPE:",
7932	})
7933
7934	testCases = append(testCases, testCase{
7935		name: "Verify-ServerAuth-SignatureType-TLS13",
7936		config: Config{
7937			MaxVersion: VersionTLS13,
7938			SignSignatureAlgorithms: []signatureAlgorithm{
7939				signatureRSAPSSWithSHA256,
7940			},
7941			Bugs: ProtocolBugs{
7942				SendSignatureAlgorithm: signatureECDSAWithP256AndSHA256,
7943			},
7944		},
7945		shouldFail:    true,
7946		expectedError: ":WRONG_SIGNATURE_TYPE:",
7947	})
7948
7949	// Test that, if the list is missing, the peer falls back to SHA-1 in
7950	// TLS 1.2, but not TLS 1.3.
7951	testCases = append(testCases, testCase{
7952		name: "ClientAuth-SHA1-Fallback-RSA",
7953		config: Config{
7954			MaxVersion: VersionTLS12,
7955			ClientAuth: RequireAnyClientCert,
7956			VerifySignatureAlgorithms: []signatureAlgorithm{
7957				signatureRSAPKCS1WithSHA1,
7958			},
7959			Bugs: ProtocolBugs{
7960				NoSignatureAlgorithms: true,
7961			},
7962		},
7963		flags: []string{
7964			"-cert-file", path.Join(*resourceDir, rsaCertificateFile),
7965			"-key-file", path.Join(*resourceDir, rsaKeyFile),
7966		},
7967	})
7968
7969	testCases = append(testCases, testCase{
7970		testType: serverTest,
7971		name:     "ServerAuth-SHA1-Fallback-RSA",
7972		config: Config{
7973			MaxVersion: VersionTLS12,
7974			VerifySignatureAlgorithms: []signatureAlgorithm{
7975				signatureRSAPKCS1WithSHA1,
7976			},
7977			Bugs: ProtocolBugs{
7978				NoSignatureAlgorithms: true,
7979			},
7980		},
7981		flags: []string{
7982			"-cert-file", path.Join(*resourceDir, rsaCertificateFile),
7983			"-key-file", path.Join(*resourceDir, rsaKeyFile),
7984		},
7985	})
7986
7987	testCases = append(testCases, testCase{
7988		name: "ClientAuth-SHA1-Fallback-ECDSA",
7989		config: Config{
7990			MaxVersion: VersionTLS12,
7991			ClientAuth: RequireAnyClientCert,
7992			VerifySignatureAlgorithms: []signatureAlgorithm{
7993				signatureECDSAWithSHA1,
7994			},
7995			Bugs: ProtocolBugs{
7996				NoSignatureAlgorithms: true,
7997			},
7998		},
7999		flags: []string{
8000			"-cert-file", path.Join(*resourceDir, ecdsaP256CertificateFile),
8001			"-key-file", path.Join(*resourceDir, ecdsaP256KeyFile),
8002		},
8003	})
8004
8005	testCases = append(testCases, testCase{
8006		testType: serverTest,
8007		name:     "ServerAuth-SHA1-Fallback-ECDSA",
8008		config: Config{
8009			MaxVersion: VersionTLS12,
8010			VerifySignatureAlgorithms: []signatureAlgorithm{
8011				signatureECDSAWithSHA1,
8012			},
8013			Bugs: ProtocolBugs{
8014				NoSignatureAlgorithms: true,
8015			},
8016		},
8017		flags: []string{
8018			"-cert-file", path.Join(*resourceDir, ecdsaP256CertificateFile),
8019			"-key-file", path.Join(*resourceDir, ecdsaP256KeyFile),
8020		},
8021	})
8022
8023	testCases = append(testCases, testCase{
8024		name: "ClientAuth-NoFallback-TLS13",
8025		config: Config{
8026			MaxVersion: VersionTLS13,
8027			ClientAuth: RequireAnyClientCert,
8028			VerifySignatureAlgorithms: []signatureAlgorithm{
8029				signatureRSAPKCS1WithSHA1,
8030			},
8031			Bugs: ProtocolBugs{
8032				NoSignatureAlgorithms: true,
8033			},
8034		},
8035		flags: []string{
8036			"-cert-file", path.Join(*resourceDir, rsaCertificateFile),
8037			"-key-file", path.Join(*resourceDir, rsaKeyFile),
8038		},
8039		shouldFail: true,
8040		// An empty CertificateRequest signature algorithm list is a
8041		// syntax error in TLS 1.3.
8042		expectedError:      ":DECODE_ERROR:",
8043		expectedLocalError: "remote error: error decoding message",
8044	})
8045
8046	testCases = append(testCases, testCase{
8047		testType: serverTest,
8048		name:     "ServerAuth-NoFallback-TLS13",
8049		config: Config{
8050			MaxVersion: VersionTLS13,
8051			VerifySignatureAlgorithms: []signatureAlgorithm{
8052				signatureRSAPKCS1WithSHA1,
8053			},
8054			Bugs: ProtocolBugs{
8055				NoSignatureAlgorithms: true,
8056			},
8057		},
8058		shouldFail:    true,
8059		expectedError: ":NO_COMMON_SIGNATURE_ALGORITHMS:",
8060	})
8061
8062	// Test that hash preferences are enforced. BoringSSL does not implement
8063	// MD5 signatures.
8064	testCases = append(testCases, testCase{
8065		testType: serverTest,
8066		name:     "ClientAuth-Enforced",
8067		config: Config{
8068			MaxVersion:   VersionTLS12,
8069			Certificates: []Certificate{rsaCertificate},
8070			SignSignatureAlgorithms: []signatureAlgorithm{
8071				signatureRSAPKCS1WithMD5,
8072			},
8073			Bugs: ProtocolBugs{
8074				IgnorePeerSignatureAlgorithmPreferences: true,
8075			},
8076		},
8077		flags:         []string{"-require-any-client-certificate"},
8078		shouldFail:    true,
8079		expectedError: ":WRONG_SIGNATURE_TYPE:",
8080	})
8081
8082	testCases = append(testCases, testCase{
8083		name: "ServerAuth-Enforced",
8084		config: Config{
8085			MaxVersion:   VersionTLS12,
8086			CipherSuites: []uint16{TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256},
8087			SignSignatureAlgorithms: []signatureAlgorithm{
8088				signatureRSAPKCS1WithMD5,
8089			},
8090			Bugs: ProtocolBugs{
8091				IgnorePeerSignatureAlgorithmPreferences: true,
8092			},
8093		},
8094		shouldFail:    true,
8095		expectedError: ":WRONG_SIGNATURE_TYPE:",
8096	})
8097	testCases = append(testCases, testCase{
8098		testType: serverTest,
8099		name:     "ClientAuth-Enforced-TLS13",
8100		config: Config{
8101			MaxVersion:   VersionTLS13,
8102			Certificates: []Certificate{rsaCertificate},
8103			SignSignatureAlgorithms: []signatureAlgorithm{
8104				signatureRSAPKCS1WithMD5,
8105			},
8106			Bugs: ProtocolBugs{
8107				IgnorePeerSignatureAlgorithmPreferences: true,
8108				IgnoreSignatureVersionChecks:            true,
8109			},
8110		},
8111		flags:         []string{"-require-any-client-certificate"},
8112		shouldFail:    true,
8113		expectedError: ":WRONG_SIGNATURE_TYPE:",
8114	})
8115
8116	testCases = append(testCases, testCase{
8117		name: "ServerAuth-Enforced-TLS13",
8118		config: Config{
8119			MaxVersion: VersionTLS13,
8120			SignSignatureAlgorithms: []signatureAlgorithm{
8121				signatureRSAPKCS1WithMD5,
8122			},
8123			Bugs: ProtocolBugs{
8124				IgnorePeerSignatureAlgorithmPreferences: true,
8125				IgnoreSignatureVersionChecks:            true,
8126			},
8127		},
8128		shouldFail:    true,
8129		expectedError: ":WRONG_SIGNATURE_TYPE:",
8130	})
8131
8132	// Test that the agreed upon digest respects the client preferences and
8133	// the server digests.
8134	testCases = append(testCases, testCase{
8135		name: "NoCommonAlgorithms-Digests",
8136		config: Config{
8137			MaxVersion: VersionTLS12,
8138			ClientAuth: RequireAnyClientCert,
8139			VerifySignatureAlgorithms: []signatureAlgorithm{
8140				signatureRSAPKCS1WithSHA512,
8141				signatureRSAPKCS1WithSHA1,
8142			},
8143		},
8144		flags: []string{
8145			"-cert-file", path.Join(*resourceDir, rsaCertificateFile),
8146			"-key-file", path.Join(*resourceDir, rsaKeyFile),
8147			"-digest-prefs", "SHA256",
8148		},
8149		shouldFail:    true,
8150		expectedError: ":NO_COMMON_SIGNATURE_ALGORITHMS:",
8151	})
8152	testCases = append(testCases, testCase{
8153		name: "NoCommonAlgorithms",
8154		config: Config{
8155			MaxVersion: VersionTLS12,
8156			ClientAuth: RequireAnyClientCert,
8157			VerifySignatureAlgorithms: []signatureAlgorithm{
8158				signatureRSAPKCS1WithSHA512,
8159				signatureRSAPKCS1WithSHA1,
8160			},
8161		},
8162		flags: []string{
8163			"-cert-file", path.Join(*resourceDir, rsaCertificateFile),
8164			"-key-file", path.Join(*resourceDir, rsaKeyFile),
8165			"-signing-prefs", strconv.Itoa(int(signatureRSAPKCS1WithSHA256)),
8166		},
8167		shouldFail:    true,
8168		expectedError: ":NO_COMMON_SIGNATURE_ALGORITHMS:",
8169	})
8170	testCases = append(testCases, testCase{
8171		name: "NoCommonAlgorithms-TLS13",
8172		config: Config{
8173			MaxVersion: VersionTLS13,
8174			ClientAuth: RequireAnyClientCert,
8175			VerifySignatureAlgorithms: []signatureAlgorithm{
8176				signatureRSAPSSWithSHA512,
8177				signatureRSAPSSWithSHA384,
8178			},
8179		},
8180		flags: []string{
8181			"-cert-file", path.Join(*resourceDir, rsaCertificateFile),
8182			"-key-file", path.Join(*resourceDir, rsaKeyFile),
8183			"-signing-prefs", strconv.Itoa(int(signatureRSAPSSWithSHA256)),
8184		},
8185		shouldFail:    true,
8186		expectedError: ":NO_COMMON_SIGNATURE_ALGORITHMS:",
8187	})
8188	testCases = append(testCases, testCase{
8189		name: "Agree-Digest-SHA256",
8190		config: Config{
8191			MaxVersion: VersionTLS12,
8192			ClientAuth: RequireAnyClientCert,
8193			VerifySignatureAlgorithms: []signatureAlgorithm{
8194				signatureRSAPKCS1WithSHA1,
8195				signatureRSAPKCS1WithSHA256,
8196			},
8197		},
8198		flags: []string{
8199			"-cert-file", path.Join(*resourceDir, rsaCertificateFile),
8200			"-key-file", path.Join(*resourceDir, rsaKeyFile),
8201			"-digest-prefs", "SHA256,SHA1",
8202		},
8203		expectedPeerSignatureAlgorithm: signatureRSAPKCS1WithSHA256,
8204	})
8205	testCases = append(testCases, testCase{
8206		name: "Agree-Digest-SHA1",
8207		config: Config{
8208			MaxVersion: VersionTLS12,
8209			ClientAuth: RequireAnyClientCert,
8210			VerifySignatureAlgorithms: []signatureAlgorithm{
8211				signatureRSAPKCS1WithSHA1,
8212			},
8213		},
8214		flags: []string{
8215			"-cert-file", path.Join(*resourceDir, rsaCertificateFile),
8216			"-key-file", path.Join(*resourceDir, rsaKeyFile),
8217			"-digest-prefs", "SHA512,SHA256,SHA1",
8218		},
8219		expectedPeerSignatureAlgorithm: signatureRSAPKCS1WithSHA1,
8220	})
8221	testCases = append(testCases, testCase{
8222		name: "Agree-Digest-Default",
8223		config: Config{
8224			MaxVersion: VersionTLS12,
8225			ClientAuth: RequireAnyClientCert,
8226			VerifySignatureAlgorithms: []signatureAlgorithm{
8227				signatureRSAPKCS1WithSHA256,
8228				signatureECDSAWithP256AndSHA256,
8229				signatureRSAPKCS1WithSHA1,
8230				signatureECDSAWithSHA1,
8231			},
8232		},
8233		flags: []string{
8234			"-cert-file", path.Join(*resourceDir, rsaCertificateFile),
8235			"-key-file", path.Join(*resourceDir, rsaKeyFile),
8236		},
8237		expectedPeerSignatureAlgorithm: signatureRSAPKCS1WithSHA256,
8238	})
8239
8240	// Test that the signing preference list may include extra algorithms
8241	// without negotiation problems.
8242	testCases = append(testCases, testCase{
8243		testType: serverTest,
8244		name:     "FilterExtraAlgorithms",
8245		config: Config{
8246			MaxVersion: VersionTLS12,
8247			VerifySignatureAlgorithms: []signatureAlgorithm{
8248				signatureRSAPKCS1WithSHA256,
8249			},
8250		},
8251		flags: []string{
8252			"-cert-file", path.Join(*resourceDir, rsaCertificateFile),
8253			"-key-file", path.Join(*resourceDir, rsaKeyFile),
8254			"-signing-prefs", strconv.Itoa(int(fakeSigAlg1)),
8255			"-signing-prefs", strconv.Itoa(int(signatureECDSAWithP256AndSHA256)),
8256			"-signing-prefs", strconv.Itoa(int(signatureRSAPKCS1WithSHA256)),
8257			"-signing-prefs", strconv.Itoa(int(fakeSigAlg2)),
8258		},
8259		expectedPeerSignatureAlgorithm: signatureRSAPKCS1WithSHA256,
8260	})
8261
8262	// In TLS 1.2 and below, ECDSA uses the curve list rather than the
8263	// signature algorithms.
8264	testCases = append(testCases, testCase{
8265		name: "CheckLeafCurve",
8266		config: Config{
8267			MaxVersion:   VersionTLS12,
8268			CipherSuites: []uint16{TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256},
8269			Certificates: []Certificate{ecdsaP256Certificate},
8270		},
8271		flags:         []string{"-p384-only"},
8272		shouldFail:    true,
8273		expectedError: ":BAD_ECC_CERT:",
8274	})
8275
8276	// In TLS 1.3, ECDSA does not use the ECDHE curve list.
8277	testCases = append(testCases, testCase{
8278		name: "CheckLeafCurve-TLS13",
8279		config: Config{
8280			MaxVersion:   VersionTLS13,
8281			Certificates: []Certificate{ecdsaP256Certificate},
8282		},
8283		flags: []string{"-p384-only"},
8284	})
8285
8286	// In TLS 1.2, the ECDSA curve is not in the signature algorithm.
8287	testCases = append(testCases, testCase{
8288		name: "ECDSACurveMismatch-Verify-TLS12",
8289		config: Config{
8290			MaxVersion:   VersionTLS12,
8291			CipherSuites: []uint16{TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256},
8292			Certificates: []Certificate{ecdsaP256Certificate},
8293			SignSignatureAlgorithms: []signatureAlgorithm{
8294				signatureECDSAWithP384AndSHA384,
8295			},
8296		},
8297	})
8298
8299	// In TLS 1.3, the ECDSA curve comes from the signature algorithm.
8300	testCases = append(testCases, testCase{
8301		name: "ECDSACurveMismatch-Verify-TLS13",
8302		config: Config{
8303			MaxVersion:   VersionTLS13,
8304			Certificates: []Certificate{ecdsaP256Certificate},
8305			SignSignatureAlgorithms: []signatureAlgorithm{
8306				signatureECDSAWithP384AndSHA384,
8307			},
8308			Bugs: ProtocolBugs{
8309				SkipECDSACurveCheck: true,
8310			},
8311		},
8312		shouldFail:    true,
8313		expectedError: ":WRONG_SIGNATURE_TYPE:",
8314	})
8315
8316	// Signature algorithm selection in TLS 1.3 should take the curve into
8317	// account.
8318	testCases = append(testCases, testCase{
8319		testType: serverTest,
8320		name:     "ECDSACurveMismatch-Sign-TLS13",
8321		config: Config{
8322			MaxVersion: VersionTLS13,
8323			VerifySignatureAlgorithms: []signatureAlgorithm{
8324				signatureECDSAWithP384AndSHA384,
8325				signatureECDSAWithP256AndSHA256,
8326			},
8327		},
8328		flags: []string{
8329			"-cert-file", path.Join(*resourceDir, ecdsaP256CertificateFile),
8330			"-key-file", path.Join(*resourceDir, ecdsaP256KeyFile),
8331		},
8332		expectedPeerSignatureAlgorithm: signatureECDSAWithP256AndSHA256,
8333	})
8334
8335	// RSASSA-PSS with SHA-512 is too large for 1024-bit RSA. Test that the
8336	// server does not attempt to sign in that case.
8337	testCases = append(testCases, testCase{
8338		testType: serverTest,
8339		name:     "RSA-PSS-Large",
8340		config: Config{
8341			MaxVersion: VersionTLS13,
8342			VerifySignatureAlgorithms: []signatureAlgorithm{
8343				signatureRSAPSSWithSHA512,
8344			},
8345		},
8346		flags: []string{
8347			"-cert-file", path.Join(*resourceDir, rsa1024CertificateFile),
8348			"-key-file", path.Join(*resourceDir, rsa1024KeyFile),
8349		},
8350		shouldFail:    true,
8351		expectedError: ":NO_COMMON_SIGNATURE_ALGORITHMS:",
8352	})
8353
8354	// Test that RSA-PSS is enabled by default for TLS 1.2.
8355	testCases = append(testCases, testCase{
8356		testType: clientTest,
8357		name:     "RSA-PSS-Default-Verify",
8358		config: Config{
8359			MaxVersion: VersionTLS12,
8360			SignSignatureAlgorithms: []signatureAlgorithm{
8361				signatureRSAPSSWithSHA256,
8362			},
8363		},
8364		flags: []string{"-max-version", strconv.Itoa(VersionTLS12)},
8365	})
8366
8367	testCases = append(testCases, testCase{
8368		testType: serverTest,
8369		name:     "RSA-PSS-Default-Sign",
8370		config: Config{
8371			MaxVersion: VersionTLS12,
8372			VerifySignatureAlgorithms: []signatureAlgorithm{
8373				signatureRSAPSSWithSHA256,
8374			},
8375		},
8376		flags: []string{"-max-version", strconv.Itoa(VersionTLS12)},
8377	})
8378
8379	// TLS 1.1 and below has no way to advertise support for or negotiate
8380	// Ed25519's signature algorithm.
8381	testCases = append(testCases, testCase{
8382		testType: clientTest,
8383		name:     "NoEd25519-TLS11-ServerAuth-Verify",
8384		config: Config{
8385			MaxVersion:   VersionTLS11,
8386			Certificates: []Certificate{ed25519Certificate},
8387			Bugs: ProtocolBugs{
8388				// Sign with Ed25519 even though it is TLS 1.1.
8389				UseLegacySigningAlgorithm: signatureEd25519,
8390			},
8391		},
8392		flags:         []string{"-enable-ed25519"},
8393		shouldFail:    true,
8394		expectedError: ":PEER_ERROR_UNSUPPORTED_CERTIFICATE_TYPE:",
8395	})
8396	testCases = append(testCases, testCase{
8397		testType: serverTest,
8398		name:     "NoEd25519-TLS11-ServerAuth-Sign",
8399		config: Config{
8400			MaxVersion: VersionTLS11,
8401		},
8402		flags: []string{
8403			"-cert-file", path.Join(*resourceDir, ed25519CertificateFile),
8404			"-key-file", path.Join(*resourceDir, ed25519KeyFile),
8405		},
8406		shouldFail:    true,
8407		expectedError: ":NO_COMMON_SIGNATURE_ALGORITHMS:",
8408	})
8409	testCases = append(testCases, testCase{
8410		testType: serverTest,
8411		name:     "NoEd25519-TLS11-ClientAuth-Verify",
8412		config: Config{
8413			MaxVersion:   VersionTLS11,
8414			Certificates: []Certificate{ed25519Certificate},
8415			Bugs: ProtocolBugs{
8416				// Sign with Ed25519 even though it is TLS 1.1.
8417				UseLegacySigningAlgorithm: signatureEd25519,
8418			},
8419		},
8420		flags: []string{
8421			"-enable-ed25519",
8422			"-require-any-client-certificate",
8423		},
8424		shouldFail:    true,
8425		expectedError: ":PEER_ERROR_UNSUPPORTED_CERTIFICATE_TYPE:",
8426	})
8427	testCases = append(testCases, testCase{
8428		testType: clientTest,
8429		name:     "NoEd25519-TLS11-ClientAuth-Sign",
8430		config: Config{
8431			MaxVersion: VersionTLS11,
8432			ClientAuth: RequireAnyClientCert,
8433		},
8434		flags: []string{
8435			"-cert-file", path.Join(*resourceDir, ed25519CertificateFile),
8436			"-key-file", path.Join(*resourceDir, ed25519KeyFile),
8437		},
8438		shouldFail:    true,
8439		expectedError: ":NO_COMMON_SIGNATURE_ALGORITHMS:",
8440	})
8441
8442	// Test Ed25519 is not advertised by default.
8443	testCases = append(testCases, testCase{
8444		testType: clientTest,
8445		name:     "Ed25519DefaultDisable-NoAdvertise",
8446		config: Config{
8447			Certificates: []Certificate{ed25519Certificate},
8448		},
8449		shouldFail:         true,
8450		expectedLocalError: "tls: no common signature algorithms",
8451	})
8452
8453	// Test Ed25519, when disabled, is not accepted if the peer ignores our
8454	// preferences.
8455	testCases = append(testCases, testCase{
8456		testType: clientTest,
8457		name:     "Ed25519DefaultDisable-NoAccept",
8458		config: Config{
8459			Certificates: []Certificate{ed25519Certificate},
8460			Bugs: ProtocolBugs{
8461				IgnorePeerSignatureAlgorithmPreferences: true,
8462			},
8463		},
8464		shouldFail:         true,
8465		expectedLocalError: "remote error: illegal parameter",
8466		expectedError:      ":WRONG_SIGNATURE_TYPE:",
8467	})
8468
8469	// Test that configuring verify preferences changes what the client
8470	// advertises.
8471	testCases = append(testCases, testCase{
8472		name: "VerifyPreferences-Advertised",
8473		config: Config{
8474			Certificates: []Certificate{rsaCertificate},
8475			SignSignatureAlgorithms: []signatureAlgorithm{
8476				signatureRSAPSSWithSHA256,
8477				signatureRSAPSSWithSHA384,
8478				signatureRSAPSSWithSHA512,
8479			},
8480		},
8481		flags: []string{
8482			"-verify-prefs", strconv.Itoa(int(signatureRSAPSSWithSHA384)),
8483			"-expect-peer-signature-algorithm", strconv.Itoa(int(signatureRSAPSSWithSHA384)),
8484		},
8485	})
8486
8487	// Test that the client advertises a set which the runner can find
8488	// nothing in common with.
8489	testCases = append(testCases, testCase{
8490		name: "VerifyPreferences-NoCommonAlgorithms",
8491		config: Config{
8492			Certificates: []Certificate{rsaCertificate},
8493			SignSignatureAlgorithms: []signatureAlgorithm{
8494				signatureRSAPSSWithSHA256,
8495				signatureRSAPSSWithSHA512,
8496			},
8497		},
8498		flags: []string{
8499			"-verify-prefs", strconv.Itoa(int(signatureRSAPSSWithSHA384)),
8500		},
8501		shouldFail:         true,
8502		expectedLocalError: "tls: no common signature algorithms",
8503	})
8504
8505	// Test that the client enforces its preferences when configured.
8506	testCases = append(testCases, testCase{
8507		name: "VerifyPreferences-Enforced",
8508		config: Config{
8509			Certificates: []Certificate{rsaCertificate},
8510			SignSignatureAlgorithms: []signatureAlgorithm{
8511				signatureRSAPSSWithSHA256,
8512				signatureRSAPSSWithSHA512,
8513			},
8514			Bugs: ProtocolBugs{
8515				IgnorePeerSignatureAlgorithmPreferences: true,
8516			},
8517		},
8518		flags: []string{
8519			"-verify-prefs", strconv.Itoa(int(signatureRSAPSSWithSHA384)),
8520		},
8521		shouldFail:         true,
8522		expectedLocalError: "remote error: illegal parameter",
8523		expectedError:      ":WRONG_SIGNATURE_TYPE:",
8524	})
8525
8526	// Test that explicitly configuring Ed25519 is as good as changing the
8527	// boolean toggle.
8528	testCases = append(testCases, testCase{
8529		name: "VerifyPreferences-Ed25519",
8530		config: Config{
8531			Certificates: []Certificate{ed25519Certificate},
8532		},
8533		flags: []string{
8534			"-verify-prefs", strconv.Itoa(int(signatureEd25519)),
8535		},
8536	})
8537}
8538
8539// timeouts is the retransmit schedule for BoringSSL. It doubles and
8540// caps at 60 seconds. On the 13th timeout, it gives up.
8541var timeouts = []time.Duration{
8542	1 * time.Second,
8543	2 * time.Second,
8544	4 * time.Second,
8545	8 * time.Second,
8546	16 * time.Second,
8547	32 * time.Second,
8548	60 * time.Second,
8549	60 * time.Second,
8550	60 * time.Second,
8551	60 * time.Second,
8552	60 * time.Second,
8553	60 * time.Second,
8554	60 * time.Second,
8555}
8556
8557// shortTimeouts is an alternate set of timeouts which would occur if the
8558// initial timeout duration was set to 250ms.
8559var shortTimeouts = []time.Duration{
8560	250 * time.Millisecond,
8561	500 * time.Millisecond,
8562	1 * time.Second,
8563	2 * time.Second,
8564	4 * time.Second,
8565	8 * time.Second,
8566	16 * time.Second,
8567	32 * time.Second,
8568	60 * time.Second,
8569	60 * time.Second,
8570	60 * time.Second,
8571	60 * time.Second,
8572	60 * time.Second,
8573}
8574
8575func addDTLSRetransmitTests() {
8576	// These tests work by coordinating some behavior on both the shim and
8577	// the runner.
8578	//
8579	// TimeoutSchedule configures the runner to send a series of timeout
8580	// opcodes to the shim (see packetAdaptor) immediately before reading
8581	// each peer handshake flight N. The timeout opcode both simulates a
8582	// timeout in the shim and acts as a synchronization point to help the
8583	// runner bracket each handshake flight.
8584	//
8585	// We assume the shim does not read from the channel eagerly. It must
8586	// first wait until it has sent flight N and is ready to receive
8587	// handshake flight N+1. At this point, it will process the timeout
8588	// opcode. It must then immediately respond with a timeout ACK and act
8589	// as if the shim was idle for the specified amount of time.
8590	//
8591	// The runner then drops all packets received before the ACK and
8592	// continues waiting for flight N. This ordering results in one attempt
8593	// at sending flight N to be dropped. For the test to complete, the
8594	// shim must send flight N again, testing that the shim implements DTLS
8595	// retransmit on a timeout.
8596
8597	// TODO(davidben): Add DTLS 1.3 versions of these tests. There will
8598	// likely be more epochs to cross and the final message's retransmit may
8599	// be more complex.
8600
8601	// Test that this is indeed the timeout schedule. Stress all
8602	// four patterns of handshake.
8603	for i := 1; i < len(timeouts); i++ {
8604		number := strconv.Itoa(i)
8605		testCases = append(testCases, testCase{
8606			protocol: dtls,
8607			name:     "DTLS-Retransmit-Client-" + number,
8608			config: Config{
8609				MaxVersion: VersionTLS12,
8610				Bugs: ProtocolBugs{
8611					TimeoutSchedule: timeouts[:i],
8612				},
8613			},
8614			resumeSession: true,
8615			flags:         []string{"-async"},
8616		})
8617		testCases = append(testCases, testCase{
8618			protocol: dtls,
8619			testType: serverTest,
8620			name:     "DTLS-Retransmit-Server-" + number,
8621			config: Config{
8622				MaxVersion: VersionTLS12,
8623				Bugs: ProtocolBugs{
8624					TimeoutSchedule: timeouts[:i],
8625				},
8626			},
8627			resumeSession: true,
8628			flags:         []string{"-async"},
8629		})
8630	}
8631
8632	// Test that exceeding the timeout schedule hits a read
8633	// timeout.
8634	testCases = append(testCases, testCase{
8635		protocol: dtls,
8636		name:     "DTLS-Retransmit-Timeout",
8637		config: Config{
8638			MaxVersion: VersionTLS12,
8639			Bugs: ProtocolBugs{
8640				TimeoutSchedule: timeouts,
8641			},
8642		},
8643		resumeSession: true,
8644		flags:         []string{"-async"},
8645		shouldFail:    true,
8646		expectedError: ":READ_TIMEOUT_EXPIRED:",
8647	})
8648
8649	// Test that timeout handling has a fudge factor, due to API
8650	// problems.
8651	testCases = append(testCases, testCase{
8652		protocol: dtls,
8653		name:     "DTLS-Retransmit-Fudge",
8654		config: Config{
8655			MaxVersion: VersionTLS12,
8656			Bugs: ProtocolBugs{
8657				TimeoutSchedule: []time.Duration{
8658					timeouts[0] - 10*time.Millisecond,
8659				},
8660			},
8661		},
8662		resumeSession: true,
8663		flags:         []string{"-async"},
8664	})
8665
8666	// Test that the final Finished retransmitting isn't
8667	// duplicated if the peer badly fragments everything.
8668	testCases = append(testCases, testCase{
8669		testType: serverTest,
8670		protocol: dtls,
8671		name:     "DTLS-Retransmit-Fragmented",
8672		config: Config{
8673			MaxVersion: VersionTLS12,
8674			Bugs: ProtocolBugs{
8675				TimeoutSchedule:          []time.Duration{timeouts[0]},
8676				MaxHandshakeRecordLength: 2,
8677			},
8678		},
8679		flags: []string{"-async"},
8680	})
8681
8682	// Test the timeout schedule when a shorter initial timeout duration is set.
8683	testCases = append(testCases, testCase{
8684		protocol: dtls,
8685		name:     "DTLS-Retransmit-Short-Client",
8686		config: Config{
8687			MaxVersion: VersionTLS12,
8688			Bugs: ProtocolBugs{
8689				TimeoutSchedule: shortTimeouts[:len(shortTimeouts)-1],
8690			},
8691		},
8692		resumeSession: true,
8693		flags: []string{
8694			"-async",
8695			"-initial-timeout-duration-ms", "250",
8696		},
8697	})
8698	testCases = append(testCases, testCase{
8699		protocol: dtls,
8700		testType: serverTest,
8701		name:     "DTLS-Retransmit-Short-Server",
8702		config: Config{
8703			MaxVersion: VersionTLS12,
8704			Bugs: ProtocolBugs{
8705				TimeoutSchedule: shortTimeouts[:len(shortTimeouts)-1],
8706			},
8707		},
8708		resumeSession: true,
8709		flags: []string{
8710			"-async",
8711			"-initial-timeout-duration-ms", "250",
8712		},
8713	})
8714}
8715
8716func addExportKeyingMaterialTests() {
8717	for _, vers := range tlsVersions {
8718		if vers.version == VersionSSL30 {
8719			continue
8720		}
8721		testCases = append(testCases, testCase{
8722			name: "ExportKeyingMaterial-" + vers.name,
8723			config: Config{
8724				MaxVersion: vers.version,
8725			},
8726			tls13Variant:         vers.tls13Variant,
8727			exportKeyingMaterial: 1024,
8728			exportLabel:          "label",
8729			exportContext:        "context",
8730			useExportContext:     true,
8731		})
8732		testCases = append(testCases, testCase{
8733			name: "ExportKeyingMaterial-NoContext-" + vers.name,
8734			config: Config{
8735				MaxVersion: vers.version,
8736			},
8737			tls13Variant:         vers.tls13Variant,
8738			exportKeyingMaterial: 1024,
8739		})
8740		testCases = append(testCases, testCase{
8741			name: "ExportKeyingMaterial-EmptyContext-" + vers.name,
8742			config: Config{
8743				MaxVersion: vers.version,
8744			},
8745			tls13Variant:         vers.tls13Variant,
8746			exportKeyingMaterial: 1024,
8747			useExportContext:     true,
8748		})
8749		testCases = append(testCases, testCase{
8750			name: "ExportKeyingMaterial-Small-" + vers.name,
8751			config: Config{
8752				MaxVersion: vers.version,
8753			},
8754			tls13Variant:         vers.tls13Variant,
8755			exportKeyingMaterial: 1,
8756			exportLabel:          "label",
8757			exportContext:        "context",
8758			useExportContext:     true,
8759		})
8760	}
8761
8762	testCases = append(testCases, testCase{
8763		name: "ExportKeyingMaterial-SSL3",
8764		config: Config{
8765			MaxVersion: VersionSSL30,
8766		},
8767		exportKeyingMaterial: 1024,
8768		exportLabel:          "label",
8769		exportContext:        "context",
8770		useExportContext:     true,
8771		shouldFail:           true,
8772		expectedError:        "failed to export keying material",
8773	})
8774
8775	// Exporters work during a False Start.
8776	testCases = append(testCases, testCase{
8777		name: "ExportKeyingMaterial-FalseStart",
8778		config: Config{
8779			MaxVersion:   VersionTLS12,
8780			CipherSuites: []uint16{TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256},
8781			NextProtos:   []string{"foo"},
8782			Bugs: ProtocolBugs{
8783				ExpectFalseStart: true,
8784			},
8785		},
8786		flags: []string{
8787			"-false-start",
8788			"-advertise-alpn", "\x03foo",
8789			"-expect-alpn", "foo",
8790		},
8791		shimWritesFirst:      true,
8792		exportKeyingMaterial: 1024,
8793		exportLabel:          "label",
8794		exportContext:        "context",
8795		useExportContext:     true,
8796	})
8797
8798	// Exporters do not work in the middle of a renegotiation. Test this by
8799	// triggering the exporter after every SSL_read call and configuring the
8800	// shim to run asynchronously.
8801	testCases = append(testCases, testCase{
8802		name: "ExportKeyingMaterial-Renegotiate",
8803		config: Config{
8804			MaxVersion: VersionTLS12,
8805		},
8806		renegotiate: 1,
8807		flags: []string{
8808			"-async",
8809			"-use-exporter-between-reads",
8810			"-renegotiate-freely",
8811			"-expect-total-renegotiations", "1",
8812		},
8813		shouldFail:    true,
8814		expectedError: "failed to export keying material",
8815	})
8816}
8817
8818func addTLSUniqueTests() {
8819	for _, isClient := range []bool{false, true} {
8820		for _, isResumption := range []bool{false, true} {
8821			for _, hasEMS := range []bool{false, true} {
8822				var suffix string
8823				if isResumption {
8824					suffix = "Resume-"
8825				} else {
8826					suffix = "Full-"
8827				}
8828
8829				if hasEMS {
8830					suffix += "EMS-"
8831				} else {
8832					suffix += "NoEMS-"
8833				}
8834
8835				if isClient {
8836					suffix += "Client"
8837				} else {
8838					suffix += "Server"
8839				}
8840
8841				test := testCase{
8842					name:          "TLSUnique-" + suffix,
8843					testTLSUnique: true,
8844					config: Config{
8845						MaxVersion: VersionTLS12,
8846						Bugs: ProtocolBugs{
8847							NoExtendedMasterSecret: !hasEMS,
8848						},
8849					},
8850				}
8851
8852				if isResumption {
8853					test.resumeSession = true
8854					test.resumeConfig = &Config{
8855						MaxVersion: VersionTLS12,
8856						Bugs: ProtocolBugs{
8857							NoExtendedMasterSecret: !hasEMS,
8858						},
8859					}
8860				}
8861
8862				if isResumption && !hasEMS {
8863					test.shouldFail = true
8864					test.expectedError = "failed to get tls-unique"
8865				}
8866
8867				testCases = append(testCases, test)
8868			}
8869		}
8870	}
8871}
8872
8873func addCustomExtensionTests() {
8874	expectedContents := "custom extension"
8875	emptyString := ""
8876
8877	for _, isClient := range []bool{false, true} {
8878		suffix := "Server"
8879		flag := "-enable-server-custom-extension"
8880		testType := serverTest
8881		if isClient {
8882			suffix = "Client"
8883			flag = "-enable-client-custom-extension"
8884			testType = clientTest
8885		}
8886
8887		testCases = append(testCases, testCase{
8888			testType: testType,
8889			name:     "CustomExtensions-" + suffix,
8890			config: Config{
8891				MaxVersion: VersionTLS12,
8892				Bugs: ProtocolBugs{
8893					CustomExtension:         expectedContents,
8894					ExpectedCustomExtension: &expectedContents,
8895				},
8896			},
8897			flags: []string{flag},
8898		})
8899		testCases = append(testCases, testCase{
8900			testType: testType,
8901			name:     "CustomExtensions-" + suffix + "-TLS13",
8902			config: Config{
8903				MaxVersion: VersionTLS13,
8904				Bugs: ProtocolBugs{
8905					CustomExtension:         expectedContents,
8906					ExpectedCustomExtension: &expectedContents,
8907				},
8908			},
8909			flags: []string{flag},
8910		})
8911
8912		// 0-RTT is not currently supported with Custom Extensions.
8913		testCases = append(testCases, testCase{
8914			testType: testType,
8915			name:     "CustomExtensions-" + suffix + "-EarlyData",
8916			config: Config{
8917				MaxVersion: VersionTLS13,
8918				Bugs: ProtocolBugs{
8919					CustomExtension:         expectedContents,
8920					ExpectedCustomExtension: &expectedContents,
8921				},
8922			},
8923			shouldFail:    true,
8924			expectedError: ":CUSTOM_EXTENSION_ERROR:",
8925			flags:         []string{flag, "-enable-early-data"},
8926		})
8927
8928		// If the parse callback fails, the handshake should also fail.
8929		testCases = append(testCases, testCase{
8930			testType: testType,
8931			name:     "CustomExtensions-ParseError-" + suffix,
8932			config: Config{
8933				MaxVersion: VersionTLS12,
8934				Bugs: ProtocolBugs{
8935					CustomExtension:         expectedContents + "foo",
8936					ExpectedCustomExtension: &expectedContents,
8937				},
8938			},
8939			flags:         []string{flag},
8940			shouldFail:    true,
8941			expectedError: ":CUSTOM_EXTENSION_ERROR:",
8942		})
8943		testCases = append(testCases, testCase{
8944			testType: testType,
8945			name:     "CustomExtensions-ParseError-" + suffix + "-TLS13",
8946			config: Config{
8947				MaxVersion: VersionTLS13,
8948				Bugs: ProtocolBugs{
8949					CustomExtension:         expectedContents + "foo",
8950					ExpectedCustomExtension: &expectedContents,
8951				},
8952			},
8953			flags:         []string{flag},
8954			shouldFail:    true,
8955			expectedError: ":CUSTOM_EXTENSION_ERROR:",
8956		})
8957
8958		// If the add callback fails, the handshake should also fail.
8959		testCases = append(testCases, testCase{
8960			testType: testType,
8961			name:     "CustomExtensions-FailAdd-" + suffix,
8962			config: Config{
8963				MaxVersion: VersionTLS12,
8964				Bugs: ProtocolBugs{
8965					CustomExtension:         expectedContents,
8966					ExpectedCustomExtension: &expectedContents,
8967				},
8968			},
8969			flags:         []string{flag, "-custom-extension-fail-add"},
8970			shouldFail:    true,
8971			expectedError: ":CUSTOM_EXTENSION_ERROR:",
8972		})
8973		testCases = append(testCases, testCase{
8974			testType: testType,
8975			name:     "CustomExtensions-FailAdd-" + suffix + "-TLS13",
8976			config: Config{
8977				MaxVersion: VersionTLS13,
8978				Bugs: ProtocolBugs{
8979					CustomExtension:         expectedContents,
8980					ExpectedCustomExtension: &expectedContents,
8981				},
8982			},
8983			flags:         []string{flag, "-custom-extension-fail-add"},
8984			shouldFail:    true,
8985			expectedError: ":CUSTOM_EXTENSION_ERROR:",
8986		})
8987
8988		// If the add callback returns zero, no extension should be
8989		// added.
8990		skipCustomExtension := expectedContents
8991		if isClient {
8992			// For the case where the client skips sending the
8993			// custom extension, the server must not “echo” it.
8994			skipCustomExtension = ""
8995		}
8996		testCases = append(testCases, testCase{
8997			testType: testType,
8998			name:     "CustomExtensions-Skip-" + suffix,
8999			config: Config{
9000				MaxVersion: VersionTLS12,
9001				Bugs: ProtocolBugs{
9002					CustomExtension:         skipCustomExtension,
9003					ExpectedCustomExtension: &emptyString,
9004				},
9005			},
9006			flags: []string{flag, "-custom-extension-skip"},
9007		})
9008		testCases = append(testCases, testCase{
9009			testType: testType,
9010			name:     "CustomExtensions-Skip-" + suffix + "-TLS13",
9011			config: Config{
9012				MaxVersion: VersionTLS13,
9013				Bugs: ProtocolBugs{
9014					CustomExtension:         skipCustomExtension,
9015					ExpectedCustomExtension: &emptyString,
9016				},
9017			},
9018			flags: []string{flag, "-custom-extension-skip"},
9019		})
9020	}
9021
9022	// The custom extension add callback should not be called if the client
9023	// doesn't send the extension.
9024	testCases = append(testCases, testCase{
9025		testType: serverTest,
9026		name:     "CustomExtensions-NotCalled-Server",
9027		config: Config{
9028			MaxVersion: VersionTLS12,
9029			Bugs: ProtocolBugs{
9030				ExpectedCustomExtension: &emptyString,
9031			},
9032		},
9033		flags: []string{"-enable-server-custom-extension", "-custom-extension-fail-add"},
9034	})
9035
9036	testCases = append(testCases, testCase{
9037		testType: serverTest,
9038		name:     "CustomExtensions-NotCalled-Server-TLS13",
9039		config: Config{
9040			MaxVersion: VersionTLS13,
9041			Bugs: ProtocolBugs{
9042				ExpectedCustomExtension: &emptyString,
9043			},
9044		},
9045		flags: []string{"-enable-server-custom-extension", "-custom-extension-fail-add"},
9046	})
9047
9048	// Test an unknown extension from the server.
9049	testCases = append(testCases, testCase{
9050		testType: clientTest,
9051		name:     "UnknownExtension-Client",
9052		config: Config{
9053			MaxVersion: VersionTLS12,
9054			Bugs: ProtocolBugs{
9055				CustomExtension: expectedContents,
9056			},
9057		},
9058		shouldFail:         true,
9059		expectedError:      ":UNEXPECTED_EXTENSION:",
9060		expectedLocalError: "remote error: unsupported extension",
9061	})
9062	testCases = append(testCases, testCase{
9063		testType: clientTest,
9064		name:     "UnknownExtension-Client-TLS13",
9065		config: Config{
9066			MaxVersion: VersionTLS13,
9067			Bugs: ProtocolBugs{
9068				CustomExtension: expectedContents,
9069			},
9070		},
9071		shouldFail:         true,
9072		expectedError:      ":UNEXPECTED_EXTENSION:",
9073		expectedLocalError: "remote error: unsupported extension",
9074	})
9075	testCases = append(testCases, testCase{
9076		testType: clientTest,
9077		name:     "UnknownUnencryptedExtension-Client-TLS13",
9078		config: Config{
9079			MaxVersion: VersionTLS13,
9080			Bugs: ProtocolBugs{
9081				CustomUnencryptedExtension: expectedContents,
9082			},
9083		},
9084		shouldFail:    true,
9085		expectedError: ":UNEXPECTED_EXTENSION:",
9086		// The shim must send an alert, but alerts at this point do not
9087		// get successfully decrypted by the runner.
9088		expectedLocalError: "local error: bad record MAC",
9089	})
9090	testCases = append(testCases, testCase{
9091		testType: clientTest,
9092		name:     "UnexpectedUnencryptedExtension-Client-TLS13",
9093		config: Config{
9094			MaxVersion: VersionTLS13,
9095			Bugs: ProtocolBugs{
9096				SendUnencryptedALPN: "foo",
9097			},
9098		},
9099		flags: []string{
9100			"-advertise-alpn", "\x03foo\x03bar",
9101		},
9102		shouldFail:    true,
9103		expectedError: ":UNEXPECTED_EXTENSION:",
9104		// The shim must send an alert, but alerts at this point do not
9105		// get successfully decrypted by the runner.
9106		expectedLocalError: "local error: bad record MAC",
9107	})
9108
9109	// Test a known but unoffered extension from the server.
9110	testCases = append(testCases, testCase{
9111		testType: clientTest,
9112		name:     "UnofferedExtension-Client",
9113		config: Config{
9114			MaxVersion: VersionTLS12,
9115			Bugs: ProtocolBugs{
9116				SendALPN: "alpn",
9117			},
9118		},
9119		shouldFail:         true,
9120		expectedError:      ":UNEXPECTED_EXTENSION:",
9121		expectedLocalError: "remote error: unsupported extension",
9122	})
9123	testCases = append(testCases, testCase{
9124		testType: clientTest,
9125		name:     "UnofferedExtension-Client-TLS13",
9126		config: Config{
9127			MaxVersion: VersionTLS13,
9128			Bugs: ProtocolBugs{
9129				SendALPN: "alpn",
9130			},
9131		},
9132		shouldFail:         true,
9133		expectedError:      ":UNEXPECTED_EXTENSION:",
9134		expectedLocalError: "remote error: unsupported extension",
9135	})
9136}
9137
9138func addRSAClientKeyExchangeTests() {
9139	for bad := RSABadValue(1); bad < NumRSABadValues; bad++ {
9140		testCases = append(testCases, testCase{
9141			testType: serverTest,
9142			name:     fmt.Sprintf("BadRSAClientKeyExchange-%d", bad),
9143			config: Config{
9144				// Ensure the ClientHello version and final
9145				// version are different, to detect if the
9146				// server uses the wrong one.
9147				MaxVersion:   VersionTLS11,
9148				CipherSuites: []uint16{TLS_RSA_WITH_3DES_EDE_CBC_SHA},
9149				Bugs: ProtocolBugs{
9150					BadRSAClientKeyExchange: bad,
9151				},
9152			},
9153			shouldFail:    true,
9154			expectedError: ":DECRYPTION_FAILED_OR_BAD_RECORD_MAC:",
9155		})
9156	}
9157
9158	// The server must compare whatever was in ClientHello.version for the
9159	// RSA premaster.
9160	testCases = append(testCases, testCase{
9161		testType: serverTest,
9162		name:     "SendClientVersion-RSA",
9163		config: Config{
9164			CipherSuites: []uint16{TLS_RSA_WITH_AES_128_GCM_SHA256},
9165			Bugs: ProtocolBugs{
9166				SendClientVersion: 0x1234,
9167			},
9168		},
9169		flags: []string{"-max-version", strconv.Itoa(VersionTLS12)},
9170	})
9171}
9172
9173var testCurves = []struct {
9174	name string
9175	id   CurveID
9176}{
9177	{"P-224", CurveP224},
9178	{"P-256", CurveP256},
9179	{"P-384", CurveP384},
9180	{"P-521", CurveP521},
9181	{"X25519", CurveX25519},
9182}
9183
9184const bogusCurve = 0x1234
9185
9186func addCurveTests() {
9187	for _, curve := range testCurves {
9188		testCases = append(testCases, testCase{
9189			name: "CurveTest-Client-" + curve.name,
9190			config: Config{
9191				MaxVersion:       VersionTLS12,
9192				CipherSuites:     []uint16{TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256},
9193				CurvePreferences: []CurveID{curve.id},
9194			},
9195			flags: []string{
9196				"-enable-all-curves",
9197				"-expect-curve-id", strconv.Itoa(int(curve.id)),
9198			},
9199			expectedCurveID: curve.id,
9200		})
9201		testCases = append(testCases, testCase{
9202			name: "CurveTest-Client-" + curve.name + "-TLS13",
9203			config: Config{
9204				MaxVersion:       VersionTLS13,
9205				CurvePreferences: []CurveID{curve.id},
9206			},
9207			flags: []string{
9208				"-enable-all-curves",
9209				"-expect-curve-id", strconv.Itoa(int(curve.id)),
9210			},
9211			expectedCurveID: curve.id,
9212		})
9213		testCases = append(testCases, testCase{
9214			testType: serverTest,
9215			name:     "CurveTest-Server-" + curve.name,
9216			config: Config{
9217				MaxVersion:       VersionTLS12,
9218				CipherSuites:     []uint16{TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256},
9219				CurvePreferences: []CurveID{curve.id},
9220			},
9221			flags: []string{
9222				"-enable-all-curves",
9223				"-expect-curve-id", strconv.Itoa(int(curve.id)),
9224			},
9225			expectedCurveID: curve.id,
9226		})
9227		testCases = append(testCases, testCase{
9228			testType: serverTest,
9229			name:     "CurveTest-Server-" + curve.name + "-TLS13",
9230			config: Config{
9231				MaxVersion:       VersionTLS13,
9232				CurvePreferences: []CurveID{curve.id},
9233			},
9234			flags: []string{
9235				"-enable-all-curves",
9236				"-expect-curve-id", strconv.Itoa(int(curve.id)),
9237			},
9238			expectedCurveID: curve.id,
9239		})
9240	}
9241
9242	// The server must be tolerant to bogus curves.
9243	testCases = append(testCases, testCase{
9244		testType: serverTest,
9245		name:     "UnknownCurve",
9246		config: Config{
9247			MaxVersion:       VersionTLS12,
9248			CipherSuites:     []uint16{TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256},
9249			CurvePreferences: []CurveID{bogusCurve, CurveP256},
9250		},
9251	})
9252
9253	// The server must be tolerant to bogus curves.
9254	testCases = append(testCases, testCase{
9255		testType: serverTest,
9256		name:     "UnknownCurve-TLS13",
9257		config: Config{
9258			MaxVersion:       VersionTLS13,
9259			CurvePreferences: []CurveID{bogusCurve, CurveP256},
9260		},
9261	})
9262
9263	// The server must not consider ECDHE ciphers when there are no
9264	// supported curves.
9265	testCases = append(testCases, testCase{
9266		testType: serverTest,
9267		name:     "NoSupportedCurves",
9268		config: Config{
9269			MaxVersion:   VersionTLS12,
9270			CipherSuites: []uint16{TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256},
9271			Bugs: ProtocolBugs{
9272				NoSupportedCurves: true,
9273			},
9274		},
9275		shouldFail:    true,
9276		expectedError: ":NO_SHARED_CIPHER:",
9277	})
9278	testCases = append(testCases, testCase{
9279		testType: serverTest,
9280		name:     "NoSupportedCurves-TLS13",
9281		config: Config{
9282			MaxVersion: VersionTLS13,
9283			Bugs: ProtocolBugs{
9284				NoSupportedCurves: true,
9285			},
9286		},
9287		shouldFail:    true,
9288		expectedError: ":NO_SHARED_GROUP:",
9289	})
9290
9291	// The server must fall back to another cipher when there are no
9292	// supported curves.
9293	testCases = append(testCases, testCase{
9294		testType: serverTest,
9295		name:     "NoCommonCurves",
9296		config: Config{
9297			MaxVersion: VersionTLS12,
9298			CipherSuites: []uint16{
9299				TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
9300				TLS_RSA_WITH_AES_128_GCM_SHA256,
9301			},
9302			CurvePreferences: []CurveID{CurveP224},
9303		},
9304		expectedCipher: TLS_RSA_WITH_AES_128_GCM_SHA256,
9305	})
9306
9307	// The client must reject bogus curves and disabled curves.
9308	testCases = append(testCases, testCase{
9309		name: "BadECDHECurve",
9310		config: Config{
9311			MaxVersion:   VersionTLS12,
9312			CipherSuites: []uint16{TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256},
9313			Bugs: ProtocolBugs{
9314				SendCurve: bogusCurve,
9315			},
9316		},
9317		shouldFail:    true,
9318		expectedError: ":WRONG_CURVE:",
9319	})
9320	testCases = append(testCases, testCase{
9321		name: "BadECDHECurve-TLS13",
9322		config: Config{
9323			MaxVersion: VersionTLS13,
9324			Bugs: ProtocolBugs{
9325				SendCurve: bogusCurve,
9326			},
9327		},
9328		shouldFail:    true,
9329		expectedError: ":WRONG_CURVE:",
9330	})
9331
9332	testCases = append(testCases, testCase{
9333		name: "UnsupportedCurve",
9334		config: Config{
9335			MaxVersion:       VersionTLS12,
9336			CipherSuites:     []uint16{TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256},
9337			CurvePreferences: []CurveID{CurveP256},
9338			Bugs: ProtocolBugs{
9339				IgnorePeerCurvePreferences: true,
9340			},
9341		},
9342		flags:         []string{"-p384-only"},
9343		shouldFail:    true,
9344		expectedError: ":WRONG_CURVE:",
9345	})
9346
9347	testCases = append(testCases, testCase{
9348		// TODO(davidben): Add a TLS 1.3 version where
9349		// HelloRetryRequest requests an unsupported curve.
9350		name: "UnsupportedCurve-ServerHello-TLS13",
9351		config: Config{
9352			MaxVersion:       VersionTLS13,
9353			CurvePreferences: []CurveID{CurveP384},
9354			Bugs: ProtocolBugs{
9355				SendCurve: CurveP256,
9356			},
9357		},
9358		flags:         []string{"-p384-only"},
9359		shouldFail:    true,
9360		expectedError: ":WRONG_CURVE:",
9361	})
9362
9363	// Test invalid curve points.
9364	testCases = append(testCases, testCase{
9365		name: "InvalidECDHPoint-Client",
9366		config: Config{
9367			MaxVersion:       VersionTLS12,
9368			CipherSuites:     []uint16{TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256},
9369			CurvePreferences: []CurveID{CurveP256},
9370			Bugs: ProtocolBugs{
9371				InvalidECDHPoint: true,
9372			},
9373		},
9374		shouldFail:    true,
9375		expectedError: ":INVALID_ENCODING:",
9376	})
9377	testCases = append(testCases, testCase{
9378		name: "InvalidECDHPoint-Client-TLS13",
9379		config: Config{
9380			MaxVersion:       VersionTLS13,
9381			CurvePreferences: []CurveID{CurveP256},
9382			Bugs: ProtocolBugs{
9383				InvalidECDHPoint: true,
9384			},
9385		},
9386		shouldFail:    true,
9387		expectedError: ":INVALID_ENCODING:",
9388	})
9389	testCases = append(testCases, testCase{
9390		testType: serverTest,
9391		name:     "InvalidECDHPoint-Server",
9392		config: Config{
9393			MaxVersion:       VersionTLS12,
9394			CipherSuites:     []uint16{TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256},
9395			CurvePreferences: []CurveID{CurveP256},
9396			Bugs: ProtocolBugs{
9397				InvalidECDHPoint: true,
9398			},
9399		},
9400		shouldFail:    true,
9401		expectedError: ":INVALID_ENCODING:",
9402	})
9403	testCases = append(testCases, testCase{
9404		testType: serverTest,
9405		name:     "InvalidECDHPoint-Server-TLS13",
9406		config: Config{
9407			MaxVersion:       VersionTLS13,
9408			CurvePreferences: []CurveID{CurveP256},
9409			Bugs: ProtocolBugs{
9410				InvalidECDHPoint: true,
9411			},
9412		},
9413		shouldFail:    true,
9414		expectedError: ":INVALID_ENCODING:",
9415	})
9416
9417	// The previous curve ID should be reported on TLS 1.2 resumption.
9418	testCases = append(testCases, testCase{
9419		name: "CurveID-Resume-Client",
9420		config: Config{
9421			MaxVersion:       VersionTLS12,
9422			CipherSuites:     []uint16{TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256},
9423			CurvePreferences: []CurveID{CurveX25519},
9424		},
9425		flags:         []string{"-expect-curve-id", strconv.Itoa(int(CurveX25519))},
9426		resumeSession: true,
9427	})
9428	testCases = append(testCases, testCase{
9429		testType: serverTest,
9430		name:     "CurveID-Resume-Server",
9431		config: Config{
9432			MaxVersion:       VersionTLS12,
9433			CipherSuites:     []uint16{TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256},
9434			CurvePreferences: []CurveID{CurveX25519},
9435		},
9436		flags:         []string{"-expect-curve-id", strconv.Itoa(int(CurveX25519))},
9437		resumeSession: true,
9438	})
9439
9440	// TLS 1.3 allows resuming at a differet curve. If this happens, the new
9441	// one should be reported.
9442	testCases = append(testCases, testCase{
9443		name: "CurveID-Resume-Client-TLS13",
9444		config: Config{
9445			MaxVersion:       VersionTLS13,
9446			CurvePreferences: []CurveID{CurveX25519},
9447		},
9448		resumeConfig: &Config{
9449			MaxVersion:       VersionTLS13,
9450			CurvePreferences: []CurveID{CurveP256},
9451		},
9452		flags: []string{
9453			"-on-initial-expect-curve-id", strconv.Itoa(int(CurveX25519)),
9454			"-on-resume-expect-curve-id", strconv.Itoa(int(CurveP256)),
9455		},
9456		resumeSession: true,
9457	})
9458	testCases = append(testCases, testCase{
9459		testType: serverTest,
9460		name:     "CurveID-Resume-Server-TLS13",
9461		config: Config{
9462			MaxVersion:       VersionTLS13,
9463			CurvePreferences: []CurveID{CurveX25519},
9464		},
9465		resumeConfig: &Config{
9466			MaxVersion:       VersionTLS13,
9467			CurvePreferences: []CurveID{CurveP256},
9468		},
9469		flags: []string{
9470			"-on-initial-expect-curve-id", strconv.Itoa(int(CurveX25519)),
9471			"-on-resume-expect-curve-id", strconv.Itoa(int(CurveP256)),
9472		},
9473		resumeSession: true,
9474	})
9475
9476	// Server-sent point formats are legal in TLS 1.2, but not in TLS 1.3.
9477	testCases = append(testCases, testCase{
9478		name: "PointFormat-ServerHello-TLS12",
9479		config: Config{
9480			MaxVersion: VersionTLS12,
9481			Bugs: ProtocolBugs{
9482				SendSupportedPointFormats: []byte{pointFormatUncompressed},
9483			},
9484		},
9485	})
9486	testCases = append(testCases, testCase{
9487		name: "PointFormat-EncryptedExtensions-TLS13",
9488		config: Config{
9489			MaxVersion: VersionTLS13,
9490			Bugs: ProtocolBugs{
9491				SendSupportedPointFormats: []byte{pointFormatUncompressed},
9492			},
9493		},
9494		shouldFail:    true,
9495		expectedError: ":ERROR_PARSING_EXTENSION:",
9496	})
9497
9498	// Test that we tolerate unknown point formats, as long as
9499	// pointFormatUncompressed is present. Limit ciphers to ECDHE ciphers to
9500	// check they are still functional.
9501	testCases = append(testCases, testCase{
9502		name: "PointFormat-Client-Tolerance",
9503		config: Config{
9504			MaxVersion: VersionTLS12,
9505			Bugs: ProtocolBugs{
9506				SendSupportedPointFormats: []byte{42, pointFormatUncompressed, 99, pointFormatCompressedPrime},
9507			},
9508		},
9509	})
9510	testCases = append(testCases, testCase{
9511		testType: serverTest,
9512		name:     "PointFormat-Server-Tolerance",
9513		config: Config{
9514			MaxVersion:   VersionTLS12,
9515			CipherSuites: []uint16{TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256},
9516			Bugs: ProtocolBugs{
9517				SendSupportedPointFormats: []byte{42, pointFormatUncompressed, 99, pointFormatCompressedPrime},
9518			},
9519		},
9520	})
9521
9522	// Test TLS 1.2 does not require the point format extension to be
9523	// present.
9524	testCases = append(testCases, testCase{
9525		name: "PointFormat-Client-Missing",
9526		config: Config{
9527			MaxVersion:   VersionTLS12,
9528			CipherSuites: []uint16{TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256},
9529			Bugs: ProtocolBugs{
9530				SendSupportedPointFormats: []byte{},
9531			},
9532		},
9533	})
9534	testCases = append(testCases, testCase{
9535		testType: serverTest,
9536		name:     "PointFormat-Server-Missing",
9537		config: Config{
9538			MaxVersion:   VersionTLS12,
9539			CipherSuites: []uint16{TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256},
9540			Bugs: ProtocolBugs{
9541				SendSupportedPointFormats: []byte{},
9542			},
9543		},
9544	})
9545
9546	// If the point format extension is present, uncompressed points must be
9547	// offered. BoringSSL requires this whether or not ECDHE is used.
9548	testCases = append(testCases, testCase{
9549		name: "PointFormat-Client-MissingUncompressed",
9550		config: Config{
9551			MaxVersion: VersionTLS12,
9552			Bugs: ProtocolBugs{
9553				SendSupportedPointFormats: []byte{pointFormatCompressedPrime},
9554			},
9555		},
9556		shouldFail:    true,
9557		expectedError: ":ERROR_PARSING_EXTENSION:",
9558	})
9559	testCases = append(testCases, testCase{
9560		testType: serverTest,
9561		name:     "PointFormat-Server-MissingUncompressed",
9562		config: Config{
9563			MaxVersion: VersionTLS12,
9564			Bugs: ProtocolBugs{
9565				SendSupportedPointFormats: []byte{pointFormatCompressedPrime},
9566			},
9567		},
9568		shouldFail:    true,
9569		expectedError: ":ERROR_PARSING_EXTENSION:",
9570	})
9571}
9572
9573func addTLS13RecordTests() {
9574	testCases = append(testCases, testCase{
9575		name: "TLS13-RecordPadding",
9576		config: Config{
9577			MaxVersion: VersionTLS13,
9578			MinVersion: VersionTLS13,
9579			Bugs: ProtocolBugs{
9580				RecordPadding: 10,
9581			},
9582		},
9583	})
9584
9585	testCases = append(testCases, testCase{
9586		name: "TLS13-EmptyRecords",
9587		config: Config{
9588			MaxVersion: VersionTLS13,
9589			MinVersion: VersionTLS13,
9590			Bugs: ProtocolBugs{
9591				OmitRecordContents: true,
9592			},
9593		},
9594		shouldFail:    true,
9595		expectedError: ":DECRYPTION_FAILED_OR_BAD_RECORD_MAC:",
9596	})
9597
9598	testCases = append(testCases, testCase{
9599		name: "TLS13-OnlyPadding",
9600		config: Config{
9601			MaxVersion: VersionTLS13,
9602			MinVersion: VersionTLS13,
9603			Bugs: ProtocolBugs{
9604				OmitRecordContents: true,
9605				RecordPadding:      10,
9606			},
9607		},
9608		shouldFail:    true,
9609		expectedError: ":DECRYPTION_FAILED_OR_BAD_RECORD_MAC:",
9610	})
9611
9612	testCases = append(testCases, testCase{
9613		name: "TLS13-WrongOuterRecord",
9614		config: Config{
9615			MaxVersion: VersionTLS13,
9616			MinVersion: VersionTLS13,
9617			Bugs: ProtocolBugs{
9618				OuterRecordType: recordTypeHandshake,
9619			},
9620		},
9621		shouldFail:    true,
9622		expectedError: ":INVALID_OUTER_RECORD_TYPE:",
9623	})
9624}
9625
9626func addSessionTicketTests() {
9627	testCases = append(testCases, testCase{
9628		// In TLS 1.2 and below, empty NewSessionTicket messages
9629		// mean the server changed its mind on sending a ticket.
9630		name: "SendEmptySessionTicket",
9631		config: Config{
9632			MaxVersion: VersionTLS12,
9633			Bugs: ProtocolBugs{
9634				SendEmptySessionTicket: true,
9635			},
9636		},
9637		flags: []string{"-expect-no-session"},
9638	})
9639
9640	// Test that the server ignores unknown PSK modes.
9641	testCases = append(testCases, testCase{
9642		testType: serverTest,
9643		name:     "TLS13-SendUnknownModeSessionTicket-Server",
9644		config: Config{
9645			MaxVersion: VersionTLS13,
9646			Bugs: ProtocolBugs{
9647				SendPSKKeyExchangeModes: []byte{0x1a, pskDHEKEMode, 0x2a},
9648			},
9649		},
9650		resumeSession:         true,
9651		expectedResumeVersion: VersionTLS13,
9652	})
9653
9654	// Test that the server does not send session tickets with no matching key exchange mode.
9655	testCases = append(testCases, testCase{
9656		testType: serverTest,
9657		name:     "TLS13-ExpectNoSessionTicketOnBadKEMode-Server",
9658		config: Config{
9659			MaxVersion: VersionTLS13,
9660			Bugs: ProtocolBugs{
9661				SendPSKKeyExchangeModes:  []byte{0x1a},
9662				ExpectNoNewSessionTicket: true,
9663			},
9664		},
9665	})
9666
9667	// Test that the server does not accept a session with no matching key exchange mode.
9668	testCases = append(testCases, testCase{
9669		testType: serverTest,
9670		name:     "TLS13-SendBadKEModeSessionTicket-Server",
9671		config: Config{
9672			MaxVersion: VersionTLS13,
9673		},
9674		resumeConfig: &Config{
9675			MaxVersion: VersionTLS13,
9676			Bugs: ProtocolBugs{
9677				SendPSKKeyExchangeModes: []byte{0x1a},
9678			},
9679		},
9680		resumeSession:        true,
9681		expectResumeRejected: true,
9682	})
9683
9684	// Test that the client ticket age is sent correctly.
9685	testCases = append(testCases, testCase{
9686		testType: clientTest,
9687		name:     "TLS13-TestValidTicketAge-Client",
9688		config: Config{
9689			MaxVersion: VersionTLS13,
9690			Bugs: ProtocolBugs{
9691				ExpectTicketAge: 10 * time.Second,
9692			},
9693		},
9694		resumeSession: true,
9695		flags: []string{
9696			"-resumption-delay", "10",
9697		},
9698	})
9699
9700	// Test that the client ticket age is enforced.
9701	testCases = append(testCases, testCase{
9702		testType: clientTest,
9703		name:     "TLS13-TestBadTicketAge-Client",
9704		config: Config{
9705			MaxVersion: VersionTLS13,
9706			Bugs: ProtocolBugs{
9707				ExpectTicketAge: 1000 * time.Second,
9708			},
9709		},
9710		resumeSession:      true,
9711		shouldFail:         true,
9712		expectedLocalError: "tls: invalid ticket age",
9713	})
9714
9715	// Test that the server's ticket age skew reporting works.
9716	testCases = append(testCases, testCase{
9717		testType: serverTest,
9718		name:     "TLS13-TicketAgeSkew-Forward",
9719		config: Config{
9720			MaxVersion: VersionTLS13,
9721			Bugs: ProtocolBugs{
9722				SendTicketAge: 15 * time.Second,
9723			},
9724		},
9725		resumeSession:        true,
9726		resumeRenewedSession: true,
9727		flags: []string{
9728			"-resumption-delay", "10",
9729			"-expect-ticket-age-skew", "5",
9730		},
9731	})
9732	testCases = append(testCases, testCase{
9733		testType: serverTest,
9734		name:     "TLS13-TicketAgeSkew-Backward",
9735		config: Config{
9736			MaxVersion: VersionTLS13,
9737			Bugs: ProtocolBugs{
9738				SendTicketAge: 5 * time.Second,
9739			},
9740		},
9741		resumeSession:        true,
9742		resumeRenewedSession: true,
9743		flags: []string{
9744			"-resumption-delay", "10",
9745			"-expect-ticket-age-skew", "-5",
9746		},
9747	})
9748
9749	testCases = append(testCases, testCase{
9750		testType: clientTest,
9751		name:     "TLS13-SendTicketEarlyDataInfo",
9752		config: Config{
9753			MaxVersion:       VersionTLS13,
9754			MaxEarlyDataSize: 16384,
9755		},
9756		flags: []string{
9757			"-enable-early-data",
9758			"-expect-early-data-info",
9759		},
9760	})
9761
9762	// Test that 0-RTT tickets are ignored in clients unless opted in.
9763	testCases = append(testCases, testCase{
9764		testType: clientTest,
9765		name:     "TLS13-SendTicketEarlyDataInfo-Disabled",
9766		config: Config{
9767			MaxVersion:       VersionTLS13,
9768			MaxEarlyDataSize: 16384,
9769		},
9770	})
9771
9772	testCases = append(testCases, testCase{
9773		testType: clientTest,
9774		name:     "TLS13-DuplicateTicketEarlyDataInfo",
9775		config: Config{
9776			MaxVersion:       VersionTLS13,
9777			MaxEarlyDataSize: 16384,
9778			Bugs: ProtocolBugs{
9779				DuplicateTicketEarlyDataInfo: true,
9780			},
9781		},
9782		shouldFail:         true,
9783		expectedError:      ":DUPLICATE_EXTENSION:",
9784		expectedLocalError: "remote error: illegal parameter",
9785	})
9786
9787	testCases = append(testCases, testCase{
9788		testType: serverTest,
9789		name:     "TLS13-ExpectTicketEarlyDataInfo",
9790		config: Config{
9791			MaxVersion: VersionTLS13,
9792			Bugs: ProtocolBugs{
9793				ExpectTicketEarlyDataInfo: true,
9794			},
9795		},
9796		flags: []string{
9797			"-enable-early-data",
9798		},
9799	})
9800
9801	// Test that, in TLS 1.3, the server-offered NewSessionTicket lifetime
9802	// is honored.
9803	testCases = append(testCases, testCase{
9804		testType: clientTest,
9805		name:     "TLS13-HonorServerSessionTicketLifetime",
9806		config: Config{
9807			MaxVersion: VersionTLS13,
9808			Bugs: ProtocolBugs{
9809				SendTicketLifetime: 20 * time.Second,
9810			},
9811		},
9812		flags: []string{
9813			"-resumption-delay", "19",
9814		},
9815		resumeSession: true,
9816	})
9817	testCases = append(testCases, testCase{
9818		testType: clientTest,
9819		name:     "TLS13-HonorServerSessionTicketLifetime-2",
9820		config: Config{
9821			MaxVersion: VersionTLS13,
9822			Bugs: ProtocolBugs{
9823				SendTicketLifetime: 20 * time.Second,
9824				// The client should not offer the expired session.
9825				ExpectNoTLS13PSK: true,
9826			},
9827		},
9828		flags: []string{
9829			"-resumption-delay", "21",
9830		},
9831		resumeSession:        true,
9832		expectResumeRejected: true,
9833	})
9834}
9835
9836func addChangeCipherSpecTests() {
9837	// Test missing ChangeCipherSpecs.
9838	testCases = append(testCases, testCase{
9839		name: "SkipChangeCipherSpec-Client",
9840		config: Config{
9841			MaxVersion: VersionTLS12,
9842			Bugs: ProtocolBugs{
9843				SkipChangeCipherSpec: true,
9844			},
9845		},
9846		shouldFail:    true,
9847		expectedError: ":UNEXPECTED_RECORD:",
9848	})
9849	testCases = append(testCases, testCase{
9850		testType: serverTest,
9851		name:     "SkipChangeCipherSpec-Server",
9852		config: Config{
9853			MaxVersion: VersionTLS12,
9854			Bugs: ProtocolBugs{
9855				SkipChangeCipherSpec: true,
9856			},
9857		},
9858		shouldFail:    true,
9859		expectedError: ":UNEXPECTED_RECORD:",
9860	})
9861	testCases = append(testCases, testCase{
9862		testType: serverTest,
9863		name:     "SkipChangeCipherSpec-Server-NPN",
9864		config: Config{
9865			MaxVersion: VersionTLS12,
9866			NextProtos: []string{"bar"},
9867			Bugs: ProtocolBugs{
9868				SkipChangeCipherSpec: true,
9869			},
9870		},
9871		flags: []string{
9872			"-advertise-npn", "\x03foo\x03bar\x03baz",
9873		},
9874		shouldFail:    true,
9875		expectedError: ":UNEXPECTED_RECORD:",
9876	})
9877
9878	// Test synchronization between the handshake and ChangeCipherSpec.
9879	// Partial post-CCS handshake messages before ChangeCipherSpec should be
9880	// rejected. Test both with and without handshake packing to handle both
9881	// when the partial post-CCS message is in its own record and when it is
9882	// attached to the pre-CCS message.
9883	for _, packed := range []bool{false, true} {
9884		var suffix string
9885		if packed {
9886			suffix = "-Packed"
9887		}
9888
9889		testCases = append(testCases, testCase{
9890			name: "FragmentAcrossChangeCipherSpec-Client" + suffix,
9891			config: Config{
9892				MaxVersion: VersionTLS12,
9893				Bugs: ProtocolBugs{
9894					FragmentAcrossChangeCipherSpec: true,
9895					PackHandshakeFlight:            packed,
9896				},
9897			},
9898			shouldFail:    true,
9899			expectedError: ":UNEXPECTED_RECORD:",
9900		})
9901		testCases = append(testCases, testCase{
9902			name: "FragmentAcrossChangeCipherSpec-Client-Resume" + suffix,
9903			config: Config{
9904				MaxVersion: VersionTLS12,
9905			},
9906			resumeSession: true,
9907			resumeConfig: &Config{
9908				MaxVersion: VersionTLS12,
9909				Bugs: ProtocolBugs{
9910					FragmentAcrossChangeCipherSpec: true,
9911					PackHandshakeFlight:            packed,
9912				},
9913			},
9914			shouldFail:    true,
9915			expectedError: ":UNEXPECTED_RECORD:",
9916		})
9917		testCases = append(testCases, testCase{
9918			testType: serverTest,
9919			name:     "FragmentAcrossChangeCipherSpec-Server" + suffix,
9920			config: Config{
9921				MaxVersion: VersionTLS12,
9922				Bugs: ProtocolBugs{
9923					FragmentAcrossChangeCipherSpec: true,
9924					PackHandshakeFlight:            packed,
9925				},
9926			},
9927			shouldFail:    true,
9928			expectedError: ":UNEXPECTED_RECORD:",
9929		})
9930		testCases = append(testCases, testCase{
9931			testType: serverTest,
9932			name:     "FragmentAcrossChangeCipherSpec-Server-Resume" + suffix,
9933			config: Config{
9934				MaxVersion: VersionTLS12,
9935			},
9936			resumeSession: true,
9937			resumeConfig: &Config{
9938				MaxVersion: VersionTLS12,
9939				Bugs: ProtocolBugs{
9940					FragmentAcrossChangeCipherSpec: true,
9941					PackHandshakeFlight:            packed,
9942				},
9943			},
9944			shouldFail:    true,
9945			expectedError: ":UNEXPECTED_RECORD:",
9946		})
9947		testCases = append(testCases, testCase{
9948			testType: serverTest,
9949			name:     "FragmentAcrossChangeCipherSpec-Server-NPN" + suffix,
9950			config: Config{
9951				MaxVersion: VersionTLS12,
9952				NextProtos: []string{"bar"},
9953				Bugs: ProtocolBugs{
9954					FragmentAcrossChangeCipherSpec: true,
9955					PackHandshakeFlight:            packed,
9956				},
9957			},
9958			flags: []string{
9959				"-advertise-npn", "\x03foo\x03bar\x03baz",
9960			},
9961			shouldFail:    true,
9962			expectedError: ":UNEXPECTED_RECORD:",
9963		})
9964	}
9965
9966	// Test that, in DTLS, ChangeCipherSpec is not allowed when there are
9967	// messages in the handshake queue. Do this by testing the server
9968	// reading the client Finished, reversing the flight so Finished comes
9969	// first.
9970	testCases = append(testCases, testCase{
9971		protocol: dtls,
9972		testType: serverTest,
9973		name:     "SendUnencryptedFinished-DTLS",
9974		config: Config{
9975			MaxVersion: VersionTLS12,
9976			Bugs: ProtocolBugs{
9977				SendUnencryptedFinished:   true,
9978				ReverseHandshakeFragments: true,
9979			},
9980		},
9981		shouldFail:    true,
9982		expectedError: ":BUFFERED_MESSAGES_ON_CIPHER_CHANGE:",
9983	})
9984
9985	// Test synchronization between encryption changes and the handshake in
9986	// TLS 1.3, where ChangeCipherSpec is implicit.
9987	testCases = append(testCases, testCase{
9988		name: "PartialEncryptedExtensionsWithServerHello",
9989		config: Config{
9990			MaxVersion: VersionTLS13,
9991			Bugs: ProtocolBugs{
9992				PartialEncryptedExtensionsWithServerHello: true,
9993			},
9994		},
9995		shouldFail:    true,
9996		expectedError: ":BUFFERED_MESSAGES_ON_CIPHER_CHANGE:",
9997	})
9998	testCases = append(testCases, testCase{
9999		testType: serverTest,
10000		name:     "PartialClientFinishedWithClientHello",
10001		config: Config{
10002			MaxVersion: VersionTLS13,
10003			Bugs: ProtocolBugs{
10004				PartialClientFinishedWithClientHello: true,
10005			},
10006		},
10007		shouldFail:    true,
10008		expectedError: ":BUFFERED_MESSAGES_ON_CIPHER_CHANGE:",
10009	})
10010
10011	// Test that early ChangeCipherSpecs are handled correctly.
10012	testCases = append(testCases, testCase{
10013		testType: serverTest,
10014		name:     "EarlyChangeCipherSpec-server-1",
10015		config: Config{
10016			MaxVersion: VersionTLS12,
10017			Bugs: ProtocolBugs{
10018				EarlyChangeCipherSpec: 1,
10019			},
10020		},
10021		shouldFail:    true,
10022		expectedError: ":UNEXPECTED_RECORD:",
10023	})
10024	testCases = append(testCases, testCase{
10025		testType: serverTest,
10026		name:     "EarlyChangeCipherSpec-server-2",
10027		config: Config{
10028			MaxVersion: VersionTLS12,
10029			Bugs: ProtocolBugs{
10030				EarlyChangeCipherSpec: 2,
10031			},
10032		},
10033		shouldFail:    true,
10034		expectedError: ":UNEXPECTED_RECORD:",
10035	})
10036	testCases = append(testCases, testCase{
10037		protocol: dtls,
10038		name:     "StrayChangeCipherSpec",
10039		config: Config{
10040			// TODO(davidben): Once DTLS 1.3 exists, test
10041			// that stray ChangeCipherSpec messages are
10042			// rejected.
10043			MaxVersion: VersionTLS12,
10044			Bugs: ProtocolBugs{
10045				StrayChangeCipherSpec: true,
10046			},
10047		},
10048	})
10049
10050	// Test that the contents of ChangeCipherSpec are checked.
10051	testCases = append(testCases, testCase{
10052		name: "BadChangeCipherSpec-1",
10053		config: Config{
10054			MaxVersion: VersionTLS12,
10055			Bugs: ProtocolBugs{
10056				BadChangeCipherSpec: []byte{2},
10057			},
10058		},
10059		shouldFail:    true,
10060		expectedError: ":BAD_CHANGE_CIPHER_SPEC:",
10061	})
10062	testCases = append(testCases, testCase{
10063		name: "BadChangeCipherSpec-2",
10064		config: Config{
10065			MaxVersion: VersionTLS12,
10066			Bugs: ProtocolBugs{
10067				BadChangeCipherSpec: []byte{1, 1},
10068			},
10069		},
10070		shouldFail:    true,
10071		expectedError: ":BAD_CHANGE_CIPHER_SPEC:",
10072	})
10073	testCases = append(testCases, testCase{
10074		protocol: dtls,
10075		name:     "BadChangeCipherSpec-DTLS-1",
10076		config: Config{
10077			MaxVersion: VersionTLS12,
10078			Bugs: ProtocolBugs{
10079				BadChangeCipherSpec: []byte{2},
10080			},
10081		},
10082		shouldFail:    true,
10083		expectedError: ":BAD_CHANGE_CIPHER_SPEC:",
10084	})
10085	testCases = append(testCases, testCase{
10086		protocol: dtls,
10087		name:     "BadChangeCipherSpec-DTLS-2",
10088		config: Config{
10089			MaxVersion: VersionTLS12,
10090			Bugs: ProtocolBugs{
10091				BadChangeCipherSpec: []byte{1, 1},
10092			},
10093		},
10094		shouldFail:    true,
10095		expectedError: ":BAD_CHANGE_CIPHER_SPEC:",
10096	})
10097}
10098
10099type perMessageTest struct {
10100	messageType uint8
10101	test        testCase
10102}
10103
10104// makePerMessageTests returns a series of test templates which cover each
10105// message in the TLS handshake. These may be used with bugs like
10106// WrongMessageType to fully test a per-message bug.
10107func makePerMessageTests() []perMessageTest {
10108	var ret []perMessageTest
10109	for _, protocol := range []protocol{tls, dtls} {
10110		var suffix string
10111		if protocol == dtls {
10112			suffix = "-DTLS"
10113		}
10114
10115		ret = append(ret, perMessageTest{
10116			messageType: typeClientHello,
10117			test: testCase{
10118				protocol: protocol,
10119				testType: serverTest,
10120				name:     "ClientHello" + suffix,
10121				config: Config{
10122					MaxVersion: VersionTLS12,
10123				},
10124			},
10125		})
10126
10127		if protocol == dtls {
10128			ret = append(ret, perMessageTest{
10129				messageType: typeHelloVerifyRequest,
10130				test: testCase{
10131					protocol: protocol,
10132					name:     "HelloVerifyRequest" + suffix,
10133					config: Config{
10134						MaxVersion: VersionTLS12,
10135					},
10136				},
10137			})
10138		}
10139
10140		ret = append(ret, perMessageTest{
10141			messageType: typeServerHello,
10142			test: testCase{
10143				protocol: protocol,
10144				name:     "ServerHello" + suffix,
10145				config: Config{
10146					MaxVersion: VersionTLS12,
10147				},
10148			},
10149		})
10150
10151		ret = append(ret, perMessageTest{
10152			messageType: typeCertificate,
10153			test: testCase{
10154				protocol: protocol,
10155				name:     "ServerCertificate" + suffix,
10156				config: Config{
10157					MaxVersion: VersionTLS12,
10158				},
10159			},
10160		})
10161
10162		ret = append(ret, perMessageTest{
10163			messageType: typeCertificateStatus,
10164			test: testCase{
10165				protocol: protocol,
10166				name:     "CertificateStatus" + suffix,
10167				config: Config{
10168					MaxVersion: VersionTLS12,
10169				},
10170				flags: []string{"-enable-ocsp-stapling"},
10171			},
10172		})
10173
10174		ret = append(ret, perMessageTest{
10175			messageType: typeServerKeyExchange,
10176			test: testCase{
10177				protocol: protocol,
10178				name:     "ServerKeyExchange" + suffix,
10179				config: Config{
10180					MaxVersion:   VersionTLS12,
10181					CipherSuites: []uint16{TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256},
10182				},
10183			},
10184		})
10185
10186		ret = append(ret, perMessageTest{
10187			messageType: typeCertificateRequest,
10188			test: testCase{
10189				protocol: protocol,
10190				name:     "CertificateRequest" + suffix,
10191				config: Config{
10192					MaxVersion: VersionTLS12,
10193					ClientAuth: RequireAnyClientCert,
10194				},
10195			},
10196		})
10197
10198		ret = append(ret, perMessageTest{
10199			messageType: typeServerHelloDone,
10200			test: testCase{
10201				protocol: protocol,
10202				name:     "ServerHelloDone" + suffix,
10203				config: Config{
10204					MaxVersion: VersionTLS12,
10205				},
10206			},
10207		})
10208
10209		ret = append(ret, perMessageTest{
10210			messageType: typeCertificate,
10211			test: testCase{
10212				testType: serverTest,
10213				protocol: protocol,
10214				name:     "ClientCertificate" + suffix,
10215				config: Config{
10216					Certificates: []Certificate{rsaCertificate},
10217					MaxVersion:   VersionTLS12,
10218				},
10219				flags: []string{"-require-any-client-certificate"},
10220			},
10221		})
10222
10223		ret = append(ret, perMessageTest{
10224			messageType: typeCertificateVerify,
10225			test: testCase{
10226				testType: serverTest,
10227				protocol: protocol,
10228				name:     "CertificateVerify" + suffix,
10229				config: Config{
10230					Certificates: []Certificate{rsaCertificate},
10231					MaxVersion:   VersionTLS12,
10232				},
10233				flags: []string{"-require-any-client-certificate"},
10234			},
10235		})
10236
10237		ret = append(ret, perMessageTest{
10238			messageType: typeClientKeyExchange,
10239			test: testCase{
10240				testType: serverTest,
10241				protocol: protocol,
10242				name:     "ClientKeyExchange" + suffix,
10243				config: Config{
10244					MaxVersion: VersionTLS12,
10245				},
10246			},
10247		})
10248
10249		if protocol != dtls {
10250			ret = append(ret, perMessageTest{
10251				messageType: typeNextProtocol,
10252				test: testCase{
10253					testType: serverTest,
10254					protocol: protocol,
10255					name:     "NextProtocol" + suffix,
10256					config: Config{
10257						MaxVersion: VersionTLS12,
10258						NextProtos: []string{"bar"},
10259					},
10260					flags: []string{"-advertise-npn", "\x03foo\x03bar\x03baz"},
10261				},
10262			})
10263
10264			ret = append(ret, perMessageTest{
10265				messageType: typeChannelID,
10266				test: testCase{
10267					testType: serverTest,
10268					protocol: protocol,
10269					name:     "ChannelID" + suffix,
10270					config: Config{
10271						MaxVersion: VersionTLS12,
10272						ChannelID:  channelIDKey,
10273					},
10274					flags: []string{
10275						"-expect-channel-id",
10276						base64.StdEncoding.EncodeToString(channelIDBytes),
10277					},
10278				},
10279			})
10280		}
10281
10282		ret = append(ret, perMessageTest{
10283			messageType: typeFinished,
10284			test: testCase{
10285				testType: serverTest,
10286				protocol: protocol,
10287				name:     "ClientFinished" + suffix,
10288				config: Config{
10289					MaxVersion: VersionTLS12,
10290				},
10291			},
10292		})
10293
10294		ret = append(ret, perMessageTest{
10295			messageType: typeNewSessionTicket,
10296			test: testCase{
10297				protocol: protocol,
10298				name:     "NewSessionTicket" + suffix,
10299				config: Config{
10300					MaxVersion: VersionTLS12,
10301				},
10302			},
10303		})
10304
10305		ret = append(ret, perMessageTest{
10306			messageType: typeFinished,
10307			test: testCase{
10308				protocol: protocol,
10309				name:     "ServerFinished" + suffix,
10310				config: Config{
10311					MaxVersion: VersionTLS12,
10312				},
10313			},
10314		})
10315
10316	}
10317
10318	ret = append(ret, perMessageTest{
10319		messageType: typeClientHello,
10320		test: testCase{
10321			testType: serverTest,
10322			name:     "TLS13-ClientHello",
10323			config: Config{
10324				MaxVersion: VersionTLS13,
10325			},
10326		},
10327	})
10328
10329	ret = append(ret, perMessageTest{
10330		messageType: typeServerHello,
10331		test: testCase{
10332			name: "TLS13-ServerHello",
10333			config: Config{
10334				MaxVersion: VersionTLS13,
10335			},
10336		},
10337	})
10338
10339	ret = append(ret, perMessageTest{
10340		messageType: typeEncryptedExtensions,
10341		test: testCase{
10342			name: "TLS13-EncryptedExtensions",
10343			config: Config{
10344				MaxVersion: VersionTLS13,
10345			},
10346		},
10347	})
10348
10349	ret = append(ret, perMessageTest{
10350		messageType: typeCertificateRequest,
10351		test: testCase{
10352			name: "TLS13-CertificateRequest",
10353			config: Config{
10354				MaxVersion: VersionTLS13,
10355				ClientAuth: RequireAnyClientCert,
10356			},
10357		},
10358	})
10359
10360	ret = append(ret, perMessageTest{
10361		messageType: typeCertificate,
10362		test: testCase{
10363			name: "TLS13-ServerCertificate",
10364			config: Config{
10365				MaxVersion: VersionTLS13,
10366			},
10367		},
10368	})
10369
10370	ret = append(ret, perMessageTest{
10371		messageType: typeCertificateVerify,
10372		test: testCase{
10373			name: "TLS13-ServerCertificateVerify",
10374			config: Config{
10375				MaxVersion: VersionTLS13,
10376			},
10377		},
10378	})
10379
10380	ret = append(ret, perMessageTest{
10381		messageType: typeFinished,
10382		test: testCase{
10383			name: "TLS13-ServerFinished",
10384			config: Config{
10385				MaxVersion: VersionTLS13,
10386			},
10387		},
10388	})
10389
10390	ret = append(ret, perMessageTest{
10391		messageType: typeCertificate,
10392		test: testCase{
10393			testType: serverTest,
10394			name:     "TLS13-ClientCertificate",
10395			config: Config{
10396				Certificates: []Certificate{rsaCertificate},
10397				MaxVersion:   VersionTLS13,
10398			},
10399			flags: []string{"-require-any-client-certificate"},
10400		},
10401	})
10402
10403	ret = append(ret, perMessageTest{
10404		messageType: typeCertificateVerify,
10405		test: testCase{
10406			testType: serverTest,
10407			name:     "TLS13-ClientCertificateVerify",
10408			config: Config{
10409				Certificates: []Certificate{rsaCertificate},
10410				MaxVersion:   VersionTLS13,
10411			},
10412			flags: []string{"-require-any-client-certificate"},
10413		},
10414	})
10415
10416	ret = append(ret, perMessageTest{
10417		messageType: typeFinished,
10418		test: testCase{
10419			testType: serverTest,
10420			name:     "TLS13-ClientFinished",
10421			config: Config{
10422				MaxVersion: VersionTLS13,
10423			},
10424		},
10425	})
10426
10427	return ret
10428}
10429
10430func addWrongMessageTypeTests() {
10431	for _, t := range makePerMessageTests() {
10432		t.test.name = "WrongMessageType-" + t.test.name
10433		t.test.config.Bugs.SendWrongMessageType = t.messageType
10434		t.test.shouldFail = true
10435		t.test.expectedError = ":UNEXPECTED_MESSAGE:"
10436		t.test.expectedLocalError = "remote error: unexpected message"
10437
10438		if t.test.config.MaxVersion >= VersionTLS13 && t.messageType == typeServerHello {
10439			// In TLS 1.3, a bad ServerHello means the client sends
10440			// an unencrypted alert while the server expects
10441			// encryption, so the alert is not readable by runner.
10442			t.test.expectedLocalError = "local error: bad record MAC"
10443		}
10444
10445		testCases = append(testCases, t.test)
10446	}
10447
10448	// The processing order for TLS 1.3 version negotiation is such that one
10449	// may accidentally accept a HelloRetryRequest in lieu of ServerHello in
10450	// TLS 1.2. Test that we do not do this.
10451	testCases = append(testCases, testCase{
10452		name: "SendServerHelloAsHelloRetryRequest",
10453		config: Config{
10454			MaxVersion: VersionTLS12,
10455			Bugs: ProtocolBugs{
10456				SendServerHelloAsHelloRetryRequest: true,
10457			},
10458		},
10459		shouldFail:         true,
10460		expectedError:      ":UNEXPECTED_MESSAGE:",
10461		expectedLocalError: "remote error: unexpected message",
10462	})
10463}
10464
10465func addTrailingMessageDataTests() {
10466	for _, t := range makePerMessageTests() {
10467		t.test.name = "TrailingMessageData-" + t.test.name
10468		t.test.config.Bugs.SendTrailingMessageData = t.messageType
10469		t.test.shouldFail = true
10470		t.test.expectedError = ":DECODE_ERROR:"
10471		t.test.expectedLocalError = "remote error: error decoding message"
10472
10473		if t.test.config.MaxVersion >= VersionTLS13 && t.messageType == typeServerHello {
10474			// In TLS 1.3, a bad ServerHello means the client sends
10475			// an unencrypted alert while the server expects
10476			// encryption, so the alert is not readable by runner.
10477			t.test.expectedLocalError = "local error: bad record MAC"
10478		}
10479
10480		if t.messageType == typeFinished {
10481			// Bad Finished messages read as the verify data having
10482			// the wrong length.
10483			t.test.expectedError = ":DIGEST_CHECK_FAILED:"
10484			t.test.expectedLocalError = "remote error: error decrypting message"
10485		}
10486
10487		testCases = append(testCases, t.test)
10488	}
10489}
10490
10491func addTLS13HandshakeTests() {
10492	testCases = append(testCases, testCase{
10493		testType: clientTest,
10494		name:     "NegotiatePSKResumption-TLS13",
10495		config: Config{
10496			MaxVersion: VersionTLS13,
10497			Bugs: ProtocolBugs{
10498				NegotiatePSKResumption: true,
10499			},
10500		},
10501		resumeSession: true,
10502		shouldFail:    true,
10503		expectedError: ":MISSING_KEY_SHARE:",
10504	})
10505
10506	testCases = append(testCases, testCase{
10507		testType: clientTest,
10508		name:     "MissingKeyShare-Client",
10509		config: Config{
10510			MaxVersion: VersionTLS13,
10511			Bugs: ProtocolBugs{
10512				MissingKeyShare: true,
10513			},
10514		},
10515		shouldFail:    true,
10516		expectedError: ":MISSING_KEY_SHARE:",
10517	})
10518
10519	testCases = append(testCases, testCase{
10520		testType: serverTest,
10521		name:     "MissingKeyShare-Server",
10522		config: Config{
10523			MaxVersion: VersionTLS13,
10524			Bugs: ProtocolBugs{
10525				MissingKeyShare: true,
10526			},
10527		},
10528		shouldFail:    true,
10529		expectedError: ":MISSING_KEY_SHARE:",
10530	})
10531
10532	testCases = append(testCases, testCase{
10533		testType: serverTest,
10534		name:     "DuplicateKeyShares",
10535		config: Config{
10536			MaxVersion: VersionTLS13,
10537			Bugs: ProtocolBugs{
10538				DuplicateKeyShares: true,
10539			},
10540		},
10541		shouldFail:    true,
10542		expectedError: ":DUPLICATE_KEY_SHARE:",
10543	})
10544
10545	testCases = append(testCases, testCase{
10546		testType: serverTest,
10547		name:     "SkipEarlyData",
10548		config: Config{
10549			MaxVersion: VersionTLS13,
10550			Bugs: ProtocolBugs{
10551				SendFakeEarlyDataLength: 4,
10552			},
10553		},
10554	})
10555
10556	testCases = append(testCases, testCase{
10557		testType: serverTest,
10558		name:     "SkipEarlyData-TLS13Experiment",
10559		config: Config{
10560			MaxVersion:   VersionTLS13,
10561			TLS13Variant: TLS13Experiment,
10562			Bugs: ProtocolBugs{
10563				SendFakeEarlyDataLength: 4,
10564			},
10565		},
10566		flags: []string{"-tls13-variant", "1"},
10567	})
10568
10569	testCases = append(testCases, testCase{
10570		testType: serverTest,
10571		name:     "SkipEarlyData-TLS13RecordTypeExperiment",
10572		config: Config{
10573			MaxVersion:   VersionTLS13,
10574			TLS13Variant: TLS13RecordTypeExperiment,
10575			Bugs: ProtocolBugs{
10576				SendFakeEarlyDataLength: 4,
10577			},
10578		},
10579		flags: []string{"-tls13-variant", "2"},
10580	})
10581
10582	testCases = append(testCases, testCase{
10583		testType: serverTest,
10584		name:     "SkipEarlyData-OmitEarlyDataExtension",
10585		config: Config{
10586			MaxVersion: VersionTLS13,
10587			Bugs: ProtocolBugs{
10588				SendFakeEarlyDataLength: 4,
10589				OmitEarlyDataExtension:  true,
10590			},
10591		},
10592		shouldFail:    true,
10593		expectedError: ":DECRYPTION_FAILED_OR_BAD_RECORD_MAC:",
10594	})
10595
10596	testCases = append(testCases, testCase{
10597		testType: serverTest,
10598		name:     "SkipEarlyData-TooMuchData",
10599		config: Config{
10600			MaxVersion: VersionTLS13,
10601			Bugs: ProtocolBugs{
10602				SendFakeEarlyDataLength: 16384 + 1,
10603			},
10604		},
10605		shouldFail:    true,
10606		expectedError: ":TOO_MUCH_SKIPPED_EARLY_DATA:",
10607	})
10608
10609	testCases = append(testCases, testCase{
10610		testType: serverTest,
10611		name:     "SkipEarlyData-Interleaved",
10612		config: Config{
10613			MaxVersion: VersionTLS13,
10614			Bugs: ProtocolBugs{
10615				SendFakeEarlyDataLength: 4,
10616				InterleaveEarlyData:     true,
10617			},
10618		},
10619		shouldFail:    true,
10620		expectedError: ":DECRYPTION_FAILED_OR_BAD_RECORD_MAC:",
10621	})
10622
10623	testCases = append(testCases, testCase{
10624		testType: serverTest,
10625		name:     "SkipEarlyData-EarlyDataInTLS12",
10626		config: Config{
10627			MaxVersion: VersionTLS13,
10628			Bugs: ProtocolBugs{
10629				SendFakeEarlyDataLength: 4,
10630			},
10631		},
10632		shouldFail:    true,
10633		expectedError: ":UNEXPECTED_RECORD:",
10634		flags:         []string{"-max-version", strconv.Itoa(VersionTLS12)},
10635	})
10636
10637	testCases = append(testCases, testCase{
10638		testType: serverTest,
10639		name:     "SkipEarlyData-HRR",
10640		config: Config{
10641			MaxVersion: VersionTLS13,
10642			Bugs: ProtocolBugs{
10643				SendFakeEarlyDataLength: 4,
10644			},
10645			DefaultCurves: []CurveID{},
10646		},
10647	})
10648
10649	testCases = append(testCases, testCase{
10650		testType: serverTest,
10651		name:     "SkipEarlyData-HRR-Interleaved",
10652		config: Config{
10653			MaxVersion: VersionTLS13,
10654			Bugs: ProtocolBugs{
10655				SendFakeEarlyDataLength: 4,
10656				InterleaveEarlyData:     true,
10657			},
10658			DefaultCurves: []CurveID{},
10659		},
10660		shouldFail:    true,
10661		expectedError: ":UNEXPECTED_RECORD:",
10662	})
10663
10664	testCases = append(testCases, testCase{
10665		testType: serverTest,
10666		name:     "SkipEarlyData-HRR-TooMuchData",
10667		config: Config{
10668			MaxVersion: VersionTLS13,
10669			Bugs: ProtocolBugs{
10670				SendFakeEarlyDataLength: 16384 + 1,
10671			},
10672			DefaultCurves: []CurveID{},
10673		},
10674		shouldFail:    true,
10675		expectedError: ":TOO_MUCH_SKIPPED_EARLY_DATA:",
10676	})
10677
10678	// Test that skipping early data looking for cleartext correctly
10679	// processes an alert record.
10680	testCases = append(testCases, testCase{
10681		testType: serverTest,
10682		name:     "SkipEarlyData-HRR-FatalAlert",
10683		config: Config{
10684			MaxVersion: VersionTLS13,
10685			Bugs: ProtocolBugs{
10686				SendEarlyAlert:          true,
10687				SendFakeEarlyDataLength: 4,
10688			},
10689			DefaultCurves: []CurveID{},
10690		},
10691		shouldFail:    true,
10692		expectedError: ":SSLV3_ALERT_HANDSHAKE_FAILURE:",
10693	})
10694
10695	testCases = append(testCases, testCase{
10696		testType: serverTest,
10697		name:     "SkipEarlyData-SecondClientHelloEarlyData",
10698		config: Config{
10699			MaxVersion: VersionTLS13,
10700			Bugs: ProtocolBugs{
10701				SendEarlyDataOnSecondClientHello: true,
10702			},
10703			DefaultCurves: []CurveID{},
10704		},
10705		shouldFail:         true,
10706		expectedLocalError: "remote error: bad record MAC",
10707	})
10708
10709	testCases = append(testCases, testCase{
10710		testType: clientTest,
10711		name:     "EmptyEncryptedExtensions",
10712		config: Config{
10713			MaxVersion: VersionTLS13,
10714			Bugs: ProtocolBugs{
10715				EmptyEncryptedExtensions: true,
10716			},
10717		},
10718		shouldFail:         true,
10719		expectedLocalError: "remote error: error decoding message",
10720	})
10721
10722	testCases = append(testCases, testCase{
10723		testType: clientTest,
10724		name:     "EncryptedExtensionsWithKeyShare",
10725		config: Config{
10726			MaxVersion: VersionTLS13,
10727			Bugs: ProtocolBugs{
10728				EncryptedExtensionsWithKeyShare: true,
10729			},
10730		},
10731		shouldFail:         true,
10732		expectedLocalError: "remote error: unsupported extension",
10733	})
10734
10735	testCases = append(testCases, testCase{
10736		testType: serverTest,
10737		name:     "SendHelloRetryRequest",
10738		config: Config{
10739			MaxVersion: VersionTLS13,
10740			// Require a HelloRetryRequest for every curve.
10741			DefaultCurves: []CurveID{},
10742		},
10743		expectedCurveID: CurveX25519,
10744	})
10745
10746	testCases = append(testCases, testCase{
10747		testType: serverTest,
10748		name:     "SendHelloRetryRequest-2",
10749		config: Config{
10750			MaxVersion:    VersionTLS13,
10751			DefaultCurves: []CurveID{CurveP384},
10752		},
10753		// Although the ClientHello did not predict our preferred curve,
10754		// we always select it whether it is predicted or not.
10755		expectedCurveID: CurveX25519,
10756	})
10757
10758	testCases = append(testCases, testCase{
10759		name: "UnknownCurve-HelloRetryRequest",
10760		config: Config{
10761			MaxVersion: VersionTLS13,
10762			// P-384 requires HelloRetryRequest in BoringSSL.
10763			CurvePreferences: []CurveID{CurveP384},
10764			Bugs: ProtocolBugs{
10765				SendHelloRetryRequestCurve: bogusCurve,
10766			},
10767		},
10768		shouldFail:    true,
10769		expectedError: ":WRONG_CURVE:",
10770	})
10771
10772	testCases = append(testCases, testCase{
10773		name: "DisabledCurve-HelloRetryRequest",
10774		config: Config{
10775			MaxVersion:       VersionTLS13,
10776			CurvePreferences: []CurveID{CurveP256},
10777			Bugs: ProtocolBugs{
10778				IgnorePeerCurvePreferences: true,
10779			},
10780		},
10781		flags:         []string{"-p384-only"},
10782		shouldFail:    true,
10783		expectedError: ":WRONG_CURVE:",
10784	})
10785
10786	testCases = append(testCases, testCase{
10787		name: "UnnecessaryHelloRetryRequest",
10788		config: Config{
10789			MaxVersion:       VersionTLS13,
10790			CurvePreferences: []CurveID{CurveX25519},
10791			Bugs: ProtocolBugs{
10792				SendHelloRetryRequestCurve: CurveX25519,
10793			},
10794		},
10795		shouldFail:    true,
10796		expectedError: ":WRONG_CURVE:",
10797	})
10798
10799	testCases = append(testCases, testCase{
10800		name: "SecondHelloRetryRequest",
10801		config: Config{
10802			MaxVersion: VersionTLS13,
10803			// P-384 requires HelloRetryRequest in BoringSSL.
10804			CurvePreferences: []CurveID{CurveP384},
10805			Bugs: ProtocolBugs{
10806				SecondHelloRetryRequest: true,
10807			},
10808		},
10809		shouldFail:    true,
10810		expectedError: ":UNEXPECTED_MESSAGE:",
10811	})
10812
10813	testCases = append(testCases, testCase{
10814		name: "HelloRetryRequest-Empty",
10815		config: Config{
10816			MaxVersion: VersionTLS13,
10817			Bugs: ProtocolBugs{
10818				AlwaysSendHelloRetryRequest: true,
10819			},
10820		},
10821		shouldFail:    true,
10822		expectedError: ":DECODE_ERROR:",
10823	})
10824
10825	testCases = append(testCases, testCase{
10826		name: "HelloRetryRequest-DuplicateCurve",
10827		config: Config{
10828			MaxVersion: VersionTLS13,
10829			// P-384 requires a HelloRetryRequest against BoringSSL's default
10830			// configuration. Assert this ExpectMissingKeyShare.
10831			CurvePreferences: []CurveID{CurveP384},
10832			Bugs: ProtocolBugs{
10833				ExpectMissingKeyShare:                true,
10834				DuplicateHelloRetryRequestExtensions: true,
10835			},
10836		},
10837		shouldFail:         true,
10838		expectedError:      ":DUPLICATE_EXTENSION:",
10839		expectedLocalError: "remote error: illegal parameter",
10840	})
10841
10842	testCases = append(testCases, testCase{
10843		name: "HelloRetryRequest-Cookie",
10844		config: Config{
10845			MaxVersion: VersionTLS13,
10846			Bugs: ProtocolBugs{
10847				SendHelloRetryRequestCookie: []byte("cookie"),
10848			},
10849		},
10850	})
10851
10852	testCases = append(testCases, testCase{
10853		name: "HelloRetryRequest-DuplicateCookie",
10854		config: Config{
10855			MaxVersion: VersionTLS13,
10856			Bugs: ProtocolBugs{
10857				SendHelloRetryRequestCookie:          []byte("cookie"),
10858				DuplicateHelloRetryRequestExtensions: true,
10859			},
10860		},
10861		shouldFail:         true,
10862		expectedError:      ":DUPLICATE_EXTENSION:",
10863		expectedLocalError: "remote error: illegal parameter",
10864	})
10865
10866	testCases = append(testCases, testCase{
10867		name: "HelloRetryRequest-EmptyCookie",
10868		config: Config{
10869			MaxVersion: VersionTLS13,
10870			Bugs: ProtocolBugs{
10871				SendHelloRetryRequestCookie: []byte{},
10872			},
10873		},
10874		shouldFail:    true,
10875		expectedError: ":DECODE_ERROR:",
10876	})
10877
10878	testCases = append(testCases, testCase{
10879		name: "HelloRetryRequest-Cookie-Curve",
10880		config: Config{
10881			MaxVersion: VersionTLS13,
10882			// P-384 requires HelloRetryRequest in BoringSSL.
10883			CurvePreferences: []CurveID{CurveP384},
10884			Bugs: ProtocolBugs{
10885				SendHelloRetryRequestCookie: []byte("cookie"),
10886				ExpectMissingKeyShare:       true,
10887			},
10888		},
10889	})
10890
10891	testCases = append(testCases, testCase{
10892		name: "HelloRetryRequest-Unknown",
10893		config: Config{
10894			MaxVersion: VersionTLS13,
10895			Bugs: ProtocolBugs{
10896				CustomHelloRetryRequestExtension: "extension",
10897			},
10898		},
10899		shouldFail:         true,
10900		expectedError:      ":UNEXPECTED_EXTENSION:",
10901		expectedLocalError: "remote error: unsupported extension",
10902	})
10903
10904	testCases = append(testCases, testCase{
10905		testType: serverTest,
10906		name:     "SecondClientHelloMissingKeyShare",
10907		config: Config{
10908			MaxVersion:    VersionTLS13,
10909			DefaultCurves: []CurveID{},
10910			Bugs: ProtocolBugs{
10911				SecondClientHelloMissingKeyShare: true,
10912			},
10913		},
10914		shouldFail:    true,
10915		expectedError: ":MISSING_KEY_SHARE:",
10916	})
10917
10918	testCases = append(testCases, testCase{
10919		testType: serverTest,
10920		name:     "SecondClientHelloWrongCurve",
10921		config: Config{
10922			MaxVersion:    VersionTLS13,
10923			DefaultCurves: []CurveID{},
10924			Bugs: ProtocolBugs{
10925				MisinterpretHelloRetryRequestCurve: CurveP521,
10926			},
10927		},
10928		shouldFail:    true,
10929		expectedError: ":WRONG_CURVE:",
10930	})
10931
10932	testCases = append(testCases, testCase{
10933		name: "HelloRetryRequestVersionMismatch",
10934		config: Config{
10935			MaxVersion: VersionTLS13,
10936			// P-384 requires HelloRetryRequest in BoringSSL.
10937			CurvePreferences: []CurveID{CurveP384},
10938			Bugs: ProtocolBugs{
10939				SendServerHelloVersion: 0x0305,
10940			},
10941		},
10942		shouldFail:    true,
10943		expectedError: ":WRONG_VERSION_NUMBER:",
10944	})
10945
10946	testCases = append(testCases, testCase{
10947		name: "HelloRetryRequestCurveMismatch",
10948		config: Config{
10949			MaxVersion: VersionTLS13,
10950			// P-384 requires HelloRetryRequest in BoringSSL.
10951			CurvePreferences: []CurveID{CurveP384},
10952			Bugs: ProtocolBugs{
10953				// Send P-384 (correct) in the HelloRetryRequest.
10954				SendHelloRetryRequestCurve: CurveP384,
10955				// But send P-256 in the ServerHello.
10956				SendCurve: CurveP256,
10957			},
10958		},
10959		shouldFail:    true,
10960		expectedError: ":WRONG_CURVE:",
10961	})
10962
10963	// Test the server selecting a curve that requires a HelloRetryRequest
10964	// without sending it.
10965	testCases = append(testCases, testCase{
10966		name: "SkipHelloRetryRequest",
10967		config: Config{
10968			MaxVersion: VersionTLS13,
10969			// P-384 requires HelloRetryRequest in BoringSSL.
10970			CurvePreferences: []CurveID{CurveP384},
10971			Bugs: ProtocolBugs{
10972				SkipHelloRetryRequest: true,
10973			},
10974		},
10975		shouldFail:    true,
10976		expectedError: ":WRONG_CURVE:",
10977	})
10978
10979	testCases = append(testCases, testCase{
10980		name: "TLS13-RequestContextInHandshake",
10981		config: Config{
10982			MaxVersion: VersionTLS13,
10983			MinVersion: VersionTLS13,
10984			ClientAuth: RequireAnyClientCert,
10985			Bugs: ProtocolBugs{
10986				SendRequestContext: []byte("request context"),
10987			},
10988		},
10989		flags: []string{
10990			"-cert-file", path.Join(*resourceDir, rsaCertificateFile),
10991			"-key-file", path.Join(*resourceDir, rsaKeyFile),
10992		},
10993		shouldFail:    true,
10994		expectedError: ":DECODE_ERROR:",
10995	})
10996
10997	testCases = append(testCases, testCase{
10998		testType: serverTest,
10999		name:     "TLS13-TrailingKeyShareData",
11000		config: Config{
11001			MaxVersion: VersionTLS13,
11002			Bugs: ProtocolBugs{
11003				TrailingKeyShareData: true,
11004			},
11005		},
11006		shouldFail:    true,
11007		expectedError: ":DECODE_ERROR:",
11008	})
11009
11010	testCases = append(testCases, testCase{
11011		name: "TLS13-AlwaysSelectPSKIdentity",
11012		config: Config{
11013			MaxVersion: VersionTLS13,
11014			Bugs: ProtocolBugs{
11015				AlwaysSelectPSKIdentity: true,
11016			},
11017		},
11018		shouldFail:    true,
11019		expectedError: ":UNEXPECTED_EXTENSION:",
11020	})
11021
11022	testCases = append(testCases, testCase{
11023		name: "TLS13-InvalidPSKIdentity",
11024		config: Config{
11025			MaxVersion: VersionTLS13,
11026			Bugs: ProtocolBugs{
11027				SelectPSKIdentityOnResume: 1,
11028			},
11029		},
11030		resumeSession: true,
11031		shouldFail:    true,
11032		expectedError: ":PSK_IDENTITY_NOT_FOUND:",
11033	})
11034
11035	testCases = append(testCases, testCase{
11036		testType: serverTest,
11037		name:     "TLS13-ExtraPSKIdentity",
11038		config: Config{
11039			MaxVersion: VersionTLS13,
11040			Bugs: ProtocolBugs{
11041				ExtraPSKIdentity:   true,
11042				SendExtraPSKBinder: true,
11043			},
11044		},
11045		resumeSession: true,
11046	})
11047
11048	// Test that unknown NewSessionTicket extensions are tolerated.
11049	testCases = append(testCases, testCase{
11050		name: "TLS13-CustomTicketExtension",
11051		config: Config{
11052			MaxVersion: VersionTLS13,
11053			Bugs: ProtocolBugs{
11054				CustomTicketExtension: "1234",
11055			},
11056		},
11057	})
11058
11059	testCases = append(testCases, testCase{
11060		testType: clientTest,
11061		name:     "TLS13-EarlyData-Reject-Client",
11062		config: Config{
11063			MaxVersion:       VersionTLS13,
11064			MaxEarlyDataSize: 16384,
11065		},
11066		resumeConfig: &Config{
11067			MaxVersion:       VersionTLS13,
11068			MaxEarlyDataSize: 16384,
11069			Bugs: ProtocolBugs{
11070				AlwaysRejectEarlyData: true,
11071			},
11072		},
11073		resumeSession: true,
11074		flags: []string{
11075			"-enable-early-data",
11076			"-expect-early-data-info",
11077			"-expect-reject-early-data",
11078			"-on-resume-shim-writes-first",
11079		},
11080	})
11081
11082	testCases = append(testCases, testCase{
11083		testType: clientTest,
11084		name:     "TLS13Experiment-EarlyData-Reject-Client",
11085		config: Config{
11086			MaxVersion:       VersionTLS13,
11087			MaxEarlyDataSize: 16384,
11088			TLS13Variant:     TLS13Experiment,
11089		},
11090		resumeConfig: &Config{
11091			MaxVersion:       VersionTLS13,
11092			TLS13Variant:     TLS13Experiment,
11093			MaxEarlyDataSize: 16384,
11094			Bugs: ProtocolBugs{
11095				AlwaysRejectEarlyData: true,
11096			},
11097		},
11098		resumeSession: true,
11099		flags: []string{
11100			"-enable-early-data",
11101			"-expect-early-data-info",
11102			"-expect-reject-early-data",
11103			"-on-resume-shim-writes-first",
11104			"-tls13-variant", "1",
11105		},
11106	})
11107
11108	testCases = append(testCases, testCase{
11109		testType: clientTest,
11110		name:     "TLS13RecordTypeExperiment-EarlyData-Reject-Client",
11111		config: Config{
11112			MaxVersion:       VersionTLS13,
11113			MaxEarlyDataSize: 16384,
11114			TLS13Variant:     TLS13RecordTypeExperiment,
11115		},
11116		resumeConfig: &Config{
11117			MaxVersion:       VersionTLS13,
11118			TLS13Variant:     TLS13RecordTypeExperiment,
11119			MaxEarlyDataSize: 16384,
11120			Bugs: ProtocolBugs{
11121				AlwaysRejectEarlyData: true,
11122			},
11123		},
11124		resumeSession: true,
11125		flags: []string{
11126			"-enable-early-data",
11127			"-expect-early-data-info",
11128			"-expect-reject-early-data",
11129			"-on-resume-shim-writes-first",
11130			"-tls13-variant", "2",
11131		},
11132	})
11133
11134	testCases = append(testCases, testCase{
11135		testType: clientTest,
11136		name:     "TLS13-EarlyData-RejectTicket-Client",
11137		config: Config{
11138			MaxVersion:       VersionTLS13,
11139			MaxEarlyDataSize: 16384,
11140			Certificates:     []Certificate{rsaCertificate},
11141		},
11142		resumeConfig: &Config{
11143			MaxVersion:             VersionTLS13,
11144			MaxEarlyDataSize:       16384,
11145			Certificates:           []Certificate{ecdsaP256Certificate},
11146			SessionTicketsDisabled: true,
11147		},
11148		resumeSession:        true,
11149		expectResumeRejected: true,
11150		flags: []string{
11151			"-enable-early-data",
11152			"-expect-early-data-info",
11153			"-expect-reject-early-data",
11154			"-on-resume-shim-writes-first",
11155			"-on-initial-expect-peer-cert-file", path.Join(*resourceDir, rsaCertificateFile),
11156			"-on-resume-expect-peer-cert-file", path.Join(*resourceDir, rsaCertificateFile),
11157			"-on-retry-expect-peer-cert-file", path.Join(*resourceDir, ecdsaP256CertificateFile),
11158			// Session tickets are disabled, so the runner will not send a ticket.
11159			"-on-retry-expect-no-session",
11160		},
11161	})
11162
11163	testCases = append(testCases, testCase{
11164		testType: clientTest,
11165		name:     "TLS13-EarlyData-HRR-Client",
11166		config: Config{
11167			MaxVersion:       VersionTLS13,
11168			MaxEarlyDataSize: 16384,
11169		},
11170		resumeConfig: &Config{
11171			MaxVersion:       VersionTLS13,
11172			MaxEarlyDataSize: 16384,
11173			Bugs: ProtocolBugs{
11174				SendHelloRetryRequestCookie: []byte{1, 2, 3, 4},
11175			},
11176		},
11177		resumeSession: true,
11178		flags: []string{
11179			"-enable-early-data",
11180			"-expect-early-data-info",
11181			"-expect-reject-early-data",
11182		},
11183	})
11184
11185	// The client must check the server does not send the early_data
11186	// extension while rejecting the session.
11187	testCases = append(testCases, testCase{
11188		testType: clientTest,
11189		name:     "TLS13-EarlyDataWithoutResume-Client",
11190		config: Config{
11191			MaxVersion:       VersionTLS13,
11192			MaxEarlyDataSize: 16384,
11193		},
11194		resumeConfig: &Config{
11195			MaxVersion:             VersionTLS13,
11196			SessionTicketsDisabled: true,
11197			Bugs: ProtocolBugs{
11198				SendEarlyDataExtension: true,
11199			},
11200		},
11201		resumeSession: true,
11202		flags: []string{
11203			"-enable-early-data",
11204			"-expect-early-data-info",
11205		},
11206		shouldFail:    true,
11207		expectedError: ":UNEXPECTED_EXTENSION:",
11208	})
11209
11210	// The client must fail with a dedicated error code if the server
11211	// responds with TLS 1.2 when offering 0-RTT.
11212	testCases = append(testCases, testCase{
11213		testType: clientTest,
11214		name:     "TLS13-EarlyDataVersionDowngrade-Client",
11215		config: Config{
11216			MaxVersion:       VersionTLS13,
11217			MaxEarlyDataSize: 16384,
11218		},
11219		resumeConfig: &Config{
11220			MaxVersion: VersionTLS12,
11221		},
11222		resumeSession: true,
11223		flags: []string{
11224			"-enable-early-data",
11225			"-expect-early-data-info",
11226		},
11227		shouldFail:    true,
11228		expectedError: ":WRONG_VERSION_ON_EARLY_DATA:",
11229	})
11230
11231	// Test that the client rejects an (unsolicited) early_data extension if
11232	// the server sent an HRR.
11233	testCases = append(testCases, testCase{
11234		testType: clientTest,
11235		name:     "TLS13-ServerAcceptsEarlyDataOnHRR-Client",
11236		config: Config{
11237			MaxVersion:       VersionTLS13,
11238			MaxEarlyDataSize: 16384,
11239		},
11240		resumeConfig: &Config{
11241			MaxVersion:       VersionTLS13,
11242			MaxEarlyDataSize: 16384,
11243			Bugs: ProtocolBugs{
11244				SendHelloRetryRequestCookie: []byte{1, 2, 3, 4},
11245				SendEarlyDataExtension:      true,
11246			},
11247		},
11248		resumeSession: true,
11249		flags: []string{
11250			"-enable-early-data",
11251			"-expect-early-data-info",
11252			"-expect-reject-early-data",
11253		},
11254		shouldFail:    true,
11255		expectedError: ":UNEXPECTED_EXTENSION:",
11256	})
11257
11258	fooString := "foo"
11259	barString := "bar"
11260
11261	// Test that the client reports the correct ALPN after a 0-RTT reject
11262	// that changed it.
11263	testCases = append(testCases, testCase{
11264		testType: clientTest,
11265		name:     "TLS13-EarlyData-ALPNMismatch-Client",
11266		config: Config{
11267			MaxVersion:       VersionTLS13,
11268			MaxEarlyDataSize: 16384,
11269			Bugs: ProtocolBugs{
11270				ALPNProtocol: &fooString,
11271			},
11272		},
11273		resumeConfig: &Config{
11274			MaxVersion:       VersionTLS13,
11275			MaxEarlyDataSize: 16384,
11276			Bugs: ProtocolBugs{
11277				ALPNProtocol: &barString,
11278			},
11279		},
11280		resumeSession: true,
11281		flags: []string{
11282			"-advertise-alpn", "\x03foo\x03bar",
11283			"-enable-early-data",
11284			"-expect-early-data-info",
11285			"-expect-reject-early-data",
11286			"-on-initial-expect-alpn", "foo",
11287			"-on-resume-expect-alpn", "foo",
11288			"-on-retry-expect-alpn", "bar",
11289		},
11290	})
11291
11292	// Test that the client reports the correct ALPN after a 0-RTT reject if
11293	// ALPN was omitted from the first connection.
11294	testCases = append(testCases, testCase{
11295		testType: clientTest,
11296		name:     "TLS13-EarlyData-ALPNOmitted1-Client",
11297		config: Config{
11298			MaxVersion:       VersionTLS13,
11299			MaxEarlyDataSize: 16384,
11300		},
11301		resumeConfig: &Config{
11302			MaxVersion:       VersionTLS13,
11303			MaxEarlyDataSize: 16384,
11304			NextProtos:       []string{"foo"},
11305		},
11306		resumeSession: true,
11307		flags: []string{
11308			"-advertise-alpn", "\x03foo\x03bar",
11309			"-enable-early-data",
11310			"-expect-early-data-info",
11311			"-expect-reject-early-data",
11312			"-on-initial-expect-alpn", "",
11313			"-on-resume-expect-alpn", "",
11314			"-on-retry-expect-alpn", "foo",
11315			"-on-resume-shim-writes-first",
11316		},
11317	})
11318
11319	// Test that the client reports the correct ALPN after a 0-RTT reject if
11320	// ALPN was omitted from the second connection.
11321	testCases = append(testCases, testCase{
11322		testType: clientTest,
11323		name:     "TLS13-EarlyData-ALPNOmitted2-Client",
11324		config: Config{
11325			MaxVersion:       VersionTLS13,
11326			MaxEarlyDataSize: 16384,
11327			NextProtos:       []string{"foo"},
11328		},
11329		resumeConfig: &Config{
11330			MaxVersion:       VersionTLS13,
11331			MaxEarlyDataSize: 16384,
11332		},
11333		resumeSession: true,
11334		flags: []string{
11335			"-advertise-alpn", "\x03foo\x03bar",
11336			"-enable-early-data",
11337			"-expect-early-data-info",
11338			"-expect-reject-early-data",
11339			"-on-initial-expect-alpn", "foo",
11340			"-on-resume-expect-alpn", "foo",
11341			"-on-retry-expect-alpn", "",
11342			"-on-resume-shim-writes-first",
11343		},
11344	})
11345
11346	// Test that the client enforces ALPN match on 0-RTT accept.
11347	testCases = append(testCases, testCase{
11348		testType: clientTest,
11349		name:     "TLS13-EarlyData-BadALPNMismatch-Client",
11350		config: Config{
11351			MaxVersion:       VersionTLS13,
11352			MaxEarlyDataSize: 16384,
11353			Bugs: ProtocolBugs{
11354				ALPNProtocol: &fooString,
11355			},
11356		},
11357		resumeConfig: &Config{
11358			MaxVersion:       VersionTLS13,
11359			MaxEarlyDataSize: 16384,
11360			Bugs: ProtocolBugs{
11361				AlwaysAcceptEarlyData: true,
11362				ALPNProtocol:          &barString,
11363			},
11364		},
11365		resumeSession: true,
11366		flags: []string{
11367			"-advertise-alpn", "\x03foo\x03bar",
11368			"-enable-early-data",
11369			"-expect-early-data-info",
11370			"-on-initial-expect-alpn", "foo",
11371			"-on-resume-expect-alpn", "foo",
11372			"-on-retry-expect-alpn", "bar",
11373		},
11374		shouldFail:    true,
11375		expectedError: ":ALPN_MISMATCH_ON_EARLY_DATA:",
11376	})
11377
11378	// Test that the server correctly rejects 0-RTT when the previous
11379	// session did not allow early data on resumption.
11380	testCases = append(testCases, testCase{
11381		testType: serverTest,
11382		name:     "TLS13-EarlyData-NonZeroRTTSession-Server",
11383		config: Config{
11384			MaxVersion: VersionTLS13,
11385		},
11386		resumeConfig: &Config{
11387			MaxVersion: VersionTLS13,
11388			Bugs: ProtocolBugs{
11389				SendEarlyData:           [][]byte{{1, 2, 3, 4}},
11390				ExpectEarlyDataAccepted: false,
11391			},
11392		},
11393		resumeSession: true,
11394		flags: []string{
11395			"-on-resume-enable-early-data",
11396			"-expect-reject-early-data",
11397		},
11398	})
11399
11400	// Test that we reject early data where ALPN is omitted from the first
11401	// connection.
11402	testCases = append(testCases, testCase{
11403		testType: serverTest,
11404		name:     "TLS13-EarlyData-ALPNOmitted1-Server",
11405		config: Config{
11406			MaxVersion: VersionTLS13,
11407			NextProtos: []string{},
11408		},
11409		resumeConfig: &Config{
11410			MaxVersion: VersionTLS13,
11411			NextProtos: []string{"foo"},
11412			Bugs: ProtocolBugs{
11413				SendEarlyData:           [][]byte{{1, 2, 3, 4}},
11414				ExpectEarlyDataAccepted: false,
11415			},
11416		},
11417		resumeSession: true,
11418		flags: []string{
11419			"-enable-early-data",
11420			"-on-initial-select-alpn", "",
11421			"-on-resume-select-alpn", "foo",
11422		},
11423	})
11424
11425	// Test that we reject early data where ALPN is omitted from the second
11426	// connection.
11427	testCases = append(testCases, testCase{
11428		testType: serverTest,
11429		name:     "TLS13-EarlyData-ALPNOmitted2-Server",
11430		config: Config{
11431			MaxVersion: VersionTLS13,
11432			NextProtos: []string{"foo"},
11433		},
11434		resumeConfig: &Config{
11435			MaxVersion: VersionTLS13,
11436			NextProtos: []string{},
11437			Bugs: ProtocolBugs{
11438				SendEarlyData:           [][]byte{{1, 2, 3, 4}},
11439				ExpectEarlyDataAccepted: false,
11440			},
11441		},
11442		resumeSession: true,
11443		flags: []string{
11444			"-enable-early-data",
11445			"-on-initial-select-alpn", "foo",
11446			"-on-resume-select-alpn", "",
11447		},
11448	})
11449
11450	// Test that we reject early data with mismatched ALPN.
11451	testCases = append(testCases, testCase{
11452		testType: serverTest,
11453		name:     "TLS13-EarlyData-ALPNMismatch-Server",
11454		config: Config{
11455			MaxVersion: VersionTLS13,
11456			NextProtos: []string{"foo"},
11457		},
11458		resumeConfig: &Config{
11459			MaxVersion: VersionTLS13,
11460			NextProtos: []string{"bar"},
11461			Bugs: ProtocolBugs{
11462				SendEarlyData:           [][]byte{{1, 2, 3, 4}},
11463				ExpectEarlyDataAccepted: false,
11464			},
11465		},
11466		resumeSession: true,
11467		flags: []string{
11468			"-enable-early-data",
11469			"-on-initial-select-alpn", "foo",
11470			"-on-resume-select-alpn", "bar",
11471		},
11472	})
11473
11474	// Test that the client offering 0-RTT and Channel ID forbids the server
11475	// from accepting both.
11476	testCases = append(testCases, testCase{
11477		testType: clientTest,
11478		name:     "TLS13-EarlyDataChannelID-AcceptBoth-Client",
11479		config: Config{
11480			MaxVersion:       VersionTLS13,
11481			MaxEarlyDataSize: 16384,
11482			RequestChannelID: true,
11483		},
11484		resumeSession:   true,
11485		expectChannelID: true,
11486		shouldFail:      true,
11487		expectedError:   ":CHANNEL_ID_ON_EARLY_DATA:",
11488		flags: []string{
11489			"-enable-early-data",
11490			"-expect-early-data-info",
11491			"-send-channel-id", path.Join(*resourceDir, channelIDKeyFile),
11492		},
11493	})
11494
11495	// Test that the client offering Channel ID and 0-RTT allows the server
11496	// to decline 0-RTT.
11497	testCases = append(testCases, testCase{
11498		testType: clientTest,
11499		name:     "TLS13-EarlyDataChannelID-AcceptChannelID-Client",
11500		config: Config{
11501			MaxVersion:       VersionTLS13,
11502			MaxEarlyDataSize: 16384,
11503			RequestChannelID: true,
11504			Bugs: ProtocolBugs{
11505				AlwaysRejectEarlyData: true,
11506			},
11507		},
11508		resumeSession:   true,
11509		expectChannelID: true,
11510		flags: []string{
11511			"-enable-early-data",
11512			"-expect-early-data-info",
11513			"-send-channel-id", path.Join(*resourceDir, channelIDKeyFile),
11514			"-expect-reject-early-data",
11515		},
11516	})
11517
11518	// Test that the client offering Channel ID and 0-RTT allows the server
11519	// to decline Channel ID.
11520	testCases = append(testCases, testCase{
11521		testType: clientTest,
11522		name:     "TLS13-EarlyDataChannelID-AcceptEarlyData-Client",
11523		config: Config{
11524			MaxVersion:       VersionTLS13,
11525			MaxEarlyDataSize: 16384,
11526		},
11527		resumeSession: true,
11528		flags: []string{
11529			"-enable-early-data",
11530			"-expect-early-data-info",
11531			"-send-channel-id", path.Join(*resourceDir, channelIDKeyFile),
11532			"-expect-accept-early-data",
11533		},
11534	})
11535
11536	// Test that the server supporting Channel ID and 0-RTT declines 0-RTT
11537	// if it would negotiate Channel ID.
11538	testCases = append(testCases, testCase{
11539		testType: serverTest,
11540		name:     "TLS13-EarlyDataChannelID-OfferBoth-Server",
11541		config: Config{
11542			MaxVersion: VersionTLS13,
11543			ChannelID:  channelIDKey,
11544			Bugs: ProtocolBugs{
11545				SendEarlyData:           [][]byte{{1, 2, 3, 4}},
11546				ExpectEarlyDataAccepted: false,
11547			},
11548		},
11549		resumeSession:   true,
11550		expectChannelID: true,
11551		flags: []string{
11552			"-enable-early-data",
11553			"-expect-reject-early-data",
11554			"-expect-channel-id",
11555			base64.StdEncoding.EncodeToString(channelIDBytes),
11556		},
11557	})
11558
11559	// Test that the server supporting Channel ID and 0-RTT accepts 0-RTT
11560	// if not offered Channel ID.
11561	testCases = append(testCases, testCase{
11562		testType: serverTest,
11563		name:     "TLS13-EarlyDataChannelID-OfferEarlyData-Server",
11564		config: Config{
11565			MaxVersion: VersionTLS13,
11566			Bugs: ProtocolBugs{
11567				SendEarlyData:           [][]byte{{1, 2, 3, 4}},
11568				ExpectEarlyDataAccepted: true,
11569				ExpectHalfRTTData:       [][]byte{{254, 253, 252, 251}},
11570			},
11571		},
11572		resumeSession:   true,
11573		expectChannelID: false,
11574		flags: []string{
11575			"-enable-early-data",
11576			"-expect-accept-early-data",
11577			"-enable-channel-id",
11578		},
11579	})
11580
11581	// Test that the server rejects 0-RTT streams without end_of_early_data.
11582	// The subsequent records should fail to decrypt.
11583	testCases = append(testCases, testCase{
11584		testType: serverTest,
11585		name:     "TLS13-EarlyData-SkipEndOfEarlyData",
11586		config: Config{
11587			MaxVersion: VersionTLS13,
11588			Bugs: ProtocolBugs{
11589				SendEarlyData:           [][]byte{{1, 2, 3, 4}},
11590				ExpectEarlyDataAccepted: true,
11591				SkipEndOfEarlyData:      true,
11592			},
11593		},
11594		resumeSession:      true,
11595		flags:              []string{"-enable-early-data"},
11596		shouldFail:         true,
11597		expectedLocalError: "remote error: bad record MAC",
11598		expectedError:      ":BAD_DECRYPT:",
11599	})
11600
11601	testCases = append(testCases, testCase{
11602		testType: serverTest,
11603		name:     "TLS13-EarlyData-UnexpectedHandshake-Server",
11604		config: Config{
11605			MaxVersion: VersionTLS13,
11606		},
11607		resumeConfig: &Config{
11608			MaxVersion: VersionTLS13,
11609			Bugs: ProtocolBugs{
11610				SendEarlyData:           [][]byte{{1, 2, 3, 4}},
11611				SendStrayEarlyHandshake: true,
11612				ExpectEarlyDataAccepted: true},
11613		},
11614		resumeSession:      true,
11615		shouldFail:         true,
11616		expectedError:      ":UNEXPECTED_RECORD:",
11617		expectedLocalError: "remote error: unexpected message",
11618		flags: []string{
11619			"-enable-early-data",
11620		},
11621	})
11622
11623	// Test that the client reports TLS 1.3 as the version while sending
11624	// early data.
11625	testCases = append(testCases, testCase{
11626		testType: clientTest,
11627		name:     "TLS13-EarlyData-Client-VersionAPI",
11628		config: Config{
11629			MaxVersion:       VersionTLS13,
11630			MaxEarlyDataSize: 16384,
11631		},
11632		resumeSession: true,
11633		flags: []string{
11634			"-enable-early-data",
11635			"-expect-early-data-info",
11636			"-expect-accept-early-data",
11637			"-expect-version", strconv.Itoa(VersionTLS13),
11638		},
11639	})
11640}
11641
11642func addTLS13CipherPreferenceTests() {
11643	// Test that client preference is honored if the shim has AES hardware
11644	// and ChaCha20-Poly1305 is preferred otherwise.
11645	testCases = append(testCases, testCase{
11646		testType: serverTest,
11647		name:     "TLS13-CipherPreference-Server-ChaCha20-AES",
11648		config: Config{
11649			MaxVersion: VersionTLS13,
11650			CipherSuites: []uint16{
11651				TLS_CHACHA20_POLY1305_SHA256,
11652				TLS_AES_128_GCM_SHA256,
11653			},
11654		},
11655		flags: []string{
11656			"-expect-cipher-aes", strconv.Itoa(int(TLS_CHACHA20_POLY1305_SHA256)),
11657			"-expect-cipher-no-aes", strconv.Itoa(int(TLS_CHACHA20_POLY1305_SHA256)),
11658		},
11659	})
11660
11661	testCases = append(testCases, testCase{
11662		testType: serverTest,
11663		name:     "TLS13-CipherPreference-Server-AES-ChaCha20",
11664		config: Config{
11665			MaxVersion: VersionTLS13,
11666			CipherSuites: []uint16{
11667				TLS_AES_128_GCM_SHA256,
11668				TLS_CHACHA20_POLY1305_SHA256,
11669			},
11670		},
11671		flags: []string{
11672			"-expect-cipher-aes", strconv.Itoa(int(TLS_AES_128_GCM_SHA256)),
11673			"-expect-cipher-no-aes", strconv.Itoa(int(TLS_CHACHA20_POLY1305_SHA256)),
11674		},
11675	})
11676
11677	// Test that the client orders ChaCha20-Poly1305 and AES-GCM based on
11678	// whether it has AES hardware.
11679	testCases = append(testCases, testCase{
11680		name: "TLS13-CipherPreference-Client",
11681		config: Config{
11682			MaxVersion: VersionTLS13,
11683			// Use the client cipher order. (This is the default but
11684			// is listed to be explicit.)
11685			PreferServerCipherSuites: false,
11686		},
11687		flags: []string{
11688			"-expect-cipher-aes", strconv.Itoa(int(TLS_AES_128_GCM_SHA256)),
11689			"-expect-cipher-no-aes", strconv.Itoa(int(TLS_CHACHA20_POLY1305_SHA256)),
11690		},
11691	})
11692}
11693
11694func addPeekTests() {
11695	// Test SSL_peek works, including on empty records.
11696	testCases = append(testCases, testCase{
11697		name:             "Peek-Basic",
11698		sendEmptyRecords: 1,
11699		flags:            []string{"-peek-then-read"},
11700	})
11701
11702	// Test SSL_peek can drive the initial handshake.
11703	testCases = append(testCases, testCase{
11704		name: "Peek-ImplicitHandshake",
11705		flags: []string{
11706			"-peek-then-read",
11707			"-implicit-handshake",
11708		},
11709	})
11710
11711	// Test SSL_peek can discover and drive a renegotiation.
11712	testCases = append(testCases, testCase{
11713		name: "Peek-Renegotiate",
11714		config: Config{
11715			MaxVersion: VersionTLS12,
11716		},
11717		renegotiate: 1,
11718		flags: []string{
11719			"-peek-then-read",
11720			"-renegotiate-freely",
11721			"-expect-total-renegotiations", "1",
11722		},
11723	})
11724
11725	// Test SSL_peek can discover a close_notify.
11726	testCases = append(testCases, testCase{
11727		name: "Peek-Shutdown",
11728		config: Config{
11729			Bugs: ProtocolBugs{
11730				ExpectCloseNotify: true,
11731			},
11732		},
11733		flags: []string{
11734			"-peek-then-read",
11735			"-check-close-notify",
11736		},
11737	})
11738
11739	// Test SSL_peek can discover an alert.
11740	testCases = append(testCases, testCase{
11741		name: "Peek-Alert",
11742		config: Config{
11743			Bugs: ProtocolBugs{
11744				SendSpuriousAlert: alertRecordOverflow,
11745			},
11746		},
11747		flags:         []string{"-peek-then-read"},
11748		shouldFail:    true,
11749		expectedError: ":TLSV1_ALERT_RECORD_OVERFLOW:",
11750	})
11751
11752	// Test SSL_peek can handle KeyUpdate.
11753	testCases = append(testCases, testCase{
11754		name: "Peek-KeyUpdate",
11755		config: Config{
11756			MaxVersion: VersionTLS13,
11757		},
11758		sendKeyUpdates:   1,
11759		keyUpdateRequest: keyUpdateNotRequested,
11760		flags:            []string{"-peek-then-read"},
11761	})
11762}
11763
11764func addRecordVersionTests() {
11765	for _, ver := range tlsVersions {
11766		// Test that the record version is enforced.
11767		testCases = append(testCases, testCase{
11768			name: "CheckRecordVersion-" + ver.name,
11769			config: Config{
11770				MinVersion: ver.version,
11771				MaxVersion: ver.version,
11772				Bugs: ProtocolBugs{
11773					SendRecordVersion: 0x03ff,
11774				},
11775			},
11776			tls13Variant:  ver.tls13Variant,
11777			shouldFail:    true,
11778			expectedError: ":WRONG_VERSION_NUMBER:",
11779		})
11780
11781		// Test that the ClientHello may use any record version, for
11782		// compatibility reasons.
11783		testCases = append(testCases, testCase{
11784			testType: serverTest,
11785			name:     "LooseInitialRecordVersion-" + ver.name,
11786			config: Config{
11787				MinVersion: ver.version,
11788				MaxVersion: ver.version,
11789				Bugs: ProtocolBugs{
11790					SendInitialRecordVersion: 0x03ff,
11791				},
11792			},
11793			tls13Variant: ver.tls13Variant,
11794		})
11795
11796		// Test that garbage ClientHello record versions are rejected.
11797		testCases = append(testCases, testCase{
11798			testType: serverTest,
11799			name:     "GarbageInitialRecordVersion-" + ver.name,
11800			config: Config{
11801				MinVersion: ver.version,
11802				MaxVersion: ver.version,
11803				Bugs: ProtocolBugs{
11804					SendInitialRecordVersion: 0xffff,
11805				},
11806			},
11807			tls13Variant:  ver.tls13Variant,
11808			shouldFail:    true,
11809			expectedError: ":WRONG_VERSION_NUMBER:",
11810		})
11811	}
11812}
11813
11814func addCertificateTests() {
11815	// Test that a certificate chain with intermediate may be sent and
11816	// received as both client and server.
11817	for _, ver := range tlsVersions {
11818		testCases = append(testCases, testCase{
11819			testType: clientTest,
11820			name:     "SendReceiveIntermediate-Client-" + ver.name,
11821			config: Config{
11822				MinVersion:   ver.version,
11823				MaxVersion:   ver.version,
11824				Certificates: []Certificate{rsaChainCertificate},
11825				ClientAuth:   RequireAnyClientCert,
11826			},
11827			tls13Variant:          ver.tls13Variant,
11828			expectPeerCertificate: &rsaChainCertificate,
11829			flags: []string{
11830				"-cert-file", path.Join(*resourceDir, rsaChainCertificateFile),
11831				"-key-file", path.Join(*resourceDir, rsaChainKeyFile),
11832				"-expect-peer-cert-file", path.Join(*resourceDir, rsaChainCertificateFile),
11833			},
11834		})
11835
11836		testCases = append(testCases, testCase{
11837			testType: serverTest,
11838			name:     "SendReceiveIntermediate-Server-" + ver.name,
11839			config: Config{
11840				MinVersion:   ver.version,
11841				MaxVersion:   ver.version,
11842				Certificates: []Certificate{rsaChainCertificate},
11843			},
11844			tls13Variant:          ver.tls13Variant,
11845			expectPeerCertificate: &rsaChainCertificate,
11846			flags: []string{
11847				"-cert-file", path.Join(*resourceDir, rsaChainCertificateFile),
11848				"-key-file", path.Join(*resourceDir, rsaChainKeyFile),
11849				"-require-any-client-certificate",
11850				"-expect-peer-cert-file", path.Join(*resourceDir, rsaChainCertificateFile),
11851			},
11852		})
11853	}
11854}
11855
11856func addRetainOnlySHA256ClientCertTests() {
11857	for _, ver := range tlsVersions {
11858		// Test that enabling
11859		// SSL_CTX_set_retain_only_sha256_of_client_certs without
11860		// actually requesting a client certificate is a no-op.
11861		testCases = append(testCases, testCase{
11862			testType: serverTest,
11863			name:     "RetainOnlySHA256-NoCert-" + ver.name,
11864			config: Config{
11865				MinVersion: ver.version,
11866				MaxVersion: ver.version,
11867			},
11868			tls13Variant: ver.tls13Variant,
11869			flags: []string{
11870				"-retain-only-sha256-client-cert-initial",
11871				"-retain-only-sha256-client-cert-resume",
11872			},
11873			resumeSession: true,
11874		})
11875
11876		// Test that when retaining only a SHA-256 certificate is
11877		// enabled, the hash appears as expected.
11878		testCases = append(testCases, testCase{
11879			testType: serverTest,
11880			name:     "RetainOnlySHA256-Cert-" + ver.name,
11881			config: Config{
11882				MinVersion:   ver.version,
11883				MaxVersion:   ver.version,
11884				Certificates: []Certificate{rsaCertificate},
11885			},
11886			tls13Variant: ver.tls13Variant,
11887			flags: []string{
11888				"-verify-peer",
11889				"-retain-only-sha256-client-cert-initial",
11890				"-retain-only-sha256-client-cert-resume",
11891				"-expect-sha256-client-cert-initial",
11892				"-expect-sha256-client-cert-resume",
11893			},
11894			resumeSession: true,
11895		})
11896
11897		// Test that when the config changes from on to off, a
11898		// resumption is rejected because the server now wants the full
11899		// certificate chain.
11900		testCases = append(testCases, testCase{
11901			testType: serverTest,
11902			name:     "RetainOnlySHA256-OnOff-" + ver.name,
11903			config: Config{
11904				MinVersion:   ver.version,
11905				MaxVersion:   ver.version,
11906				Certificates: []Certificate{rsaCertificate},
11907			},
11908			tls13Variant: ver.tls13Variant,
11909			flags: []string{
11910				"-verify-peer",
11911				"-retain-only-sha256-client-cert-initial",
11912				"-expect-sha256-client-cert-initial",
11913			},
11914			resumeSession:        true,
11915			expectResumeRejected: true,
11916		})
11917
11918		// Test that when the config changes from off to on, a
11919		// resumption is rejected because the server now wants just the
11920		// hash.
11921		testCases = append(testCases, testCase{
11922			testType: serverTest,
11923			name:     "RetainOnlySHA256-OffOn-" + ver.name,
11924			config: Config{
11925				MinVersion:   ver.version,
11926				MaxVersion:   ver.version,
11927				Certificates: []Certificate{rsaCertificate},
11928			},
11929			tls13Variant: ver.tls13Variant,
11930			flags: []string{
11931				"-verify-peer",
11932				"-retain-only-sha256-client-cert-resume",
11933				"-expect-sha256-client-cert-resume",
11934			},
11935			resumeSession:        true,
11936			expectResumeRejected: true,
11937		})
11938	}
11939}
11940
11941func addECDSAKeyUsageTests() {
11942	p256 := elliptic.P256()
11943	priv, err := ecdsa.GenerateKey(p256, rand.Reader)
11944	if err != nil {
11945		panic(err)
11946	}
11947
11948	serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128)
11949	serialNumber, err := rand.Int(rand.Reader, serialNumberLimit)
11950	if err != nil {
11951		panic(err)
11952	}
11953
11954	template := x509.Certificate{
11955		SerialNumber: serialNumber,
11956		Subject: pkix.Name{
11957			Organization: []string{"Acme Co"},
11958		},
11959		NotBefore: time.Now(),
11960		NotAfter:  time.Now(),
11961
11962		// An ECC certificate with only the keyAgreement key usgae may
11963		// be used with ECDH, but not ECDSA.
11964		KeyUsage:              x509.KeyUsageKeyAgreement,
11965		ExtKeyUsage:           []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
11966		BasicConstraintsValid: true,
11967	}
11968
11969	derBytes, err := x509.CreateCertificate(rand.Reader, &template, &template, &priv.PublicKey, priv)
11970	if err != nil {
11971		panic(err)
11972	}
11973
11974	cert := Certificate{
11975		Certificate: [][]byte{derBytes},
11976		PrivateKey:  priv,
11977	}
11978
11979	for _, ver := range tlsVersions {
11980		if ver.version < VersionTLS12 {
11981			continue
11982		}
11983
11984		testCases = append(testCases, testCase{
11985			testType: clientTest,
11986			name:     "ECDSAKeyUsage-" + ver.name,
11987			config: Config{
11988				MinVersion:   ver.version,
11989				MaxVersion:   ver.version,
11990				Certificates: []Certificate{cert},
11991			},
11992			tls13Variant:  ver.tls13Variant,
11993			shouldFail:    true,
11994			expectedError: ":ECC_CERT_NOT_FOR_SIGNING:",
11995		})
11996	}
11997}
11998
11999func addExtraHandshakeTests() {
12000	// An extra SSL_do_handshake is normally a no-op. These tests use -async
12001	// to ensure there is no transport I/O.
12002	testCases = append(testCases, testCase{
12003		testType: clientTest,
12004		name:     "ExtraHandshake-Client-TLS12",
12005		config: Config{
12006			MinVersion: VersionTLS12,
12007			MaxVersion: VersionTLS12,
12008		},
12009		flags: []string{
12010			"-async",
12011			"-no-op-extra-handshake",
12012		},
12013	})
12014	testCases = append(testCases, testCase{
12015		testType: serverTest,
12016		name:     "ExtraHandshake-Server-TLS12",
12017		config: Config{
12018			MinVersion: VersionTLS12,
12019			MaxVersion: VersionTLS12,
12020		},
12021		flags: []string{
12022			"-async",
12023			"-no-op-extra-handshake",
12024		},
12025	})
12026	testCases = append(testCases, testCase{
12027		testType: clientTest,
12028		name:     "ExtraHandshake-Client-TLS13",
12029		config: Config{
12030			MinVersion: VersionTLS13,
12031			MaxVersion: VersionTLS13,
12032		},
12033		flags: []string{
12034			"-async",
12035			"-no-op-extra-handshake",
12036		},
12037	})
12038	testCases = append(testCases, testCase{
12039		testType: serverTest,
12040		name:     "ExtraHandshake-Server-TLS13",
12041		config: Config{
12042			MinVersion: VersionTLS13,
12043			MaxVersion: VersionTLS13,
12044		},
12045		flags: []string{
12046			"-async",
12047			"-no-op-extra-handshake",
12048		},
12049	})
12050
12051	// An extra SSL_do_handshake is a no-op in server 0-RTT.
12052	testCases = append(testCases, testCase{
12053		testType: serverTest,
12054		name:     "ExtraHandshake-Server-EarlyData-TLS13",
12055		config: Config{
12056			MaxVersion: VersionTLS13,
12057			MinVersion: VersionTLS13,
12058			Bugs: ProtocolBugs{
12059				SendEarlyData:           [][]byte{{1, 2, 3, 4}},
12060				ExpectEarlyDataAccepted: true,
12061				ExpectHalfRTTData:       [][]byte{{254, 253, 252, 251}},
12062			},
12063		},
12064		messageCount:  2,
12065		resumeSession: true,
12066		flags: []string{
12067			"-async",
12068			"-enable-early-data",
12069			"-expect-accept-early-data",
12070			"-no-op-extra-handshake",
12071		},
12072	})
12073
12074	// An extra SSL_do_handshake drives the handshake to completion in False
12075	// Start. We test this by handshaking twice and asserting the False
12076	// Start does not appear to happen. See AlertBeforeFalseStartTest for
12077	// how the test works.
12078	testCases = append(testCases, testCase{
12079		testType: clientTest,
12080		name:     "ExtraHandshake-FalseStart",
12081		config: Config{
12082			MaxVersion:   VersionTLS12,
12083			CipherSuites: []uint16{TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256},
12084			NextProtos:   []string{"foo"},
12085			Bugs: ProtocolBugs{
12086				ExpectFalseStart:          true,
12087				AlertBeforeFalseStartTest: alertAccessDenied,
12088			},
12089		},
12090		flags: []string{
12091			"-handshake-twice",
12092			"-false-start",
12093			"-advertise-alpn", "\x03foo",
12094			"-expect-alpn", "foo",
12095		},
12096		shimWritesFirst:    true,
12097		shouldFail:         true,
12098		expectedError:      ":TLSV1_ALERT_ACCESS_DENIED:",
12099		expectedLocalError: "tls: peer did not false start: EOF",
12100	})
12101}
12102
12103// Test that omitted and empty extensions blocks are tolerated.
12104func addOmitExtensionsTests() {
12105	for _, ver := range tlsVersions {
12106		if ver.version > VersionTLS12 {
12107			continue
12108		}
12109
12110		testCases = append(testCases, testCase{
12111			testType: serverTest,
12112			name:     "OmitExtensions-ClientHello-" + ver.name,
12113			config: Config{
12114				MinVersion:             ver.version,
12115				MaxVersion:             ver.version,
12116				SessionTicketsDisabled: true,
12117				Bugs: ProtocolBugs{
12118					OmitExtensions: true,
12119				},
12120			},
12121		})
12122
12123		testCases = append(testCases, testCase{
12124			testType: serverTest,
12125			name:     "EmptyExtensions-ClientHello-" + ver.name,
12126			config: Config{
12127				MinVersion:             ver.version,
12128				MaxVersion:             ver.version,
12129				SessionTicketsDisabled: true,
12130				Bugs: ProtocolBugs{
12131					EmptyExtensions: true,
12132				},
12133			},
12134		})
12135
12136		testCases = append(testCases, testCase{
12137			testType: clientTest,
12138			name:     "OmitExtensions-ServerHello-" + ver.name,
12139			config: Config{
12140				MinVersion:             ver.version,
12141				MaxVersion:             ver.version,
12142				SessionTicketsDisabled: true,
12143				Bugs: ProtocolBugs{
12144					OmitExtensions: true,
12145					// Disable all ServerHello extensions so
12146					// OmitExtensions works.
12147					NoExtendedMasterSecret: true,
12148					NoRenegotiationInfo:    true,
12149				},
12150			},
12151		})
12152
12153		testCases = append(testCases, testCase{
12154			testType: clientTest,
12155			name:     "EmptyExtensions-ServerHello-" + ver.name,
12156			config: Config{
12157				MinVersion:             ver.version,
12158				MaxVersion:             ver.version,
12159				SessionTicketsDisabled: true,
12160				Bugs: ProtocolBugs{
12161					EmptyExtensions: true,
12162					// Disable all ServerHello extensions so
12163					// EmptyExtensions works.
12164					NoExtendedMasterSecret: true,
12165					NoRenegotiationInfo:    true,
12166				},
12167			},
12168		})
12169	}
12170}
12171
12172func worker(statusChan chan statusMsg, c chan *testCase, shimPath string, wg *sync.WaitGroup) {
12173	defer wg.Done()
12174
12175	for test := range c {
12176		var err error
12177
12178		if *mallocTest >= 0 {
12179			for mallocNumToFail := int64(*mallocTest); ; mallocNumToFail++ {
12180				statusChan <- statusMsg{test: test, started: true}
12181				if err = runTest(test, shimPath, mallocNumToFail); err != errMoreMallocs {
12182					if err != nil {
12183						fmt.Printf("\n\nmalloc test failed at %d: %s\n", mallocNumToFail, err)
12184					}
12185					break
12186				}
12187			}
12188		} else if *repeatUntilFailure {
12189			for err == nil {
12190				statusChan <- statusMsg{test: test, started: true}
12191				err = runTest(test, shimPath, -1)
12192			}
12193		} else {
12194			statusChan <- statusMsg{test: test, started: true}
12195			err = runTest(test, shimPath, -1)
12196		}
12197		statusChan <- statusMsg{test: test, err: err}
12198	}
12199}
12200
12201type statusMsg struct {
12202	test    *testCase
12203	started bool
12204	err     error
12205}
12206
12207func statusPrinter(doneChan chan *testOutput, statusChan chan statusMsg, total int) {
12208	var started, done, failed, unimplemented, lineLen int
12209
12210	testOutput := newTestOutput()
12211	for msg := range statusChan {
12212		if !*pipe {
12213			// Erase the previous status line.
12214			var erase string
12215			for i := 0; i < lineLen; i++ {
12216				erase += "\b \b"
12217			}
12218			fmt.Print(erase)
12219		}
12220
12221		if msg.started {
12222			started++
12223		} else {
12224			done++
12225
12226			if msg.err != nil {
12227				if msg.err == errUnimplemented {
12228					if *pipe {
12229						// Print each test instead of a status line.
12230						fmt.Printf("UNIMPLEMENTED (%s)\n", msg.test.name)
12231					}
12232					unimplemented++
12233					testOutput.addResult(msg.test.name, "UNIMPLEMENTED")
12234				} else {
12235					fmt.Printf("FAILED (%s)\n%s\n", msg.test.name, msg.err)
12236					failed++
12237					testOutput.addResult(msg.test.name, "FAIL")
12238				}
12239			} else {
12240				if *pipe {
12241					// Print each test instead of a status line.
12242					fmt.Printf("PASSED (%s)\n", msg.test.name)
12243				}
12244				testOutput.addResult(msg.test.name, "PASS")
12245			}
12246		}
12247
12248		if !*pipe {
12249			// Print a new status line.
12250			line := fmt.Sprintf("%d/%d/%d/%d/%d", failed, unimplemented, done, started, total)
12251			lineLen = len(line)
12252			os.Stdout.WriteString(line)
12253		}
12254	}
12255
12256	doneChan <- testOutput
12257}
12258
12259func main() {
12260	flag.Parse()
12261	*resourceDir = path.Clean(*resourceDir)
12262	initCertificates()
12263
12264	addBasicTests()
12265	addCipherSuiteTests()
12266	addBadECDSASignatureTests()
12267	addCBCPaddingTests()
12268	addCBCSplittingTests()
12269	addClientAuthTests()
12270	addDDoSCallbackTests()
12271	addVersionNegotiationTests()
12272	addMinimumVersionTests()
12273	addExtensionTests()
12274	addResumptionVersionTests()
12275	addExtendedMasterSecretTests()
12276	addRenegotiationTests()
12277	addDTLSReplayTests()
12278	addSignatureAlgorithmTests()
12279	addDTLSRetransmitTests()
12280	addExportKeyingMaterialTests()
12281	addTLSUniqueTests()
12282	addCustomExtensionTests()
12283	addRSAClientKeyExchangeTests()
12284	addCurveTests()
12285	addSessionTicketTests()
12286	addTLS13RecordTests()
12287	addAllStateMachineCoverageTests()
12288	addChangeCipherSpecTests()
12289	addWrongMessageTypeTests()
12290	addTrailingMessageDataTests()
12291	addTLS13HandshakeTests()
12292	addTLS13CipherPreferenceTests()
12293	addPeekTests()
12294	addRecordVersionTests()
12295	addCertificateTests()
12296	addRetainOnlySHA256ClientCertTests()
12297	addECDSAKeyUsageTests()
12298	addExtraHandshakeTests()
12299	addOmitExtensionsTests()
12300
12301	var wg sync.WaitGroup
12302
12303	statusChan := make(chan statusMsg, *numWorkers)
12304	testChan := make(chan *testCase, *numWorkers)
12305	doneChan := make(chan *testOutput)
12306
12307	if len(*shimConfigFile) != 0 {
12308		encoded, err := ioutil.ReadFile(*shimConfigFile)
12309		if err != nil {
12310			fmt.Fprintf(os.Stderr, "Couldn't read config file %q: %s\n", *shimConfigFile, err)
12311			os.Exit(1)
12312		}
12313
12314		if err := json.Unmarshal(encoded, &shimConfig); err != nil {
12315			fmt.Fprintf(os.Stderr, "Couldn't decode config file %q: %s\n", *shimConfigFile, err)
12316			os.Exit(1)
12317		}
12318	}
12319
12320	go statusPrinter(doneChan, statusChan, len(testCases))
12321
12322	for i := 0; i < *numWorkers; i++ {
12323		wg.Add(1)
12324		go worker(statusChan, testChan, *shimPath, &wg)
12325	}
12326
12327	var foundTest bool
12328	for i := range testCases {
12329		matched := true
12330		if len(*testToRun) != 0 {
12331			var err error
12332			matched, err = filepath.Match(*testToRun, testCases[i].name)
12333			if err != nil {
12334				fmt.Fprintf(os.Stderr, "Error matching pattern: %s\n", err)
12335				os.Exit(1)
12336			}
12337		}
12338
12339		if !*includeDisabled {
12340			for pattern := range shimConfig.DisabledTests {
12341				isDisabled, err := filepath.Match(pattern, testCases[i].name)
12342				if err != nil {
12343					fmt.Fprintf(os.Stderr, "Error matching pattern %q from config file: %s\n", pattern, err)
12344					os.Exit(1)
12345				}
12346
12347				if isDisabled {
12348					matched = false
12349					break
12350				}
12351			}
12352		}
12353
12354		if matched {
12355			foundTest = true
12356			testChan <- &testCases[i]
12357
12358			// Only run one test if repeating until failure.
12359			if *repeatUntilFailure {
12360				break
12361			}
12362		}
12363	}
12364
12365	if !foundTest {
12366		fmt.Fprintf(os.Stderr, "No tests run\n")
12367		os.Exit(1)
12368	}
12369
12370	close(testChan)
12371	wg.Wait()
12372	close(statusChan)
12373	testOutput := <-doneChan
12374
12375	fmt.Printf("\n")
12376
12377	if *jsonOutput != "" {
12378		if err := testOutput.writeTo(*jsonOutput); err != nil {
12379			fmt.Fprintf(os.Stderr, "Error: %s\n", err)
12380		}
12381	}
12382
12383	if !*allowUnimplemented && testOutput.NumFailuresByType["UNIMPLEMENTED"] > 0 {
12384		os.Exit(1)
12385	}
12386
12387	if !testOutput.noneFailed {
12388		os.Exit(1)
12389	}
12390}
12391