Help us shape the future of Go! Take the 2026 Go Developer Survey

Source file src/crypto/tls/tls_test.go

     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/ecdh"
    12  	"crypto/ecdsa"
    13  	"crypto/elliptic"
    14  	"crypto/fips140"
    15  	"crypto/internal/boring"
    16  	"crypto/internal/cryptotest"
    17  	"crypto/mldsa"
    18  	"crypto/rand"
    19  	"crypto/tls/internal/fips140tls"
    20  	"crypto/x509"
    21  	"crypto/x509/pkix"
    22  	"encoding/asn1"
    23  	"encoding/json"
    24  	"encoding/pem"
    25  	"errors"
    26  	"fmt"
    27  	"internal/testenv"
    28  	"io"
    29  	"math"
    30  	"math/big"
    31  	"net"
    32  	"os"
    33  	"reflect"
    34  	"slices"
    35  	"strings"
    36  	"testing"
    37  	"time"
    38  
    39  	"golang.org/x/crypto/cryptobyte"
    40  )
    41  
    42  var testTime = func() time.Time { return time.Unix(1476984729, 0) }
    43  
    44  var testConfigServer = &Config{
    45  	Time: testTime,
    46  	Certificates: []Certificate{testECDSAP256Cert, testRSA2048Cert, testEd25519Cert, testSNICert,
    47  		testMLDSA44Cert, testMLDSA65Cert, testMLDSA87Cert},
    48  	ClientCAs: testClientRootCertPool,
    49  }
    50  
    51  var testConfigClient = &Config{
    52  	Time: testTime,
    53  	Certificates: []Certificate{testClientECDSAP256Cert, testClientRSA2048Cert, testClientEd25519Cert,
    54  		testClientMLDSA44Cert, testClientMLDSA65Cert, testClientMLDSA87Cert},
    55  	RootCAs:    testRootCertPool,
    56  	ServerName: "test.golang.example",
    57  }
    58  
    59  func TestX509KeyPair(t *testing.T) {
    60  	var rsaCertPEM = `-----BEGIN CERTIFICATE-----
    61  MIIB0zCCAX2gAwIBAgIJAI/M7BYjwB+uMA0GCSqGSIb3DQEBBQUAMEUxCzAJBgNV
    62  BAYTAkFVMRMwEQYDVQQIDApTb21lLVN0YXRlMSEwHwYDVQQKDBhJbnRlcm5ldCBX
    63  aWRnaXRzIFB0eSBMdGQwHhcNMTIwOTEyMjE1MjAyWhcNMTUwOTEyMjE1MjAyWjBF
    64  MQswCQYDVQQGEwJBVTETMBEGA1UECAwKU29tZS1TdGF0ZTEhMB8GA1UECgwYSW50
    65  ZXJuZXQgV2lkZ2l0cyBQdHkgTHRkMFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBANLJ
    66  hPHhITqQbPklG3ibCVxwGMRfp/v4XqhfdQHdcVfHap6NQ5Wok/4xIA+ui35/MmNa
    67  rtNuC+BdZ1tMuVCPFZcCAwEAAaNQME4wHQYDVR0OBBYEFJvKs8RfJaXTH08W+SGv
    68  zQyKn0H8MB8GA1UdIwQYMBaAFJvKs8RfJaXTH08W+SGvzQyKn0H8MAwGA1UdEwQF
    69  MAMBAf8wDQYJKoZIhvcNAQEFBQADQQBJlffJHybjDGxRMqaRmDhX0+6v02TUKZsW
    70  r5QuVbpQhH6u+0UgcW0jp9QwpxoPTLTWGXEWBBBurxFwiCBhkQ+V
    71  -----END CERTIFICATE-----
    72  `
    73  
    74  	var rsaKeyPEM = testingKey(`-----BEGIN RSA TESTING KEY-----
    75  MIIBOwIBAAJBANLJhPHhITqQbPklG3ibCVxwGMRfp/v4XqhfdQHdcVfHap6NQ5Wo
    76  k/4xIA+ui35/MmNartNuC+BdZ1tMuVCPFZcCAwEAAQJAEJ2N+zsR0Xn8/Q6twa4G
    77  6OB1M1WO+k+ztnX/1SvNeWu8D6GImtupLTYgjZcHufykj09jiHmjHx8u8ZZB/o1N
    78  MQIhAPW+eyZo7ay3lMz1V01WVjNKK9QSn1MJlb06h/LuYv9FAiEA25WPedKgVyCW
    79  SmUwbPw8fnTcpqDWE3yTO3vKcebqMSsCIBF3UmVue8YU3jybC3NxuXq3wNm34R8T
    80  xVLHwDXh/6NJAiEAl2oHGGLz64BuAfjKrqwz7qMYr9HCLIe/YsoWq/olzScCIQDi
    81  D2lWusoe2/nEqfDVVWGWlyJ7yOmqaVm/iNUN9B2N2g==
    82  -----END RSA TESTING KEY-----
    83  `)
    84  
    85  	// keyPEM is the same as rsaKeyPEM, but declares itself as just
    86  	// "PRIVATE KEY", not "RSA PRIVATE KEY".  https://golang.org/issue/4477
    87  	var keyPEM = testingKey(`-----BEGIN TESTING KEY-----
    88  MIIBOwIBAAJBANLJhPHhITqQbPklG3ibCVxwGMRfp/v4XqhfdQHdcVfHap6NQ5Wo
    89  k/4xIA+ui35/MmNartNuC+BdZ1tMuVCPFZcCAwEAAQJAEJ2N+zsR0Xn8/Q6twa4G
    90  6OB1M1WO+k+ztnX/1SvNeWu8D6GImtupLTYgjZcHufykj09jiHmjHx8u8ZZB/o1N
    91  MQIhAPW+eyZo7ay3lMz1V01WVjNKK9QSn1MJlb06h/LuYv9FAiEA25WPedKgVyCW
    92  SmUwbPw8fnTcpqDWE3yTO3vKcebqMSsCIBF3UmVue8YU3jybC3NxuXq3wNm34R8T
    93  xVLHwDXh/6NJAiEAl2oHGGLz64BuAfjKrqwz7qMYr9HCLIe/YsoWq/olzScCIQDi
    94  D2lWusoe2/nEqfDVVWGWlyJ7yOmqaVm/iNUN9B2N2g==
    95  -----END TESTING KEY-----
    96  `)
    97  
    98  	var ecdsaCertPEM = `-----BEGIN CERTIFICATE-----
    99  MIIB/jCCAWICCQDscdUxw16XFDAJBgcqhkjOPQQBMEUxCzAJBgNVBAYTAkFVMRMw
   100  EQYDVQQIEwpTb21lLVN0YXRlMSEwHwYDVQQKExhJbnRlcm5ldCBXaWRnaXRzIFB0
   101  eSBMdGQwHhcNMTIxMTE0MTI0MDQ4WhcNMTUxMTE0MTI0MDQ4WjBFMQswCQYDVQQG
   102  EwJBVTETMBEGA1UECBMKU29tZS1TdGF0ZTEhMB8GA1UEChMYSW50ZXJuZXQgV2lk
   103  Z2l0cyBQdHkgTHRkMIGbMBAGByqGSM49AgEGBSuBBAAjA4GGAAQBY9+my9OoeSUR
   104  lDQdV/x8LsOuLilthhiS1Tz4aGDHIPwC1mlvnf7fg5lecYpMCrLLhauAc1UJXcgl
   105  01xoLuzgtAEAgv2P/jgytzRSpUYvgLBt1UA0leLYBy6mQQbrNEuqT3INapKIcUv8
   106  XxYP0xMEUksLPq6Ca+CRSqTtrd/23uTnapkwCQYHKoZIzj0EAQOBigAwgYYCQXJo
   107  A7Sl2nLVf+4Iu/tAX/IF4MavARKC4PPHK3zfuGfPR3oCCcsAoz3kAzOeijvd0iXb
   108  H5jBImIxPL4WxQNiBTexAkF8D1EtpYuWdlVQ80/h/f4pBcGiXPqX5h2PQSQY7hP1
   109  +jwM1FGS4fREIOvlBYr/SzzQRtwrvrzGYxDEDbsC0ZGRnA==
   110  -----END CERTIFICATE-----
   111  `
   112  
   113  	var ecdsaKeyPEM = testingKey(`-----BEGIN EC PARAMETERS-----
   114  BgUrgQQAIw==
   115  -----END EC PARAMETERS-----
   116  -----BEGIN EC TESTING KEY-----
   117  MIHcAgEBBEIBrsoKp0oqcv6/JovJJDoDVSGWdirrkgCWxrprGlzB9o0X8fV675X0
   118  NwuBenXFfeZvVcwluO7/Q9wkYoPd/t3jGImgBwYFK4EEACOhgYkDgYYABAFj36bL
   119  06h5JRGUNB1X/Hwuw64uKW2GGJLVPPhoYMcg/ALWaW+d/t+DmV5xikwKssuFq4Bz
   120  VQldyCXTXGgu7OC0AQCC/Y/+ODK3NFKlRi+AsG3VQDSV4tgHLqZBBus0S6pPcg1q
   121  kohxS/xfFg/TEwRSSws+roJr4JFKpO2t3/be5OdqmQ==
   122  -----END EC TESTING KEY-----
   123  `)
   124  
   125  	type test struct {
   126  		algo string
   127  		cert string
   128  		key  string
   129  	}
   130  	var keyPairTests = []test{
   131  		{"ECDSA", ecdsaCertPEM, ecdsaKeyPEM},
   132  		{"RSA", rsaCertPEM, rsaKeyPEM},
   133  		{"RSA-untyped", rsaCertPEM, keyPEM}, // golang.org/issue/4477
   134  	}
   135  
   136  	if fips140.Version() != "v1.0.0" {
   137  		keyPairTests = append(keyPairTests,
   138  			test{"ML-DSA-44", testMLDSA44CertPEM, testingKey(testMLDSA44KeyPEM)},
   139  			test{"ML-DSA-65", testMLDSA65CertPEM, testingKey(testMLDSA65KeyPEM)},
   140  			test{"ML-DSA-87", testMLDSA87CertPEM, testingKey(testMLDSA87KeyPEM)},
   141  		)
   142  	}
   143  
   144  	t.Parallel()
   145  	var pem []byte
   146  	for _, test := range keyPairTests {
   147  		pem = []byte(test.cert + test.key)
   148  		if _, err := X509KeyPair(pem, pem); err != nil {
   149  			t.Errorf("Failed to load %s cert followed by %s key: %s", test.algo, test.algo, err)
   150  		}
   151  		pem = []byte(test.key + test.cert)
   152  		if _, err := X509KeyPair(pem, pem); err != nil {
   153  			t.Errorf("Failed to load %s key followed by %s cert: %s", test.algo, test.algo, err)
   154  		}
   155  	}
   156  
   157  	_, err := X509KeyPair([]byte(rsaKeyPEM), []byte(rsaCertPEM))
   158  	if err == nil {
   159  		t.Fatalf("X509KeyPair didn't return an error when arguments were switched")
   160  	}
   161  	if subStr := "been switched"; !strings.Contains(err.Error(), subStr) {
   162  		t.Fatalf("Expected %q in the error when switching arguments to X509KeyPair, but the error was %q", subStr, err)
   163  	}
   164  
   165  	_, err = X509KeyPair([]byte(rsaCertPEM), []byte(rsaCertPEM))
   166  	if err == nil {
   167  		t.Fatalf("X509KeyPair didn't return an error when both arguments were certificates")
   168  	}
   169  	if subStr := "certificate"; !strings.Contains(err.Error(), subStr) {
   170  		t.Fatalf("Expected %q in the error when both arguments to X509KeyPair were certificates, but the error was %q", subStr, err)
   171  	}
   172  
   173  	const nonsensePEM = `
   174  -----BEGIN NONSENSE-----
   175  Zm9vZm9vZm9v
   176  -----END NONSENSE-----
   177  `
   178  
   179  	_, err = X509KeyPair([]byte(nonsensePEM), []byte(nonsensePEM))
   180  	if err == nil {
   181  		t.Fatalf("X509KeyPair didn't return an error when both arguments were nonsense")
   182  	}
   183  	if subStr := "NONSENSE"; !strings.Contains(err.Error(), subStr) {
   184  		t.Fatalf("Expected %q in the error when both arguments to X509KeyPair were nonsense, but the error was %q", subStr, err)
   185  	}
   186  
   187  	if _, err := X509KeyPair([]byte(rsaCertPEM), []byte(ecdsaKeyPEM)); err == nil {
   188  		t.Error("Load of RSA certificate succeeded with ECDSA private key")
   189  	}
   190  	if _, err := X509KeyPair([]byte(ecdsaCertPEM), []byte(rsaKeyPEM)); err == nil {
   191  		t.Error("Load of ECDSA certificate succeeded with RSA private key")
   192  	}
   193  }
   194  
   195  func newLocalListener(t testing.TB) net.Listener {
   196  	t.Helper()
   197  	ln, err := net.Listen("tcp", "127.0.0.1:0")
   198  	if err != nil {
   199  		ln, err = net.Listen("tcp6", "[::1]:0")
   200  	}
   201  	if err != nil {
   202  		t.Fatal(err)
   203  	}
   204  	return ln
   205  }
   206  
   207  func runWithFIPSEnabled(t *testing.T, testFunc func(t *testing.T)) {
   208  	originalFIPS := fips140tls.Required()
   209  	defer func() {
   210  		if originalFIPS {
   211  			fips140tls.Force()
   212  		} else {
   213  			fips140tls.TestingOnlyAbandon()
   214  		}
   215  	}()
   216  
   217  	fips140tls.Force()
   218  	t.Run("fips140tls", testFunc)
   219  }
   220  
   221  func runWithFIPSDisabled(t *testing.T, testFunc func(t *testing.T)) {
   222  	if fips140.Enforced() {
   223  		t.Run("no-fips140tls", func(t *testing.T) {
   224  			t.Skip("can't run no-fips140tls tests in fips140=only mode")
   225  		})
   226  		return
   227  	}
   228  
   229  	originalFIPS := fips140tls.Required()
   230  	defer func() {
   231  		if originalFIPS {
   232  			fips140tls.Force()
   233  		} else {
   234  			fips140tls.TestingOnlyAbandon()
   235  		}
   236  	}()
   237  
   238  	fips140tls.TestingOnlyAbandon()
   239  	t.Run("no-fips140tls", testFunc)
   240  }
   241  
   242  func skipFIPS(t *testing.T) {
   243  	if fips140tls.Required() {
   244  		t.Skip("skipping test in FIPS mode")
   245  	}
   246  }
   247  
   248  func TestDialTimeout(t *testing.T) {
   249  	if testing.Short() {
   250  		t.Skip("skipping in short mode")
   251  	}
   252  
   253  	timeout := 100 * time.Microsecond
   254  	for !t.Failed() {
   255  		acceptc := make(chan net.Conn)
   256  		listener := newLocalListener(t)
   257  		go func() {
   258  			for {
   259  				conn, err := listener.Accept()
   260  				if err != nil {
   261  					close(acceptc)
   262  					return
   263  				}
   264  				acceptc <- conn
   265  			}
   266  		}()
   267  
   268  		addr := listener.Addr().String()
   269  		dialer := &net.Dialer{
   270  			Timeout: timeout,
   271  		}
   272  		if conn, err := DialWithDialer(dialer, "tcp", addr, nil); err == nil {
   273  			conn.Close()
   274  			t.Errorf("DialWithTimeout unexpectedly completed successfully")
   275  		} else if !isTimeoutError(err) {
   276  			t.Errorf("resulting error not a timeout: %v\nType %T: %#v", err, err, err)
   277  		}
   278  
   279  		listener.Close()
   280  
   281  		// We're looking for a timeout during the handshake, so check that the
   282  		// Listener actually accepted the connection to initiate it. (If the server
   283  		// takes too long to accept the connection, we might cancel before the
   284  		// underlying net.Conn is ever dialed — without ever attempting a
   285  		// handshake.)
   286  		lconn, ok := <-acceptc
   287  		if ok {
   288  			// The Listener accepted a connection, so assume that it was from our
   289  			// Dial: we triggered the timeout at the point where we wanted it!
   290  			t.Logf("Listener accepted a connection from %s", lconn.RemoteAddr())
   291  			lconn.Close()
   292  		}
   293  		// Close any spurious extra connections from the listener. (This is
   294  		// possible if there are, for example, stray Dial calls from other tests.)
   295  		for extraConn := range acceptc {
   296  			t.Logf("spurious extra connection from %s", extraConn.RemoteAddr())
   297  			extraConn.Close()
   298  		}
   299  		if ok {
   300  			break
   301  		}
   302  
   303  		t.Logf("with timeout %v, DialWithDialer returned before listener accepted any connections; retrying", timeout)
   304  		timeout *= 2
   305  	}
   306  }
   307  
   308  func TestDeadlineOnWrite(t *testing.T) {
   309  	if testing.Short() {
   310  		t.Skip("skipping in short mode")
   311  	}
   312  
   313  	ln := newLocalListener(t)
   314  	defer ln.Close()
   315  
   316  	srvCh := make(chan *Conn, 1)
   317  
   318  	go func() {
   319  		sconn, err := ln.Accept()
   320  		if err != nil {
   321  			srvCh <- nil
   322  			return
   323  		}
   324  		srv := Server(sconn, testConfigServer.Clone())
   325  		if err := srv.Handshake(); err != nil {
   326  			srvCh <- nil
   327  			return
   328  		}
   329  		srvCh <- srv
   330  	}()
   331  
   332  	clientConfig := testConfigClient.Clone()
   333  	clientConfig.MaxVersion = VersionTLS12
   334  	conn, err := Dial("tcp", ln.Addr().String(), clientConfig)
   335  	if err != nil {
   336  		t.Fatal(err)
   337  	}
   338  	defer conn.Close()
   339  
   340  	srv := <-srvCh
   341  	if srv == nil {
   342  		t.Error(err)
   343  	}
   344  
   345  	// Make sure the client/server is setup correctly and is able to do a typical Write/Read
   346  	buf := make([]byte, 6)
   347  	if _, err := srv.Write([]byte("foobar")); err != nil {
   348  		t.Errorf("Write err: %v", err)
   349  	}
   350  	if n, err := conn.Read(buf); n != 6 || err != nil || string(buf) != "foobar" {
   351  		t.Errorf("Read = %d, %v, data %q; want 6, nil, foobar", n, err, buf)
   352  	}
   353  
   354  	// Set a deadline which should cause Write to timeout
   355  	if err = srv.SetDeadline(time.Now()); err != nil {
   356  		t.Fatalf("SetDeadline(time.Now()) err: %v", err)
   357  	}
   358  	if _, err = srv.Write([]byte("should fail")); err == nil {
   359  		t.Fatal("Write should have timed out")
   360  	}
   361  
   362  	// Clear deadline and make sure it still times out
   363  	if err = srv.SetDeadline(time.Time{}); err != nil {
   364  		t.Fatalf("SetDeadline(time.Time{}) err: %v", err)
   365  	}
   366  	if _, err = srv.Write([]byte("This connection is permanently broken")); err == nil {
   367  		t.Fatal("Write which previously failed should still time out")
   368  	}
   369  
   370  	// Verify the error
   371  	if ne := err.(net.Error); ne.Temporary() != false {
   372  		t.Error("Write timed out but incorrectly classified the error as Temporary")
   373  	}
   374  	if !isTimeoutError(err) {
   375  		t.Error("Write timed out but did not classify the error as a Timeout")
   376  	}
   377  }
   378  
   379  type readerFunc func([]byte) (int, error)
   380  
   381  func (f readerFunc) Read(b []byte) (int, error) { return f(b) }
   382  
   383  // TestDialer tests that tls.Dialer.DialContext can abort in the middle of a handshake.
   384  // (The other cases are all handled by the existing dial tests in this package, which
   385  // all also flow through the same code shared code paths)
   386  func TestDialer(t *testing.T) {
   387  	ln := newLocalListener(t)
   388  	defer ln.Close()
   389  
   390  	unblockServer := make(chan struct{}) // close-only
   391  	defer close(unblockServer)
   392  	go func() {
   393  		conn, err := ln.Accept()
   394  		if err != nil {
   395  			return
   396  		}
   397  		defer conn.Close()
   398  		<-unblockServer
   399  	}()
   400  
   401  	ctx, cancel := context.WithCancel(context.Background())
   402  	d := Dialer{Config: &Config{
   403  		Rand: readerFunc(func(b []byte) (n int, err error) {
   404  			// By the time crypto/tls wants randomness, that means it has a TCP
   405  			// connection, so we're past the Dialer's dial and now blocked
   406  			// in a handshake. Cancel our context and see if we get unstuck.
   407  			// (Our TCP listener above never reads or writes, so the Handshake
   408  			// would otherwise be stuck forever)
   409  			cancel()
   410  			return len(b), nil
   411  		}),
   412  		ServerName: "foo",
   413  	}}
   414  	_, err := d.DialContext(ctx, "tcp", ln.Addr().String())
   415  	if err != context.Canceled {
   416  		t.Errorf("err = %v; want context.Canceled", err)
   417  	}
   418  }
   419  
   420  func isTimeoutError(err error) bool {
   421  	if ne, ok := err.(net.Error); ok {
   422  		return ne.Timeout()
   423  	}
   424  	return false
   425  }
   426  
   427  // tests that Conn.Read returns (non-zero, io.EOF) instead of
   428  // (non-zero, nil) when a Close (alertCloseNotify) is sitting right
   429  // behind the application data in the buffer.
   430  func TestConnReadNonzeroAndEOF(t *testing.T) {
   431  	// This test is racy: it assumes that after a write to a
   432  	// localhost TCP connection, the peer TCP connection can
   433  	// immediately read it. Because it's racy, we skip this test
   434  	// in short mode, and then retry it several times with an
   435  	// increasing sleep in between our final write (via srv.Close
   436  	// below) and the following read.
   437  	if testing.Short() {
   438  		t.Skip("skipping in short mode")
   439  	}
   440  	var err error
   441  	for delay := time.Millisecond; delay <= 64*time.Millisecond; delay *= 2 {
   442  		if err = testConnReadNonzeroAndEOF(t, delay); err == nil {
   443  			return
   444  		}
   445  	}
   446  	t.Error(err)
   447  }
   448  
   449  func testConnReadNonzeroAndEOF(t *testing.T, delay time.Duration) error {
   450  	ln := newLocalListener(t)
   451  	defer ln.Close()
   452  
   453  	srvCh := make(chan *Conn, 1)
   454  	var serr error
   455  	go func() {
   456  		sconn, err := ln.Accept()
   457  		if err != nil {
   458  			serr = err
   459  			srvCh <- nil
   460  			return
   461  		}
   462  		serverConfig := testConfigServer.Clone()
   463  		srv := Server(sconn, serverConfig)
   464  		if err := srv.Handshake(); err != nil {
   465  			serr = fmt.Errorf("handshake: %v", err)
   466  			srvCh <- nil
   467  			return
   468  		}
   469  		srvCh <- srv
   470  	}()
   471  
   472  	clientConfig := testConfigClient.Clone()
   473  	// In TLS 1.3, alerts are encrypted and disguised as application data, so
   474  	// the opportunistic peek won't work.
   475  	clientConfig.MaxVersion = VersionTLS12
   476  	conn, err := Dial("tcp", ln.Addr().String(), clientConfig)
   477  	if err != nil {
   478  		t.Fatal(err)
   479  	}
   480  	defer conn.Close()
   481  
   482  	srv := <-srvCh
   483  	if srv == nil {
   484  		return serr
   485  	}
   486  
   487  	buf := make([]byte, 6)
   488  
   489  	srv.Write([]byte("foobar"))
   490  	n, err := conn.Read(buf)
   491  	if n != 6 || err != nil || string(buf) != "foobar" {
   492  		return fmt.Errorf("Read = %d, %v, data %q; want 6, nil, foobar", n, err, buf)
   493  	}
   494  
   495  	srv.Write([]byte("abcdef"))
   496  	srv.Close()
   497  	time.Sleep(delay)
   498  	n, err = conn.Read(buf)
   499  	if n != 6 || string(buf) != "abcdef" {
   500  		return fmt.Errorf("Read = %d, buf= %q; want 6, abcdef", n, buf)
   501  	}
   502  	if err != io.EOF {
   503  		return fmt.Errorf("Second Read error = %v; want io.EOF", err)
   504  	}
   505  	return nil
   506  }
   507  
   508  func TestTLSUniqueMatches(t *testing.T) {
   509  	ln := newLocalListener(t)
   510  	defer ln.Close()
   511  
   512  	serverConfig := testConfigServer.Clone()
   513  	serverConfig.MaxVersion = VersionTLS12 // TLSUnique is not defined in TLS 1.3
   514  
   515  	serverTLSUniques := make(chan []byte)
   516  	parentDone := make(chan struct{})
   517  	childDone := make(chan struct{})
   518  	defer close(parentDone)
   519  	go func() {
   520  		defer close(childDone)
   521  		for i := 0; i < 2; i++ {
   522  			sconn, err := ln.Accept()
   523  			if err != nil {
   524  				t.Error(err)
   525  				return
   526  			}
   527  			srv := Server(sconn, serverConfig)
   528  			if err := srv.Handshake(); err != nil {
   529  				t.Error(err)
   530  				return
   531  			}
   532  			select {
   533  			case <-parentDone:
   534  				return
   535  			case serverTLSUniques <- srv.ConnectionState().TLSUnique:
   536  			}
   537  		}
   538  	}()
   539  
   540  	clientConfig := testConfigClient.Clone()
   541  	clientConfig.ClientSessionCache = NewLRUClientSessionCache(1)
   542  	conn, err := Dial("tcp", ln.Addr().String(), clientConfig)
   543  	if err != nil {
   544  		t.Fatal(err)
   545  	}
   546  
   547  	var serverTLSUniquesValue []byte
   548  	select {
   549  	case <-childDone:
   550  		return
   551  	case serverTLSUniquesValue = <-serverTLSUniques:
   552  	}
   553  
   554  	if !bytes.Equal(conn.ConnectionState().TLSUnique, serverTLSUniquesValue) {
   555  		t.Error("client and server channel bindings differ")
   556  	}
   557  	if serverTLSUniquesValue == nil || bytes.Equal(serverTLSUniquesValue, make([]byte, 12)) {
   558  		t.Error("tls-unique is empty or zero")
   559  	}
   560  	conn.Close()
   561  
   562  	conn, err = Dial("tcp", ln.Addr().String(), clientConfig)
   563  	if err != nil {
   564  		t.Fatal(err)
   565  	}
   566  	defer conn.Close()
   567  	if !conn.ConnectionState().DidResume {
   568  		t.Error("second session did not use resumption")
   569  	}
   570  
   571  	select {
   572  	case <-childDone:
   573  		return
   574  	case serverTLSUniquesValue = <-serverTLSUniques:
   575  	}
   576  
   577  	if !bytes.Equal(conn.ConnectionState().TLSUnique, serverTLSUniquesValue) {
   578  		t.Error("client and server channel bindings differ when session resumption is used")
   579  	}
   580  	if serverTLSUniquesValue == nil || bytes.Equal(serverTLSUniquesValue, make([]byte, 12)) {
   581  		t.Error("resumption tls-unique is empty or zero")
   582  	}
   583  }
   584  
   585  func TestVerifyHostname(t *testing.T) {
   586  	testenv.MustHaveExternalNetwork(t)
   587  
   588  	c, err := Dial("tcp", "www.google.com:https", nil)
   589  	if err != nil {
   590  		t.Fatal(err)
   591  	}
   592  	if err := c.VerifyHostname("www.google.com"); err != nil {
   593  		t.Fatalf("verify www.google.com: %v", err)
   594  	}
   595  	if err := c.VerifyHostname("www.yahoo.com"); err == nil {
   596  		t.Fatalf("verify www.yahoo.com succeeded")
   597  	}
   598  
   599  	c, err = Dial("tcp", "www.google.com:https", &Config{InsecureSkipVerify: true})
   600  	if err != nil {
   601  		t.Fatal(err)
   602  	}
   603  	if err := c.VerifyHostname("www.google.com"); err == nil {
   604  		t.Fatalf("verify www.google.com succeeded with InsecureSkipVerify=true")
   605  	}
   606  }
   607  
   608  func TestRealResumption(t *testing.T) {
   609  	testenv.MustHaveExternalNetwork(t)
   610  
   611  	config := &Config{
   612  		ServerName:         "yahoo.com",
   613  		ClientSessionCache: NewLRUClientSessionCache(0),
   614  	}
   615  
   616  	for range 10 {
   617  		conn, err := Dial("tcp", "yahoo.com:443", config)
   618  		if err != nil {
   619  			t.Log("Dial error:", err)
   620  			continue
   621  		}
   622  		// Do a read to consume the NewSessionTicket messages.
   623  		fmt.Fprintf(conn, "GET / HTTP/1.1\r\nHost: yahoo.com\r\nConnection: close\r\n\r\n")
   624  		conn.Read(make([]byte, 4096))
   625  		conn.Close()
   626  
   627  		conn, err = Dial("tcp", "yahoo.com:443", config)
   628  		if err != nil {
   629  			t.Log("second Dial error:", err)
   630  			continue
   631  		}
   632  		state := conn.ConnectionState()
   633  		conn.Close()
   634  
   635  		if state.DidResume {
   636  			return
   637  		}
   638  	}
   639  
   640  	t.Fatal("no connection used session resumption")
   641  }
   642  
   643  func TestConnCloseBreakingWrite(t *testing.T) {
   644  	ln := newLocalListener(t)
   645  	defer ln.Close()
   646  
   647  	srvCh := make(chan *Conn, 1)
   648  	var serr error
   649  	var sconn net.Conn
   650  	go func() {
   651  		var err error
   652  		sconn, err = ln.Accept()
   653  		if err != nil {
   654  			serr = err
   655  			srvCh <- nil
   656  			return
   657  		}
   658  		serverConfig := testConfigServer.Clone()
   659  		srv := Server(sconn, serverConfig)
   660  		if err := srv.Handshake(); err != nil {
   661  			serr = fmt.Errorf("handshake: %v", err)
   662  			srvCh <- nil
   663  			return
   664  		}
   665  		srvCh <- srv
   666  	}()
   667  
   668  	cconn, err := net.Dial("tcp", ln.Addr().String())
   669  	if err != nil {
   670  		t.Fatal(err)
   671  	}
   672  	defer cconn.Close()
   673  
   674  	conn := &changeImplConn{
   675  		Conn: cconn,
   676  	}
   677  
   678  	clientConfig := testConfigClient.Clone()
   679  	tconn := Client(conn, clientConfig)
   680  	if err := tconn.Handshake(); err != nil {
   681  		t.Fatal(err)
   682  	}
   683  
   684  	srv := <-srvCh
   685  	if srv == nil {
   686  		t.Fatal(serr)
   687  	}
   688  	defer sconn.Close()
   689  
   690  	connClosed := make(chan struct{})
   691  	conn.closeFunc = func() error {
   692  		close(connClosed)
   693  		return nil
   694  	}
   695  
   696  	inWrite := make(chan bool, 1)
   697  	var errConnClosed = errors.New("conn closed for test")
   698  	conn.writeFunc = func(p []byte) (n int, err error) {
   699  		inWrite <- true
   700  		<-connClosed
   701  		return 0, errConnClosed
   702  	}
   703  
   704  	closeReturned := make(chan bool, 1)
   705  	go func() {
   706  		<-inWrite
   707  		tconn.Close() // test that this doesn't block forever.
   708  		closeReturned <- true
   709  	}()
   710  
   711  	_, err = tconn.Write([]byte("foo"))
   712  	if err != errConnClosed {
   713  		t.Errorf("Write error = %v; want errConnClosed", err)
   714  	}
   715  
   716  	<-closeReturned
   717  	if err := tconn.Close(); err != net.ErrClosed {
   718  		t.Errorf("Close error = %v; want net.ErrClosed", err)
   719  	}
   720  }
   721  
   722  func TestConnCloseWrite(t *testing.T) {
   723  	ln := newLocalListener(t)
   724  	defer ln.Close()
   725  
   726  	clientDoneChan := make(chan struct{})
   727  
   728  	serverCloseWrite := func() error {
   729  		sconn, err := ln.Accept()
   730  		if err != nil {
   731  			return fmt.Errorf("accept: %v", err)
   732  		}
   733  		defer sconn.Close()
   734  
   735  		serverConfig := testConfigServer.Clone()
   736  		srv := Server(sconn, serverConfig)
   737  		if err := srv.Handshake(); err != nil {
   738  			return fmt.Errorf("handshake: %v", err)
   739  		}
   740  		defer srv.Close()
   741  
   742  		data, err := io.ReadAll(srv)
   743  		if err != nil {
   744  			return err
   745  		}
   746  		if len(data) > 0 {
   747  			return fmt.Errorf("Read data = %q; want nothing", data)
   748  		}
   749  
   750  		if err := srv.CloseWrite(); err != nil {
   751  			return fmt.Errorf("server CloseWrite: %v", err)
   752  		}
   753  
   754  		// Wait for clientCloseWrite to finish, so we know we
   755  		// tested the CloseWrite before we defer the
   756  		// sconn.Close above, which would also cause the
   757  		// client to unblock like CloseWrite.
   758  		<-clientDoneChan
   759  		return nil
   760  	}
   761  
   762  	clientCloseWrite := func() error {
   763  		defer close(clientDoneChan)
   764  
   765  		clientConfig := testConfigClient.Clone()
   766  		conn, err := Dial("tcp", ln.Addr().String(), clientConfig)
   767  		if err != nil {
   768  			return err
   769  		}
   770  		if err := conn.Handshake(); err != nil {
   771  			return err
   772  		}
   773  		defer conn.Close()
   774  
   775  		if err := conn.CloseWrite(); err != nil {
   776  			return fmt.Errorf("client CloseWrite: %v", err)
   777  		}
   778  
   779  		if _, err := conn.Write([]byte{0}); err != errShutdown {
   780  			return fmt.Errorf("CloseWrite error = %v; want errShutdown", err)
   781  		}
   782  
   783  		data, err := io.ReadAll(conn)
   784  		if err != nil {
   785  			return err
   786  		}
   787  		if len(data) > 0 {
   788  			return fmt.Errorf("Read data = %q; want nothing", data)
   789  		}
   790  		return nil
   791  	}
   792  
   793  	errChan := make(chan error, 2)
   794  
   795  	go func() { errChan <- serverCloseWrite() }()
   796  	go func() { errChan <- clientCloseWrite() }()
   797  
   798  	for i := 0; i < 2; i++ {
   799  		select {
   800  		case err := <-errChan:
   801  			if err != nil {
   802  				t.Fatal(err)
   803  			}
   804  		case <-time.After(10 * time.Second):
   805  			t.Fatal("deadlock")
   806  		}
   807  	}
   808  
   809  	// Also test CloseWrite being called before the handshake is
   810  	// finished:
   811  	{
   812  		ln2 := newLocalListener(t)
   813  		defer ln2.Close()
   814  
   815  		netConn, err := net.Dial("tcp", ln2.Addr().String())
   816  		if err != nil {
   817  			t.Fatal(err)
   818  		}
   819  		defer netConn.Close()
   820  		conn := Client(netConn, testConfigClient.Clone())
   821  
   822  		if err := conn.CloseWrite(); err != errEarlyCloseWrite {
   823  			t.Errorf("CloseWrite error = %v; want errEarlyCloseWrite", err)
   824  		}
   825  	}
   826  }
   827  
   828  func TestWarningAlertFlood(t *testing.T) {
   829  	ln := newLocalListener(t)
   830  	defer ln.Close()
   831  
   832  	server := func() error {
   833  		sconn, err := ln.Accept()
   834  		if err != nil {
   835  			return fmt.Errorf("accept: %v", err)
   836  		}
   837  		defer sconn.Close()
   838  
   839  		serverConfig := testConfigServer.Clone()
   840  		srv := Server(sconn, serverConfig)
   841  		if err := srv.Handshake(); err != nil {
   842  			return fmt.Errorf("handshake: %v", err)
   843  		}
   844  		defer srv.Close()
   845  
   846  		_, err = io.ReadAll(srv)
   847  		if err == nil {
   848  			return errors.New("unexpected lack of error from server")
   849  		}
   850  		const expected = "too many ignored"
   851  		if str := err.Error(); !strings.Contains(str, expected) {
   852  			return fmt.Errorf("expected error containing %q, but saw: %s", expected, str)
   853  		}
   854  
   855  		return nil
   856  	}
   857  
   858  	errChan := make(chan error, 1)
   859  	go func() { errChan <- server() }()
   860  
   861  	clientConfig := testConfigClient.Clone()
   862  	clientConfig.MaxVersion = VersionTLS12 // there are no warning alerts in TLS 1.3
   863  	conn, err := Dial("tcp", ln.Addr().String(), clientConfig)
   864  	if err != nil {
   865  		t.Fatal(err)
   866  	}
   867  	defer conn.Close()
   868  	if err := conn.Handshake(); err != nil {
   869  		t.Fatal(err)
   870  	}
   871  
   872  	for i := 0; i < maxUselessRecords+1; i++ {
   873  		conn.sendAlert(alertNoRenegotiation)
   874  	}
   875  
   876  	if err := <-errChan; err != nil {
   877  		t.Fatal(err)
   878  	}
   879  }
   880  
   881  func TestCloneFuncFields(t *testing.T) {
   882  	const expectedCount = 10
   883  	called := 0
   884  
   885  	c1 := Config{
   886  		Time: func() time.Time {
   887  			called |= 1 << 0
   888  			return time.Time{}
   889  		},
   890  		GetCertificate: func(*ClientHelloInfo) (*Certificate, error) {
   891  			called |= 1 << 1
   892  			return nil, nil
   893  		},
   894  		GetClientCertificate: func(*CertificateRequestInfo) (*Certificate, error) {
   895  			called |= 1 << 2
   896  			return nil, nil
   897  		},
   898  		GetConfigForClient: func(*ClientHelloInfo) (*Config, error) {
   899  			called |= 1 << 3
   900  			return nil, nil
   901  		},
   902  		VerifyPeerCertificate: func(rawCerts [][]byte, verifiedChains [][]*x509.Certificate) error {
   903  			called |= 1 << 4
   904  			return nil
   905  		},
   906  		VerifyConnection: func(ConnectionState) error {
   907  			called |= 1 << 5
   908  			return nil
   909  		},
   910  		UnwrapSession: func(identity []byte, cs ConnectionState) (*SessionState, error) {
   911  			called |= 1 << 6
   912  			return nil, nil
   913  		},
   914  		WrapSession: func(cs ConnectionState, ss *SessionState) ([]byte, error) {
   915  			called |= 1 << 7
   916  			return nil, nil
   917  		},
   918  		EncryptedClientHelloRejectionVerify: func(ConnectionState) error {
   919  			called |= 1 << 8
   920  			return nil
   921  		},
   922  		GetEncryptedClientHelloKeys: func(*ClientHelloInfo) ([]EncryptedClientHelloKey, error) {
   923  			called |= 1 << 9
   924  			return nil, nil
   925  		},
   926  	}
   927  
   928  	c2 := c1.Clone()
   929  
   930  	c2.Time()
   931  	c2.GetCertificate(nil)
   932  	c2.GetClientCertificate(nil)
   933  	c2.GetConfigForClient(nil)
   934  	c2.VerifyPeerCertificate(nil, nil)
   935  	c2.VerifyConnection(ConnectionState{})
   936  	c2.UnwrapSession(nil, ConnectionState{})
   937  	c2.WrapSession(ConnectionState{}, nil)
   938  	c2.EncryptedClientHelloRejectionVerify(ConnectionState{})
   939  	c2.GetEncryptedClientHelloKeys(nil)
   940  
   941  	if called != (1<<expectedCount)-1 {
   942  		t.Fatalf("expected %d calls but saw calls %b", expectedCount, called)
   943  	}
   944  }
   945  
   946  func TestCloneNonFuncFields(t *testing.T) {
   947  	var c1 Config
   948  	v := reflect.ValueOf(&c1).Elem()
   949  
   950  	typ := v.Type()
   951  	for i := 0; i < typ.NumField(); i++ {
   952  		f := v.Field(i)
   953  		// testing/quick can't handle functions or interfaces and so
   954  		// isn't used here.
   955  		switch fn := typ.Field(i).Name; fn {
   956  		case "Rand":
   957  			f.Set(reflect.ValueOf(io.Reader(os.Stdin)))
   958  		case "Time", "GetCertificate", "GetConfigForClient", "VerifyPeerCertificate", "VerifyConnection", "GetClientCertificate", "WrapSession", "UnwrapSession", "EncryptedClientHelloRejectionVerify", "GetEncryptedClientHelloKeys":
   959  			// DeepEqual can't compare functions. If you add a
   960  			// function field to this list, you must also change
   961  			// TestCloneFuncFields to ensure that the func field is
   962  			// cloned.
   963  		case "Certificates":
   964  			f.Set(reflect.ValueOf([]Certificate{
   965  				{Certificate: [][]byte{{'b'}}},
   966  			}))
   967  		case "NameToCertificate":
   968  			f.Set(reflect.ValueOf(map[string]*Certificate{"a": nil}))
   969  		case "RootCAs", "ClientCAs":
   970  			f.Set(reflect.ValueOf(x509.NewCertPool()))
   971  		case "ClientSessionCache":
   972  			f.Set(reflect.ValueOf(NewLRUClientSessionCache(10)))
   973  		case "KeyLogWriter":
   974  			f.Set(reflect.ValueOf(io.Writer(os.Stdout)))
   975  		case "NextProtos":
   976  			f.Set(reflect.ValueOf([]string{"a", "b"}))
   977  		case "ServerName":
   978  			f.Set(reflect.ValueOf("b"))
   979  		case "ClientAuth":
   980  			f.Set(reflect.ValueOf(VerifyClientCertIfGiven))
   981  		case "InsecureSkipVerify", "SessionTicketsDisabled", "DynamicRecordSizingDisabled", "PreferServerCipherSuites":
   982  			f.Set(reflect.ValueOf(true))
   983  		case "MinVersion", "MaxVersion":
   984  			f.Set(reflect.ValueOf(uint16(VersionTLS12)))
   985  		case "SessionTicketKey":
   986  			f.Set(reflect.ValueOf([32]byte{}))
   987  		case "CipherSuites":
   988  			f.Set(reflect.ValueOf([]uint16{1, 2}))
   989  		case "CurvePreferences":
   990  			f.Set(reflect.ValueOf([]CurveID{CurveP256}))
   991  		case "Renegotiation":
   992  			f.Set(reflect.ValueOf(RenegotiateOnceAsClient))
   993  		case "EncryptedClientHelloConfigList":
   994  			f.Set(reflect.ValueOf([]byte{'x'}))
   995  		case "EncryptedClientHelloKeys":
   996  			f.Set(reflect.ValueOf([]EncryptedClientHelloKey{
   997  				{Config: []byte{1}, PrivateKey: []byte{1}},
   998  			}))
   999  		case "mutex", "autoSessionTicketKeys", "sessionTicketKeys":
  1000  			continue // these are unexported fields that are handled separately
  1001  		default:
  1002  			t.Errorf("all fields must be accounted for, but saw unknown field %q", fn)
  1003  		}
  1004  	}
  1005  	// Set the unexported fields related to session ticket keys, which are copied with Clone().
  1006  	c1.autoSessionTicketKeys = []ticketKey{c1.ticketKeyFromBytes(c1.SessionTicketKey)}
  1007  	c1.sessionTicketKeys = []ticketKey{c1.ticketKeyFromBytes(c1.SessionTicketKey)}
  1008  
  1009  	c2 := c1.Clone()
  1010  	if !reflect.DeepEqual(&c1, c2) {
  1011  		t.Errorf("clone failed to copy a field")
  1012  	}
  1013  }
  1014  
  1015  func TestCloneNilConfig(t *testing.T) {
  1016  	var config *Config
  1017  	if cc := config.Clone(); cc != nil {
  1018  		t.Fatalf("Clone with nil should return nil, got: %+v", cc)
  1019  	}
  1020  }
  1021  
  1022  // changeImplConn is a net.Conn which can change its Write and Close
  1023  // methods.
  1024  type changeImplConn struct {
  1025  	net.Conn
  1026  	writeFunc func([]byte) (int, error)
  1027  	closeFunc func() error
  1028  }
  1029  
  1030  func (w *changeImplConn) Write(p []byte) (n int, err error) {
  1031  	if w.writeFunc != nil {
  1032  		return w.writeFunc(p)
  1033  	}
  1034  	return w.Conn.Write(p)
  1035  }
  1036  
  1037  func (w *changeImplConn) Close() error {
  1038  	if w.closeFunc != nil {
  1039  		return w.closeFunc()
  1040  	}
  1041  	return w.Conn.Close()
  1042  }
  1043  
  1044  func throughput(b *testing.B, version uint16, totalBytes int64, dynamicRecordSizingDisabled bool) {
  1045  	ln := newLocalListener(b)
  1046  	defer ln.Close()
  1047  
  1048  	N := b.N
  1049  
  1050  	// Less than 64KB because Windows appears to use a TCP rwin < 64KB.
  1051  	// See Issue #15899.
  1052  	const bufsize = 32 << 10
  1053  
  1054  	go func() {
  1055  		buf := make([]byte, bufsize)
  1056  		for i := 0; i < N; i++ {
  1057  			sconn, err := ln.Accept()
  1058  			if err != nil {
  1059  				// panic rather than synchronize to avoid benchmark overhead
  1060  				// (cannot call b.Fatal in goroutine)
  1061  				panic(fmt.Errorf("accept: %v", err))
  1062  			}
  1063  			serverConfig := testConfigServer.Clone()
  1064  			serverConfig.CipherSuites = nil // the defaults may prefer faster ciphers
  1065  			serverConfig.DynamicRecordSizingDisabled = dynamicRecordSizingDisabled
  1066  			srv := Server(sconn, serverConfig)
  1067  			if err := srv.Handshake(); err != nil {
  1068  				panic(fmt.Errorf("handshake: %v", err))
  1069  			}
  1070  			if _, err := io.CopyBuffer(srv, srv, buf); err != nil {
  1071  				panic(fmt.Errorf("copy buffer: %v", err))
  1072  			}
  1073  		}
  1074  	}()
  1075  
  1076  	b.SetBytes(totalBytes)
  1077  	clientConfig := testConfigClient.Clone()
  1078  	clientConfig.CipherSuites = nil // the defaults may prefer faster ciphers
  1079  	clientConfig.DynamicRecordSizingDisabled = dynamicRecordSizingDisabled
  1080  	clientConfig.MaxVersion = version
  1081  
  1082  	buf := make([]byte, bufsize)
  1083  	chunks := int(math.Ceil(float64(totalBytes) / float64(len(buf))))
  1084  	for i := 0; i < N; i++ {
  1085  		conn, err := Dial("tcp", ln.Addr().String(), clientConfig)
  1086  		if err != nil {
  1087  			b.Fatal(err)
  1088  		}
  1089  		for j := 0; j < chunks; j++ {
  1090  			_, err := conn.Write(buf)
  1091  			if err != nil {
  1092  				b.Fatal(err)
  1093  			}
  1094  			_, err = io.ReadFull(conn, buf)
  1095  			if err != nil {
  1096  				b.Fatal(err)
  1097  			}
  1098  		}
  1099  		conn.Close()
  1100  	}
  1101  }
  1102  
  1103  func BenchmarkThroughput(b *testing.B) {
  1104  	for _, mode := range []string{"Max", "Dynamic"} {
  1105  		for size := 1; size <= 64; size <<= 1 {
  1106  			name := fmt.Sprintf("%sPacket/%dMB", mode, size)
  1107  			b.Run(name, func(b *testing.B) {
  1108  				b.Run("TLSv12", func(b *testing.B) {
  1109  					throughput(b, VersionTLS12, int64(size<<20), mode == "Max")
  1110  				})
  1111  				b.Run("TLSv13", func(b *testing.B) {
  1112  					throughput(b, VersionTLS13, int64(size<<20), mode == "Max")
  1113  				})
  1114  			})
  1115  		}
  1116  	}
  1117  }
  1118  
  1119  type slowConn struct {
  1120  	net.Conn
  1121  	bps int
  1122  }
  1123  
  1124  func (c *slowConn) Write(p []byte) (int, error) {
  1125  	if c.bps == 0 {
  1126  		panic("too slow")
  1127  	}
  1128  	t0 := time.Now()
  1129  	wrote := 0
  1130  	for wrote < len(p) {
  1131  		time.Sleep(100 * time.Microsecond)
  1132  		allowed := int(time.Since(t0).Seconds()*float64(c.bps)) / 8
  1133  		if allowed > len(p) {
  1134  			allowed = len(p)
  1135  		}
  1136  		if wrote < allowed {
  1137  			n, err := c.Conn.Write(p[wrote:allowed])
  1138  			wrote += n
  1139  			if err != nil {
  1140  				return wrote, err
  1141  			}
  1142  		}
  1143  	}
  1144  	return len(p), nil
  1145  }
  1146  
  1147  func latency(b *testing.B, version uint16, bps int, dynamicRecordSizingDisabled bool) {
  1148  	ln := newLocalListener(b)
  1149  	defer ln.Close()
  1150  
  1151  	N := b.N
  1152  
  1153  	go func() {
  1154  		for i := 0; i < N; i++ {
  1155  			sconn, err := ln.Accept()
  1156  			if err != nil {
  1157  				// panic rather than synchronize to avoid benchmark overhead
  1158  				// (cannot call b.Fatal in goroutine)
  1159  				panic(fmt.Errorf("accept: %v", err))
  1160  			}
  1161  			serverConfig := testConfigServer.Clone()
  1162  			serverConfig.DynamicRecordSizingDisabled = dynamicRecordSizingDisabled
  1163  			srv := Server(&slowConn{sconn, bps}, serverConfig)
  1164  			if err := srv.Handshake(); err != nil {
  1165  				panic(fmt.Errorf("handshake: %v", err))
  1166  			}
  1167  			io.Copy(srv, srv)
  1168  		}
  1169  	}()
  1170  
  1171  	clientConfig := testConfigClient.Clone()
  1172  	clientConfig.DynamicRecordSizingDisabled = dynamicRecordSizingDisabled
  1173  	clientConfig.MaxVersion = version
  1174  
  1175  	buf := make([]byte, 16384)
  1176  	peek := make([]byte, 1)
  1177  
  1178  	for i := 0; i < N; i++ {
  1179  		conn, err := Dial("tcp", ln.Addr().String(), clientConfig)
  1180  		if err != nil {
  1181  			b.Fatal(err)
  1182  		}
  1183  		// make sure we're connected and previous connection has stopped
  1184  		if _, err := conn.Write(buf[:1]); err != nil {
  1185  			b.Fatal(err)
  1186  		}
  1187  		if _, err := io.ReadFull(conn, peek); err != nil {
  1188  			b.Fatal(err)
  1189  		}
  1190  		if _, err := conn.Write(buf); err != nil {
  1191  			b.Fatal(err)
  1192  		}
  1193  		if _, err = io.ReadFull(conn, peek); err != nil {
  1194  			b.Fatal(err)
  1195  		}
  1196  		conn.Close()
  1197  	}
  1198  }
  1199  
  1200  func BenchmarkLatency(b *testing.B) {
  1201  	for _, mode := range []string{"Max", "Dynamic"} {
  1202  		for _, kbps := range []int{200, 500, 1000, 2000, 5000} {
  1203  			name := fmt.Sprintf("%sPacket/%dkbps", mode, kbps)
  1204  			b.Run(name, func(b *testing.B) {
  1205  				b.Run("TLSv12", func(b *testing.B) {
  1206  					latency(b, VersionTLS12, kbps*1000, mode == "Max")
  1207  				})
  1208  				b.Run("TLSv13", func(b *testing.B) {
  1209  					latency(b, VersionTLS13, kbps*1000, mode == "Max")
  1210  				})
  1211  			})
  1212  		}
  1213  	}
  1214  }
  1215  
  1216  func TestConnectionStateMarshal(t *testing.T) {
  1217  	cs := &ConnectionState{}
  1218  	_, err := json.Marshal(cs)
  1219  	if err != nil {
  1220  		t.Errorf("json.Marshal failed on ConnectionState: %v", err)
  1221  	}
  1222  }
  1223  
  1224  func TestConnectionState(t *testing.T) {
  1225  	const alpnProtocol = "golang"
  1226  	const serverName = "test.golang.example"
  1227  	var scts = [][]byte{[]byte("dummy sct 1"), []byte("dummy sct 2")}
  1228  	var ocsp = []byte("dummy ocsp")
  1229  
  1230  	checkConnectionState := func(t *testing.T, cs ConnectionState, version uint16, isClient bool) {
  1231  		// On the client, the peer is the server (testRSA2048Cert under
  1232  		// testRootCert); on the server, the peer is the client
  1233  		// (testClientRSA2048Cert under testClientRootCert).
  1234  		peerLeaf, peerRoot := testRSA2048Cert.Certificate[0], testRootCert.Certificate[0]
  1235  		if !isClient {
  1236  			peerLeaf, peerRoot = testClientRSA2048Cert.Certificate[0], testClientRootCert.Certificate[0]
  1237  		}
  1238  		if cs.Version != version {
  1239  			t.Errorf("got Version %x, expected %x", cs.Version, version)
  1240  		}
  1241  
  1242  		if !cs.HandshakeComplete {
  1243  			t.Errorf("got HandshakeComplete %v, expected true", cs.HandshakeComplete)
  1244  		}
  1245  
  1246  		if cs.DidResume {
  1247  			t.Errorf("got DidResume %v, expected false", cs.DidResume)
  1248  		}
  1249  
  1250  		if cs.CipherSuite == 0 {
  1251  			t.Errorf("got zero CipherSuite")
  1252  		}
  1253  
  1254  		if cs.CurveID == 0 {
  1255  			t.Errorf("got zero CurveID")
  1256  		}
  1257  
  1258  		if cs.NegotiatedProtocol != alpnProtocol {
  1259  			t.Errorf("got ALPN protocol %q, expected %q", cs.NegotiatedProtocol, alpnProtocol)
  1260  		}
  1261  
  1262  		if !cs.NegotiatedProtocolIsMutual {
  1263  			t.Errorf("got NegotiatedProtocolIsMutual %v, expected true", cs.NegotiatedProtocolIsMutual)
  1264  		}
  1265  
  1266  		if cs.ServerName != serverName {
  1267  			t.Errorf("got ServerName %q, expected %q", cs.ServerName, serverName)
  1268  		}
  1269  
  1270  		if len(cs.PeerCertificates) != 1 {
  1271  			t.Errorf("got %d PeerCertificates, expected %d", len(cs.PeerCertificates), 1)
  1272  		} else if !bytes.Equal(cs.PeerCertificates[0].Raw, peerLeaf) {
  1273  			t.Errorf("got PeerCertificates %x, expected %x", cs.PeerCertificates[0].Raw, peerLeaf)
  1274  		}
  1275  
  1276  		if len(cs.VerifiedChains) != 1 {
  1277  			t.Errorf("got %d long verified chain, expected %d", len(cs.VerifiedChains), 1)
  1278  		} else if len(cs.VerifiedChains[0]) != 2 {
  1279  			t.Errorf("got %d verified chain, expected %d", len(cs.VerifiedChains[0]), 2)
  1280  		} else if !bytes.Equal(cs.VerifiedChains[0][0].Raw, peerLeaf) {
  1281  			t.Errorf("got verified chain[0][0] %x, expected %x", cs.VerifiedChains[0][0].Raw, peerLeaf)
  1282  		} else if !bytes.Equal(cs.VerifiedChains[0][1].Raw, peerRoot) {
  1283  			t.Errorf("got verified chain[0][1] %x, expected %x", cs.VerifiedChains[0][1].Raw, peerRoot)
  1284  		}
  1285  
  1286  		// Only TLS 1.3 supports OCSP and SCTs on client certs.
  1287  		if isClient || version == VersionTLS13 {
  1288  			if len(cs.SignedCertificateTimestamps) != 2 {
  1289  				t.Errorf("got %d SCTs, expected %d", len(cs.SignedCertificateTimestamps), 2)
  1290  			} else if !bytes.Equal(cs.SignedCertificateTimestamps[0], scts[0]) {
  1291  				t.Errorf("got SCTs %x, expected %x", cs.SignedCertificateTimestamps[0], scts[0])
  1292  			} else if !bytes.Equal(cs.SignedCertificateTimestamps[1], scts[1]) {
  1293  				t.Errorf("got SCTs %x, expected %x", cs.SignedCertificateTimestamps[1], scts[1])
  1294  			}
  1295  			if !bytes.Equal(cs.OCSPResponse, ocsp) {
  1296  				t.Errorf("got OCSP %x, expected %x", cs.OCSPResponse, ocsp)
  1297  			}
  1298  		} else {
  1299  			if cs.SignedCertificateTimestamps != nil {
  1300  				t.Errorf("got %d SCTs, expected nil", len(cs.SignedCertificateTimestamps))
  1301  			}
  1302  			if cs.OCSPResponse != nil {
  1303  				t.Errorf("got OCSP %x, expected nil", cs.OCSPResponse)
  1304  			}
  1305  		}
  1306  
  1307  		if version == VersionTLS13 {
  1308  			if cs.TLSUnique != nil {
  1309  				t.Errorf("got TLSUnique %x, expected nil", cs.TLSUnique)
  1310  			}
  1311  		} else {
  1312  			if cs.TLSUnique == nil {
  1313  				t.Errorf("got nil TLSUnique")
  1314  			}
  1315  		}
  1316  	}
  1317  
  1318  	compareConnectionStates := func(t *testing.T, cs1, cs2 ConnectionState) {
  1319  		if cs1.Version != cs2.Version {
  1320  			t.Errorf("Version mismatch: %x != %x", cs1.Version, cs2.Version)
  1321  		}
  1322  		if cs1.HandshakeComplete != cs2.HandshakeComplete {
  1323  			t.Errorf("HandshakeComplete mismatch: %v != %v", cs1.HandshakeComplete, cs2.HandshakeComplete)
  1324  		}
  1325  		// DidResume is expected to be different.
  1326  		if cs1.CipherSuite != cs2.CipherSuite {
  1327  			t.Errorf("CipherSuite mismatch: %x != %x", cs1.CipherSuite, cs2.CipherSuite)
  1328  		}
  1329  		if cs1.CurveID != cs2.CurveID {
  1330  			t.Errorf("CurveID mismatch: %s != %s", cs1.CurveID, cs2.CurveID)
  1331  		}
  1332  		if cs1.NegotiatedProtocol != cs2.NegotiatedProtocol {
  1333  			t.Errorf("NegotiatedProtocol mismatch: %q != %q", cs1.NegotiatedProtocol, cs2.NegotiatedProtocol)
  1334  		}
  1335  		if cs1.NegotiatedProtocolIsMutual != cs2.NegotiatedProtocolIsMutual {
  1336  			t.Errorf("NegotiatedProtocolIsMutual mismatch: %v != %v", cs1.NegotiatedProtocolIsMutual, cs2.NegotiatedProtocolIsMutual)
  1337  		}
  1338  		if cs1.ServerName != cs2.ServerName {
  1339  			t.Errorf("ServerName mismatch: %q != %q", cs1.ServerName, cs2.ServerName)
  1340  		}
  1341  		if !reflect.DeepEqual(cs1.PeerCertificates, cs2.PeerCertificates) {
  1342  			t.Errorf("PeerCertificates mismatch")
  1343  		}
  1344  		if !reflect.DeepEqual(cs1.VerifiedChains, cs2.VerifiedChains) {
  1345  			t.Errorf("VerifiedChains mismatch")
  1346  		}
  1347  		if !reflect.DeepEqual(cs1.SignedCertificateTimestamps, cs2.SignedCertificateTimestamps) {
  1348  			t.Errorf("SignedCertificateTimestamps mismatch: %x != %x", cs1.SignedCertificateTimestamps, cs2.SignedCertificateTimestamps)
  1349  		}
  1350  		if !bytes.Equal(cs1.OCSPResponse, cs2.OCSPResponse) {
  1351  			t.Errorf("OCSPResponse mismatch: %x != %x", cs1.OCSPResponse, cs2.OCSPResponse)
  1352  		}
  1353  		// TLSUnique is expected to be different.
  1354  	}
  1355  
  1356  	for _, v := range []uint16{VersionTLS10, VersionTLS12, VersionTLS13} {
  1357  		if !isFIPSVersion(v) && fips140tls.Required() {
  1358  			t.Skipf("skipping test in FIPS 140-3 mode for non-FIPS version %x", v)
  1359  		}
  1360  		var name string
  1361  		switch v {
  1362  		case VersionTLS10:
  1363  			name = "TLSv10"
  1364  		case VersionTLS12:
  1365  			name = "TLSv12"
  1366  		case VersionTLS13:
  1367  			name = "TLSv13"
  1368  		}
  1369  		t.Run(name, func(t *testing.T) {
  1370  			serverCert := testRSA2048Cert
  1371  			serverCert.SignedCertificateTimestamps = scts
  1372  			serverCert.OCSPStaple = ocsp
  1373  			clientCert := testClientRSA2048Cert
  1374  			clientCert.SignedCertificateTimestamps = scts
  1375  			clientCert.OCSPStaple = ocsp
  1376  
  1377  			serverConfig := &Config{
  1378  				Time:         testTime,
  1379  				Certificates: []Certificate{serverCert},
  1380  				MinVersion:   v,
  1381  				MaxVersion:   v,
  1382  				ClientCAs:    testClientRootCertPool,
  1383  				ClientAuth:   RequireAndVerifyClientCert,
  1384  				NextProtos:   []string{alpnProtocol},
  1385  			}
  1386  			clientConfig := &Config{
  1387  				Time:               testTime,
  1388  				Certificates:       []Certificate{clientCert},
  1389  				MinVersion:         v,
  1390  				MaxVersion:         v,
  1391  				RootCAs:            testRootCertPool,
  1392  				NextProtos:         []string{alpnProtocol},
  1393  				ServerName:         serverName,
  1394  				ClientSessionCache: NewLRUClientSessionCache(1),
  1395  			}
  1396  
  1397  			ss, cs, err := testHandshake(t, clientConfig, serverConfig)
  1398  			if err != nil {
  1399  				t.Fatalf("handshake failed: %v", err)
  1400  			}
  1401  
  1402  			t.Run("Client", func(t *testing.T) { checkConnectionState(t, cs, v, true) })
  1403  			t.Run("Server", func(t *testing.T) { checkConnectionState(t, ss, v, false) })
  1404  
  1405  			t.Run("Resume", func(t *testing.T) {
  1406  				// TODO: test changing parameters between original and resumed
  1407  				// connection when the protocol allows it.
  1408  
  1409  				ss1, cs1, err := testHandshake(t, clientConfig, serverConfig)
  1410  				if err != nil {
  1411  					t.Fatalf("handshake failed: %v", err)
  1412  				}
  1413  
  1414  				if !cs1.DidResume || !ss1.DidResume {
  1415  					t.Errorf("DidResume is false")
  1416  				}
  1417  
  1418  				t.Run("Client", func(t *testing.T) { compareConnectionStates(t, cs, cs1) })
  1419  				t.Run("Server", func(t *testing.T) { compareConnectionStates(t, ss, ss1) })
  1420  			})
  1421  		})
  1422  	}
  1423  }
  1424  
  1425  // Issue 28744: Ensure that we don't modify memory
  1426  // that Config doesn't own such as Certificates.
  1427  func TestBuildNameToCertificate_doesntModifyCertificates(t *testing.T) {
  1428  	config := testConfigServer.Clone()
  1429  	config.Certificates = []Certificate{testRSA2048Cert, testSNICert}
  1430  
  1431  	config.BuildNameToCertificate()
  1432  	got := config.Certificates
  1433  	want := []Certificate{testRSA2048Cert, testSNICert}
  1434  	if !reflect.DeepEqual(got, want) {
  1435  		t.Fatalf("Certificates were mutated by BuildNameToCertificate\nGot: %#v\nWant: %#v\n", got, want)
  1436  	}
  1437  }
  1438  
  1439  func testingKey(s string) string { return strings.ReplaceAll(s, "TESTING KEY", "PRIVATE KEY") }
  1440  
  1441  func TestClientHelloInfo_SupportsCertificate(t *testing.T) {
  1442  	skipFIPS(t) // SHA-1, Ed25519, and legacy RSA kex test cases not FIPS compatible.
  1443  
  1444  	pkcs1Cert := testRSA2048Cert
  1445  	pkcs1Cert.SupportedSignatureAlgorithms = []SignatureScheme{PKCS1WithSHA1, PKCS1WithSHA256}
  1446  
  1447  	tests := []struct {
  1448  		c       Certificate
  1449  		chi     *ClientHelloInfo
  1450  		wantErr string
  1451  	}{
  1452  		{testRSA2048Cert, &ClientHelloInfo{
  1453  			ServerName:        "test.golang.example",
  1454  			SignatureSchemes:  []SignatureScheme{PSSWithSHA256},
  1455  			SupportedVersions: []uint16{VersionTLS13},
  1456  		}, ""},
  1457  		{testECDSAP256Cert, &ClientHelloInfo{
  1458  			SignatureSchemes:  []SignatureScheme{PSSWithSHA256, ECDSAWithP256AndSHA256},
  1459  			SupportedVersions: []uint16{VersionTLS13, VersionTLS12},
  1460  		}, ""},
  1461  		{testRSA2048Cert, &ClientHelloInfo{
  1462  			ServerName:        "example.com",
  1463  			SignatureSchemes:  []SignatureScheme{PSSWithSHA256},
  1464  			SupportedVersions: []uint16{VersionTLS13},
  1465  		}, "not valid for requested server name"},
  1466  		{testECDSAP256Cert, &ClientHelloInfo{
  1467  			SignatureSchemes:  []SignatureScheme{ECDSAWithP384AndSHA384},
  1468  			SupportedVersions: []uint16{VersionTLS13},
  1469  		}, "signature algorithms"},
  1470  		{pkcs1Cert, &ClientHelloInfo{
  1471  			SignatureSchemes:  []SignatureScheme{PSSWithSHA256, ECDSAWithP256AndSHA256},
  1472  			SupportedVersions: []uint16{VersionTLS13},
  1473  		}, "signature algorithms"},
  1474  
  1475  		{testRSA2048Cert, &ClientHelloInfo{
  1476  			CipherSuites:      []uint16{TLS_RSA_WITH_AES_128_GCM_SHA256},
  1477  			SignatureSchemes:  []SignatureScheme{PKCS1WithSHA1},
  1478  			SupportedVersions: []uint16{VersionTLS13, VersionTLS12},
  1479  		}, "signature algorithms"},
  1480  		{testRSA2048Cert, &ClientHelloInfo{
  1481  			CipherSuites:      []uint16{TLS_RSA_WITH_AES_128_GCM_SHA256},
  1482  			SignatureSchemes:  []SignatureScheme{PKCS1WithSHA1},
  1483  			SupportedVersions: []uint16{VersionTLS13, VersionTLS12},
  1484  			config: &Config{
  1485  				CipherSuites: []uint16{TLS_RSA_WITH_AES_128_GCM_SHA256},
  1486  				MaxVersion:   VersionTLS12,
  1487  			},
  1488  		}, ""}, // Check that mutual version selection works.
  1489  
  1490  		{testECDSAP256Cert, &ClientHelloInfo{
  1491  			CipherSuites:      []uint16{TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256},
  1492  			SupportedCurves:   []CurveID{CurveP256},
  1493  			SupportedPoints:   []uint8{pointFormatUncompressed},
  1494  			SignatureSchemes:  []SignatureScheme{ECDSAWithP256AndSHA256},
  1495  			SupportedVersions: []uint16{VersionTLS12},
  1496  		}, ""},
  1497  		{testECDSAP256Cert, &ClientHelloInfo{
  1498  			CipherSuites:      []uint16{TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256},
  1499  			SupportedCurves:   []CurveID{CurveP256},
  1500  			SupportedPoints:   []uint8{pointFormatUncompressed},
  1501  			SignatureSchemes:  []SignatureScheme{ECDSAWithP384AndSHA384},
  1502  			SupportedVersions: []uint16{VersionTLS12},
  1503  		}, ""}, // TLS 1.2 does not restrict curves based on the SignatureScheme.
  1504  		{testECDSAP256Cert, &ClientHelloInfo{
  1505  			CipherSuites:      []uint16{TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256},
  1506  			SupportedCurves:   []CurveID{CurveP256},
  1507  			SupportedPoints:   []uint8{pointFormatUncompressed},
  1508  			SignatureSchemes:  nil,
  1509  			SupportedVersions: []uint16{VersionTLS12},
  1510  		}, ""}, // TLS 1.2 comes with default signature schemes.
  1511  		{testECDSAP256Cert, &ClientHelloInfo{
  1512  			CipherSuites:      []uint16{TLS_RSA_WITH_AES_128_GCM_SHA256},
  1513  			SupportedCurves:   []CurveID{CurveP256},
  1514  			SupportedPoints:   []uint8{pointFormatUncompressed},
  1515  			SignatureSchemes:  []SignatureScheme{ECDSAWithP256AndSHA256},
  1516  			SupportedVersions: []uint16{VersionTLS12},
  1517  		}, "cipher suite"},
  1518  		{testECDSAP256Cert, &ClientHelloInfo{
  1519  			CipherSuites:      []uint16{TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256},
  1520  			SupportedCurves:   []CurveID{CurveP256},
  1521  			SupportedPoints:   []uint8{pointFormatUncompressed},
  1522  			SignatureSchemes:  []SignatureScheme{ECDSAWithP256AndSHA256},
  1523  			SupportedVersions: []uint16{VersionTLS12},
  1524  			config: &Config{
  1525  				CipherSuites: []uint16{TLS_RSA_WITH_AES_128_GCM_SHA256},
  1526  			},
  1527  		}, "cipher suite"},
  1528  		{testECDSAP256Cert, &ClientHelloInfo{
  1529  			CipherSuites:      []uint16{TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256},
  1530  			SupportedCurves:   []CurveID{CurveP384},
  1531  			SupportedPoints:   []uint8{pointFormatUncompressed},
  1532  			SignatureSchemes:  []SignatureScheme{ECDSAWithP256AndSHA256},
  1533  			SupportedVersions: []uint16{VersionTLS12},
  1534  		}, "certificate curve"},
  1535  		{testECDSAP256Cert, &ClientHelloInfo{
  1536  			CipherSuites:      []uint16{TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256},
  1537  			SupportedCurves:   []CurveID{CurveP256},
  1538  			SupportedPoints:   []uint8{1},
  1539  			SignatureSchemes:  []SignatureScheme{ECDSAWithP256AndSHA256},
  1540  			SupportedVersions: []uint16{VersionTLS12},
  1541  		}, "only incompatible point formats"},
  1542  		{testECDSAP256Cert, &ClientHelloInfo{
  1543  			CipherSuites:      []uint16{TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256},
  1544  			SupportedCurves:   []CurveID{CurveP256},
  1545  			SupportedPoints:   []uint8{pointFormatUncompressed},
  1546  			SignatureSchemes:  []SignatureScheme{PSSWithSHA256},
  1547  			SupportedVersions: []uint16{VersionTLS12},
  1548  		}, "signature algorithms"},
  1549  
  1550  		{testEd25519Cert, &ClientHelloInfo{
  1551  			CipherSuites:      []uint16{TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256},
  1552  			SupportedCurves:   []CurveID{CurveP256}, // only relevant for ECDHE support
  1553  			SupportedPoints:   []uint8{pointFormatUncompressed},
  1554  			SignatureSchemes:  []SignatureScheme{Ed25519},
  1555  			SupportedVersions: []uint16{VersionTLS12},
  1556  		}, ""},
  1557  		{testEd25519Cert, &ClientHelloInfo{
  1558  			CipherSuites:      []uint16{TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256},
  1559  			SupportedCurves:   []CurveID{CurveP256}, // only relevant for ECDHE support
  1560  			SupportedPoints:   []uint8{pointFormatUncompressed},
  1561  			SignatureSchemes:  []SignatureScheme{Ed25519},
  1562  			SupportedVersions: []uint16{VersionTLS10},
  1563  			config:            &Config{MinVersion: VersionTLS10},
  1564  		}, "doesn't support Ed25519"},
  1565  		{testEd25519Cert, &ClientHelloInfo{
  1566  			CipherSuites:      []uint16{TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256},
  1567  			SupportedCurves:   []CurveID{},
  1568  			SupportedPoints:   []uint8{pointFormatUncompressed},
  1569  			SignatureSchemes:  []SignatureScheme{Ed25519},
  1570  			SupportedVersions: []uint16{VersionTLS12},
  1571  		}, "doesn't support ECDHE"},
  1572  
  1573  		{testRSA2048Cert, &ClientHelloInfo{
  1574  			CipherSuites:      []uint16{TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA},
  1575  			SupportedCurves:   []CurveID{CurveP256}, // only relevant for ECDHE support
  1576  			SupportedPoints:   []uint8{pointFormatUncompressed},
  1577  			SupportedVersions: []uint16{VersionTLS10},
  1578  			config:            &Config{MinVersion: VersionTLS10},
  1579  		}, ""},
  1580  		{testRSA2048Cert, &ClientHelloInfo{
  1581  			CipherSuites:      []uint16{TLS_RSA_WITH_AES_128_GCM_SHA256},
  1582  			SupportedVersions: []uint16{VersionTLS12},
  1583  			config: &Config{
  1584  				CipherSuites: []uint16{TLS_RSA_WITH_AES_128_GCM_SHA256},
  1585  			},
  1586  		}, ""}, // static RSA fallback
  1587  
  1588  		{testMLDSA44Cert, &ClientHelloInfo{
  1589  			SignatureSchemes:  []SignatureScheme{MLDSA44},
  1590  			SupportedVersions: []uint16{VersionTLS13},
  1591  		}, ""},
  1592  		{testMLDSA65Cert, &ClientHelloInfo{
  1593  			SignatureSchemes:  []SignatureScheme{MLDSA65},
  1594  			SupportedVersions: []uint16{VersionTLS13},
  1595  		}, ""},
  1596  		{testMLDSA87Cert, &ClientHelloInfo{
  1597  			SignatureSchemes:  []SignatureScheme{MLDSA87},
  1598  			SupportedVersions: []uint16{VersionTLS13},
  1599  		}, ""},
  1600  		{testMLDSA44Cert, &ClientHelloInfo{
  1601  			CipherSuites:      []uint16{TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256},
  1602  			SupportedCurves:   []CurveID{CurveP256},
  1603  			SupportedPoints:   []uint8{pointFormatUncompressed},
  1604  			SupportedVersions: []uint16{VersionTLS12},
  1605  		}, "doesn't support ML-DSA"},
  1606  	}
  1607  	for i, tt := range tests {
  1608  		err := tt.chi.SupportsCertificate(&tt.c)
  1609  		switch {
  1610  		case tt.wantErr == "" && err != nil:
  1611  			t.Errorf("%d: unexpected error: %v", i, err)
  1612  		case tt.wantErr != "" && err == nil:
  1613  			t.Errorf("%d: unexpected success", i)
  1614  		case tt.wantErr != "" && !strings.Contains(err.Error(), tt.wantErr):
  1615  			t.Errorf("%d: got error %q, expected %q", i, err, tt.wantErr)
  1616  		}
  1617  	}
  1618  }
  1619  
  1620  func TestCipherSuites(t *testing.T) {
  1621  	var lastID uint16
  1622  	for _, c := range CipherSuites() {
  1623  		if lastID > c.ID {
  1624  			t.Errorf("CipherSuites are not ordered by ID: got %#04x after %#04x", c.ID, lastID)
  1625  		} else {
  1626  			lastID = c.ID
  1627  		}
  1628  
  1629  		if c.Insecure {
  1630  			t.Errorf("%#04x: Insecure CipherSuite returned by CipherSuites()", c.ID)
  1631  		}
  1632  	}
  1633  	lastID = 0
  1634  	for _, c := range InsecureCipherSuites() {
  1635  		if lastID > c.ID {
  1636  			t.Errorf("InsecureCipherSuites are not ordered by ID: got %#04x after %#04x", c.ID, lastID)
  1637  		} else {
  1638  			lastID = c.ID
  1639  		}
  1640  
  1641  		if !c.Insecure {
  1642  			t.Errorf("%#04x: not Insecure CipherSuite returned by InsecureCipherSuites()", c.ID)
  1643  		}
  1644  	}
  1645  
  1646  	CipherSuiteByID := func(id uint16) *CipherSuite {
  1647  		for _, c := range CipherSuites() {
  1648  			if c.ID == id {
  1649  				return c
  1650  			}
  1651  		}
  1652  		for _, c := range InsecureCipherSuites() {
  1653  			if c.ID == id {
  1654  				return c
  1655  			}
  1656  		}
  1657  		return nil
  1658  	}
  1659  
  1660  	for _, c := range cipherSuites {
  1661  		cc := CipherSuiteByID(c.id)
  1662  		if cc == nil {
  1663  			t.Errorf("%#04x: no CipherSuite entry", c.id)
  1664  			continue
  1665  		}
  1666  
  1667  		if tls12Only := c.flags&suiteTLS12 != 0; tls12Only && len(cc.SupportedVersions) != 1 {
  1668  			t.Errorf("%#04x: suite is TLS 1.2 only, but SupportedVersions is %v", c.id, cc.SupportedVersions)
  1669  		} else if !tls12Only && len(cc.SupportedVersions) != 3 {
  1670  			t.Errorf("%#04x: suite TLS 1.0-1.2, but SupportedVersions is %v", c.id, cc.SupportedVersions)
  1671  		}
  1672  
  1673  		if cc.Insecure {
  1674  			if slices.Contains(defaultCipherSuites(false), c.id) {
  1675  				t.Errorf("%#04x: insecure suite in default list", c.id)
  1676  			}
  1677  		} else {
  1678  			if !slices.Contains(defaultCipherSuites(false), c.id) {
  1679  				t.Errorf("%#04x: secure suite not in default list", c.id)
  1680  			}
  1681  		}
  1682  
  1683  		if got := CipherSuiteName(c.id); got != cc.Name {
  1684  			t.Errorf("%#04x: unexpected CipherSuiteName: got %q, expected %q", c.id, got, cc.Name)
  1685  		}
  1686  	}
  1687  	for _, c := range cipherSuitesTLS13 {
  1688  		cc := CipherSuiteByID(c.id)
  1689  		if cc == nil {
  1690  			t.Errorf("%#04x: no CipherSuite entry", c.id)
  1691  			continue
  1692  		}
  1693  
  1694  		if cc.Insecure {
  1695  			t.Errorf("%#04x: Insecure %v, expected false", c.id, cc.Insecure)
  1696  		}
  1697  		if len(cc.SupportedVersions) != 1 || cc.SupportedVersions[0] != VersionTLS13 {
  1698  			t.Errorf("%#04x: suite is TLS 1.3 only, but SupportedVersions is %v", c.id, cc.SupportedVersions)
  1699  		}
  1700  
  1701  		if got := CipherSuiteName(c.id); got != cc.Name {
  1702  			t.Errorf("%#04x: unexpected CipherSuiteName: got %q, expected %q", c.id, got, cc.Name)
  1703  		}
  1704  	}
  1705  
  1706  	if got := CipherSuiteName(0xabc); got != "0x0ABC" {
  1707  		t.Errorf("unexpected fallback CipherSuiteName: got %q, expected 0x0ABC", got)
  1708  	}
  1709  
  1710  	if len(cipherSuitesPreferenceOrder) != len(cipherSuites) {
  1711  		t.Errorf("cipherSuitesPreferenceOrder is not the same size as cipherSuites")
  1712  	}
  1713  	if len(cipherSuitesPreferenceOrderNoAES) != len(cipherSuitesPreferenceOrder) {
  1714  		t.Errorf("cipherSuitesPreferenceOrderNoAES is not the same size as cipherSuitesPreferenceOrder")
  1715  	}
  1716  
  1717  	// Check that disabled suites are marked insecure.
  1718  	for id := range disabledCipherSuites {
  1719  		c := CipherSuiteByID(id)
  1720  		if c == nil {
  1721  			t.Errorf("%#04x: no CipherSuite entry", id)
  1722  			continue
  1723  		}
  1724  		if !c.Insecure {
  1725  			t.Errorf("%#04x: disabled by default but not marked insecure", id)
  1726  		}
  1727  	}
  1728  
  1729  	for i, prefOrder := range [][]uint16{cipherSuitesPreferenceOrder, cipherSuitesPreferenceOrderNoAES} {
  1730  		// Check that insecure and HTTP/2 bad cipher suites are at the end of
  1731  		// the preference lists.
  1732  		var sawInsecure, sawBad bool
  1733  		for _, id := range prefOrder {
  1734  			c := CipherSuiteByID(id)
  1735  			if c == nil {
  1736  				t.Errorf("%#04x: no CipherSuite entry", id)
  1737  				continue
  1738  			}
  1739  
  1740  			if c.Insecure {
  1741  				sawInsecure = true
  1742  			} else if sawInsecure {
  1743  				t.Errorf("%#04x: secure suite after insecure one(s)", id)
  1744  			}
  1745  
  1746  			if http2isBadCipher(id) {
  1747  				sawBad = true
  1748  			} else if sawBad {
  1749  				t.Errorf("%#04x: non-bad suite after bad HTTP/2 one(s)", id)
  1750  			}
  1751  		}
  1752  
  1753  		// Check that the list is sorted according to the documented criteria.
  1754  		isBetter := func(a, b uint16) int {
  1755  			aSuite, bSuite := cipherSuiteByID(a), cipherSuiteByID(b)
  1756  			aName, bName := CipherSuiteName(a), CipherSuiteName(b)
  1757  			// * < RC4
  1758  			if !strings.Contains(aName, "RC4") && strings.Contains(bName, "RC4") {
  1759  				return -1
  1760  			} else if strings.Contains(aName, "RC4") && !strings.Contains(bName, "RC4") {
  1761  				return +1
  1762  			}
  1763  			// * < CBC_SHA256
  1764  			if !strings.Contains(aName, "CBC_SHA256") && strings.Contains(bName, "CBC_SHA256") {
  1765  				return -1
  1766  			} else if strings.Contains(aName, "CBC_SHA256") && !strings.Contains(bName, "CBC_SHA256") {
  1767  				return +1
  1768  			}
  1769  			// * < 3DES
  1770  			if !strings.Contains(aName, "3DES") && strings.Contains(bName, "3DES") {
  1771  				return -1
  1772  			} else if strings.Contains(aName, "3DES") && !strings.Contains(bName, "3DES") {
  1773  				return +1
  1774  			}
  1775  			// ECDHE < *
  1776  			if aSuite.flags&suiteECDHE != 0 && bSuite.flags&suiteECDHE == 0 {
  1777  				return -1
  1778  			} else if aSuite.flags&suiteECDHE == 0 && bSuite.flags&suiteECDHE != 0 {
  1779  				return +1
  1780  			}
  1781  			// AEAD < CBC
  1782  			if aSuite.aead != nil && bSuite.aead == nil {
  1783  				return -1
  1784  			} else if aSuite.aead == nil && bSuite.aead != nil {
  1785  				return +1
  1786  			}
  1787  			// AES < ChaCha20
  1788  			if strings.Contains(aName, "AES") && strings.Contains(bName, "CHACHA20") {
  1789  				// negative for cipherSuitesPreferenceOrder
  1790  				if i == 0 {
  1791  					return -1
  1792  				} else {
  1793  					return +1
  1794  				}
  1795  			} else if strings.Contains(aName, "CHACHA20") && strings.Contains(bName, "AES") {
  1796  				// negative for cipherSuitesPreferenceOrderNoAES
  1797  				if i != 0 {
  1798  					return -1
  1799  				} else {
  1800  					return +1
  1801  				}
  1802  			}
  1803  			// AES-128 < AES-256
  1804  			if strings.Contains(aName, "AES_128") && strings.Contains(bName, "AES_256") {
  1805  				return -1
  1806  			} else if strings.Contains(aName, "AES_256") && strings.Contains(bName, "AES_128") {
  1807  				return +1
  1808  			}
  1809  			// ECDSA < RSA
  1810  			if aSuite.flags&suiteECSign != 0 && bSuite.flags&suiteECSign == 0 {
  1811  				return -1
  1812  			} else if aSuite.flags&suiteECSign == 0 && bSuite.flags&suiteECSign != 0 {
  1813  				return +1
  1814  			}
  1815  			t.Fatalf("two ciphersuites are equal by all criteria: %v and %v", aName, bName)
  1816  			panic("unreachable")
  1817  		}
  1818  		if !slices.IsSortedFunc(prefOrder, isBetter) {
  1819  			t.Error("preference order is not sorted according to the rules")
  1820  		}
  1821  	}
  1822  }
  1823  
  1824  func TestVersionName(t *testing.T) {
  1825  	if got, exp := VersionName(VersionTLS13), "TLS 1.3"; got != exp {
  1826  		t.Errorf("unexpected VersionName: got %q, expected %q", got, exp)
  1827  	}
  1828  	if got, exp := VersionName(0x12a), "0x012A"; got != exp {
  1829  		t.Errorf("unexpected fallback VersionName: got %q, expected %q", got, exp)
  1830  	}
  1831  }
  1832  
  1833  // http2isBadCipher is copied from net/http.
  1834  // TODO: if it ends up exposed somewhere, use that instead.
  1835  func http2isBadCipher(cipher uint16) bool {
  1836  	switch cipher {
  1837  	case TLS_RSA_WITH_RC4_128_SHA,
  1838  		TLS_RSA_WITH_3DES_EDE_CBC_SHA,
  1839  		TLS_RSA_WITH_AES_128_CBC_SHA,
  1840  		TLS_RSA_WITH_AES_256_CBC_SHA,
  1841  		TLS_RSA_WITH_AES_128_CBC_SHA256,
  1842  		TLS_RSA_WITH_AES_128_GCM_SHA256,
  1843  		TLS_RSA_WITH_AES_256_GCM_SHA384,
  1844  		TLS_ECDHE_ECDSA_WITH_RC4_128_SHA,
  1845  		TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA,
  1846  		TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA,
  1847  		TLS_ECDHE_RSA_WITH_RC4_128_SHA,
  1848  		TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA,
  1849  		TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,
  1850  		TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA,
  1851  		TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256,
  1852  		TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256:
  1853  		return true
  1854  	default:
  1855  		return false
  1856  	}
  1857  }
  1858  
  1859  type brokenSigner struct{ crypto.Signer }
  1860  
  1861  func (s brokenSigner) Sign(rand io.Reader, digest []byte, opts crypto.SignerOpts) (signature []byte, err error) {
  1862  	// Replace opts with opts.HashFunc(), so rsa.PSSOptions are discarded.
  1863  	return s.Signer.Sign(rand, digest, opts.HashFunc())
  1864  }
  1865  
  1866  // TestPKCS1OnlyCert uses a client certificate with a broken crypto.Signer that
  1867  // always makes PKCS #1 v1.5 signatures, so can't be used with RSA-PSS.
  1868  func TestPKCS1OnlyCert(t *testing.T) {
  1869  	clientConfig := testConfigClient.Clone()
  1870  	clientConfig.Certificates = []Certificate{{
  1871  		Certificate: testClientRSA2048Cert.Certificate,
  1872  		PrivateKey:  brokenSigner{testClientRSA2048Key},
  1873  	}}
  1874  	serverConfig := testConfigServer.Clone()
  1875  	serverConfig.MaxVersion = VersionTLS12 // TLS 1.3 doesn't support PKCS #1 v1.5
  1876  	serverConfig.ClientAuth = RequireAnyClientCert
  1877  
  1878  	// If RSA-PSS is selected, the handshake should fail.
  1879  	if _, _, err := testHandshake(t, clientConfig, serverConfig); err == nil {
  1880  		t.Fatal("expected broken certificate to cause connection to fail")
  1881  	}
  1882  
  1883  	clientConfig.Certificates[0].SupportedSignatureAlgorithms =
  1884  		[]SignatureScheme{PKCS1WithSHA1, PKCS1WithSHA256}
  1885  
  1886  	// But if the certificate restricts supported algorithms, RSA-PSS should not
  1887  	// be selected, and the handshake should succeed.
  1888  	if _, _, err := testHandshake(t, clientConfig, serverConfig); err != nil {
  1889  		t.Error(err)
  1890  	}
  1891  }
  1892  
  1893  func TestVerifyCertificates(t *testing.T) {
  1894  	// See https://go.dev/issue/31641.
  1895  	t.Run("TLSv12", func(t *testing.T) { testVerifyCertificates(t, VersionTLS12) })
  1896  	t.Run("TLSv13", func(t *testing.T) { testVerifyCertificates(t, VersionTLS13) })
  1897  }
  1898  
  1899  func testVerifyCertificates(t *testing.T, version uint16) {
  1900  	tests := []struct {
  1901  		name string
  1902  
  1903  		InsecureSkipVerify bool
  1904  		ClientAuth         ClientAuthType
  1905  		ClientCertificates bool
  1906  	}{
  1907  		{
  1908  			name: "defaults",
  1909  		},
  1910  		{
  1911  			name:               "InsecureSkipVerify",
  1912  			InsecureSkipVerify: true,
  1913  		},
  1914  		{
  1915  			name:       "RequestClientCert with no certs",
  1916  			ClientAuth: RequestClientCert,
  1917  		},
  1918  		{
  1919  			name:               "RequestClientCert with certs",
  1920  			ClientAuth:         RequestClientCert,
  1921  			ClientCertificates: true,
  1922  		},
  1923  		{
  1924  			name:               "RequireAnyClientCert",
  1925  			ClientAuth:         RequireAnyClientCert,
  1926  			ClientCertificates: true,
  1927  		},
  1928  		{
  1929  			name:       "VerifyClientCertIfGiven with no certs",
  1930  			ClientAuth: VerifyClientCertIfGiven,
  1931  		},
  1932  		{
  1933  			name:               "VerifyClientCertIfGiven with certs",
  1934  			ClientAuth:         VerifyClientCertIfGiven,
  1935  			ClientCertificates: true,
  1936  		},
  1937  		{
  1938  			name:               "RequireAndVerifyClientCert",
  1939  			ClientAuth:         RequireAndVerifyClientCert,
  1940  			ClientCertificates: true,
  1941  		},
  1942  	}
  1943  
  1944  	for _, test := range tests {
  1945  		t.Run(test.name, func(t *testing.T) {
  1946  			t.Parallel()
  1947  
  1948  			var serverVerifyConnection, clientVerifyConnection bool
  1949  			var serverVerifyPeerCertificates, clientVerifyPeerCertificates bool
  1950  
  1951  			clientConfig := testConfigClient.Clone()
  1952  			clientConfig.MaxVersion = version
  1953  			clientConfig.MinVersion = version
  1954  			clientConfig.ClientSessionCache = NewLRUClientSessionCache(1)
  1955  			serverConfig := testConfigServer.Clone()
  1956  			serverConfig.MaxVersion = version
  1957  			serverConfig.MinVersion = version
  1958  
  1959  			clientConfig.VerifyConnection = func(cs ConnectionState) error {
  1960  				clientVerifyConnection = true
  1961  				return nil
  1962  			}
  1963  			clientConfig.VerifyPeerCertificate = func(rawCerts [][]byte, verifiedChains [][]*x509.Certificate) error {
  1964  				clientVerifyPeerCertificates = true
  1965  				return nil
  1966  			}
  1967  			serverConfig.VerifyConnection = func(cs ConnectionState) error {
  1968  				serverVerifyConnection = true
  1969  				return nil
  1970  			}
  1971  			serverConfig.VerifyPeerCertificate = func(rawCerts [][]byte, verifiedChains [][]*x509.Certificate) error {
  1972  				serverVerifyPeerCertificates = true
  1973  				return nil
  1974  			}
  1975  
  1976  			clientConfig.InsecureSkipVerify = test.InsecureSkipVerify
  1977  			serverConfig.ClientAuth = test.ClientAuth
  1978  			if !test.ClientCertificates {
  1979  				clientConfig.Certificates = nil
  1980  			}
  1981  
  1982  			if _, _, err := testHandshake(t, clientConfig, serverConfig); err != nil {
  1983  				t.Fatal(err)
  1984  			}
  1985  
  1986  			want := serverConfig.ClientAuth != NoClientCert
  1987  			if serverVerifyPeerCertificates != want {
  1988  				t.Errorf("VerifyPeerCertificates on the server: got %v, want %v",
  1989  					serverVerifyPeerCertificates, want)
  1990  			}
  1991  			if !clientVerifyPeerCertificates {
  1992  				t.Errorf("VerifyPeerCertificates not called on the client")
  1993  			}
  1994  			if !serverVerifyConnection {
  1995  				t.Error("VerifyConnection did not get called on the server")
  1996  			}
  1997  			if !clientVerifyConnection {
  1998  				t.Error("VerifyConnection did not get called on the client")
  1999  			}
  2000  
  2001  			serverVerifyPeerCertificates, clientVerifyPeerCertificates = false, false
  2002  			serverVerifyConnection, clientVerifyConnection = false, false
  2003  			cs, _, err := testHandshake(t, clientConfig, serverConfig)
  2004  			if err != nil {
  2005  				t.Fatal(err)
  2006  			}
  2007  			if !cs.DidResume {
  2008  				t.Error("expected resumption")
  2009  			}
  2010  
  2011  			if serverVerifyPeerCertificates {
  2012  				t.Error("VerifyPeerCertificates got called on the server on resumption")
  2013  			}
  2014  			if clientVerifyPeerCertificates {
  2015  				t.Error("VerifyPeerCertificates got called on the client on resumption")
  2016  			}
  2017  			if !serverVerifyConnection {
  2018  				t.Error("VerifyConnection did not get called on the server on resumption")
  2019  			}
  2020  			if !clientVerifyConnection {
  2021  				t.Error("VerifyConnection did not get called on the client on resumption")
  2022  			}
  2023  		})
  2024  	}
  2025  }
  2026  
  2027  func TestHandshakeMLKEM(t *testing.T) {
  2028  	if boring.Enabled && fips140tls.Required() {
  2029  		t.Skip("ML-KEM not supported in BoringCrypto FIPS mode")
  2030  	}
  2031  	defaultWithPQ := []CurveID{X25519MLKEM768, SecP256r1MLKEM768, SecP384r1MLKEM1024,
  2032  		X25519, CurveP256, CurveP384, CurveP521}
  2033  	defaultWithoutPQ := []CurveID{X25519, CurveP256, CurveP384, CurveP521}
  2034  	var tests = []struct {
  2035  		name           string
  2036  		clientConfig   func(*Config)
  2037  		serverConfig   func(*Config)
  2038  		preparation    func(*testing.T)
  2039  		expectClient   []CurveID
  2040  		expectSelected CurveID
  2041  		expectHRR      bool
  2042  	}{
  2043  		{
  2044  			name:           "Default",
  2045  			expectClient:   defaultWithPQ,
  2046  			expectSelected: X25519MLKEM768,
  2047  		},
  2048  		{
  2049  			name: "ClientCurvePreferences",
  2050  			clientConfig: func(config *Config) {
  2051  				config.CurvePreferences = []CurveID{X25519}
  2052  			},
  2053  			expectClient:   []CurveID{X25519},
  2054  			expectSelected: X25519,
  2055  		},
  2056  		{
  2057  			name: "ServerCurvePreferencesX25519",
  2058  			serverConfig: func(config *Config) {
  2059  				config.CurvePreferences = []CurveID{X25519}
  2060  			},
  2061  			expectClient:   defaultWithPQ,
  2062  			expectSelected: X25519,
  2063  		},
  2064  		{
  2065  			name: "ServerCurvePreferencesHRR",
  2066  			serverConfig: func(config *Config) {
  2067  				config.CurvePreferences = []CurveID{CurveP256}
  2068  			},
  2069  			expectClient:   defaultWithPQ,
  2070  			expectSelected: CurveP256,
  2071  			expectHRR:      true,
  2072  		},
  2073  		{
  2074  			name: "SecP256r1MLKEM768-Only",
  2075  			clientConfig: func(config *Config) {
  2076  				config.CurvePreferences = []CurveID{SecP256r1MLKEM768}
  2077  			},
  2078  			expectClient:   []CurveID{SecP256r1MLKEM768},
  2079  			expectSelected: SecP256r1MLKEM768,
  2080  		},
  2081  		{
  2082  			name: "SecP256r1MLKEM768-HRR",
  2083  			serverConfig: func(config *Config) {
  2084  				config.CurvePreferences = []CurveID{SecP256r1MLKEM768, CurveP256}
  2085  			},
  2086  			expectClient:   defaultWithPQ,
  2087  			expectSelected: SecP256r1MLKEM768,
  2088  			expectHRR:      true,
  2089  		},
  2090  		{
  2091  			name: "SecP384r1MLKEM1024",
  2092  			clientConfig: func(config *Config) {
  2093  				config.CurvePreferences = []CurveID{SecP384r1MLKEM1024, CurveP384}
  2094  			},
  2095  			expectClient:   []CurveID{SecP384r1MLKEM1024, CurveP384},
  2096  			expectSelected: SecP384r1MLKEM1024,
  2097  		},
  2098  		{
  2099  			name: "CurveP256NoHRR",
  2100  			clientConfig: func(config *Config) {
  2101  				config.CurvePreferences = []CurveID{SecP256r1MLKEM768, CurveP256}
  2102  			},
  2103  			serverConfig: func(config *Config) {
  2104  				config.CurvePreferences = []CurveID{CurveP256}
  2105  			},
  2106  			expectClient:   []CurveID{SecP256r1MLKEM768, CurveP256},
  2107  			expectSelected: CurveP256,
  2108  		},
  2109  		{
  2110  			name: "CurveP384HRR",
  2111  			clientConfig: func(config *Config) {
  2112  				config.CurvePreferences = []CurveID{SecP256r1MLKEM768, CurveP384}
  2113  			},
  2114  			serverConfig: func(config *Config) {
  2115  				config.CurvePreferences = []CurveID{CurveP384}
  2116  			},
  2117  			expectClient:   []CurveID{SecP256r1MLKEM768, CurveP384},
  2118  			expectSelected: CurveP384,
  2119  			expectHRR:      true,
  2120  		},
  2121  		{
  2122  			name: "ClientMLKEMOnly",
  2123  			clientConfig: func(config *Config) {
  2124  				config.CurvePreferences = []CurveID{X25519MLKEM768}
  2125  			},
  2126  			expectClient:   []CurveID{X25519MLKEM768},
  2127  			expectSelected: X25519MLKEM768,
  2128  		},
  2129  		{
  2130  			name: "ClientSortedCurvePreferences",
  2131  			clientConfig: func(config *Config) {
  2132  				config.CurvePreferences = []CurveID{CurveP256, X25519MLKEM768}
  2133  			},
  2134  			expectClient:   []CurveID{X25519MLKEM768, CurveP256},
  2135  			expectSelected: X25519MLKEM768,
  2136  		},
  2137  		{
  2138  			name: "ClientTLSv12",
  2139  			clientConfig: func(config *Config) {
  2140  				config.MaxVersion = VersionTLS12
  2141  			},
  2142  			expectClient:   defaultWithoutPQ,
  2143  			expectSelected: X25519,
  2144  		},
  2145  		{
  2146  			name: "ServerTLSv12",
  2147  			serverConfig: func(config *Config) {
  2148  				config.MaxVersion = VersionTLS12
  2149  			},
  2150  			expectClient:   defaultWithPQ,
  2151  			expectSelected: X25519,
  2152  		},
  2153  		{
  2154  			name: "GODEBUG tlsmlkem=0",
  2155  			preparation: func(t *testing.T) {
  2156  				testenv.SetGODEBUG(t, "tlsmlkem=0")
  2157  			},
  2158  			expectClient:   defaultWithoutPQ,
  2159  			expectSelected: X25519,
  2160  		},
  2161  		{
  2162  			name: "GODEBUG tlssecpmlkem=0",
  2163  			preparation: func(t *testing.T) {
  2164  				testenv.SetGODEBUG(t, "tlssecpmlkem=0")
  2165  			},
  2166  			expectClient:   []CurveID{X25519MLKEM768, X25519, CurveP256, CurveP384, CurveP521},
  2167  			expectSelected: X25519MLKEM768,
  2168  		},
  2169  		{
  2170  			name: "CurvePreferences override GODEBUG",
  2171  			preparation: func(t *testing.T) {
  2172  				testenv.SetGODEBUG(t, "tlsmlkem=0")
  2173  				testenv.SetGODEBUG(t, "tlssecpmlkem=0")
  2174  			},
  2175  			clientConfig: func(config *Config) {
  2176  				config.CurvePreferences = []CurveID{CurveP256, SecP256r1MLKEM768, MLKEM1024}
  2177  			},
  2178  			serverConfig: func(config *Config) {
  2179  				config.CurvePreferences = []CurveID{CurveP256, SecP256r1MLKEM768, MLKEM1024}
  2180  			},
  2181  			expectClient:   []CurveID{SecP256r1MLKEM768, MLKEM1024, CurveP256},
  2182  			expectSelected: SecP256r1MLKEM768,
  2183  		},
  2184  		{
  2185  			name: "ClientMLKEM1024Only",
  2186  			clientConfig: func(config *Config) {
  2187  				config.CurvePreferences = []CurveID{MLKEM1024}
  2188  			},
  2189  			serverConfig: func(config *Config) {
  2190  				config.CurvePreferences = append(defaultWithPQ, MLKEM1024)
  2191  			},
  2192  			expectClient:   []CurveID{MLKEM1024},
  2193  			expectSelected: MLKEM1024,
  2194  		},
  2195  		{
  2196  			name: "ServerMLKEM1024Only",
  2197  			clientConfig: func(config *Config) {
  2198  				config.CurvePreferences = append(defaultWithPQ, MLKEM1024)
  2199  			},
  2200  			serverConfig: func(config *Config) {
  2201  				config.CurvePreferences = []CurveID{MLKEM1024}
  2202  			},
  2203  			expectClient: []CurveID{X25519MLKEM768, SecP256r1MLKEM768, SecP384r1MLKEM1024,
  2204  				MLKEM1024, X25519, CurveP256, CurveP384, CurveP521},
  2205  			expectSelected: MLKEM1024,
  2206  			expectHRR:      true,
  2207  		},
  2208  		{
  2209  			name: "MLKEM1024NotPreferredOverHybrid",
  2210  			clientConfig: func(config *Config) {
  2211  				config.CurvePreferences = []CurveID{MLKEM1024, X25519MLKEM768}
  2212  			},
  2213  			serverConfig: func(config *Config) {
  2214  				config.CurvePreferences = []CurveID{MLKEM1024, X25519MLKEM768}
  2215  			},
  2216  			expectClient:   []CurveID{X25519MLKEM768, MLKEM1024},
  2217  			expectSelected: X25519MLKEM768,
  2218  		},
  2219  		{
  2220  			name: "MLKEM1024PreferredOverECC",
  2221  			clientConfig: func(config *Config) {
  2222  				config.CurvePreferences = []CurveID{X25519, MLKEM1024}
  2223  			},
  2224  			serverConfig: func(config *Config) {
  2225  				config.CurvePreferences = []CurveID{X25519, MLKEM1024}
  2226  			},
  2227  			expectClient:   []CurveID{MLKEM1024, X25519},
  2228  			expectSelected: MLKEM1024,
  2229  		},
  2230  	}
  2231  
  2232  	baseServerConfig := testConfigServer.Clone()
  2233  	baseClientConfig := testConfigClient.Clone()
  2234  	for _, test := range tests {
  2235  		t.Run(test.name, func(t *testing.T) {
  2236  			if fips140tls.Required() && test.expectSelected == X25519 {
  2237  				t.Skip("X25519 not supported in FIPS mode")
  2238  			}
  2239  			if test.preparation != nil {
  2240  				test.preparation(t)
  2241  			} else {
  2242  				t.Parallel()
  2243  			}
  2244  			serverConfig := baseServerConfig.Clone()
  2245  			if test.serverConfig != nil {
  2246  				test.serverConfig(serverConfig)
  2247  			}
  2248  			serverConfig.GetConfigForClient = func(hello *ClientHelloInfo) (*Config, error) {
  2249  				expectClient := slices.Clone(test.expectClient)
  2250  				expectClient = slices.DeleteFunc(expectClient, func(c CurveID) bool {
  2251  					return fips140tls.Required() && c == X25519
  2252  				})
  2253  				if !slices.Equal(hello.SupportedCurves, expectClient) {
  2254  					t.Errorf("got client curves %v, expected %v", hello.SupportedCurves, expectClient)
  2255  				}
  2256  				return nil, nil
  2257  			}
  2258  			clientConfig := baseClientConfig.Clone()
  2259  			if test.clientConfig != nil {
  2260  				test.clientConfig(clientConfig)
  2261  			}
  2262  			ss, cs, err := testHandshake(t, clientConfig, serverConfig)
  2263  			if err != nil {
  2264  				t.Fatal(err)
  2265  			}
  2266  			if ss.CurveID != test.expectSelected {
  2267  				t.Errorf("server selected curve %v, expected %v", ss.CurveID, test.expectSelected)
  2268  			}
  2269  			if cs.CurveID != test.expectSelected {
  2270  				t.Errorf("client selected curve %v, expected %v", cs.CurveID, test.expectSelected)
  2271  			}
  2272  			if test.expectHRR {
  2273  				if !ss.HelloRetryRequest {
  2274  					t.Error("server did not use HRR")
  2275  				}
  2276  				if !cs.HelloRetryRequest {
  2277  					t.Error("client did not use HRR")
  2278  				}
  2279  			} else {
  2280  				if ss.HelloRetryRequest {
  2281  					t.Error("server used HRR")
  2282  				}
  2283  				if cs.HelloRetryRequest {
  2284  					t.Error("client used HRR")
  2285  				}
  2286  			}
  2287  		})
  2288  	}
  2289  }
  2290  
  2291  func TestSupportedSignatureAlgorithmsCert(t *testing.T) {
  2292  	// Preserve the Go 1.26 list and order for middlebox compatibility.
  2293  	want := []SignatureScheme{
  2294  		PSSWithSHA256,
  2295  		ECDSAWithP256AndSHA256,
  2296  		Ed25519,
  2297  		PSSWithSHA384,
  2298  		PSSWithSHA512,
  2299  		PKCS1WithSHA256,
  2300  		PKCS1WithSHA384,
  2301  		PKCS1WithSHA512,
  2302  		ECDSAWithP384AndSHA384,
  2303  		ECDSAWithP521AndSHA512,
  2304  		PKCS1WithSHA1,
  2305  		ECDSAWithSHA1,
  2306  	}
  2307  	if fips140tls.Required() {
  2308  		want = slices.DeleteFunc(want, func(s SignatureScheme) bool {
  2309  			return !slices.Contains(allowedSignatureAlgorithmsFIPS, s)
  2310  		})
  2311  	}
  2312  	for _, tt := range []struct {
  2313  		minVers, maxVers uint16
  2314  	}{
  2315  		{VersionTLS12, VersionTLS12},
  2316  		{VersionTLS12, VersionTLS13},
  2317  		{VersionTLS13, VersionTLS13},
  2318  		{VersionTLS10, VersionTLS13},
  2319  	} {
  2320  		t.Run(VersionName(tt.minVers)+"-"+VersionName(tt.maxVers), func(t *testing.T) {
  2321  			got := supportedSignatureAlgorithmsCert(tt.minVers, tt.maxVers)
  2322  			if !slices.Equal(got, want) {
  2323  				t.Errorf("supportedSignatureAlgorithmsCert = %v, want %v", got, want)
  2324  			}
  2325  		})
  2326  	}
  2327  }
  2328  
  2329  // TestSupportedSignatureAlgorithmsMLDSAGating asserts the spec-mandated
  2330  // version-level gating of ML-DSA in signature_algorithms. Outside the FIPS 140-3
  2331  // v1.0.0 module, ML-DSA MUST NOT appear in the TLS 1.2 advertised list, MUST appear in
  2332  // the TLS 1.3 advertised list. Under FIPS 140-3 v1.0.0 (which doesn't include
  2333  // ML-DSA), ML-DSA MUST NOT be advertised in either extension.
  2334  // ML-DSA is omitted from signature_algorithms_cert for middlebox compatibility.
  2335  func TestSupportedSignatureAlgorithmsMLDSAGating(t *testing.T) {
  2336  	mldsaSchemes := []SignatureScheme{MLDSA44, MLDSA65, MLDSA87}
  2337  
  2338  	if fips140.Version() == "v1.0.0" {
  2339  		fullRange := supportedSignatureAlgorithms(VersionTLS10, VersionTLS13)
  2340  		certExt := supportedSignatureAlgorithmsCert(VersionTLS10, VersionTLS13)
  2341  		for _, s := range mldsaSchemes {
  2342  			if slices.Contains(fullRange, s) {
  2343  				t.Errorf("supportedSignatureAlgorithms contains %v under FIPS 140-3 v1.0.0", s)
  2344  			}
  2345  			if slices.Contains(certExt, s) {
  2346  				t.Errorf("supportedSignatureAlgorithmsCert contains %v under FIPS 140-3 v1.0.0", s)
  2347  			}
  2348  		}
  2349  		return
  2350  	}
  2351  
  2352  	tls12Only := supportedSignatureAlgorithms(VersionTLS12, VersionTLS12)
  2353  	tls12OnlyCert := supportedSignatureAlgorithmsCert(VersionTLS12, VersionTLS12)
  2354  	for _, s := range mldsaSchemes {
  2355  		if slices.Contains(tls12Only, s) {
  2356  			t.Errorf("supportedSignatureAlgorithms(TLS12, TLS12) contains %v; ML-DSA must not be advertised in TLS 1.2", s)
  2357  		}
  2358  		if slices.Contains(tls12OnlyCert, s) {
  2359  			t.Errorf("supportedSignatureAlgorithmsCert(TLS12, TLS12) contains %v; ML-DSA must not be advertised in TLS 1.2", s)
  2360  		}
  2361  	}
  2362  	tls13Only := supportedSignatureAlgorithms(VersionTLS13, VersionTLS13)
  2363  	tls12And13 := supportedSignatureAlgorithms(VersionTLS12, VersionTLS13)
  2364  	tls13OnlyCert := supportedSignatureAlgorithmsCert(VersionTLS13, VersionTLS13)
  2365  	for _, s := range mldsaSchemes {
  2366  		if !slices.Contains(tls13Only, s) {
  2367  			t.Errorf("supportedSignatureAlgorithms(TLS13, TLS13) is missing %v", s)
  2368  		}
  2369  		if !slices.Contains(tls12And13, s) {
  2370  			t.Errorf("supportedSignatureAlgorithms(TLS12, TLS13) is missing %v", s)
  2371  		}
  2372  		if slices.Contains(tls13OnlyCert, s) {
  2373  			t.Errorf("supportedSignatureAlgorithmsCert(TLS13, TLS13) contains %v", s)
  2374  		}
  2375  	}
  2376  }
  2377  
  2378  func TestHandshakeMLDSA(t *testing.T) {
  2379  	for _, tt := range []struct {
  2380  		name   string
  2381  		cert   Certificate
  2382  		client Certificate
  2383  	}{
  2384  		{"MLDSA44", testMLDSA44Cert, testClientMLDSA44Cert},
  2385  		{"MLDSA65", testMLDSA65Cert, testClientMLDSA65Cert},
  2386  		{"MLDSA87", testMLDSA87Cert, testClientMLDSA87Cert},
  2387  	} {
  2388  		t.Run(tt.name+"/ServerAuth", func(t *testing.T) {
  2389  			t.Parallel()
  2390  			serverConfig := testConfigServer.Clone()
  2391  			serverConfig.Certificates = []Certificate{tt.cert}
  2392  			clientConfig := testConfigClient.Clone()
  2393  			_, cs, err := testHandshake(t, clientConfig, serverConfig)
  2394  			if fips140.Version() == "v1.0.0" {
  2395  				if err == nil {
  2396  					t.Errorf("ML-DSA handshake unexpectedly succeeded with FIPS 140-3 module v1.0.0")
  2397  				}
  2398  				// Loaded certificate has cert bytes but no usable private key.
  2399  				if len(tt.cert.Certificate) == 0 {
  2400  					t.Errorf("certificate bytes missing")
  2401  				}
  2402  				if tt.cert.PrivateKey != nil {
  2403  					t.Errorf("PrivateKey = %T, want nil under v1.0.0", tt.cert.PrivateKey)
  2404  				}
  2405  				return
  2406  			}
  2407  			if err != nil {
  2408  				t.Fatalf("handshake: %v", err)
  2409  			}
  2410  			if _, ok := cs.PeerCertificates[0].PublicKey.(*mldsa.PublicKey); !ok {
  2411  				t.Errorf("server peer cert public key = %T, want *mldsa.PublicKey",
  2412  					cs.PeerCertificates[0].PublicKey)
  2413  			}
  2414  		})
  2415  		t.Run(tt.name+"/ClientAuth", func(t *testing.T) {
  2416  			t.Parallel()
  2417  			serverConfig := testConfigServer.Clone()
  2418  			serverConfig.Certificates = []Certificate{testECDSAP256Cert}
  2419  			serverConfig.ClientAuth = RequireAndVerifyClientCert
  2420  			clientConfig := testConfigClient.Clone()
  2421  			clientConfig.Certificates = []Certificate{tt.client}
  2422  			ss, _, err := testHandshake(t, clientConfig, serverConfig)
  2423  			if fips140.Version() == "v1.0.0" {
  2424  				if err == nil {
  2425  					t.Errorf("ML-DSA handshake unexpectedly succeeded with FIPS 140-3 module v1.0.0")
  2426  				}
  2427  				// Loaded certificate has cert bytes but no usable private key.
  2428  				if len(tt.client.Certificate) == 0 {
  2429  					t.Errorf("certificate bytes missing")
  2430  				}
  2431  				if tt.client.PrivateKey != nil {
  2432  					t.Errorf("PrivateKey = %T, want nil under v1.0.0", tt.client.PrivateKey)
  2433  				}
  2434  				return
  2435  			}
  2436  			if err != nil {
  2437  				t.Fatalf("handshake: %v", err)
  2438  			}
  2439  			if _, ok := ss.PeerCertificates[0].PublicKey.(*mldsa.PublicKey); !ok {
  2440  				t.Errorf("client peer cert public key = %T, want *mldsa.PublicKey",
  2441  					ss.PeerCertificates[0].PublicKey)
  2442  			}
  2443  		})
  2444  		t.Run(tt.name+"/MutualAuth", func(t *testing.T) {
  2445  			t.Parallel()
  2446  			serverConfig := testConfigServer.Clone()
  2447  			serverConfig.Certificates = []Certificate{tt.cert}
  2448  			serverConfig.ClientAuth = RequireAndVerifyClientCert
  2449  			clientConfig := testConfigClient.Clone()
  2450  			clientConfig.Certificates = []Certificate{tt.client}
  2451  			ss, cs, err := testHandshake(t, clientConfig, serverConfig)
  2452  			if fips140.Version() == "v1.0.0" {
  2453  				if err == nil {
  2454  					t.Errorf("ML-DSA handshake unexpectedly succeeded with FIPS 140-3 module v1.0.0")
  2455  				}
  2456  				return
  2457  			}
  2458  			if err != nil {
  2459  				t.Fatalf("handshake: %v", err)
  2460  			}
  2461  			if _, ok := cs.PeerCertificates[0].PublicKey.(*mldsa.PublicKey); !ok {
  2462  				t.Errorf("client-side peer cert public key = %T, want *mldsa.PublicKey",
  2463  					cs.PeerCertificates[0].PublicKey)
  2464  			}
  2465  			if _, ok := ss.PeerCertificates[0].PublicKey.(*mldsa.PublicKey); !ok {
  2466  				t.Errorf("server-side peer cert public key = %T, want *mldsa.PublicKey",
  2467  					ss.PeerCertificates[0].PublicKey)
  2468  			}
  2469  		})
  2470  		for _, v := range []uint16{VersionTLS10, VersionTLS12} {
  2471  			name := tt.name + "/RejectedVersion/" + VersionName(v)
  2472  			t.Run(name+"/Server", func(t *testing.T) {
  2473  				if v == VersionTLS10 {
  2474  					skipFIPS(t) // TLS 1.0 is not allowed in FIPS 140-3 mode.
  2475  				}
  2476  				cryptotest.MustMinimumFIPS140ModuleVersion(t, "v1.26.0")
  2477  				t.Parallel()
  2478  				serverConfig := testConfigServer.Clone()
  2479  				serverConfig.MinVersion = VersionTLS10
  2480  				serverConfig.Certificates = []Certificate{tt.cert}
  2481  				serverConfig.MaxVersion = v
  2482  				clientConfig := testConfigClient.Clone()
  2483  				clientConfig.MinVersion = VersionTLS10
  2484  				if _, _, err := testHandshake(t, clientConfig, serverConfig); err == nil {
  2485  					t.Fatal("expected handshake failure when ML-DSA is the only server cert and the negotiation is not TLS 1.3")
  2486  				} else if !strings.Contains(err.Error(), "ML-DSA") {
  2487  					t.Errorf("error message should mention ML-DSA, got %q", err)
  2488  				}
  2489  
  2490  				serverConfig.MaxVersion = 0
  2491  				clientConfig.MaxVersion = v
  2492  				if _, _, err := testHandshake(t, clientConfig, serverConfig); err == nil {
  2493  					t.Fatal("expected handshake failure when ML-DSA is the only server cert and the negotiation is not TLS 1.3")
  2494  				} else if !strings.Contains(err.Error(), "ML-DSA") {
  2495  					t.Errorf("error message should mention ML-DSA, got %q", err)
  2496  				}
  2497  			})
  2498  			t.Run(name+"/Client", func(t *testing.T) {
  2499  				cryptotest.MustMinimumFIPS140ModuleVersion(t, "v1.26.0")
  2500  				t.Parallel()
  2501  				serverConfig := testConfigServer.Clone()
  2502  				serverConfig.MinVersion = VersionTLS10
  2503  				serverConfig.ClientAuth = RequireAndVerifyClientCert
  2504  				clientConfig := testConfigClient.Clone()
  2505  				clientConfig.MinVersion = VersionTLS10
  2506  				clientConfig.Certificates = []Certificate{tt.client}
  2507  				clientConfig.MaxVersion = v
  2508  				if _, _, err := testHandshake(t, clientConfig, serverConfig); err == nil {
  2509  					t.Fatal("expected handshake failure when ML-DSA is the only client cert and the negotiation is not TLS 1.3")
  2510  				}
  2511  				// The error message on the client can't be helpful because we
  2512  				// don't know if the server requires a certificate until/unless
  2513  				// the server aborts later in the handshake, by which time we
  2514  				// lost track of which certificate we didn't offer and why.
  2515  
  2516  				clientConfig.MaxVersion = 0
  2517  				serverConfig.MaxVersion = v
  2518  				if _, _, err := testHandshake(t, clientConfig, serverConfig); err == nil {
  2519  					t.Fatal("expected handshake failure when ML-DSA is the only client cert and the negotiation is not TLS 1.3")
  2520  				}
  2521  			})
  2522  		}
  2523  		t.Run(tt.name+"/CorruptedSignature/Server", func(t *testing.T) {
  2524  			cryptotest.MustMinimumFIPS140ModuleVersion(t, "v1.26.0")
  2525  			t.Parallel()
  2526  			serverConfig := testConfigServer.Clone()
  2527  			serverConfig.Certificates = []Certificate{{
  2528  				Certificate: tt.cert.Certificate,
  2529  				PrivateKey:  bitFlippingSigner{tt.cert.PrivateKey.(crypto.Signer)},
  2530  			}}
  2531  			clientConfig := testConfigClient.Clone()
  2532  			_, _, err := testHandshake(t, clientConfig, serverConfig)
  2533  			if err == nil {
  2534  				t.Fatal("handshake unexpectedly succeeded with corrupted ML-DSA signature")
  2535  			}
  2536  			// The client returns the verification error; the server returns
  2537  			// "remote error: tls: decrypt_error" reflecting the alert.
  2538  			if !strings.Contains(err.Error(), "decrypt") &&
  2539  				!strings.Contains(err.Error(), "ML-DSA verification failure") {
  2540  				t.Errorf("error = %q; want one mentioning decrypt_error or ML-DSA verification", err)
  2541  			}
  2542  		})
  2543  		t.Run(tt.name+"/CorruptedSignature/Client", func(t *testing.T) {
  2544  			cryptotest.MustMinimumFIPS140ModuleVersion(t, "v1.26.0")
  2545  			t.Parallel()
  2546  			serverConfig := testConfigServer.Clone()
  2547  			serverConfig.ClientAuth = RequireAndVerifyClientCert
  2548  			clientConfig := testConfigClient.Clone()
  2549  			clientConfig.Certificates = []Certificate{{
  2550  				Certificate: tt.client.Certificate,
  2551  				PrivateKey:  bitFlippingSigner{tt.client.PrivateKey.(crypto.Signer)},
  2552  			}}
  2553  			_, _, err := testHandshake(t, clientConfig, serverConfig)
  2554  			if err == nil {
  2555  				t.Fatal("handshake unexpectedly succeeded with corrupted ML-DSA signature")
  2556  			}
  2557  			// The server returns the verification error; the client returns
  2558  			// "remote error: tls: decrypt_error" reflecting the alert.
  2559  			if !strings.Contains(err.Error(), "decrypt") &&
  2560  				!strings.Contains(err.Error(), "ML-DSA verification failure") {
  2561  				t.Errorf("error = %q; want one mentioning decrypt_error or ML-DSA verification", err)
  2562  			}
  2563  		})
  2564  	}
  2565  }
  2566  
  2567  func TestX509KeyPairPopulateCertificate(t *testing.T) {
  2568  	key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
  2569  	if err != nil {
  2570  		t.Fatal(err)
  2571  	}
  2572  	keyDER, err := x509.MarshalPKCS8PrivateKey(key)
  2573  	if err != nil {
  2574  		t.Fatal(err)
  2575  	}
  2576  	keyPEM := pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: keyDER})
  2577  	tmpl := &x509.Certificate{
  2578  		SerialNumber: big.NewInt(1),
  2579  		Subject:      pkix.Name{CommonName: "test"},
  2580  	}
  2581  	certDER, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, key.Public(), key)
  2582  	if err != nil {
  2583  		t.Fatal(err)
  2584  	}
  2585  	certPEM := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: certDER})
  2586  
  2587  	cert, err := X509KeyPair(certPEM, keyPEM)
  2588  	if err != nil {
  2589  		t.Fatal(err)
  2590  	}
  2591  	if cert.Leaf == nil {
  2592  		t.Fatal("Leaf should be populated")
  2593  	}
  2594  }
  2595  
  2596  func TestEarlyLargeCertMsg(t *testing.T) {
  2597  	client, server := localPipe(t)
  2598  
  2599  	go func() {
  2600  		if _, err := client.Write([]byte{byte(recordTypeHandshake), 3, 4, 0, 4, typeCertificate, 1, 255, 255}); err != nil {
  2601  			t.Log(err)
  2602  		}
  2603  	}()
  2604  
  2605  	expectedErr := "tls: handshake message of length 131071 bytes exceeds maximum of 65536 bytes"
  2606  	servConn := Server(server, testConfigServer.Clone())
  2607  	err := servConn.Handshake()
  2608  	if err == nil {
  2609  		t.Fatal("unexpected success")
  2610  	}
  2611  	if err.Error() != expectedErr {
  2612  		t.Fatalf("unexpected error: got %q, want %q", err, expectedErr)
  2613  	}
  2614  }
  2615  
  2616  func TestLargeCertMsg(t *testing.T) {
  2617  	k, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
  2618  	if err != nil {
  2619  		t.Fatal(err)
  2620  	}
  2621  	tmpl := &x509.Certificate{
  2622  		SerialNumber: big.NewInt(1),
  2623  		Subject:      pkix.Name{CommonName: "test"},
  2624  		ExtraExtensions: []pkix.Extension{
  2625  			{
  2626  				Id: asn1.ObjectIdentifier{1, 2, 3},
  2627  				// Ballast to inflate the certificate beyond the
  2628  				// regular handshake record size.
  2629  				Value: make([]byte, 65536),
  2630  			},
  2631  		},
  2632  	}
  2633  	cert, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, k.Public(), k)
  2634  	if err != nil {
  2635  		t.Fatal(err)
  2636  	}
  2637  
  2638  	clientConfig, serverConfig := testConfigClient.Clone(), testConfigServer.Clone()
  2639  	clientConfig.InsecureSkipVerify = true
  2640  	serverConfig.Certificates = []Certificate{
  2641  		{
  2642  			Certificate: [][]byte{cert},
  2643  			PrivateKey:  k,
  2644  		},
  2645  	}
  2646  	if _, _, err := testHandshake(t, clientConfig, serverConfig); err != nil {
  2647  		t.Fatalf("unexpected failure: %s", err)
  2648  	}
  2649  }
  2650  
  2651  func TestECH(t *testing.T) {
  2652  	k, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
  2653  	if err != nil {
  2654  		t.Fatal(err)
  2655  	}
  2656  	tmpl := &x509.Certificate{
  2657  		SerialNumber: big.NewInt(1),
  2658  		DNSNames:     []string{"public.example"},
  2659  		NotBefore:    time.Now().Add(-time.Hour),
  2660  		NotAfter:     time.Now().Add(time.Hour),
  2661  	}
  2662  	publicCertDER, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, k.Public(), k)
  2663  	if err != nil {
  2664  		t.Fatal(err)
  2665  	}
  2666  	publicCert, err := x509.ParseCertificate(publicCertDER)
  2667  	if err != nil {
  2668  		t.Fatal(err)
  2669  	}
  2670  	tmpl.DNSNames[0] = "secret.example"
  2671  	secretCertDER, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, k.Public(), k)
  2672  	if err != nil {
  2673  		t.Fatal(err)
  2674  	}
  2675  	secretCert, err := x509.ParseCertificate(secretCertDER)
  2676  	if err != nil {
  2677  		t.Fatal(err)
  2678  	}
  2679  
  2680  	marshalECHConfig := func(version uint16, id uint8, pubKey []byte, publicName string, maxNameLen uint8) []byte {
  2681  		builder := cryptobyte.NewBuilder(nil)
  2682  		builder.AddUint16(version)
  2683  		builder.AddUint16LengthPrefixed(func(builder *cryptobyte.Builder) {
  2684  			builder.AddUint8(id)
  2685  			builder.AddUint16(0x0020 /* DHKEM(X25519, HKDF-SHA256) */)
  2686  			builder.AddUint16LengthPrefixed(func(builder *cryptobyte.Builder) {
  2687  				builder.AddBytes(pubKey)
  2688  			})
  2689  			builder.AddUint16LengthPrefixed(func(builder *cryptobyte.Builder) {
  2690  				builder.AddUint16(0x0001 /* HKDF-SHA256 */)
  2691  				builder.AddUint16(0x0001 /* AES-128-GCM */)
  2692  			})
  2693  			builder.AddUint8(maxNameLen)
  2694  			builder.AddUint8LengthPrefixed(func(builder *cryptobyte.Builder) {
  2695  				builder.AddBytes([]byte(publicName))
  2696  			})
  2697  			builder.AddUint16(0) // extensions
  2698  		})
  2699  
  2700  		return builder.BytesOrPanic()
  2701  	}
  2702  
  2703  	echKey, err := ecdh.X25519().GenerateKey(rand.Reader)
  2704  	if err != nil {
  2705  		t.Fatal(err)
  2706  	}
  2707  
  2708  	echConfig := marshalECHConfig(extensionEncryptedClientHello, 123, echKey.PublicKey().Bytes(), "public.example", 32)
  2709  
  2710  	builder := cryptobyte.NewBuilder(nil)
  2711  	builder.AddUint16LengthPrefixed(func(builder *cryptobyte.Builder) {
  2712  		builder.AddBytes(echConfig)
  2713  	})
  2714  	echConfigList := builder.BytesOrPanic()
  2715  
  2716  	clientConfig, serverConfig := testConfigClient.Clone(), testConfigServer.Clone()
  2717  	clientConfig.Time = nil
  2718  	clientConfig.MinVersion = VersionTLS13
  2719  	clientConfig.ServerName = "secret.example"
  2720  	clientConfig.RootCAs = x509.NewCertPool()
  2721  	clientConfig.RootCAs.AddCert(secretCert)
  2722  	clientConfig.RootCAs.AddCert(publicCert)
  2723  	clientConfig.EncryptedClientHelloConfigList = echConfigList
  2724  	clientConfig.ClientSessionCache = NewLRUClientSessionCache(2)
  2725  	serverConfig.InsecureSkipVerify = false
  2726  	serverConfig.Time = nil
  2727  	serverConfig.MinVersion = VersionTLS13
  2728  	serverConfig.ServerName = "public.example"
  2729  	serverConfig.Certificates = []Certificate{
  2730  		{Certificate: [][]byte{publicCertDER}, PrivateKey: k},
  2731  		{Certificate: [][]byte{secretCertDER}, PrivateKey: k},
  2732  	}
  2733  	serverConfig.EncryptedClientHelloKeys = []EncryptedClientHelloKey{
  2734  		{Config: echConfig, PrivateKey: echKey.Bytes(), SendAsRetry: true},
  2735  	}
  2736  
  2737  	check := func() {
  2738  		ss, cs, err := testHandshake(t, clientConfig, serverConfig)
  2739  		if err != nil {
  2740  			t.Fatalf("unexpected failure: %s", err)
  2741  		}
  2742  		if !ss.ECHAccepted {
  2743  			t.Fatal("server ConnectionState shows ECH not accepted")
  2744  		}
  2745  		if !cs.ECHAccepted {
  2746  			t.Fatal("client ConnectionState shows ECH not accepted")
  2747  		}
  2748  		if cs.ServerName != "secret.example" || ss.ServerName != "secret.example" {
  2749  			t.Fatalf("unexpected ConnectionState.ServerName, want %q, got server:%q, client: %q", "secret.example", ss.ServerName, cs.ServerName)
  2750  		}
  2751  		if len(cs.VerifiedChains) != 1 {
  2752  			t.Fatal("unexpected number of certificate chains")
  2753  		}
  2754  		if len(cs.VerifiedChains[0]) != 1 {
  2755  			t.Fatal("unexpected number of certificates")
  2756  		}
  2757  		if !cs.VerifiedChains[0][0].Equal(secretCert) {
  2758  			t.Fatal("unexpected certificate")
  2759  		}
  2760  	}
  2761  
  2762  	check()
  2763  
  2764  	serverConfig.GetEncryptedClientHelloKeys = func(_ *ClientHelloInfo) ([]EncryptedClientHelloKey, error) {
  2765  		return []EncryptedClientHelloKey{{Config: echConfig, PrivateKey: echKey.Bytes(), SendAsRetry: true}}, nil
  2766  	}
  2767  	randKey, err := ecdh.X25519().GenerateKey(rand.Reader)
  2768  	if err != nil {
  2769  		t.Fatal(err)
  2770  	}
  2771  	randConfig := marshalECHConfig(extensionEncryptedClientHello, 32, randKey.PublicKey().Bytes(), "random.example", 32)
  2772  	serverConfig.EncryptedClientHelloKeys = []EncryptedClientHelloKey{
  2773  		{Config: randConfig, PrivateKey: randKey.Bytes(), SendAsRetry: true},
  2774  	}
  2775  
  2776  	check()
  2777  
  2778  	// A server configured with an unsupported-version ECHConfig ahead of a
  2779  	// usable one must skip the unusable entry (per RFC 9849 §4) and
  2780  	// trial-decrypt against the next key, rather than aborting the handshake
  2781  	// on the first entry.
  2782  	unsupportedKey, err := ecdh.X25519().GenerateKey(rand.Reader)
  2783  	if err != nil {
  2784  		t.Fatal(err)
  2785  	}
  2786  	unsupportedConfig := marshalECHConfig(0xbadd, 99, unsupportedKey.PublicKey().Bytes(), "public.example", 32)
  2787  	serverConfig.GetEncryptedClientHelloKeys = nil
  2788  	serverConfig.EncryptedClientHelloKeys = []EncryptedClientHelloKey{
  2789  		{Config: unsupportedConfig, PrivateKey: unsupportedKey.Bytes(), SendAsRetry: true},
  2790  		{Config: echConfig, PrivateKey: echKey.Bytes(), SendAsRetry: true},
  2791  	}
  2792  
  2793  	check()
  2794  }
  2795  
  2796  func TestMessageSigner(t *testing.T) {
  2797  	t.Run("TLSv10", func(t *testing.T) { testMessageSigner(t, VersionTLS10) })
  2798  	t.Run("TLSv12", func(t *testing.T) { testMessageSigner(t, VersionTLS12) })
  2799  	t.Run("TLSv13", func(t *testing.T) { testMessageSigner(t, VersionTLS13) })
  2800  }
  2801  
  2802  func testMessageSigner(t *testing.T, version uint16) {
  2803  	clientConfig, serverConfig := testConfigClient.Clone(), testConfigServer.Clone()
  2804  	serverConfig.ClientAuth = RequireAnyClientCert
  2805  	clientConfig.MinVersion = version
  2806  	clientConfig.MaxVersion = version
  2807  	serverConfig.MinVersion = version
  2808  	serverConfig.MaxVersion = version
  2809  	clientConfig.Certificates = []Certificate{{
  2810  		Certificate: testClientRSA2048Cert.Certificate,
  2811  		PrivateKey:  messageOnlySigner{testClientRSA2048Key},
  2812  	}}
  2813  	serverConfig.Certificates = []Certificate{{
  2814  		Certificate: testRSA2048Cert.Certificate,
  2815  		PrivateKey:  messageOnlySigner{testRSA2048Key},
  2816  	}}
  2817  
  2818  	_, _, err := testHandshake(t, clientConfig, serverConfig)
  2819  	if version < VersionTLS12 {
  2820  		if err == nil {
  2821  			t.Fatal("expected failure for TLS 1.0/1.1")
  2822  		}
  2823  	} else {
  2824  		if err != nil {
  2825  			t.Fatalf("unexpected failure: %s", err)
  2826  		}
  2827  	}
  2828  
  2829  	clientConfig.Certificates = []Certificate{{
  2830  		Certificate: testClientECDSAP256Cert.Certificate,
  2831  		PrivateKey:  messageOnlySigner{testClientECDSAP256Key},
  2832  	}}
  2833  	serverConfig.Certificates = []Certificate{{
  2834  		Certificate: testECDSAP256Cert.Certificate,
  2835  		PrivateKey:  messageOnlySigner{testECDSAP256Key},
  2836  	}}
  2837  
  2838  	_, _, err = testHandshake(t, clientConfig, serverConfig)
  2839  	if version < VersionTLS12 {
  2840  		if err == nil {
  2841  			t.Fatal("expected failure for TLS 1.0/1.1")
  2842  		}
  2843  	} else {
  2844  		if err != nil {
  2845  			t.Fatalf("unexpected failure: %s", err)
  2846  		}
  2847  	}
  2848  }
  2849  
  2850  type messageOnlySigner struct{ crypto.Signer }
  2851  
  2852  func (s messageOnlySigner) Public() crypto.PublicKey {
  2853  	return s.Signer.Public()
  2854  }
  2855  
  2856  func (s messageOnlySigner) Sign(rand io.Reader, msg []byte, opts crypto.SignerOpts) (signature []byte, err error) {
  2857  	return nil, errors.New("messageOnlySigner: Sign called")
  2858  }
  2859  
  2860  func (s messageOnlySigner) SignMessage(rand io.Reader, msg []byte, opts crypto.SignerOpts) (signature []byte, err error) {
  2861  	h := opts.HashFunc().New()
  2862  	h.Write(msg)
  2863  	digest := h.Sum(nil)
  2864  	return s.Signer.Sign(rand, digest, opts)
  2865  }
  2866  
  2867  // bitFlippingSigner wraps a crypto.Signer and flips a bit in the signature,
  2868  // producing an invalid signature.
  2869  type bitFlippingSigner struct{ crypto.Signer }
  2870  
  2871  func (s bitFlippingSigner) Public() crypto.PublicKey {
  2872  	return s.Signer.Public()
  2873  }
  2874  
  2875  func (s bitFlippingSigner) Sign(rand io.Reader, digest []byte, opts crypto.SignerOpts) ([]byte, error) {
  2876  	sig, err := s.Signer.Sign(rand, digest, opts)
  2877  	if err != nil {
  2878  		return nil, err
  2879  	}
  2880  	sig[0] ^= 1
  2881  	return sig, nil
  2882  }
  2883  
  2884  // TestInvalidHandshakeSignature tests that invalid handshake signatures are
  2885  // rejected for all TLS versions, for both server and client certificates,
  2886  // even when InsecureSkipVerify or RequireAnyClientCert are used (which disable
  2887  // certificate chain verification, but not signature verification).
  2888  func TestInvalidHandshakeSignature(t *testing.T) {
  2889  	t.Run("TLSv10", func(t *testing.T) {
  2890  		skipFIPS(t)
  2891  		testInvalidHandshakeSignature(t, VersionTLS10)
  2892  	})
  2893  	t.Run("TLSv12", func(t *testing.T) { testInvalidHandshakeSignature(t, VersionTLS12) })
  2894  	t.Run("TLSv13", func(t *testing.T) { testInvalidHandshakeSignature(t, VersionTLS13) })
  2895  }
  2896  
  2897  func testInvalidHandshakeSignature(t *testing.T, version uint16) {
  2898  	serverConfig := testConfigServer.Clone()
  2899  	serverConfig.MaxVersion = version
  2900  	serverConfig.MinVersion = version
  2901  	serverConfig.SessionTicketsDisabled = true
  2902  	clientConfig := testConfigClient.Clone()
  2903  	clientConfig.MaxVersion = version
  2904  	clientConfig.MinVersion = version
  2905  
  2906  	// Test that the server rejects invalid client certificate signatures,
  2907  	// even when RequireAnyClientCert is used.
  2908  	t.Run("ClientSignature", func(t *testing.T) {
  2909  		serverConfig := serverConfig.Clone()
  2910  		serverConfig.ClientAuth = RequireAnyClientCert
  2911  		clientConfig := clientConfig.Clone()
  2912  		clientConfig.Certificates = []Certificate{{
  2913  			Certificate: testClientECDSAP256Cert.Certificate,
  2914  			PrivateKey:  bitFlippingSigner{testClientECDSAP256Cert.PrivateKey.(crypto.Signer)},
  2915  		}}
  2916  
  2917  		clientErr, serverErr := testInvalidSignatureHandshake(t, clientConfig, serverConfig)
  2918  		if serverErr == nil {
  2919  			t.Fatalf("expected server to reject invalid client signature; client err = %v", clientErr)
  2920  		}
  2921  		if !strings.Contains(serverErr.Error(), "invalid signature") {
  2922  			t.Errorf("expected 'invalid signature' error, got: %v", serverErr)
  2923  		}
  2924  	})
  2925  
  2926  	// Test that the client rejects invalid server certificate signatures.
  2927  	t.Run("ServerSignature", func(t *testing.T) {
  2928  		serverConfig := serverConfig.Clone()
  2929  		serverConfig.Certificates = []Certificate{{
  2930  			Certificate: testRSA2048Cert.Certificate,
  2931  			PrivateKey:  bitFlippingSigner{testRSA2048Cert.PrivateKey.(crypto.Signer)},
  2932  		}}
  2933  
  2934  		clientErr, serverErr := testInvalidSignatureHandshake(t, clientConfig, serverConfig)
  2935  		if clientErr == nil {
  2936  			t.Fatalf("expected client to reject invalid server signature; server err = %v", serverErr)
  2937  		}
  2938  		if !strings.Contains(clientErr.Error(), "invalid signature") {
  2939  			t.Errorf("expected 'invalid signature' error, got: %v", clientErr)
  2940  		}
  2941  	})
  2942  
  2943  	// Test that InsecureSkipVerify doesn't disable server signature verification.
  2944  	t.Run("ServerSignature/InsecureSkipVerify", func(t *testing.T) {
  2945  		clientConfig := clientConfig.Clone()
  2946  		clientConfig.InsecureSkipVerify = true
  2947  		serverConfig := serverConfig.Clone()
  2948  		serverConfig.Certificates = []Certificate{{
  2949  			Certificate: testRSA2048Cert.Certificate,
  2950  			PrivateKey:  bitFlippingSigner{testRSA2048Cert.PrivateKey.(crypto.Signer)},
  2951  		}}
  2952  
  2953  		clientErr, serverErr := testInvalidSignatureHandshake(t, clientConfig, serverConfig)
  2954  		if clientErr == nil {
  2955  			t.Fatalf("expected client to reject invalid server signature despite InsecureSkipVerify; server err = %v", serverErr)
  2956  		}
  2957  		if !strings.Contains(clientErr.Error(), "invalid signature") {
  2958  			t.Errorf("expected 'invalid signature' error, got: %v", clientErr)
  2959  		}
  2960  	})
  2961  }
  2962  
  2963  // testInvalidSignatureHandshake performs a TLS handshake and returns the
  2964  // errors from both client and server. Unlike testHandshake, it doesn't try
  2965  // to exchange data after the handshake.
  2966  func testInvalidSignatureHandshake(t *testing.T, clientConfig, serverConfig *Config) (clientErr, serverErr error) {
  2967  	c, s := localPipe(t)
  2968  	done := make(chan struct{})
  2969  	go func() {
  2970  		defer close(done)
  2971  		clientErr = Client(c, clientConfig).Handshake()
  2972  		c.Close()
  2973  	}()
  2974  	serverErr = Server(s, serverConfig).Handshake()
  2975  	s.Close()
  2976  	<-done
  2977  	return
  2978  }
  2979  
  2980  func TestKeyLogWriterErr(t *testing.T) {
  2981  	var f *os.File // typed nil
  2982  	err := (&Config{KeyLogWriter: f}).writeKeyLog("CLIENT_RANDOM", make([]byte, 32), make([]byte, 48))
  2983  	if err == nil {
  2984  		t.Fatal("writeKeyLog: expected error, got nil")
  2985  	}
  2986  
  2987  	if want := os.ErrInvalid; !errors.Is(err, os.ErrInvalid) {
  2988  		t.Errorf("got %v, want %v", err, want)
  2989  	}
  2990  	if got, want := err.Error(), "KeyLogWriter"; !strings.Contains(got, want) {
  2991  		t.Errorf("got %q, want %q", got, want)
  2992  	}
  2993  }
  2994  
  2995  func testLocalCertificate(t *testing.T, version uint16, callback bool) {
  2996  	clientConfig, serverConfig := testConfigClient.Clone(), testConfigServer.Clone()
  2997  
  2998  	clientConfig.MinVersion, serverConfig.MinVersion = version, version
  2999  	clientConfig.MaxVersion, serverConfig.MaxVersion = version, version
  3000  	if version < VersionTLS12 {
  3001  		skipFIPS(t)
  3002  	}
  3003  	serverConfig.ClientAuth = RequestClientCert
  3004  
  3005  	serverCert, clientCert := testConfigServer.Certificates[0], testConfigClient.Certificates[0]
  3006  
  3007  	if callback {
  3008  		clientConfig.GetClientCertificate = func(_ *CertificateRequestInfo) (*Certificate, error) {
  3009  			return &Certificate{
  3010  				Certificate: clientCert.Certificate,
  3011  				PrivateKey:  clientCert.PrivateKey,
  3012  			}, nil
  3013  		}
  3014  		clientConfig.Certificates = nil
  3015  		serverConfig.GetCertificate = func(_ *ClientHelloInfo) (*Certificate, error) {
  3016  			return &Certificate{
  3017  				Certificate: serverCert.Certificate,
  3018  				PrivateKey:  serverCert.PrivateKey,
  3019  			}, nil
  3020  		}
  3021  		serverConfig.Certificates = nil
  3022  	}
  3023  
  3024  	ss, cs, err := testHandshake(t, clientConfig, serverConfig)
  3025  	if err != nil {
  3026  		t.Fatalf("unexpected failure: %s", err)
  3027  	}
  3028  
  3029  	if !slices.EqualFunc(ss.LocalCertificate, serverCert.Certificate, bytes.Equal) {
  3030  		t.Errorf("unexpected server local certificate: %x, want %x", ss.LocalCertificate, serverCert.Certificate)
  3031  	}
  3032  
  3033  	if !slices.EqualFunc(cs.LocalCertificate, clientCert.Certificate, bytes.Equal) {
  3034  		t.Errorf("unexpected client local certificate: %x, want %x", cs.LocalCertificate, clientCert.Certificate)
  3035  	}
  3036  }
  3037  
  3038  func TestLocalCertificate(t *testing.T) {
  3039  	for _, useCallback := range []bool{true, false} {
  3040  		name := "UseCertificates"
  3041  		if useCallback {
  3042  			name = "UseCallbacks"
  3043  		}
  3044  		t.Run(name, func(t *testing.T) {
  3045  			for _, v := range []uint16{VersionTLS10, VersionTLS11, VersionTLS12, VersionTLS13} {
  3046  				t.Run(VersionName(v), func(t *testing.T) {
  3047  					testLocalCertificate(t, v, useCallback)
  3048  				})
  3049  			}
  3050  		})
  3051  	}
  3052  }
  3053  
  3054  func testLocalCertificateResumption(t *testing.T, version uint16, callback bool) {
  3055  	clientConfig, serverConfig := testConfigClient.Clone(), testConfigServer.Clone()
  3056  
  3057  	clientConfig.MinVersion, serverConfig.MinVersion = version, version
  3058  	clientConfig.MaxVersion, serverConfig.MaxVersion = version, version
  3059  	if version < VersionTLS12 {
  3060  		skipFIPS(t)
  3061  	}
  3062  	clientConfig.ClientSessionCache = NewLRUClientSessionCache(1)
  3063  	serverConfig.ClientAuth = RequestClientCert
  3064  
  3065  	serverCert, clientCert := testConfigServer.Certificates[0], testConfigClient.Certificates[0]
  3066  
  3067  	if callback {
  3068  		clientConfig.GetClientCertificate = func(_ *CertificateRequestInfo) (*Certificate, error) {
  3069  			return &Certificate{
  3070  				Certificate: clientCert.Certificate,
  3071  				PrivateKey:  clientCert.PrivateKey,
  3072  			}, nil
  3073  		}
  3074  		clientConfig.Certificates = nil
  3075  		serverConfig.GetCertificate = func(_ *ClientHelloInfo) (*Certificate, error) {
  3076  			return &Certificate{
  3077  				Certificate: serverCert.Certificate,
  3078  				PrivateKey:  serverCert.PrivateKey,
  3079  			}, nil
  3080  		}
  3081  		serverConfig.Certificates = nil
  3082  	}
  3083  
  3084  	if _, _, err := testHandshake(t, clientConfig, serverConfig); err != nil {
  3085  		t.Fatalf("first handshake failed: %s", err)
  3086  	}
  3087  
  3088  	ss, cs, err := testHandshake(t, clientConfig, serverConfig)
  3089  	if err != nil {
  3090  		t.Fatalf("second handshake failed: %s", err)
  3091  	}
  3092  	if !ss.DidResume || !cs.DidResume {
  3093  		t.Fatalf("second handshake did not resume (server=%v client=%v)", ss.DidResume, cs.DidResume)
  3094  	}
  3095  	if ss.LocalCertificate != nil {
  3096  		t.Errorf("server LocalCertificate on resumed connection: got %x, want nil", ss.LocalCertificate)
  3097  	}
  3098  	if cs.LocalCertificate != nil {
  3099  		t.Errorf("client LocalCertificate on resumed connection: got %x, want nil", cs.LocalCertificate)
  3100  	}
  3101  }
  3102  
  3103  func TestLocalCertificateResumption(t *testing.T) {
  3104  	for _, useCallback := range []bool{true, false} {
  3105  		name := "UseCertificates"
  3106  		if useCallback {
  3107  			name = "UseCallbacks"
  3108  		}
  3109  		t.Run(name, func(t *testing.T) {
  3110  			for _, v := range []uint16{VersionTLS10, VersionTLS11, VersionTLS12, VersionTLS13} {
  3111  				t.Run(VersionName(v), func(t *testing.T) {
  3112  					testLocalCertificateResumption(t, v, useCallback)
  3113  				})
  3114  			}
  3115  		})
  3116  	}
  3117  }
  3118  

View as plain text