github.com/hxx258456/ccgo@v0.0.5-0.20230213014102-48b35f46f66f/gmtls/handshake_server_test.go (about)

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