Source file src/crypto/tls/handshake_server_test.go

     1  // Copyright 2009 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"
    11  	"crypto/ecdh"
    12  	"crypto/elliptic"
    13  	"crypto/rand"
    14  	"crypto/tls/internal/fips140tls"
    15  	"crypto/x509"
    16  	"encoding/pem"
    17  	"errors"
    18  	"fmt"
    19  	"io"
    20  	"net"
    21  	"os"
    22  	"os/exec"
    23  	"path/filepath"
    24  	"runtime"
    25  	"slices"
    26  	"strings"
    27  	"sync/atomic"
    28  	"testing"
    29  	"time"
    30  )
    31  
    32  func testClientHello(t *testing.T, serverConfig *Config, m handshakeMessage) {
    33  	t.Helper()
    34  	testClientHelloFailure(t, serverConfig, m, "")
    35  }
    36  
    37  // testFatal is a hack to prevent the compiler from complaining that there is a
    38  // call to t.Fatal from a non-test goroutine
    39  func testFatal(t *testing.T, err error) {
    40  	t.Helper()
    41  	t.Fatal(err)
    42  }
    43  
    44  func testClientHelloFailure(t *testing.T, serverConfig *Config, m handshakeMessage, expectedSubStr string) {
    45  	c, s := localPipe(t)
    46  	go func() {
    47  		cli := Client(c, testConfig)
    48  		if ch, ok := m.(*clientHelloMsg); ok {
    49  			cli.vers = ch.vers
    50  		}
    51  		if _, err := cli.writeHandshakeRecord(m, nil); err != nil {
    52  			testFatal(t, err)
    53  		}
    54  		c.Close()
    55  	}()
    56  	ctx := context.Background()
    57  	conn := Server(s, serverConfig)
    58  	ch, ech, err := conn.readClientHello(ctx)
    59  	if conn.vers == VersionTLS13 {
    60  		hs := serverHandshakeStateTLS13{
    61  			c:           conn,
    62  			ctx:         ctx,
    63  			clientHello: ch,
    64  			echContext:  ech,
    65  		}
    66  		if err == nil {
    67  			err = hs.processClientHello()
    68  		}
    69  		if err == nil {
    70  			err = hs.checkForResumption()
    71  		}
    72  		if err == nil {
    73  			err = hs.pickCertificate()
    74  		}
    75  	} else {
    76  		hs := serverHandshakeState{
    77  			c:           conn,
    78  			ctx:         ctx,
    79  			clientHello: ch,
    80  		}
    81  		if err == nil {
    82  			err = hs.processClientHello()
    83  		}
    84  		if err == nil {
    85  			err = hs.pickCipherSuite()
    86  		}
    87  	}
    88  	s.Close()
    89  	t.Helper()
    90  	if len(expectedSubStr) == 0 {
    91  		if err != nil && err != io.EOF {
    92  			t.Errorf("Got error: %s; expected to succeed", err)
    93  		}
    94  	} else if err == nil || !strings.Contains(err.Error(), expectedSubStr) {
    95  		t.Errorf("Got error: %v; expected to match substring '%s'", err, expectedSubStr)
    96  	}
    97  }
    98  
    99  func TestSimpleError(t *testing.T) {
   100  	testClientHelloFailure(t, testConfig, &serverHelloDoneMsg{}, "unexpected handshake message")
   101  }
   102  
   103  var badProtocolVersions = []uint16{0x0000, 0x0005, 0x0100, 0x0105, 0x0200, 0x0205, VersionSSL30}
   104  
   105  func TestRejectBadProtocolVersion(t *testing.T) {
   106  	config := testConfig.Clone()
   107  	config.MinVersion = VersionSSL30
   108  	for _, v := range badProtocolVersions {
   109  		testClientHelloFailure(t, config, &clientHelloMsg{
   110  			vers:   v,
   111  			random: make([]byte, 32),
   112  		}, "unsupported versions")
   113  	}
   114  	testClientHelloFailure(t, config, &clientHelloMsg{
   115  		vers:              VersionTLS12,
   116  		supportedVersions: badProtocolVersions,
   117  		random:            make([]byte, 32),
   118  	}, "unsupported versions")
   119  }
   120  
   121  func TestNoSuiteOverlap(t *testing.T) {
   122  	clientHello := &clientHelloMsg{
   123  		vers:               VersionTLS12,
   124  		random:             make([]byte, 32),
   125  		cipherSuites:       []uint16{0xff00},
   126  		compressionMethods: []uint8{compressionNone},
   127  	}
   128  	testClientHelloFailure(t, testConfig, clientHello, "no cipher suite supported by both client and server")
   129  }
   130  
   131  func TestNoCompressionOverlap(t *testing.T) {
   132  	clientHello := &clientHelloMsg{
   133  		vers:               VersionTLS12,
   134  		random:             make([]byte, 32),
   135  		cipherSuites:       []uint16{TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256},
   136  		compressionMethods: []uint8{0xff},
   137  	}
   138  	testClientHelloFailure(t, testConfig, clientHello, "client does not support uncompressed connections")
   139  }
   140  
   141  func TestNoRC4ByDefault(t *testing.T) {
   142  	clientHello := &clientHelloMsg{
   143  		vers:               VersionTLS12,
   144  		random:             make([]byte, 32),
   145  		cipherSuites:       []uint16{TLS_RSA_WITH_RC4_128_SHA},
   146  		compressionMethods: []uint8{compressionNone},
   147  	}
   148  	serverConfig := testConfig.Clone()
   149  	// Reset the enabled cipher suites to nil in order to test the
   150  	// defaults.
   151  	serverConfig.CipherSuites = nil
   152  	testClientHelloFailure(t, serverConfig, clientHello, "no cipher suite supported by both client and server")
   153  }
   154  
   155  func TestRejectSNIWithTrailingDot(t *testing.T) {
   156  	testClientHelloFailure(t, testConfig, &clientHelloMsg{
   157  		vers:       VersionTLS12,
   158  		random:     make([]byte, 32),
   159  		serverName: "foo.com.",
   160  	}, "decoding message")
   161  }
   162  
   163  func TestDontSelectECDSAWithRSAKey(t *testing.T) {
   164  	// Test that, even when both sides support an ECDSA cipher suite, it
   165  	// won't be selected if the server's private key doesn't support it.
   166  	clientHello := &clientHelloMsg{
   167  		vers:               VersionTLS12,
   168  		random:             make([]byte, 32),
   169  		cipherSuites:       []uint16{TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384},
   170  		compressionMethods: []uint8{compressionNone},
   171  		supportedCurves:    []CurveID{CurveP256},
   172  		supportedPoints:    []uint8{pointFormatUncompressed},
   173  	}
   174  	serverConfig := testConfig.Clone()
   175  	serverConfig.CipherSuites = clientHello.cipherSuites
   176  	serverConfig.Certificates = make([]Certificate, 1)
   177  	serverConfig.Certificates[0].Certificate = [][]byte{testECDSACertificate}
   178  	serverConfig.Certificates[0].PrivateKey = testECDSAPrivateKey
   179  	serverConfig.BuildNameToCertificate()
   180  	// First test that it *does* work when the server's key is ECDSA.
   181  	testClientHello(t, serverConfig, clientHello)
   182  
   183  	// Now test that switching to an RSA key causes the expected error (and
   184  	// not an internal error about a signing failure).
   185  	serverConfig.Certificates = testConfig.Certificates
   186  	testClientHelloFailure(t, serverConfig, clientHello, "no cipher suite supported by both client and server")
   187  }
   188  
   189  func TestDontSelectRSAWithECDSAKey(t *testing.T) {
   190  	// Test that, even when both sides support an RSA cipher suite, it
   191  	// won't be selected if the server's private key doesn't support it.
   192  	clientHello := &clientHelloMsg{
   193  		vers:               VersionTLS12,
   194  		random:             make([]byte, 32),
   195  		cipherSuites:       []uint16{TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256},
   196  		compressionMethods: []uint8{compressionNone},
   197  		supportedCurves:    []CurveID{CurveP256},
   198  		supportedPoints:    []uint8{pointFormatUncompressed},
   199  	}
   200  	serverConfig := testConfig.Clone()
   201  	serverConfig.CipherSuites = clientHello.cipherSuites
   202  	// First test that it *does* work when the server's key is RSA.
   203  	testClientHello(t, serverConfig, clientHello)
   204  
   205  	// Now test that switching to an ECDSA key causes the expected error
   206  	// (and not an internal error about a signing failure).
   207  	serverConfig.Certificates = make([]Certificate, 1)
   208  	serverConfig.Certificates[0].Certificate = [][]byte{testECDSACertificate}
   209  	serverConfig.Certificates[0].PrivateKey = testECDSAPrivateKey
   210  	serverConfig.BuildNameToCertificate()
   211  	testClientHelloFailure(t, serverConfig, clientHello, "no cipher suite supported by both client and server")
   212  }
   213  
   214  func TestRenegotiationExtension(t *testing.T) {
   215  	skipFIPS(t) // #70505
   216  
   217  	clientHello := &clientHelloMsg{
   218  		vers:                         VersionTLS12,
   219  		compressionMethods:           []uint8{compressionNone},
   220  		random:                       make([]byte, 32),
   221  		secureRenegotiationSupported: true,
   222  		cipherSuites:                 []uint16{TLS_RSA_WITH_RC4_128_SHA},
   223  	}
   224  
   225  	bufChan := make(chan []byte, 1)
   226  	c, s := localPipe(t)
   227  
   228  	go func() {
   229  		cli := Client(c, testConfig)
   230  		cli.vers = clientHello.vers
   231  		if _, err := cli.writeHandshakeRecord(clientHello, nil); err != nil {
   232  			testFatal(t, err)
   233  		}
   234  
   235  		buf := make([]byte, 1024)
   236  		n, err := c.Read(buf)
   237  		if err != nil {
   238  			t.Errorf("Server read returned error: %s", err)
   239  		}
   240  		c.Close()
   241  		bufChan <- buf[:n]
   242  	}()
   243  
   244  	Server(s, testConfig).Handshake()
   245  	buf := <-bufChan
   246  
   247  	if len(buf) < 5+4 {
   248  		t.Fatalf("Server returned short message of length %d", len(buf))
   249  	}
   250  	// buf contains a TLS record, with a 5 byte record header and a 4 byte
   251  	// handshake header. The length of the ServerHello is taken from the
   252  	// handshake header.
   253  	serverHelloLen := int(buf[6])<<16 | int(buf[7])<<8 | int(buf[8])
   254  
   255  	var serverHello serverHelloMsg
   256  	// unmarshal expects to be given the handshake header, but
   257  	// serverHelloLen doesn't include it.
   258  	if !serverHello.unmarshal(buf[5 : 9+serverHelloLen]) {
   259  		t.Fatalf("Failed to parse ServerHello")
   260  	}
   261  
   262  	if !serverHello.secureRenegotiationSupported {
   263  		t.Errorf("Secure renegotiation extension was not echoed.")
   264  	}
   265  }
   266  
   267  func TestTLS12OnlyCipherSuites(t *testing.T) {
   268  	skipFIPS(t) // No TLS 1.1 in FIPS mode.
   269  
   270  	// Test that a Server doesn't select a TLS 1.2-only cipher suite when
   271  	// the client negotiates TLS 1.1.
   272  	clientHello := &clientHelloMsg{
   273  		vers:   VersionTLS11,
   274  		random: make([]byte, 32),
   275  		cipherSuites: []uint16{
   276  			// The Server, by default, will use the client's
   277  			// preference order. So the GCM cipher suite
   278  			// will be selected unless it's excluded because
   279  			// of the version in this ClientHello.
   280  			TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
   281  			TLS_RSA_WITH_RC4_128_SHA,
   282  		},
   283  		compressionMethods: []uint8{compressionNone},
   284  		supportedCurves:    []CurveID{CurveP256, CurveP384, CurveP521},
   285  		supportedPoints:    []uint8{pointFormatUncompressed},
   286  	}
   287  
   288  	c, s := localPipe(t)
   289  	replyChan := make(chan any)
   290  	go func() {
   291  		cli := Client(c, testConfig)
   292  		cli.vers = clientHello.vers
   293  		if _, err := cli.writeHandshakeRecord(clientHello, nil); err != nil {
   294  			testFatal(t, err)
   295  		}
   296  		reply, err := cli.readHandshake(nil)
   297  		c.Close()
   298  		if err != nil {
   299  			replyChan <- err
   300  		} else {
   301  			replyChan <- reply
   302  		}
   303  	}()
   304  	config := testConfig.Clone()
   305  	config.CipherSuites = clientHello.cipherSuites
   306  	Server(s, config).Handshake()
   307  	s.Close()
   308  	reply := <-replyChan
   309  	if err, ok := reply.(error); ok {
   310  		t.Fatal(err)
   311  	}
   312  	serverHello, ok := reply.(*serverHelloMsg)
   313  	if !ok {
   314  		t.Fatalf("didn't get ServerHello message in reply. Got %v\n", reply)
   315  	}
   316  	if s := serverHello.cipherSuite; s != TLS_RSA_WITH_RC4_128_SHA {
   317  		t.Fatalf("bad cipher suite from server: %x", s)
   318  	}
   319  }
   320  
   321  func TestTLSPointFormats(t *testing.T) {
   322  	// Test that a Server returns the ec_point_format extension when ECC is
   323  	// negotiated, and not on a RSA handshake or if ec_point_format is missing.
   324  	tests := []struct {
   325  		name                string
   326  		cipherSuites        []uint16
   327  		supportedCurves     []CurveID
   328  		supportedPoints     []uint8
   329  		wantSupportedPoints bool
   330  	}{
   331  		{"ECC", []uint16{TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256}, []CurveID{CurveP256}, []uint8{pointFormatUncompressed}, true},
   332  		{"ECC without ec_point_format", []uint16{TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256}, []CurveID{CurveP256}, nil, false},
   333  		{"ECC with extra values", []uint16{TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256}, []CurveID{CurveP256}, []uint8{13, 37, pointFormatUncompressed, 42}, true},
   334  		{"RSA", []uint16{TLS_RSA_WITH_AES_256_GCM_SHA384}, nil, nil, false},
   335  		{"RSA with ec_point_format", []uint16{TLS_RSA_WITH_AES_256_GCM_SHA384}, nil, []uint8{pointFormatUncompressed}, false},
   336  	}
   337  	for _, tt := range tests {
   338  		// The RSA subtests should be enabled for FIPS 140 required mode: #70505
   339  		if strings.HasPrefix(tt.name, "RSA") && fips140tls.Required() {
   340  			t.Logf("skipping in FIPS mode.")
   341  			continue
   342  		}
   343  		t.Run(tt.name, func(t *testing.T) {
   344  			clientHello := &clientHelloMsg{
   345  				vers:               VersionTLS12,
   346  				random:             make([]byte, 32),
   347  				cipherSuites:       tt.cipherSuites,
   348  				compressionMethods: []uint8{compressionNone},
   349  				supportedCurves:    tt.supportedCurves,
   350  				supportedPoints:    tt.supportedPoints,
   351  			}
   352  
   353  			c, s := localPipe(t)
   354  			replyChan := make(chan any)
   355  			go func() {
   356  				clientConfig := testConfig.Clone()
   357  				clientConfig.Certificates = []Certificate{{Certificate: [][]byte{testRSA2048Certificate}, PrivateKey: testRSA2048PrivateKey}}
   358  				cli := Client(c, clientConfig)
   359  				cli.vers = clientHello.vers
   360  				if _, err := cli.writeHandshakeRecord(clientHello, nil); err != nil {
   361  					testFatal(t, err)
   362  				}
   363  				reply, err := cli.readHandshake(nil)
   364  				c.Close()
   365  				if err != nil {
   366  					replyChan <- err
   367  				} else {
   368  					replyChan <- reply
   369  				}
   370  			}()
   371  			serverConfig := testConfig.Clone()
   372  			serverConfig.Certificates = []Certificate{{Certificate: [][]byte{testRSA2048Certificate}, PrivateKey: testRSA2048PrivateKey}}
   373  			serverConfig.CipherSuites = clientHello.cipherSuites
   374  			Server(s, serverConfig).Handshake()
   375  			s.Close()
   376  			reply := <-replyChan
   377  			if err, ok := reply.(error); ok {
   378  				t.Fatal(err)
   379  			}
   380  			serverHello, ok := reply.(*serverHelloMsg)
   381  			if !ok {
   382  				t.Fatalf("didn't get ServerHello message in reply. Got %v\n", reply)
   383  			}
   384  			if tt.wantSupportedPoints {
   385  				if !bytes.Equal(serverHello.supportedPoints, []uint8{pointFormatUncompressed}) {
   386  					t.Fatal("incorrect ec_point_format extension from server")
   387  				}
   388  			} else {
   389  				if len(serverHello.supportedPoints) != 0 {
   390  					t.Fatalf("unexpected ec_point_format extension from server: %v", serverHello.supportedPoints)
   391  				}
   392  			}
   393  		})
   394  	}
   395  }
   396  
   397  func TestAlertForwarding(t *testing.T) {
   398  	c, s := localPipe(t)
   399  	go func() {
   400  		Client(c, testConfig).sendAlert(alertUnknownCA)
   401  		c.Close()
   402  	}()
   403  
   404  	err := Server(s, testConfig).Handshake()
   405  	s.Close()
   406  	if opErr, ok := errors.AsType[*net.OpError](err); !ok || opErr.Err != error(alertUnknownCA) {
   407  		t.Errorf("Got error: %s; expected: %s", err, error(alertUnknownCA))
   408  	}
   409  }
   410  
   411  func TestClose(t *testing.T) {
   412  	c, s := localPipe(t)
   413  	go c.Close()
   414  
   415  	err := Server(s, testConfig).Handshake()
   416  	s.Close()
   417  	if err != io.EOF {
   418  		t.Errorf("Got error: %s; expected: %s", err, io.EOF)
   419  	}
   420  }
   421  
   422  func TestVersion(t *testing.T) {
   423  	serverConfig := &Config{
   424  		Certificates: testConfig.Certificates,
   425  		MaxVersion:   VersionTLS13,
   426  	}
   427  	clientConfig := &Config{
   428  		InsecureSkipVerify: true,
   429  		MinVersion:         VersionTLS12,
   430  	}
   431  	state, _, err := testHandshake(t, clientConfig, serverConfig)
   432  	if err != nil {
   433  		t.Fatalf("handshake failed: %s", err)
   434  	}
   435  	if state.Version != VersionTLS13 {
   436  		t.Fatalf("incorrect version %x, should be %x", state.Version, VersionTLS11)
   437  	}
   438  
   439  	clientConfig.MinVersion = 0
   440  	serverConfig.MaxVersion = VersionTLS11
   441  	_, _, err = testHandshake(t, clientConfig, serverConfig)
   442  	if err == nil {
   443  		t.Fatalf("expected failure to connect with TLS 1.0/1.1")
   444  	}
   445  }
   446  
   447  func TestCipherSuitePreference(t *testing.T) {
   448  	skipFIPS(t) // No RC4 or CHACHA20_POLY1305 in FIPS mode.
   449  
   450  	serverConfig := &Config{
   451  		CipherSuites: []uint16{TLS_RSA_WITH_RC4_128_SHA, TLS_AES_128_GCM_SHA256,
   452  			TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256},
   453  		Certificates: testConfig.Certificates,
   454  		MaxVersion:   VersionTLS12,
   455  		GetConfigForClient: func(chi *ClientHelloInfo) (*Config, error) {
   456  			if chi.CipherSuites[0] != TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256 {
   457  				t.Error("the advertised order should not depend on Config.CipherSuites")
   458  			}
   459  			if len(chi.CipherSuites) != 2+len(defaultCipherSuitesTLS13) {
   460  				t.Error("the advertised TLS 1.2 suites should be filtered by Config.CipherSuites")
   461  			}
   462  			return nil, nil
   463  		},
   464  	}
   465  	clientConfig := &Config{
   466  		CipherSuites:       []uint16{TLS_RSA_WITH_AES_128_CBC_SHA, TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256},
   467  		InsecureSkipVerify: true,
   468  	}
   469  	state, _, err := testHandshake(t, clientConfig, serverConfig)
   470  	if err != nil {
   471  		t.Fatalf("handshake failed: %s", err)
   472  	}
   473  	if state.CipherSuite != TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256 {
   474  		t.Error("the preference order should not depend on Config.CipherSuites")
   475  	}
   476  }
   477  
   478  func TestSCTHandshake(t *testing.T) {
   479  	t.Run("TLSv12", func(t *testing.T) { testSCTHandshake(t, VersionTLS12) })
   480  	t.Run("TLSv13", func(t *testing.T) { testSCTHandshake(t, VersionTLS13) })
   481  }
   482  
   483  func testSCTHandshake(t *testing.T, version uint16) {
   484  	expected := [][]byte{[]byte("certificate"), []byte("transparency")}
   485  	serverConfig := &Config{
   486  		Certificates: []Certificate{{
   487  			Certificate:                 [][]byte{testRSACertificate},
   488  			PrivateKey:                  testRSAPrivateKey,
   489  			SignedCertificateTimestamps: expected,
   490  		}},
   491  		MaxVersion: version,
   492  	}
   493  	clientConfig := &Config{
   494  		InsecureSkipVerify: true,
   495  	}
   496  	_, state, err := testHandshake(t, clientConfig, serverConfig)
   497  	if err != nil {
   498  		t.Fatalf("handshake failed: %s", err)
   499  	}
   500  	actual := state.SignedCertificateTimestamps
   501  	if len(actual) != len(expected) {
   502  		t.Fatalf("got %d scts, want %d", len(actual), len(expected))
   503  	}
   504  	for i, sct := range expected {
   505  		if !bytes.Equal(sct, actual[i]) {
   506  			t.Fatalf("SCT #%d was %x, but expected %x", i, actual[i], sct)
   507  		}
   508  	}
   509  }
   510  
   511  func TestCrossVersionResume(t *testing.T) {
   512  	t.Run("TLSv12", func(t *testing.T) { testCrossVersionResume(t, VersionTLS12) })
   513  	t.Run("TLSv13", func(t *testing.T) { testCrossVersionResume(t, VersionTLS13) })
   514  }
   515  
   516  func testCrossVersionResume(t *testing.T, version uint16) {
   517  	serverConfig := &Config{
   518  		CipherSuites: []uint16{TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256},
   519  		Certificates: testConfig.Certificates,
   520  		Time:         testTime,
   521  	}
   522  	clientConfig := &Config{
   523  		CipherSuites:       []uint16{TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256},
   524  		InsecureSkipVerify: true,
   525  		ClientSessionCache: NewLRUClientSessionCache(1),
   526  		ServerName:         "servername",
   527  		MinVersion:         VersionTLS12,
   528  		Time:               testTime,
   529  	}
   530  
   531  	// Establish a session at TLS 1.3.
   532  	clientConfig.MaxVersion = VersionTLS13
   533  	_, _, err := testHandshake(t, clientConfig, serverConfig)
   534  	if err != nil {
   535  		t.Fatalf("handshake failed: %s", err)
   536  	}
   537  
   538  	// The client session cache now contains a TLS 1.3 session.
   539  	state, _, err := testHandshake(t, clientConfig, serverConfig)
   540  	if err != nil {
   541  		t.Fatalf("handshake failed: %s", err)
   542  	}
   543  	if !state.DidResume {
   544  		t.Fatalf("handshake did not resume at the same version")
   545  	}
   546  
   547  	// Test that the server will decline to resume at a lower version.
   548  	clientConfig.MaxVersion = VersionTLS12
   549  	state, _, err = testHandshake(t, clientConfig, serverConfig)
   550  	if err != nil {
   551  		t.Fatalf("handshake failed: %s", err)
   552  	}
   553  	if state.DidResume {
   554  		t.Fatalf("handshake resumed at a lower version")
   555  	}
   556  
   557  	// The client session cache now contains a TLS 1.2 session.
   558  	state, _, err = testHandshake(t, clientConfig, serverConfig)
   559  	if err != nil {
   560  		t.Fatalf("handshake failed: %s", err)
   561  	}
   562  	if !state.DidResume {
   563  		t.Fatalf("handshake did not resume at the same version")
   564  	}
   565  
   566  	// Test that the server will decline to resume at a higher version.
   567  	clientConfig.MaxVersion = VersionTLS13
   568  	state, _, err = testHandshake(t, clientConfig, serverConfig)
   569  	if err != nil {
   570  		t.Fatalf("handshake failed: %s", err)
   571  	}
   572  	if state.DidResume {
   573  		t.Fatalf("handshake resumed at a higher version")
   574  	}
   575  }
   576  
   577  // Note: see comment in handshake_test.go for details of how the reference
   578  // tests work.
   579  
   580  // serverTest represents a test of the TLS server handshake against a reference
   581  // implementation.
   582  type serverTest struct {
   583  	// name is a freeform string identifying the test and the file in which
   584  	// the expected results will be stored.
   585  	name string
   586  	// command, if not empty, contains a series of arguments for the
   587  	// command to run for the reference server.
   588  	command []string
   589  	// expectedPeerCerts contains a list of PEM blocks of expected
   590  	// certificates from the client.
   591  	expectedPeerCerts []string
   592  	// config, if not nil, contains a custom Config to use for this test.
   593  	config *Config
   594  	// expectHandshakeErrorIncluding, when not empty, contains a string
   595  	// that must be a substring of the error resulting from the handshake.
   596  	expectHandshakeErrorIncluding string
   597  	// validate, if not nil, is a function that will be called with the
   598  	// ConnectionState of the resulting connection. It returns false if the
   599  	// ConnectionState is unacceptable.
   600  	validate func(ConnectionState) error
   601  	// wait, if true, prevents this subtest from calling t.Parallel.
   602  	// If false, runServerTest* returns immediately.
   603  	wait bool
   604  }
   605  
   606  var defaultClientCommand = []string{"openssl", "s_client", "-no_ticket"}
   607  
   608  // connFromCommand starts opens a listening socket and starts the reference
   609  // client to connect to it. It returns a recordingConn that wraps the resulting
   610  // connection.
   611  func (test *serverTest) connFromCommand() (conn *recordingConn, child *exec.Cmd, err error) {
   612  	l, err := net.ListenTCP("tcp", &net.TCPAddr{
   613  		IP:   net.IPv4(127, 0, 0, 1),
   614  		Port: 0,
   615  	})
   616  	if err != nil {
   617  		return nil, nil, err
   618  	}
   619  	defer l.Close()
   620  
   621  	port := l.Addr().(*net.TCPAddr).Port
   622  
   623  	var command []string
   624  	command = append(command, test.command...)
   625  	if len(command) == 0 {
   626  		command = defaultClientCommand
   627  	}
   628  	command = append(command, "-connect")
   629  	command = append(command, fmt.Sprintf("127.0.0.1:%d", port))
   630  	cmd := exec.Command(command[0], command[1:]...)
   631  	cmd.Stdin = nil
   632  	var output bytes.Buffer
   633  	cmd.Stdout = &output
   634  	cmd.Stderr = &output
   635  	if err := cmd.Start(); err != nil {
   636  		return nil, nil, err
   637  	}
   638  
   639  	connChan := make(chan any, 1)
   640  	go func() {
   641  		tcpConn, err := l.Accept()
   642  		if err != nil {
   643  			connChan <- err
   644  			return
   645  		}
   646  		connChan <- tcpConn
   647  	}()
   648  
   649  	var tcpConn net.Conn
   650  	select {
   651  	case connOrError := <-connChan:
   652  		if err, ok := connOrError.(error); ok {
   653  			return nil, nil, err
   654  		}
   655  		tcpConn = connOrError.(net.Conn)
   656  	case <-time.After(2 * time.Second):
   657  		return nil, nil, errors.New("timed out waiting for connection from child process")
   658  	}
   659  
   660  	record := &recordingConn{
   661  		Conn: tcpConn,
   662  	}
   663  
   664  	return record, cmd, nil
   665  }
   666  
   667  func (test *serverTest) dataPath() string {
   668  	return filepath.Join("testdata", "Server-"+test.name)
   669  }
   670  
   671  func (test *serverTest) loadData() (flows [][]byte, err error) {
   672  	in, err := os.Open(test.dataPath())
   673  	if err != nil {
   674  		return nil, err
   675  	}
   676  	defer in.Close()
   677  	return parseTestData(in)
   678  }
   679  
   680  func (test *serverTest) run(t *testing.T, write bool) {
   681  	var serverConn net.Conn
   682  	var recordingConn *recordingConn
   683  	var childProcess *exec.Cmd
   684  
   685  	if write {
   686  		var err error
   687  		recordingConn, childProcess, err = test.connFromCommand()
   688  		if err != nil {
   689  			t.Fatalf("Failed to start subcommand: %s", err)
   690  		}
   691  		serverConn = recordingConn
   692  		defer func() {
   693  			if t.Failed() {
   694  				t.Logf("OpenSSL output:\n\n%s", childProcess.Stdout)
   695  			}
   696  		}()
   697  	} else {
   698  		flows, err := test.loadData()
   699  		if err != nil {
   700  			t.Fatalf("Failed to load data from %s", test.dataPath())
   701  		}
   702  		serverConn = &replayingConn{t: t, flows: flows, reading: true}
   703  	}
   704  	config := test.config
   705  	if config == nil {
   706  		config = testConfig
   707  	}
   708  	server := Server(serverConn, config)
   709  
   710  	_, err := server.Write([]byte("hello, world\n"))
   711  	if len(test.expectHandshakeErrorIncluding) > 0 {
   712  		if err == nil {
   713  			t.Errorf("Error expected, but no error returned")
   714  		} else if s := err.Error(); !strings.Contains(s, test.expectHandshakeErrorIncluding) {
   715  			t.Errorf("Error expected containing '%s' but got '%s'", test.expectHandshakeErrorIncluding, s)
   716  		}
   717  	} else {
   718  		if err != nil {
   719  			t.Logf("Error from Server.Write: '%s'", err)
   720  		}
   721  	}
   722  	server.Close()
   723  
   724  	connState := server.ConnectionState()
   725  	peerCerts := connState.PeerCertificates
   726  	if len(peerCerts) == len(test.expectedPeerCerts) {
   727  		for i, peerCert := range peerCerts {
   728  			block, _ := pem.Decode([]byte(test.expectedPeerCerts[i]))
   729  			if !bytes.Equal(block.Bytes, peerCert.Raw) {
   730  				t.Fatalf("%s: mismatch on peer cert %d", test.name, i+1)
   731  			}
   732  		}
   733  	} else {
   734  		t.Fatalf("%s: mismatch on peer list length: %d (wanted) != %d (got)", test.name, len(test.expectedPeerCerts), len(peerCerts))
   735  	}
   736  
   737  	if test.validate != nil && !t.Failed() {
   738  		if err := test.validate(connState); err != nil {
   739  			t.Fatalf("validate callback returned error: %s", err)
   740  		}
   741  	}
   742  
   743  	if write {
   744  		serverConn.Close()
   745  		path := test.dataPath()
   746  		out, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644)
   747  		if err != nil {
   748  			t.Fatalf("Failed to create output file: %s", err)
   749  		}
   750  		defer out.Close()
   751  		recordingConn.Close()
   752  		if len(recordingConn.flows) < 3 {
   753  			if len(test.expectHandshakeErrorIncluding) == 0 {
   754  				t.Fatalf("Handshake failed")
   755  			}
   756  		}
   757  		recordingConn.WriteTo(out)
   758  		t.Logf("Wrote %s\n", path)
   759  		childProcess.Wait()
   760  	}
   761  }
   762  
   763  func runServerTestForVersion(t *testing.T, template *serverTest, version, option string) {
   764  	// Make a deep copy of the template before going parallel.
   765  	test := *template
   766  	if template.config != nil {
   767  		test.config = template.config.Clone()
   768  	}
   769  	test.name = version + "-" + test.name
   770  	if len(test.command) == 0 {
   771  		test.command = defaultClientCommand
   772  	}
   773  	test.command = append([]string(nil), test.command...)
   774  	test.command = append(test.command, option)
   775  
   776  	runTestAndUpdateIfNeeded(t, version, test.run, test.wait)
   777  }
   778  
   779  func runServerTestTLS10(t *testing.T, template *serverTest) {
   780  	runServerTestForVersion(t, template, "TLSv10", "-tls1")
   781  }
   782  
   783  func runServerTestTLS11(t *testing.T, template *serverTest) {
   784  	runServerTestForVersion(t, template, "TLSv11", "-tls1_1")
   785  }
   786  
   787  func runServerTestTLS12(t *testing.T, template *serverTest) {
   788  	runServerTestForVersion(t, template, "TLSv12", "-tls1_2")
   789  }
   790  
   791  func runServerTestTLS13(t *testing.T, template *serverTest) {
   792  	runServerTestForVersion(t, template, "TLSv13", "-tls1_3")
   793  }
   794  
   795  func TestHandshakeServerRSARC4(t *testing.T) {
   796  	test := &serverTest{
   797  		name:    "RSA-RC4",
   798  		command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "RC4-SHA"},
   799  	}
   800  	runServerTestTLS10(t, test)
   801  	runServerTestTLS11(t, test)
   802  	runServerTestTLS12(t, test)
   803  }
   804  
   805  func TestHandshakeServerRSA3DES(t *testing.T) {
   806  	test := &serverTest{
   807  		name:    "RSA-3DES",
   808  		command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "DES-CBC3-SHA"},
   809  	}
   810  	runServerTestTLS10(t, test)
   811  	runServerTestTLS12(t, test)
   812  }
   813  
   814  func TestHandshakeServerRSAAES(t *testing.T) {
   815  	test := &serverTest{
   816  		name:    "RSA-AES",
   817  		command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "AES128-SHA"},
   818  	}
   819  	runServerTestTLS10(t, test)
   820  	runServerTestTLS12(t, test)
   821  }
   822  
   823  func TestHandshakeServerAESGCM(t *testing.T) {
   824  	test := &serverTest{
   825  		name:    "RSA-AES-GCM",
   826  		command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "ECDHE-RSA-AES128-GCM-SHA256"},
   827  	}
   828  	runServerTestTLS12(t, test)
   829  }
   830  
   831  func TestHandshakeServerAES256GCMSHA384(t *testing.T) {
   832  	test := &serverTest{
   833  		name:    "RSA-AES256-GCM-SHA384",
   834  		command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "ECDHE-RSA-AES256-GCM-SHA384"},
   835  	}
   836  	runServerTestTLS12(t, test)
   837  }
   838  
   839  func TestHandshakeServerAES128SHA256(t *testing.T) {
   840  	test := &serverTest{
   841  		name:    "AES128-SHA256",
   842  		command: []string{"openssl", "s_client", "-no_ticket", "-ciphersuites", "TLS_AES_128_GCM_SHA256"},
   843  	}
   844  	runServerTestTLS13(t, test)
   845  }
   846  func TestHandshakeServerAES256SHA384(t *testing.T) {
   847  	test := &serverTest{
   848  		name:    "AES256-SHA384",
   849  		command: []string{"openssl", "s_client", "-no_ticket", "-ciphersuites", "TLS_AES_256_GCM_SHA384"},
   850  	}
   851  	runServerTestTLS13(t, test)
   852  }
   853  func TestHandshakeServerCHACHA20SHA256(t *testing.T) {
   854  	test := &serverTest{
   855  		name:    "CHACHA20-SHA256",
   856  		command: []string{"openssl", "s_client", "-no_ticket", "-ciphersuites", "TLS_CHACHA20_POLY1305_SHA256"},
   857  	}
   858  	runServerTestTLS13(t, test)
   859  }
   860  
   861  func TestHandshakeServerECDHEECDSAAES(t *testing.T) {
   862  	config := testConfig.Clone()
   863  	config.Certificates = make([]Certificate, 1)
   864  	config.Certificates[0].Certificate = [][]byte{testECDSACertificate}
   865  	config.Certificates[0].PrivateKey = testECDSAPrivateKey
   866  	config.BuildNameToCertificate()
   867  
   868  	test := &serverTest{
   869  		name:    "ECDHE-ECDSA-AES",
   870  		command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "ECDHE-ECDSA-AES256-SHA", "-ciphersuites", "TLS_AES_128_GCM_SHA256"},
   871  		config:  config,
   872  	}
   873  	runServerTestTLS10(t, test)
   874  	runServerTestTLS12(t, test)
   875  	runServerTestTLS13(t, test)
   876  }
   877  
   878  func TestHandshakeServerX25519(t *testing.T) {
   879  	config := testConfig.Clone()
   880  	config.CurvePreferences = []CurveID{X25519}
   881  
   882  	test := &serverTest{
   883  		name:    "X25519",
   884  		command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "ECDHE-RSA-CHACHA20-POLY1305", "-ciphersuites", "TLS_CHACHA20_POLY1305_SHA256", "-curves", "X25519"},
   885  		config:  config,
   886  	}
   887  	runServerTestTLS12(t, test)
   888  	runServerTestTLS13(t, test)
   889  }
   890  
   891  func TestHandshakeServerP256(t *testing.T) {
   892  	config := testConfig.Clone()
   893  	config.CurvePreferences = []CurveID{CurveP256}
   894  
   895  	test := &serverTest{
   896  		name:    "P256",
   897  		command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "ECDHE-RSA-CHACHA20-POLY1305", "-ciphersuites", "TLS_CHACHA20_POLY1305_SHA256", "-curves", "P-256"},
   898  		config:  config,
   899  	}
   900  	runServerTestTLS12(t, test)
   901  	runServerTestTLS13(t, test)
   902  }
   903  
   904  func TestHandshakeServerHelloRetryRequest(t *testing.T) {
   905  	config := testConfig.Clone()
   906  	config.CurvePreferences = []CurveID{CurveP256}
   907  
   908  	test := &serverTest{
   909  		name:    "HelloRetryRequest",
   910  		command: []string{"openssl", "s_client", "-no_ticket", "-ciphersuites", "TLS_CHACHA20_POLY1305_SHA256", "-curves", "X25519:P-256"},
   911  		config:  config,
   912  		validate: func(cs ConnectionState) error {
   913  			if !cs.testingOnlyDidHRR {
   914  				return errors.New("expected HelloRetryRequest")
   915  			}
   916  			return nil
   917  		},
   918  	}
   919  	runServerTestTLS13(t, test)
   920  }
   921  
   922  // TestHandshakeServerKeySharePreference checks that we prefer a key share even
   923  // if it's later in the CurvePreferences order.
   924  func TestHandshakeServerKeySharePreference(t *testing.T) {
   925  	config := testConfig.Clone()
   926  	config.CurvePreferences = []CurveID{X25519, CurveP256}
   927  
   928  	test := &serverTest{
   929  		name:    "KeySharePreference",
   930  		command: []string{"openssl", "s_client", "-no_ticket", "-ciphersuites", "TLS_CHACHA20_POLY1305_SHA256", "-curves", "P-256:X25519"},
   931  		config:  config,
   932  		validate: func(cs ConnectionState) error {
   933  			if cs.testingOnlyDidHRR {
   934  				return errors.New("unexpected HelloRetryRequest")
   935  			}
   936  			return nil
   937  		},
   938  	}
   939  	runServerTestTLS13(t, test)
   940  }
   941  
   942  func TestHandshakeServerALPN(t *testing.T) {
   943  	config := testConfig.Clone()
   944  	config.NextProtos = []string{"proto1", "proto2"}
   945  
   946  	test := &serverTest{
   947  		name: "ALPN",
   948  		// Note that this needs OpenSSL 1.0.2 because that is the first
   949  		// version that supports the -alpn flag.
   950  		command: []string{"openssl", "s_client", "-alpn", "proto2,proto1", "-cipher", "ECDHE-RSA-CHACHA20-POLY1305", "-ciphersuites", "TLS_CHACHA20_POLY1305_SHA256"},
   951  		config:  config,
   952  		validate: func(state ConnectionState) error {
   953  			// The server's preferences should override the client.
   954  			if state.NegotiatedProtocol != "proto1" {
   955  				return fmt.Errorf("Got protocol %q, wanted proto1", state.NegotiatedProtocol)
   956  			}
   957  			return nil
   958  		},
   959  	}
   960  	runServerTestTLS12(t, test)
   961  	runServerTestTLS13(t, test)
   962  }
   963  
   964  func TestHandshakeServerALPNNoMatch(t *testing.T) {
   965  	config := testConfig.Clone()
   966  	config.NextProtos = []string{"proto3"}
   967  
   968  	test := &serverTest{
   969  		name: "ALPN-NoMatch",
   970  		// Note that this needs OpenSSL 1.0.2 because that is the first
   971  		// version that supports the -alpn flag.
   972  		command:                       []string{"openssl", "s_client", "-alpn", "proto2,proto1", "-cipher", "ECDHE-RSA-CHACHA20-POLY1305", "-ciphersuites", "TLS_CHACHA20_POLY1305_SHA256"},
   973  		config:                        config,
   974  		expectHandshakeErrorIncluding: "client requested unsupported application protocol",
   975  	}
   976  	runServerTestTLS12(t, test)
   977  	runServerTestTLS13(t, test)
   978  }
   979  
   980  func TestHandshakeServerALPNNotConfigured(t *testing.T) {
   981  	config := testConfig.Clone()
   982  	config.NextProtos = nil
   983  
   984  	test := &serverTest{
   985  		name: "ALPN-NotConfigured",
   986  		// Note that this needs OpenSSL 1.0.2 because that is the first
   987  		// version that supports the -alpn flag.
   988  		command: []string{"openssl", "s_client", "-alpn", "proto2,proto1", "-cipher", "ECDHE-RSA-CHACHA20-POLY1305", "-ciphersuites", "TLS_CHACHA20_POLY1305_SHA256"},
   989  		config:  config,
   990  		validate: func(state ConnectionState) error {
   991  			if state.NegotiatedProtocol != "" {
   992  				return fmt.Errorf("Got protocol %q, wanted nothing", state.NegotiatedProtocol)
   993  			}
   994  			return nil
   995  		},
   996  	}
   997  	runServerTestTLS12(t, test)
   998  	runServerTestTLS13(t, test)
   999  }
  1000  
  1001  func TestHandshakeServerALPNFallback(t *testing.T) {
  1002  	config := testConfig.Clone()
  1003  	config.NextProtos = []string{"proto1", "h2", "proto2"}
  1004  
  1005  	test := &serverTest{
  1006  		name: "ALPN-Fallback",
  1007  		// Note that this needs OpenSSL 1.0.2 because that is the first
  1008  		// version that supports the -alpn flag.
  1009  		command: []string{"openssl", "s_client", "-alpn", "proto3,http/1.1,proto4", "-cipher", "ECDHE-RSA-CHACHA20-POLY1305", "-ciphersuites", "TLS_CHACHA20_POLY1305_SHA256"},
  1010  		config:  config,
  1011  		validate: func(state ConnectionState) error {
  1012  			if state.NegotiatedProtocol != "" {
  1013  				return fmt.Errorf("Got protocol %q, wanted nothing", state.NegotiatedProtocol)
  1014  			}
  1015  			return nil
  1016  		},
  1017  	}
  1018  	runServerTestTLS12(t, test)
  1019  	runServerTestTLS13(t, test)
  1020  }
  1021  
  1022  // TestHandshakeServerSNI involves a client sending an SNI extension of
  1023  // "snitest.com", which happens to match the CN of testSNICertificate. The test
  1024  // verifies that the server correctly selects that certificate.
  1025  func TestHandshakeServerSNI(t *testing.T) {
  1026  	test := &serverTest{
  1027  		name:    "SNI",
  1028  		command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "AES128-SHA", "-servername", "snitest.com"},
  1029  	}
  1030  	runServerTestTLS12(t, test)
  1031  }
  1032  
  1033  // TestHandshakeServerSNIGetCertificate is similar to TestHandshakeServerSNI, but
  1034  // tests the dynamic GetCertificate method
  1035  func TestHandshakeServerSNIGetCertificate(t *testing.T) {
  1036  	config := testConfig.Clone()
  1037  
  1038  	// Replace the NameToCertificate map with a GetCertificate function
  1039  	nameToCert := config.NameToCertificate
  1040  	config.NameToCertificate = nil
  1041  	config.GetCertificate = func(clientHello *ClientHelloInfo) (*Certificate, error) {
  1042  		cert := nameToCert[clientHello.ServerName]
  1043  		return cert, nil
  1044  	}
  1045  	test := &serverTest{
  1046  		name:    "SNI-GetCertificate",
  1047  		command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "AES128-SHA", "-servername", "snitest.com"},
  1048  		config:  config,
  1049  	}
  1050  	runServerTestTLS12(t, test)
  1051  }
  1052  
  1053  // TestHandshakeServerSNIGetCertificateNotFound is similar to
  1054  // TestHandshakeServerSNICertForName, but tests to make sure that when the
  1055  // GetCertificate method doesn't return a cert, we fall back to what's in
  1056  // the NameToCertificate map.
  1057  func TestHandshakeServerSNIGetCertificateNotFound(t *testing.T) {
  1058  	config := testConfig.Clone()
  1059  
  1060  	config.GetCertificate = func(clientHello *ClientHelloInfo) (*Certificate, error) {
  1061  		return nil, nil
  1062  	}
  1063  	test := &serverTest{
  1064  		name:    "SNI-GetCertificateNotFound",
  1065  		command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "AES128-SHA", "-servername", "snitest.com"},
  1066  		config:  config,
  1067  	}
  1068  	runServerTestTLS12(t, test)
  1069  }
  1070  
  1071  // TestHandshakeServerGetCertificateExtensions tests to make sure that the
  1072  // Extensions passed to GetCertificate match what we expect based on the
  1073  // clientHelloMsg
  1074  func TestHandshakeServerGetCertificateExtensions(t *testing.T) {
  1075  	const errMsg = "TestHandshakeServerGetCertificateExtensions error"
  1076  	// ensure the test condition inside our GetCertificate callback
  1077  	// is actually invoked
  1078  	var called atomic.Int32
  1079  
  1080  	testVersions := []uint16{VersionTLS12, VersionTLS13}
  1081  	for _, vers := range testVersions {
  1082  		t.Run(fmt.Sprintf("TLS version %04x", vers), func(t *testing.T) {
  1083  			pk, _ := ecdh.P256().GenerateKey(rand.Reader)
  1084  			clientHello := &clientHelloMsg{
  1085  				vers:                         vers,
  1086  				random:                       make([]byte, 32),
  1087  				cipherSuites:                 []uint16{TLS_AES_128_GCM_SHA256},
  1088  				compressionMethods:           []uint8{compressionNone},
  1089  				serverName:                   "test",
  1090  				keyShares:                    []keyShare{{group: CurveP256, data: pk.PublicKey().Bytes()}},
  1091  				supportedCurves:              []CurveID{CurveP256},
  1092  				supportedSignatureAlgorithms: []SignatureScheme{ECDSAWithP256AndSHA256},
  1093  			}
  1094  
  1095  			// the clientHelloMsg initialized just above is serialized with
  1096  			// two extensions: server_name(0) and application_layer_protocol_negotiation(16)
  1097  			expectedExtensions := []uint16{
  1098  				extensionServerName,
  1099  				extensionSupportedCurves,
  1100  				extensionSignatureAlgorithms,
  1101  				extensionKeyShare,
  1102  			}
  1103  
  1104  			if vers == VersionTLS13 {
  1105  				clientHello.supportedVersions = []uint16{VersionTLS13}
  1106  				expectedExtensions = append(expectedExtensions, extensionSupportedVersions)
  1107  			}
  1108  
  1109  			// Go's TLS client presents extensions in the ClientHello sorted by extension ID
  1110  			slices.Sort(expectedExtensions)
  1111  
  1112  			serverConfig := testConfig.Clone()
  1113  			serverConfig.GetCertificate = func(clientHello *ClientHelloInfo) (*Certificate, error) {
  1114  				if !slices.Equal(expectedExtensions, clientHello.Extensions) {
  1115  					t.Errorf("expected extensions on ClientHelloInfo (%v) to match clientHelloMsg (%v)", expectedExtensions, clientHello.Extensions)
  1116  				}
  1117  				called.Add(1)
  1118  
  1119  				return nil, errors.New(errMsg)
  1120  			}
  1121  			testClientHelloFailure(t, serverConfig, clientHello, errMsg)
  1122  		})
  1123  	}
  1124  
  1125  	if int(called.Load()) != len(testVersions) {
  1126  		t.Error("expected our GetCertificate test to be called twice")
  1127  	}
  1128  }
  1129  
  1130  // TestHandshakeServerSNIGetCertificateError tests to make sure that errors in
  1131  // GetCertificate result in a tls alert.
  1132  func TestHandshakeServerSNIGetCertificateError(t *testing.T) {
  1133  	const errMsg = "TestHandshakeServerSNIGetCertificateError error"
  1134  
  1135  	serverConfig := testConfig.Clone()
  1136  	serverConfig.GetCertificate = func(clientHello *ClientHelloInfo) (*Certificate, error) {
  1137  		return nil, errors.New(errMsg)
  1138  	}
  1139  
  1140  	clientHello := &clientHelloMsg{
  1141  		vers:               VersionTLS12,
  1142  		random:             make([]byte, 32),
  1143  		cipherSuites:       []uint16{TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256},
  1144  		compressionMethods: []uint8{compressionNone},
  1145  		serverName:         "test",
  1146  	}
  1147  	testClientHelloFailure(t, serverConfig, clientHello, errMsg)
  1148  }
  1149  
  1150  // TestHandshakeServerEmptyCertificates tests that GetCertificates is called in
  1151  // the case that Certificates is empty, even without SNI.
  1152  func TestHandshakeServerEmptyCertificates(t *testing.T) {
  1153  	const errMsg = "TestHandshakeServerEmptyCertificates error"
  1154  
  1155  	serverConfig := testConfig.Clone()
  1156  	serverConfig.GetCertificate = func(clientHello *ClientHelloInfo) (*Certificate, error) {
  1157  		return nil, errors.New(errMsg)
  1158  	}
  1159  	serverConfig.Certificates = nil
  1160  
  1161  	clientHello := &clientHelloMsg{
  1162  		vers:               VersionTLS12,
  1163  		random:             make([]byte, 32),
  1164  		cipherSuites:       []uint16{TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256},
  1165  		compressionMethods: []uint8{compressionNone},
  1166  	}
  1167  	testClientHelloFailure(t, serverConfig, clientHello, errMsg)
  1168  
  1169  	// With an empty Certificates and a nil GetCertificate, the server
  1170  	// should always return a “no certificates” error.
  1171  	serverConfig.GetCertificate = nil
  1172  
  1173  	clientHello = &clientHelloMsg{
  1174  		vers:               VersionTLS12,
  1175  		random:             make([]byte, 32),
  1176  		cipherSuites:       []uint16{TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256},
  1177  		compressionMethods: []uint8{compressionNone},
  1178  	}
  1179  	testClientHelloFailure(t, serverConfig, clientHello, "no certificates")
  1180  }
  1181  
  1182  func TestServerResumption(t *testing.T) {
  1183  	sessionFilePath := tempFile("")
  1184  	defer os.Remove(sessionFilePath)
  1185  
  1186  	testIssue := &serverTest{
  1187  		name:    "IssueTicket",
  1188  		command: []string{"openssl", "s_client", "-cipher", "AES128-SHA", "-ciphersuites", "TLS_AES_128_GCM_SHA256", "-sess_out", sessionFilePath},
  1189  		wait:    true,
  1190  	}
  1191  	testResume := &serverTest{
  1192  		name:    "Resume",
  1193  		command: []string{"openssl", "s_client", "-cipher", "AES128-SHA", "-ciphersuites", "TLS_AES_128_GCM_SHA256", "-sess_in", sessionFilePath},
  1194  		validate: func(state ConnectionState) error {
  1195  			if !state.DidResume {
  1196  				return errors.New("did not resume")
  1197  			}
  1198  			return nil
  1199  		},
  1200  	}
  1201  
  1202  	runServerTestTLS12(t, testIssue)
  1203  	runServerTestTLS12(t, testResume)
  1204  
  1205  	runServerTestTLS13(t, testIssue)
  1206  	runServerTestTLS13(t, testResume)
  1207  
  1208  	config := testConfig.Clone()
  1209  	config.CurvePreferences = []CurveID{CurveP256}
  1210  
  1211  	testResumeHRR := &serverTest{
  1212  		name: "Resume-HelloRetryRequest",
  1213  		command: []string{"openssl", "s_client", "-curves", "X25519:P-256", "-cipher", "AES128-SHA", "-ciphersuites",
  1214  			"TLS_AES_128_GCM_SHA256", "-sess_in", sessionFilePath},
  1215  		config: config,
  1216  		validate: func(state ConnectionState) error {
  1217  			if !state.DidResume {
  1218  				return errors.New("did not resume")
  1219  			}
  1220  			return nil
  1221  		},
  1222  	}
  1223  
  1224  	runServerTestTLS13(t, testResumeHRR)
  1225  }
  1226  
  1227  func TestServerResumptionDisabled(t *testing.T) {
  1228  	sessionFilePath := tempFile("")
  1229  	defer os.Remove(sessionFilePath)
  1230  
  1231  	config := testConfig.Clone()
  1232  
  1233  	testIssue := &serverTest{
  1234  		name:    "IssueTicketPreDisable",
  1235  		command: []string{"openssl", "s_client", "-cipher", "AES128-SHA", "-ciphersuites", "TLS_AES_128_GCM_SHA256", "-sess_out", sessionFilePath},
  1236  		config:  config,
  1237  		wait:    true,
  1238  	}
  1239  	testResume := &serverTest{
  1240  		name:    "ResumeDisabled",
  1241  		command: []string{"openssl", "s_client", "-cipher", "AES128-SHA", "-ciphersuites", "TLS_AES_128_GCM_SHA256", "-sess_in", sessionFilePath},
  1242  		config:  config,
  1243  		validate: func(state ConnectionState) error {
  1244  			if state.DidResume {
  1245  				return errors.New("resumed with SessionTicketsDisabled")
  1246  			}
  1247  			return nil
  1248  		},
  1249  	}
  1250  
  1251  	config.SessionTicketsDisabled = false
  1252  	runServerTestTLS12(t, testIssue)
  1253  	config.SessionTicketsDisabled = true
  1254  	runServerTestTLS12(t, testResume)
  1255  
  1256  	config.SessionTicketsDisabled = false
  1257  	runServerTestTLS13(t, testIssue)
  1258  	config.SessionTicketsDisabled = true
  1259  	runServerTestTLS13(t, testResume)
  1260  }
  1261  
  1262  func TestFallbackSCSV(t *testing.T) {
  1263  	serverConfig := Config{
  1264  		Certificates: testConfig.Certificates,
  1265  		MinVersion:   VersionTLS11,
  1266  	}
  1267  	test := &serverTest{
  1268  		name:   "FallbackSCSV",
  1269  		config: &serverConfig,
  1270  		// OpenSSL 1.0.1j is needed for the -fallback_scsv option.
  1271  		command:                       []string{"openssl", "s_client", "-fallback_scsv"},
  1272  		expectHandshakeErrorIncluding: "inappropriate protocol fallback",
  1273  	}
  1274  	runServerTestTLS11(t, test)
  1275  }
  1276  
  1277  func TestHandshakeServerExportKeyingMaterial(t *testing.T) {
  1278  	test := &serverTest{
  1279  		name:    "ExportKeyingMaterial",
  1280  		command: []string{"openssl", "s_client", "-cipher", "ECDHE-RSA-AES256-SHA", "-ciphersuites", "TLS_CHACHA20_POLY1305_SHA256"},
  1281  		config:  testConfig.Clone(),
  1282  		validate: func(state ConnectionState) error {
  1283  			if km, err := state.ExportKeyingMaterial("test", nil, 42); err != nil {
  1284  				return fmt.Errorf("ExportKeyingMaterial failed: %v", err)
  1285  			} else if len(km) != 42 {
  1286  				return fmt.Errorf("Got %d bytes from ExportKeyingMaterial, wanted %d", len(km), 42)
  1287  			}
  1288  			return nil
  1289  		},
  1290  	}
  1291  	runServerTestTLS10(t, test)
  1292  	runServerTestTLS12(t, test)
  1293  	runServerTestTLS13(t, test)
  1294  }
  1295  
  1296  func TestHandshakeServerRSAPKCS1v15(t *testing.T) {
  1297  	test := &serverTest{
  1298  		name:    "RSA-RSAPKCS1v15",
  1299  		command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "ECDHE-RSA-CHACHA20-POLY1305", "-sigalgs", "rsa_pkcs1_sha256"},
  1300  	}
  1301  	runServerTestTLS12(t, test)
  1302  }
  1303  
  1304  func TestHandshakeServerRSAPSS(t *testing.T) {
  1305  	// We send rsa_pss_rsae_sha512 first, as the test key won't fit, and we
  1306  	// verify the server implementation will disregard the client preference in
  1307  	// that case. See Issue 29793.
  1308  	test := &serverTest{
  1309  		name:    "RSA-RSAPSS",
  1310  		command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "ECDHE-RSA-CHACHA20-POLY1305", "-ciphersuites", "TLS_CHACHA20_POLY1305_SHA256", "-sigalgs", "rsa_pss_rsae_sha512:rsa_pss_rsae_sha256"},
  1311  	}
  1312  	runServerTestTLS12(t, test)
  1313  	runServerTestTLS13(t, test)
  1314  
  1315  	test = &serverTest{
  1316  		name:                          "RSA-RSAPSS-TooSmall",
  1317  		command:                       []string{"openssl", "s_client", "-no_ticket", "-ciphersuites", "TLS_CHACHA20_POLY1305_SHA256", "-sigalgs", "rsa_pss_rsae_sha512"},
  1318  		expectHandshakeErrorIncluding: "peer doesn't support any of the certificate's signature algorithms",
  1319  	}
  1320  	runServerTestTLS13(t, test)
  1321  }
  1322  
  1323  func TestHandshakeServerEd25519(t *testing.T) {
  1324  	config := testConfig.Clone()
  1325  	config.Certificates = make([]Certificate, 1)
  1326  	config.Certificates[0].Certificate = [][]byte{testEd25519Certificate}
  1327  	config.Certificates[0].PrivateKey = testEd25519PrivateKey
  1328  	config.BuildNameToCertificate()
  1329  
  1330  	test := &serverTest{
  1331  		name:    "Ed25519",
  1332  		command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "ECDHE-ECDSA-CHACHA20-POLY1305", "-ciphersuites", "TLS_CHACHA20_POLY1305_SHA256"},
  1333  		config:  config,
  1334  	}
  1335  	runServerTestTLS12(t, test)
  1336  	runServerTestTLS13(t, test)
  1337  }
  1338  
  1339  func benchmarkHandshakeServer(b *testing.B, version uint16, cipherSuite uint16, curve CurveID, cert []byte, key crypto.PrivateKey) {
  1340  	config := testConfig.Clone()
  1341  	config.CipherSuites = []uint16{cipherSuite}
  1342  	config.CurvePreferences = []CurveID{curve}
  1343  	config.Certificates = make([]Certificate, 1)
  1344  	config.Certificates[0].Certificate = [][]byte{cert}
  1345  	config.Certificates[0].PrivateKey = key
  1346  	config.BuildNameToCertificate()
  1347  
  1348  	clientConn, serverConn := localPipe(b)
  1349  	serverConn = &recordingConn{Conn: serverConn}
  1350  	go func() {
  1351  		config := testConfig.Clone()
  1352  		config.MaxVersion = version
  1353  		config.CurvePreferences = []CurveID{curve}
  1354  		client := Client(clientConn, config)
  1355  		client.Handshake()
  1356  	}()
  1357  	server := Server(serverConn, config)
  1358  	if err := server.Handshake(); err != nil {
  1359  		b.Fatalf("handshake failed: %v", err)
  1360  	}
  1361  	serverConn.Close()
  1362  	flows := serverConn.(*recordingConn).flows
  1363  
  1364  	b.ResetTimer()
  1365  	for i := 0; i < b.N; i++ {
  1366  		replay := &replayingConn{t: b, flows: slices.Clone(flows), reading: true}
  1367  		server := Server(replay, config)
  1368  		if err := server.Handshake(); err != nil {
  1369  			b.Fatalf("handshake failed: %v", err)
  1370  		}
  1371  	}
  1372  }
  1373  
  1374  func BenchmarkHandshakeServer(b *testing.B) {
  1375  	b.Run("RSA", func(b *testing.B) {
  1376  		benchmarkHandshakeServer(b, VersionTLS12, TLS_RSA_WITH_AES_128_GCM_SHA256,
  1377  			0, testRSACertificate, testRSAPrivateKey)
  1378  	})
  1379  	b.Run("ECDHE-P256-RSA", func(b *testing.B) {
  1380  		b.Run("TLSv13", func(b *testing.B) {
  1381  			benchmarkHandshakeServer(b, VersionTLS13, TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256,
  1382  				CurveP256, testRSACertificate, testRSAPrivateKey)
  1383  		})
  1384  		b.Run("TLSv12", func(b *testing.B) {
  1385  			benchmarkHandshakeServer(b, VersionTLS12, TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256,
  1386  				CurveP256, testRSACertificate, testRSAPrivateKey)
  1387  		})
  1388  	})
  1389  	b.Run("ECDHE-P256-ECDSA-P256", func(b *testing.B) {
  1390  		b.Run("TLSv13", func(b *testing.B) {
  1391  			benchmarkHandshakeServer(b, VersionTLS13, TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256,
  1392  				CurveP256, testP256Certificate, testP256PrivateKey)
  1393  		})
  1394  		b.Run("TLSv12", func(b *testing.B) {
  1395  			benchmarkHandshakeServer(b, VersionTLS12, TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256,
  1396  				CurveP256, testP256Certificate, testP256PrivateKey)
  1397  		})
  1398  	})
  1399  	b.Run("ECDHE-X25519-ECDSA-P256", func(b *testing.B) {
  1400  		b.Run("TLSv13", func(b *testing.B) {
  1401  			benchmarkHandshakeServer(b, VersionTLS13, TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256,
  1402  				X25519, testP256Certificate, testP256PrivateKey)
  1403  		})
  1404  		b.Run("TLSv12", func(b *testing.B) {
  1405  			benchmarkHandshakeServer(b, VersionTLS12, TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256,
  1406  				X25519, testP256Certificate, testP256PrivateKey)
  1407  		})
  1408  	})
  1409  	b.Run("ECDHE-P521-ECDSA-P521", func(b *testing.B) {
  1410  		if testECDSAPrivateKey.PublicKey.Curve != elliptic.P521() {
  1411  			b.Fatal("test ECDSA key doesn't use curve P-521")
  1412  		}
  1413  		b.Run("TLSv13", func(b *testing.B) {
  1414  			benchmarkHandshakeServer(b, VersionTLS13, TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256,
  1415  				CurveP521, testECDSACertificate, testECDSAPrivateKey)
  1416  		})
  1417  		b.Run("TLSv12", func(b *testing.B) {
  1418  			benchmarkHandshakeServer(b, VersionTLS12, TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256,
  1419  				CurveP521, testECDSACertificate, testECDSAPrivateKey)
  1420  		})
  1421  	})
  1422  }
  1423  
  1424  func TestClientAuth(t *testing.T) {
  1425  	var certPath, keyPath, ecdsaCertPath, ecdsaKeyPath, ed25519CertPath, ed25519KeyPath string
  1426  
  1427  	if *update {
  1428  		certPath = tempFile(clientCertificatePEM)
  1429  		defer os.Remove(certPath)
  1430  		keyPath = tempFile(clientKeyPEM)
  1431  		defer os.Remove(keyPath)
  1432  		ecdsaCertPath = tempFile(clientECDSACertificatePEM)
  1433  		defer os.Remove(ecdsaCertPath)
  1434  		ecdsaKeyPath = tempFile(clientECDSAKeyPEM)
  1435  		defer os.Remove(ecdsaKeyPath)
  1436  		ed25519CertPath = tempFile(clientEd25519CertificatePEM)
  1437  		defer os.Remove(ed25519CertPath)
  1438  		ed25519KeyPath = tempFile(clientEd25519KeyPEM)
  1439  		defer os.Remove(ed25519KeyPath)
  1440  	} else {
  1441  		t.Parallel()
  1442  	}
  1443  
  1444  	config := testConfig.Clone()
  1445  	config.ClientAuth = RequestClientCert
  1446  
  1447  	test := &serverTest{
  1448  		name:    "ClientAuthRequestedNotGiven",
  1449  		command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "AES128-SHA", "-ciphersuites", "TLS_AES_128_GCM_SHA256"},
  1450  		config:  config,
  1451  	}
  1452  	runServerTestTLS12(t, test)
  1453  	runServerTestTLS13(t, test)
  1454  
  1455  	test = &serverTest{
  1456  		name: "ClientAuthRequestedAndGiven",
  1457  		command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "AES128-SHA", "-ciphersuites", "TLS_AES_128_GCM_SHA256",
  1458  			"-cert", certPath, "-key", keyPath, "-client_sigalgs", "rsa_pss_rsae_sha256"},
  1459  		config:            config,
  1460  		expectedPeerCerts: []string{clientCertificatePEM},
  1461  	}
  1462  	runServerTestTLS12(t, test)
  1463  	runServerTestTLS13(t, test)
  1464  
  1465  	test = &serverTest{
  1466  		name: "ClientAuthRequestedAndECDSAGiven",
  1467  		command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "AES128-SHA", "-ciphersuites", "TLS_AES_128_GCM_SHA256",
  1468  			"-cert", ecdsaCertPath, "-key", ecdsaKeyPath},
  1469  		config:            config,
  1470  		expectedPeerCerts: []string{clientECDSACertificatePEM},
  1471  	}
  1472  	runServerTestTLS12(t, test)
  1473  	runServerTestTLS13(t, test)
  1474  
  1475  	test = &serverTest{
  1476  		name: "ClientAuthRequestedAndEd25519Given",
  1477  		command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "AES128-SHA", "-ciphersuites", "TLS_AES_128_GCM_SHA256",
  1478  			"-cert", ed25519CertPath, "-key", ed25519KeyPath},
  1479  		config:            config,
  1480  		expectedPeerCerts: []string{clientEd25519CertificatePEM},
  1481  	}
  1482  	runServerTestTLS12(t, test)
  1483  	runServerTestTLS13(t, test)
  1484  
  1485  	test = &serverTest{
  1486  		name: "ClientAuthRequestedAndPKCS1v15Given",
  1487  		command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "AES128-SHA",
  1488  			"-cert", certPath, "-key", keyPath, "-client_sigalgs", "rsa_pkcs1_sha256"},
  1489  		config:            config,
  1490  		expectedPeerCerts: []string{clientCertificatePEM},
  1491  	}
  1492  	runServerTestTLS12(t, test)
  1493  }
  1494  
  1495  func TestSNIGivenOnFailure(t *testing.T) {
  1496  	const expectedServerName = "test.testing"
  1497  
  1498  	clientHello := &clientHelloMsg{
  1499  		vers:               VersionTLS12,
  1500  		random:             make([]byte, 32),
  1501  		cipherSuites:       []uint16{TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256},
  1502  		compressionMethods: []uint8{compressionNone},
  1503  		serverName:         expectedServerName,
  1504  	}
  1505  
  1506  	serverConfig := testConfig.Clone()
  1507  	// Erase the server's cipher suites to ensure the handshake fails.
  1508  	serverConfig.CipherSuites = nil
  1509  
  1510  	c, s := localPipe(t)
  1511  	go func() {
  1512  		cli := Client(c, testConfig)
  1513  		cli.vers = clientHello.vers
  1514  		if _, err := cli.writeHandshakeRecord(clientHello, nil); err != nil {
  1515  			testFatal(t, err)
  1516  		}
  1517  		c.Close()
  1518  	}()
  1519  	conn := Server(s, serverConfig)
  1520  	ctx := context.Background()
  1521  	ch, _, err := conn.readClientHello(ctx)
  1522  	hs := serverHandshakeState{
  1523  		c:           conn,
  1524  		ctx:         ctx,
  1525  		clientHello: ch,
  1526  	}
  1527  	if err == nil {
  1528  		err = hs.processClientHello()
  1529  	}
  1530  	if err == nil {
  1531  		err = hs.pickCipherSuite()
  1532  	}
  1533  	defer s.Close()
  1534  
  1535  	if err == nil {
  1536  		t.Error("No error reported from server")
  1537  	}
  1538  
  1539  	cs := hs.c.ConnectionState()
  1540  	if cs.HandshakeComplete {
  1541  		t.Error("Handshake registered as complete")
  1542  	}
  1543  
  1544  	if cs.ServerName != expectedServerName {
  1545  		t.Errorf("Expected ServerName of %q, but got %q", expectedServerName, cs.ServerName)
  1546  	}
  1547  }
  1548  
  1549  var getConfigForClientTests = []struct {
  1550  	setup          func(config *Config)
  1551  	callback       func(clientHello *ClientHelloInfo) (*Config, error)
  1552  	errorSubstring string
  1553  	verify         func(config *Config) error
  1554  }{
  1555  	{
  1556  		nil,
  1557  		func(clientHello *ClientHelloInfo) (*Config, error) {
  1558  			return nil, nil
  1559  		},
  1560  		"",
  1561  		nil,
  1562  	},
  1563  	{
  1564  		nil,
  1565  		func(clientHello *ClientHelloInfo) (*Config, error) {
  1566  			return nil, errors.New("should bubble up")
  1567  		},
  1568  		"should bubble up",
  1569  		nil,
  1570  	},
  1571  	{
  1572  		nil,
  1573  		func(clientHello *ClientHelloInfo) (*Config, error) {
  1574  			config := testConfig.Clone()
  1575  			// Setting a maximum version of TLS 1.1 should cause
  1576  			// the handshake to fail, as the client MinVersion is TLS 1.2.
  1577  			config.MaxVersion = VersionTLS11
  1578  			return config, nil
  1579  		},
  1580  		"client offered only unsupported versions",
  1581  		nil,
  1582  	},
  1583  	{
  1584  		func(config *Config) {
  1585  			for i := range config.SessionTicketKey {
  1586  				config.SessionTicketKey[i] = byte(i)
  1587  			}
  1588  			config.sessionTicketKeys = nil
  1589  		},
  1590  		func(clientHello *ClientHelloInfo) (*Config, error) {
  1591  			config := testConfig.Clone()
  1592  			clear(config.SessionTicketKey[:])
  1593  			config.sessionTicketKeys = nil
  1594  			return config, nil
  1595  		},
  1596  		"",
  1597  		func(config *Config) error {
  1598  			if config.SessionTicketKey == [32]byte{} {
  1599  				return fmt.Errorf("expected SessionTicketKey to be set")
  1600  			}
  1601  			return nil
  1602  		},
  1603  	},
  1604  	{
  1605  		func(config *Config) {
  1606  			var dummyKey [32]byte
  1607  			for i := range dummyKey {
  1608  				dummyKey[i] = byte(i)
  1609  			}
  1610  
  1611  			config.SetSessionTicketKeys([][32]byte{dummyKey})
  1612  		},
  1613  		func(clientHello *ClientHelloInfo) (*Config, error) {
  1614  			config := testConfig.Clone()
  1615  			config.sessionTicketKeys = nil
  1616  			return config, nil
  1617  		},
  1618  		"",
  1619  		func(config *Config) error {
  1620  			if config.SessionTicketKey == [32]byte{} {
  1621  				return fmt.Errorf("expected SessionTicketKey to be set")
  1622  			}
  1623  			return nil
  1624  		},
  1625  	},
  1626  }
  1627  
  1628  func TestGetConfigForClient(t *testing.T) {
  1629  	serverConfig := testConfig.Clone()
  1630  	clientConfig := testConfig.Clone()
  1631  	clientConfig.MinVersion = VersionTLS12
  1632  
  1633  	for i, test := range getConfigForClientTests {
  1634  		if test.setup != nil {
  1635  			test.setup(serverConfig)
  1636  		}
  1637  
  1638  		var configReturned *Config
  1639  		serverConfig.GetConfigForClient = func(clientHello *ClientHelloInfo) (*Config, error) {
  1640  			config, err := test.callback(clientHello)
  1641  			configReturned = config
  1642  			return config, err
  1643  		}
  1644  		c, s := localPipe(t)
  1645  		done := make(chan error)
  1646  
  1647  		go func() {
  1648  			defer s.Close()
  1649  			done <- Server(s, serverConfig).Handshake()
  1650  		}()
  1651  
  1652  		clientErr := Client(c, clientConfig).Handshake()
  1653  		c.Close()
  1654  
  1655  		serverErr := <-done
  1656  
  1657  		if len(test.errorSubstring) == 0 {
  1658  			if serverErr != nil || clientErr != nil {
  1659  				t.Errorf("test[%d]: expected no error but got serverErr: %q, clientErr: %q", i, serverErr, clientErr)
  1660  			}
  1661  			if test.verify != nil {
  1662  				if err := test.verify(configReturned); err != nil {
  1663  					t.Errorf("test[%d]: verify returned error: %v", i, err)
  1664  				}
  1665  			}
  1666  		} else {
  1667  			if serverErr == nil {
  1668  				t.Errorf("test[%d]: expected error containing %q but got no error", i, test.errorSubstring)
  1669  			} else if !strings.Contains(serverErr.Error(), test.errorSubstring) {
  1670  				t.Errorf("test[%d]: expected error to contain %q but it was %q", i, test.errorSubstring, serverErr)
  1671  			}
  1672  		}
  1673  	}
  1674  }
  1675  
  1676  func TestCloseServerConnectionOnIdleClient(t *testing.T) {
  1677  	clientConn, serverConn := localPipe(t)
  1678  	server := Server(serverConn, testConfig.Clone())
  1679  	go func() {
  1680  		clientConn.Write([]byte{'0'})
  1681  		server.Close()
  1682  	}()
  1683  	server.SetReadDeadline(time.Now().Add(time.Minute))
  1684  	err := server.Handshake()
  1685  	if err != nil {
  1686  		if err, ok := err.(net.Error); ok && err.Timeout() {
  1687  			t.Errorf("Expected a closed network connection error but got '%s'", err.Error())
  1688  		}
  1689  	} else {
  1690  		t.Errorf("Error expected, but no error returned")
  1691  	}
  1692  }
  1693  
  1694  func TestCloneHash(t *testing.T) {
  1695  	h1 := crypto.SHA256.New()
  1696  	h1.Write([]byte("test"))
  1697  	s1 := h1.Sum(nil)
  1698  	h2 := cloneHash(h1, crypto.SHA256)
  1699  	s2 := h2.Sum(nil)
  1700  	if !bytes.Equal(s1, s2) {
  1701  		t.Error("cloned hash generated a different sum")
  1702  	}
  1703  }
  1704  
  1705  func expectError(t *testing.T, err error, sub string) {
  1706  	if err == nil {
  1707  		t.Errorf(`expected error %q, got nil`, sub)
  1708  	} else if !strings.Contains(err.Error(), sub) {
  1709  		t.Errorf(`expected error %q, got %q`, sub, err)
  1710  	}
  1711  }
  1712  
  1713  func TestKeyTooSmallForRSAPSS(t *testing.T) {
  1714  	cert, err := X509KeyPair([]byte(`-----BEGIN CERTIFICATE-----
  1715  MIIBcTCCARugAwIBAgIQGjQnkCFlUqaFlt6ixyz/tDANBgkqhkiG9w0BAQsFADAS
  1716  MRAwDgYDVQQKEwdBY21lIENvMB4XDTE5MDExODIzMjMyOFoXDTIwMDExODIzMjMy
  1717  OFowEjEQMA4GA1UEChMHQWNtZSBDbzBcMA0GCSqGSIb3DQEBAQUAA0sAMEgCQQDd
  1718  ez1rFUDwax2HTxbcnFUP9AhcgEGMHVV2nn4VVEWFJB6I8C/Nkx0XyyQlrmFYBzEQ
  1719  nIPhKls4T0hFoLvjJnXpAgMBAAGjTTBLMA4GA1UdDwEB/wQEAwIFoDATBgNVHSUE
  1720  DDAKBggrBgEFBQcDATAMBgNVHRMBAf8EAjAAMBYGA1UdEQQPMA2CC2V4YW1wbGUu
  1721  Y29tMA0GCSqGSIb3DQEBCwUAA0EAxDuUS+BrrS3c+h+k+fQPOmOScy6yTX9mHw0Q
  1722  KbucGamXYEy0URIwOdO0tQ3LHPc1YGvYSPwkDjkjqECs2Vm/AA==
  1723  -----END CERTIFICATE-----`), []byte(testingKey(`-----BEGIN RSA TESTING KEY-----
  1724  MIIBOgIBAAJBAN17PWsVQPBrHYdPFtycVQ/0CFyAQYwdVXaefhVURYUkHojwL82T
  1725  HRfLJCWuYVgHMRCcg+EqWzhPSEWgu+MmdekCAwEAAQJBALjQYNTdXF4CFBbXwUz/
  1726  yt9QFDYT9B5WT/12jeGAe653gtYS6OOi/+eAkGmzg1GlRnw6fOfn+HYNFDORST7z
  1727  4j0CIQDn2xz9hVWQEu9ee3vecNT3f60huDGTNoRhtqgweQGX0wIhAPSLj1VcRZEz
  1728  nKpbtU22+PbIMSJ+e80fmY9LIPx5N4HTAiAthGSimMR9bloz0EY3GyuUEyqoDgMd
  1729  hXxjuno2WesoJQIgemilbcALXpxsLmZLgcQ2KSmaVr7jb5ECx9R+hYKTw1sCIG4s
  1730  T+E0J8wlH24pgwQHzy7Ko2qLwn1b5PW8ecrlvP1g
  1731  -----END RSA TESTING KEY-----`)))
  1732  	if err != nil {
  1733  		t.Fatal(err)
  1734  	}
  1735  
  1736  	clientConn, serverConn := localPipe(t)
  1737  	client := Client(clientConn, testConfig)
  1738  	done := make(chan struct{})
  1739  	go func() {
  1740  		config := testConfig.Clone()
  1741  		config.Certificates = []Certificate{cert}
  1742  		config.MinVersion = VersionTLS13
  1743  		server := Server(serverConn, config)
  1744  		err := server.Handshake()
  1745  		expectError(t, err, "key size too small")
  1746  		close(done)
  1747  	}()
  1748  	err = client.Handshake()
  1749  	expectError(t, err, "handshake failure")
  1750  	<-done
  1751  }
  1752  
  1753  func TestMultipleCertificates(t *testing.T) {
  1754  	clientConfig := testConfig.Clone()
  1755  	clientConfig.CipherSuites = []uint16{TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256}
  1756  	clientConfig.MaxVersion = VersionTLS12
  1757  
  1758  	serverConfig := testConfig.Clone()
  1759  	serverConfig.Certificates = []Certificate{{
  1760  		Certificate: [][]byte{testECDSACertificate},
  1761  		PrivateKey:  testECDSAPrivateKey,
  1762  	}, {
  1763  		Certificate: [][]byte{testRSACertificate},
  1764  		PrivateKey:  testRSAPrivateKey,
  1765  	}}
  1766  
  1767  	_, clientState, err := testHandshake(t, clientConfig, serverConfig)
  1768  	if err != nil {
  1769  		t.Fatal(err)
  1770  	}
  1771  	if got := clientState.PeerCertificates[0].PublicKeyAlgorithm; got != x509.RSA {
  1772  		t.Errorf("expected RSA certificate, got %v", got)
  1773  	}
  1774  }
  1775  
  1776  func TestAESCipherReordering(t *testing.T) {
  1777  	skipFIPS(t) // No CHACHA20_POLY1305 for FIPS.
  1778  
  1779  	currentAESSupport := hasAESGCMHardwareSupport
  1780  	defer func() { hasAESGCMHardwareSupport = currentAESSupport }()
  1781  
  1782  	tests := []struct {
  1783  		name            string
  1784  		clientCiphers   []uint16
  1785  		serverHasAESGCM bool
  1786  		serverCiphers   []uint16
  1787  		expectedCipher  uint16
  1788  	}{
  1789  		{
  1790  			name: "server has hardware AES, client doesn't (pick ChaCha)",
  1791  			clientCiphers: []uint16{
  1792  				TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256,
  1793  				TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
  1794  				TLS_RSA_WITH_AES_128_CBC_SHA,
  1795  			},
  1796  			serverHasAESGCM: true,
  1797  			expectedCipher:  TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256,
  1798  		},
  1799  		{
  1800  			name: "client prefers AES-GCM, server doesn't have hardware AES (pick ChaCha)",
  1801  			clientCiphers: []uint16{
  1802  				TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
  1803  				TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256,
  1804  				TLS_RSA_WITH_AES_128_CBC_SHA,
  1805  			},
  1806  			serverHasAESGCM: false,
  1807  			expectedCipher:  TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256,
  1808  		},
  1809  		{
  1810  			name: "client prefers AES-GCM, server has hardware AES (pick AES-GCM)",
  1811  			clientCiphers: []uint16{
  1812  				TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
  1813  				TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256,
  1814  				TLS_RSA_WITH_AES_128_CBC_SHA,
  1815  			},
  1816  			serverHasAESGCM: true,
  1817  			expectedCipher:  TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
  1818  		},
  1819  		{
  1820  			name: "client prefers AES-GCM and sends GREASE, server has hardware AES (pick AES-GCM)",
  1821  			clientCiphers: []uint16{
  1822  				0x0A0A, // GREASE value
  1823  				TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
  1824  				TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256,
  1825  				TLS_RSA_WITH_AES_128_CBC_SHA,
  1826  			},
  1827  			serverHasAESGCM: true,
  1828  			expectedCipher:  TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
  1829  		},
  1830  		{
  1831  			name: "client prefers AES-GCM and doesn't support ChaCha, server doesn't have hardware AES (pick AES-GCM)",
  1832  			clientCiphers: []uint16{
  1833  				TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
  1834  				TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
  1835  				TLS_RSA_WITH_AES_128_CBC_SHA,
  1836  			},
  1837  			serverHasAESGCM: false,
  1838  			expectedCipher:  TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
  1839  		},
  1840  		{
  1841  			name: "client prefers AES-GCM and AES-CBC over ChaCha, server doesn't have hardware AES (pick ChaCha)",
  1842  			clientCiphers: []uint16{
  1843  				TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
  1844  				TLS_RSA_WITH_AES_128_CBC_SHA,
  1845  				TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256,
  1846  			},
  1847  			serverHasAESGCM: false,
  1848  			expectedCipher:  TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256,
  1849  		},
  1850  		{
  1851  			name: "client prefers AES-GCM over ChaCha and sends GREASE, server doesn't have hardware AES (pick ChaCha)",
  1852  			clientCiphers: []uint16{
  1853  				0x0A0A, // GREASE value
  1854  				TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
  1855  				TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256,
  1856  				TLS_RSA_WITH_AES_128_CBC_SHA,
  1857  			},
  1858  			serverHasAESGCM: false,
  1859  			expectedCipher:  TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256,
  1860  		},
  1861  		{
  1862  			name: "client supports multiple AES-GCM, server doesn't have hardware AES and doesn't support ChaCha (AES-GCM)",
  1863  			clientCiphers: []uint16{
  1864  				TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
  1865  				TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256,
  1866  				TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
  1867  			},
  1868  			serverHasAESGCM: false,
  1869  			serverCiphers: []uint16{
  1870  				TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
  1871  				TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
  1872  			},
  1873  			expectedCipher: TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
  1874  		},
  1875  		{
  1876  			name: "client prefers AES-GCM, server has hardware but doesn't support AES (pick ChaCha)",
  1877  			clientCiphers: []uint16{
  1878  				TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
  1879  				TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256,
  1880  				TLS_RSA_WITH_AES_128_CBC_SHA,
  1881  			},
  1882  			serverHasAESGCM: true,
  1883  			serverCiphers: []uint16{
  1884  				TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256,
  1885  			},
  1886  			expectedCipher: TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256,
  1887  		},
  1888  	}
  1889  
  1890  	for _, tc := range tests {
  1891  		t.Run(tc.name, func(t *testing.T) {
  1892  			hasAESGCMHardwareSupport = tc.serverHasAESGCM
  1893  			hs := &serverHandshakeState{
  1894  				c: &Conn{
  1895  					config: &Config{
  1896  						CipherSuites: tc.serverCiphers,
  1897  					},
  1898  					vers: VersionTLS12,
  1899  				},
  1900  				clientHello: &clientHelloMsg{
  1901  					cipherSuites: tc.clientCiphers,
  1902  					vers:         VersionTLS12,
  1903  				},
  1904  				ecdheOk:      true,
  1905  				rsaSignOk:    true,
  1906  				rsaDecryptOk: true,
  1907  			}
  1908  
  1909  			err := hs.pickCipherSuite()
  1910  			if err != nil {
  1911  				t.Errorf("pickCipherSuite failed: %s", err)
  1912  			}
  1913  
  1914  			if tc.expectedCipher != hs.suite.id {
  1915  				t.Errorf("unexpected cipher chosen: want %d, got %d", tc.expectedCipher, hs.suite.id)
  1916  			}
  1917  		})
  1918  	}
  1919  }
  1920  
  1921  func TestAESCipherReorderingTLS13(t *testing.T) {
  1922  	skipFIPS(t) // No CHACHA20_POLY1305 for FIPS.
  1923  
  1924  	currentAESSupport := hasAESGCMHardwareSupport
  1925  	defer func() { hasAESGCMHardwareSupport = currentAESSupport }()
  1926  
  1927  	tests := []struct {
  1928  		name            string
  1929  		clientCiphers   []uint16
  1930  		serverHasAESGCM bool
  1931  		expectedCipher  uint16
  1932  	}{
  1933  		{
  1934  			name: "server has hardware AES, client doesn't (pick ChaCha)",
  1935  			clientCiphers: []uint16{
  1936  				TLS_CHACHA20_POLY1305_SHA256,
  1937  				TLS_AES_128_GCM_SHA256,
  1938  			},
  1939  			serverHasAESGCM: true,
  1940  			expectedCipher:  TLS_CHACHA20_POLY1305_SHA256,
  1941  		},
  1942  		{
  1943  			name: "neither server nor client have hardware AES (pick ChaCha)",
  1944  			clientCiphers: []uint16{
  1945  				TLS_CHACHA20_POLY1305_SHA256,
  1946  				TLS_AES_128_GCM_SHA256,
  1947  			},
  1948  			serverHasAESGCM: false,
  1949  			expectedCipher:  TLS_CHACHA20_POLY1305_SHA256,
  1950  		},
  1951  		{
  1952  			name: "client prefers AES, server doesn't have hardware (pick ChaCha)",
  1953  			clientCiphers: []uint16{
  1954  				TLS_AES_128_GCM_SHA256,
  1955  				TLS_CHACHA20_POLY1305_SHA256,
  1956  			},
  1957  			serverHasAESGCM: false,
  1958  			expectedCipher:  TLS_CHACHA20_POLY1305_SHA256,
  1959  		},
  1960  		{
  1961  			name: "client prefers AES and sends GREASE, server doesn't have hardware (pick ChaCha)",
  1962  			clientCiphers: []uint16{
  1963  				0x0A0A, // GREASE value
  1964  				TLS_AES_128_GCM_SHA256,
  1965  				TLS_CHACHA20_POLY1305_SHA256,
  1966  			},
  1967  			serverHasAESGCM: false,
  1968  			expectedCipher:  TLS_CHACHA20_POLY1305_SHA256,
  1969  		},
  1970  		{
  1971  			name: "client prefers AES, server has hardware AES (pick AES)",
  1972  			clientCiphers: []uint16{
  1973  				TLS_AES_128_GCM_SHA256,
  1974  				TLS_CHACHA20_POLY1305_SHA256,
  1975  			},
  1976  			serverHasAESGCM: true,
  1977  			expectedCipher:  TLS_AES_128_GCM_SHA256,
  1978  		},
  1979  		{
  1980  			name: "client prefers AES and sends GREASE, server has hardware AES (pick AES)",
  1981  			clientCiphers: []uint16{
  1982  				0x0A0A, // GREASE value
  1983  				TLS_AES_128_GCM_SHA256,
  1984  				TLS_CHACHA20_POLY1305_SHA256,
  1985  			},
  1986  			serverHasAESGCM: true,
  1987  			expectedCipher:  TLS_AES_128_GCM_SHA256,
  1988  		},
  1989  	}
  1990  
  1991  	for _, tc := range tests {
  1992  		t.Run(tc.name, func(t *testing.T) {
  1993  			hasAESGCMHardwareSupport = tc.serverHasAESGCM
  1994  			pk, _ := ecdh.X25519().GenerateKey(rand.Reader)
  1995  			hs := &serverHandshakeStateTLS13{
  1996  				c: &Conn{
  1997  					config: &Config{},
  1998  					vers:   VersionTLS13,
  1999  				},
  2000  				clientHello: &clientHelloMsg{
  2001  					cipherSuites:       tc.clientCiphers,
  2002  					supportedVersions:  []uint16{VersionTLS13},
  2003  					compressionMethods: []uint8{compressionNone},
  2004  					keyShares:          []keyShare{{group: X25519, data: pk.PublicKey().Bytes()}},
  2005  					supportedCurves:    []CurveID{X25519},
  2006  				},
  2007  			}
  2008  
  2009  			err := hs.processClientHello()
  2010  			if err != nil {
  2011  				t.Errorf("pickCipherSuite failed: %s", err)
  2012  			}
  2013  
  2014  			if tc.expectedCipher != hs.suite.id {
  2015  				t.Errorf("unexpected cipher chosen: want %d, got %d", tc.expectedCipher, hs.suite.id)
  2016  			}
  2017  		})
  2018  	}
  2019  }
  2020  
  2021  // TestServerHandshakeContextCancellation tests that canceling
  2022  // the context given to the server side conn.HandshakeContext
  2023  // interrupts the in-progress handshake.
  2024  func TestServerHandshakeContextCancellation(t *testing.T) {
  2025  	c, s := localPipe(t)
  2026  	ctx, cancel := context.WithCancel(context.Background())
  2027  	unblockClient := make(chan struct{})
  2028  	defer close(unblockClient)
  2029  	go func() {
  2030  		cancel()
  2031  		<-unblockClient
  2032  		_ = c.Close()
  2033  	}()
  2034  	conn := Server(s, testConfig)
  2035  	// Initiates server side handshake, which will block until a client hello is read
  2036  	// unless the cancellation works.
  2037  	err := conn.HandshakeContext(ctx)
  2038  	if err == nil {
  2039  		t.Fatal("Server handshake did not error when the context was canceled")
  2040  	}
  2041  	if err != context.Canceled {
  2042  		t.Errorf("Unexpected server handshake error: %v", err)
  2043  	}
  2044  	if runtime.GOOS == "js" || runtime.GOOS == "wasip1" {
  2045  		t.Skip("conn.Close does not error as expected when called multiple times on GOOS=js or GOOS=wasip1")
  2046  	}
  2047  	err = conn.Close()
  2048  	if err == nil {
  2049  		t.Error("Server connection was not closed when the context was canceled")
  2050  	}
  2051  }
  2052  
  2053  // TestHandshakeContextHierarchy tests whether the contexts
  2054  // available to GetClientCertificate and GetCertificate are
  2055  // derived from the context provided to HandshakeContext, and
  2056  // that those contexts are canceled after HandshakeContext has
  2057  // returned.
  2058  func TestHandshakeContextHierarchy(t *testing.T) {
  2059  	c, s := localPipe(t)
  2060  	clientErr := make(chan error, 1)
  2061  	clientConfig := testConfig.Clone()
  2062  	serverConfig := testConfig.Clone()
  2063  	ctx, cancel := context.WithCancel(context.Background())
  2064  	defer cancel()
  2065  	key := struct{}{}
  2066  	ctx = context.WithValue(ctx, key, true)
  2067  	go func() {
  2068  		defer close(clientErr)
  2069  		defer c.Close()
  2070  		var innerCtx context.Context
  2071  		clientConfig.Certificates = nil
  2072  		clientConfig.GetClientCertificate = func(certificateRequest *CertificateRequestInfo) (*Certificate, error) {
  2073  			if val, ok := certificateRequest.Context().Value(key).(bool); !ok || !val {
  2074  				t.Errorf("GetClientCertificate context was not child of HandshakeContext")
  2075  			}
  2076  			innerCtx = certificateRequest.Context()
  2077  			return &Certificate{
  2078  				Certificate: [][]byte{testRSACertificate},
  2079  				PrivateKey:  testRSAPrivateKey,
  2080  			}, nil
  2081  		}
  2082  		cli := Client(c, clientConfig)
  2083  		err := cli.HandshakeContext(ctx)
  2084  		if err != nil {
  2085  			clientErr <- err
  2086  			return
  2087  		}
  2088  		select {
  2089  		case <-innerCtx.Done():
  2090  		default:
  2091  			t.Errorf("GetClientCertificate context was not canceled after HandshakeContext returned.")
  2092  		}
  2093  	}()
  2094  	var innerCtx context.Context
  2095  	serverConfig.Certificates = nil
  2096  	serverConfig.ClientAuth = RequestClientCert
  2097  	serverConfig.GetCertificate = func(clientHello *ClientHelloInfo) (*Certificate, error) {
  2098  		if val, ok := clientHello.Context().Value(key).(bool); !ok || !val {
  2099  			t.Errorf("GetClientCertificate context was not child of HandshakeContext")
  2100  		}
  2101  		innerCtx = clientHello.Context()
  2102  		return &Certificate{
  2103  			Certificate: [][]byte{testRSACertificate},
  2104  			PrivateKey:  testRSAPrivateKey,
  2105  		}, nil
  2106  	}
  2107  	conn := Server(s, serverConfig)
  2108  	err := conn.HandshakeContext(ctx)
  2109  	if err != nil {
  2110  		t.Errorf("Unexpected server handshake error: %v", err)
  2111  	}
  2112  	select {
  2113  	case <-innerCtx.Done():
  2114  	default:
  2115  		t.Errorf("GetCertificate context was not canceled after HandshakeContext returned.")
  2116  	}
  2117  	if err := <-clientErr; err != nil {
  2118  		t.Errorf("Unexpected client error: %v", err)
  2119  	}
  2120  }
  2121  

View as plain text