github.com/Psiphon-Labs/tls-tris@v0.0.0-20230824155421-58bf6d336a9a/tls_test.go (about)

     1  // Copyright 2012 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  	"crypto/x509"
    10  	"errors"
    11  	"fmt"
    12  	"io"
    13  	"io/ioutil"
    14  	"math"
    15  	"net"
    16  	"os"
    17  	"reflect"
    18  	"strings"
    19  	"testing"
    20  	"time"
    21  )
    22  
    23  var rsaCertPEM = `-----BEGIN CERTIFICATE-----
    24  MIIB0zCCAX2gAwIBAgIJAI/M7BYjwB+uMA0GCSqGSIb3DQEBBQUAMEUxCzAJBgNV
    25  BAYTAkFVMRMwEQYDVQQIDApTb21lLVN0YXRlMSEwHwYDVQQKDBhJbnRlcm5ldCBX
    26  aWRnaXRzIFB0eSBMdGQwHhcNMTIwOTEyMjE1MjAyWhcNMTUwOTEyMjE1MjAyWjBF
    27  MQswCQYDVQQGEwJBVTETMBEGA1UECAwKU29tZS1TdGF0ZTEhMB8GA1UECgwYSW50
    28  ZXJuZXQgV2lkZ2l0cyBQdHkgTHRkMFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBANLJ
    29  hPHhITqQbPklG3ibCVxwGMRfp/v4XqhfdQHdcVfHap6NQ5Wok/4xIA+ui35/MmNa
    30  rtNuC+BdZ1tMuVCPFZcCAwEAAaNQME4wHQYDVR0OBBYEFJvKs8RfJaXTH08W+SGv
    31  zQyKn0H8MB8GA1UdIwQYMBaAFJvKs8RfJaXTH08W+SGvzQyKn0H8MAwGA1UdEwQF
    32  MAMBAf8wDQYJKoZIhvcNAQEFBQADQQBJlffJHybjDGxRMqaRmDhX0+6v02TUKZsW
    33  r5QuVbpQhH6u+0UgcW0jp9QwpxoPTLTWGXEWBBBurxFwiCBhkQ+V
    34  -----END CERTIFICATE-----
    35  `
    36  
    37  var rsaKeyPEM = `-----BEGIN RSA PRIVATE KEY-----
    38  MIIBOwIBAAJBANLJhPHhITqQbPklG3ibCVxwGMRfp/v4XqhfdQHdcVfHap6NQ5Wo
    39  k/4xIA+ui35/MmNartNuC+BdZ1tMuVCPFZcCAwEAAQJAEJ2N+zsR0Xn8/Q6twa4G
    40  6OB1M1WO+k+ztnX/1SvNeWu8D6GImtupLTYgjZcHufykj09jiHmjHx8u8ZZB/o1N
    41  MQIhAPW+eyZo7ay3lMz1V01WVjNKK9QSn1MJlb06h/LuYv9FAiEA25WPedKgVyCW
    42  SmUwbPw8fnTcpqDWE3yTO3vKcebqMSsCIBF3UmVue8YU3jybC3NxuXq3wNm34R8T
    43  xVLHwDXh/6NJAiEAl2oHGGLz64BuAfjKrqwz7qMYr9HCLIe/YsoWq/olzScCIQDi
    44  D2lWusoe2/nEqfDVVWGWlyJ7yOmqaVm/iNUN9B2N2g==
    45  -----END RSA PRIVATE KEY-----
    46  `
    47  
    48  // keyPEM is the same as rsaKeyPEM, but declares itself as just
    49  // "PRIVATE KEY", not "RSA PRIVATE KEY".  https://golang.org/issue/4477
    50  var keyPEM = `-----BEGIN PRIVATE KEY-----
    51  MIIBOwIBAAJBANLJhPHhITqQbPklG3ibCVxwGMRfp/v4XqhfdQHdcVfHap6NQ5Wo
    52  k/4xIA+ui35/MmNartNuC+BdZ1tMuVCPFZcCAwEAAQJAEJ2N+zsR0Xn8/Q6twa4G
    53  6OB1M1WO+k+ztnX/1SvNeWu8D6GImtupLTYgjZcHufykj09jiHmjHx8u8ZZB/o1N
    54  MQIhAPW+eyZo7ay3lMz1V01WVjNKK9QSn1MJlb06h/LuYv9FAiEA25WPedKgVyCW
    55  SmUwbPw8fnTcpqDWE3yTO3vKcebqMSsCIBF3UmVue8YU3jybC3NxuXq3wNm34R8T
    56  xVLHwDXh/6NJAiEAl2oHGGLz64BuAfjKrqwz7qMYr9HCLIe/YsoWq/olzScCIQDi
    57  D2lWusoe2/nEqfDVVWGWlyJ7yOmqaVm/iNUN9B2N2g==
    58  -----END PRIVATE KEY-----
    59  `
    60  
    61  var ecdsaCertPEM = `-----BEGIN CERTIFICATE-----
    62  MIIB/jCCAWICCQDscdUxw16XFDAJBgcqhkjOPQQBMEUxCzAJBgNVBAYTAkFVMRMw
    63  EQYDVQQIEwpTb21lLVN0YXRlMSEwHwYDVQQKExhJbnRlcm5ldCBXaWRnaXRzIFB0
    64  eSBMdGQwHhcNMTIxMTE0MTI0MDQ4WhcNMTUxMTE0MTI0MDQ4WjBFMQswCQYDVQQG
    65  EwJBVTETMBEGA1UECBMKU29tZS1TdGF0ZTEhMB8GA1UEChMYSW50ZXJuZXQgV2lk
    66  Z2l0cyBQdHkgTHRkMIGbMBAGByqGSM49AgEGBSuBBAAjA4GGAAQBY9+my9OoeSUR
    67  lDQdV/x8LsOuLilthhiS1Tz4aGDHIPwC1mlvnf7fg5lecYpMCrLLhauAc1UJXcgl
    68  01xoLuzgtAEAgv2P/jgytzRSpUYvgLBt1UA0leLYBy6mQQbrNEuqT3INapKIcUv8
    69  XxYP0xMEUksLPq6Ca+CRSqTtrd/23uTnapkwCQYHKoZIzj0EAQOBigAwgYYCQXJo
    70  A7Sl2nLVf+4Iu/tAX/IF4MavARKC4PPHK3zfuGfPR3oCCcsAoz3kAzOeijvd0iXb
    71  H5jBImIxPL4WxQNiBTexAkF8D1EtpYuWdlVQ80/h/f4pBcGiXPqX5h2PQSQY7hP1
    72  +jwM1FGS4fREIOvlBYr/SzzQRtwrvrzGYxDEDbsC0ZGRnA==
    73  -----END CERTIFICATE-----
    74  `
    75  
    76  var ecdsaKeyPEM = `-----BEGIN EC PARAMETERS-----
    77  BgUrgQQAIw==
    78  -----END EC PARAMETERS-----
    79  -----BEGIN EC PRIVATE KEY-----
    80  MIHcAgEBBEIBrsoKp0oqcv6/JovJJDoDVSGWdirrkgCWxrprGlzB9o0X8fV675X0
    81  NwuBenXFfeZvVcwluO7/Q9wkYoPd/t3jGImgBwYFK4EEACOhgYkDgYYABAFj36bL
    82  06h5JRGUNB1X/Hwuw64uKW2GGJLVPPhoYMcg/ALWaW+d/t+DmV5xikwKssuFq4Bz
    83  VQldyCXTXGgu7OC0AQCC/Y/+ODK3NFKlRi+AsG3VQDSV4tgHLqZBBus0S6pPcg1q
    84  kohxS/xfFg/TEwRSSws+roJr4JFKpO2t3/be5OdqmQ==
    85  -----END EC PRIVATE KEY-----
    86  `
    87  
    88  var keyPairTests = []struct {
    89  	algo string
    90  	cert string
    91  	key  string
    92  }{
    93  	{"ECDSA", ecdsaCertPEM, ecdsaKeyPEM},
    94  	{"RSA", rsaCertPEM, rsaKeyPEM},
    95  	{"RSA-untyped", rsaCertPEM, keyPEM}, // golang.org/issue/4477
    96  }
    97  
    98  func TestX509KeyPair(t *testing.T) {
    99  	t.Parallel()
   100  	var pem []byte
   101  	for _, test := range keyPairTests {
   102  		pem = []byte(test.cert + test.key)
   103  		if _, err := X509KeyPair(pem, pem); err != nil {
   104  			t.Errorf("Failed to load %s cert followed by %s key: %s", test.algo, test.algo, err)
   105  		}
   106  		pem = []byte(test.key + test.cert)
   107  		if _, err := X509KeyPair(pem, pem); err != nil {
   108  			t.Errorf("Failed to load %s key followed by %s cert: %s", test.algo, test.algo, err)
   109  		}
   110  	}
   111  }
   112  
   113  func TestX509KeyPairErrors(t *testing.T) {
   114  	_, err := X509KeyPair([]byte(rsaKeyPEM), []byte(rsaCertPEM))
   115  	if err == nil {
   116  		t.Fatalf("X509KeyPair didn't return an error when arguments were switched")
   117  	}
   118  	if subStr := "been switched"; !strings.Contains(err.Error(), subStr) {
   119  		t.Fatalf("Expected %q in the error when switching arguments to X509KeyPair, but the error was %q", subStr, err)
   120  	}
   121  
   122  	_, err = X509KeyPair([]byte(rsaCertPEM), []byte(rsaCertPEM))
   123  	if err == nil {
   124  		t.Fatalf("X509KeyPair didn't return an error when both arguments were certificates")
   125  	}
   126  	if subStr := "certificate"; !strings.Contains(err.Error(), subStr) {
   127  		t.Fatalf("Expected %q in the error when both arguments to X509KeyPair were certificates, but the error was %q", subStr, err)
   128  	}
   129  
   130  	const nonsensePEM = `
   131  -----BEGIN NONSENSE-----
   132  Zm9vZm9vZm9v
   133  -----END NONSENSE-----
   134  `
   135  
   136  	_, err = X509KeyPair([]byte(nonsensePEM), []byte(nonsensePEM))
   137  	if err == nil {
   138  		t.Fatalf("X509KeyPair didn't return an error when both arguments were nonsense")
   139  	}
   140  	if subStr := "NONSENSE"; !strings.Contains(err.Error(), subStr) {
   141  		t.Fatalf("Expected %q in the error when both arguments to X509KeyPair were nonsense, but the error was %q", subStr, err)
   142  	}
   143  }
   144  
   145  func TestX509MixedKeyPair(t *testing.T) {
   146  	if _, err := X509KeyPair([]byte(rsaCertPEM), []byte(ecdsaKeyPEM)); err == nil {
   147  		t.Error("Load of RSA certificate succeeded with ECDSA private key")
   148  	}
   149  	if _, err := X509KeyPair([]byte(ecdsaCertPEM), []byte(rsaKeyPEM)); err == nil {
   150  		t.Error("Load of ECDSA certificate succeeded with RSA private key")
   151  	}
   152  }
   153  
   154  func newLocalListener(t testing.TB) net.Listener {
   155  	ln, err := net.Listen("tcp", "127.0.0.1:0")
   156  	if err != nil {
   157  		ln, err = net.Listen("tcp6", "[::1]:0")
   158  	}
   159  	if err != nil {
   160  		t.Fatal(err)
   161  	}
   162  	return ln
   163  }
   164  
   165  func TestDialTimeout(t *testing.T) {
   166  	if testing.Short() {
   167  		t.Skip("skipping in short mode")
   168  	}
   169  	listener := newLocalListener(t)
   170  
   171  	addr := listener.Addr().String()
   172  	defer listener.Close()
   173  
   174  	complete := make(chan bool)
   175  	defer close(complete)
   176  
   177  	go func() {
   178  		conn, err := listener.Accept()
   179  		if err != nil {
   180  			t.Error(err)
   181  			return
   182  		}
   183  		<-complete
   184  		conn.Close()
   185  	}()
   186  
   187  	dialer := &net.Dialer{
   188  		Timeout: 10 * time.Millisecond,
   189  	}
   190  
   191  	var err error
   192  	if _, err = DialWithDialer(dialer, "tcp", addr, nil); err == nil {
   193  		t.Fatal("DialWithTimeout completed successfully")
   194  	}
   195  
   196  	if !isTimeoutError(err) {
   197  		t.Errorf("resulting error not a timeout: %v\nType %T: %#v", err, err, err)
   198  	}
   199  }
   200  
   201  func isTimeoutError(err error) bool {
   202  	if ne, ok := err.(net.Error); ok {
   203  		return ne.Timeout()
   204  	}
   205  	return false
   206  }
   207  
   208  // tests that Conn.Read returns (non-zero, io.EOF) instead of
   209  // (non-zero, nil) when a Close (alertCloseNotify) is sitting right
   210  // behind the application data in the buffer.
   211  func TestConnReadNonzeroAndEOF(t *testing.T) {
   212  	// This test is racy: it assumes that after a write to a
   213  	// localhost TCP connection, the peer TCP connection can
   214  	// immediately read it. Because it's racy, we skip this test
   215  	// in short mode, and then retry it several times with an
   216  	// increasing sleep in between our final write (via srv.Close
   217  	// below) and the following read.
   218  	if testing.Short() {
   219  		t.Skip("skipping in short mode")
   220  	}
   221  	var err error
   222  	for delay := time.Millisecond; delay <= 64*time.Millisecond; delay *= 2 {
   223  		if err = testConnReadNonzeroAndEOF(t, delay); err == nil {
   224  			return
   225  		}
   226  	}
   227  	t.Error(err)
   228  }
   229  
   230  func testConnReadNonzeroAndEOF(t *testing.T, delay time.Duration) error {
   231  	ln := newLocalListener(t)
   232  	defer ln.Close()
   233  
   234  	srvCh := make(chan *Conn, 1)
   235  	var serr error
   236  	go func() {
   237  		sconn, err := ln.Accept()
   238  		if err != nil {
   239  			serr = err
   240  			srvCh <- nil
   241  			return
   242  		}
   243  		serverConfig := testConfig.Clone()
   244  		srv := Server(sconn, serverConfig)
   245  		if err := srv.Handshake(); err != nil {
   246  			serr = fmt.Errorf("handshake: %v", err)
   247  			srvCh <- nil
   248  			return
   249  		}
   250  		srvCh <- srv
   251  	}()
   252  
   253  	clientConfig := testConfig.Clone()
   254  	conn, err := Dial("tcp", ln.Addr().String(), clientConfig)
   255  	if err != nil {
   256  		t.Fatal(err)
   257  	}
   258  	defer conn.Close()
   259  
   260  	srv := <-srvCh
   261  	if srv == nil {
   262  		return serr
   263  	}
   264  
   265  	buf := make([]byte, 6)
   266  
   267  	srv.Write([]byte("foobar"))
   268  	n, err := conn.Read(buf)
   269  	if n != 6 || err != nil || string(buf) != "foobar" {
   270  		return fmt.Errorf("Read = %d, %v, data %q; want 6, nil, foobar", n, err, buf)
   271  	}
   272  
   273  	srv.Write([]byte("abcdef"))
   274  	srv.Close()
   275  	time.Sleep(delay)
   276  	n, err = conn.Read(buf)
   277  	if n != 6 || string(buf) != "abcdef" {
   278  		return fmt.Errorf("Read = %d, buf= %q; want 6, abcdef", n, buf)
   279  	}
   280  	if err != io.EOF {
   281  		return fmt.Errorf("Second Read error = %v; want io.EOF", err)
   282  	}
   283  	return nil
   284  }
   285  
   286  func TestTLSUniqueMatches(t *testing.T) {
   287  	ln := newLocalListener(t)
   288  	defer ln.Close()
   289  
   290  	serverTLSUniques := make(chan []byte)
   291  	go func() {
   292  		for i := 0; i < 2; i++ {
   293  			sconn, err := ln.Accept()
   294  			if err != nil {
   295  				t.Error(err)
   296  				return
   297  			}
   298  			serverConfig := testConfig.Clone()
   299  			srv := Server(sconn, serverConfig)
   300  			if err := srv.Handshake(); err != nil {
   301  				t.Error(err)
   302  				return
   303  			}
   304  			serverTLSUniques <- srv.ConnectionState().TLSUnique
   305  		}
   306  	}()
   307  
   308  	clientConfig := testConfig.Clone()
   309  	clientConfig.ClientSessionCache = NewLRUClientSessionCache(1)
   310  	conn, err := Dial("tcp", ln.Addr().String(), clientConfig)
   311  	if err != nil {
   312  		t.Fatal(err)
   313  	}
   314  	if !bytes.Equal(conn.ConnectionState().TLSUnique, <-serverTLSUniques) {
   315  		t.Error("client and server channel bindings differ")
   316  	}
   317  	conn.Close()
   318  
   319  	conn, err = Dial("tcp", ln.Addr().String(), clientConfig)
   320  	if err != nil {
   321  		t.Fatal(err)
   322  	}
   323  	defer conn.Close()
   324  	if !conn.ConnectionState().DidResume {
   325  		t.Error("second session did not use resumption")
   326  	}
   327  	if !bytes.Equal(conn.ConnectionState().TLSUnique, <-serverTLSUniques) {
   328  		t.Error("client and server channel bindings differ when session resumption is used")
   329  	}
   330  }
   331  
   332  func TestVerifyHostname(t *testing.T) {
   333  	c, err := Dial("tcp", "www.google.com:https", nil)
   334  	if err != nil {
   335  		t.Fatal(err)
   336  	}
   337  	if err := c.VerifyHostname("www.google.com"); err != nil {
   338  		t.Fatalf("verify www.google.com: %v", err)
   339  	}
   340  	if err := c.VerifyHostname("www.yahoo.com"); err == nil {
   341  		t.Fatalf("verify www.yahoo.com succeeded")
   342  	}
   343  
   344  	c, err = Dial("tcp", "www.google.com:https", &Config{InsecureSkipVerify: true})
   345  	if err != nil {
   346  		t.Fatal(err)
   347  	}
   348  	if err := c.VerifyHostname("www.google.com"); err == nil {
   349  		t.Fatalf("verify www.google.com succeeded with InsecureSkipVerify=true")
   350  	}
   351  	if err := c.VerifyHostname("www.yahoo.com"); err == nil {
   352  		t.Fatalf("verify www.google.com succeeded with InsecureSkipVerify=true")
   353  	}
   354  }
   355  
   356  func TestVerifyHostnameResumed(t *testing.T) {
   357  	config := &Config{
   358  		ClientSessionCache: NewLRUClientSessionCache(32),
   359  		// There is no "New ticket" sent in case TLS v1.3 is advertised.
   360  		// Hence forcing TLSv12
   361  		MaxVersion: VersionTLS12,
   362  	}
   363  
   364  	for i := 0; i < 2; i++ {
   365  		c, err := Dial("tcp", "www.google.com:https", config)
   366  		if err != nil {
   367  			t.Fatalf("Dial #%d: %v", i, err)
   368  		}
   369  		cs := c.ConnectionState()
   370  		if i > 0 && !cs.DidResume {
   371  			t.Fatalf("Subsequent connection unexpectedly didn't resume")
   372  		}
   373  		if cs.VerifiedChains == nil {
   374  			t.Fatalf("Dial #%d: cs.VerifiedChains == nil", i)
   375  		}
   376  		if err := c.VerifyHostname("www.google.com"); err != nil {
   377  			t.Fatalf("verify www.google.com #%d: %v", i, err)
   378  		}
   379  		c.Close()
   380  	}
   381  }
   382  
   383  func TestConnCloseBreakingWrite(t *testing.T) {
   384  	ln := newLocalListener(t)
   385  	defer ln.Close()
   386  
   387  	srvCh := make(chan *Conn, 1)
   388  	var serr error
   389  	var sconn net.Conn
   390  	go func() {
   391  		var err error
   392  		sconn, err = ln.Accept()
   393  		if err != nil {
   394  			serr = err
   395  			srvCh <- nil
   396  			return
   397  		}
   398  		serverConfig := testConfig.Clone()
   399  		srv := Server(sconn, serverConfig)
   400  		if err := srv.Handshake(); err != nil {
   401  			serr = fmt.Errorf("handshake: %v", err)
   402  			srvCh <- nil
   403  			return
   404  		}
   405  		srvCh <- srv
   406  	}()
   407  
   408  	cconn, err := net.Dial("tcp", ln.Addr().String())
   409  	if err != nil {
   410  		t.Fatal(err)
   411  	}
   412  	defer cconn.Close()
   413  
   414  	conn := &changeImplConn{
   415  		Conn: cconn,
   416  	}
   417  
   418  	clientConfig := testConfig.Clone()
   419  	tconn := Client(conn, clientConfig)
   420  	if err := tconn.Handshake(); err != nil {
   421  		t.Fatal(err)
   422  	}
   423  
   424  	srv := <-srvCh
   425  	if srv == nil {
   426  		t.Fatal(serr)
   427  	}
   428  	defer sconn.Close()
   429  
   430  	connClosed := make(chan struct{})
   431  	conn.closeFunc = func() error {
   432  		close(connClosed)
   433  		return nil
   434  	}
   435  
   436  	inWrite := make(chan bool, 1)
   437  	var errConnClosed = errors.New("conn closed for test")
   438  	conn.writeFunc = func(p []byte) (n int, err error) {
   439  		inWrite <- true
   440  		<-connClosed
   441  		return 0, errConnClosed
   442  	}
   443  
   444  	closeReturned := make(chan bool, 1)
   445  	go func() {
   446  		<-inWrite
   447  		tconn.Close() // test that this doesn't block forever.
   448  		closeReturned <- true
   449  	}()
   450  
   451  	_, err = tconn.Write([]byte("foo"))
   452  	if err != errConnClosed {
   453  		t.Errorf("Write error = %v; want errConnClosed", err)
   454  	}
   455  
   456  	<-closeReturned
   457  	if err := tconn.Close(); err != errClosed {
   458  		t.Errorf("Close error = %v; want errClosed", err)
   459  	}
   460  }
   461  
   462  func TestConnCloseWrite(t *testing.T) {
   463  	ln := newLocalListener(t)
   464  	defer ln.Close()
   465  
   466  	clientDoneChan := make(chan struct{})
   467  
   468  	serverCloseWrite := func() error {
   469  		sconn, err := ln.Accept()
   470  		if err != nil {
   471  			return fmt.Errorf("accept: %v", err)
   472  		}
   473  		defer sconn.Close()
   474  
   475  		serverConfig := testConfig.Clone()
   476  		srv := Server(sconn, serverConfig)
   477  		if err := srv.Handshake(); err != nil {
   478  			return fmt.Errorf("handshake: %v", err)
   479  		}
   480  		defer srv.Close()
   481  
   482  		data, err := ioutil.ReadAll(srv)
   483  		if err != nil {
   484  			return err
   485  		}
   486  		if len(data) > 0 {
   487  			return fmt.Errorf("Read data = %q; want nothing", data)
   488  		}
   489  
   490  		if err := srv.CloseWrite(); err != nil {
   491  			return fmt.Errorf("server CloseWrite: %v", err)
   492  		}
   493  
   494  		// Wait for clientCloseWrite to finish, so we know we
   495  		// tested the CloseWrite before we defer the
   496  		// sconn.Close above, which would also cause the
   497  		// client to unblock like CloseWrite.
   498  		<-clientDoneChan
   499  		return nil
   500  	}
   501  
   502  	clientCloseWrite := func() error {
   503  		defer close(clientDoneChan)
   504  
   505  		clientConfig := testConfig.Clone()
   506  		conn, err := Dial("tcp", ln.Addr().String(), clientConfig)
   507  		if err != nil {
   508  			return err
   509  		}
   510  		if err := conn.Handshake(); err != nil {
   511  			return err
   512  		}
   513  		defer conn.Close()
   514  
   515  		if err := conn.CloseWrite(); err != nil {
   516  			return fmt.Errorf("client CloseWrite: %v", err)
   517  		}
   518  
   519  		if _, err := conn.Write([]byte{0}); err != errShutdown {
   520  			return fmt.Errorf("CloseWrite error = %v; want errShutdown", err)
   521  		}
   522  
   523  		data, err := ioutil.ReadAll(conn)
   524  		if err != nil {
   525  			return err
   526  		}
   527  		if len(data) > 0 {
   528  			return fmt.Errorf("Read data = %q; want nothing", data)
   529  		}
   530  		return nil
   531  	}
   532  
   533  	errChan := make(chan error, 2)
   534  
   535  	go func() { errChan <- serverCloseWrite() }()
   536  	go func() { errChan <- clientCloseWrite() }()
   537  
   538  	for i := 0; i < 2; i++ {
   539  		select {
   540  		case err := <-errChan:
   541  			if err != nil {
   542  				t.Fatal(err)
   543  			}
   544  		case <-time.After(10 * time.Second):
   545  			t.Fatal("deadlock")
   546  		}
   547  	}
   548  
   549  	// Also test CloseWrite being called before the handshake is
   550  	// finished:
   551  	{
   552  		ln2 := newLocalListener(t)
   553  		defer ln2.Close()
   554  
   555  		netConn, err := net.Dial("tcp", ln2.Addr().String())
   556  		if err != nil {
   557  			t.Fatal(err)
   558  		}
   559  		defer netConn.Close()
   560  		conn := Client(netConn, testConfig.Clone())
   561  
   562  		if err := conn.CloseWrite(); err != errEarlyCloseWrite {
   563  			t.Errorf("CloseWrite error = %v; want errEarlyCloseWrite", err)
   564  		}
   565  	}
   566  }
   567  
   568  func TestWarningAlertFlood(t *testing.T) {
   569  	ln := newLocalListener(t)
   570  	defer ln.Close()
   571  
   572  	server := func() error {
   573  		sconn, err := ln.Accept()
   574  		if err != nil {
   575  			return fmt.Errorf("accept: %v", err)
   576  		}
   577  		defer sconn.Close()
   578  
   579  		serverConfig := testConfig.Clone()
   580  		srv := Server(sconn, serverConfig)
   581  		if err := srv.Handshake(); err != nil {
   582  			return fmt.Errorf("handshake: %v", err)
   583  		}
   584  		defer srv.Close()
   585  
   586  		_, err = ioutil.ReadAll(srv)
   587  		if err == nil {
   588  			return errors.New("unexpected lack of error from server")
   589  		}
   590  		const expected = "too many warn"
   591  		if str := err.Error(); !strings.Contains(str, expected) {
   592  			return fmt.Errorf("expected error containing %q, but saw: %s", expected, str)
   593  		}
   594  
   595  		return nil
   596  	}
   597  
   598  	errChan := make(chan error, 1)
   599  	go func() { errChan <- server() }()
   600  
   601  	clientConfig := testConfig.Clone()
   602  	conn, err := Dial("tcp", ln.Addr().String(), clientConfig)
   603  	if err != nil {
   604  		t.Fatal(err)
   605  	}
   606  	defer conn.Close()
   607  	if err := conn.Handshake(); err != nil {
   608  		t.Fatal(err)
   609  	}
   610  
   611  	for i := 0; i < maxWarnAlertCount+1; i++ {
   612  		conn.sendAlert(alertNoRenegotiation)
   613  	}
   614  
   615  	if err := <-errChan; err != nil {
   616  		t.Fatal(err)
   617  	}
   618  }
   619  
   620  func TestCloneFuncFields(t *testing.T) {
   621  	const expectedCount = 5
   622  	called := 0
   623  
   624  	c1 := Config{
   625  		Time: func() time.Time {
   626  			called |= 1 << 0
   627  			return time.Time{}
   628  		},
   629  		GetCertificate: func(*ClientHelloInfo) (*Certificate, error) {
   630  			called |= 1 << 1
   631  			return nil, nil
   632  		},
   633  		GetClientCertificate: func(*CertificateRequestInfo) (*Certificate, error) {
   634  			called |= 1 << 2
   635  			return nil, nil
   636  		},
   637  		GetConfigForClient: func(*ClientHelloInfo) (*Config, error) {
   638  			called |= 1 << 3
   639  			return nil, nil
   640  		},
   641  		VerifyPeerCertificate: func(rawCerts [][]byte, verifiedChains [][]*x509.Certificate) error {
   642  			called |= 1 << 4
   643  			return nil
   644  		},
   645  	}
   646  
   647  	c2 := c1.Clone()
   648  
   649  	c2.Time()
   650  	c2.GetCertificate(nil)
   651  	c2.GetClientCertificate(nil)
   652  	c2.GetConfigForClient(nil)
   653  	c2.VerifyPeerCertificate(nil, nil)
   654  
   655  	if called != (1<<expectedCount)-1 {
   656  		t.Fatalf("expected %d calls but saw calls %b", expectedCount, called)
   657  	}
   658  }
   659  
   660  func TestCloneNonFuncFields(t *testing.T) {
   661  	var c1 Config
   662  	v := reflect.ValueOf(&c1).Elem()
   663  
   664  	typ := v.Type()
   665  	for i := 0; i < typ.NumField(); i++ {
   666  		f := v.Field(i)
   667  		if !f.CanSet() {
   668  			// unexported field; not cloned.
   669  			continue
   670  		}
   671  
   672  		// testing/quick can't handle functions or interfaces and so
   673  		// isn't used here.
   674  		switch fn := typ.Field(i).Name; fn {
   675  		case "Rand":
   676  			f.Set(reflect.ValueOf(io.Reader(os.Stdin)))
   677  		case "Time", "GetCertificate", "GetConfigForClient", "VerifyPeerCertificate", "GetClientCertificate", "GetDelegatedCredential":
   678  			// DeepEqual can't compare functions. If you add a
   679  			// function field to this list, you must also change
   680  			// TestCloneFuncFields to ensure that the func field is
   681  			// cloned.
   682  		case "Certificates":
   683  			f.Set(reflect.ValueOf([]Certificate{
   684  				{Certificate: [][]byte{{'b'}}},
   685  			}))
   686  		case "NameToCertificate":
   687  			f.Set(reflect.ValueOf(map[string]*Certificate{"a": nil}))
   688  		case "RootCAs", "ClientCAs":
   689  			f.Set(reflect.ValueOf(x509.NewCertPool()))
   690  		case "ClientSessionCache":
   691  			f.Set(reflect.ValueOf(NewLRUClientSessionCache(10)))
   692  		case "KeyLogWriter":
   693  			f.Set(reflect.ValueOf(io.Writer(os.Stdout)))
   694  		case "NextProtos":
   695  			f.Set(reflect.ValueOf([]string{"a", "b"}))
   696  		case "ServerName":
   697  			f.Set(reflect.ValueOf("b"))
   698  		case "ClientAuth":
   699  			f.Set(reflect.ValueOf(VerifyClientCertIfGiven))
   700  		case "InsecureSkipVerify", "SessionTicketsDisabled", "DynamicRecordSizingDisabled", "PreferServerCipherSuites", "Accept0RTTData":
   701  			f.Set(reflect.ValueOf(true))
   702  		case "MinVersion", "MaxVersion":
   703  			f.Set(reflect.ValueOf(uint16(VersionTLS12)))
   704  		case "SessionTicketKey":
   705  			f.Set(reflect.ValueOf([32]byte{}))
   706  		case "CipherSuites":
   707  			f.Set(reflect.ValueOf([]uint16{1, 2}))
   708  		case "CurvePreferences":
   709  			f.Set(reflect.ValueOf([]CurveID{CurveP256}))
   710  		case "Renegotiation":
   711  			f.Set(reflect.ValueOf(RenegotiateOnceAsClient))
   712  		case "Max0RTTDataSize":
   713  			f.Set(reflect.ValueOf(uint32(0)))
   714  		case "SessionTicketSealer":
   715  			// TODO
   716  		case "AcceptDelegatedCredential":
   717  			f.Set(reflect.ValueOf(false))
   718  		case "UseExtendedMasterSecret":
   719  			f.Set(reflect.ValueOf(false))
   720  		default:
   721  			t.Errorf("all fields must be accounted for, but saw unknown field %q", fn)
   722  		}
   723  	}
   724  
   725  	c2 := c1.Clone()
   726  	// DeepEqual also compares unexported fields, thus c2 needs to have run
   727  	// serverInit in order to be DeepEqual to c1. Cloning it and discarding
   728  	// the result is sufficient.
   729  	c2.Clone()
   730  
   731  	if !reflect.DeepEqual(&c1, c2) {
   732  		t.Errorf("clone failed to copy a field")
   733  	}
   734  }
   735  
   736  // changeImplConn is a net.Conn which can change its Write and Close
   737  // methods.
   738  type changeImplConn struct {
   739  	net.Conn
   740  	writeFunc func([]byte) (int, error)
   741  	closeFunc func() error
   742  }
   743  
   744  func (w *changeImplConn) Write(p []byte) (n int, err error) {
   745  	if w.writeFunc != nil {
   746  		return w.writeFunc(p)
   747  	}
   748  	return w.Conn.Write(p)
   749  }
   750  
   751  func (w *changeImplConn) Close() error {
   752  	if w.closeFunc != nil {
   753  		return w.closeFunc()
   754  	}
   755  	return w.Conn.Close()
   756  }
   757  
   758  func throughput(b *testing.B, totalBytes int64, dynamicRecordSizingDisabled bool) {
   759  	ln := newLocalListener(b)
   760  	defer ln.Close()
   761  
   762  	N := b.N
   763  
   764  	// Less than 64KB because Windows appears to use a TCP rwin < 64KB.
   765  	// See Issue #15899.
   766  	const bufsize = 32 << 10
   767  
   768  	go func() {
   769  		buf := make([]byte, bufsize)
   770  		for i := 0; i < N; i++ {
   771  			sconn, err := ln.Accept()
   772  			if err != nil {
   773  				// panic rather than synchronize to avoid benchmark overhead
   774  				// (cannot call b.Fatal in goroutine)
   775  				panic(fmt.Errorf("accept: %v", err))
   776  			}
   777  			serverConfig := testConfig.Clone()
   778  			serverConfig.CipherSuites = nil // the defaults may prefer faster ciphers
   779  			serverConfig.DynamicRecordSizingDisabled = dynamicRecordSizingDisabled
   780  			srv := Server(sconn, serverConfig)
   781  			if err := srv.Handshake(); err != nil {
   782  				panic(fmt.Errorf("handshake: %v", err))
   783  			}
   784  			if _, err := io.CopyBuffer(srv, srv, buf); err != nil {
   785  				panic(fmt.Errorf("copy buffer: %v", err))
   786  			}
   787  		}
   788  	}()
   789  
   790  	b.SetBytes(totalBytes)
   791  	clientConfig := testConfig.Clone()
   792  	clientConfig.CipherSuites = nil // the defaults may prefer faster ciphers
   793  	clientConfig.DynamicRecordSizingDisabled = dynamicRecordSizingDisabled
   794  
   795  	buf := make([]byte, bufsize)
   796  	chunks := int(math.Ceil(float64(totalBytes) / float64(len(buf))))
   797  	for i := 0; i < N; i++ {
   798  		conn, err := Dial("tcp", ln.Addr().String(), clientConfig)
   799  		if err != nil {
   800  			b.Fatal(err)
   801  		}
   802  		for j := 0; j < chunks; j++ {
   803  			_, err := conn.Write(buf)
   804  			if err != nil {
   805  				b.Fatal(err)
   806  			}
   807  			_, err = io.ReadFull(conn, buf)
   808  			if err != nil {
   809  				b.Fatal(err)
   810  			}
   811  		}
   812  		conn.Close()
   813  	}
   814  }
   815  
   816  func BenchmarkThroughput(b *testing.B) {
   817  	for _, mode := range []string{"Max", "Dynamic"} {
   818  		for size := 1; size <= 64; size <<= 1 {
   819  			name := fmt.Sprintf("%sPacket/%dMB", mode, size)
   820  			b.Run(name, func(b *testing.B) {
   821  				throughput(b, int64(size<<20), mode == "Max")
   822  			})
   823  		}
   824  	}
   825  }
   826  
   827  type slowConn struct {
   828  	net.Conn
   829  	bps int
   830  }
   831  
   832  func (c *slowConn) Write(p []byte) (int, error) {
   833  	if c.bps == 0 {
   834  		panic("too slow")
   835  	}
   836  	t0 := time.Now()
   837  	wrote := 0
   838  	for wrote < len(p) {
   839  		time.Sleep(100 * time.Microsecond)
   840  		allowed := int(time.Since(t0).Seconds()*float64(c.bps)) / 8
   841  		if allowed > len(p) {
   842  			allowed = len(p)
   843  		}
   844  		if wrote < allowed {
   845  			n, err := c.Conn.Write(p[wrote:allowed])
   846  			wrote += n
   847  			if err != nil {
   848  				return wrote, err
   849  			}
   850  		}
   851  	}
   852  	return len(p), nil
   853  }
   854  
   855  func latency(b *testing.B, bps int, dynamicRecordSizingDisabled bool) {
   856  	ln := newLocalListener(b)
   857  	defer ln.Close()
   858  
   859  	N := b.N
   860  
   861  	go func() {
   862  		for i := 0; i < N; i++ {
   863  			sconn, err := ln.Accept()
   864  			if err != nil {
   865  				// panic rather than synchronize to avoid benchmark overhead
   866  				// (cannot call b.Fatal in goroutine)
   867  				panic(fmt.Errorf("accept: %v", err))
   868  			}
   869  			serverConfig := testConfig.Clone()
   870  			serverConfig.DynamicRecordSizingDisabled = dynamicRecordSizingDisabled
   871  			srv := Server(&slowConn{sconn, bps}, serverConfig)
   872  			if err := srv.Handshake(); err != nil {
   873  				panic(fmt.Errorf("handshake: %v", err))
   874  			}
   875  			io.Copy(srv, srv)
   876  		}
   877  	}()
   878  
   879  	clientConfig := testConfig.Clone()
   880  	clientConfig.DynamicRecordSizingDisabled = dynamicRecordSizingDisabled
   881  
   882  	buf := make([]byte, 16384)
   883  	peek := make([]byte, 1)
   884  
   885  	for i := 0; i < N; i++ {
   886  		conn, err := Dial("tcp", ln.Addr().String(), clientConfig)
   887  		if err != nil {
   888  			b.Fatal(err)
   889  		}
   890  		// make sure we're connected and previous connection has stopped
   891  		if _, err := conn.Write(buf[:1]); err != nil {
   892  			b.Fatal(err)
   893  		}
   894  		if _, err := io.ReadFull(conn, peek); err != nil {
   895  			b.Fatal(err)
   896  		}
   897  		if _, err := conn.Write(buf); err != nil {
   898  			b.Fatal(err)
   899  		}
   900  		if _, err = io.ReadFull(conn, peek); err != nil {
   901  			b.Fatal(err)
   902  		}
   903  		conn.Close()
   904  	}
   905  }
   906  
   907  func BenchmarkLatency(b *testing.B) {
   908  	for _, mode := range []string{"Max", "Dynamic"} {
   909  		for _, kbps := range []int{200, 500, 1000, 2000, 5000} {
   910  			name := fmt.Sprintf("%sPacket/%dkbps", mode, kbps)
   911  			b.Run(name, func(b *testing.B) {
   912  				latency(b, kbps*1000, mode == "Max")
   913  			})
   914  		}
   915  	}
   916  }