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