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