github.com/JimmyHuang454/JLS-go@v0.0.0-20230831150107-90d536585ba0/tls/handshake_server_test.go (about)

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