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