Source file src/crypto/tls/handshake_client_test.go

     1  // Copyright 2010 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package tls
     6  
     7  import (
     8  	"bytes"
     9  	"context"
    10  	"crypto/ecdsa"
    11  	"crypto/elliptic"
    12  	"crypto/rand"
    13  	"crypto/rsa"
    14  	"crypto/tls/internal/fips140tls"
    15  	"crypto/x509"
    16  	"crypto/x509/pkix"
    17  	"encoding/base64"
    18  	"encoding/hex"
    19  	"encoding/pem"
    20  	"errors"
    21  	"fmt"
    22  	"internal/byteorder"
    23  	"io"
    24  	"math/big"
    25  	"net"
    26  	"os"
    27  	"os/exec"
    28  	"path/filepath"
    29  	"reflect"
    30  	"runtime"
    31  	"strconv"
    32  	"strings"
    33  	"testing"
    34  	"time"
    35  )
    36  
    37  // Note: see comment in handshake_test.go for details of how the reference
    38  // tests work.
    39  
    40  // opensslInputEvent enumerates possible inputs that can be sent to an `openssl
    41  // s_client` process.
    42  type opensslInputEvent int
    43  
    44  const (
    45  	// opensslRenegotiate causes OpenSSL to request a renegotiation of the
    46  	// connection.
    47  	opensslRenegotiate opensslInputEvent = iota
    48  
    49  	// opensslSendBanner causes OpenSSL to send the contents of
    50  	// opensslSentinel on the connection.
    51  	opensslSendSentinel
    52  
    53  	// opensslKeyUpdate causes OpenSSL to send a key update message to the
    54  	// client and request one back.
    55  	opensslKeyUpdate
    56  )
    57  
    58  const opensslSentinel = "SENTINEL\n"
    59  
    60  type opensslInput chan opensslInputEvent
    61  
    62  func (i opensslInput) Read(buf []byte) (n int, err error) {
    63  	for event := range i {
    64  		switch event {
    65  		case opensslRenegotiate:
    66  			return copy(buf, []byte("R\n")), nil
    67  		case opensslKeyUpdate:
    68  			return copy(buf, []byte("K\n")), nil
    69  		case opensslSendSentinel:
    70  			return copy(buf, []byte(opensslSentinel)), nil
    71  		default:
    72  			panic("unknown event")
    73  		}
    74  	}
    75  
    76  	return 0, io.EOF
    77  }
    78  
    79  // opensslOutputSink is an io.Writer that receives the stdout and stderr from an
    80  // `openssl` process and sends a value to handshakeComplete or readKeyUpdate
    81  // when certain messages are seen.
    82  type opensslOutputSink struct {
    83  	handshakeComplete chan struct{}
    84  	readKeyUpdate     chan struct{}
    85  	all               []byte
    86  	line              []byte
    87  }
    88  
    89  func newOpensslOutputSink() *opensslOutputSink {
    90  	return &opensslOutputSink{make(chan struct{}), make(chan struct{}), nil, nil}
    91  }
    92  
    93  // opensslEndOfHandshake is a message that the “openssl s_server” tool will
    94  // print when a handshake completes if run with “-state”.
    95  const opensslEndOfHandshake = "SSL_accept:SSLv3/TLS write finished"
    96  
    97  // opensslReadKeyUpdate is a message that the “openssl s_server” tool will
    98  // print when a KeyUpdate message is received if run with “-state”.
    99  const opensslReadKeyUpdate = "SSL_accept:TLSv1.3 read client key update"
   100  
   101  func (o *opensslOutputSink) Write(data []byte) (n int, err error) {
   102  	o.line = append(o.line, data...)
   103  	o.all = append(o.all, data...)
   104  
   105  	for {
   106  		line, next, ok := bytes.Cut(o.line, []byte("\n"))
   107  		if !ok {
   108  			break
   109  		}
   110  
   111  		if bytes.Equal([]byte(opensslEndOfHandshake), line) {
   112  			o.handshakeComplete <- struct{}{}
   113  		}
   114  		if bytes.Equal([]byte(opensslReadKeyUpdate), line) {
   115  			o.readKeyUpdate <- struct{}{}
   116  		}
   117  		o.line = next
   118  	}
   119  
   120  	return len(data), nil
   121  }
   122  
   123  func (o *opensslOutputSink) String() string {
   124  	return string(o.all)
   125  }
   126  
   127  // clientTest represents a test of the TLS client handshake against a reference
   128  // implementation.
   129  type clientTest struct {
   130  	// name is a freeform string identifying the test and the file in which
   131  	// the expected results will be stored.
   132  	name string
   133  	// args, if not empty, contains a series of arguments for the
   134  	// command to run for the reference server.
   135  	args []string
   136  	// config, if not nil, contains a custom Config to use for this test.
   137  	config *Config
   138  	// serverCert, if not zero, contains a certificate for the reference server.
   139  	serverCert *Certificate
   140  	// extensions, if not nil, contains a list of extension data to be returned
   141  	// from the ServerHello. The data should be in standard TLS format with
   142  	// a 2-byte uint16 type, 2-byte data length, followed by the extension data.
   143  	extensions [][]byte
   144  	// validate, if not nil, is a function that will be called with the
   145  	// ConnectionState of the resulting connection. It returns a non-nil
   146  	// error if the ConnectionState is unacceptable.
   147  	validate func(ConnectionState) error
   148  	// numRenegotiations is the number of times that the connection will be
   149  	// renegotiated.
   150  	numRenegotiations int
   151  	// renegotiationExpectedToFail, if not zero, is the number of the
   152  	// renegotiation attempt that is expected to fail.
   153  	renegotiationExpectedToFail int
   154  	// checkRenegotiationError, if not nil, is called with any error
   155  	// arising from renegotiation. It can map expected errors to nil to
   156  	// ignore them.
   157  	checkRenegotiationError func(renegotiationNum int, err error) error
   158  	// sendKeyUpdate will cause the server to send a KeyUpdate message.
   159  	sendKeyUpdate bool
   160  }
   161  
   162  var serverCommand []string
   163  
   164  // connFromCommand starts the reference server process, connects to it and
   165  // returns a recordingConn for the connection. The stdin return value is an
   166  // opensslInput for the stdin of the child process. It must be closed before
   167  // Waiting for child.
   168  func (test *clientTest) connFromCommand() (conn *recordingConn, child *exec.Cmd, stdin opensslInput, stdout *opensslOutputSink, err error) {
   169  	cert := &testECDSAP256Cert
   170  	if test.serverCert != nil {
   171  		cert = test.serverCert
   172  	}
   173  	certPath := tempFile(string(cert.Certificate[0]))
   174  	defer os.Remove(certPath)
   175  
   176  	derBytes, err := x509.MarshalPKCS8PrivateKey(cert.PrivateKey)
   177  	if err != nil {
   178  		panic(err)
   179  	}
   180  
   181  	var pemOut bytes.Buffer
   182  	pem.Encode(&pemOut, &pem.Block{Type: "PRIVATE KEY", Bytes: derBytes})
   183  
   184  	keyPath := tempFile(pemOut.String())
   185  	defer os.Remove(keyPath)
   186  
   187  	var command []string
   188  	command = append(command, serverCommand...)
   189  	command = append(command, test.args...)
   190  	command = append(command, "-cert", certPath, "-certform", "DER", "-key", keyPath)
   191  	// serverPort contains the port that OpenSSL will listen on. OpenSSL
   192  	// can't take "0" as an argument here so we have to pick a number and
   193  	// hope that it's not in use on the machine. Since this only occurs
   194  	// when -update is given and thus when there's a human watching the
   195  	// test, this isn't too bad.
   196  	const serverPort = 24323
   197  	command = append(command, "-accept", strconv.Itoa(serverPort))
   198  
   199  	if len(test.extensions) > 0 {
   200  		var serverInfo bytes.Buffer
   201  		for _, ext := range test.extensions {
   202  			pem.Encode(&serverInfo, &pem.Block{
   203  				Type:  fmt.Sprintf("SERVERINFO FOR EXTENSION %d", byteorder.BEUint16(ext)),
   204  				Bytes: ext,
   205  			})
   206  		}
   207  		serverInfoPath := tempFile(serverInfo.String())
   208  		defer os.Remove(serverInfoPath)
   209  		command = append(command, "-serverinfo", serverInfoPath)
   210  	}
   211  
   212  	if test.numRenegotiations > 0 || test.sendKeyUpdate {
   213  		found := false
   214  		for _, flag := range command[1:] {
   215  			if flag == "-state" {
   216  				found = true
   217  				break
   218  			}
   219  		}
   220  
   221  		if !found {
   222  			panic("-state flag missing to OpenSSL, you need this if testing renegotiation or KeyUpdate")
   223  		}
   224  	}
   225  
   226  	cmd := exec.Command(command[0], command[1:]...)
   227  	stdin = opensslInput(make(chan opensslInputEvent))
   228  	cmd.Stdin = stdin
   229  	out := newOpensslOutputSink()
   230  	cmd.Stdout = out
   231  	cmd.Stderr = out
   232  	if err := cmd.Start(); err != nil {
   233  		return nil, nil, nil, nil, err
   234  	}
   235  
   236  	// OpenSSL does print an "ACCEPT" banner, but it does so *before*
   237  	// opening the listening socket, so we can't use that to wait until it
   238  	// has started listening. Thus we are forced to poll until we get a
   239  	// connection.
   240  	var tcpConn net.Conn
   241  	for i := uint(0); i < 5; i++ {
   242  		tcpConn, err = net.DialTCP("tcp", nil, &net.TCPAddr{
   243  			IP:   net.IPv4(127, 0, 0, 1),
   244  			Port: serverPort,
   245  		})
   246  		if err == nil {
   247  			break
   248  		}
   249  		time.Sleep((1 << i) * 5 * time.Millisecond)
   250  	}
   251  	if err != nil {
   252  		close(stdin)
   253  		cmd.Process.Kill()
   254  		err = fmt.Errorf("error connecting to the OpenSSL server: %v (%v)\n\n%s", err, cmd.Wait(), out)
   255  		return nil, nil, nil, nil, err
   256  	}
   257  
   258  	record := &recordingConn{
   259  		Conn: tcpConn,
   260  	}
   261  
   262  	return record, cmd, stdin, out, nil
   263  }
   264  
   265  func (test *clientTest) dataPath() string {
   266  	return filepath.Join("testdata", "Client-"+test.name)
   267  }
   268  
   269  func (test *clientTest) loadData() (flows [][]byte, err error) {
   270  	in, err := os.Open(test.dataPath())
   271  	if err != nil {
   272  		return nil, err
   273  	}
   274  	defer in.Close()
   275  	return parseTestData(in)
   276  }
   277  
   278  func (test *clientTest) run(t *testing.T, write bool) {
   279  	var clientConn net.Conn
   280  	var recordingConn *recordingConn
   281  	var childProcess *exec.Cmd
   282  	var stdin opensslInput
   283  	var stdout *opensslOutputSink
   284  
   285  	if write {
   286  		var err error
   287  		recordingConn, childProcess, stdin, stdout, err = test.connFromCommand()
   288  		if err != nil {
   289  			t.Fatalf("Failed to start subcommand: %s", err)
   290  		}
   291  		clientConn = recordingConn
   292  		defer func() {
   293  			if t.Failed() {
   294  				t.Logf("OpenSSL output:\n\n%s", stdout.all)
   295  			}
   296  		}()
   297  	} else {
   298  		flows, err := test.loadData()
   299  		if err != nil {
   300  			t.Fatalf("failed to load data from %s: %v", test.dataPath(), err)
   301  		}
   302  		clientConn = &replayingConn{t: t, flows: flows, reading: false}
   303  	}
   304  
   305  	config := test.config
   306  	if config == nil {
   307  		config = testConfigClient
   308  	}
   309  	config = config.Clone()
   310  	client := Client(clientConn, config)
   311  	defer client.Close()
   312  
   313  	if _, err := client.Write([]byte("hello\n")); err != nil {
   314  		t.Errorf("Client.Write failed: %s", err)
   315  		return
   316  	}
   317  
   318  	for i := 1; i <= test.numRenegotiations; i++ {
   319  		// The initial handshake will generate a
   320  		// handshakeComplete signal which needs to be quashed.
   321  		if i == 1 && write {
   322  			<-stdout.handshakeComplete
   323  		}
   324  
   325  		// OpenSSL will try to interleave application data and
   326  		// a renegotiation if we send both concurrently.
   327  		// Therefore: ask OpensSSL to start a renegotiation, run
   328  		// a goroutine to call client.Read and thus process the
   329  		// renegotiation request, watch for OpenSSL's stdout to
   330  		// indicate that the handshake is complete and,
   331  		// finally, have OpenSSL write something to cause
   332  		// client.Read to complete.
   333  		if write {
   334  			stdin <- opensslRenegotiate
   335  		}
   336  
   337  		signalChan := make(chan struct{})
   338  
   339  		go func() {
   340  			defer close(signalChan)
   341  
   342  			buf := make([]byte, 256)
   343  			n, err := client.Read(buf)
   344  
   345  			if test.checkRenegotiationError != nil {
   346  				newErr := test.checkRenegotiationError(i, err)
   347  				if err != nil && newErr == nil {
   348  					return
   349  				}
   350  				err = newErr
   351  			}
   352  
   353  			if err != nil {
   354  				t.Errorf("Client.Read failed after renegotiation #%d: %s", i, err)
   355  				return
   356  			}
   357  
   358  			buf = buf[:n]
   359  			if !bytes.Equal([]byte(opensslSentinel), buf) {
   360  				t.Errorf("Client.Read returned %q, but wanted %q", string(buf), opensslSentinel)
   361  			}
   362  
   363  			if expected := i + 1; client.handshakes != expected {
   364  				t.Errorf("client should have recorded %d handshakes, but believes that %d have occurred", expected, client.handshakes)
   365  			}
   366  		}()
   367  
   368  		if write && test.renegotiationExpectedToFail != i {
   369  			<-stdout.handshakeComplete
   370  			stdin <- opensslSendSentinel
   371  		}
   372  		<-signalChan
   373  	}
   374  
   375  	if test.sendKeyUpdate {
   376  		if write {
   377  			<-stdout.handshakeComplete
   378  			stdin <- opensslKeyUpdate
   379  		}
   380  
   381  		doneRead := make(chan struct{})
   382  
   383  		go func() {
   384  			defer close(doneRead)
   385  
   386  			buf := make([]byte, 256)
   387  			n, err := client.Read(buf)
   388  
   389  			if err != nil {
   390  				t.Errorf("Client.Read failed after KeyUpdate: %s", err)
   391  				return
   392  			}
   393  
   394  			buf = buf[:n]
   395  			if !bytes.Equal([]byte(opensslSentinel), buf) {
   396  				t.Errorf("Client.Read returned %q, but wanted %q", string(buf), opensslSentinel)
   397  			}
   398  		}()
   399  
   400  		if write {
   401  			// There's no real reason to wait for the client KeyUpdate to
   402  			// send data with the new server keys, except that s_server
   403  			// drops writes if they are sent at the wrong time.
   404  			<-stdout.readKeyUpdate
   405  			stdin <- opensslSendSentinel
   406  		}
   407  		<-doneRead
   408  
   409  		if _, err := client.Write([]byte("hello again\n")); err != nil {
   410  			t.Errorf("Client.Write failed: %s", err)
   411  			return
   412  		}
   413  	}
   414  
   415  	if test.validate != nil {
   416  		if err := test.validate(client.ConnectionState()); err != nil {
   417  			t.Errorf("validate callback returned error: %s", err)
   418  		}
   419  	}
   420  
   421  	// If the server sent us an alert after our last flight, give it a
   422  	// chance to arrive.
   423  	if write && test.renegotiationExpectedToFail == 0 {
   424  		if err := peekError(client); err != nil {
   425  			t.Errorf("final Read returned an error: %s", err)
   426  		}
   427  	}
   428  
   429  	if write {
   430  		client.Close()
   431  		recordingConn.Close()
   432  		close(stdin)
   433  		if err := childProcess.Wait(); err != nil {
   434  			t.Errorf("OpenSSL exited with error: %s", err)
   435  		}
   436  		if t.Failed() {
   437  			t.Logf("OpenSSL output:\n\n%s", stdout.all)
   438  			return
   439  		}
   440  		if len(recordingConn.flows) < 3 {
   441  			t.Fatalf("Client connection didn't work")
   442  		}
   443  		path := test.dataPath()
   444  		out, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644)
   445  		if err != nil {
   446  			t.Fatalf("Failed to create output file: %s", err)
   447  		}
   448  		defer out.Close()
   449  		recordingConn.WriteTo(out)
   450  		t.Logf("Wrote %s\n", path)
   451  	}
   452  }
   453  
   454  // peekError does a read with a short timeout to check if the next read would
   455  // cause an error, for example if there is an alert waiting on the wire.
   456  func peekError(conn net.Conn) error {
   457  	conn.SetReadDeadline(time.Now().Add(100 * time.Millisecond))
   458  	if n, err := conn.Read(make([]byte, 1)); n != 0 {
   459  		return errors.New("unexpectedly read data")
   460  	} else if err != nil {
   461  		if netErr, ok := err.(net.Error); !ok || !netErr.Timeout() {
   462  			return err
   463  		}
   464  	}
   465  	return nil
   466  }
   467  
   468  func runClientTestForVersion(t *testing.T, template *clientTest, version, option string) {
   469  	test := *template
   470  	if template.config != nil {
   471  		test.config = template.config.Clone()
   472  	}
   473  	test.name = version + "-" + test.name
   474  	test.args = append([]string{option}, test.args...)
   475  
   476  	runTestAndUpdateIfNeeded(t, version, test.run)
   477  }
   478  
   479  func runClientTestTLS10(t *testing.T, template *clientTest) {
   480  	if template.config == nil {
   481  		template.config = testConfigClient.Clone()
   482  	}
   483  	if template.config.MinVersion == 0 {
   484  		template.config.MinVersion = VersionTLS10
   485  	}
   486  	runClientTestForVersion(t, template, "TLSv10", "-tls1")
   487  }
   488  
   489  func runClientTestTLS11(t *testing.T, template *clientTest) {
   490  	if template.config == nil {
   491  		template.config = testConfigClient.Clone()
   492  	}
   493  	if template.config.MinVersion == 0 {
   494  		template.config.MinVersion = VersionTLS11
   495  	}
   496  	runClientTestForVersion(t, template, "TLSv11", "-tls1_1")
   497  }
   498  
   499  func runClientTestTLS12(t *testing.T, template *clientTest) {
   500  	runClientTestForVersion(t, template, "TLSv12", "-tls1_2")
   501  }
   502  
   503  func runClientTestTLS13(t *testing.T, template *clientTest) {
   504  	runClientTestForVersion(t, template, "TLSv13", "-tls1_3")
   505  }
   506  
   507  func TestHandshakeClientRSARC4(t *testing.T) {
   508  	config := testConfigClient.Clone()
   509  	config.CipherSuites = []uint16{TLS_RSA_WITH_RC4_128_SHA}
   510  	test := &clientTest{
   511  		name:       "RSA-RC4",
   512  		args:       []string{"-cipher", "RC4-SHA"},
   513  		serverCert: &testRSA2048Cert,
   514  		config:     config,
   515  		validate:   checkCipherSuite(TLS_RSA_WITH_RC4_128_SHA),
   516  	}
   517  	runClientTestTLS10(t, test)
   518  	runClientTestTLS11(t, test)
   519  	runClientTestTLS12(t, test)
   520  }
   521  
   522  func TestHandshakeClientRSAAES128GCM(t *testing.T) {
   523  	config := testConfigClient.Clone()
   524  	config.CipherSuites = []uint16{TLS_RSA_WITH_AES_128_GCM_SHA256}
   525  	test := &clientTest{
   526  		name:       "AES128-GCM-SHA256",
   527  		args:       []string{"-cipher", "AES128-GCM-SHA256"},
   528  		serverCert: &testRSA2048Cert,
   529  		config:     config,
   530  		validate:   checkCipherSuite(TLS_RSA_WITH_AES_128_GCM_SHA256),
   531  	}
   532  	runClientTestTLS12(t, test)
   533  }
   534  
   535  func TestHandshakeClientRSAAES256GCM(t *testing.T) {
   536  	config := testConfigClient.Clone()
   537  	config.CipherSuites = []uint16{TLS_RSA_WITH_AES_256_GCM_SHA384}
   538  	test := &clientTest{
   539  		name:       "AES256-GCM-SHA384",
   540  		args:       []string{"-cipher", "AES256-GCM-SHA384"},
   541  		serverCert: &testRSA2048Cert,
   542  		config:     config,
   543  		validate:   checkCipherSuite(TLS_RSA_WITH_AES_256_GCM_SHA384),
   544  	}
   545  	runClientTestTLS12(t, test)
   546  }
   547  
   548  func TestHandshakeClientECDHERSAAES(t *testing.T) {
   549  	test := &clientTest{
   550  		name:       "ECDHE-RSA-AES",
   551  		args:       []string{"-cipher", "ECDHE-RSA-AES128-SHA"},
   552  		serverCert: &testRSA2048Cert,
   553  		validate:   checkCipherSuite(TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA),
   554  	}
   555  	runClientTestTLS10(t, test)
   556  	runClientTestTLS11(t, test)
   557  	runClientTestTLS12(t, test)
   558  }
   559  
   560  func TestHandshakeClientECDHEECDSAAES(t *testing.T) {
   561  	test := &clientTest{
   562  		name:     "ECDHE-ECDSA-AES",
   563  		args:     []string{"-cipher", "ECDHE-ECDSA-AES128-SHA"},
   564  		validate: checkCipherSuite(TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA),
   565  	}
   566  	runClientTestTLS10(t, test)
   567  	runClientTestTLS11(t, test)
   568  	runClientTestTLS12(t, test)
   569  }
   570  
   571  func TestHandshakeClientECDHEECDSAAESGCM(t *testing.T) {
   572  	test := &clientTest{
   573  		name:     "ECDHE-ECDSA-AES-GCM",
   574  		args:     []string{"-cipher", "ECDHE-ECDSA-AES128-GCM-SHA256"},
   575  		validate: checkCipherSuite(TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256),
   576  	}
   577  	runClientTestTLS12(t, test)
   578  }
   579  
   580  func TestHandshakeClientAES256GCMSHA384(t *testing.T) {
   581  	test := &clientTest{
   582  		name:     "ECDHE-ECDSA-AES256-GCM-SHA384",
   583  		args:     []string{"-cipher", "ECDHE-ECDSA-AES256-GCM-SHA384"},
   584  		validate: checkCipherSuite(TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384),
   585  	}
   586  	runClientTestTLS12(t, test)
   587  }
   588  
   589  func TestHandshakeClientAES128CBCSHA256(t *testing.T) {
   590  	config := testConfigClient.Clone()
   591  	config.CipherSuites = []uint16{TLS_RSA_WITH_AES_128_CBC_SHA256}
   592  	test := &clientTest{
   593  		name:       "AES128-SHA256",
   594  		args:       []string{"-cipher", "AES128-SHA256"},
   595  		serverCert: &testRSA2048Cert,
   596  		config:     config,
   597  		validate:   checkCipherSuite(TLS_RSA_WITH_AES_128_CBC_SHA256),
   598  	}
   599  	runClientTestTLS12(t, test)
   600  }
   601  
   602  func TestHandshakeClientECDHERSAAES128CBCSHA256(t *testing.T) {
   603  	config := testConfigClient.Clone()
   604  	config.CipherSuites = []uint16{TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256}
   605  	test := &clientTest{
   606  		name:       "ECDHE-RSA-AES128-SHA256",
   607  		args:       []string{"-cipher", "ECDHE-RSA-AES128-SHA256"},
   608  		serverCert: &testRSA2048Cert,
   609  		config:     config,
   610  		validate:   checkCipherSuite(TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256),
   611  	}
   612  	runClientTestTLS12(t, test)
   613  }
   614  
   615  func TestHandshakeClientECDHEECDSAAES128CBCSHA256(t *testing.T) {
   616  	config := testConfigClient.Clone()
   617  	config.CipherSuites = []uint16{TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256}
   618  	test := &clientTest{
   619  		name:     "ECDHE-ECDSA-AES128-SHA256",
   620  		args:     []string{"-cipher", "ECDHE-ECDSA-AES128-SHA256"},
   621  		config:   config,
   622  		validate: checkCipherSuite(TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256),
   623  	}
   624  	runClientTestTLS12(t, test)
   625  }
   626  
   627  func TestHandshakeClientX25519(t *testing.T) {
   628  	test := &clientTest{
   629  		name:     "X25519-ECDHE",
   630  		args:     []string{"-curves", "X25519"},
   631  		validate: checkCurveID(X25519),
   632  	}
   633  	runClientTestTLS12(t, test)
   634  	runClientTestTLS13(t, test)
   635  }
   636  
   637  func TestHandshakeClientP256(t *testing.T) {
   638  	test := &clientTest{
   639  		name:     "P256-ECDHE",
   640  		args:     []string{"-curves", "P-256"},
   641  		validate: checkCurveID(CurveP256),
   642  	}
   643  	runClientTestTLS12(t, test)
   644  	runClientTestTLS13(t, test)
   645  }
   646  
   647  func TestHandshakeClientHelloRetryRequest(t *testing.T) {
   648  	config := testConfigClient.Clone()
   649  	config.CurvePreferences = []CurveID{X25519, CurveP256}
   650  
   651  	test := &clientTest{
   652  		name:   "HelloRetryRequest",
   653  		args:   []string{"-curves", "P-256"},
   654  		config: config,
   655  		validate: func(cs ConnectionState) error {
   656  			if !cs.HelloRetryRequest {
   657  				return errors.New("expected HelloRetryRequest")
   658  			}
   659  			return nil
   660  		},
   661  	}
   662  
   663  	runClientTestTLS13(t, test)
   664  }
   665  
   666  func TestHandshakeClientECDHERSAChaCha20(t *testing.T) {
   667  	test := &clientTest{
   668  		name:       "ECDHE-RSA-CHACHA20-POLY1305",
   669  		args:       []string{"-cipher", "ECDHE-RSA-CHACHA20-POLY1305"},
   670  		serverCert: &testRSA2048Cert,
   671  		validate:   checkCipherSuite(TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256),
   672  	}
   673  	runClientTestTLS12(t, test)
   674  }
   675  
   676  func TestHandshakeClientECDHEECDSAChaCha20(t *testing.T) {
   677  	test := &clientTest{
   678  		name:     "ECDHE-ECDSA-CHACHA20-POLY1305",
   679  		args:     []string{"-cipher", "ECDHE-ECDSA-CHACHA20-POLY1305"},
   680  		validate: checkCipherSuite(TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256),
   681  	}
   682  	runClientTestTLS12(t, test)
   683  }
   684  
   685  func TestHandshakeClientAES128SHA256(t *testing.T) {
   686  	test := &clientTest{
   687  		name:     "AES128-SHA256",
   688  		args:     []string{"-ciphersuites", "TLS_AES_128_GCM_SHA256"},
   689  		validate: checkCipherSuite(TLS_AES_128_GCM_SHA256),
   690  	}
   691  	runClientTestTLS13(t, test)
   692  }
   693  
   694  func TestHandshakeClientAES256SHA384(t *testing.T) {
   695  	test := &clientTest{
   696  		name:     "AES256-SHA384",
   697  		args:     []string{"-ciphersuites", "TLS_AES_256_GCM_SHA384"},
   698  		validate: checkCipherSuite(TLS_AES_256_GCM_SHA384),
   699  	}
   700  	runClientTestTLS13(t, test)
   701  }
   702  
   703  func TestHandshakeClientCHACHA20SHA256(t *testing.T) {
   704  	test := &clientTest{
   705  		name:     "CHACHA20-SHA256",
   706  		args:     []string{"-ciphersuites", "TLS_CHACHA20_POLY1305_SHA256"},
   707  		validate: checkCipherSuite(TLS_CHACHA20_POLY1305_SHA256),
   708  	}
   709  	runClientTestTLS13(t, test)
   710  }
   711  
   712  func checkPeerCertificateType(expected x509.PublicKeyAlgorithm) func(ConnectionState) error {
   713  	return func(cs ConnectionState) error {
   714  		if len(cs.PeerCertificates) == 0 {
   715  			return errors.New("no peer certificates")
   716  		}
   717  		if cs.PeerCertificates[0].PublicKeyAlgorithm != expected {
   718  			return fmt.Errorf("peer certificate public key algorithm is %v, but expected %v", cs.PeerCertificates[0].PublicKeyAlgorithm, expected)
   719  		}
   720  		return nil
   721  	}
   722  }
   723  
   724  func TestHandshakeClientRSATLS13(t *testing.T) {
   725  	test := &clientTest{
   726  		name:       "RSA",
   727  		serverCert: &testRSA2048Cert,
   728  		validate:   checkPeerCertificateType(x509.RSA),
   729  	}
   730  	runClientTestTLS13(t, test)
   731  }
   732  
   733  func TestHandshakeClientECDSATLS13(t *testing.T) {
   734  	test := &clientTest{
   735  		name:     "ECDSA",
   736  		validate: checkPeerCertificateType(x509.ECDSA),
   737  	}
   738  	runClientTestTLS13(t, test)
   739  }
   740  
   741  func TestHandshakeClientEd25519(t *testing.T) {
   742  	test := &clientTest{
   743  		name:       "Ed25519",
   744  		serverCert: &testEd25519Cert,
   745  		validate:   checkPeerCertificateType(x509.Ed25519),
   746  	}
   747  	runClientTestTLS12(t, test)
   748  	runClientTestTLS13(t, test)
   749  }
   750  
   751  func TestHandshakeClientCertEd25519(t *testing.T) {
   752  	test := &clientTest{
   753  		name:       "ClientCert-Ed25519-Ed25519",
   754  		args:       []string{"-Verify", "1", "-client_sigalgs", "ed25519"},
   755  		serverCert: &testEd25519Cert,
   756  	}
   757  
   758  	runClientTestTLS12(t, test)
   759  	runClientTestTLS13(t, test)
   760  
   761  	test = &clientTest{
   762  		name:       "ClientCert-Ed25519-RSA-ECDHE",
   763  		args:       []string{"-Verify", "1", "-client_sigalgs", "ed25519"},
   764  		serverCert: &testRSA2048Cert,
   765  	}
   766  
   767  	runClientTestTLS12(t, test)
   768  	runClientTestTLS13(t, test)
   769  
   770  	config := testConfigClient.Clone()
   771  	config.CipherSuites = []uint16{TLS_RSA_WITH_AES_128_CBC_SHA256}
   772  	test = &clientTest{
   773  		name:       "ClientCert-Ed25519-RSA",
   774  		args:       []string{"-Verify", "1", "-client_sigalgs", "ed25519", "-cipher", "AES128-SHA256"},
   775  		serverCert: &testRSA2048Cert,
   776  		config:     config,
   777  		validate:   checkCipherSuite(TLS_RSA_WITH_AES_128_CBC_SHA256),
   778  	}
   779  
   780  	runClientTestTLS12(t, test)
   781  }
   782  
   783  func TestHandshakeClientCertRSA(t *testing.T) {
   784  	config := testConfigClient.Clone()
   785  	config.Certificates = []Certificate{testClientRSA2048Cert}
   786  
   787  	test := &clientTest{
   788  		name:       "ClientCert-RSA-RSA-ECDHE",
   789  		args:       []string{"-Verify", "1"},
   790  		config:     config,
   791  		serverCert: &testRSA2048Cert,
   792  	}
   793  
   794  	runClientTestTLS10(t, test)
   795  	runClientTestTLS12(t, test)
   796  	runClientTestTLS13(t, test)
   797  
   798  	test = &clientTest{
   799  		name:   "ClientCert-RSA-ECDSA",
   800  		args:   []string{"-Verify", "1"},
   801  		config: config,
   802  	}
   803  
   804  	runClientTestTLS10(t, test)
   805  	runClientTestTLS12(t, test)
   806  	runClientTestTLS13(t, test)
   807  
   808  	config.CipherSuites = []uint16{TLS_RSA_WITH_AES_128_CBC_SHA}
   809  	test = &clientTest{
   810  		name:       "ClientCert-RSA-RSA",
   811  		args:       []string{"-cipher", "AES128", "-Verify", "1"},
   812  		config:     config,
   813  		serverCert: &testRSA2048Cert,
   814  		validate:   checkCipherSuite(TLS_RSA_WITH_AES_128_CBC_SHA),
   815  	}
   816  
   817  	runClientTestTLS10(t, test)
   818  	runClientTestTLS12(t, test)
   819  }
   820  
   821  func TestHandshakeClientCertECDSA(t *testing.T) {
   822  	config := testConfigClient.Clone()
   823  	config.Certificates = []Certificate{testClientECDSAP256Cert}
   824  
   825  	test := &clientTest{
   826  		name:   "ClientCert-ECDSA-ECDSA",
   827  		args:   []string{"-Verify", "1"},
   828  		config: config,
   829  	}
   830  
   831  	runClientTestTLS10(t, test)
   832  	runClientTestTLS12(t, test)
   833  	runClientTestTLS13(t, test)
   834  
   835  	test = &clientTest{
   836  		name:       "ClientCert-ECDSA-RSA-ECDHE",
   837  		args:       []string{"-Verify", "1"},
   838  		config:     config,
   839  		serverCert: &testRSA2048Cert,
   840  	}
   841  
   842  	runClientTestTLS10(t, test)
   843  	runClientTestTLS12(t, test)
   844  	runClientTestTLS13(t, test)
   845  
   846  	config.CipherSuites = []uint16{TLS_RSA_WITH_AES_128_CBC_SHA}
   847  	test = &clientTest{
   848  		name:       "ClientCert-ECDSA-RSA",
   849  		args:       []string{"-cipher", "AES128", "-Verify", "1"},
   850  		config:     config,
   851  		serverCert: &testRSA2048Cert,
   852  		validate:   checkCipherSuite(TLS_RSA_WITH_AES_128_CBC_SHA),
   853  	}
   854  
   855  	runClientTestTLS10(t, test)
   856  	runClientTestTLS12(t, test)
   857  }
   858  
   859  // TestHandshakeClientCertRSAPSS tests rsa_pss_rsae_sha256 signatures from both
   860  // client and server certificates. It also serves from both sides a certificate
   861  // signed itself with RSA-PSS, mostly to check that crypto/x509 chain validation
   862  // works.
   863  func TestHandshakeClientCertRSAPSS(t *testing.T) {
   864  	config := testConfigClient.Clone()
   865  	config.Certificates = []Certificate{testClientRSAPSSCert}
   866  	test := &clientTest{
   867  		name: "ClientCert-RSA-RSAPSS",
   868  		args: []string{"-Verify", "1",
   869  			"-client_sigalgs", "rsa_pss_rsae_sha256", "-sigalgs", "rsa_pss_rsae_sha256"},
   870  		config:     config,
   871  		serverCert: &testRSAPSSCert,
   872  		validate: func(cs ConnectionState) error {
   873  			if cs.PeerCertificates[0].SignatureAlgorithm != x509.SHA512WithRSAPSS {
   874  				return fmt.Errorf("peer certificate signature algorithm is %v, but expected %v", cs.PeerCertificates[0].SignatureAlgorithm, x509.SHA512WithRSAPSS)
   875  			}
   876  			return nil
   877  		},
   878  	}
   879  	runClientTestTLS12(t, test)
   880  	runClientTestTLS13(t, test)
   881  }
   882  
   883  func TestHandshakeClientCertRSAPKCS1v15(t *testing.T) {
   884  	test := &clientTest{
   885  		name: "ClientCert-RSA-RSAPKCS1v15",
   886  		args: []string{"-Verify", "1",
   887  			"-client_sigalgs", "rsa_pkcs1_sha256", "-sigalgs", "rsa_pkcs1_sha256"},
   888  		serverCert: &testRSA2048Cert,
   889  	}
   890  	runClientTestTLS12(t, test)
   891  }
   892  
   893  func TestClientKeyUpdate(t *testing.T) {
   894  	test := &clientTest{
   895  		name:          "KeyUpdate",
   896  		args:          []string{"-state"},
   897  		sendKeyUpdate: true,
   898  	}
   899  	runClientTestTLS13(t, test)
   900  }
   901  
   902  func TestResumption(t *testing.T) {
   903  	t.Run("TLSv12", func(t *testing.T) { testResumption(t, VersionTLS12) })
   904  	t.Run("TLSv13", func(t *testing.T) { testResumption(t, VersionTLS13) })
   905  }
   906  
   907  func testResumption(t *testing.T, version uint16) {
   908  	if testing.Short() {
   909  		t.Skip("skipping in -short mode")
   910  	}
   911  
   912  	testCertificates := []Certificate{testRSA2048Cert}
   913  	serverConfig := &Config{
   914  		MaxVersion:   version,
   915  		CipherSuites: []uint16{TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384},
   916  		Certificates: testCertificates,
   917  		Time:         testTime,
   918  	}
   919  
   920  	clientConfig := &Config{
   921  		MaxVersion:         version,
   922  		CipherSuites:       []uint16{TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256},
   923  		ClientSessionCache: NewLRUClientSessionCache(32),
   924  		RootCAs:            testRootCertPool,
   925  		ServerName:         "test.golang.example",
   926  		Time:               testTime,
   927  	}
   928  
   929  	testResumeState := func(test string, didResume bool) {
   930  		t.Helper()
   931  		_, hs, err := testHandshake(t, clientConfig, serverConfig)
   932  		if err != nil {
   933  			t.Fatalf("%s: handshake failed: %s", test, err)
   934  		}
   935  		if hs.DidResume != didResume {
   936  			t.Fatalf("%s resumed: %v, expected: %v", test, hs.DidResume, didResume)
   937  		}
   938  		if didResume && (hs.PeerCertificates == nil || hs.VerifiedChains == nil) {
   939  			t.Fatalf("expected non-nil certificates after resumption. Got peerCertificates: %#v, verifiedCertificates: %#v", hs.PeerCertificates, hs.VerifiedChains)
   940  		}
   941  		if got, want := hs.ServerName, clientConfig.ServerName; got != want {
   942  			t.Errorf("%s: server name %s, want %s", test, got, want)
   943  		}
   944  	}
   945  
   946  	getTicket := func() []byte {
   947  		return clientConfig.ClientSessionCache.(*lruSessionCache).q.Front().Value.(*lruSessionCacheEntry).state.session.ticket
   948  	}
   949  	deleteTicket := func() {
   950  		ticketKey := clientConfig.ClientSessionCache.(*lruSessionCache).q.Front().Value.(*lruSessionCacheEntry).sessionKey
   951  		clientConfig.ClientSessionCache.Put(ticketKey, nil)
   952  	}
   953  	corruptTicket := func() {
   954  		clientConfig.ClientSessionCache.(*lruSessionCache).q.Front().Value.(*lruSessionCacheEntry).state.session.secret[0] ^= 0xff
   955  	}
   956  	randomKey := func() [32]byte {
   957  		var k [32]byte
   958  		if _, err := io.ReadFull(serverConfig.rand(), k[:]); err != nil {
   959  			t.Fatalf("Failed to read new SessionTicketKey: %s", err)
   960  		}
   961  		return k
   962  	}
   963  
   964  	testResumeState("Handshake", false)
   965  	ticket := getTicket()
   966  	testResumeState("Resume", true)
   967  	if bytes.Equal(ticket, getTicket()) {
   968  		t.Fatal("ticket didn't change after resumption")
   969  	}
   970  
   971  	// An old session ticket is replaced with a ticket encrypted with a fresh key.
   972  	ticket = getTicket()
   973  	serverConfig.Time = func() time.Time { return testTime().Add(24*time.Hour + time.Minute) }
   974  	testResumeState("ResumeWithOldTicket", true)
   975  	if bytes.Equal(ticket, getTicket()) {
   976  		t.Fatal("old first ticket matches the fresh one")
   977  	}
   978  
   979  	// Once the session master secret is expired, a full handshake should occur.
   980  	ticket = getTicket()
   981  	serverConfig.Time = func() time.Time { return testTime().Add(24*8*time.Hour + time.Minute) }
   982  	testResumeState("ResumeWithExpiredTicket", false)
   983  	if bytes.Equal(ticket, getTicket()) {
   984  		t.Fatal("expired first ticket matches the fresh one")
   985  	}
   986  
   987  	serverConfig.Time = testTime // reset the time back
   988  	key1 := randomKey()
   989  	serverConfig.SetSessionTicketKeys([][32]byte{key1})
   990  
   991  	testResumeState("InvalidSessionTicketKey", false)
   992  	testResumeState("ResumeAfterInvalidSessionTicketKey", true)
   993  
   994  	key2 := randomKey()
   995  	serverConfig.SetSessionTicketKeys([][32]byte{key2, key1})
   996  	ticket = getTicket()
   997  	testResumeState("KeyChange", true)
   998  	if bytes.Equal(ticket, getTicket()) {
   999  		t.Fatal("new ticket wasn't included while resuming")
  1000  	}
  1001  	testResumeState("KeyChangeFinish", true)
  1002  
  1003  	// Age the session ticket a bit, but not yet expired.
  1004  	serverConfig.Time = func() time.Time { return testTime().Add(24*time.Hour + time.Minute) }
  1005  	testResumeState("OldSessionTicket", true)
  1006  	ticket = getTicket()
  1007  	// Expire the session ticket, which would force a full handshake.
  1008  	serverConfig.Time = func() time.Time { return testTime().Add(24*8*time.Hour + 2*time.Minute) }
  1009  	testResumeState("ExpiredSessionTicket", false)
  1010  	if bytes.Equal(ticket, getTicket()) {
  1011  		t.Fatal("new ticket wasn't provided after old ticket expired")
  1012  	}
  1013  
  1014  	// Age the session ticket a bit at a time, but don't expire it.
  1015  	d := 0 * time.Hour
  1016  	serverConfig.Time = func() time.Time { return testTime().Add(d) }
  1017  	deleteTicket()
  1018  	testResumeState("GetFreshSessionTicket", false)
  1019  	for i := 0; i < 13; i++ {
  1020  		d += 12 * time.Hour
  1021  		testResumeState("OldSessionTicket", true)
  1022  	}
  1023  	// Expire it (now a little more than 7 days) and make sure a full
  1024  	// handshake occurs for TLS 1.2. Resumption should still occur for
  1025  	// TLS 1.3 since the client should be using a fresh ticket sent over
  1026  	// by the server.
  1027  	d += 12*time.Hour + time.Minute
  1028  	if version == VersionTLS13 {
  1029  		testResumeState("ExpiredSessionTicket", true)
  1030  	} else {
  1031  		testResumeState("ExpiredSessionTicket", false)
  1032  	}
  1033  	if bytes.Equal(ticket, getTicket()) {
  1034  		t.Fatal("new ticket wasn't provided after old ticket expired")
  1035  	}
  1036  
  1037  	// Reset serverConfig to ensure that calling SetSessionTicketKeys
  1038  	// before the serverConfig is used works.
  1039  	serverConfig = &Config{
  1040  		MaxVersion:   version,
  1041  		CipherSuites: []uint16{TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384},
  1042  		Certificates: testCertificates,
  1043  		Time:         testTime,
  1044  	}
  1045  	serverConfig.SetSessionTicketKeys([][32]byte{key2})
  1046  
  1047  	testResumeState("FreshConfig", true)
  1048  
  1049  	// In TLS 1.3, cross-cipher suite resumption is allowed as long as the KDF
  1050  	// hash matches. Also, Config.CipherSuites does not apply to TLS 1.3.
  1051  	if version != VersionTLS13 {
  1052  		clientConfig.CipherSuites = []uint16{TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384}
  1053  		testResumeState("DifferentCipherSuite", false)
  1054  		testResumeState("DifferentCipherSuiteRecovers", true)
  1055  	}
  1056  
  1057  	deleteTicket()
  1058  	testResumeState("WithoutSessionTicket", false)
  1059  
  1060  	// In TLS 1.3, HelloRetryRequest is sent after incorrect key share.
  1061  	// See https://www.rfc-editor.org/rfc/rfc8446#page-14.
  1062  	if version == VersionTLS13 {
  1063  		deleteTicket()
  1064  		serverConfig = &Config{
  1065  			// Use a different curve than the client to force a HelloRetryRequest.
  1066  			CurvePreferences: []CurveID{CurveP521, CurveP384, CurveP256},
  1067  			MaxVersion:       version,
  1068  			Certificates:     testCertificates,
  1069  			Time:             testTime,
  1070  		}
  1071  		testResumeState("InitialHandshake", false)
  1072  		testResumeState("WithHelloRetryRequest", true)
  1073  
  1074  		// Reset serverConfig back.
  1075  		serverConfig = &Config{
  1076  			MaxVersion:   version,
  1077  			CipherSuites: []uint16{TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384},
  1078  			Certificates: testCertificates,
  1079  			Time:         testTime,
  1080  		}
  1081  	}
  1082  
  1083  	// Session resumption should work when using client certificates
  1084  	deleteTicket()
  1085  	serverConfig.ClientCAs = testClientRootCertPool
  1086  	serverConfig.ClientAuth = RequireAndVerifyClientCert
  1087  	clientConfig.Certificates = []Certificate{testClientRSA2048Cert}
  1088  	testResumeState("InitialHandshake", false)
  1089  	testResumeState("WithClientCertificates", true)
  1090  	serverConfig.ClientAuth = NoClientCert
  1091  
  1092  	// Tickets should be removed from the session cache on TLS handshake
  1093  	// failure, and the client should recover from a corrupted PSK
  1094  	testResumeState("FetchTicketToCorrupt", false)
  1095  	corruptTicket()
  1096  	_, _, err := testHandshake(t, clientConfig, serverConfig)
  1097  	if err == nil {
  1098  		t.Fatalf("handshake did not fail with a corrupted client secret")
  1099  	}
  1100  	testResumeState("AfterHandshakeFailure", false)
  1101  
  1102  	clientConfig.ClientSessionCache = nil
  1103  	testResumeState("WithoutSessionCache", false)
  1104  
  1105  	clientConfig.ClientSessionCache = &serializingClientCache{t: t}
  1106  	testResumeState("BeforeSerializingCache", false)
  1107  	testResumeState("WithSerializingCache", true)
  1108  }
  1109  
  1110  type serializingClientCache struct {
  1111  	t *testing.T
  1112  
  1113  	ticket, state []byte
  1114  }
  1115  
  1116  func (c *serializingClientCache) Get(sessionKey string) (session *ClientSessionState, ok bool) {
  1117  	if c.ticket == nil {
  1118  		return nil, false
  1119  	}
  1120  	state, err := ParseSessionState(c.state)
  1121  	if err != nil {
  1122  		c.t.Error(err)
  1123  		return nil, false
  1124  	}
  1125  	cs, err := NewResumptionState(c.ticket, state)
  1126  	if err != nil {
  1127  		c.t.Error(err)
  1128  		return nil, false
  1129  	}
  1130  	return cs, true
  1131  }
  1132  
  1133  func (c *serializingClientCache) Put(sessionKey string, cs *ClientSessionState) {
  1134  	if cs == nil {
  1135  		c.ticket, c.state = nil, nil
  1136  		return
  1137  	}
  1138  	ticket, state, err := cs.ResumptionState()
  1139  	if err != nil {
  1140  		c.t.Error(err)
  1141  		return
  1142  	}
  1143  	stateBytes, err := state.Bytes()
  1144  	if err != nil {
  1145  		c.t.Error(err)
  1146  		return
  1147  	}
  1148  	c.ticket, c.state = ticket, stateBytes
  1149  }
  1150  
  1151  func TestLRUClientSessionCache(t *testing.T) {
  1152  	// Initialize cache of capacity 4.
  1153  	cache := NewLRUClientSessionCache(4)
  1154  	cs := make([]ClientSessionState, 6)
  1155  	keys := []string{"0", "1", "2", "3", "4", "5", "6"}
  1156  
  1157  	// Add 4 entries to the cache and look them up.
  1158  	for i := 0; i < 4; i++ {
  1159  		cache.Put(keys[i], &cs[i])
  1160  	}
  1161  	for i := 0; i < 4; i++ {
  1162  		if s, ok := cache.Get(keys[i]); !ok || s != &cs[i] {
  1163  			t.Fatalf("session cache failed lookup for added key: %s", keys[i])
  1164  		}
  1165  	}
  1166  
  1167  	// Add 2 more entries to the cache. First 2 should be evicted.
  1168  	for i := 4; i < 6; i++ {
  1169  		cache.Put(keys[i], &cs[i])
  1170  	}
  1171  	for i := 0; i < 2; i++ {
  1172  		if s, ok := cache.Get(keys[i]); ok || s != nil {
  1173  			t.Fatalf("session cache should have evicted key: %s", keys[i])
  1174  		}
  1175  	}
  1176  
  1177  	// Touch entry 2. LRU should evict 3 next.
  1178  	cache.Get(keys[2])
  1179  	cache.Put(keys[0], &cs[0])
  1180  	if s, ok := cache.Get(keys[3]); ok || s != nil {
  1181  		t.Fatalf("session cache should have evicted key 3")
  1182  	}
  1183  
  1184  	// Update entry 0 in place.
  1185  	cache.Put(keys[0], &cs[3])
  1186  	if s, ok := cache.Get(keys[0]); !ok || s != &cs[3] {
  1187  		t.Fatalf("session cache failed update for key 0")
  1188  	}
  1189  
  1190  	// Calling Put with a nil entry deletes the key.
  1191  	cache.Put(keys[0], nil)
  1192  	if _, ok := cache.Get(keys[0]); ok {
  1193  		t.Fatalf("session cache failed to delete key 0")
  1194  	}
  1195  
  1196  	// Delete entry 2. LRU should keep 4 and 5
  1197  	cache.Put(keys[2], nil)
  1198  	if _, ok := cache.Get(keys[2]); ok {
  1199  		t.Fatalf("session cache failed to delete key 4")
  1200  	}
  1201  	for i := 4; i < 6; i++ {
  1202  		if s, ok := cache.Get(keys[i]); !ok || s != &cs[i] {
  1203  			t.Fatalf("session cache should not have deleted key: %s", keys[i])
  1204  		}
  1205  	}
  1206  }
  1207  
  1208  func TestKeyLogTLS12(t *testing.T) {
  1209  	var serverBuf, clientBuf bytes.Buffer
  1210  
  1211  	clientConfig := testConfigClient.Clone()
  1212  	clientConfig.KeyLogWriter = &clientBuf
  1213  	clientConfig.MaxVersion = VersionTLS12
  1214  
  1215  	serverConfig := testConfigServer.Clone()
  1216  	serverConfig.KeyLogWriter = &serverBuf
  1217  	serverConfig.MaxVersion = VersionTLS12
  1218  
  1219  	c, s := localPipe(t)
  1220  	done := make(chan bool)
  1221  
  1222  	go func() {
  1223  		defer close(done)
  1224  
  1225  		if err := Server(s, serverConfig).Handshake(); err != nil {
  1226  			t.Errorf("server: %s", err)
  1227  			return
  1228  		}
  1229  		s.Close()
  1230  	}()
  1231  
  1232  	if err := Client(c, clientConfig).Handshake(); err != nil {
  1233  		t.Fatalf("client: %s", err)
  1234  	}
  1235  
  1236  	c.Close()
  1237  	<-done
  1238  
  1239  	checkKeylogLine := func(side, loggedLine string) {
  1240  		if len(loggedLine) == 0 {
  1241  			t.Fatalf("%s: no keylog line was produced", side)
  1242  		}
  1243  		rest, ok := strings.CutSuffix(loggedLine, "\n")
  1244  		if !ok {
  1245  			t.Fatalf("%s: keylog line is missing trailing newline: %q", side, loggedLine)
  1246  		}
  1247  		label, rest, ok := strings.Cut(rest, " ")
  1248  		if !ok || label != "CLIENT_RANDOM" {
  1249  			t.Fatalf("%s: keylog line has incorrect label: %q", side, loggedLine)
  1250  		}
  1251  		clientRandom, masterSecret, ok := strings.Cut(rest, " ")
  1252  		if !ok {
  1253  			t.Fatalf("%s: keylog line is missing master secret: %q", side, loggedLine)
  1254  		}
  1255  		if b, err := hex.DecodeString(clientRandom); err != nil || len(b) != 32 {
  1256  			t.Fatalf("%s: keylog line has invalid client random: %q", side, loggedLine)
  1257  		}
  1258  		if b, err := hex.DecodeString(masterSecret); err != nil || len(b) != 48 {
  1259  			t.Fatalf("%s: keylog line has invalid master secret: %q", side, loggedLine)
  1260  		}
  1261  	}
  1262  
  1263  	checkKeylogLine("client", clientBuf.String())
  1264  	checkKeylogLine("server", serverBuf.String())
  1265  }
  1266  
  1267  func TestKeyLogTLS13(t *testing.T) {
  1268  	var serverBuf, clientBuf bytes.Buffer
  1269  
  1270  	clientConfig := testConfigClient.Clone()
  1271  	clientConfig.KeyLogWriter = &clientBuf
  1272  
  1273  	serverConfig := testConfigServer.Clone()
  1274  	serverConfig.KeyLogWriter = &serverBuf
  1275  
  1276  	c, s := localPipe(t)
  1277  	done := make(chan bool)
  1278  
  1279  	go func() {
  1280  		defer close(done)
  1281  
  1282  		if err := Server(s, serverConfig).Handshake(); err != nil {
  1283  			t.Errorf("server: %s", err)
  1284  			return
  1285  		}
  1286  		s.Close()
  1287  	}()
  1288  
  1289  	if err := Client(c, clientConfig).Handshake(); err != nil {
  1290  		t.Fatalf("client: %s", err)
  1291  	}
  1292  
  1293  	c.Close()
  1294  	<-done
  1295  
  1296  	checkKeylogLines := func(side, loggedLines string) {
  1297  		loggedLines = strings.TrimSpace(loggedLines)
  1298  		lines := strings.Split(loggedLines, "\n")
  1299  		if len(lines) != 4 {
  1300  			t.Errorf("Expected the %s to log 4 lines, got %d", side, len(lines))
  1301  		}
  1302  	}
  1303  
  1304  	checkKeylogLines("client", clientBuf.String())
  1305  	checkKeylogLines("server", serverBuf.String())
  1306  }
  1307  
  1308  func TestHandshakeClientALPNMatch(t *testing.T) {
  1309  	config := testConfigClient.Clone()
  1310  	config.NextProtos = []string{"proto2", "proto1"}
  1311  	test := &clientTest{
  1312  		name:   "ALPN",
  1313  		args:   []string{"-alpn", "proto1,proto2"},
  1314  		config: config,
  1315  		// The server's preferences should override the client.
  1316  		validate: checkNegotiatedProtocol("proto1"),
  1317  	}
  1318  	runClientTestTLS12(t, test)
  1319  	runClientTestTLS13(t, test)
  1320  }
  1321  
  1322  func TestServerSelectingUnconfiguredApplicationProtocol(t *testing.T) {
  1323  	// This checks that the server can't select an application protocol that the
  1324  	// client didn't offer.
  1325  
  1326  	c, s := localPipe(t)
  1327  	errChan := make(chan error, 1)
  1328  
  1329  	go func() {
  1330  		client := Client(c, &Config{
  1331  			ServerName:   "foo",
  1332  			CipherSuites: []uint16{TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256},
  1333  			NextProtos:   []string{"http", "something-else"},
  1334  		})
  1335  		errChan <- client.Handshake()
  1336  	}()
  1337  
  1338  	var header [5]byte
  1339  	if _, err := io.ReadFull(s, header[:]); err != nil {
  1340  		t.Fatal(err)
  1341  	}
  1342  	recordLen := int(header[3])<<8 | int(header[4])
  1343  
  1344  	record := make([]byte, recordLen)
  1345  	if _, err := io.ReadFull(s, record); err != nil {
  1346  		t.Fatal(err)
  1347  	}
  1348  
  1349  	serverHello := &serverHelloMsg{
  1350  		vers:         VersionTLS12,
  1351  		random:       make([]byte, 32),
  1352  		cipherSuite:  TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
  1353  		alpnProtocol: "how-about-this",
  1354  	}
  1355  	serverHelloBytes := mustMarshal(t, serverHello)
  1356  
  1357  	s.Write([]byte{
  1358  		byte(recordTypeHandshake),
  1359  		byte(VersionTLS12 >> 8),
  1360  		byte(VersionTLS12 & 0xff),
  1361  		byte(len(serverHelloBytes) >> 8),
  1362  		byte(len(serverHelloBytes)),
  1363  	})
  1364  	s.Write(serverHelloBytes)
  1365  	s.Close()
  1366  
  1367  	if err := <-errChan; !strings.Contains(err.Error(), "server selected unadvertised ALPN protocol") {
  1368  		t.Fatalf("Expected error about unconfigured ALPN protocol but got %q", err)
  1369  	}
  1370  }
  1371  
  1372  // sctsBase64 contains data from `openssl s_client -serverinfo 18 -connect ritter.vg:443`
  1373  const sctsBase64 = "ABIBaQFnAHUApLkJkLQYWBSHuxOizGdwCjw1mAT5G9+443fNDsgN3BAAAAFHl5nuFgAABAMARjBEAiAcS4JdlW5nW9sElUv2zvQyPoZ6ejKrGGB03gjaBZFMLwIgc1Qbbn+hsH0RvObzhS+XZhr3iuQQJY8S9G85D9KeGPAAdgBo9pj4H2SCvjqM7rkoHUz8cVFdZ5PURNEKZ6y7T0/7xAAAAUeX4bVwAAAEAwBHMEUCIDIhFDgG2HIuADBkGuLobU5a4dlCHoJLliWJ1SYT05z6AiEAjxIoZFFPRNWMGGIjskOTMwXzQ1Wh2e7NxXE1kd1J0QsAdgDuS723dc5guuFCaR+r4Z5mow9+X7By2IMAxHuJeqj9ywAAAUhcZIqHAAAEAwBHMEUCICmJ1rBT09LpkbzxtUC+Hi7nXLR0J+2PmwLp+sJMuqK+AiEAr0NkUnEVKVhAkccIFpYDqHOlZaBsuEhWWrYpg2RtKp0="
  1374  
  1375  func TestHandshakeClientSCTs(t *testing.T) {
  1376  	scts, err := base64.StdEncoding.DecodeString(sctsBase64)
  1377  	if err != nil {
  1378  		t.Fatal(err)
  1379  	}
  1380  
  1381  	test := &clientTest{
  1382  		name:       "SCT",
  1383  		extensions: [][]byte{scts},
  1384  		validate: func(state ConnectionState) error {
  1385  			expectedSCTs := [][]byte{
  1386  				scts[8:125],
  1387  				scts[127:245],
  1388  				scts[247:],
  1389  			}
  1390  			if n := len(state.SignedCertificateTimestamps); n != len(expectedSCTs) {
  1391  				return fmt.Errorf("Got %d scts, wanted %d", n, len(expectedSCTs))
  1392  			}
  1393  			for i, expected := range expectedSCTs {
  1394  				if sct := state.SignedCertificateTimestamps[i]; !bytes.Equal(sct, expected) {
  1395  					return fmt.Errorf("SCT #%d contained %x, expected %x", i, sct, expected)
  1396  				}
  1397  			}
  1398  			return nil
  1399  		},
  1400  	}
  1401  	runClientTestTLS12(t, test)
  1402  
  1403  	// TLS 1.3 moved SCTs to the Certificate extensions and -serverinfo only
  1404  	// supports ServerHello extensions.
  1405  }
  1406  
  1407  func TestRenegotiationRejected(t *testing.T) {
  1408  	test := &clientTest{
  1409  		name:                        "RenegotiationRejected",
  1410  		args:                        []string{"-state"},
  1411  		numRenegotiations:           1,
  1412  		renegotiationExpectedToFail: 1,
  1413  		checkRenegotiationError: func(renegotiationNum int, err error) error {
  1414  			if err == nil {
  1415  				return errors.New("expected error from renegotiation but got nil")
  1416  			}
  1417  			if !strings.Contains(err.Error(), "no renegotiation") {
  1418  				return fmt.Errorf("expected renegotiation to be rejected but got %q", err)
  1419  			}
  1420  			return nil
  1421  		},
  1422  	}
  1423  	runClientTestTLS12(t, test)
  1424  }
  1425  
  1426  func TestRenegotiateOnce(t *testing.T) {
  1427  	config := testConfigClient.Clone()
  1428  	config.Renegotiation = RenegotiateOnceAsClient
  1429  
  1430  	test := &clientTest{
  1431  		name:              "RenegotiateOnce",
  1432  		args:              []string{"-state"},
  1433  		config:            config,
  1434  		numRenegotiations: 1,
  1435  	}
  1436  
  1437  	runClientTestTLS12(t, test)
  1438  }
  1439  
  1440  func TestRenegotiateTwice(t *testing.T) {
  1441  	config := testConfigClient.Clone()
  1442  	config.Renegotiation = RenegotiateFreelyAsClient
  1443  
  1444  	test := &clientTest{
  1445  		name:              "RenegotiateTwice",
  1446  		args:              []string{"-state"},
  1447  		config:            config,
  1448  		numRenegotiations: 2,
  1449  	}
  1450  
  1451  	runClientTestTLS12(t, test)
  1452  }
  1453  
  1454  func TestRenegotiateTwiceRejected(t *testing.T) {
  1455  	config := testConfigClient.Clone()
  1456  	config.Renegotiation = RenegotiateOnceAsClient
  1457  
  1458  	test := &clientTest{
  1459  		name:                        "RenegotiateTwiceRejected",
  1460  		args:                        []string{"-state"},
  1461  		config:                      config,
  1462  		numRenegotiations:           2,
  1463  		renegotiationExpectedToFail: 2,
  1464  		checkRenegotiationError: func(renegotiationNum int, err error) error {
  1465  			if renegotiationNum == 1 {
  1466  				return err
  1467  			}
  1468  
  1469  			if err == nil {
  1470  				return errors.New("expected error from renegotiation but got nil")
  1471  			}
  1472  			if !strings.Contains(err.Error(), "no renegotiation") {
  1473  				return fmt.Errorf("expected renegotiation to be rejected but got %q", err)
  1474  			}
  1475  			return nil
  1476  		},
  1477  	}
  1478  
  1479  	runClientTestTLS12(t, test)
  1480  }
  1481  
  1482  func TestHandshakeClientExportKeyingMaterial(t *testing.T) {
  1483  	test := &clientTest{
  1484  		name: "ExportKeyingMaterial",
  1485  		validate: func(state ConnectionState) error {
  1486  			if km, err := state.ExportKeyingMaterial("test", nil, 42); err != nil {
  1487  				return fmt.Errorf("ExportKeyingMaterial failed: %v", err)
  1488  			} else if len(km) != 42 {
  1489  				return fmt.Errorf("Got %d bytes from ExportKeyingMaterial, wanted %d", len(km), 42)
  1490  			}
  1491  			return nil
  1492  		},
  1493  	}
  1494  	runClientTestTLS10(t, test)
  1495  	runClientTestTLS12(t, test)
  1496  	runClientTestTLS13(t, test)
  1497  }
  1498  
  1499  var hostnameInSNITests = []struct {
  1500  	in, out string
  1501  }{
  1502  	// Opaque string
  1503  	{"", ""},
  1504  	{"localhost", "localhost"},
  1505  	{"foo, bar, baz and qux", "foo, bar, baz and qux"},
  1506  
  1507  	// DNS hostname
  1508  	{"golang.org", "golang.org"},
  1509  	{"golang.org.", "golang.org"},
  1510  
  1511  	// Literal IPv4 address
  1512  	{"1.2.3.4", ""},
  1513  
  1514  	// Literal IPv6 address
  1515  	{"::1", ""},
  1516  	{"::1%lo0", ""}, // with zone identifier
  1517  	{"[::1]", ""},   // as per RFC 5952 we allow the [] style as IPv6 literal
  1518  	{"[::1%lo0]", ""},
  1519  }
  1520  
  1521  func TestHostnameInSNI(t *testing.T) {
  1522  	for _, tt := range hostnameInSNITests {
  1523  		c, s := localPipe(t)
  1524  
  1525  		go func(host string) {
  1526  			Client(c, &Config{ServerName: host, InsecureSkipVerify: true}).Handshake()
  1527  		}(tt.in)
  1528  
  1529  		var header [5]byte
  1530  		if _, err := io.ReadFull(s, header[:]); err != nil {
  1531  			t.Fatal(err)
  1532  		}
  1533  		recordLen := int(header[3])<<8 | int(header[4])
  1534  
  1535  		record := make([]byte, recordLen)
  1536  		if _, err := io.ReadFull(s, record[:]); err != nil {
  1537  			t.Fatal(err)
  1538  		}
  1539  
  1540  		c.Close()
  1541  		s.Close()
  1542  
  1543  		var m clientHelloMsg
  1544  		if !m.unmarshal(record) {
  1545  			t.Errorf("unmarshaling ClientHello for %q failed", tt.in)
  1546  			continue
  1547  		}
  1548  		if tt.in != tt.out && m.serverName == tt.in {
  1549  			t.Errorf("prohibited %q found in ClientHello: %x", tt.in, record)
  1550  		}
  1551  		if m.serverName != tt.out {
  1552  			t.Errorf("expected %q not found in ClientHello: %x", tt.out, record)
  1553  		}
  1554  	}
  1555  }
  1556  
  1557  func TestServerSelectingUnconfiguredCipherSuite(t *testing.T) {
  1558  	// This checks that the server can't select a cipher suite that the
  1559  	// client didn't offer. See #13174.
  1560  
  1561  	c, s := localPipe(t)
  1562  	errChan := make(chan error, 1)
  1563  
  1564  	go func() {
  1565  		client := Client(c, &Config{
  1566  			ServerName:   "foo",
  1567  			CipherSuites: []uint16{TLS_RSA_WITH_AES_128_GCM_SHA256},
  1568  		})
  1569  		errChan <- client.Handshake()
  1570  	}()
  1571  
  1572  	var header [5]byte
  1573  	if _, err := io.ReadFull(s, header[:]); err != nil {
  1574  		t.Fatal(err)
  1575  	}
  1576  	recordLen := int(header[3])<<8 | int(header[4])
  1577  
  1578  	record := make([]byte, recordLen)
  1579  	if _, err := io.ReadFull(s, record); err != nil {
  1580  		t.Fatal(err)
  1581  	}
  1582  
  1583  	// Create a ServerHello that selects a different cipher suite than the
  1584  	// sole one that the client offered.
  1585  	serverHello := &serverHelloMsg{
  1586  		vers:        VersionTLS12,
  1587  		random:      make([]byte, 32),
  1588  		cipherSuite: TLS_RSA_WITH_AES_256_GCM_SHA384,
  1589  	}
  1590  	serverHelloBytes := mustMarshal(t, serverHello)
  1591  
  1592  	s.Write([]byte{
  1593  		byte(recordTypeHandshake),
  1594  		byte(VersionTLS12 >> 8),
  1595  		byte(VersionTLS12 & 0xff),
  1596  		byte(len(serverHelloBytes) >> 8),
  1597  		byte(len(serverHelloBytes)),
  1598  	})
  1599  	s.Write(serverHelloBytes)
  1600  	s.Close()
  1601  
  1602  	if err := <-errChan; !strings.Contains(err.Error(), "unconfigured cipher") {
  1603  		t.Fatalf("Expected error about unconfigured cipher suite but got %q", err)
  1604  	}
  1605  }
  1606  
  1607  func TestVerifyConnection(t *testing.T) {
  1608  	t.Run("TLSv12", func(t *testing.T) { testVerifyConnection(t, VersionTLS12) })
  1609  	t.Run("TLSv13", func(t *testing.T) { testVerifyConnection(t, VersionTLS13) })
  1610  }
  1611  
  1612  func testVerifyConnection(t *testing.T, version uint16) {
  1613  	checkFields := func(c ConnectionState, called *int, errorType string) error {
  1614  		if c.Version != version {
  1615  			return fmt.Errorf("%s: got Version %v, want %v", errorType, c.Version, version)
  1616  		}
  1617  		if c.HandshakeComplete {
  1618  			return fmt.Errorf("%s: got HandshakeComplete, want false", errorType)
  1619  		}
  1620  		if c.ServerName != "test.golang.example" {
  1621  			return fmt.Errorf("%s: got ServerName %s, want %s", errorType, c.ServerName, "test.golang.example")
  1622  		}
  1623  		if c.NegotiatedProtocol != "protocol1" {
  1624  			return fmt.Errorf("%s: got NegotiatedProtocol %s, want %s", errorType, c.NegotiatedProtocol, "protocol1")
  1625  		}
  1626  		if c.CipherSuite == 0 {
  1627  			return fmt.Errorf("%s: got CipherSuite 0, want non-zero", errorType)
  1628  		}
  1629  		wantDidResume := false
  1630  		if *called == 2 { // if this is the second time, then it should be a resumption
  1631  			wantDidResume = true
  1632  		}
  1633  		if c.DidResume != wantDidResume {
  1634  			return fmt.Errorf("%s: got DidResume %t, want %t", errorType, c.DidResume, wantDidResume)
  1635  		}
  1636  		return nil
  1637  	}
  1638  
  1639  	tests := []struct {
  1640  		name            string
  1641  		configureServer func(*Config, *int)
  1642  		configureClient func(*Config, *int)
  1643  	}{
  1644  		{
  1645  			name: "RequireAndVerifyClientCert",
  1646  			configureServer: func(config *Config, called *int) {
  1647  				config.ClientAuth = RequireAndVerifyClientCert
  1648  				config.VerifyConnection = func(c ConnectionState) error {
  1649  					*called++
  1650  					if l := len(c.PeerCertificates); l != 1 {
  1651  						return fmt.Errorf("server: got len(PeerCertificates) = %d, wanted 1", l)
  1652  					}
  1653  					if len(c.VerifiedChains) == 0 {
  1654  						return fmt.Errorf("server: got len(VerifiedChains) = 0, wanted non-zero")
  1655  					}
  1656  					return checkFields(c, called, "server")
  1657  				}
  1658  			},
  1659  			configureClient: func(config *Config, called *int) {
  1660  				config.VerifyConnection = func(c ConnectionState) error {
  1661  					*called++
  1662  					if l := len(c.PeerCertificates); l != 1 {
  1663  						return fmt.Errorf("client: got len(PeerCertificates) = %d, wanted 1", l)
  1664  					}
  1665  					if len(c.VerifiedChains) == 0 {
  1666  						return fmt.Errorf("client: got len(VerifiedChains) = 0, wanted non-zero")
  1667  					}
  1668  					if c.DidResume {
  1669  						return nil
  1670  						// The SCTs and OCSP Response are dropped on resumption.
  1671  						// See http://golang.org/issue/39075.
  1672  					}
  1673  					if len(c.OCSPResponse) == 0 {
  1674  						return fmt.Errorf("client: got len(OCSPResponse) = 0, wanted non-zero")
  1675  					}
  1676  					if len(c.SignedCertificateTimestamps) == 0 {
  1677  						return fmt.Errorf("client: got len(SignedCertificateTimestamps) = 0, wanted non-zero")
  1678  					}
  1679  					return checkFields(c, called, "client")
  1680  				}
  1681  			},
  1682  		},
  1683  		{
  1684  			name: "InsecureSkipVerify",
  1685  			configureServer: func(config *Config, called *int) {
  1686  				config.ClientAuth = RequireAnyClientCert
  1687  				config.InsecureSkipVerify = true
  1688  				config.VerifyConnection = func(c ConnectionState) error {
  1689  					*called++
  1690  					if l := len(c.PeerCertificates); l != 1 {
  1691  						return fmt.Errorf("server: got len(PeerCertificates) = %d, wanted 1", l)
  1692  					}
  1693  					if c.VerifiedChains != nil {
  1694  						return fmt.Errorf("server: got Verified Chains %v, want nil", c.VerifiedChains)
  1695  					}
  1696  					return checkFields(c, called, "server")
  1697  				}
  1698  			},
  1699  			configureClient: func(config *Config, called *int) {
  1700  				config.InsecureSkipVerify = true
  1701  				config.VerifyConnection = func(c ConnectionState) error {
  1702  					*called++
  1703  					if l := len(c.PeerCertificates); l != 1 {
  1704  						return fmt.Errorf("client: got len(PeerCertificates) = %d, wanted 1", l)
  1705  					}
  1706  					if c.VerifiedChains != nil {
  1707  						return fmt.Errorf("server: got Verified Chains %v, want nil", c.VerifiedChains)
  1708  					}
  1709  					if c.DidResume {
  1710  						return nil
  1711  						// The SCTs and OCSP Response are dropped on resumption.
  1712  						// See http://golang.org/issue/39075.
  1713  					}
  1714  					if len(c.OCSPResponse) == 0 {
  1715  						return fmt.Errorf("client: got len(OCSPResponse) = 0, wanted non-zero")
  1716  					}
  1717  					if len(c.SignedCertificateTimestamps) == 0 {
  1718  						return fmt.Errorf("client: got len(SignedCertificateTimestamps) = 0, wanted non-zero")
  1719  					}
  1720  					return checkFields(c, called, "client")
  1721  				}
  1722  			},
  1723  		},
  1724  		{
  1725  			name: "NoClientCert",
  1726  			configureServer: func(config *Config, called *int) {
  1727  				config.ClientAuth = NoClientCert
  1728  				config.VerifyConnection = func(c ConnectionState) error {
  1729  					*called++
  1730  					return checkFields(c, called, "server")
  1731  				}
  1732  			},
  1733  			configureClient: func(config *Config, called *int) {
  1734  				config.VerifyConnection = func(c ConnectionState) error {
  1735  					*called++
  1736  					return checkFields(c, called, "client")
  1737  				}
  1738  			},
  1739  		},
  1740  		{
  1741  			name: "RequestClientCert",
  1742  			configureServer: func(config *Config, called *int) {
  1743  				config.ClientAuth = RequestClientCert
  1744  				config.VerifyConnection = func(c ConnectionState) error {
  1745  					*called++
  1746  					return checkFields(c, called, "server")
  1747  				}
  1748  			},
  1749  			configureClient: func(config *Config, called *int) {
  1750  				config.Certificates = nil // clear the client cert
  1751  				config.VerifyConnection = func(c ConnectionState) error {
  1752  					*called++
  1753  					if l := len(c.PeerCertificates); l != 1 {
  1754  						return fmt.Errorf("client: got len(PeerCertificates) = %d, wanted 1", l)
  1755  					}
  1756  					if len(c.VerifiedChains) == 0 {
  1757  						return fmt.Errorf("client: got len(VerifiedChains) = 0, wanted non-zero")
  1758  					}
  1759  					if c.DidResume {
  1760  						return nil
  1761  						// The SCTs and OCSP Response are dropped on resumption.
  1762  						// See http://golang.org/issue/39075.
  1763  					}
  1764  					if len(c.OCSPResponse) == 0 {
  1765  						return fmt.Errorf("client: got len(OCSPResponse) = 0, wanted non-zero")
  1766  					}
  1767  					if len(c.SignedCertificateTimestamps) == 0 {
  1768  						return fmt.Errorf("client: got len(SignedCertificateTimestamps) = 0, wanted non-zero")
  1769  					}
  1770  					return checkFields(c, called, "client")
  1771  				}
  1772  			},
  1773  		},
  1774  	}
  1775  	for _, test := range tests {
  1776  		var serverCalled, clientCalled int
  1777  
  1778  		serverConfig := &Config{
  1779  			MaxVersion:   version,
  1780  			Certificates: []Certificate{testRSA2048Cert},
  1781  			Time:         testTime,
  1782  			ClientCAs:    testClientRootCertPool,
  1783  			NextProtos:   []string{"protocol1"},
  1784  		}
  1785  		serverConfig.Certificates[0].SignedCertificateTimestamps = [][]byte{[]byte("dummy sct 1"), []byte("dummy sct 2")}
  1786  		serverConfig.Certificates[0].OCSPStaple = []byte("dummy ocsp")
  1787  		test.configureServer(serverConfig, &serverCalled)
  1788  
  1789  		clientConfig := &Config{
  1790  			MaxVersion:         version,
  1791  			ClientSessionCache: NewLRUClientSessionCache(32),
  1792  			RootCAs:            testRootCertPool,
  1793  			ServerName:         "test.golang.example",
  1794  			Certificates:       []Certificate{testClientRSA2048Cert},
  1795  			Time:               testTime,
  1796  			NextProtos:         []string{"protocol1"},
  1797  		}
  1798  		test.configureClient(clientConfig, &clientCalled)
  1799  
  1800  		testHandshakeState := func(name string, didResume bool) {
  1801  			_, hs, err := testHandshake(t, clientConfig, serverConfig)
  1802  			if err != nil {
  1803  				t.Fatalf("%s: handshake failed: %s", name, err)
  1804  			}
  1805  			if hs.DidResume != didResume {
  1806  				t.Errorf("%s: resumed: %v, expected: %v", name, hs.DidResume, didResume)
  1807  			}
  1808  			wantCalled := 1
  1809  			if didResume {
  1810  				wantCalled = 2 // resumption would mean this is the second time it was called in this test
  1811  			}
  1812  			if clientCalled != wantCalled {
  1813  				t.Errorf("%s: expected client VerifyConnection called %d times, did %d times", name, wantCalled, clientCalled)
  1814  			}
  1815  			if serverCalled != wantCalled {
  1816  				t.Errorf("%s: expected server VerifyConnection called %d times, did %d times", name, wantCalled, serverCalled)
  1817  			}
  1818  		}
  1819  		testHandshakeState(fmt.Sprintf("%s-FullHandshake", test.name), false)
  1820  		testHandshakeState(fmt.Sprintf("%s-Resumption", test.name), true)
  1821  	}
  1822  }
  1823  
  1824  func TestVerifyPeerCertificate(t *testing.T) {
  1825  	t.Run("TLSv12", func(t *testing.T) { testVerifyPeerCertificate(t, VersionTLS12) })
  1826  	t.Run("TLSv13", func(t *testing.T) { testVerifyPeerCertificate(t, VersionTLS13) })
  1827  }
  1828  
  1829  func testVerifyPeerCertificate(t *testing.T, version uint16) {
  1830  	sentinelErr := errors.New("TestVerifyPeerCertificate")
  1831  
  1832  	verifyPeerCertificateCallback := func(called *bool, rawCerts [][]byte, validatedChains [][]*x509.Certificate) error {
  1833  		if l := len(rawCerts); l != 1 {
  1834  			return fmt.Errorf("got len(rawCerts) = %d, wanted 1", l)
  1835  		}
  1836  		if len(validatedChains) == 0 {
  1837  			return errors.New("got len(validatedChains) = 0, wanted non-zero")
  1838  		}
  1839  		*called = true
  1840  		return nil
  1841  	}
  1842  	verifyConnectionCallback := func(called *bool, isClient bool, c ConnectionState) error {
  1843  		if l := len(c.PeerCertificates); l != 1 {
  1844  			return fmt.Errorf("got len(PeerCertificates) = %d, wanted 1", l)
  1845  		}
  1846  		if len(c.VerifiedChains) == 0 {
  1847  			return fmt.Errorf("got len(VerifiedChains) = 0, wanted non-zero")
  1848  		}
  1849  		if isClient && len(c.OCSPResponse) == 0 {
  1850  			return fmt.Errorf("got len(OCSPResponse) = 0, wanted non-zero")
  1851  		}
  1852  		*called = true
  1853  		return nil
  1854  	}
  1855  
  1856  	tests := []struct {
  1857  		configureServer func(*Config, *bool)
  1858  		configureClient func(*Config, *bool)
  1859  		validate        func(t *testing.T, testNo int, clientCalled, serverCalled bool, clientErr, serverErr error)
  1860  	}{
  1861  		{
  1862  			configureServer: func(config *Config, called *bool) {
  1863  				config.InsecureSkipVerify = false
  1864  				config.VerifyPeerCertificate = func(rawCerts [][]byte, validatedChains [][]*x509.Certificate) error {
  1865  					return verifyPeerCertificateCallback(called, rawCerts, validatedChains)
  1866  				}
  1867  			},
  1868  			configureClient: func(config *Config, called *bool) {
  1869  				config.InsecureSkipVerify = false
  1870  				config.VerifyPeerCertificate = func(rawCerts [][]byte, validatedChains [][]*x509.Certificate) error {
  1871  					return verifyPeerCertificateCallback(called, rawCerts, validatedChains)
  1872  				}
  1873  			},
  1874  			validate: func(t *testing.T, testNo int, clientCalled, serverCalled bool, clientErr, serverErr error) {
  1875  				if clientErr != nil {
  1876  					t.Errorf("test[%d]: client handshake failed: %v", testNo, clientErr)
  1877  				}
  1878  				if serverErr != nil {
  1879  					t.Errorf("test[%d]: server handshake failed: %v", testNo, serverErr)
  1880  				}
  1881  				if !clientCalled {
  1882  					t.Errorf("test[%d]: client did not call callback", testNo)
  1883  				}
  1884  				if !serverCalled {
  1885  					t.Errorf("test[%d]: server did not call callback", testNo)
  1886  				}
  1887  			},
  1888  		},
  1889  		{
  1890  			configureServer: func(config *Config, called *bool) {
  1891  				config.InsecureSkipVerify = false
  1892  				config.VerifyPeerCertificate = func(rawCerts [][]byte, validatedChains [][]*x509.Certificate) error {
  1893  					return sentinelErr
  1894  				}
  1895  			},
  1896  			configureClient: func(config *Config, called *bool) {
  1897  				config.VerifyPeerCertificate = nil
  1898  			},
  1899  			validate: func(t *testing.T, testNo int, clientCalled, serverCalled bool, clientErr, serverErr error) {
  1900  				if serverErr != sentinelErr {
  1901  					t.Errorf("#%d: got server error %v, wanted sentinelErr", testNo, serverErr)
  1902  				}
  1903  			},
  1904  		},
  1905  		{
  1906  			configureServer: func(config *Config, called *bool) {
  1907  				config.InsecureSkipVerify = false
  1908  			},
  1909  			configureClient: func(config *Config, called *bool) {
  1910  				config.VerifyPeerCertificate = func(rawCerts [][]byte, validatedChains [][]*x509.Certificate) error {
  1911  					return sentinelErr
  1912  				}
  1913  			},
  1914  			validate: func(t *testing.T, testNo int, clientCalled, serverCalled bool, clientErr, serverErr error) {
  1915  				if clientErr != sentinelErr {
  1916  					t.Errorf("#%d: got client error %v, wanted sentinelErr", testNo, clientErr)
  1917  				}
  1918  			},
  1919  		},
  1920  		{
  1921  			configureServer: func(config *Config, called *bool) {
  1922  				config.InsecureSkipVerify = false
  1923  			},
  1924  			configureClient: func(config *Config, called *bool) {
  1925  				config.InsecureSkipVerify = true
  1926  				config.VerifyPeerCertificate = func(rawCerts [][]byte, validatedChains [][]*x509.Certificate) error {
  1927  					if l := len(rawCerts); l != 1 {
  1928  						return fmt.Errorf("got len(rawCerts) = %d, wanted 1", l)
  1929  					}
  1930  					// With InsecureSkipVerify set, this
  1931  					// callback should still be called but
  1932  					// validatedChains must be empty.
  1933  					if l := len(validatedChains); l != 0 {
  1934  						return fmt.Errorf("got len(validatedChains) = %d, wanted zero", l)
  1935  					}
  1936  					*called = true
  1937  					return nil
  1938  				}
  1939  			},
  1940  			validate: func(t *testing.T, testNo int, clientCalled, serverCalled bool, clientErr, serverErr error) {
  1941  				if clientErr != nil {
  1942  					t.Errorf("test[%d]: client handshake failed: %v", testNo, clientErr)
  1943  				}
  1944  				if serverErr != nil {
  1945  					t.Errorf("test[%d]: server handshake failed: %v", testNo, serverErr)
  1946  				}
  1947  				if !clientCalled {
  1948  					t.Errorf("test[%d]: client did not call callback", testNo)
  1949  				}
  1950  			},
  1951  		},
  1952  		{
  1953  			configureServer: func(config *Config, called *bool) {
  1954  				config.InsecureSkipVerify = false
  1955  				config.VerifyConnection = func(c ConnectionState) error {
  1956  					return verifyConnectionCallback(called, false, c)
  1957  				}
  1958  			},
  1959  			configureClient: func(config *Config, called *bool) {
  1960  				config.InsecureSkipVerify = false
  1961  				config.VerifyConnection = func(c ConnectionState) error {
  1962  					return verifyConnectionCallback(called, true, c)
  1963  				}
  1964  			},
  1965  			validate: func(t *testing.T, testNo int, clientCalled, serverCalled bool, clientErr, serverErr error) {
  1966  				if clientErr != nil {
  1967  					t.Errorf("test[%d]: client handshake failed: %v", testNo, clientErr)
  1968  				}
  1969  				if serverErr != nil {
  1970  					t.Errorf("test[%d]: server handshake failed: %v", testNo, serverErr)
  1971  				}
  1972  				if !clientCalled {
  1973  					t.Errorf("test[%d]: client did not call callback", testNo)
  1974  				}
  1975  				if !serverCalled {
  1976  					t.Errorf("test[%d]: server did not call callback", testNo)
  1977  				}
  1978  			},
  1979  		},
  1980  		{
  1981  			configureServer: func(config *Config, called *bool) {
  1982  				config.InsecureSkipVerify = false
  1983  				config.VerifyConnection = func(c ConnectionState) error {
  1984  					return sentinelErr
  1985  				}
  1986  			},
  1987  			configureClient: func(config *Config, called *bool) {
  1988  				config.InsecureSkipVerify = false
  1989  				config.VerifyConnection = nil
  1990  			},
  1991  			validate: func(t *testing.T, testNo int, clientCalled, serverCalled bool, clientErr, serverErr error) {
  1992  				if serverErr != sentinelErr {
  1993  					t.Errorf("#%d: got server error %v, wanted sentinelErr", testNo, serverErr)
  1994  				}
  1995  			},
  1996  		},
  1997  		{
  1998  			configureServer: func(config *Config, called *bool) {
  1999  				config.InsecureSkipVerify = false
  2000  				config.VerifyConnection = nil
  2001  			},
  2002  			configureClient: func(config *Config, called *bool) {
  2003  				config.InsecureSkipVerify = false
  2004  				config.VerifyConnection = func(c ConnectionState) error {
  2005  					return sentinelErr
  2006  				}
  2007  			},
  2008  			validate: func(t *testing.T, testNo int, clientCalled, serverCalled bool, clientErr, serverErr error) {
  2009  				if clientErr != sentinelErr {
  2010  					t.Errorf("#%d: got client error %v, wanted sentinelErr", testNo, clientErr)
  2011  				}
  2012  			},
  2013  		},
  2014  		{
  2015  			configureServer: func(config *Config, called *bool) {
  2016  				config.InsecureSkipVerify = false
  2017  				config.VerifyPeerCertificate = func(rawCerts [][]byte, validatedChains [][]*x509.Certificate) error {
  2018  					return verifyPeerCertificateCallback(called, rawCerts, validatedChains)
  2019  				}
  2020  				config.VerifyConnection = func(c ConnectionState) error {
  2021  					return sentinelErr
  2022  				}
  2023  			},
  2024  			configureClient: func(config *Config, called *bool) {
  2025  				config.InsecureSkipVerify = false
  2026  				config.VerifyPeerCertificate = nil
  2027  				config.VerifyConnection = nil
  2028  			},
  2029  			validate: func(t *testing.T, testNo int, clientCalled, serverCalled bool, clientErr, serverErr error) {
  2030  				if serverErr != sentinelErr {
  2031  					t.Errorf("#%d: got server error %v, wanted sentinelErr", testNo, serverErr)
  2032  				}
  2033  				if !serverCalled {
  2034  					t.Errorf("test[%d]: server did not call callback", testNo)
  2035  				}
  2036  			},
  2037  		},
  2038  		{
  2039  			configureServer: func(config *Config, called *bool) {
  2040  				config.InsecureSkipVerify = false
  2041  				config.VerifyPeerCertificate = nil
  2042  				config.VerifyConnection = nil
  2043  			},
  2044  			configureClient: func(config *Config, called *bool) {
  2045  				config.InsecureSkipVerify = false
  2046  				config.VerifyPeerCertificate = func(rawCerts [][]byte, validatedChains [][]*x509.Certificate) error {
  2047  					return verifyPeerCertificateCallback(called, rawCerts, validatedChains)
  2048  				}
  2049  				config.VerifyConnection = func(c ConnectionState) error {
  2050  					return sentinelErr
  2051  				}
  2052  			},
  2053  			validate: func(t *testing.T, testNo int, clientCalled, serverCalled bool, clientErr, serverErr error) {
  2054  				if clientErr != sentinelErr {
  2055  					t.Errorf("#%d: got client error %v, wanted sentinelErr", testNo, clientErr)
  2056  				}
  2057  				if !clientCalled {
  2058  					t.Errorf("test[%d]: client did not call callback", testNo)
  2059  				}
  2060  			},
  2061  		},
  2062  	}
  2063  
  2064  	for i, test := range tests {
  2065  		c, s := localPipe(t)
  2066  		done := make(chan error)
  2067  
  2068  		var clientCalled, serverCalled bool
  2069  
  2070  		go func() {
  2071  			config := testConfigServer.Clone()
  2072  			config.ClientAuth = RequireAndVerifyClientCert
  2073  			config.MaxVersion = version
  2074  			config.Certificates = []Certificate{testRSA2048Cert}
  2075  			config.Certificates[0].SignedCertificateTimestamps = [][]byte{[]byte("dummy sct 1"), []byte("dummy sct 2")}
  2076  			config.Certificates[0].OCSPStaple = []byte("dummy ocsp")
  2077  			test.configureServer(config, &serverCalled)
  2078  
  2079  			err := Server(s, config).Handshake()
  2080  			s.Close()
  2081  			done <- err
  2082  		}()
  2083  
  2084  		config := testConfigClient.Clone()
  2085  		config.Certificates = []Certificate{testClientRSA2048Cert}
  2086  		config.MaxVersion = version
  2087  		test.configureClient(config, &clientCalled)
  2088  		clientErr := Client(c, config).Handshake()
  2089  		c.Close()
  2090  		serverErr := <-done
  2091  
  2092  		test.validate(t, i, clientCalled, serverCalled, clientErr, serverErr)
  2093  	}
  2094  }
  2095  
  2096  // brokenConn wraps a net.Conn and causes all Writes after a certain number to
  2097  // fail with brokenConnErr.
  2098  type brokenConn struct {
  2099  	net.Conn
  2100  
  2101  	// breakAfter is the number of successful writes that will be allowed
  2102  	// before all subsequent writes fail.
  2103  	breakAfter int
  2104  
  2105  	// numWrites is the number of writes that have been done.
  2106  	numWrites int
  2107  }
  2108  
  2109  // brokenConnErr is the error that brokenConn returns once exhausted.
  2110  var brokenConnErr = errors.New("too many writes to brokenConn")
  2111  
  2112  func (b *brokenConn) Write(data []byte) (int, error) {
  2113  	if b.numWrites >= b.breakAfter {
  2114  		return 0, brokenConnErr
  2115  	}
  2116  
  2117  	b.numWrites++
  2118  	return b.Conn.Write(data)
  2119  }
  2120  
  2121  func TestFailedWrite(t *testing.T) {
  2122  	// Test that a write error during the handshake is returned.
  2123  	for _, breakAfter := range []int{0, 1} {
  2124  		c, s := localPipe(t)
  2125  		done := make(chan bool)
  2126  
  2127  		go func() {
  2128  			Server(s, testConfigServer.Clone()).Handshake()
  2129  			s.Close()
  2130  			done <- true
  2131  		}()
  2132  
  2133  		brokenC := &brokenConn{Conn: c, breakAfter: breakAfter}
  2134  		err := Client(brokenC, testConfigClient.Clone()).Handshake()
  2135  		if err != brokenConnErr {
  2136  			t.Errorf("#%d: expected error from brokenConn but got %q", breakAfter, err)
  2137  		}
  2138  		brokenC.Close()
  2139  
  2140  		<-done
  2141  	}
  2142  }
  2143  
  2144  // writeCountingConn wraps a net.Conn and counts the number of Write calls.
  2145  type writeCountingConn struct {
  2146  	net.Conn
  2147  
  2148  	// numWrites is the number of writes that have been done.
  2149  	numWrites int
  2150  }
  2151  
  2152  func (wcc *writeCountingConn) Write(data []byte) (int, error) {
  2153  	wcc.numWrites++
  2154  	return wcc.Conn.Write(data)
  2155  }
  2156  
  2157  func TestBuffering(t *testing.T) {
  2158  	t.Run("TLSv12", func(t *testing.T) { testBuffering(t, VersionTLS12) })
  2159  	t.Run("TLSv13", func(t *testing.T) { testBuffering(t, VersionTLS13) })
  2160  }
  2161  
  2162  func testBuffering(t *testing.T, version uint16) {
  2163  	c, s := localPipe(t)
  2164  	done := make(chan bool)
  2165  
  2166  	clientWCC := &writeCountingConn{Conn: c}
  2167  	serverWCC := &writeCountingConn{Conn: s}
  2168  
  2169  	go func() {
  2170  		config := testConfigServer.Clone()
  2171  		config.MaxVersion = version
  2172  		Server(serverWCC, config).Handshake()
  2173  		serverWCC.Close()
  2174  		done <- true
  2175  	}()
  2176  
  2177  	err := Client(clientWCC, testConfigClient.Clone()).Handshake()
  2178  	if err != nil {
  2179  		t.Fatal(err)
  2180  	}
  2181  	clientWCC.Close()
  2182  	<-done
  2183  
  2184  	var expectedClient, expectedServer int
  2185  	if version == VersionTLS13 {
  2186  		expectedClient = 2
  2187  		expectedServer = 1
  2188  	} else {
  2189  		expectedClient = 2
  2190  		expectedServer = 2
  2191  	}
  2192  
  2193  	if n := clientWCC.numWrites; n != expectedClient {
  2194  		t.Errorf("expected client handshake to complete with %d writes, but saw %d", expectedClient, n)
  2195  	}
  2196  
  2197  	if n := serverWCC.numWrites; n != expectedServer {
  2198  		t.Errorf("expected server handshake to complete with %d writes, but saw %d", expectedServer, n)
  2199  	}
  2200  }
  2201  
  2202  func TestAlertFlushing(t *testing.T) {
  2203  	c, s := localPipe(t)
  2204  	done := make(chan bool)
  2205  
  2206  	clientWCC := &writeCountingConn{Conn: c}
  2207  	serverWCC := &writeCountingConn{Conn: s}
  2208  
  2209  	serverConfig := testConfigServer.Clone()
  2210  
  2211  	// Cause a signature-time error
  2212  	brokenKey := rsa.PrivateKey{PublicKey: testRSA2048Key.PublicKey}
  2213  	brokenKey.D = big.NewInt(42)
  2214  	serverConfig.Certificates = []Certificate{{
  2215  		Certificate: testRSA2048Cert.Certificate,
  2216  		PrivateKey:  &brokenKey,
  2217  	}}
  2218  
  2219  	go func() {
  2220  		Server(serverWCC, serverConfig).Handshake()
  2221  		serverWCC.Close()
  2222  		done <- true
  2223  	}()
  2224  
  2225  	err := Client(clientWCC, testConfigClient.Clone()).Handshake()
  2226  	if err == nil {
  2227  		t.Fatal("client unexpectedly returned no error")
  2228  	}
  2229  
  2230  	const expectedError = "remote error: tls: internal error"
  2231  	if e := err.Error(); !strings.Contains(e, expectedError) {
  2232  		t.Fatalf("expected to find %q in error but error was %q", expectedError, e)
  2233  	}
  2234  	clientWCC.Close()
  2235  	<-done
  2236  
  2237  	if n := serverWCC.numWrites; n != 1 {
  2238  		t.Errorf("expected server handshake to complete with one write, but saw %d", n)
  2239  	}
  2240  }
  2241  
  2242  func TestHandshakeRace(t *testing.T) {
  2243  	if testing.Short() {
  2244  		t.Skip("skipping in -short mode")
  2245  	}
  2246  	t.Parallel()
  2247  	// This test races a Read and Write to try and complete a handshake in
  2248  	// order to provide some evidence that there are no races or deadlocks
  2249  	// in the handshake locking.
  2250  	for i := 0; i < 32; i++ {
  2251  		c, s := localPipe(t)
  2252  
  2253  		go func() {
  2254  			server := Server(s, testConfigServer.Clone())
  2255  			if err := server.Handshake(); err != nil {
  2256  				panic(err)
  2257  			}
  2258  
  2259  			var request [1]byte
  2260  			if n, err := server.Read(request[:]); err != nil || n != 1 {
  2261  				panic(err)
  2262  			}
  2263  
  2264  			server.Write(request[:])
  2265  			server.Close()
  2266  		}()
  2267  
  2268  		startWrite := make(chan struct{})
  2269  		startRead := make(chan struct{})
  2270  		readDone := make(chan struct{}, 1)
  2271  
  2272  		client := Client(c, testConfigClient.Clone())
  2273  		go func() {
  2274  			<-startWrite
  2275  			var request [1]byte
  2276  			client.Write(request[:])
  2277  		}()
  2278  
  2279  		go func() {
  2280  			<-startRead
  2281  			var reply [1]byte
  2282  			if _, err := io.ReadFull(client, reply[:]); err != nil {
  2283  				panic(err)
  2284  			}
  2285  			c.Close()
  2286  			readDone <- struct{}{}
  2287  		}()
  2288  
  2289  		if i&1 == 1 {
  2290  			startWrite <- struct{}{}
  2291  			startRead <- struct{}{}
  2292  		} else {
  2293  			startRead <- struct{}{}
  2294  			startWrite <- struct{}{}
  2295  		}
  2296  		<-readDone
  2297  	}
  2298  }
  2299  
  2300  var getClientCertificateTests = []struct {
  2301  	setup               func(*Config, *Config)
  2302  	expectedClientError string
  2303  	verify              func(*testing.T, int, *ConnectionState)
  2304  }{
  2305  	{
  2306  		func(clientConfig, serverConfig *Config) {
  2307  			// Returning a Certificate with no certificate data
  2308  			// should result in an empty message being sent to the
  2309  			// server.
  2310  			serverConfig.ClientCAs = nil
  2311  			clientConfig.GetClientCertificate = func(cri *CertificateRequestInfo) (*Certificate, error) {
  2312  				if len(cri.SignatureSchemes) == 0 {
  2313  					panic("empty SignatureSchemes")
  2314  				}
  2315  				if len(cri.AcceptableCAs) != 0 {
  2316  					panic("AcceptableCAs should have been empty")
  2317  				}
  2318  				return new(Certificate), nil
  2319  			}
  2320  		},
  2321  		"",
  2322  		func(t *testing.T, testNum int, cs *ConnectionState) {
  2323  			if l := len(cs.PeerCertificates); l != 0 {
  2324  				t.Errorf("#%d: expected no certificates but got %d", testNum, l)
  2325  			}
  2326  		},
  2327  	},
  2328  	{
  2329  		func(clientConfig, serverConfig *Config) {
  2330  			// With TLS 1.1, the SignatureSchemes should be
  2331  			// synthesised from the supported certificate types.
  2332  			clientConfig.MaxVersion = VersionTLS11
  2333  			clientConfig.GetClientCertificate = func(cri *CertificateRequestInfo) (*Certificate, error) {
  2334  				if len(cri.SignatureSchemes) == 0 {
  2335  					panic("empty SignatureSchemes")
  2336  				}
  2337  				return new(Certificate), nil
  2338  			}
  2339  		},
  2340  		"",
  2341  		func(t *testing.T, testNum int, cs *ConnectionState) {
  2342  			if l := len(cs.PeerCertificates); l != 0 {
  2343  				t.Errorf("#%d: expected no certificates but got %d", testNum, l)
  2344  			}
  2345  		},
  2346  	},
  2347  	{
  2348  		func(clientConfig, serverConfig *Config) {
  2349  			// Returning an error should abort the handshake with
  2350  			// that error.
  2351  			clientConfig.GetClientCertificate = func(cri *CertificateRequestInfo) (*Certificate, error) {
  2352  				return nil, errors.New("GetClientCertificate")
  2353  			}
  2354  		},
  2355  		"GetClientCertificate",
  2356  		func(t *testing.T, testNum int, cs *ConnectionState) {
  2357  		},
  2358  	},
  2359  	{
  2360  		func(clientConfig, serverConfig *Config) {
  2361  			clientConfig.GetClientCertificate = func(cri *CertificateRequestInfo) (*Certificate, error) {
  2362  				if len(cri.AcceptableCAs) == 0 {
  2363  					panic("empty AcceptableCAs")
  2364  				}
  2365  				cert := &testClientRSA2048Cert
  2366  				return cert, nil
  2367  			}
  2368  		},
  2369  		"",
  2370  		func(t *testing.T, testNum int, cs *ConnectionState) {
  2371  			if len(cs.VerifiedChains) == 0 {
  2372  				t.Errorf("#%d: expected some verified chains, but found none", testNum)
  2373  			}
  2374  		},
  2375  	},
  2376  }
  2377  
  2378  func TestGetClientCertificate(t *testing.T) {
  2379  	t.Run("TLSv12", func(t *testing.T) { testGetClientCertificate(t, VersionTLS12) })
  2380  	t.Run("TLSv13", func(t *testing.T) { testGetClientCertificate(t, VersionTLS13) })
  2381  }
  2382  
  2383  func testGetClientCertificate(t *testing.T, version uint16) {
  2384  	for i, test := range getClientCertificateTests {
  2385  		serverConfig := testConfigServer.Clone()
  2386  		serverConfig.Certificates = []Certificate{testRSA2048Cert}
  2387  		serverConfig.ClientAuth = VerifyClientCertIfGiven
  2388  		serverConfig.MinVersion = VersionTLS10
  2389  		serverConfig.MaxVersion = version
  2390  
  2391  		clientConfig := testConfigClient.Clone()
  2392  		clientConfig.Certificates = []Certificate{testClientRSA2048Cert}
  2393  		clientConfig.MinVersion = VersionTLS10
  2394  		clientConfig.MaxVersion = version
  2395  
  2396  		test.setup(clientConfig, serverConfig)
  2397  
  2398  		// TLS 1.1 isn't available for FIPS required
  2399  		if fips140tls.Required() && clientConfig.MaxVersion == VersionTLS11 {
  2400  			t.Logf("skipping test %d for FIPS mode", i)
  2401  			continue
  2402  		}
  2403  
  2404  		type serverResult struct {
  2405  			cs  ConnectionState
  2406  			err error
  2407  		}
  2408  
  2409  		c, s := localPipe(t)
  2410  		done := make(chan serverResult)
  2411  
  2412  		go func() {
  2413  			defer s.Close()
  2414  			server := Server(s, serverConfig)
  2415  			err := server.Handshake()
  2416  
  2417  			var cs ConnectionState
  2418  			if err == nil {
  2419  				cs = server.ConnectionState()
  2420  			}
  2421  			done <- serverResult{cs, err}
  2422  		}()
  2423  
  2424  		clientErr := Client(c, clientConfig).Handshake()
  2425  		c.Close()
  2426  
  2427  		result := <-done
  2428  
  2429  		if clientErr != nil {
  2430  			if len(test.expectedClientError) == 0 {
  2431  				t.Errorf("#%d: client error: %v", i, clientErr)
  2432  			} else if got := clientErr.Error(); got != test.expectedClientError {
  2433  				t.Errorf("#%d: expected client error %q, but got %q", i, test.expectedClientError, got)
  2434  			} else {
  2435  				test.verify(t, i, &result.cs)
  2436  			}
  2437  		} else if len(test.expectedClientError) > 0 {
  2438  			t.Errorf("#%d: expected client error %q, but got no error", i, test.expectedClientError)
  2439  		} else if err := result.err; err != nil {
  2440  			t.Errorf("#%d: server error: %v", i, err)
  2441  		} else {
  2442  			test.verify(t, i, &result.cs)
  2443  		}
  2444  	}
  2445  }
  2446  
  2447  func TestRSAPSSKeyError(t *testing.T) {
  2448  	// crypto/tls does not support the rsa_pss_pss_* SignatureSchemes. If support for
  2449  	// public keys with OID RSASSA-PSS is added to crypto/x509, they will be misused with
  2450  	// the rsa_pss_rsae_* SignatureSchemes. Assert that RSASSA-PSS certificates don't
  2451  	// parse, or that they don't carry *rsa.PublicKey keys.
  2452  	b, _ := pem.Decode([]byte(`
  2453  -----BEGIN CERTIFICATE-----
  2454  MIIDZTCCAhygAwIBAgIUCF2x0FyTgZG0CC9QTDjGWkB5vgEwPgYJKoZIhvcNAQEK
  2455  MDGgDTALBglghkgBZQMEAgGhGjAYBgkqhkiG9w0BAQgwCwYJYIZIAWUDBAIBogQC
  2456  AgDeMBIxEDAOBgNVBAMMB1JTQS1QU1MwHhcNMTgwNjI3MjI0NDM2WhcNMTgwNzI3
  2457  MjI0NDM2WjASMRAwDgYDVQQDDAdSU0EtUFNTMIIBIDALBgkqhkiG9w0BAQoDggEP
  2458  ADCCAQoCggEBANxDm0f76JdI06YzsjB3AmmjIYkwUEGxePlafmIASFjDZl/elD0Z
  2459  /a7xLX468b0qGxLS5al7XCcEprSdsDR6DF5L520+pCbpfLyPOjuOvGmk9KzVX4x5
  2460  b05YXYuXdsQ0Kjxcx2i3jjCday6scIhMJVgBZxTEyMj1thPQM14SHzKCd/m6HmCL
  2461  QmswpH2yMAAcBRWzRpp/vdH5DeOJEB3aelq7094no731mrLUCHRiZ1htq8BDB3ou
  2462  czwqgwspbqZ4dnMXl2MvfySQ5wJUxQwILbiuAKO2lVVPUbFXHE9pgtznNoPvKwQT
  2463  JNcX8ee8WIZc2SEGzofjk3NpjR+2ADB2u3sCAwEAAaNTMFEwHQYDVR0OBBYEFNEz
  2464  AdyJ2f+fU+vSCS6QzohnOnprMB8GA1UdIwQYMBaAFNEzAdyJ2f+fU+vSCS6Qzohn
  2465  OnprMA8GA1UdEwEB/wQFMAMBAf8wPgYJKoZIhvcNAQEKMDGgDTALBglghkgBZQME
  2466  AgGhGjAYBgkqhkiG9w0BAQgwCwYJYIZIAWUDBAIBogQCAgDeA4IBAQCjEdrR5aab
  2467  sZmCwrMeKidXgfkmWvfuLDE+TCbaqDZp7BMWcMQXT9O0UoUT5kqgKj2ARm2pEW0Z
  2468  H3Z1vj3bbds72qcDIJXp+l0fekyLGeCrX/CbgnMZXEP7+/+P416p34ChR1Wz4dU1
  2469  KD3gdsUuTKKeMUog3plxlxQDhRQmiL25ygH1LmjLd6dtIt0GVRGr8lj3euVeprqZ
  2470  bZ3Uq5eLfsn8oPgfC57gpO6yiN+UURRTlK3bgYvLh4VWB3XXk9UaQZ7Mq1tpXjoD
  2471  HYFybkWzibkZp4WRo+Fa28rirH+/wHt0vfeN7UCceURZEx4JaxIIfe4ku7uDRhJi
  2472  RwBA9Xk1KBNF
  2473  -----END CERTIFICATE-----`))
  2474  	if b == nil {
  2475  		t.Fatal("Failed to decode certificate")
  2476  	}
  2477  	cert, err := x509.ParseCertificate(b.Bytes)
  2478  	if err != nil {
  2479  		return
  2480  	}
  2481  	if _, ok := cert.PublicKey.(*rsa.PublicKey); ok {
  2482  		t.Error("A RSASSA-PSS certificate was parsed like a PKCS#1 v1.5 one, and it will be mistakenly used with rsa_pss_rsae_* signature algorithms")
  2483  	}
  2484  }
  2485  
  2486  func TestCloseClientConnectionOnIdleServer(t *testing.T) {
  2487  	clientConn, serverConn := localPipe(t)
  2488  	client := Client(clientConn, testConfigClient.Clone())
  2489  	go func() {
  2490  		var b [1]byte
  2491  		serverConn.Read(b[:])
  2492  		client.Close()
  2493  	}()
  2494  	client.SetWriteDeadline(time.Now().Add(time.Minute))
  2495  	err := client.Handshake()
  2496  	if err != nil {
  2497  		if err, ok := err.(net.Error); ok && err.Timeout() {
  2498  			t.Errorf("Expected a closed network connection error but got '%s'", err.Error())
  2499  		}
  2500  	} else {
  2501  		t.Errorf("Error expected, but no error returned")
  2502  	}
  2503  }
  2504  
  2505  func testDowngradeCanary(t *testing.T, clientVersion, serverVersion uint16) error {
  2506  	defer func() { testingOnlyForceDowngradeCanary = false }()
  2507  	testingOnlyForceDowngradeCanary = true
  2508  
  2509  	clientConfig := testConfigClient.Clone()
  2510  	clientConfig.MinVersion = VersionTLS10
  2511  	clientConfig.MaxVersion = clientVersion
  2512  	serverConfig := testConfigServer.Clone()
  2513  	serverConfig.MinVersion = VersionTLS10
  2514  	serverConfig.MaxVersion = serverVersion
  2515  	_, _, err := testHandshake(t, clientConfig, serverConfig)
  2516  	return err
  2517  }
  2518  
  2519  func TestDowngradeCanary(t *testing.T) {
  2520  	if err := testDowngradeCanary(t, VersionTLS13, VersionTLS12); err == nil {
  2521  		t.Errorf("downgrade from TLS 1.3 to TLS 1.2 was not detected")
  2522  	}
  2523  	if testing.Short() {
  2524  		t.Skip("skipping the rest of the checks in short mode")
  2525  	}
  2526  	if err := testDowngradeCanary(t, VersionTLS13, VersionTLS11); err == nil {
  2527  		t.Errorf("downgrade from TLS 1.3 to TLS 1.1 was not detected")
  2528  	}
  2529  	if err := testDowngradeCanary(t, VersionTLS13, VersionTLS10); err == nil {
  2530  		t.Errorf("downgrade from TLS 1.3 to TLS 1.0 was not detected")
  2531  	}
  2532  	if err := testDowngradeCanary(t, VersionTLS12, VersionTLS11); err == nil {
  2533  		t.Errorf("downgrade from TLS 1.2 to TLS 1.1 was not detected")
  2534  	}
  2535  	if err := testDowngradeCanary(t, VersionTLS12, VersionTLS10); err == nil {
  2536  		t.Errorf("downgrade from TLS 1.2 to TLS 1.0 was not detected")
  2537  	}
  2538  	if err := testDowngradeCanary(t, VersionTLS13, VersionTLS13); err != nil {
  2539  		t.Errorf("server unexpectedly sent downgrade canary for TLS 1.3")
  2540  	}
  2541  	if err := testDowngradeCanary(t, VersionTLS12, VersionTLS12); err != nil {
  2542  		t.Errorf("client didn't ignore expected TLS 1.2 canary")
  2543  	}
  2544  	if !fips140tls.Required() {
  2545  		if err := testDowngradeCanary(t, VersionTLS11, VersionTLS11); err != nil {
  2546  			t.Errorf("client unexpectedly reacted to a canary in TLS 1.1")
  2547  		}
  2548  		if err := testDowngradeCanary(t, VersionTLS10, VersionTLS10); err != nil {
  2549  			t.Errorf("client unexpectedly reacted to a canary in TLS 1.0")
  2550  		}
  2551  	} else {
  2552  		t.Logf("skipping TLS 1.1 and TLS 1.0 downgrade canary checks in FIPS mode")
  2553  	}
  2554  }
  2555  
  2556  func TestResumptionKeepsOCSPAndSCT(t *testing.T) {
  2557  	t.Run("TLSv12", func(t *testing.T) { testResumptionKeepsOCSPAndSCT(t, VersionTLS12) })
  2558  	t.Run("TLSv13", func(t *testing.T) { testResumptionKeepsOCSPAndSCT(t, VersionTLS13) })
  2559  }
  2560  
  2561  func testResumptionKeepsOCSPAndSCT(t *testing.T, ver uint16) {
  2562  	clientConfig := &Config{
  2563  		MaxVersion:         ver,
  2564  		ClientSessionCache: NewLRUClientSessionCache(32),
  2565  		ServerName:         "test.golang.example",
  2566  		RootCAs:            testRootCertPool,
  2567  		Time:               testTime,
  2568  	}
  2569  	serverConfig := testConfigServer.Clone()
  2570  	serverConfig.Certificates = []Certificate{testRSA2048Cert}
  2571  	serverConfig.MaxVersion = ver
  2572  	serverConfig.Certificates[0].OCSPStaple = []byte{1, 2, 3}
  2573  	serverConfig.Certificates[0].SignedCertificateTimestamps = [][]byte{{4, 5, 6}}
  2574  
  2575  	_, ccs, err := testHandshake(t, clientConfig, serverConfig)
  2576  	if err != nil {
  2577  		t.Fatalf("handshake failed: %s", err)
  2578  	}
  2579  	// after a new session we expect to see OCSPResponse and
  2580  	// SignedCertificateTimestamps populated as usual
  2581  	if !bytes.Equal(ccs.OCSPResponse, serverConfig.Certificates[0].OCSPStaple) {
  2582  		t.Errorf("client ConnectionState contained unexpected OCSPResponse: wanted %v, got %v",
  2583  			serverConfig.Certificates[0].OCSPStaple, ccs.OCSPResponse)
  2584  	}
  2585  	if !reflect.DeepEqual(ccs.SignedCertificateTimestamps, serverConfig.Certificates[0].SignedCertificateTimestamps) {
  2586  		t.Errorf("client ConnectionState contained unexpected SignedCertificateTimestamps: wanted %v, got %v",
  2587  			serverConfig.Certificates[0].SignedCertificateTimestamps, ccs.SignedCertificateTimestamps)
  2588  	}
  2589  
  2590  	// if the server doesn't send any SCTs, repopulate the old SCTs
  2591  	oldSCTs := serverConfig.Certificates[0].SignedCertificateTimestamps
  2592  	serverConfig.Certificates[0].SignedCertificateTimestamps = nil
  2593  	_, ccs, err = testHandshake(t, clientConfig, serverConfig)
  2594  	if err != nil {
  2595  		t.Fatalf("handshake failed: %s", err)
  2596  	}
  2597  	if !ccs.DidResume {
  2598  		t.Fatalf("expected session to be resumed")
  2599  	}
  2600  	// after a resumed session we also expect to see OCSPResponse
  2601  	// and SignedCertificateTimestamps populated
  2602  	if !bytes.Equal(ccs.OCSPResponse, serverConfig.Certificates[0].OCSPStaple) {
  2603  		t.Errorf("client ConnectionState contained unexpected OCSPResponse after resumption: wanted %v, got %v",
  2604  			serverConfig.Certificates[0].OCSPStaple, ccs.OCSPResponse)
  2605  	}
  2606  	if !reflect.DeepEqual(ccs.SignedCertificateTimestamps, oldSCTs) {
  2607  		t.Errorf("client ConnectionState contained unexpected SignedCertificateTimestamps after resumption: wanted %v, got %v",
  2608  			oldSCTs, ccs.SignedCertificateTimestamps)
  2609  	}
  2610  
  2611  	//  Only test overriding the SCTs for TLS 1.2, since in 1.3
  2612  	// the server won't send the message containing them
  2613  	if ver == VersionTLS13 {
  2614  		return
  2615  	}
  2616  
  2617  	// if the server changes the SCTs it sends, they should override the saved SCTs
  2618  	serverConfig.Certificates[0].SignedCertificateTimestamps = [][]byte{{7, 8, 9}}
  2619  	_, ccs, err = testHandshake(t, clientConfig, serverConfig)
  2620  	if err != nil {
  2621  		t.Fatalf("handshake failed: %s", err)
  2622  	}
  2623  	if !ccs.DidResume {
  2624  		t.Fatalf("expected session to be resumed")
  2625  	}
  2626  	if !reflect.DeepEqual(ccs.SignedCertificateTimestamps, serverConfig.Certificates[0].SignedCertificateTimestamps) {
  2627  		t.Errorf("client ConnectionState contained unexpected SignedCertificateTimestamps after resumption: wanted %v, got %v",
  2628  			serverConfig.Certificates[0].SignedCertificateTimestamps, ccs.SignedCertificateTimestamps)
  2629  	}
  2630  }
  2631  
  2632  // TestClientHandshakeContextCancellation tests that canceling
  2633  // the context given to the client side conn.HandshakeContext
  2634  // interrupts the in-progress handshake.
  2635  func TestClientHandshakeContextCancellation(t *testing.T) {
  2636  	c, s := localPipe(t)
  2637  	ctx, cancel := context.WithCancel(context.Background())
  2638  	unblockServer := make(chan struct{})
  2639  	defer close(unblockServer)
  2640  	go func() {
  2641  		cancel()
  2642  		<-unblockServer
  2643  		_ = s.Close()
  2644  	}()
  2645  	cli := Client(c, testConfigClient.Clone())
  2646  	// Initiates client side handshake, which will block until the client hello is read
  2647  	// by the server, unless the cancellation works.
  2648  	err := cli.HandshakeContext(ctx)
  2649  	if err == nil {
  2650  		t.Fatal("Client handshake did not error when the context was canceled")
  2651  	}
  2652  	if err != context.Canceled {
  2653  		t.Errorf("Unexpected client handshake error: %v", err)
  2654  	}
  2655  	if runtime.GOOS == "js" || runtime.GOOS == "wasip1" {
  2656  		t.Skip("conn.Close does not error as expected when called multiple times on GOOS=js or GOOS=wasip1")
  2657  	}
  2658  	err = cli.Close()
  2659  	if err == nil {
  2660  		t.Error("Client connection was not closed when the context was canceled")
  2661  	}
  2662  }
  2663  
  2664  // TestTLS13OnlyClientHelloCipherSuite tests that when a client states that
  2665  // it only supports TLS 1.3, it correctly advertises only TLS 1.3 ciphers.
  2666  func TestTLS13OnlyClientHelloCipherSuite(t *testing.T) {
  2667  	tls13Tests := []struct {
  2668  		name    string
  2669  		ciphers []uint16
  2670  	}{
  2671  		{
  2672  			name:    "nil",
  2673  			ciphers: nil,
  2674  		},
  2675  		{
  2676  			name:    "empty",
  2677  			ciphers: []uint16{},
  2678  		},
  2679  		{
  2680  			name:    "some TLS 1.2 cipher",
  2681  			ciphers: []uint16{TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256},
  2682  		},
  2683  		{
  2684  			name:    "some TLS 1.3 cipher",
  2685  			ciphers: []uint16{TLS_AES_128_GCM_SHA256},
  2686  		},
  2687  		{
  2688  			name:    "some TLS 1.2 and 1.3 ciphers",
  2689  			ciphers: []uint16{TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384, TLS_AES_256_GCM_SHA384},
  2690  		},
  2691  	}
  2692  	for _, tt := range tls13Tests {
  2693  		t.Run(tt.name, func(t *testing.T) {
  2694  			t.Parallel()
  2695  			testTLS13OnlyClientHelloCipherSuite(t, tt.ciphers)
  2696  		})
  2697  	}
  2698  }
  2699  
  2700  func testTLS13OnlyClientHelloCipherSuite(t *testing.T, ciphers []uint16) {
  2701  	serverConfig := &Config{
  2702  		Certificates: testConfigServer.Certificates,
  2703  		GetConfigForClient: func(chi *ClientHelloInfo) (*Config, error) {
  2704  			expectedCiphersuites := defaultCipherSuitesTLS13NoAES
  2705  			if fips140tls.Required() {
  2706  				expectedCiphersuites = allowedCipherSuitesTLS13FIPS
  2707  			}
  2708  			if len(chi.CipherSuites) != len(expectedCiphersuites) {
  2709  				t.Errorf("only TLS 1.3 suites should be advertised, got=%x", chi.CipherSuites)
  2710  			} else {
  2711  				for i := range expectedCiphersuites {
  2712  					if want, got := expectedCiphersuites[i], chi.CipherSuites[i]; want != got {
  2713  						t.Errorf("cipher at index %d does not match, want=%x, got=%x", i, want, got)
  2714  					}
  2715  				}
  2716  			}
  2717  			return nil, nil
  2718  		},
  2719  	}
  2720  	clientConfig := &Config{
  2721  		MinVersion:         VersionTLS13, // client only supports TLS 1.3
  2722  		CipherSuites:       ciphers,
  2723  		InsecureSkipVerify: true,
  2724  	}
  2725  	if _, _, err := testHandshake(t, clientConfig, serverConfig); err != nil {
  2726  		t.Fatalf("handshake failed: %s", err)
  2727  	}
  2728  }
  2729  
  2730  // discardConn wraps a net.Conn but discards all writes, but reports that they happened.
  2731  type discardConn struct {
  2732  	net.Conn
  2733  }
  2734  
  2735  func (dc *discardConn) Write(data []byte) (int, error) {
  2736  	return len(data), nil
  2737  }
  2738  
  2739  func TestHandshakeRSATooBig(t *testing.T) {
  2740  	// largeRSAKeyCertPEM contains a 8193 bit RSA key
  2741  	const largeRSAKeyCertPEM = `-----BEGIN CERTIFICATE-----
  2742  MIIInjCCBIWgAwIBAgIBAjANBgkqhkiG9w0BAQsFADASMRAwDgYDVQQDEwd0ZXN0
  2743  aW5nMB4XDTIzMDYwNzIxMjMzNloXDTIzMDYwNzIzMjMzNlowEjEQMA4GA1UEAxMH
  2744  dGVzdGluZzCCBCIwDQYJKoZIhvcNAQEBBQADggQPADCCBAoCggQBAWdHsf6Rh2Ca
  2745  n2SQwn4t4OQrOjbLLdGE1pM6TBKKrHUFy62uEL8atNjlcfXIsa4aEu3xNGiqxqur
  2746  ZectlkZbm0FkaaQ1Wr9oikDY3KfjuaXdPdO/XC/h8AKNxlDOylyXwUSK/CuYb+1j
  2747  gy8yF5QFvVfwW/xwTlHmhUeSkVSQPosfQ6yXNNsmMzkd+ZPWLrfq4R+wiNtwYGu0
  2748  WSBcI/M9o8/vrNLnIppoiBJJ13j9CR1ToEAzOFh9wwRWLY10oZhoh1ONN1KQURx4
  2749  qedzvvP2DSjZbUccdvl2rBGvZpzfOiFdm1FCnxB0c72Cqx+GTHXBFf8bsa7KHky9
  2750  sNO1GUanbq17WoDNgwbY6H51bfShqv0CErxatwWox3we4EcAmFHPVTCYL1oWVMGo
  2751  a3Eth91NZj+b/nGhF9lhHKGzXSv9brmLLkfvM1jA6XhNhA7BQ5Vz67lj2j3XfXdh
  2752  t/BU5pBXbL4Ut4mIhT1YnKXAjX2/LF5RHQTE8Vwkx5JAEKZyUEGOReD/B+7GOrLp
  2753  HduMT9vZAc5aR2k9I8qq1zBAzsL69lyQNAPaDYd1BIAjUety9gAYaSQffCgAgpRO
  2754  Gt+DYvxS+7AT/yEd5h74MU2AH7KrAkbXOtlwupiGwhMVTstncDJWXMJqbBhyHPF8
  2755  3UmZH0hbL4PYmzSj9LDWQQXI2tv6vrCpfts3Cqhqxz9vRpgY7t1Wu6l/r+KxYYz3
  2756  1pcGpPvRmPh0DJm7cPTiXqPnZcPt+ulSaSdlxmd19OnvG5awp0fXhxryZVwuiT8G
  2757  VDkhyARrxYrdjlINsZJZbQjO0t8ketXAELJOnbFXXzeCOosyOHkLwsqOO96AVJA8
  2758  45ZVL5m95ClGy0RSrjVIkXsxTAMVG6SPAqKwk6vmTdRGuSPS4rhgckPVDHmccmuq
  2759  dfnT2YkX+wB2/M3oCgU+s30fAHGkbGZ0pCdNbFYFZLiH0iiMbTDl/0L/z7IdK0nH
  2760  GLHVE7apPraKC6xl6rPWsD2iSfrmtIPQa0+rqbIVvKP5JdfJ8J4alI+OxFw/znQe
  2761  V0/Rez0j22Fe119LZFFSXhRv+ZSvcq20xDwh00mzcumPWpYuCVPozA18yIhC9tNn
  2762  ALHndz0tDseIdy9vC71jQWy9iwri3ueN0DekMMF8JGzI1Z6BAFzgyAx3DkHtwHg7
  2763  B7qD0jPG5hJ5+yt323fYgJsuEAYoZ8/jzZ01pkX8bt+UsVN0DGnSGsI2ktnIIk3J
  2764  l+8krjmUy6EaW79nITwoOqaeHOIp8m3UkjEcoKOYrzHRKqRy+A09rY+m/cAQaafW
  2765  4xp0Zv7qZPLwnu0jsqB4jD8Ll9yPB02ndsoV6U5PeHzTkVhPml19jKUAwFfs7TJg
  2766  kXy+/xFhYVUCAwEAATANBgkqhkiG9w0BAQsFAAOCBAIAAQnZY77pMNeypfpba2WK
  2767  aDasT7dk2JqP0eukJCVPTN24Zca+xJNPdzuBATm/8SdZK9lddIbjSnWRsKvTnO2r
  2768  /rYdlPf3jM5uuJtb8+Uwwe1s+gszelGS9G/lzzq+ehWicRIq2PFcs8o3iQMfENiv
  2769  qILJ+xjcrvms5ZPDNahWkfRx3KCg8Q+/at2n5p7XYjMPYiLKHnDC+RE2b1qT20IZ
  2770  FhuK/fTWLmKbfYFNNga6GC4qcaZJ7x0pbm4SDTYp0tkhzcHzwKhidfNB5J2vNz6l
  2771  Ur6wiYwamFTLqcOwWo7rdvI+sSn05WQBv0QZlzFX+OAu0l7WQ7yU+noOxBhjvHds
  2772  14+r9qcQZg2q9kG+evopYZqYXRUNNlZKo9MRBXhfrISulFAc5lRFQIXMXnglvAu+
  2773  Ipz2gomEAOcOPNNVldhKAU94GAMJd/KfN0ZP7gX3YvPzuYU6XDhag5RTohXLm18w
  2774  5AF+ES3DOQ6ixu3DTf0D+6qrDuK+prdX8ivcdTQVNOQ+MIZeGSc6NWWOTaMGJ3lg
  2775  aZIxJUGdo6E7GBGiC1YTjgFKFbHzek1LRTh/LX3vbSudxwaG0HQxwsU9T4DWiMqa
  2776  Fkf2KteLEUA6HrR+0XlAZrhwoqAmrJ+8lCFX3V0gE9lpENfVHlFXDGyx10DpTB28
  2777  DdjnY3F7EPWNzwf9P3oNT69CKW3Bk6VVr3ROOJtDxVu1ioWo3TaXltQ0VOnap2Pu
  2778  sa5wfrpfwBDuAS9JCDg4ttNp2nW3F7tgXC6xPqw5pvGwUppEw9XNrqV8TZrxduuv
  2779  rQ3NyZ7KSzIpmFlD3UwV/fGfz3UQmHS6Ng1evrUID9DjfYNfRqSGIGjDfxGtYD+j
  2780  Z1gLJZuhjJpNtwBkKRtlNtrCWCJK2hidK/foxwD7kwAPo2I9FjpltxCRywZUs07X
  2781  KwXTfBR9v6ij1LV6K58hFS+8ezZyZ05CeVBFkMQdclTOSfuPxlMkQOtjp8QWDj+F
  2782  j/MYziT5KBkHvcbrjdRtUJIAi4N7zCsPZtjik918AK1WBNRVqPbrgq/XSEXMfuvs
  2783  6JbfK0B76vdBDRtJFC1JsvnIrGbUztxXzyQwFLaR/AjVJqpVlysLWzPKWVX6/+SJ
  2784  u1NQOl2E8P6ycyBsuGnO89p0S4F8cMRcI2X1XQsZ7/q0NBrOMaEp5T3SrWo9GiQ3
  2785  o2SBdbs3Y6MBPBtTu977Z/0RO63J3M5i2tjUiDfrFy7+VRLKr7qQ7JibohyB8QaR
  2786  9tedgjn2f+of7PnP/PEl1cCphUZeHM7QKUMPT8dbqwmKtlYY43EHXcvNOT5IBk3X
  2787  9lwJoZk/B2i+ZMRNSP34ztAwtxmasPt6RAWGQpWCn9qmttAHAnMfDqe7F7jVR6rS
  2788  u58=
  2789  -----END CERTIFICATE-----`
  2790  
  2791  	testCert, _ := pem.Decode([]byte(largeRSAKeyCertPEM))
  2792  
  2793  	c := &Conn{conn: &discardConn{}, config: testConfigClient.Clone()}
  2794  
  2795  	expectedErr := "tls: server sent certificate containing RSA key larger than 8192 bits"
  2796  	err := c.verifyServerCertificate([][]byte{testCert.Bytes})
  2797  	if err == nil || err.Error() != expectedErr {
  2798  		t.Errorf("Conn.verifyServerCertificate unexpected error: want %q, got %q", expectedErr, err)
  2799  	}
  2800  
  2801  	expectedErr = "tls: client sent certificate containing RSA key larger than 8192 bits"
  2802  	err = c.processCertsFromClient(Certificate{Certificate: [][]byte{testCert.Bytes}})
  2803  	if err == nil || err.Error() != expectedErr {
  2804  		t.Errorf("Conn.processCertsFromClient unexpected error: want %q, got %q", expectedErr, err)
  2805  	}
  2806  }
  2807  
  2808  func TestTLS13ECHRejectionCallbacks(t *testing.T) {
  2809  	k, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
  2810  	if err != nil {
  2811  		t.Fatal(err)
  2812  	}
  2813  	tmpl := &x509.Certificate{
  2814  		SerialNumber: big.NewInt(1),
  2815  		Subject:      pkix.Name{CommonName: "test"},
  2816  		DNSNames:     []string{"example.golang"},
  2817  		NotBefore:    testConfigServer.Time().Add(-time.Hour),
  2818  		NotAfter:     testConfigServer.Time().Add(time.Hour),
  2819  	}
  2820  	certDER, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, k.Public(), k)
  2821  	if err != nil {
  2822  		t.Fatal(err)
  2823  	}
  2824  	cert, err := x509.ParseCertificate(certDER)
  2825  	if err != nil {
  2826  		t.Fatal(err)
  2827  	}
  2828  
  2829  	clientConfig, serverConfig := testConfigClient.Clone(), testConfigServer.Clone()
  2830  	serverConfig.Certificates = []Certificate{
  2831  		{
  2832  			Certificate: [][]byte{certDER},
  2833  			PrivateKey:  k,
  2834  		},
  2835  	}
  2836  	serverConfig.MinVersion = VersionTLS13
  2837  	clientConfig.RootCAs = x509.NewCertPool()
  2838  	clientConfig.RootCAs.AddCert(cert)
  2839  	clientConfig.MinVersion = VersionTLS13
  2840  	clientConfig.EncryptedClientHelloConfigList, _ = hex.DecodeString("0041fe0d003d0100200020204bed0a11fc0dde595a9b78d966b0011128eb83f65d3c91c1cc5ac786cd246f000400010001ff0e6578616d706c652e676f6c616e670000")
  2841  	clientConfig.ServerName = "example.golang"
  2842  
  2843  	for _, tc := range []struct {
  2844  		name        string
  2845  		expectedErr string
  2846  
  2847  		verifyConnection                    func(ConnectionState) error
  2848  		verifyPeerCertificate               func([][]byte, [][]*x509.Certificate) error
  2849  		encryptedClientHelloRejectionVerify func(ConnectionState) error
  2850  	}{
  2851  		{
  2852  			name:        "no callbacks",
  2853  			expectedErr: "tls: server rejected ECH",
  2854  		},
  2855  		{
  2856  			name: "EncryptedClientHelloRejectionVerify, no err",
  2857  			encryptedClientHelloRejectionVerify: func(ConnectionState) error {
  2858  				return nil
  2859  			},
  2860  			expectedErr: "tls: server rejected ECH",
  2861  		},
  2862  		{
  2863  			name: "EncryptedClientHelloRejectionVerify, err",
  2864  			encryptedClientHelloRejectionVerify: func(ConnectionState) error {
  2865  				return errors.New("callback err")
  2866  			},
  2867  			// testHandshake returns the server side error, so we just need to
  2868  			// check alertBadCertificate was sent
  2869  			expectedErr: "callback err",
  2870  		},
  2871  		{
  2872  			name: "VerifyConnection, err",
  2873  			verifyConnection: func(ConnectionState) error {
  2874  				return errors.New("callback err")
  2875  			},
  2876  			expectedErr: "tls: server rejected ECH",
  2877  		},
  2878  		{
  2879  			name: "VerifyPeerCertificate, err",
  2880  			verifyPeerCertificate: func([][]byte, [][]*x509.Certificate) error {
  2881  				return errors.New("callback err")
  2882  			},
  2883  			expectedErr: "tls: server rejected ECH",
  2884  		},
  2885  	} {
  2886  		t.Run(tc.name, func(t *testing.T) {
  2887  			c, s := localPipe(t)
  2888  			done := make(chan error)
  2889  
  2890  			go func() {
  2891  				serverErr := Server(s, serverConfig).Handshake()
  2892  				s.Close()
  2893  				done <- serverErr
  2894  			}()
  2895  
  2896  			cConfig := clientConfig.Clone()
  2897  			cConfig.VerifyConnection = tc.verifyConnection
  2898  			cConfig.VerifyPeerCertificate = tc.verifyPeerCertificate
  2899  			cConfig.EncryptedClientHelloRejectionVerify = tc.encryptedClientHelloRejectionVerify
  2900  
  2901  			clientErr := Client(c, cConfig).Handshake()
  2902  			c.Close()
  2903  
  2904  			if tc.expectedErr == "" && clientErr != nil {
  2905  				t.Fatalf("unexpected err: %s", clientErr)
  2906  			} else if clientErr != nil && tc.expectedErr != clientErr.Error() {
  2907  				t.Fatalf("unexpected err: got %q, want %q", clientErr, tc.expectedErr)
  2908  			}
  2909  		})
  2910  	}
  2911  }
  2912  
  2913  func TestECHTLS12Server(t *testing.T) {
  2914  	clientConfig, serverConfig := testConfigClient.Clone(), testConfigServer.Clone()
  2915  
  2916  	serverConfig.MaxVersion = VersionTLS12
  2917  	clientConfig.MinVersion = 0
  2918  
  2919  	clientConfig.EncryptedClientHelloConfigList, _ = hex.DecodeString("0041fe0d003d0100200020204bed0a11fc0dde595a9b78d966b0011128eb83f65d3c91c1cc5ac786cd246f000400010001ff0e6578616d706c652e676f6c616e670000")
  2920  
  2921  	expectedErr := "server: tls: client offered only unsupported versions: [304]\nclient: remote error: tls: protocol version not supported"
  2922  	_, _, err := testHandshake(t, clientConfig, serverConfig)
  2923  	if err == nil || err.Error() != expectedErr {
  2924  		t.Fatalf("unexpected handshake error: got %q, want %q", err, expectedErr)
  2925  	}
  2926  }
  2927  

View as plain text