github.com/c12o16h1/go/src@v0.0.0-20200114212001-5a151c0f00ed/crypto/tls/handshake_client_test.go (about)

     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  	"crypto/rsa"
    10  	"crypto/x509"
    11  	"encoding/base64"
    12  	"encoding/binary"
    13  	"encoding/pem"
    14  	"errors"
    15  	"fmt"
    16  	"io"
    17  	"math/big"
    18  	"net"
    19  	"os"
    20  	"os/exec"
    21  	"path/filepath"
    22  	"strconv"
    23  	"strings"
    24  	"testing"
    25  	"time"
    26  )
    27  
    28  // Note: see comment in handshake_test.go for details of how the reference
    29  // tests work.
    30  
    31  // opensslInputEvent enumerates possible inputs that can be sent to an `openssl
    32  // s_client` process.
    33  type opensslInputEvent int
    34  
    35  const (
    36  	// opensslRenegotiate causes OpenSSL to request a renegotiation of the
    37  	// connection.
    38  	opensslRenegotiate opensslInputEvent = iota
    39  
    40  	// opensslSendBanner causes OpenSSL to send the contents of
    41  	// opensslSentinel on the connection.
    42  	opensslSendSentinel
    43  
    44  	// opensslKeyUpdate causes OpenSSL to send send a key update message to the
    45  	// client and request one back.
    46  	opensslKeyUpdate
    47  )
    48  
    49  const opensslSentinel = "SENTINEL\n"
    50  
    51  type opensslInput chan opensslInputEvent
    52  
    53  func (i opensslInput) Read(buf []byte) (n int, err error) {
    54  	for event := range i {
    55  		switch event {
    56  		case opensslRenegotiate:
    57  			return copy(buf, []byte("R\n")), nil
    58  		case opensslKeyUpdate:
    59  			return copy(buf, []byte("K\n")), nil
    60  		case opensslSendSentinel:
    61  			return copy(buf, []byte(opensslSentinel)), nil
    62  		default:
    63  			panic("unknown event")
    64  		}
    65  	}
    66  
    67  	return 0, io.EOF
    68  }
    69  
    70  // opensslOutputSink is an io.Writer that receives the stdout and stderr from an
    71  // `openssl` process and sends a value to handshakeComplete or readKeyUpdate
    72  // when certain messages are seen.
    73  type opensslOutputSink struct {
    74  	handshakeComplete chan struct{}
    75  	readKeyUpdate     chan struct{}
    76  	all               []byte
    77  	line              []byte
    78  }
    79  
    80  func newOpensslOutputSink() *opensslOutputSink {
    81  	return &opensslOutputSink{make(chan struct{}), make(chan struct{}), nil, nil}
    82  }
    83  
    84  // opensslEndOfHandshake is a message that the “openssl s_server” tool will
    85  // print when a handshake completes if run with “-state”.
    86  const opensslEndOfHandshake = "SSL_accept:SSLv3/TLS write finished"
    87  
    88  // opensslReadKeyUpdate is a message that the “openssl s_server” tool will
    89  // print when a KeyUpdate message is received if run with “-state”.
    90  const opensslReadKeyUpdate = "SSL_accept:TLSv1.3 read client key update"
    91  
    92  func (o *opensslOutputSink) Write(data []byte) (n int, err error) {
    93  	o.line = append(o.line, data...)
    94  	o.all = append(o.all, data...)
    95  
    96  	for {
    97  		i := bytes.IndexByte(o.line, '\n')
    98  		if i < 0 {
    99  			break
   100  		}
   101  
   102  		if bytes.Equal([]byte(opensslEndOfHandshake), o.line[:i]) {
   103  			o.handshakeComplete <- struct{}{}
   104  		}
   105  		if bytes.Equal([]byte(opensslReadKeyUpdate), o.line[:i]) {
   106  			o.readKeyUpdate <- struct{}{}
   107  		}
   108  		o.line = o.line[i+1:]
   109  	}
   110  
   111  	return len(data), nil
   112  }
   113  
   114  func (o *opensslOutputSink) String() string {
   115  	return string(o.all)
   116  }
   117  
   118  // clientTest represents a test of the TLS client handshake against a reference
   119  // implementation.
   120  type clientTest struct {
   121  	// name is a freeform string identifying the test and the file in which
   122  	// the expected results will be stored.
   123  	name string
   124  	// args, if not empty, contains a series of arguments for the
   125  	// command to run for the reference server.
   126  	args []string
   127  	// config, if not nil, contains a custom Config to use for this test.
   128  	config *Config
   129  	// cert, if not empty, contains a DER-encoded certificate for the
   130  	// reference server.
   131  	cert []byte
   132  	// key, if not nil, contains either a *rsa.PrivateKey, ed25519.PrivateKey or
   133  	// *ecdsa.PrivateKey which is the private key for the reference server.
   134  	key interface{}
   135  	// extensions, if not nil, contains a list of extension data to be returned
   136  	// from the ServerHello. The data should be in standard TLS format with
   137  	// a 2-byte uint16 type, 2-byte data length, followed by the extension data.
   138  	extensions [][]byte
   139  	// validate, if not nil, is a function that will be called with the
   140  	// ConnectionState of the resulting connection. It returns a non-nil
   141  	// error if the ConnectionState is unacceptable.
   142  	validate func(ConnectionState) error
   143  	// numRenegotiations is the number of times that the connection will be
   144  	// renegotiated.
   145  	numRenegotiations int
   146  	// renegotiationExpectedToFail, if not zero, is the number of the
   147  	// renegotiation attempt that is expected to fail.
   148  	renegotiationExpectedToFail int
   149  	// checkRenegotiationError, if not nil, is called with any error
   150  	// arising from renegotiation. It can map expected errors to nil to
   151  	// ignore them.
   152  	checkRenegotiationError func(renegotiationNum int, err error) error
   153  	// sendKeyUpdate will cause the server to send a KeyUpdate message.
   154  	sendKeyUpdate bool
   155  }
   156  
   157  var serverCommand = []string{"openssl", "s_server", "-no_ticket", "-num_tickets", "0"}
   158  
   159  // connFromCommand starts the reference server process, connects to it and
   160  // returns a recordingConn for the connection. The stdin return value is an
   161  // opensslInput for the stdin of the child process. It must be closed before
   162  // Waiting for child.
   163  func (test *clientTest) connFromCommand() (conn *recordingConn, child *exec.Cmd, stdin opensslInput, stdout *opensslOutputSink, err error) {
   164  	cert := testRSACertificate
   165  	if len(test.cert) > 0 {
   166  		cert = test.cert
   167  	}
   168  	certPath := tempFile(string(cert))
   169  	defer os.Remove(certPath)
   170  
   171  	var key interface{} = testRSAPrivateKey
   172  	if test.key != nil {
   173  		key = test.key
   174  	}
   175  	derBytes, err := x509.MarshalPKCS8PrivateKey(key)
   176  	if err != nil {
   177  		panic(err)
   178  	}
   179  
   180  	var pemOut bytes.Buffer
   181  	pem.Encode(&pemOut, &pem.Block{Type: "PRIVATE KEY", Bytes: derBytes})
   182  
   183  	keyPath := tempFile(pemOut.String())
   184  	defer os.Remove(keyPath)
   185  
   186  	var command []string
   187  	command = append(command, serverCommand...)
   188  	command = append(command, test.args...)
   189  	command = append(command, "-cert", certPath, "-certform", "DER", "-key", keyPath)
   190  	// serverPort contains the port that OpenSSL will listen on. OpenSSL
   191  	// can't take "0" as an argument here so we have to pick a number and
   192  	// hope that it's not in use on the machine. Since this only occurs
   193  	// when -update is given and thus when there's a human watching the
   194  	// test, this isn't too bad.
   195  	const serverPort = 24323
   196  	command = append(command, "-accept", strconv.Itoa(serverPort))
   197  
   198  	if len(test.extensions) > 0 {
   199  		var serverInfo bytes.Buffer
   200  		for _, ext := range test.extensions {
   201  			pem.Encode(&serverInfo, &pem.Block{
   202  				Type:  fmt.Sprintf("SERVERINFO FOR EXTENSION %d", binary.BigEndian.Uint16(ext)),
   203  				Bytes: ext,
   204  			})
   205  		}
   206  		serverInfoPath := tempFile(serverInfo.String())
   207  		defer os.Remove(serverInfoPath)
   208  		command = append(command, "-serverinfo", serverInfoPath)
   209  	}
   210  
   211  	if test.numRenegotiations > 0 || test.sendKeyUpdate {
   212  		found := false
   213  		for _, flag := range command[1:] {
   214  			if flag == "-state" {
   215  				found = true
   216  				break
   217  			}
   218  		}
   219  
   220  		if !found {
   221  			panic("-state flag missing to OpenSSL, you need this if testing renegotiation or KeyUpdate")
   222  		}
   223  	}
   224  
   225  	cmd := exec.Command(command[0], command[1:]...)
   226  	stdin = opensslInput(make(chan opensslInputEvent))
   227  	cmd.Stdin = stdin
   228  	out := newOpensslOutputSink()
   229  	cmd.Stdout = out
   230  	cmd.Stderr = out
   231  	if err := cmd.Start(); err != nil {
   232  		return nil, nil, nil, nil, err
   233  	}
   234  
   235  	// OpenSSL does print an "ACCEPT" banner, but it does so *before*
   236  	// opening the listening socket, so we can't use that to wait until it
   237  	// has started listening. Thus we are forced to poll until we get a
   238  	// connection.
   239  	var tcpConn net.Conn
   240  	for i := uint(0); i < 5; i++ {
   241  		tcpConn, err = net.DialTCP("tcp", nil, &net.TCPAddr{
   242  			IP:   net.IPv4(127, 0, 0, 1),
   243  			Port: serverPort,
   244  		})
   245  		if err == nil {
   246  			break
   247  		}
   248  		time.Sleep((1 << i) * 5 * time.Millisecond)
   249  	}
   250  	if err != nil {
   251  		close(stdin)
   252  		cmd.Process.Kill()
   253  		err = fmt.Errorf("error connecting to the OpenSSL server: %v (%v)\n\n%s", err, cmd.Wait(), out)
   254  		return nil, nil, nil, nil, err
   255  	}
   256  
   257  	record := &recordingConn{
   258  		Conn: tcpConn,
   259  	}
   260  
   261  	return record, cmd, stdin, out, nil
   262  }
   263  
   264  func (test *clientTest) dataPath() string {
   265  	return filepath.Join("testdata", "Client-"+test.name)
   266  }
   267  
   268  func (test *clientTest) loadData() (flows [][]byte, err error) {
   269  	in, err := os.Open(test.dataPath())
   270  	if err != nil {
   271  		return nil, err
   272  	}
   273  	defer in.Close()
   274  	return parseTestData(in)
   275  }
   276  
   277  func (test *clientTest) run(t *testing.T, write bool) {
   278  	var clientConn, serverConn net.Conn
   279  	var recordingConn *recordingConn
   280  	var childProcess *exec.Cmd
   281  	var stdin opensslInput
   282  	var stdout *opensslOutputSink
   283  
   284  	if write {
   285  		var err error
   286  		recordingConn, childProcess, stdin, stdout, err = test.connFromCommand()
   287  		if err != nil {
   288  			t.Fatalf("Failed to start subcommand: %s", err)
   289  		}
   290  		clientConn = recordingConn
   291  		defer func() {
   292  			if t.Failed() {
   293  				t.Logf("OpenSSL output:\n\n%s", stdout.all)
   294  			}
   295  		}()
   296  	} else {
   297  		clientConn, serverConn = localPipe(t)
   298  	}
   299  
   300  	doneChan := make(chan bool)
   301  	defer func() {
   302  		clientConn.Close()
   303  		<-doneChan
   304  	}()
   305  	go func() {
   306  		defer close(doneChan)
   307  
   308  		config := test.config
   309  		if config == nil {
   310  			config = testConfig
   311  		}
   312  		client := Client(clientConn, config)
   313  		defer client.Close()
   314  
   315  		if _, err := client.Write([]byte("hello\n")); err != nil {
   316  			t.Errorf("Client.Write failed: %s", err)
   317  			return
   318  		}
   319  
   320  		for i := 1; i <= test.numRenegotiations; i++ {
   321  			// The initial handshake will generate a
   322  			// handshakeComplete signal which needs to be quashed.
   323  			if i == 1 && write {
   324  				<-stdout.handshakeComplete
   325  			}
   326  
   327  			// OpenSSL will try to interleave application data and
   328  			// a renegotiation if we send both concurrently.
   329  			// Therefore: ask OpensSSL to start a renegotiation, run
   330  			// a goroutine to call client.Read and thus process the
   331  			// renegotiation request, watch for OpenSSL's stdout to
   332  			// indicate that the handshake is complete and,
   333  			// finally, have OpenSSL write something to cause
   334  			// client.Read to complete.
   335  			if write {
   336  				stdin <- opensslRenegotiate
   337  			}
   338  
   339  			signalChan := make(chan struct{})
   340  
   341  			go func() {
   342  				defer close(signalChan)
   343  
   344  				buf := make([]byte, 256)
   345  				n, err := client.Read(buf)
   346  
   347  				if test.checkRenegotiationError != nil {
   348  					newErr := test.checkRenegotiationError(i, err)
   349  					if err != nil && newErr == nil {
   350  						return
   351  					}
   352  					err = newErr
   353  				}
   354  
   355  				if err != nil {
   356  					t.Errorf("Client.Read failed after renegotiation #%d: %s", i, err)
   357  					return
   358  				}
   359  
   360  				buf = buf[:n]
   361  				if !bytes.Equal([]byte(opensslSentinel), buf) {
   362  					t.Errorf("Client.Read returned %q, but wanted %q", string(buf), opensslSentinel)
   363  				}
   364  
   365  				if expected := i + 1; client.handshakes != expected {
   366  					t.Errorf("client should have recorded %d handshakes, but believes that %d have occurred", expected, client.handshakes)
   367  				}
   368  			}()
   369  
   370  			if write && test.renegotiationExpectedToFail != i {
   371  				<-stdout.handshakeComplete
   372  				stdin <- opensslSendSentinel
   373  			}
   374  			<-signalChan
   375  		}
   376  
   377  		if test.sendKeyUpdate {
   378  			if write {
   379  				<-stdout.handshakeComplete
   380  				stdin <- opensslKeyUpdate
   381  			}
   382  
   383  			doneRead := make(chan struct{})
   384  
   385  			go func() {
   386  				defer close(doneRead)
   387  
   388  				buf := make([]byte, 256)
   389  				n, err := client.Read(buf)
   390  
   391  				if err != nil {
   392  					t.Errorf("Client.Read failed after KeyUpdate: %s", err)
   393  					return
   394  				}
   395  
   396  				buf = buf[:n]
   397  				if !bytes.Equal([]byte(opensslSentinel), buf) {
   398  					t.Errorf("Client.Read returned %q, but wanted %q", string(buf), opensslSentinel)
   399  				}
   400  			}()
   401  
   402  			if write {
   403  				// There's no real reason to wait for the client KeyUpdate to
   404  				// send data with the new server keys, except that s_server
   405  				// drops writes if they are sent at the wrong time.
   406  				<-stdout.readKeyUpdate
   407  				stdin <- opensslSendSentinel
   408  			}
   409  			<-doneRead
   410  
   411  			if _, err := client.Write([]byte("hello again\n")); err != nil {
   412  				t.Errorf("Client.Write failed: %s", err)
   413  				return
   414  			}
   415  		}
   416  
   417  		if test.validate != nil {
   418  			if err := test.validate(client.ConnectionState()); err != nil {
   419  				t.Errorf("validate callback returned error: %s", err)
   420  			}
   421  		}
   422  
   423  		// If the server sent us an alert after our last flight, give it a
   424  		// chance to arrive.
   425  		if write && test.renegotiationExpectedToFail == 0 {
   426  			if err := peekError(client); err != nil {
   427  				t.Errorf("final Read returned an error: %s", err)
   428  			}
   429  		}
   430  	}()
   431  
   432  	if !write {
   433  		flows, err := test.loadData()
   434  		if err != nil {
   435  			t.Fatalf("%s: failed to load data from %s: %v", test.name, test.dataPath(), err)
   436  		}
   437  		for i, b := range flows {
   438  			if i%2 == 1 {
   439  				if *fast {
   440  					serverConn.SetWriteDeadline(time.Now().Add(1 * time.Second))
   441  				} else {
   442  					serverConn.SetWriteDeadline(time.Now().Add(1 * time.Minute))
   443  				}
   444  				serverConn.Write(b)
   445  				continue
   446  			}
   447  			bb := make([]byte, len(b))
   448  			if *fast {
   449  				serverConn.SetReadDeadline(time.Now().Add(1 * time.Second))
   450  			} else {
   451  				serverConn.SetReadDeadline(time.Now().Add(1 * time.Minute))
   452  			}
   453  			_, err := io.ReadFull(serverConn, bb)
   454  			if err != nil {
   455  				t.Fatalf("%s, flow %d: %s", test.name, i+1, err)
   456  			}
   457  			if !bytes.Equal(b, bb) {
   458  				t.Fatalf("%s, flow %d: mismatch on read: got:%x want:%x", test.name, i+1, bb, b)
   459  			}
   460  		}
   461  	}
   462  
   463  	<-doneChan
   464  	if !write {
   465  		serverConn.Close()
   466  	}
   467  
   468  	if write {
   469  		path := test.dataPath()
   470  		out, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644)
   471  		if err != nil {
   472  			t.Fatalf("Failed to create output file: %s", err)
   473  		}
   474  		defer out.Close()
   475  		recordingConn.Close()
   476  		close(stdin)
   477  		childProcess.Process.Kill()
   478  		childProcess.Wait()
   479  		if len(recordingConn.flows) < 3 {
   480  			t.Fatalf("Client connection didn't work")
   481  		}
   482  		recordingConn.WriteTo(out)
   483  		t.Logf("Wrote %s\n", path)
   484  	}
   485  }
   486  
   487  // peekError does a read with a short timeout to check if the next read would
   488  // cause an error, for example if there is an alert waiting on the wire.
   489  func peekError(conn net.Conn) error {
   490  	conn.SetReadDeadline(time.Now().Add(100 * time.Millisecond))
   491  	if n, err := conn.Read(make([]byte, 1)); n != 0 {
   492  		return errors.New("unexpectedly read data")
   493  	} else if err != nil {
   494  		if netErr, ok := err.(net.Error); !ok || !netErr.Timeout() {
   495  			return err
   496  		}
   497  	}
   498  	return nil
   499  }
   500  
   501  func runClientTestForVersion(t *testing.T, template *clientTest, version, option string) {
   502  	// Make a deep copy of the template before going parallel.
   503  	test := *template
   504  	if template.config != nil {
   505  		test.config = template.config.Clone()
   506  	}
   507  	test.name = version + "-" + test.name
   508  	test.args = append([]string{option}, test.args...)
   509  
   510  	runTestAndUpdateIfNeeded(t, version, test.run, false)
   511  }
   512  
   513  func runClientTestTLS10(t *testing.T, template *clientTest) {
   514  	runClientTestForVersion(t, template, "TLSv10", "-tls1")
   515  }
   516  
   517  func runClientTestTLS11(t *testing.T, template *clientTest) {
   518  	runClientTestForVersion(t, template, "TLSv11", "-tls1_1")
   519  }
   520  
   521  func runClientTestTLS12(t *testing.T, template *clientTest) {
   522  	runClientTestForVersion(t, template, "TLSv12", "-tls1_2")
   523  }
   524  
   525  func runClientTestTLS13(t *testing.T, template *clientTest) {
   526  	runClientTestForVersion(t, template, "TLSv13", "-tls1_3")
   527  }
   528  
   529  func TestHandshakeClientRSARC4(t *testing.T) {
   530  	test := &clientTest{
   531  		name: "RSA-RC4",
   532  		args: []string{"-cipher", "RC4-SHA"},
   533  	}
   534  	runClientTestTLS10(t, test)
   535  	runClientTestTLS11(t, test)
   536  	runClientTestTLS12(t, test)
   537  }
   538  
   539  func TestHandshakeClientRSAAES128GCM(t *testing.T) {
   540  	test := &clientTest{
   541  		name: "AES128-GCM-SHA256",
   542  		args: []string{"-cipher", "AES128-GCM-SHA256"},
   543  	}
   544  	runClientTestTLS12(t, test)
   545  }
   546  
   547  func TestHandshakeClientRSAAES256GCM(t *testing.T) {
   548  	test := &clientTest{
   549  		name: "AES256-GCM-SHA384",
   550  		args: []string{"-cipher", "AES256-GCM-SHA384"},
   551  	}
   552  	runClientTestTLS12(t, test)
   553  }
   554  
   555  func TestHandshakeClientECDHERSAAES(t *testing.T) {
   556  	test := &clientTest{
   557  		name: "ECDHE-RSA-AES",
   558  		args: []string{"-cipher", "ECDHE-RSA-AES128-SHA"},
   559  	}
   560  	runClientTestTLS10(t, test)
   561  	runClientTestTLS11(t, test)
   562  	runClientTestTLS12(t, test)
   563  }
   564  
   565  func TestHandshakeClientECDHEECDSAAES(t *testing.T) {
   566  	test := &clientTest{
   567  		name: "ECDHE-ECDSA-AES",
   568  		args: []string{"-cipher", "ECDHE-ECDSA-AES128-SHA"},
   569  		cert: testECDSACertificate,
   570  		key:  testECDSAPrivateKey,
   571  	}
   572  	runClientTestTLS10(t, test)
   573  	runClientTestTLS11(t, test)
   574  	runClientTestTLS12(t, test)
   575  }
   576  
   577  func TestHandshakeClientECDHEECDSAAESGCM(t *testing.T) {
   578  	test := &clientTest{
   579  		name: "ECDHE-ECDSA-AES-GCM",
   580  		args: []string{"-cipher", "ECDHE-ECDSA-AES128-GCM-SHA256"},
   581  		cert: testECDSACertificate,
   582  		key:  testECDSAPrivateKey,
   583  	}
   584  	runClientTestTLS12(t, test)
   585  }
   586  
   587  func TestHandshakeClientAES256GCMSHA384(t *testing.T) {
   588  	test := &clientTest{
   589  		name: "ECDHE-ECDSA-AES256-GCM-SHA384",
   590  		args: []string{"-cipher", "ECDHE-ECDSA-AES256-GCM-SHA384"},
   591  		cert: testECDSACertificate,
   592  		key:  testECDSAPrivateKey,
   593  	}
   594  	runClientTestTLS12(t, test)
   595  }
   596  
   597  func TestHandshakeClientAES128CBCSHA256(t *testing.T) {
   598  	test := &clientTest{
   599  		name: "AES128-SHA256",
   600  		args: []string{"-cipher", "AES128-SHA256"},
   601  	}
   602  	runClientTestTLS12(t, test)
   603  }
   604  
   605  func TestHandshakeClientECDHERSAAES128CBCSHA256(t *testing.T) {
   606  	test := &clientTest{
   607  		name: "ECDHE-RSA-AES128-SHA256",
   608  		args: []string{"-cipher", "ECDHE-RSA-AES128-SHA256"},
   609  	}
   610  	runClientTestTLS12(t, test)
   611  }
   612  
   613  func TestHandshakeClientECDHEECDSAAES128CBCSHA256(t *testing.T) {
   614  	test := &clientTest{
   615  		name: "ECDHE-ECDSA-AES128-SHA256",
   616  		args: []string{"-cipher", "ECDHE-ECDSA-AES128-SHA256"},
   617  		cert: testECDSACertificate,
   618  		key:  testECDSAPrivateKey,
   619  	}
   620  	runClientTestTLS12(t, test)
   621  }
   622  
   623  func TestHandshakeClientX25519(t *testing.T) {
   624  	config := testConfig.Clone()
   625  	config.CurvePreferences = []CurveID{X25519}
   626  
   627  	test := &clientTest{
   628  		name:   "X25519-ECDHE",
   629  		args:   []string{"-cipher", "ECDHE-RSA-AES128-GCM-SHA256", "-curves", "X25519"},
   630  		config: config,
   631  	}
   632  
   633  	runClientTestTLS12(t, test)
   634  	runClientTestTLS13(t, test)
   635  }
   636  
   637  func TestHandshakeClientP256(t *testing.T) {
   638  	config := testConfig.Clone()
   639  	config.CurvePreferences = []CurveID{CurveP256}
   640  
   641  	test := &clientTest{
   642  		name:   "P256-ECDHE",
   643  		args:   []string{"-cipher", "ECDHE-RSA-AES128-GCM-SHA256", "-curves", "P-256"},
   644  		config: config,
   645  	}
   646  
   647  	runClientTestTLS12(t, test)
   648  	runClientTestTLS13(t, test)
   649  }
   650  
   651  func TestHandshakeClientHelloRetryRequest(t *testing.T) {
   652  	config := testConfig.Clone()
   653  	config.CurvePreferences = []CurveID{X25519, CurveP256}
   654  
   655  	test := &clientTest{
   656  		name:   "HelloRetryRequest",
   657  		args:   []string{"-cipher", "ECDHE-RSA-AES128-GCM-SHA256", "-curves", "P-256"},
   658  		config: config,
   659  	}
   660  
   661  	runClientTestTLS13(t, test)
   662  }
   663  
   664  func TestHandshakeClientECDHERSAChaCha20(t *testing.T) {
   665  	config := testConfig.Clone()
   666  	config.CipherSuites = []uint16{TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305}
   667  
   668  	test := &clientTest{
   669  		name:   "ECDHE-RSA-CHACHA20-POLY1305",
   670  		args:   []string{"-cipher", "ECDHE-RSA-CHACHA20-POLY1305"},
   671  		config: config,
   672  	}
   673  
   674  	runClientTestTLS12(t, test)
   675  }
   676  
   677  func TestHandshakeClientECDHEECDSAChaCha20(t *testing.T) {
   678  	config := testConfig.Clone()
   679  	config.CipherSuites = []uint16{TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305}
   680  
   681  	test := &clientTest{
   682  		name:   "ECDHE-ECDSA-CHACHA20-POLY1305",
   683  		args:   []string{"-cipher", "ECDHE-ECDSA-CHACHA20-POLY1305"},
   684  		config: config,
   685  		cert:   testECDSACertificate,
   686  		key:    testECDSAPrivateKey,
   687  	}
   688  
   689  	runClientTestTLS12(t, test)
   690  }
   691  
   692  func TestHandshakeClientAES128SHA256(t *testing.T) {
   693  	test := &clientTest{
   694  		name: "AES128-SHA256",
   695  		args: []string{"-ciphersuites", "TLS_AES_128_GCM_SHA256"},
   696  	}
   697  	runClientTestTLS13(t, test)
   698  }
   699  func TestHandshakeClientAES256SHA384(t *testing.T) {
   700  	test := &clientTest{
   701  		name: "AES256-SHA384",
   702  		args: []string{"-ciphersuites", "TLS_AES_256_GCM_SHA384"},
   703  	}
   704  	runClientTestTLS13(t, test)
   705  }
   706  func TestHandshakeClientCHACHA20SHA256(t *testing.T) {
   707  	test := &clientTest{
   708  		name: "CHACHA20-SHA256",
   709  		args: []string{"-ciphersuites", "TLS_CHACHA20_POLY1305_SHA256"},
   710  	}
   711  	runClientTestTLS13(t, test)
   712  }
   713  
   714  func TestHandshakeClientECDSATLS13(t *testing.T) {
   715  	test := &clientTest{
   716  		name: "ECDSA",
   717  		cert: testECDSACertificate,
   718  		key:  testECDSAPrivateKey,
   719  	}
   720  	runClientTestTLS13(t, test)
   721  }
   722  
   723  func TestHandshakeClientEd25519(t *testing.T) {
   724  	test := &clientTest{
   725  		name: "Ed25519",
   726  		cert: testEd25519Certificate,
   727  		key:  testEd25519PrivateKey,
   728  	}
   729  	runClientTestTLS12(t, test)
   730  	runClientTestTLS13(t, test)
   731  
   732  	config := testConfig.Clone()
   733  	cert, _ := X509KeyPair([]byte(clientEd25519CertificatePEM), []byte(clientEd25519KeyPEM))
   734  	config.Certificates = []Certificate{cert}
   735  
   736  	test = &clientTest{
   737  		name:   "ClientCert-Ed25519",
   738  		args:   []string{"-Verify", "1"},
   739  		config: config,
   740  	}
   741  
   742  	runClientTestTLS12(t, test)
   743  	runClientTestTLS13(t, test)
   744  }
   745  
   746  func TestHandshakeClientCertRSA(t *testing.T) {
   747  	config := testConfig.Clone()
   748  	cert, _ := X509KeyPair([]byte(clientCertificatePEM), []byte(clientKeyPEM))
   749  	config.Certificates = []Certificate{cert}
   750  
   751  	test := &clientTest{
   752  		name:   "ClientCert-RSA-RSA",
   753  		args:   []string{"-cipher", "AES128", "-Verify", "1"},
   754  		config: config,
   755  	}
   756  
   757  	runClientTestTLS10(t, test)
   758  	runClientTestTLS12(t, test)
   759  
   760  	test = &clientTest{
   761  		name:   "ClientCert-RSA-ECDSA",
   762  		args:   []string{"-cipher", "ECDHE-ECDSA-AES128-SHA", "-Verify", "1"},
   763  		config: config,
   764  		cert:   testECDSACertificate,
   765  		key:    testECDSAPrivateKey,
   766  	}
   767  
   768  	runClientTestTLS10(t, test)
   769  	runClientTestTLS12(t, test)
   770  	runClientTestTLS13(t, test)
   771  
   772  	test = &clientTest{
   773  		name:   "ClientCert-RSA-AES256-GCM-SHA384",
   774  		args:   []string{"-cipher", "ECDHE-RSA-AES256-GCM-SHA384", "-Verify", "1"},
   775  		config: config,
   776  		cert:   testRSACertificate,
   777  		key:    testRSAPrivateKey,
   778  	}
   779  
   780  	runClientTestTLS12(t, test)
   781  }
   782  
   783  func TestHandshakeClientCertECDSA(t *testing.T) {
   784  	config := testConfig.Clone()
   785  	cert, _ := X509KeyPair([]byte(clientECDSACertificatePEM), []byte(clientECDSAKeyPEM))
   786  	config.Certificates = []Certificate{cert}
   787  
   788  	test := &clientTest{
   789  		name:   "ClientCert-ECDSA-RSA",
   790  		args:   []string{"-cipher", "AES128", "-Verify", "1"},
   791  		config: config,
   792  	}
   793  
   794  	runClientTestTLS10(t, test)
   795  	runClientTestTLS12(t, test)
   796  	runClientTestTLS13(t, test)
   797  
   798  	test = &clientTest{
   799  		name:   "ClientCert-ECDSA-ECDSA",
   800  		args:   []string{"-cipher", "ECDHE-ECDSA-AES128-SHA", "-Verify", "1"},
   801  		config: config,
   802  		cert:   testECDSACertificate,
   803  		key:    testECDSAPrivateKey,
   804  	}
   805  
   806  	runClientTestTLS10(t, test)
   807  	runClientTestTLS12(t, test)
   808  }
   809  
   810  // TestHandshakeClientCertRSAPSS tests rsa_pss_rsae_sha256 signatures from both
   811  // client and server certificates. It also serves from both sides a certificate
   812  // signed itself with RSA-PSS, mostly to check that crypto/x509 chain validation
   813  // works.
   814  func TestHandshakeClientCertRSAPSS(t *testing.T) {
   815  	cert, err := x509.ParseCertificate(testRSAPSSCertificate)
   816  	if err != nil {
   817  		panic(err)
   818  	}
   819  	rootCAs := x509.NewCertPool()
   820  	rootCAs.AddCert(cert)
   821  
   822  	config := testConfig.Clone()
   823  	// Use GetClientCertificate to bypass the client certificate selection logic.
   824  	config.GetClientCertificate = func(*CertificateRequestInfo) (*Certificate, error) {
   825  		return &Certificate{
   826  			Certificate: [][]byte{testRSAPSSCertificate},
   827  			PrivateKey:  testRSAPrivateKey,
   828  		}, nil
   829  	}
   830  	config.RootCAs = rootCAs
   831  
   832  	test := &clientTest{
   833  		name: "ClientCert-RSA-RSAPSS",
   834  		args: []string{"-cipher", "AES128", "-Verify", "1", "-client_sigalgs",
   835  			"rsa_pss_rsae_sha256", "-sigalgs", "rsa_pss_rsae_sha256"},
   836  		config: config,
   837  		cert:   testRSAPSSCertificate,
   838  		key:    testRSAPrivateKey,
   839  	}
   840  	runClientTestTLS12(t, test)
   841  	runClientTestTLS13(t, test)
   842  }
   843  
   844  func TestHandshakeClientCertRSAPKCS1v15(t *testing.T) {
   845  	config := testConfig.Clone()
   846  	cert, _ := X509KeyPair([]byte(clientCertificatePEM), []byte(clientKeyPEM))
   847  	config.Certificates = []Certificate{cert}
   848  
   849  	test := &clientTest{
   850  		name: "ClientCert-RSA-RSAPKCS1v15",
   851  		args: []string{"-cipher", "AES128", "-Verify", "1", "-client_sigalgs",
   852  			"rsa_pkcs1_sha256", "-sigalgs", "rsa_pkcs1_sha256"},
   853  		config: config,
   854  	}
   855  
   856  	runClientTestTLS12(t, test)
   857  }
   858  
   859  func TestClientKeyUpdate(t *testing.T) {
   860  	test := &clientTest{
   861  		name:          "KeyUpdate",
   862  		args:          []string{"-state"},
   863  		sendKeyUpdate: true,
   864  	}
   865  	runClientTestTLS13(t, test)
   866  }
   867  
   868  func TestResumption(t *testing.T) {
   869  	t.Run("TLSv12", func(t *testing.T) { testResumption(t, VersionTLS12) })
   870  	t.Run("TLSv13", func(t *testing.T) { testResumption(t, VersionTLS13) })
   871  }
   872  
   873  func testResumption(t *testing.T, version uint16) {
   874  	if testing.Short() {
   875  		t.Skip("skipping in -short mode")
   876  	}
   877  	serverConfig := &Config{
   878  		MaxVersion:   version,
   879  		CipherSuites: []uint16{TLS_RSA_WITH_RC4_128_SHA, TLS_ECDHE_RSA_WITH_RC4_128_SHA},
   880  		Certificates: testConfig.Certificates,
   881  	}
   882  
   883  	issuer, err := x509.ParseCertificate(testRSACertificateIssuer)
   884  	if err != nil {
   885  		panic(err)
   886  	}
   887  
   888  	rootCAs := x509.NewCertPool()
   889  	rootCAs.AddCert(issuer)
   890  
   891  	clientConfig := &Config{
   892  		MaxVersion:         version,
   893  		CipherSuites:       []uint16{TLS_RSA_WITH_RC4_128_SHA},
   894  		ClientSessionCache: NewLRUClientSessionCache(32),
   895  		RootCAs:            rootCAs,
   896  		ServerName:         "example.golang",
   897  	}
   898  
   899  	testResumeState := func(test string, didResume bool) {
   900  		_, hs, err := testHandshake(t, clientConfig, serverConfig)
   901  		if err != nil {
   902  			t.Fatalf("%s: handshake failed: %s", test, err)
   903  		}
   904  		if hs.DidResume != didResume {
   905  			t.Fatalf("%s resumed: %v, expected: %v", test, hs.DidResume, didResume)
   906  		}
   907  		if didResume && (hs.PeerCertificates == nil || hs.VerifiedChains == nil) {
   908  			t.Fatalf("expected non-nil certificates after resumption. Got peerCertificates: %#v, verifiedCertificates: %#v", hs.PeerCertificates, hs.VerifiedChains)
   909  		}
   910  	}
   911  
   912  	getTicket := func() []byte {
   913  		return clientConfig.ClientSessionCache.(*lruSessionCache).q.Front().Value.(*lruSessionCacheEntry).state.sessionTicket
   914  	}
   915  	deleteTicket := func() {
   916  		ticketKey := clientConfig.ClientSessionCache.(*lruSessionCache).q.Front().Value.(*lruSessionCacheEntry).sessionKey
   917  		clientConfig.ClientSessionCache.Put(ticketKey, nil)
   918  	}
   919  	corruptTicket := func() {
   920  		clientConfig.ClientSessionCache.(*lruSessionCache).q.Front().Value.(*lruSessionCacheEntry).state.masterSecret[0] ^= 0xff
   921  	}
   922  	randomKey := func() [32]byte {
   923  		var k [32]byte
   924  		if _, err := io.ReadFull(serverConfig.rand(), k[:]); err != nil {
   925  			t.Fatalf("Failed to read new SessionTicketKey: %s", err)
   926  		}
   927  		return k
   928  	}
   929  
   930  	testResumeState("Handshake", false)
   931  	ticket := getTicket()
   932  	testResumeState("Resume", true)
   933  	if !bytes.Equal(ticket, getTicket()) && version != VersionTLS13 {
   934  		t.Fatal("first ticket doesn't match ticket after resumption")
   935  	}
   936  	if bytes.Equal(ticket, getTicket()) && version == VersionTLS13 {
   937  		t.Fatal("ticket didn't change after resumption")
   938  	}
   939  
   940  	key1 := randomKey()
   941  	serverConfig.SetSessionTicketKeys([][32]byte{key1})
   942  
   943  	testResumeState("InvalidSessionTicketKey", false)
   944  	testResumeState("ResumeAfterInvalidSessionTicketKey", true)
   945  
   946  	key2 := randomKey()
   947  	serverConfig.SetSessionTicketKeys([][32]byte{key2, key1})
   948  	ticket = getTicket()
   949  	testResumeState("KeyChange", true)
   950  	if bytes.Equal(ticket, getTicket()) {
   951  		t.Fatal("new ticket wasn't included while resuming")
   952  	}
   953  	testResumeState("KeyChangeFinish", true)
   954  
   955  	// Reset serverConfig to ensure that calling SetSessionTicketKeys
   956  	// before the serverConfig is used works.
   957  	serverConfig = &Config{
   958  		MaxVersion:   version,
   959  		CipherSuites: []uint16{TLS_RSA_WITH_RC4_128_SHA, TLS_ECDHE_RSA_WITH_RC4_128_SHA},
   960  		Certificates: testConfig.Certificates,
   961  	}
   962  	serverConfig.SetSessionTicketKeys([][32]byte{key2})
   963  
   964  	testResumeState("FreshConfig", true)
   965  
   966  	// In TLS 1.3, cross-cipher suite resumption is allowed as long as the KDF
   967  	// hash matches. Also, Config.CipherSuites does not apply to TLS 1.3.
   968  	if version != VersionTLS13 {
   969  		clientConfig.CipherSuites = []uint16{TLS_ECDHE_RSA_WITH_RC4_128_SHA}
   970  		testResumeState("DifferentCipherSuite", false)
   971  		testResumeState("DifferentCipherSuiteRecovers", true)
   972  	}
   973  
   974  	deleteTicket()
   975  	testResumeState("WithoutSessionTicket", false)
   976  
   977  	// Session resumption should work when using client certificates
   978  	deleteTicket()
   979  	serverConfig.ClientCAs = rootCAs
   980  	serverConfig.ClientAuth = RequireAndVerifyClientCert
   981  	clientConfig.Certificates = serverConfig.Certificates
   982  	testResumeState("InitialHandshake", false)
   983  	testResumeState("WithClientCertificates", true)
   984  	serverConfig.ClientAuth = NoClientCert
   985  
   986  	// Tickets should be removed from the session cache on TLS handshake
   987  	// failure, and the client should recover from a corrupted PSK
   988  	testResumeState("FetchTicketToCorrupt", false)
   989  	corruptTicket()
   990  	_, _, err = testHandshake(t, clientConfig, serverConfig)
   991  	if err == nil {
   992  		t.Fatalf("handshake did not fail with a corrupted client secret")
   993  	}
   994  	testResumeState("AfterHandshakeFailure", false)
   995  
   996  	clientConfig.ClientSessionCache = nil
   997  	testResumeState("WithoutSessionCache", false)
   998  }
   999  
  1000  func TestLRUClientSessionCache(t *testing.T) {
  1001  	// Initialize cache of capacity 4.
  1002  	cache := NewLRUClientSessionCache(4)
  1003  	cs := make([]ClientSessionState, 6)
  1004  	keys := []string{"0", "1", "2", "3", "4", "5", "6"}
  1005  
  1006  	// Add 4 entries to the cache and look them up.
  1007  	for i := 0; i < 4; i++ {
  1008  		cache.Put(keys[i], &cs[i])
  1009  	}
  1010  	for i := 0; i < 4; i++ {
  1011  		if s, ok := cache.Get(keys[i]); !ok || s != &cs[i] {
  1012  			t.Fatalf("session cache failed lookup for added key: %s", keys[i])
  1013  		}
  1014  	}
  1015  
  1016  	// Add 2 more entries to the cache. First 2 should be evicted.
  1017  	for i := 4; i < 6; i++ {
  1018  		cache.Put(keys[i], &cs[i])
  1019  	}
  1020  	for i := 0; i < 2; i++ {
  1021  		if s, ok := cache.Get(keys[i]); ok || s != nil {
  1022  			t.Fatalf("session cache should have evicted key: %s", keys[i])
  1023  		}
  1024  	}
  1025  
  1026  	// Touch entry 2. LRU should evict 3 next.
  1027  	cache.Get(keys[2])
  1028  	cache.Put(keys[0], &cs[0])
  1029  	if s, ok := cache.Get(keys[3]); ok || s != nil {
  1030  		t.Fatalf("session cache should have evicted key 3")
  1031  	}
  1032  
  1033  	// Update entry 0 in place.
  1034  	cache.Put(keys[0], &cs[3])
  1035  	if s, ok := cache.Get(keys[0]); !ok || s != &cs[3] {
  1036  		t.Fatalf("session cache failed update for key 0")
  1037  	}
  1038  
  1039  	// Calling Put with a nil entry deletes the key.
  1040  	cache.Put(keys[0], nil)
  1041  	if _, ok := cache.Get(keys[0]); ok {
  1042  		t.Fatalf("session cache failed to delete key 0")
  1043  	}
  1044  
  1045  	// Delete entry 2. LRU should keep 4 and 5
  1046  	cache.Put(keys[2], nil)
  1047  	if _, ok := cache.Get(keys[2]); ok {
  1048  		t.Fatalf("session cache failed to delete key 4")
  1049  	}
  1050  	for i := 4; i < 6; i++ {
  1051  		if s, ok := cache.Get(keys[i]); !ok || s != &cs[i] {
  1052  			t.Fatalf("session cache should not have deleted key: %s", keys[i])
  1053  		}
  1054  	}
  1055  }
  1056  
  1057  func TestKeyLogTLS12(t *testing.T) {
  1058  	var serverBuf, clientBuf bytes.Buffer
  1059  
  1060  	clientConfig := testConfig.Clone()
  1061  	clientConfig.KeyLogWriter = &clientBuf
  1062  	clientConfig.MaxVersion = VersionTLS12
  1063  
  1064  	serverConfig := testConfig.Clone()
  1065  	serverConfig.KeyLogWriter = &serverBuf
  1066  	serverConfig.MaxVersion = VersionTLS12
  1067  
  1068  	c, s := localPipe(t)
  1069  	done := make(chan bool)
  1070  
  1071  	go func() {
  1072  		defer close(done)
  1073  
  1074  		if err := Server(s, serverConfig).Handshake(); err != nil {
  1075  			t.Errorf("server: %s", err)
  1076  			return
  1077  		}
  1078  		s.Close()
  1079  	}()
  1080  
  1081  	if err := Client(c, clientConfig).Handshake(); err != nil {
  1082  		t.Fatalf("client: %s", err)
  1083  	}
  1084  
  1085  	c.Close()
  1086  	<-done
  1087  
  1088  	checkKeylogLine := func(side, loggedLine string) {
  1089  		if len(loggedLine) == 0 {
  1090  			t.Fatalf("%s: no keylog line was produced", side)
  1091  		}
  1092  		const expectedLen = 13 /* "CLIENT_RANDOM" */ +
  1093  			1 /* space */ +
  1094  			32*2 /* hex client nonce */ +
  1095  			1 /* space */ +
  1096  			48*2 /* hex master secret */ +
  1097  			1 /* new line */
  1098  		if len(loggedLine) != expectedLen {
  1099  			t.Fatalf("%s: keylog line has incorrect length (want %d, got %d): %q", side, expectedLen, len(loggedLine), loggedLine)
  1100  		}
  1101  		if !strings.HasPrefix(loggedLine, "CLIENT_RANDOM "+strings.Repeat("0", 64)+" ") {
  1102  			t.Fatalf("%s: keylog line has incorrect structure or nonce: %q", side, loggedLine)
  1103  		}
  1104  	}
  1105  
  1106  	checkKeylogLine("client", clientBuf.String())
  1107  	checkKeylogLine("server", serverBuf.String())
  1108  }
  1109  
  1110  func TestKeyLogTLS13(t *testing.T) {
  1111  	var serverBuf, clientBuf bytes.Buffer
  1112  
  1113  	clientConfig := testConfig.Clone()
  1114  	clientConfig.KeyLogWriter = &clientBuf
  1115  
  1116  	serverConfig := testConfig.Clone()
  1117  	serverConfig.KeyLogWriter = &serverBuf
  1118  
  1119  	c, s := localPipe(t)
  1120  	done := make(chan bool)
  1121  
  1122  	go func() {
  1123  		defer close(done)
  1124  
  1125  		if err := Server(s, serverConfig).Handshake(); err != nil {
  1126  			t.Errorf("server: %s", err)
  1127  			return
  1128  		}
  1129  		s.Close()
  1130  	}()
  1131  
  1132  	if err := Client(c, clientConfig).Handshake(); err != nil {
  1133  		t.Fatalf("client: %s", err)
  1134  	}
  1135  
  1136  	c.Close()
  1137  	<-done
  1138  
  1139  	checkKeylogLines := func(side, loggedLines string) {
  1140  		loggedLines = strings.TrimSpace(loggedLines)
  1141  		lines := strings.Split(loggedLines, "\n")
  1142  		if len(lines) != 4 {
  1143  			t.Errorf("Expected the %s to log 4 lines, got %d", side, len(lines))
  1144  		}
  1145  	}
  1146  
  1147  	checkKeylogLines("client", clientBuf.String())
  1148  	checkKeylogLines("server", serverBuf.String())
  1149  }
  1150  
  1151  func TestHandshakeClientALPNMatch(t *testing.T) {
  1152  	config := testConfig.Clone()
  1153  	config.NextProtos = []string{"proto2", "proto1"}
  1154  
  1155  	test := &clientTest{
  1156  		name: "ALPN",
  1157  		// Note that this needs OpenSSL 1.0.2 because that is the first
  1158  		// version that supports the -alpn flag.
  1159  		args:   []string{"-alpn", "proto1,proto2"},
  1160  		config: config,
  1161  		validate: func(state ConnectionState) error {
  1162  			// The server's preferences should override the client.
  1163  			if state.NegotiatedProtocol != "proto1" {
  1164  				return fmt.Errorf("Got protocol %q, wanted proto1", state.NegotiatedProtocol)
  1165  			}
  1166  			return nil
  1167  		},
  1168  	}
  1169  	runClientTestTLS12(t, test)
  1170  	runClientTestTLS13(t, test)
  1171  }
  1172  
  1173  // sctsBase64 contains data from `openssl s_client -serverinfo 18 -connect ritter.vg:443`
  1174  const sctsBase64 = "ABIBaQFnAHUApLkJkLQYWBSHuxOizGdwCjw1mAT5G9+443fNDsgN3BAAAAFHl5nuFgAABAMARjBEAiAcS4JdlW5nW9sElUv2zvQyPoZ6ejKrGGB03gjaBZFMLwIgc1Qbbn+hsH0RvObzhS+XZhr3iuQQJY8S9G85D9KeGPAAdgBo9pj4H2SCvjqM7rkoHUz8cVFdZ5PURNEKZ6y7T0/7xAAAAUeX4bVwAAAEAwBHMEUCIDIhFDgG2HIuADBkGuLobU5a4dlCHoJLliWJ1SYT05z6AiEAjxIoZFFPRNWMGGIjskOTMwXzQ1Wh2e7NxXE1kd1J0QsAdgDuS723dc5guuFCaR+r4Z5mow9+X7By2IMAxHuJeqj9ywAAAUhcZIqHAAAEAwBHMEUCICmJ1rBT09LpkbzxtUC+Hi7nXLR0J+2PmwLp+sJMuqK+AiEAr0NkUnEVKVhAkccIFpYDqHOlZaBsuEhWWrYpg2RtKp0="
  1175  
  1176  func TestHandshakClientSCTs(t *testing.T) {
  1177  	config := testConfig.Clone()
  1178  
  1179  	scts, err := base64.StdEncoding.DecodeString(sctsBase64)
  1180  	if err != nil {
  1181  		t.Fatal(err)
  1182  	}
  1183  
  1184  	// Note that this needs OpenSSL 1.0.2 because that is the first
  1185  	// version that supports the -serverinfo flag.
  1186  	test := &clientTest{
  1187  		name:       "SCT",
  1188  		config:     config,
  1189  		extensions: [][]byte{scts},
  1190  		validate: func(state ConnectionState) error {
  1191  			expectedSCTs := [][]byte{
  1192  				scts[8:125],
  1193  				scts[127:245],
  1194  				scts[247:],
  1195  			}
  1196  			if n := len(state.SignedCertificateTimestamps); n != len(expectedSCTs) {
  1197  				return fmt.Errorf("Got %d scts, wanted %d", n, len(expectedSCTs))
  1198  			}
  1199  			for i, expected := range expectedSCTs {
  1200  				if sct := state.SignedCertificateTimestamps[i]; !bytes.Equal(sct, expected) {
  1201  					return fmt.Errorf("SCT #%d contained %x, expected %x", i, sct, expected)
  1202  				}
  1203  			}
  1204  			return nil
  1205  		},
  1206  	}
  1207  	runClientTestTLS12(t, test)
  1208  
  1209  	// TLS 1.3 moved SCTs to the Certificate extensions and -serverinfo only
  1210  	// supports ServerHello extensions.
  1211  }
  1212  
  1213  func TestRenegotiationRejected(t *testing.T) {
  1214  	config := testConfig.Clone()
  1215  	test := &clientTest{
  1216  		name:                        "RenegotiationRejected",
  1217  		args:                        []string{"-state"},
  1218  		config:                      config,
  1219  		numRenegotiations:           1,
  1220  		renegotiationExpectedToFail: 1,
  1221  		checkRenegotiationError: func(renegotiationNum int, err error) error {
  1222  			if err == nil {
  1223  				return errors.New("expected error from renegotiation but got nil")
  1224  			}
  1225  			if !strings.Contains(err.Error(), "no renegotiation") {
  1226  				return fmt.Errorf("expected renegotiation to be rejected but got %q", err)
  1227  			}
  1228  			return nil
  1229  		},
  1230  	}
  1231  	runClientTestTLS12(t, test)
  1232  }
  1233  
  1234  func TestRenegotiateOnce(t *testing.T) {
  1235  	config := testConfig.Clone()
  1236  	config.Renegotiation = RenegotiateOnceAsClient
  1237  
  1238  	test := &clientTest{
  1239  		name:              "RenegotiateOnce",
  1240  		args:              []string{"-state"},
  1241  		config:            config,
  1242  		numRenegotiations: 1,
  1243  	}
  1244  
  1245  	runClientTestTLS12(t, test)
  1246  }
  1247  
  1248  func TestRenegotiateTwice(t *testing.T) {
  1249  	config := testConfig.Clone()
  1250  	config.Renegotiation = RenegotiateFreelyAsClient
  1251  
  1252  	test := &clientTest{
  1253  		name:              "RenegotiateTwice",
  1254  		args:              []string{"-state"},
  1255  		config:            config,
  1256  		numRenegotiations: 2,
  1257  	}
  1258  
  1259  	runClientTestTLS12(t, test)
  1260  }
  1261  
  1262  func TestRenegotiateTwiceRejected(t *testing.T) {
  1263  	config := testConfig.Clone()
  1264  	config.Renegotiation = RenegotiateOnceAsClient
  1265  
  1266  	test := &clientTest{
  1267  		name:                        "RenegotiateTwiceRejected",
  1268  		args:                        []string{"-state"},
  1269  		config:                      config,
  1270  		numRenegotiations:           2,
  1271  		renegotiationExpectedToFail: 2,
  1272  		checkRenegotiationError: func(renegotiationNum int, err error) error {
  1273  			if renegotiationNum == 1 {
  1274  				return err
  1275  			}
  1276  
  1277  			if err == nil {
  1278  				return errors.New("expected error from renegotiation but got nil")
  1279  			}
  1280  			if !strings.Contains(err.Error(), "no renegotiation") {
  1281  				return fmt.Errorf("expected renegotiation to be rejected but got %q", err)
  1282  			}
  1283  			return nil
  1284  		},
  1285  	}
  1286  
  1287  	runClientTestTLS12(t, test)
  1288  }
  1289  
  1290  func TestHandshakeClientExportKeyingMaterial(t *testing.T) {
  1291  	test := &clientTest{
  1292  		name:   "ExportKeyingMaterial",
  1293  		config: testConfig.Clone(),
  1294  		validate: func(state ConnectionState) error {
  1295  			if km, err := state.ExportKeyingMaterial("test", nil, 42); err != nil {
  1296  				return fmt.Errorf("ExportKeyingMaterial failed: %v", err)
  1297  			} else if len(km) != 42 {
  1298  				return fmt.Errorf("Got %d bytes from ExportKeyingMaterial, wanted %d", len(km), 42)
  1299  			}
  1300  			return nil
  1301  		},
  1302  	}
  1303  	runClientTestTLS10(t, test)
  1304  	runClientTestTLS12(t, test)
  1305  	runClientTestTLS13(t, test)
  1306  }
  1307  
  1308  var hostnameInSNITests = []struct {
  1309  	in, out string
  1310  }{
  1311  	// Opaque string
  1312  	{"", ""},
  1313  	{"localhost", "localhost"},
  1314  	{"foo, bar, baz and qux", "foo, bar, baz and qux"},
  1315  
  1316  	// DNS hostname
  1317  	{"golang.org", "golang.org"},
  1318  	{"golang.org.", "golang.org"},
  1319  
  1320  	// Literal IPv4 address
  1321  	{"1.2.3.4", ""},
  1322  
  1323  	// Literal IPv6 address
  1324  	{"::1", ""},
  1325  	{"::1%lo0", ""}, // with zone identifier
  1326  	{"[::1]", ""},   // as per RFC 5952 we allow the [] style as IPv6 literal
  1327  	{"[::1%lo0]", ""},
  1328  }
  1329  
  1330  func TestHostnameInSNI(t *testing.T) {
  1331  	for _, tt := range hostnameInSNITests {
  1332  		c, s := localPipe(t)
  1333  
  1334  		go func(host string) {
  1335  			Client(c, &Config{ServerName: host, InsecureSkipVerify: true}).Handshake()
  1336  		}(tt.in)
  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  		c.Close()
  1350  		s.Close()
  1351  
  1352  		var m clientHelloMsg
  1353  		if !m.unmarshal(record) {
  1354  			t.Errorf("unmarshaling ClientHello for %q failed", tt.in)
  1355  			continue
  1356  		}
  1357  		if tt.in != tt.out && m.serverName == tt.in {
  1358  			t.Errorf("prohibited %q found in ClientHello: %x", tt.in, record)
  1359  		}
  1360  		if m.serverName != tt.out {
  1361  			t.Errorf("expected %q not found in ClientHello: %x", tt.out, record)
  1362  		}
  1363  	}
  1364  }
  1365  
  1366  func TestServerSelectingUnconfiguredCipherSuite(t *testing.T) {
  1367  	// This checks that the server can't select a cipher suite that the
  1368  	// client didn't offer. See #13174.
  1369  
  1370  	c, s := localPipe(t)
  1371  	errChan := make(chan error, 1)
  1372  
  1373  	go func() {
  1374  		client := Client(c, &Config{
  1375  			ServerName:   "foo",
  1376  			CipherSuites: []uint16{TLS_RSA_WITH_AES_128_GCM_SHA256},
  1377  		})
  1378  		errChan <- client.Handshake()
  1379  	}()
  1380  
  1381  	var header [5]byte
  1382  	if _, err := io.ReadFull(s, header[:]); err != nil {
  1383  		t.Fatal(err)
  1384  	}
  1385  	recordLen := int(header[3])<<8 | int(header[4])
  1386  
  1387  	record := make([]byte, recordLen)
  1388  	if _, err := io.ReadFull(s, record); err != nil {
  1389  		t.Fatal(err)
  1390  	}
  1391  
  1392  	// Create a ServerHello that selects a different cipher suite than the
  1393  	// sole one that the client offered.
  1394  	serverHello := &serverHelloMsg{
  1395  		vers:        VersionTLS12,
  1396  		random:      make([]byte, 32),
  1397  		cipherSuite: TLS_RSA_WITH_AES_256_GCM_SHA384,
  1398  	}
  1399  	serverHelloBytes := serverHello.marshal()
  1400  
  1401  	s.Write([]byte{
  1402  		byte(recordTypeHandshake),
  1403  		byte(VersionTLS12 >> 8),
  1404  		byte(VersionTLS12 & 0xff),
  1405  		byte(len(serverHelloBytes) >> 8),
  1406  		byte(len(serverHelloBytes)),
  1407  	})
  1408  	s.Write(serverHelloBytes)
  1409  	s.Close()
  1410  
  1411  	if err := <-errChan; !strings.Contains(err.Error(), "unconfigured cipher") {
  1412  		t.Fatalf("Expected error about unconfigured cipher suite but got %q", err)
  1413  	}
  1414  }
  1415  
  1416  func TestVerifyPeerCertificate(t *testing.T) {
  1417  	t.Run("TLSv12", func(t *testing.T) { testVerifyPeerCertificate(t, VersionTLS12) })
  1418  	t.Run("TLSv13", func(t *testing.T) { testVerifyPeerCertificate(t, VersionTLS13) })
  1419  }
  1420  
  1421  func testVerifyPeerCertificate(t *testing.T, version uint16) {
  1422  	issuer, err := x509.ParseCertificate(testRSACertificateIssuer)
  1423  	if err != nil {
  1424  		panic(err)
  1425  	}
  1426  
  1427  	rootCAs := x509.NewCertPool()
  1428  	rootCAs.AddCert(issuer)
  1429  
  1430  	now := func() time.Time { return time.Unix(1476984729, 0) }
  1431  
  1432  	sentinelErr := errors.New("TestVerifyPeerCertificate")
  1433  
  1434  	verifyCallback := func(called *bool, rawCerts [][]byte, validatedChains [][]*x509.Certificate) error {
  1435  		if l := len(rawCerts); l != 1 {
  1436  			return fmt.Errorf("got len(rawCerts) = %d, wanted 1", l)
  1437  		}
  1438  		if len(validatedChains) == 0 {
  1439  			return errors.New("got len(validatedChains) = 0, wanted non-zero")
  1440  		}
  1441  		*called = true
  1442  		return nil
  1443  	}
  1444  
  1445  	tests := []struct {
  1446  		configureServer func(*Config, *bool)
  1447  		configureClient func(*Config, *bool)
  1448  		validate        func(t *testing.T, testNo int, clientCalled, serverCalled bool, clientErr, serverErr error)
  1449  	}{
  1450  		{
  1451  			configureServer: func(config *Config, called *bool) {
  1452  				config.InsecureSkipVerify = false
  1453  				config.VerifyPeerCertificate = func(rawCerts [][]byte, validatedChains [][]*x509.Certificate) error {
  1454  					return verifyCallback(called, rawCerts, validatedChains)
  1455  				}
  1456  			},
  1457  			configureClient: func(config *Config, called *bool) {
  1458  				config.InsecureSkipVerify = false
  1459  				config.VerifyPeerCertificate = func(rawCerts [][]byte, validatedChains [][]*x509.Certificate) error {
  1460  					return verifyCallback(called, rawCerts, validatedChains)
  1461  				}
  1462  			},
  1463  			validate: func(t *testing.T, testNo int, clientCalled, serverCalled bool, clientErr, serverErr error) {
  1464  				if clientErr != nil {
  1465  					t.Errorf("test[%d]: client handshake failed: %v", testNo, clientErr)
  1466  				}
  1467  				if serverErr != nil {
  1468  					t.Errorf("test[%d]: server handshake failed: %v", testNo, serverErr)
  1469  				}
  1470  				if !clientCalled {
  1471  					t.Errorf("test[%d]: client did not call callback", testNo)
  1472  				}
  1473  				if !serverCalled {
  1474  					t.Errorf("test[%d]: server did not call callback", testNo)
  1475  				}
  1476  			},
  1477  		},
  1478  		{
  1479  			configureServer: func(config *Config, called *bool) {
  1480  				config.InsecureSkipVerify = false
  1481  				config.VerifyPeerCertificate = func(rawCerts [][]byte, validatedChains [][]*x509.Certificate) error {
  1482  					return sentinelErr
  1483  				}
  1484  			},
  1485  			configureClient: func(config *Config, called *bool) {
  1486  				config.VerifyPeerCertificate = nil
  1487  			},
  1488  			validate: func(t *testing.T, testNo int, clientCalled, serverCalled bool, clientErr, serverErr error) {
  1489  				if serverErr != sentinelErr {
  1490  					t.Errorf("#%d: got server error %v, wanted sentinelErr", testNo, serverErr)
  1491  				}
  1492  			},
  1493  		},
  1494  		{
  1495  			configureServer: func(config *Config, called *bool) {
  1496  				config.InsecureSkipVerify = false
  1497  			},
  1498  			configureClient: func(config *Config, called *bool) {
  1499  				config.VerifyPeerCertificate = func(rawCerts [][]byte, validatedChains [][]*x509.Certificate) error {
  1500  					return sentinelErr
  1501  				}
  1502  			},
  1503  			validate: func(t *testing.T, testNo int, clientCalled, serverCalled bool, clientErr, serverErr error) {
  1504  				if clientErr != sentinelErr {
  1505  					t.Errorf("#%d: got client error %v, wanted sentinelErr", testNo, clientErr)
  1506  				}
  1507  			},
  1508  		},
  1509  		{
  1510  			configureServer: func(config *Config, called *bool) {
  1511  				config.InsecureSkipVerify = false
  1512  			},
  1513  			configureClient: func(config *Config, called *bool) {
  1514  				config.InsecureSkipVerify = true
  1515  				config.VerifyPeerCertificate = func(rawCerts [][]byte, validatedChains [][]*x509.Certificate) error {
  1516  					if l := len(rawCerts); l != 1 {
  1517  						return fmt.Errorf("got len(rawCerts) = %d, wanted 1", l)
  1518  					}
  1519  					// With InsecureSkipVerify set, this
  1520  					// callback should still be called but
  1521  					// validatedChains must be empty.
  1522  					if l := len(validatedChains); l != 0 {
  1523  						return fmt.Errorf("got len(validatedChains) = %d, wanted zero", l)
  1524  					}
  1525  					*called = true
  1526  					return nil
  1527  				}
  1528  			},
  1529  			validate: func(t *testing.T, testNo int, clientCalled, serverCalled bool, clientErr, serverErr error) {
  1530  				if clientErr != nil {
  1531  					t.Errorf("test[%d]: client handshake failed: %v", testNo, clientErr)
  1532  				}
  1533  				if serverErr != nil {
  1534  					t.Errorf("test[%d]: server handshake failed: %v", testNo, serverErr)
  1535  				}
  1536  				if !clientCalled {
  1537  					t.Errorf("test[%d]: client did not call callback", testNo)
  1538  				}
  1539  			},
  1540  		},
  1541  	}
  1542  
  1543  	for i, test := range tests {
  1544  		c, s := localPipe(t)
  1545  		done := make(chan error)
  1546  
  1547  		var clientCalled, serverCalled bool
  1548  
  1549  		go func() {
  1550  			config := testConfig.Clone()
  1551  			config.ServerName = "example.golang"
  1552  			config.ClientAuth = RequireAndVerifyClientCert
  1553  			config.ClientCAs = rootCAs
  1554  			config.Time = now
  1555  			config.MaxVersion = version
  1556  			test.configureServer(config, &serverCalled)
  1557  
  1558  			err = Server(s, config).Handshake()
  1559  			s.Close()
  1560  			done <- err
  1561  		}()
  1562  
  1563  		config := testConfig.Clone()
  1564  		config.ServerName = "example.golang"
  1565  		config.RootCAs = rootCAs
  1566  		config.Time = now
  1567  		config.MaxVersion = version
  1568  		test.configureClient(config, &clientCalled)
  1569  		clientErr := Client(c, config).Handshake()
  1570  		c.Close()
  1571  		serverErr := <-done
  1572  
  1573  		test.validate(t, i, clientCalled, serverCalled, clientErr, serverErr)
  1574  	}
  1575  }
  1576  
  1577  // brokenConn wraps a net.Conn and causes all Writes after a certain number to
  1578  // fail with brokenConnErr.
  1579  type brokenConn struct {
  1580  	net.Conn
  1581  
  1582  	// breakAfter is the number of successful writes that will be allowed
  1583  	// before all subsequent writes fail.
  1584  	breakAfter int
  1585  
  1586  	// numWrites is the number of writes that have been done.
  1587  	numWrites int
  1588  }
  1589  
  1590  // brokenConnErr is the error that brokenConn returns once exhausted.
  1591  var brokenConnErr = errors.New("too many writes to brokenConn")
  1592  
  1593  func (b *brokenConn) Write(data []byte) (int, error) {
  1594  	if b.numWrites >= b.breakAfter {
  1595  		return 0, brokenConnErr
  1596  	}
  1597  
  1598  	b.numWrites++
  1599  	return b.Conn.Write(data)
  1600  }
  1601  
  1602  func TestFailedWrite(t *testing.T) {
  1603  	// Test that a write error during the handshake is returned.
  1604  	for _, breakAfter := range []int{0, 1} {
  1605  		c, s := localPipe(t)
  1606  		done := make(chan bool)
  1607  
  1608  		go func() {
  1609  			Server(s, testConfig).Handshake()
  1610  			s.Close()
  1611  			done <- true
  1612  		}()
  1613  
  1614  		brokenC := &brokenConn{Conn: c, breakAfter: breakAfter}
  1615  		err := Client(brokenC, testConfig).Handshake()
  1616  		if err != brokenConnErr {
  1617  			t.Errorf("#%d: expected error from brokenConn but got %q", breakAfter, err)
  1618  		}
  1619  		brokenC.Close()
  1620  
  1621  		<-done
  1622  	}
  1623  }
  1624  
  1625  // writeCountingConn wraps a net.Conn and counts the number of Write calls.
  1626  type writeCountingConn struct {
  1627  	net.Conn
  1628  
  1629  	// numWrites is the number of writes that have been done.
  1630  	numWrites int
  1631  }
  1632  
  1633  func (wcc *writeCountingConn) Write(data []byte) (int, error) {
  1634  	wcc.numWrites++
  1635  	return wcc.Conn.Write(data)
  1636  }
  1637  
  1638  func TestBuffering(t *testing.T) {
  1639  	t.Run("TLSv12", func(t *testing.T) { testBuffering(t, VersionTLS12) })
  1640  	t.Run("TLSv13", func(t *testing.T) { testBuffering(t, VersionTLS13) })
  1641  }
  1642  
  1643  func testBuffering(t *testing.T, version uint16) {
  1644  	c, s := localPipe(t)
  1645  	done := make(chan bool)
  1646  
  1647  	clientWCC := &writeCountingConn{Conn: c}
  1648  	serverWCC := &writeCountingConn{Conn: s}
  1649  
  1650  	go func() {
  1651  		config := testConfig.Clone()
  1652  		config.MaxVersion = version
  1653  		Server(serverWCC, config).Handshake()
  1654  		serverWCC.Close()
  1655  		done <- true
  1656  	}()
  1657  
  1658  	err := Client(clientWCC, testConfig).Handshake()
  1659  	if err != nil {
  1660  		t.Fatal(err)
  1661  	}
  1662  	clientWCC.Close()
  1663  	<-done
  1664  
  1665  	var expectedClient, expectedServer int
  1666  	if version == VersionTLS13 {
  1667  		expectedClient = 2
  1668  		expectedServer = 1
  1669  	} else {
  1670  		expectedClient = 2
  1671  		expectedServer = 2
  1672  	}
  1673  
  1674  	if n := clientWCC.numWrites; n != expectedClient {
  1675  		t.Errorf("expected client handshake to complete with %d writes, but saw %d", expectedClient, n)
  1676  	}
  1677  
  1678  	if n := serverWCC.numWrites; n != expectedServer {
  1679  		t.Errorf("expected server handshake to complete with %d writes, but saw %d", expectedServer, n)
  1680  	}
  1681  }
  1682  
  1683  func TestAlertFlushing(t *testing.T) {
  1684  	c, s := localPipe(t)
  1685  	done := make(chan bool)
  1686  
  1687  	clientWCC := &writeCountingConn{Conn: c}
  1688  	serverWCC := &writeCountingConn{Conn: s}
  1689  
  1690  	serverConfig := testConfig.Clone()
  1691  
  1692  	// Cause a signature-time error
  1693  	brokenKey := rsa.PrivateKey{PublicKey: testRSAPrivateKey.PublicKey}
  1694  	brokenKey.D = big.NewInt(42)
  1695  	serverConfig.Certificates = []Certificate{{
  1696  		Certificate: [][]byte{testRSACertificate},
  1697  		PrivateKey:  &brokenKey,
  1698  	}}
  1699  
  1700  	go func() {
  1701  		Server(serverWCC, serverConfig).Handshake()
  1702  		serverWCC.Close()
  1703  		done <- true
  1704  	}()
  1705  
  1706  	err := Client(clientWCC, testConfig).Handshake()
  1707  	if err == nil {
  1708  		t.Fatal("client unexpectedly returned no error")
  1709  	}
  1710  
  1711  	const expectedError = "remote error: tls: internal error"
  1712  	if e := err.Error(); !strings.Contains(e, expectedError) {
  1713  		t.Fatalf("expected to find %q in error but error was %q", expectedError, e)
  1714  	}
  1715  	clientWCC.Close()
  1716  	<-done
  1717  
  1718  	if n := serverWCC.numWrites; n != 1 {
  1719  		t.Errorf("expected server handshake to complete with one write, but saw %d", n)
  1720  	}
  1721  }
  1722  
  1723  func TestHandshakeRace(t *testing.T) {
  1724  	if testing.Short() {
  1725  		t.Skip("skipping in -short mode")
  1726  	}
  1727  	t.Parallel()
  1728  	// This test races a Read and Write to try and complete a handshake in
  1729  	// order to provide some evidence that there are no races or deadlocks
  1730  	// in the handshake locking.
  1731  	for i := 0; i < 32; i++ {
  1732  		c, s := localPipe(t)
  1733  
  1734  		go func() {
  1735  			server := Server(s, testConfig)
  1736  			if err := server.Handshake(); err != nil {
  1737  				panic(err)
  1738  			}
  1739  
  1740  			var request [1]byte
  1741  			if n, err := server.Read(request[:]); err != nil || n != 1 {
  1742  				panic(err)
  1743  			}
  1744  
  1745  			server.Write(request[:])
  1746  			server.Close()
  1747  		}()
  1748  
  1749  		startWrite := make(chan struct{})
  1750  		startRead := make(chan struct{})
  1751  		readDone := make(chan struct{})
  1752  
  1753  		client := Client(c, testConfig)
  1754  		go func() {
  1755  			<-startWrite
  1756  			var request [1]byte
  1757  			client.Write(request[:])
  1758  		}()
  1759  
  1760  		go func() {
  1761  			<-startRead
  1762  			var reply [1]byte
  1763  			if _, err := io.ReadFull(client, reply[:]); err != nil {
  1764  				panic(err)
  1765  			}
  1766  			c.Close()
  1767  			readDone <- struct{}{}
  1768  		}()
  1769  
  1770  		if i&1 == 1 {
  1771  			startWrite <- struct{}{}
  1772  			startRead <- struct{}{}
  1773  		} else {
  1774  			startRead <- struct{}{}
  1775  			startWrite <- struct{}{}
  1776  		}
  1777  		<-readDone
  1778  	}
  1779  }
  1780  
  1781  var getClientCertificateTests = []struct {
  1782  	setup               func(*Config, *Config)
  1783  	expectedClientError string
  1784  	verify              func(*testing.T, int, *ConnectionState)
  1785  }{
  1786  	{
  1787  		func(clientConfig, serverConfig *Config) {
  1788  			// Returning a Certificate with no certificate data
  1789  			// should result in an empty message being sent to the
  1790  			// server.
  1791  			serverConfig.ClientCAs = nil
  1792  			clientConfig.GetClientCertificate = func(cri *CertificateRequestInfo) (*Certificate, error) {
  1793  				if len(cri.SignatureSchemes) == 0 {
  1794  					panic("empty SignatureSchemes")
  1795  				}
  1796  				if len(cri.AcceptableCAs) != 0 {
  1797  					panic("AcceptableCAs should have been empty")
  1798  				}
  1799  				return new(Certificate), nil
  1800  			}
  1801  		},
  1802  		"",
  1803  		func(t *testing.T, testNum int, cs *ConnectionState) {
  1804  			if l := len(cs.PeerCertificates); l != 0 {
  1805  				t.Errorf("#%d: expected no certificates but got %d", testNum, l)
  1806  			}
  1807  		},
  1808  	},
  1809  	{
  1810  		func(clientConfig, serverConfig *Config) {
  1811  			// With TLS 1.1, the SignatureSchemes should be
  1812  			// synthesised from the supported certificate types.
  1813  			clientConfig.MaxVersion = VersionTLS11
  1814  			clientConfig.GetClientCertificate = func(cri *CertificateRequestInfo) (*Certificate, error) {
  1815  				if len(cri.SignatureSchemes) == 0 {
  1816  					panic("empty SignatureSchemes")
  1817  				}
  1818  				return new(Certificate), nil
  1819  			}
  1820  		},
  1821  		"",
  1822  		func(t *testing.T, testNum int, cs *ConnectionState) {
  1823  			if l := len(cs.PeerCertificates); l != 0 {
  1824  				t.Errorf("#%d: expected no certificates but got %d", testNum, l)
  1825  			}
  1826  		},
  1827  	},
  1828  	{
  1829  		func(clientConfig, serverConfig *Config) {
  1830  			// Returning an error should abort the handshake with
  1831  			// that error.
  1832  			clientConfig.GetClientCertificate = func(cri *CertificateRequestInfo) (*Certificate, error) {
  1833  				return nil, errors.New("GetClientCertificate")
  1834  			}
  1835  		},
  1836  		"GetClientCertificate",
  1837  		func(t *testing.T, testNum int, cs *ConnectionState) {
  1838  		},
  1839  	},
  1840  	{
  1841  		func(clientConfig, serverConfig *Config) {
  1842  			clientConfig.GetClientCertificate = func(cri *CertificateRequestInfo) (*Certificate, error) {
  1843  				if len(cri.AcceptableCAs) == 0 {
  1844  					panic("empty AcceptableCAs")
  1845  				}
  1846  				cert := &Certificate{
  1847  					Certificate: [][]byte{testRSACertificate},
  1848  					PrivateKey:  testRSAPrivateKey,
  1849  				}
  1850  				return cert, nil
  1851  			}
  1852  		},
  1853  		"",
  1854  		func(t *testing.T, testNum int, cs *ConnectionState) {
  1855  			if len(cs.VerifiedChains) == 0 {
  1856  				t.Errorf("#%d: expected some verified chains, but found none", testNum)
  1857  			}
  1858  		},
  1859  	},
  1860  }
  1861  
  1862  func TestGetClientCertificate(t *testing.T) {
  1863  	t.Run("TLSv12", func(t *testing.T) { testGetClientCertificate(t, VersionTLS12) })
  1864  	t.Run("TLSv13", func(t *testing.T) { testGetClientCertificate(t, VersionTLS13) })
  1865  }
  1866  
  1867  func testGetClientCertificate(t *testing.T, version uint16) {
  1868  	issuer, err := x509.ParseCertificate(testRSACertificateIssuer)
  1869  	if err != nil {
  1870  		panic(err)
  1871  	}
  1872  
  1873  	for i, test := range getClientCertificateTests {
  1874  		serverConfig := testConfig.Clone()
  1875  		serverConfig.ClientAuth = VerifyClientCertIfGiven
  1876  		serverConfig.RootCAs = x509.NewCertPool()
  1877  		serverConfig.RootCAs.AddCert(issuer)
  1878  		serverConfig.ClientCAs = serverConfig.RootCAs
  1879  		serverConfig.Time = func() time.Time { return time.Unix(1476984729, 0) }
  1880  		serverConfig.MaxVersion = version
  1881  
  1882  		clientConfig := testConfig.Clone()
  1883  		clientConfig.MaxVersion = version
  1884  
  1885  		test.setup(clientConfig, serverConfig)
  1886  
  1887  		type serverResult struct {
  1888  			cs  ConnectionState
  1889  			err error
  1890  		}
  1891  
  1892  		c, s := localPipe(t)
  1893  		done := make(chan serverResult)
  1894  
  1895  		go func() {
  1896  			defer s.Close()
  1897  			server := Server(s, serverConfig)
  1898  			err := server.Handshake()
  1899  
  1900  			var cs ConnectionState
  1901  			if err == nil {
  1902  				cs = server.ConnectionState()
  1903  			}
  1904  			done <- serverResult{cs, err}
  1905  		}()
  1906  
  1907  		clientErr := Client(c, clientConfig).Handshake()
  1908  		c.Close()
  1909  
  1910  		result := <-done
  1911  
  1912  		if clientErr != nil {
  1913  			if len(test.expectedClientError) == 0 {
  1914  				t.Errorf("#%d: client error: %v", i, clientErr)
  1915  			} else if got := clientErr.Error(); got != test.expectedClientError {
  1916  				t.Errorf("#%d: expected client error %q, but got %q", i, test.expectedClientError, got)
  1917  			} else {
  1918  				test.verify(t, i, &result.cs)
  1919  			}
  1920  		} else if len(test.expectedClientError) > 0 {
  1921  			t.Errorf("#%d: expected client error %q, but got no error", i, test.expectedClientError)
  1922  		} else if err := result.err; err != nil {
  1923  			t.Errorf("#%d: server error: %v", i, err)
  1924  		} else {
  1925  			test.verify(t, i, &result.cs)
  1926  		}
  1927  	}
  1928  }
  1929  
  1930  func TestRSAPSSKeyError(t *testing.T) {
  1931  	// crypto/tls does not support the rsa_pss_pss_* SignatureSchemes. If support for
  1932  	// public keys with OID RSASSA-PSS is added to crypto/x509, they will be misused with
  1933  	// the rsa_pss_rsae_* SignatureSchemes. Assert that RSASSA-PSS certificates don't
  1934  	// parse, or that they don't carry *rsa.PublicKey keys.
  1935  	b, _ := pem.Decode([]byte(`
  1936  -----BEGIN CERTIFICATE-----
  1937  MIIDZTCCAhygAwIBAgIUCF2x0FyTgZG0CC9QTDjGWkB5vgEwPgYJKoZIhvcNAQEK
  1938  MDGgDTALBglghkgBZQMEAgGhGjAYBgkqhkiG9w0BAQgwCwYJYIZIAWUDBAIBogQC
  1939  AgDeMBIxEDAOBgNVBAMMB1JTQS1QU1MwHhcNMTgwNjI3MjI0NDM2WhcNMTgwNzI3
  1940  MjI0NDM2WjASMRAwDgYDVQQDDAdSU0EtUFNTMIIBIDALBgkqhkiG9w0BAQoDggEP
  1941  ADCCAQoCggEBANxDm0f76JdI06YzsjB3AmmjIYkwUEGxePlafmIASFjDZl/elD0Z
  1942  /a7xLX468b0qGxLS5al7XCcEprSdsDR6DF5L520+pCbpfLyPOjuOvGmk9KzVX4x5
  1943  b05YXYuXdsQ0Kjxcx2i3jjCday6scIhMJVgBZxTEyMj1thPQM14SHzKCd/m6HmCL
  1944  QmswpH2yMAAcBRWzRpp/vdH5DeOJEB3aelq7094no731mrLUCHRiZ1htq8BDB3ou
  1945  czwqgwspbqZ4dnMXl2MvfySQ5wJUxQwILbiuAKO2lVVPUbFXHE9pgtznNoPvKwQT
  1946  JNcX8ee8WIZc2SEGzofjk3NpjR+2ADB2u3sCAwEAAaNTMFEwHQYDVR0OBBYEFNEz
  1947  AdyJ2f+fU+vSCS6QzohnOnprMB8GA1UdIwQYMBaAFNEzAdyJ2f+fU+vSCS6Qzohn
  1948  OnprMA8GA1UdEwEB/wQFMAMBAf8wPgYJKoZIhvcNAQEKMDGgDTALBglghkgBZQME
  1949  AgGhGjAYBgkqhkiG9w0BAQgwCwYJYIZIAWUDBAIBogQCAgDeA4IBAQCjEdrR5aab
  1950  sZmCwrMeKidXgfkmWvfuLDE+TCbaqDZp7BMWcMQXT9O0UoUT5kqgKj2ARm2pEW0Z
  1951  H3Z1vj3bbds72qcDIJXp+l0fekyLGeCrX/CbgnMZXEP7+/+P416p34ChR1Wz4dU1
  1952  KD3gdsUuTKKeMUog3plxlxQDhRQmiL25ygH1LmjLd6dtIt0GVRGr8lj3euVeprqZ
  1953  bZ3Uq5eLfsn8oPgfC57gpO6yiN+UURRTlK3bgYvLh4VWB3XXk9UaQZ7Mq1tpXjoD
  1954  HYFybkWzibkZp4WRo+Fa28rirH+/wHt0vfeN7UCceURZEx4JaxIIfe4ku7uDRhJi
  1955  RwBA9Xk1KBNF
  1956  -----END CERTIFICATE-----`))
  1957  	if b == nil {
  1958  		t.Fatal("Failed to decode certificate")
  1959  	}
  1960  	cert, err := x509.ParseCertificate(b.Bytes)
  1961  	if err != nil {
  1962  		return
  1963  	}
  1964  	if _, ok := cert.PublicKey.(*rsa.PublicKey); ok {
  1965  		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")
  1966  	}
  1967  }
  1968  
  1969  func TestCloseClientConnectionOnIdleServer(t *testing.T) {
  1970  	clientConn, serverConn := localPipe(t)
  1971  	client := Client(clientConn, testConfig.Clone())
  1972  	go func() {
  1973  		var b [1]byte
  1974  		serverConn.Read(b[:])
  1975  		client.Close()
  1976  	}()
  1977  	client.SetWriteDeadline(time.Now().Add(time.Minute))
  1978  	err := client.Handshake()
  1979  	if err != nil {
  1980  		if err, ok := err.(net.Error); ok && err.Timeout() {
  1981  			t.Errorf("Expected a closed network connection error but got '%s'", err.Error())
  1982  		}
  1983  	} else {
  1984  		t.Errorf("Error expected, but no error returned")
  1985  	}
  1986  }