github.com/gidoBOSSftw5731/go/src@v0.0.0-20210226122457-d24b0edbf019/crypto/tls/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  	"context"
    10  	"crypto"
    11  	"crypto/x509"
    12  	"encoding/json"
    13  	"errors"
    14  	"fmt"
    15  	"internal/testenv"
    16  	"io"
    17  	"math"
    18  	"net"
    19  	"os"
    20  	"reflect"
    21  	"strings"
    22  	"testing"
    23  	"time"
    24  )
    25  
    26  var rsaCertPEM = `-----BEGIN CERTIFICATE-----
    27  MIIB0zCCAX2gAwIBAgIJAI/M7BYjwB+uMA0GCSqGSIb3DQEBBQUAMEUxCzAJBgNV
    28  BAYTAkFVMRMwEQYDVQQIDApTb21lLVN0YXRlMSEwHwYDVQQKDBhJbnRlcm5ldCBX
    29  aWRnaXRzIFB0eSBMdGQwHhcNMTIwOTEyMjE1MjAyWhcNMTUwOTEyMjE1MjAyWjBF
    30  MQswCQYDVQQGEwJBVTETMBEGA1UECAwKU29tZS1TdGF0ZTEhMB8GA1UECgwYSW50
    31  ZXJuZXQgV2lkZ2l0cyBQdHkgTHRkMFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBANLJ
    32  hPHhITqQbPklG3ibCVxwGMRfp/v4XqhfdQHdcVfHap6NQ5Wok/4xIA+ui35/MmNa
    33  rtNuC+BdZ1tMuVCPFZcCAwEAAaNQME4wHQYDVR0OBBYEFJvKs8RfJaXTH08W+SGv
    34  zQyKn0H8MB8GA1UdIwQYMBaAFJvKs8RfJaXTH08W+SGvzQyKn0H8MAwGA1UdEwQF
    35  MAMBAf8wDQYJKoZIhvcNAQEFBQADQQBJlffJHybjDGxRMqaRmDhX0+6v02TUKZsW
    36  r5QuVbpQhH6u+0UgcW0jp9QwpxoPTLTWGXEWBBBurxFwiCBhkQ+V
    37  -----END CERTIFICATE-----
    38  `
    39  
    40  var rsaKeyPEM = testingKey(`-----BEGIN RSA TESTING KEY-----
    41  MIIBOwIBAAJBANLJhPHhITqQbPklG3ibCVxwGMRfp/v4XqhfdQHdcVfHap6NQ5Wo
    42  k/4xIA+ui35/MmNartNuC+BdZ1tMuVCPFZcCAwEAAQJAEJ2N+zsR0Xn8/Q6twa4G
    43  6OB1M1WO+k+ztnX/1SvNeWu8D6GImtupLTYgjZcHufykj09jiHmjHx8u8ZZB/o1N
    44  MQIhAPW+eyZo7ay3lMz1V01WVjNKK9QSn1MJlb06h/LuYv9FAiEA25WPedKgVyCW
    45  SmUwbPw8fnTcpqDWE3yTO3vKcebqMSsCIBF3UmVue8YU3jybC3NxuXq3wNm34R8T
    46  xVLHwDXh/6NJAiEAl2oHGGLz64BuAfjKrqwz7qMYr9HCLIe/YsoWq/olzScCIQDi
    47  D2lWusoe2/nEqfDVVWGWlyJ7yOmqaVm/iNUN9B2N2g==
    48  -----END RSA TESTING KEY-----
    49  `)
    50  
    51  // keyPEM is the same as rsaKeyPEM, but declares itself as just
    52  // "PRIVATE KEY", not "RSA PRIVATE KEY".  https://golang.org/issue/4477
    53  var keyPEM = testingKey(`-----BEGIN TESTING KEY-----
    54  MIIBOwIBAAJBANLJhPHhITqQbPklG3ibCVxwGMRfp/v4XqhfdQHdcVfHap6NQ5Wo
    55  k/4xIA+ui35/MmNartNuC+BdZ1tMuVCPFZcCAwEAAQJAEJ2N+zsR0Xn8/Q6twa4G
    56  6OB1M1WO+k+ztnX/1SvNeWu8D6GImtupLTYgjZcHufykj09jiHmjHx8u8ZZB/o1N
    57  MQIhAPW+eyZo7ay3lMz1V01WVjNKK9QSn1MJlb06h/LuYv9FAiEA25WPedKgVyCW
    58  SmUwbPw8fnTcpqDWE3yTO3vKcebqMSsCIBF3UmVue8YU3jybC3NxuXq3wNm34R8T
    59  xVLHwDXh/6NJAiEAl2oHGGLz64BuAfjKrqwz7qMYr9HCLIe/YsoWq/olzScCIQDi
    60  D2lWusoe2/nEqfDVVWGWlyJ7yOmqaVm/iNUN9B2N2g==
    61  -----END TESTING KEY-----
    62  `)
    63  
    64  var ecdsaCertPEM = `-----BEGIN CERTIFICATE-----
    65  MIIB/jCCAWICCQDscdUxw16XFDAJBgcqhkjOPQQBMEUxCzAJBgNVBAYTAkFVMRMw
    66  EQYDVQQIEwpTb21lLVN0YXRlMSEwHwYDVQQKExhJbnRlcm5ldCBXaWRnaXRzIFB0
    67  eSBMdGQwHhcNMTIxMTE0MTI0MDQ4WhcNMTUxMTE0MTI0MDQ4WjBFMQswCQYDVQQG
    68  EwJBVTETMBEGA1UECBMKU29tZS1TdGF0ZTEhMB8GA1UEChMYSW50ZXJuZXQgV2lk
    69  Z2l0cyBQdHkgTHRkMIGbMBAGByqGSM49AgEGBSuBBAAjA4GGAAQBY9+my9OoeSUR
    70  lDQdV/x8LsOuLilthhiS1Tz4aGDHIPwC1mlvnf7fg5lecYpMCrLLhauAc1UJXcgl
    71  01xoLuzgtAEAgv2P/jgytzRSpUYvgLBt1UA0leLYBy6mQQbrNEuqT3INapKIcUv8
    72  XxYP0xMEUksLPq6Ca+CRSqTtrd/23uTnapkwCQYHKoZIzj0EAQOBigAwgYYCQXJo
    73  A7Sl2nLVf+4Iu/tAX/IF4MavARKC4PPHK3zfuGfPR3oCCcsAoz3kAzOeijvd0iXb
    74  H5jBImIxPL4WxQNiBTexAkF8D1EtpYuWdlVQ80/h/f4pBcGiXPqX5h2PQSQY7hP1
    75  +jwM1FGS4fREIOvlBYr/SzzQRtwrvrzGYxDEDbsC0ZGRnA==
    76  -----END CERTIFICATE-----
    77  `
    78  
    79  var ecdsaKeyPEM = testingKey(`-----BEGIN EC PARAMETERS-----
    80  BgUrgQQAIw==
    81  -----END EC PARAMETERS-----
    82  -----BEGIN EC TESTING KEY-----
    83  MIHcAgEBBEIBrsoKp0oqcv6/JovJJDoDVSGWdirrkgCWxrprGlzB9o0X8fV675X0
    84  NwuBenXFfeZvVcwluO7/Q9wkYoPd/t3jGImgBwYFK4EEACOhgYkDgYYABAFj36bL
    85  06h5JRGUNB1X/Hwuw64uKW2GGJLVPPhoYMcg/ALWaW+d/t+DmV5xikwKssuFq4Bz
    86  VQldyCXTXGgu7OC0AQCC/Y/+ODK3NFKlRi+AsG3VQDSV4tgHLqZBBus0S6pPcg1q
    87  kohxS/xfFg/TEwRSSws+roJr4JFKpO2t3/be5OdqmQ==
    88  -----END EC TESTING KEY-----
    89  `)
    90  
    91  var keyPairTests = []struct {
    92  	algo string
    93  	cert string
    94  	key  string
    95  }{
    96  	{"ECDSA", ecdsaCertPEM, ecdsaKeyPEM},
    97  	{"RSA", rsaCertPEM, rsaKeyPEM},
    98  	{"RSA-untyped", rsaCertPEM, keyPEM}, // golang.org/issue/4477
    99  }
   100  
   101  func TestX509KeyPair(t *testing.T) {
   102  	t.Parallel()
   103  	var pem []byte
   104  	for _, test := range keyPairTests {
   105  		pem = []byte(test.cert + test.key)
   106  		if _, err := X509KeyPair(pem, pem); err != nil {
   107  			t.Errorf("Failed to load %s cert followed by %s key: %s", test.algo, test.algo, err)
   108  		}
   109  		pem = []byte(test.key + test.cert)
   110  		if _, err := X509KeyPair(pem, pem); err != nil {
   111  			t.Errorf("Failed to load %s key followed by %s cert: %s", test.algo, test.algo, err)
   112  		}
   113  	}
   114  }
   115  
   116  func TestX509KeyPairErrors(t *testing.T) {
   117  	_, err := X509KeyPair([]byte(rsaKeyPEM), []byte(rsaCertPEM))
   118  	if err == nil {
   119  		t.Fatalf("X509KeyPair didn't return an error when arguments were switched")
   120  	}
   121  	if subStr := "been switched"; !strings.Contains(err.Error(), subStr) {
   122  		t.Fatalf("Expected %q in the error when switching arguments to X509KeyPair, but the error was %q", subStr, err)
   123  	}
   124  
   125  	_, err = X509KeyPair([]byte(rsaCertPEM), []byte(rsaCertPEM))
   126  	if err == nil {
   127  		t.Fatalf("X509KeyPair didn't return an error when both arguments were certificates")
   128  	}
   129  	if subStr := "certificate"; !strings.Contains(err.Error(), subStr) {
   130  		t.Fatalf("Expected %q in the error when both arguments to X509KeyPair were certificates, but the error was %q", subStr, err)
   131  	}
   132  
   133  	const nonsensePEM = `
   134  -----BEGIN NONSENSE-----
   135  Zm9vZm9vZm9v
   136  -----END NONSENSE-----
   137  `
   138  
   139  	_, err = X509KeyPair([]byte(nonsensePEM), []byte(nonsensePEM))
   140  	if err == nil {
   141  		t.Fatalf("X509KeyPair didn't return an error when both arguments were nonsense")
   142  	}
   143  	if subStr := "NONSENSE"; !strings.Contains(err.Error(), subStr) {
   144  		t.Fatalf("Expected %q in the error when both arguments to X509KeyPair were nonsense, but the error was %q", subStr, err)
   145  	}
   146  }
   147  
   148  func TestX509MixedKeyPair(t *testing.T) {
   149  	if _, err := X509KeyPair([]byte(rsaCertPEM), []byte(ecdsaKeyPEM)); err == nil {
   150  		t.Error("Load of RSA certificate succeeded with ECDSA private key")
   151  	}
   152  	if _, err := X509KeyPair([]byte(ecdsaCertPEM), []byte(rsaKeyPEM)); err == nil {
   153  		t.Error("Load of ECDSA certificate succeeded with RSA private key")
   154  	}
   155  }
   156  
   157  func newLocalListener(t testing.TB) net.Listener {
   158  	ln, err := net.Listen("tcp", "127.0.0.1:0")
   159  	if err != nil {
   160  		ln, err = net.Listen("tcp6", "[::1]:0")
   161  	}
   162  	if err != nil {
   163  		t.Fatal(err)
   164  	}
   165  	return ln
   166  }
   167  
   168  func TestDialTimeout(t *testing.T) {
   169  	if testing.Short() {
   170  		t.Skip("skipping in short mode")
   171  	}
   172  	listener := newLocalListener(t)
   173  
   174  	addr := listener.Addr().String()
   175  	defer listener.Close()
   176  
   177  	complete := make(chan bool)
   178  	defer close(complete)
   179  
   180  	go func() {
   181  		conn, err := listener.Accept()
   182  		if err != nil {
   183  			t.Error(err)
   184  			return
   185  		}
   186  		<-complete
   187  		conn.Close()
   188  	}()
   189  
   190  	dialer := &net.Dialer{
   191  		Timeout: 10 * time.Millisecond,
   192  	}
   193  
   194  	var err error
   195  	if _, err = DialWithDialer(dialer, "tcp", addr, nil); err == nil {
   196  		t.Fatal("DialWithTimeout completed successfully")
   197  	}
   198  
   199  	if !isTimeoutError(err) {
   200  		t.Errorf("resulting error not a timeout: %v\nType %T: %#v", err, err, err)
   201  	}
   202  }
   203  
   204  func TestDeadlineOnWrite(t *testing.T) {
   205  	if testing.Short() {
   206  		t.Skip("skipping in short mode")
   207  	}
   208  
   209  	ln := newLocalListener(t)
   210  	defer ln.Close()
   211  
   212  	srvCh := make(chan *Conn, 1)
   213  
   214  	go func() {
   215  		sconn, err := ln.Accept()
   216  		if err != nil {
   217  			srvCh <- nil
   218  			return
   219  		}
   220  		srv := Server(sconn, testConfig.Clone())
   221  		if err := srv.Handshake(); err != nil {
   222  			srvCh <- nil
   223  			return
   224  		}
   225  		srvCh <- srv
   226  	}()
   227  
   228  	clientConfig := testConfig.Clone()
   229  	clientConfig.MaxVersion = VersionTLS12
   230  	conn, err := Dial("tcp", ln.Addr().String(), clientConfig)
   231  	if err != nil {
   232  		t.Fatal(err)
   233  	}
   234  	defer conn.Close()
   235  
   236  	srv := <-srvCh
   237  	if srv == nil {
   238  		t.Error(err)
   239  	}
   240  
   241  	// Make sure the client/server is setup correctly and is able to do a typical Write/Read
   242  	buf := make([]byte, 6)
   243  	if _, err := srv.Write([]byte("foobar")); err != nil {
   244  		t.Errorf("Write err: %v", err)
   245  	}
   246  	if n, err := conn.Read(buf); n != 6 || err != nil || string(buf) != "foobar" {
   247  		t.Errorf("Read = %d, %v, data %q; want 6, nil, foobar", n, err, buf)
   248  	}
   249  
   250  	// Set a deadline which should cause Write to timeout
   251  	if err = srv.SetDeadline(time.Now()); err != nil {
   252  		t.Fatalf("SetDeadline(time.Now()) err: %v", err)
   253  	}
   254  	if _, err = srv.Write([]byte("should fail")); err == nil {
   255  		t.Fatal("Write should have timed out")
   256  	}
   257  
   258  	// Clear deadline and make sure it still times out
   259  	if err = srv.SetDeadline(time.Time{}); err != nil {
   260  		t.Fatalf("SetDeadline(time.Time{}) err: %v", err)
   261  	}
   262  	if _, err = srv.Write([]byte("This connection is permanently broken")); err == nil {
   263  		t.Fatal("Write which previously failed should still time out")
   264  	}
   265  
   266  	// Verify the error
   267  	if ne := err.(net.Error); ne.Temporary() != false {
   268  		t.Error("Write timed out but incorrectly classified the error as Temporary")
   269  	}
   270  	if !isTimeoutError(err) {
   271  		t.Error("Write timed out but did not classify the error as a Timeout")
   272  	}
   273  }
   274  
   275  type readerFunc func([]byte) (int, error)
   276  
   277  func (f readerFunc) Read(b []byte) (int, error) { return f(b) }
   278  
   279  // TestDialer tests that tls.Dialer.DialContext can abort in the middle of a handshake.
   280  // (The other cases are all handled by the existing dial tests in this package, which
   281  // all also flow through the same code shared code paths)
   282  func TestDialer(t *testing.T) {
   283  	ln := newLocalListener(t)
   284  	defer ln.Close()
   285  
   286  	unblockServer := make(chan struct{}) // close-only
   287  	defer close(unblockServer)
   288  	go func() {
   289  		conn, err := ln.Accept()
   290  		if err != nil {
   291  			return
   292  		}
   293  		defer conn.Close()
   294  		<-unblockServer
   295  	}()
   296  
   297  	ctx, cancel := context.WithCancel(context.Background())
   298  	d := Dialer{Config: &Config{
   299  		Rand: readerFunc(func(b []byte) (n int, err error) {
   300  			// By the time crypto/tls wants randomness, that means it has a TCP
   301  			// connection, so we're past the Dialer's dial and now blocked
   302  			// in a handshake. Cancel our context and see if we get unstuck.
   303  			// (Our TCP listener above never reads or writes, so the Handshake
   304  			// would otherwise be stuck forever)
   305  			cancel()
   306  			return len(b), nil
   307  		}),
   308  		ServerName: "foo",
   309  	}}
   310  	_, err := d.DialContext(ctx, "tcp", ln.Addr().String())
   311  	if err != context.Canceled {
   312  		t.Errorf("err = %v; want context.Canceled", err)
   313  	}
   314  }
   315  
   316  func isTimeoutError(err error) bool {
   317  	if ne, ok := err.(net.Error); ok {
   318  		return ne.Timeout()
   319  	}
   320  	return false
   321  }
   322  
   323  // tests that Conn.Read returns (non-zero, io.EOF) instead of
   324  // (non-zero, nil) when a Close (alertCloseNotify) is sitting right
   325  // behind the application data in the buffer.
   326  func TestConnReadNonzeroAndEOF(t *testing.T) {
   327  	// This test is racy: it assumes that after a write to a
   328  	// localhost TCP connection, the peer TCP connection can
   329  	// immediately read it. Because it's racy, we skip this test
   330  	// in short mode, and then retry it several times with an
   331  	// increasing sleep in between our final write (via srv.Close
   332  	// below) and the following read.
   333  	if testing.Short() {
   334  		t.Skip("skipping in short mode")
   335  	}
   336  	var err error
   337  	for delay := time.Millisecond; delay <= 64*time.Millisecond; delay *= 2 {
   338  		if err = testConnReadNonzeroAndEOF(t, delay); err == nil {
   339  			return
   340  		}
   341  	}
   342  	t.Error(err)
   343  }
   344  
   345  func testConnReadNonzeroAndEOF(t *testing.T, delay time.Duration) error {
   346  	ln := newLocalListener(t)
   347  	defer ln.Close()
   348  
   349  	srvCh := make(chan *Conn, 1)
   350  	var serr error
   351  	go func() {
   352  		sconn, err := ln.Accept()
   353  		if err != nil {
   354  			serr = err
   355  			srvCh <- nil
   356  			return
   357  		}
   358  		serverConfig := testConfig.Clone()
   359  		srv := Server(sconn, serverConfig)
   360  		if err := srv.Handshake(); err != nil {
   361  			serr = fmt.Errorf("handshake: %v", err)
   362  			srvCh <- nil
   363  			return
   364  		}
   365  		srvCh <- srv
   366  	}()
   367  
   368  	clientConfig := testConfig.Clone()
   369  	// In TLS 1.3, alerts are encrypted and disguised as application data, so
   370  	// the opportunistic peek won't work.
   371  	clientConfig.MaxVersion = VersionTLS12
   372  	conn, err := Dial("tcp", ln.Addr().String(), clientConfig)
   373  	if err != nil {
   374  		t.Fatal(err)
   375  	}
   376  	defer conn.Close()
   377  
   378  	srv := <-srvCh
   379  	if srv == nil {
   380  		return serr
   381  	}
   382  
   383  	buf := make([]byte, 6)
   384  
   385  	srv.Write([]byte("foobar"))
   386  	n, err := conn.Read(buf)
   387  	if n != 6 || err != nil || string(buf) != "foobar" {
   388  		return fmt.Errorf("Read = %d, %v, data %q; want 6, nil, foobar", n, err, buf)
   389  	}
   390  
   391  	srv.Write([]byte("abcdef"))
   392  	srv.Close()
   393  	time.Sleep(delay)
   394  	n, err = conn.Read(buf)
   395  	if n != 6 || string(buf) != "abcdef" {
   396  		return fmt.Errorf("Read = %d, buf= %q; want 6, abcdef", n, buf)
   397  	}
   398  	if err != io.EOF {
   399  		return fmt.Errorf("Second Read error = %v; want io.EOF", err)
   400  	}
   401  	return nil
   402  }
   403  
   404  func TestTLSUniqueMatches(t *testing.T) {
   405  	ln := newLocalListener(t)
   406  	defer ln.Close()
   407  
   408  	serverTLSUniques := make(chan []byte)
   409  	parentDone := make(chan struct{})
   410  	childDone := make(chan struct{})
   411  	defer close(parentDone)
   412  	go func() {
   413  		defer close(childDone)
   414  		for i := 0; i < 2; i++ {
   415  			sconn, err := ln.Accept()
   416  			if err != nil {
   417  				t.Error(err)
   418  				return
   419  			}
   420  			serverConfig := testConfig.Clone()
   421  			serverConfig.MaxVersion = VersionTLS12 // TLSUnique is not defined in TLS 1.3
   422  			srv := Server(sconn, serverConfig)
   423  			if err := srv.Handshake(); err != nil {
   424  				t.Error(err)
   425  				return
   426  			}
   427  			select {
   428  			case <-parentDone:
   429  				return
   430  			case serverTLSUniques <- srv.ConnectionState().TLSUnique:
   431  			}
   432  		}
   433  	}()
   434  
   435  	clientConfig := testConfig.Clone()
   436  	clientConfig.ClientSessionCache = NewLRUClientSessionCache(1)
   437  	conn, err := Dial("tcp", ln.Addr().String(), clientConfig)
   438  	if err != nil {
   439  		t.Fatal(err)
   440  	}
   441  
   442  	var serverTLSUniquesValue []byte
   443  	select {
   444  	case <-childDone:
   445  		return
   446  	case serverTLSUniquesValue = <-serverTLSUniques:
   447  	}
   448  
   449  	if !bytes.Equal(conn.ConnectionState().TLSUnique, serverTLSUniquesValue) {
   450  		t.Error("client and server channel bindings differ")
   451  	}
   452  	conn.Close()
   453  
   454  	conn, err = Dial("tcp", ln.Addr().String(), clientConfig)
   455  	if err != nil {
   456  		t.Fatal(err)
   457  	}
   458  	defer conn.Close()
   459  	if !conn.ConnectionState().DidResume {
   460  		t.Error("second session did not use resumption")
   461  	}
   462  
   463  	select {
   464  	case <-childDone:
   465  		return
   466  	case serverTLSUniquesValue = <-serverTLSUniques:
   467  	}
   468  
   469  	if !bytes.Equal(conn.ConnectionState().TLSUnique, serverTLSUniquesValue) {
   470  		t.Error("client and server channel bindings differ when session resumption is used")
   471  	}
   472  }
   473  
   474  func TestVerifyHostname(t *testing.T) {
   475  	testenv.MustHaveExternalNetwork(t)
   476  
   477  	c, err := Dial("tcp", "www.google.com:https", nil)
   478  	if err != nil {
   479  		t.Fatal(err)
   480  	}
   481  	if err := c.VerifyHostname("www.google.com"); err != nil {
   482  		t.Fatalf("verify www.google.com: %v", err)
   483  	}
   484  	if err := c.VerifyHostname("www.yahoo.com"); err == nil {
   485  		t.Fatalf("verify www.yahoo.com succeeded")
   486  	}
   487  
   488  	c, err = Dial("tcp", "www.google.com:https", &Config{InsecureSkipVerify: true})
   489  	if err != nil {
   490  		t.Fatal(err)
   491  	}
   492  	if err := c.VerifyHostname("www.google.com"); err == nil {
   493  		t.Fatalf("verify www.google.com succeeded with InsecureSkipVerify=true")
   494  	}
   495  }
   496  
   497  func TestConnCloseBreakingWrite(t *testing.T) {
   498  	ln := newLocalListener(t)
   499  	defer ln.Close()
   500  
   501  	srvCh := make(chan *Conn, 1)
   502  	var serr error
   503  	var sconn net.Conn
   504  	go func() {
   505  		var err error
   506  		sconn, err = ln.Accept()
   507  		if err != nil {
   508  			serr = err
   509  			srvCh <- nil
   510  			return
   511  		}
   512  		serverConfig := testConfig.Clone()
   513  		srv := Server(sconn, serverConfig)
   514  		if err := srv.Handshake(); err != nil {
   515  			serr = fmt.Errorf("handshake: %v", err)
   516  			srvCh <- nil
   517  			return
   518  		}
   519  		srvCh <- srv
   520  	}()
   521  
   522  	cconn, err := net.Dial("tcp", ln.Addr().String())
   523  	if err != nil {
   524  		t.Fatal(err)
   525  	}
   526  	defer cconn.Close()
   527  
   528  	conn := &changeImplConn{
   529  		Conn: cconn,
   530  	}
   531  
   532  	clientConfig := testConfig.Clone()
   533  	tconn := Client(conn, clientConfig)
   534  	if err := tconn.Handshake(); err != nil {
   535  		t.Fatal(err)
   536  	}
   537  
   538  	srv := <-srvCh
   539  	if srv == nil {
   540  		t.Fatal(serr)
   541  	}
   542  	defer sconn.Close()
   543  
   544  	connClosed := make(chan struct{})
   545  	conn.closeFunc = func() error {
   546  		close(connClosed)
   547  		return nil
   548  	}
   549  
   550  	inWrite := make(chan bool, 1)
   551  	var errConnClosed = errors.New("conn closed for test")
   552  	conn.writeFunc = func(p []byte) (n int, err error) {
   553  		inWrite <- true
   554  		<-connClosed
   555  		return 0, errConnClosed
   556  	}
   557  
   558  	closeReturned := make(chan bool, 1)
   559  	go func() {
   560  		<-inWrite
   561  		tconn.Close() // test that this doesn't block forever.
   562  		closeReturned <- true
   563  	}()
   564  
   565  	_, err = tconn.Write([]byte("foo"))
   566  	if err != errConnClosed {
   567  		t.Errorf("Write error = %v; want errConnClosed", err)
   568  	}
   569  
   570  	<-closeReturned
   571  	if err := tconn.Close(); err != net.ErrClosed {
   572  		t.Errorf("Close error = %v; want net.ErrClosed", err)
   573  	}
   574  }
   575  
   576  func TestConnCloseWrite(t *testing.T) {
   577  	ln := newLocalListener(t)
   578  	defer ln.Close()
   579  
   580  	clientDoneChan := make(chan struct{})
   581  
   582  	serverCloseWrite := func() error {
   583  		sconn, err := ln.Accept()
   584  		if err != nil {
   585  			return fmt.Errorf("accept: %v", err)
   586  		}
   587  		defer sconn.Close()
   588  
   589  		serverConfig := testConfig.Clone()
   590  		srv := Server(sconn, serverConfig)
   591  		if err := srv.Handshake(); err != nil {
   592  			return fmt.Errorf("handshake: %v", err)
   593  		}
   594  		defer srv.Close()
   595  
   596  		data, err := io.ReadAll(srv)
   597  		if err != nil {
   598  			return err
   599  		}
   600  		if len(data) > 0 {
   601  			return fmt.Errorf("Read data = %q; want nothing", data)
   602  		}
   603  
   604  		if err := srv.CloseWrite(); err != nil {
   605  			return fmt.Errorf("server CloseWrite: %v", err)
   606  		}
   607  
   608  		// Wait for clientCloseWrite to finish, so we know we
   609  		// tested the CloseWrite before we defer the
   610  		// sconn.Close above, which would also cause the
   611  		// client to unblock like CloseWrite.
   612  		<-clientDoneChan
   613  		return nil
   614  	}
   615  
   616  	clientCloseWrite := func() error {
   617  		defer close(clientDoneChan)
   618  
   619  		clientConfig := testConfig.Clone()
   620  		conn, err := Dial("tcp", ln.Addr().String(), clientConfig)
   621  		if err != nil {
   622  			return err
   623  		}
   624  		if err := conn.Handshake(); err != nil {
   625  			return err
   626  		}
   627  		defer conn.Close()
   628  
   629  		if err := conn.CloseWrite(); err != nil {
   630  			return fmt.Errorf("client CloseWrite: %v", err)
   631  		}
   632  
   633  		if _, err := conn.Write([]byte{0}); err != errShutdown {
   634  			return fmt.Errorf("CloseWrite error = %v; want errShutdown", err)
   635  		}
   636  
   637  		data, err := io.ReadAll(conn)
   638  		if err != nil {
   639  			return err
   640  		}
   641  		if len(data) > 0 {
   642  			return fmt.Errorf("Read data = %q; want nothing", data)
   643  		}
   644  		return nil
   645  	}
   646  
   647  	errChan := make(chan error, 2)
   648  
   649  	go func() { errChan <- serverCloseWrite() }()
   650  	go func() { errChan <- clientCloseWrite() }()
   651  
   652  	for i := 0; i < 2; i++ {
   653  		select {
   654  		case err := <-errChan:
   655  			if err != nil {
   656  				t.Fatal(err)
   657  			}
   658  		case <-time.After(10 * time.Second):
   659  			t.Fatal("deadlock")
   660  		}
   661  	}
   662  
   663  	// Also test CloseWrite being called before the handshake is
   664  	// finished:
   665  	{
   666  		ln2 := newLocalListener(t)
   667  		defer ln2.Close()
   668  
   669  		netConn, err := net.Dial("tcp", ln2.Addr().String())
   670  		if err != nil {
   671  			t.Fatal(err)
   672  		}
   673  		defer netConn.Close()
   674  		conn := Client(netConn, testConfig.Clone())
   675  
   676  		if err := conn.CloseWrite(); err != errEarlyCloseWrite {
   677  			t.Errorf("CloseWrite error = %v; want errEarlyCloseWrite", err)
   678  		}
   679  	}
   680  }
   681  
   682  func TestWarningAlertFlood(t *testing.T) {
   683  	ln := newLocalListener(t)
   684  	defer ln.Close()
   685  
   686  	server := func() error {
   687  		sconn, err := ln.Accept()
   688  		if err != nil {
   689  			return fmt.Errorf("accept: %v", err)
   690  		}
   691  		defer sconn.Close()
   692  
   693  		serverConfig := testConfig.Clone()
   694  		srv := Server(sconn, serverConfig)
   695  		if err := srv.Handshake(); err != nil {
   696  			return fmt.Errorf("handshake: %v", err)
   697  		}
   698  		defer srv.Close()
   699  
   700  		_, err = io.ReadAll(srv)
   701  		if err == nil {
   702  			return errors.New("unexpected lack of error from server")
   703  		}
   704  		const expected = "too many ignored"
   705  		if str := err.Error(); !strings.Contains(str, expected) {
   706  			return fmt.Errorf("expected error containing %q, but saw: %s", expected, str)
   707  		}
   708  
   709  		return nil
   710  	}
   711  
   712  	errChan := make(chan error, 1)
   713  	go func() { errChan <- server() }()
   714  
   715  	clientConfig := testConfig.Clone()
   716  	clientConfig.MaxVersion = VersionTLS12 // there are no warning alerts in TLS 1.3
   717  	conn, err := Dial("tcp", ln.Addr().String(), clientConfig)
   718  	if err != nil {
   719  		t.Fatal(err)
   720  	}
   721  	defer conn.Close()
   722  	if err := conn.Handshake(); err != nil {
   723  		t.Fatal(err)
   724  	}
   725  
   726  	for i := 0; i < maxUselessRecords+1; i++ {
   727  		conn.sendAlert(alertNoRenegotiation)
   728  	}
   729  
   730  	if err := <-errChan; err != nil {
   731  		t.Fatal(err)
   732  	}
   733  }
   734  
   735  func TestCloneFuncFields(t *testing.T) {
   736  	const expectedCount = 6
   737  	called := 0
   738  
   739  	c1 := Config{
   740  		Time: func() time.Time {
   741  			called |= 1 << 0
   742  			return time.Time{}
   743  		},
   744  		GetCertificate: func(*ClientHelloInfo) (*Certificate, error) {
   745  			called |= 1 << 1
   746  			return nil, nil
   747  		},
   748  		GetClientCertificate: func(*CertificateRequestInfo) (*Certificate, error) {
   749  			called |= 1 << 2
   750  			return nil, nil
   751  		},
   752  		GetConfigForClient: func(*ClientHelloInfo) (*Config, error) {
   753  			called |= 1 << 3
   754  			return nil, nil
   755  		},
   756  		VerifyPeerCertificate: func(rawCerts [][]byte, verifiedChains [][]*x509.Certificate) error {
   757  			called |= 1 << 4
   758  			return nil
   759  		},
   760  		VerifyConnection: func(ConnectionState) error {
   761  			called |= 1 << 5
   762  			return nil
   763  		},
   764  	}
   765  
   766  	c2 := c1.Clone()
   767  
   768  	c2.Time()
   769  	c2.GetCertificate(nil)
   770  	c2.GetClientCertificate(nil)
   771  	c2.GetConfigForClient(nil)
   772  	c2.VerifyPeerCertificate(nil, nil)
   773  	c2.VerifyConnection(ConnectionState{})
   774  
   775  	if called != (1<<expectedCount)-1 {
   776  		t.Fatalf("expected %d calls but saw calls %b", expectedCount, called)
   777  	}
   778  }
   779  
   780  func TestCloneNonFuncFields(t *testing.T) {
   781  	var c1 Config
   782  	v := reflect.ValueOf(&c1).Elem()
   783  
   784  	typ := v.Type()
   785  	for i := 0; i < typ.NumField(); i++ {
   786  		f := v.Field(i)
   787  		// testing/quick can't handle functions or interfaces and so
   788  		// isn't used here.
   789  		switch fn := typ.Field(i).Name; fn {
   790  		case "Rand":
   791  			f.Set(reflect.ValueOf(io.Reader(os.Stdin)))
   792  		case "Time", "GetCertificate", "GetConfigForClient", "VerifyPeerCertificate", "VerifyConnection", "GetClientCertificate":
   793  			// DeepEqual can't compare functions. If you add a
   794  			// function field to this list, you must also change
   795  			// TestCloneFuncFields to ensure that the func field is
   796  			// cloned.
   797  		case "Certificates":
   798  			f.Set(reflect.ValueOf([]Certificate{
   799  				{Certificate: [][]byte{{'b'}}},
   800  			}))
   801  		case "NameToCertificate":
   802  			f.Set(reflect.ValueOf(map[string]*Certificate{"a": nil}))
   803  		case "RootCAs", "ClientCAs":
   804  			f.Set(reflect.ValueOf(x509.NewCertPool()))
   805  		case "ClientSessionCache":
   806  			f.Set(reflect.ValueOf(NewLRUClientSessionCache(10)))
   807  		case "KeyLogWriter":
   808  			f.Set(reflect.ValueOf(io.Writer(os.Stdout)))
   809  		case "NextProtos":
   810  			f.Set(reflect.ValueOf([]string{"a", "b"}))
   811  		case "ServerName":
   812  			f.Set(reflect.ValueOf("b"))
   813  		case "ClientAuth":
   814  			f.Set(reflect.ValueOf(VerifyClientCertIfGiven))
   815  		case "InsecureSkipVerify", "SessionTicketsDisabled", "DynamicRecordSizingDisabled", "PreferServerCipherSuites":
   816  			f.Set(reflect.ValueOf(true))
   817  		case "MinVersion", "MaxVersion":
   818  			f.Set(reflect.ValueOf(uint16(VersionTLS12)))
   819  		case "SessionTicketKey":
   820  			f.Set(reflect.ValueOf([32]byte{}))
   821  		case "CipherSuites":
   822  			f.Set(reflect.ValueOf([]uint16{1, 2}))
   823  		case "CurvePreferences":
   824  			f.Set(reflect.ValueOf([]CurveID{CurveP256}))
   825  		case "Renegotiation":
   826  			f.Set(reflect.ValueOf(RenegotiateOnceAsClient))
   827  		case "mutex", "autoSessionTicketKeys", "sessionTicketKeys":
   828  			continue // these are unexported fields that are handled separately
   829  		default:
   830  			t.Errorf("all fields must be accounted for, but saw unknown field %q", fn)
   831  		}
   832  	}
   833  	// Set the unexported fields related to session ticket keys, which are copied with Clone().
   834  	c1.autoSessionTicketKeys = []ticketKey{c1.ticketKeyFromBytes(c1.SessionTicketKey)}
   835  	c1.sessionTicketKeys = []ticketKey{c1.ticketKeyFromBytes(c1.SessionTicketKey)}
   836  
   837  	c2 := c1.Clone()
   838  	if !reflect.DeepEqual(&c1, c2) {
   839  		t.Errorf("clone failed to copy a field")
   840  	}
   841  }
   842  
   843  func TestCloneNilConfig(t *testing.T) {
   844  	var config *Config
   845  	if cc := config.Clone(); cc != nil {
   846  		t.Fatalf("Clone with nil should return nil, got: %+v", cc)
   847  	}
   848  }
   849  
   850  // changeImplConn is a net.Conn which can change its Write and Close
   851  // methods.
   852  type changeImplConn struct {
   853  	net.Conn
   854  	writeFunc func([]byte) (int, error)
   855  	closeFunc func() error
   856  }
   857  
   858  func (w *changeImplConn) Write(p []byte) (n int, err error) {
   859  	if w.writeFunc != nil {
   860  		return w.writeFunc(p)
   861  	}
   862  	return w.Conn.Write(p)
   863  }
   864  
   865  func (w *changeImplConn) Close() error {
   866  	if w.closeFunc != nil {
   867  		return w.closeFunc()
   868  	}
   869  	return w.Conn.Close()
   870  }
   871  
   872  func throughput(b *testing.B, version uint16, totalBytes int64, dynamicRecordSizingDisabled bool) {
   873  	ln := newLocalListener(b)
   874  	defer ln.Close()
   875  
   876  	N := b.N
   877  
   878  	// Less than 64KB because Windows appears to use a TCP rwin < 64KB.
   879  	// See Issue #15899.
   880  	const bufsize = 32 << 10
   881  
   882  	go func() {
   883  		buf := make([]byte, bufsize)
   884  		for i := 0; i < N; i++ {
   885  			sconn, err := ln.Accept()
   886  			if err != nil {
   887  				// panic rather than synchronize to avoid benchmark overhead
   888  				// (cannot call b.Fatal in goroutine)
   889  				panic(fmt.Errorf("accept: %v", err))
   890  			}
   891  			serverConfig := testConfig.Clone()
   892  			serverConfig.CipherSuites = nil // the defaults may prefer faster ciphers
   893  			serverConfig.DynamicRecordSizingDisabled = dynamicRecordSizingDisabled
   894  			srv := Server(sconn, serverConfig)
   895  			if err := srv.Handshake(); err != nil {
   896  				panic(fmt.Errorf("handshake: %v", err))
   897  			}
   898  			if _, err := io.CopyBuffer(srv, srv, buf); err != nil {
   899  				panic(fmt.Errorf("copy buffer: %v", err))
   900  			}
   901  		}
   902  	}()
   903  
   904  	b.SetBytes(totalBytes)
   905  	clientConfig := testConfig.Clone()
   906  	clientConfig.CipherSuites = nil // the defaults may prefer faster ciphers
   907  	clientConfig.DynamicRecordSizingDisabled = dynamicRecordSizingDisabled
   908  	clientConfig.MaxVersion = version
   909  
   910  	buf := make([]byte, bufsize)
   911  	chunks := int(math.Ceil(float64(totalBytes) / float64(len(buf))))
   912  	for i := 0; i < N; i++ {
   913  		conn, err := Dial("tcp", ln.Addr().String(), clientConfig)
   914  		if err != nil {
   915  			b.Fatal(err)
   916  		}
   917  		for j := 0; j < chunks; j++ {
   918  			_, err := conn.Write(buf)
   919  			if err != nil {
   920  				b.Fatal(err)
   921  			}
   922  			_, err = io.ReadFull(conn, buf)
   923  			if err != nil {
   924  				b.Fatal(err)
   925  			}
   926  		}
   927  		conn.Close()
   928  	}
   929  }
   930  
   931  func BenchmarkThroughput(b *testing.B) {
   932  	for _, mode := range []string{"Max", "Dynamic"} {
   933  		for size := 1; size <= 64; size <<= 1 {
   934  			name := fmt.Sprintf("%sPacket/%dMB", mode, size)
   935  			b.Run(name, func(b *testing.B) {
   936  				b.Run("TLSv12", func(b *testing.B) {
   937  					throughput(b, VersionTLS12, int64(size<<20), mode == "Max")
   938  				})
   939  				b.Run("TLSv13", func(b *testing.B) {
   940  					throughput(b, VersionTLS13, int64(size<<20), mode == "Max")
   941  				})
   942  			})
   943  		}
   944  	}
   945  }
   946  
   947  type slowConn struct {
   948  	net.Conn
   949  	bps int
   950  }
   951  
   952  func (c *slowConn) Write(p []byte) (int, error) {
   953  	if c.bps == 0 {
   954  		panic("too slow")
   955  	}
   956  	t0 := time.Now()
   957  	wrote := 0
   958  	for wrote < len(p) {
   959  		time.Sleep(100 * time.Microsecond)
   960  		allowed := int(time.Since(t0).Seconds()*float64(c.bps)) / 8
   961  		if allowed > len(p) {
   962  			allowed = len(p)
   963  		}
   964  		if wrote < allowed {
   965  			n, err := c.Conn.Write(p[wrote:allowed])
   966  			wrote += n
   967  			if err != nil {
   968  				return wrote, err
   969  			}
   970  		}
   971  	}
   972  	return len(p), nil
   973  }
   974  
   975  func latency(b *testing.B, version uint16, bps int, dynamicRecordSizingDisabled bool) {
   976  	ln := newLocalListener(b)
   977  	defer ln.Close()
   978  
   979  	N := b.N
   980  
   981  	go func() {
   982  		for i := 0; i < N; i++ {
   983  			sconn, err := ln.Accept()
   984  			if err != nil {
   985  				// panic rather than synchronize to avoid benchmark overhead
   986  				// (cannot call b.Fatal in goroutine)
   987  				panic(fmt.Errorf("accept: %v", err))
   988  			}
   989  			serverConfig := testConfig.Clone()
   990  			serverConfig.DynamicRecordSizingDisabled = dynamicRecordSizingDisabled
   991  			srv := Server(&slowConn{sconn, bps}, serverConfig)
   992  			if err := srv.Handshake(); err != nil {
   993  				panic(fmt.Errorf("handshake: %v", err))
   994  			}
   995  			io.Copy(srv, srv)
   996  		}
   997  	}()
   998  
   999  	clientConfig := testConfig.Clone()
  1000  	clientConfig.DynamicRecordSizingDisabled = dynamicRecordSizingDisabled
  1001  	clientConfig.MaxVersion = version
  1002  
  1003  	buf := make([]byte, 16384)
  1004  	peek := make([]byte, 1)
  1005  
  1006  	for i := 0; i < N; i++ {
  1007  		conn, err := Dial("tcp", ln.Addr().String(), clientConfig)
  1008  		if err != nil {
  1009  			b.Fatal(err)
  1010  		}
  1011  		// make sure we're connected and previous connection has stopped
  1012  		if _, err := conn.Write(buf[:1]); err != nil {
  1013  			b.Fatal(err)
  1014  		}
  1015  		if _, err := io.ReadFull(conn, peek); err != nil {
  1016  			b.Fatal(err)
  1017  		}
  1018  		if _, err := conn.Write(buf); err != nil {
  1019  			b.Fatal(err)
  1020  		}
  1021  		if _, err = io.ReadFull(conn, peek); err != nil {
  1022  			b.Fatal(err)
  1023  		}
  1024  		conn.Close()
  1025  	}
  1026  }
  1027  
  1028  func BenchmarkLatency(b *testing.B) {
  1029  	for _, mode := range []string{"Max", "Dynamic"} {
  1030  		for _, kbps := range []int{200, 500, 1000, 2000, 5000} {
  1031  			name := fmt.Sprintf("%sPacket/%dkbps", mode, kbps)
  1032  			b.Run(name, func(b *testing.B) {
  1033  				b.Run("TLSv12", func(b *testing.B) {
  1034  					latency(b, VersionTLS12, kbps*1000, mode == "Max")
  1035  				})
  1036  				b.Run("TLSv13", func(b *testing.B) {
  1037  					latency(b, VersionTLS13, kbps*1000, mode == "Max")
  1038  				})
  1039  			})
  1040  		}
  1041  	}
  1042  }
  1043  
  1044  func TestConnectionStateMarshal(t *testing.T) {
  1045  	cs := &ConnectionState{}
  1046  	_, err := json.Marshal(cs)
  1047  	if err != nil {
  1048  		t.Errorf("json.Marshal failed on ConnectionState: %v", err)
  1049  	}
  1050  }
  1051  
  1052  func TestConnectionState(t *testing.T) {
  1053  	issuer, err := x509.ParseCertificate(testRSACertificateIssuer)
  1054  	if err != nil {
  1055  		panic(err)
  1056  	}
  1057  	rootCAs := x509.NewCertPool()
  1058  	rootCAs.AddCert(issuer)
  1059  
  1060  	now := func() time.Time { return time.Unix(1476984729, 0) }
  1061  
  1062  	const alpnProtocol = "golang"
  1063  	const serverName = "example.golang"
  1064  	var scts = [][]byte{[]byte("dummy sct 1"), []byte("dummy sct 2")}
  1065  	var ocsp = []byte("dummy ocsp")
  1066  
  1067  	for _, v := range []uint16{VersionTLS12, VersionTLS13} {
  1068  		var name string
  1069  		switch v {
  1070  		case VersionTLS12:
  1071  			name = "TLSv12"
  1072  		case VersionTLS13:
  1073  			name = "TLSv13"
  1074  		}
  1075  		t.Run(name, func(t *testing.T) {
  1076  			config := &Config{
  1077  				Time:         now,
  1078  				Rand:         zeroSource{},
  1079  				Certificates: make([]Certificate, 1),
  1080  				MaxVersion:   v,
  1081  				RootCAs:      rootCAs,
  1082  				ClientCAs:    rootCAs,
  1083  				ClientAuth:   RequireAndVerifyClientCert,
  1084  				NextProtos:   []string{alpnProtocol},
  1085  				ServerName:   serverName,
  1086  			}
  1087  			config.Certificates[0].Certificate = [][]byte{testRSACertificate}
  1088  			config.Certificates[0].PrivateKey = testRSAPrivateKey
  1089  			config.Certificates[0].SignedCertificateTimestamps = scts
  1090  			config.Certificates[0].OCSPStaple = ocsp
  1091  
  1092  			ss, cs, err := testHandshake(t, config, config)
  1093  			if err != nil {
  1094  				t.Fatalf("Handshake failed: %v", err)
  1095  			}
  1096  
  1097  			if ss.Version != v || cs.Version != v {
  1098  				t.Errorf("Got versions %x (server) and %x (client), expected %x", ss.Version, cs.Version, v)
  1099  			}
  1100  
  1101  			if !ss.HandshakeComplete || !cs.HandshakeComplete {
  1102  				t.Errorf("Got HandshakeComplete %v (server) and %v (client), expected true", ss.HandshakeComplete, cs.HandshakeComplete)
  1103  			}
  1104  
  1105  			if ss.DidResume || cs.DidResume {
  1106  				t.Errorf("Got DidResume %v (server) and %v (client), expected false", ss.DidResume, cs.DidResume)
  1107  			}
  1108  
  1109  			if ss.CipherSuite == 0 || cs.CipherSuite == 0 {
  1110  				t.Errorf("Got invalid cipher suite: %v (server) and %v (client)", ss.CipherSuite, cs.CipherSuite)
  1111  			}
  1112  
  1113  			if ss.NegotiatedProtocol != alpnProtocol || cs.NegotiatedProtocol != alpnProtocol {
  1114  				t.Errorf("Got negotiated protocol %q (server) and %q (client), expected %q", ss.NegotiatedProtocol, cs.NegotiatedProtocol, alpnProtocol)
  1115  			}
  1116  
  1117  			if !cs.NegotiatedProtocolIsMutual {
  1118  				t.Errorf("Got false NegotiatedProtocolIsMutual on the client side")
  1119  			}
  1120  			// NegotiatedProtocolIsMutual on the server side is unspecified.
  1121  
  1122  			if ss.ServerName != serverName {
  1123  				t.Errorf("Got server name %q, expected %q", ss.ServerName, serverName)
  1124  			}
  1125  			if cs.ServerName != serverName {
  1126  				t.Errorf("Got server name on client connection %q, expected %q", cs.ServerName, serverName)
  1127  			}
  1128  
  1129  			if len(ss.PeerCertificates) != 1 || len(cs.PeerCertificates) != 1 {
  1130  				t.Errorf("Got %d (server) and %d (client) peer certificates, expected %d", len(ss.PeerCertificates), len(cs.PeerCertificates), 1)
  1131  			}
  1132  
  1133  			if len(ss.VerifiedChains) != 1 || len(cs.VerifiedChains) != 1 {
  1134  				t.Errorf("Got %d (server) and %d (client) verified chains, expected %d", len(ss.VerifiedChains), len(cs.VerifiedChains), 1)
  1135  			} else if len(ss.VerifiedChains[0]) != 2 || len(cs.VerifiedChains[0]) != 2 {
  1136  				t.Errorf("Got %d (server) and %d (client) long verified chain, expected %d", len(ss.VerifiedChains[0]), len(cs.VerifiedChains[0]), 2)
  1137  			}
  1138  
  1139  			if len(cs.SignedCertificateTimestamps) != 2 {
  1140  				t.Errorf("Got %d SCTs, expected %d", len(cs.SignedCertificateTimestamps), 2)
  1141  			}
  1142  			if !bytes.Equal(cs.OCSPResponse, ocsp) {
  1143  				t.Errorf("Got OCSPs %x, expected %x", cs.OCSPResponse, ocsp)
  1144  			}
  1145  			// Only TLS 1.3 supports OCSP and SCTs on client certs.
  1146  			if v == VersionTLS13 {
  1147  				if len(ss.SignedCertificateTimestamps) != 2 {
  1148  					t.Errorf("Got %d client SCTs, expected %d", len(ss.SignedCertificateTimestamps), 2)
  1149  				}
  1150  				if !bytes.Equal(ss.OCSPResponse, ocsp) {
  1151  					t.Errorf("Got client OCSPs %x, expected %x", ss.OCSPResponse, ocsp)
  1152  				}
  1153  			}
  1154  
  1155  			if v == VersionTLS13 {
  1156  				if ss.TLSUnique != nil || cs.TLSUnique != nil {
  1157  					t.Errorf("Got TLSUnique %x (server) and %x (client), expected nil in TLS 1.3", ss.TLSUnique, cs.TLSUnique)
  1158  				}
  1159  			} else {
  1160  				if ss.TLSUnique == nil || cs.TLSUnique == nil {
  1161  					t.Errorf("Got TLSUnique %x (server) and %x (client), expected non-nil", ss.TLSUnique, cs.TLSUnique)
  1162  				}
  1163  			}
  1164  		})
  1165  	}
  1166  }
  1167  
  1168  // Issue 28744: Ensure that we don't modify memory
  1169  // that Config doesn't own such as Certificates.
  1170  func TestBuildNameToCertificate_doesntModifyCertificates(t *testing.T) {
  1171  	c0 := Certificate{
  1172  		Certificate: [][]byte{testRSACertificate},
  1173  		PrivateKey:  testRSAPrivateKey,
  1174  	}
  1175  	c1 := Certificate{
  1176  		Certificate: [][]byte{testSNICertificate},
  1177  		PrivateKey:  testRSAPrivateKey,
  1178  	}
  1179  	config := testConfig.Clone()
  1180  	config.Certificates = []Certificate{c0, c1}
  1181  
  1182  	config.BuildNameToCertificate()
  1183  	got := config.Certificates
  1184  	want := []Certificate{c0, c1}
  1185  	if !reflect.DeepEqual(got, want) {
  1186  		t.Fatalf("Certificates were mutated by BuildNameToCertificate\nGot: %#v\nWant: %#v\n", got, want)
  1187  	}
  1188  }
  1189  
  1190  func testingKey(s string) string { return strings.ReplaceAll(s, "TESTING KEY", "PRIVATE KEY") }
  1191  
  1192  func TestClientHelloInfo_SupportsCertificate(t *testing.T) {
  1193  	rsaCert := &Certificate{
  1194  		Certificate: [][]byte{testRSACertificate},
  1195  		PrivateKey:  testRSAPrivateKey,
  1196  	}
  1197  	pkcs1Cert := &Certificate{
  1198  		Certificate:                  [][]byte{testRSACertificate},
  1199  		PrivateKey:                   testRSAPrivateKey,
  1200  		SupportedSignatureAlgorithms: []SignatureScheme{PKCS1WithSHA1, PKCS1WithSHA256},
  1201  	}
  1202  	ecdsaCert := &Certificate{
  1203  		// ECDSA P-256 certificate
  1204  		Certificate: [][]byte{testP256Certificate},
  1205  		PrivateKey:  testP256PrivateKey,
  1206  	}
  1207  	ed25519Cert := &Certificate{
  1208  		Certificate: [][]byte{testEd25519Certificate},
  1209  		PrivateKey:  testEd25519PrivateKey,
  1210  	}
  1211  
  1212  	tests := []struct {
  1213  		c       *Certificate
  1214  		chi     *ClientHelloInfo
  1215  		wantErr string
  1216  	}{
  1217  		{rsaCert, &ClientHelloInfo{
  1218  			ServerName:        "example.golang",
  1219  			SignatureSchemes:  []SignatureScheme{PSSWithSHA256},
  1220  			SupportedVersions: []uint16{VersionTLS13},
  1221  		}, ""},
  1222  		{ecdsaCert, &ClientHelloInfo{
  1223  			SignatureSchemes:  []SignatureScheme{PSSWithSHA256, ECDSAWithP256AndSHA256},
  1224  			SupportedVersions: []uint16{VersionTLS13, VersionTLS12},
  1225  		}, ""},
  1226  		{rsaCert, &ClientHelloInfo{
  1227  			ServerName:        "example.com",
  1228  			SignatureSchemes:  []SignatureScheme{PSSWithSHA256},
  1229  			SupportedVersions: []uint16{VersionTLS13},
  1230  		}, "not valid for requested server name"},
  1231  		{ecdsaCert, &ClientHelloInfo{
  1232  			SignatureSchemes:  []SignatureScheme{ECDSAWithP384AndSHA384},
  1233  			SupportedVersions: []uint16{VersionTLS13},
  1234  		}, "signature algorithms"},
  1235  		{pkcs1Cert, &ClientHelloInfo{
  1236  			SignatureSchemes:  []SignatureScheme{PSSWithSHA256, ECDSAWithP256AndSHA256},
  1237  			SupportedVersions: []uint16{VersionTLS13},
  1238  		}, "signature algorithms"},
  1239  
  1240  		{rsaCert, &ClientHelloInfo{
  1241  			CipherSuites:      []uint16{TLS_RSA_WITH_AES_128_GCM_SHA256},
  1242  			SignatureSchemes:  []SignatureScheme{PKCS1WithSHA1},
  1243  			SupportedVersions: []uint16{VersionTLS13, VersionTLS12},
  1244  		}, "signature algorithms"},
  1245  		{rsaCert, &ClientHelloInfo{
  1246  			CipherSuites:      []uint16{TLS_RSA_WITH_AES_128_GCM_SHA256},
  1247  			SignatureSchemes:  []SignatureScheme{PKCS1WithSHA1},
  1248  			SupportedVersions: []uint16{VersionTLS13, VersionTLS12},
  1249  			config: &Config{
  1250  				MaxVersion: VersionTLS12,
  1251  			},
  1252  		}, ""}, // Check that mutual version selection works.
  1253  
  1254  		{ecdsaCert, &ClientHelloInfo{
  1255  			CipherSuites:      []uint16{TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256},
  1256  			SupportedCurves:   []CurveID{CurveP256},
  1257  			SupportedPoints:   []uint8{pointFormatUncompressed},
  1258  			SignatureSchemes:  []SignatureScheme{ECDSAWithP256AndSHA256},
  1259  			SupportedVersions: []uint16{VersionTLS12},
  1260  		}, ""},
  1261  		{ecdsaCert, &ClientHelloInfo{
  1262  			CipherSuites:      []uint16{TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256},
  1263  			SupportedCurves:   []CurveID{CurveP256},
  1264  			SupportedPoints:   []uint8{pointFormatUncompressed},
  1265  			SignatureSchemes:  []SignatureScheme{ECDSAWithP384AndSHA384},
  1266  			SupportedVersions: []uint16{VersionTLS12},
  1267  		}, ""}, // TLS 1.2 does not restrict curves based on the SignatureScheme.
  1268  		{ecdsaCert, &ClientHelloInfo{
  1269  			CipherSuites:      []uint16{TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256},
  1270  			SupportedCurves:   []CurveID{CurveP256},
  1271  			SupportedPoints:   []uint8{pointFormatUncompressed},
  1272  			SignatureSchemes:  nil,
  1273  			SupportedVersions: []uint16{VersionTLS12},
  1274  		}, ""}, // TLS 1.2 comes with default signature schemes.
  1275  		{ecdsaCert, &ClientHelloInfo{
  1276  			CipherSuites:      []uint16{TLS_RSA_WITH_AES_128_GCM_SHA256},
  1277  			SupportedCurves:   []CurveID{CurveP256},
  1278  			SupportedPoints:   []uint8{pointFormatUncompressed},
  1279  			SignatureSchemes:  []SignatureScheme{ECDSAWithP256AndSHA256},
  1280  			SupportedVersions: []uint16{VersionTLS12},
  1281  		}, "cipher suite"},
  1282  		{ecdsaCert, &ClientHelloInfo{
  1283  			CipherSuites:      []uint16{TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256},
  1284  			SupportedCurves:   []CurveID{CurveP256},
  1285  			SupportedPoints:   []uint8{pointFormatUncompressed},
  1286  			SignatureSchemes:  []SignatureScheme{ECDSAWithP256AndSHA256},
  1287  			SupportedVersions: []uint16{VersionTLS12},
  1288  			config: &Config{
  1289  				CipherSuites: []uint16{TLS_RSA_WITH_AES_128_GCM_SHA256},
  1290  			},
  1291  		}, "cipher suite"},
  1292  		{ecdsaCert, &ClientHelloInfo{
  1293  			CipherSuites:      []uint16{TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256},
  1294  			SupportedCurves:   []CurveID{CurveP384},
  1295  			SupportedPoints:   []uint8{pointFormatUncompressed},
  1296  			SignatureSchemes:  []SignatureScheme{ECDSAWithP256AndSHA256},
  1297  			SupportedVersions: []uint16{VersionTLS12},
  1298  		}, "certificate curve"},
  1299  		{ecdsaCert, &ClientHelloInfo{
  1300  			CipherSuites:      []uint16{TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256},
  1301  			SupportedCurves:   []CurveID{CurveP256},
  1302  			SupportedPoints:   []uint8{1},
  1303  			SignatureSchemes:  []SignatureScheme{ECDSAWithP256AndSHA256},
  1304  			SupportedVersions: []uint16{VersionTLS12},
  1305  		}, "doesn't support ECDHE"},
  1306  		{ecdsaCert, &ClientHelloInfo{
  1307  			CipherSuites:      []uint16{TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256},
  1308  			SupportedCurves:   []CurveID{CurveP256},
  1309  			SupportedPoints:   []uint8{pointFormatUncompressed},
  1310  			SignatureSchemes:  []SignatureScheme{PSSWithSHA256},
  1311  			SupportedVersions: []uint16{VersionTLS12},
  1312  		}, "signature algorithms"},
  1313  
  1314  		{ed25519Cert, &ClientHelloInfo{
  1315  			CipherSuites:      []uint16{TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256},
  1316  			SupportedCurves:   []CurveID{CurveP256}, // only relevant for ECDHE support
  1317  			SupportedPoints:   []uint8{pointFormatUncompressed},
  1318  			SignatureSchemes:  []SignatureScheme{Ed25519},
  1319  			SupportedVersions: []uint16{VersionTLS12},
  1320  		}, ""},
  1321  		{ed25519Cert, &ClientHelloInfo{
  1322  			CipherSuites:      []uint16{TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256},
  1323  			SupportedCurves:   []CurveID{CurveP256}, // only relevant for ECDHE support
  1324  			SupportedPoints:   []uint8{pointFormatUncompressed},
  1325  			SignatureSchemes:  []SignatureScheme{Ed25519},
  1326  			SupportedVersions: []uint16{VersionTLS10},
  1327  		}, "doesn't support Ed25519"},
  1328  		{ed25519Cert, &ClientHelloInfo{
  1329  			CipherSuites:      []uint16{TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256},
  1330  			SupportedCurves:   []CurveID{},
  1331  			SupportedPoints:   []uint8{pointFormatUncompressed},
  1332  			SignatureSchemes:  []SignatureScheme{Ed25519},
  1333  			SupportedVersions: []uint16{VersionTLS12},
  1334  		}, "doesn't support ECDHE"},
  1335  
  1336  		{rsaCert, &ClientHelloInfo{
  1337  			CipherSuites:      []uint16{TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA},
  1338  			SupportedCurves:   []CurveID{CurveP256}, // only relevant for ECDHE support
  1339  			SupportedPoints:   []uint8{pointFormatUncompressed},
  1340  			SupportedVersions: []uint16{VersionTLS10},
  1341  		}, ""},
  1342  		{rsaCert, &ClientHelloInfo{
  1343  			CipherSuites:      []uint16{TLS_RSA_WITH_AES_128_GCM_SHA256},
  1344  			SupportedVersions: []uint16{VersionTLS12},
  1345  		}, ""}, // static RSA fallback
  1346  	}
  1347  	for i, tt := range tests {
  1348  		err := tt.chi.SupportsCertificate(tt.c)
  1349  		switch {
  1350  		case tt.wantErr == "" && err != nil:
  1351  			t.Errorf("%d: unexpected error: %v", i, err)
  1352  		case tt.wantErr != "" && err == nil:
  1353  			t.Errorf("%d: unexpected success", i)
  1354  		case tt.wantErr != "" && !strings.Contains(err.Error(), tt.wantErr):
  1355  			t.Errorf("%d: got error %q, expected %q", i, err, tt.wantErr)
  1356  		}
  1357  	}
  1358  }
  1359  
  1360  func TestCipherSuites(t *testing.T) {
  1361  	var lastID uint16
  1362  	for _, c := range CipherSuites() {
  1363  		if lastID > c.ID {
  1364  			t.Errorf("CipherSuites are not ordered by ID: got %#04x after %#04x", c.ID, lastID)
  1365  		} else {
  1366  			lastID = c.ID
  1367  		}
  1368  
  1369  		if c.Insecure {
  1370  			t.Errorf("%#04x: Insecure CipherSuite returned by CipherSuites()", c.ID)
  1371  		}
  1372  	}
  1373  	lastID = 0
  1374  	for _, c := range InsecureCipherSuites() {
  1375  		if lastID > c.ID {
  1376  			t.Errorf("InsecureCipherSuites are not ordered by ID: got %#04x after %#04x", c.ID, lastID)
  1377  		} else {
  1378  			lastID = c.ID
  1379  		}
  1380  
  1381  		if !c.Insecure {
  1382  			t.Errorf("%#04x: not Insecure CipherSuite returned by InsecureCipherSuites()", c.ID)
  1383  		}
  1384  	}
  1385  
  1386  	cipherSuiteByID := func(id uint16) *CipherSuite {
  1387  		for _, c := range CipherSuites() {
  1388  			if c.ID == id {
  1389  				return c
  1390  			}
  1391  		}
  1392  		for _, c := range InsecureCipherSuites() {
  1393  			if c.ID == id {
  1394  				return c
  1395  			}
  1396  		}
  1397  		return nil
  1398  	}
  1399  
  1400  	for _, c := range cipherSuites {
  1401  		cc := cipherSuiteByID(c.id)
  1402  		if cc == nil {
  1403  			t.Errorf("%#04x: no CipherSuite entry", c.id)
  1404  			continue
  1405  		}
  1406  
  1407  		if defaultOff := c.flags&suiteDefaultOff != 0; defaultOff != cc.Insecure {
  1408  			t.Errorf("%#04x: Insecure %v, expected %v", c.id, cc.Insecure, defaultOff)
  1409  		}
  1410  		if tls12Only := c.flags&suiteTLS12 != 0; tls12Only && len(cc.SupportedVersions) != 1 {
  1411  			t.Errorf("%#04x: suite is TLS 1.2 only, but SupportedVersions is %v", c.id, cc.SupportedVersions)
  1412  		} else if !tls12Only && len(cc.SupportedVersions) != 3 {
  1413  			t.Errorf("%#04x: suite TLS 1.0-1.2, but SupportedVersions is %v", c.id, cc.SupportedVersions)
  1414  		}
  1415  
  1416  		if got := CipherSuiteName(c.id); got != cc.Name {
  1417  			t.Errorf("%#04x: unexpected CipherSuiteName: got %q, expected %q", c.id, got, cc.Name)
  1418  		}
  1419  	}
  1420  	for _, c := range cipherSuitesTLS13 {
  1421  		cc := cipherSuiteByID(c.id)
  1422  		if cc == nil {
  1423  			t.Errorf("%#04x: no CipherSuite entry", c.id)
  1424  			continue
  1425  		}
  1426  
  1427  		if cc.Insecure {
  1428  			t.Errorf("%#04x: Insecure %v, expected false", c.id, cc.Insecure)
  1429  		}
  1430  		if len(cc.SupportedVersions) != 1 || cc.SupportedVersions[0] != VersionTLS13 {
  1431  			t.Errorf("%#04x: suite is TLS 1.3 only, but SupportedVersions is %v", c.id, cc.SupportedVersions)
  1432  		}
  1433  
  1434  		if got := CipherSuiteName(c.id); got != cc.Name {
  1435  			t.Errorf("%#04x: unexpected CipherSuiteName: got %q, expected %q", c.id, got, cc.Name)
  1436  		}
  1437  	}
  1438  
  1439  	if got := CipherSuiteName(0xabc); got != "0x0ABC" {
  1440  		t.Errorf("unexpected fallback CipherSuiteName: got %q, expected 0x0ABC", got)
  1441  	}
  1442  }
  1443  
  1444  type brokenSigner struct{ crypto.Signer }
  1445  
  1446  func (s brokenSigner) Sign(rand io.Reader, digest []byte, opts crypto.SignerOpts) (signature []byte, err error) {
  1447  	// Replace opts with opts.HashFunc(), so rsa.PSSOptions are discarded.
  1448  	return s.Signer.Sign(rand, digest, opts.HashFunc())
  1449  }
  1450  
  1451  // TestPKCS1OnlyCert uses a client certificate with a broken crypto.Signer that
  1452  // always makes PKCS #1 v1.5 signatures, so can't be used with RSA-PSS.
  1453  func TestPKCS1OnlyCert(t *testing.T) {
  1454  	clientConfig := testConfig.Clone()
  1455  	clientConfig.Certificates = []Certificate{{
  1456  		Certificate: [][]byte{testRSACertificate},
  1457  		PrivateKey:  brokenSigner{testRSAPrivateKey},
  1458  	}}
  1459  	serverConfig := testConfig.Clone()
  1460  	serverConfig.MaxVersion = VersionTLS12 // TLS 1.3 doesn't support PKCS #1 v1.5
  1461  	serverConfig.ClientAuth = RequireAnyClientCert
  1462  
  1463  	// If RSA-PSS is selected, the handshake should fail.
  1464  	if _, _, err := testHandshake(t, clientConfig, serverConfig); err == nil {
  1465  		t.Fatal("expected broken certificate to cause connection to fail")
  1466  	}
  1467  
  1468  	clientConfig.Certificates[0].SupportedSignatureAlgorithms =
  1469  		[]SignatureScheme{PKCS1WithSHA1, PKCS1WithSHA256}
  1470  
  1471  	// But if the certificate restricts supported algorithms, RSA-PSS should not
  1472  	// be selected, and the handshake should succeed.
  1473  	if _, _, err := testHandshake(t, clientConfig, serverConfig); err != nil {
  1474  		t.Error(err)
  1475  	}
  1476  }