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

View as plain text