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  // TestSupportedSignatureAlgorithmsMLDSAGating asserts the spec-mandated
  2292  // version-level gating of ML-DSA. Outside the FIPS 140-3 v1.0.0 module:
  2293  // ML-DSA MUST NOT appear in the TLS 1.2 advertised list, MUST appear in
  2294  // the TLS 1.3 advertised list. Under FIPS 140-3 v1.0.0 (which doesn't include
  2295  // ML-DSA), ML-DSA MUST NOT be advertised in either extension.
  2296  func TestSupportedSignatureAlgorithmsMLDSAGating(t *testing.T) {
  2297  	mldsaSchemes := []SignatureScheme{MLDSA44, MLDSA65, MLDSA87}
  2298  
  2299  	if fips140.Version() == "v1.0.0" {
  2300  		fullRange := supportedSignatureAlgorithms(VersionTLS10, VersionTLS13)
  2301  		certExt := supportedSignatureAlgorithmsCert(VersionTLS10, VersionTLS13)
  2302  		for _, s := range mldsaSchemes {
  2303  			if slices.Contains(fullRange, s) {
  2304  				t.Errorf("supportedSignatureAlgorithms contains %v under FIPS 140-3 v1.0.0", s)
  2305  			}
  2306  			if slices.Contains(certExt, s) {
  2307  				t.Errorf("supportedSignatureAlgorithmsCert contains %v under FIPS 140-3 v1.0.0", s)
  2308  			}
  2309  		}
  2310  		return
  2311  	}
  2312  
  2313  	tls12Only := supportedSignatureAlgorithms(VersionTLS12, VersionTLS12)
  2314  	tls12OnlyCert := supportedSignatureAlgorithmsCert(VersionTLS12, VersionTLS12)
  2315  	for _, s := range mldsaSchemes {
  2316  		if slices.Contains(tls12Only, s) {
  2317  			t.Errorf("supportedSignatureAlgorithms(TLS12, TLS12) contains %v; ML-DSA must not be advertised in TLS 1.2", s)
  2318  		}
  2319  		if slices.Contains(tls12OnlyCert, s) {
  2320  			t.Errorf("supportedSignatureAlgorithmsCert(TLS12, TLS12) contains %v; ML-DSA must not be advertised in TLS 1.2", s)
  2321  		}
  2322  	}
  2323  	tls13Only := supportedSignatureAlgorithms(VersionTLS13, VersionTLS13)
  2324  	tls13OnlyCert := supportedSignatureAlgorithmsCert(VersionTLS13, VersionTLS13)
  2325  	for _, s := range mldsaSchemes {
  2326  		if !slices.Contains(tls13Only, s) {
  2327  			t.Errorf("supportedSignatureAlgorithms(TLS13, TLS13) is missing %v", s)
  2328  		}
  2329  		if !slices.Contains(tls13OnlyCert, s) {
  2330  			t.Errorf("supportedSignatureAlgorithmsCert(TLS13, TLS13) is missing %v", s)
  2331  		}
  2332  	}
  2333  }
  2334  
  2335  func TestHandshakeMLDSA(t *testing.T) {
  2336  	for _, tt := range []struct {
  2337  		name   string
  2338  		cert   Certificate
  2339  		client Certificate
  2340  	}{
  2341  		{"MLDSA44", testMLDSA44Cert, testClientMLDSA44Cert},
  2342  		{"MLDSA65", testMLDSA65Cert, testClientMLDSA65Cert},
  2343  		{"MLDSA87", testMLDSA87Cert, testClientMLDSA87Cert},
  2344  	} {
  2345  		t.Run(tt.name+"/ServerAuth", func(t *testing.T) {
  2346  			t.Parallel()
  2347  			serverConfig := testConfigServer.Clone()
  2348  			serverConfig.Certificates = []Certificate{tt.cert}
  2349  			clientConfig := testConfigClient.Clone()
  2350  			_, cs, err := testHandshake(t, clientConfig, serverConfig)
  2351  			if fips140.Version() == "v1.0.0" {
  2352  				if err == nil {
  2353  					t.Errorf("ML-DSA handshake unexpectedly succeeded with FIPS 140-3 module v1.0.0")
  2354  				}
  2355  				// Loaded certificate has cert bytes but no usable private key.
  2356  				if len(tt.cert.Certificate) == 0 {
  2357  					t.Errorf("certificate bytes missing")
  2358  				}
  2359  				if tt.cert.PrivateKey != nil {
  2360  					t.Errorf("PrivateKey = %T, want nil under v1.0.0", tt.cert.PrivateKey)
  2361  				}
  2362  				return
  2363  			}
  2364  			if err != nil {
  2365  				t.Fatalf("handshake: %v", err)
  2366  			}
  2367  			if _, ok := cs.PeerCertificates[0].PublicKey.(*mldsa.PublicKey); !ok {
  2368  				t.Errorf("server peer cert public key = %T, want *mldsa.PublicKey",
  2369  					cs.PeerCertificates[0].PublicKey)
  2370  			}
  2371  		})
  2372  		t.Run(tt.name+"/ClientAuth", func(t *testing.T) {
  2373  			t.Parallel()
  2374  			serverConfig := testConfigServer.Clone()
  2375  			serverConfig.Certificates = []Certificate{testECDSAP256Cert}
  2376  			serverConfig.ClientAuth = RequireAndVerifyClientCert
  2377  			clientConfig := testConfigClient.Clone()
  2378  			clientConfig.Certificates = []Certificate{tt.client}
  2379  			ss, _, err := testHandshake(t, clientConfig, serverConfig)
  2380  			if fips140.Version() == "v1.0.0" {
  2381  				if err == nil {
  2382  					t.Errorf("ML-DSA handshake unexpectedly succeeded with FIPS 140-3 module v1.0.0")
  2383  				}
  2384  				// Loaded certificate has cert bytes but no usable private key.
  2385  				if len(tt.client.Certificate) == 0 {
  2386  					t.Errorf("certificate bytes missing")
  2387  				}
  2388  				if tt.client.PrivateKey != nil {
  2389  					t.Errorf("PrivateKey = %T, want nil under v1.0.0", tt.client.PrivateKey)
  2390  				}
  2391  				return
  2392  			}
  2393  			if err != nil {
  2394  				t.Fatalf("handshake: %v", err)
  2395  			}
  2396  			if _, ok := ss.PeerCertificates[0].PublicKey.(*mldsa.PublicKey); !ok {
  2397  				t.Errorf("client peer cert public key = %T, want *mldsa.PublicKey",
  2398  					ss.PeerCertificates[0].PublicKey)
  2399  			}
  2400  		})
  2401  		t.Run(tt.name+"/MutualAuth", func(t *testing.T) {
  2402  			t.Parallel()
  2403  			serverConfig := testConfigServer.Clone()
  2404  			serverConfig.Certificates = []Certificate{tt.cert}
  2405  			serverConfig.ClientAuth = RequireAndVerifyClientCert
  2406  			clientConfig := testConfigClient.Clone()
  2407  			clientConfig.Certificates = []Certificate{tt.client}
  2408  			ss, cs, err := testHandshake(t, clientConfig, serverConfig)
  2409  			if fips140.Version() == "v1.0.0" {
  2410  				if err == nil {
  2411  					t.Errorf("ML-DSA handshake unexpectedly succeeded with FIPS 140-3 module v1.0.0")
  2412  				}
  2413  				return
  2414  			}
  2415  			if err != nil {
  2416  				t.Fatalf("handshake: %v", err)
  2417  			}
  2418  			if _, ok := cs.PeerCertificates[0].PublicKey.(*mldsa.PublicKey); !ok {
  2419  				t.Errorf("client-side peer cert public key = %T, want *mldsa.PublicKey",
  2420  					cs.PeerCertificates[0].PublicKey)
  2421  			}
  2422  			if _, ok := ss.PeerCertificates[0].PublicKey.(*mldsa.PublicKey); !ok {
  2423  				t.Errorf("server-side peer cert public key = %T, want *mldsa.PublicKey",
  2424  					ss.PeerCertificates[0].PublicKey)
  2425  			}
  2426  		})
  2427  		for _, v := range []uint16{VersionTLS10, VersionTLS12} {
  2428  			name := tt.name + "/RejectedVersion/" + VersionName(v)
  2429  			t.Run(name+"/Server", func(t *testing.T) {
  2430  				if v == VersionTLS10 {
  2431  					skipFIPS(t) // TLS 1.0 is not allowed in FIPS 140-3 mode.
  2432  				}
  2433  				cryptotest.MustMinimumFIPS140ModuleVersion(t, "v1.26.0")
  2434  				t.Parallel()
  2435  				serverConfig := testConfigServer.Clone()
  2436  				serverConfig.MinVersion = VersionTLS10
  2437  				serverConfig.Certificates = []Certificate{tt.cert}
  2438  				serverConfig.MaxVersion = v
  2439  				clientConfig := testConfigClient.Clone()
  2440  				clientConfig.MinVersion = VersionTLS10
  2441  				if _, _, err := testHandshake(t, clientConfig, serverConfig); err == nil {
  2442  					t.Fatal("expected handshake failure when ML-DSA is the only server cert and the negotiation is not TLS 1.3")
  2443  				} else if !strings.Contains(err.Error(), "ML-DSA") {
  2444  					t.Errorf("error message should mention ML-DSA, got %q", err)
  2445  				}
  2446  
  2447  				serverConfig.MaxVersion = 0
  2448  				clientConfig.MaxVersion = v
  2449  				if _, _, err := testHandshake(t, clientConfig, serverConfig); err == nil {
  2450  					t.Fatal("expected handshake failure when ML-DSA is the only server cert and the negotiation is not TLS 1.3")
  2451  				} else if !strings.Contains(err.Error(), "ML-DSA") {
  2452  					t.Errorf("error message should mention ML-DSA, got %q", err)
  2453  				}
  2454  			})
  2455  			t.Run(name+"/Client", func(t *testing.T) {
  2456  				cryptotest.MustMinimumFIPS140ModuleVersion(t, "v1.26.0")
  2457  				t.Parallel()
  2458  				serverConfig := testConfigServer.Clone()
  2459  				serverConfig.MinVersion = VersionTLS10
  2460  				serverConfig.ClientAuth = RequireAndVerifyClientCert
  2461  				clientConfig := testConfigClient.Clone()
  2462  				clientConfig.MinVersion = VersionTLS10
  2463  				clientConfig.Certificates = []Certificate{tt.client}
  2464  				clientConfig.MaxVersion = v
  2465  				if _, _, err := testHandshake(t, clientConfig, serverConfig); err == nil {
  2466  					t.Fatal("expected handshake failure when ML-DSA is the only client cert and the negotiation is not TLS 1.3")
  2467  				}
  2468  				// The error message on the client can't be helpful because we
  2469  				// don't know if the server requires a certificate until/unless
  2470  				// the server aborts later in the handshake, by which time we
  2471  				// lost track of which certificate we didn't offer and why.
  2472  
  2473  				clientConfig.MaxVersion = 0
  2474  				serverConfig.MaxVersion = v
  2475  				if _, _, err := testHandshake(t, clientConfig, serverConfig); err == nil {
  2476  					t.Fatal("expected handshake failure when ML-DSA is the only client cert and the negotiation is not TLS 1.3")
  2477  				}
  2478  			})
  2479  		}
  2480  		t.Run(tt.name+"/CorruptedSignature/Server", func(t *testing.T) {
  2481  			cryptotest.MustMinimumFIPS140ModuleVersion(t, "v1.26.0")
  2482  			t.Parallel()
  2483  			serverConfig := testConfigServer.Clone()
  2484  			serverConfig.Certificates = []Certificate{{
  2485  				Certificate: tt.cert.Certificate,
  2486  				PrivateKey:  bitFlippingSigner{tt.cert.PrivateKey.(crypto.Signer)},
  2487  			}}
  2488  			clientConfig := testConfigClient.Clone()
  2489  			_, _, err := testHandshake(t, clientConfig, serverConfig)
  2490  			if err == nil {
  2491  				t.Fatal("handshake unexpectedly succeeded with corrupted ML-DSA signature")
  2492  			}
  2493  			// The client returns the verification error; the server returns
  2494  			// "remote error: tls: decrypt_error" reflecting the alert.
  2495  			if !strings.Contains(err.Error(), "decrypt") &&
  2496  				!strings.Contains(err.Error(), "ML-DSA verification failure") {
  2497  				t.Errorf("error = %q; want one mentioning decrypt_error or ML-DSA verification", err)
  2498  			}
  2499  		})
  2500  		t.Run(tt.name+"/CorruptedSignature/Client", func(t *testing.T) {
  2501  			cryptotest.MustMinimumFIPS140ModuleVersion(t, "v1.26.0")
  2502  			t.Parallel()
  2503  			serverConfig := testConfigServer.Clone()
  2504  			serverConfig.ClientAuth = RequireAndVerifyClientCert
  2505  			clientConfig := testConfigClient.Clone()
  2506  			clientConfig.Certificates = []Certificate{{
  2507  				Certificate: tt.client.Certificate,
  2508  				PrivateKey:  bitFlippingSigner{tt.client.PrivateKey.(crypto.Signer)},
  2509  			}}
  2510  			_, _, err := testHandshake(t, clientConfig, serverConfig)
  2511  			if err == nil {
  2512  				t.Fatal("handshake unexpectedly succeeded with corrupted ML-DSA signature")
  2513  			}
  2514  			// The server returns the verification error; the client returns
  2515  			// "remote error: tls: decrypt_error" reflecting the alert.
  2516  			if !strings.Contains(err.Error(), "decrypt") &&
  2517  				!strings.Contains(err.Error(), "ML-DSA verification failure") {
  2518  				t.Errorf("error = %q; want one mentioning decrypt_error or ML-DSA verification", err)
  2519  			}
  2520  		})
  2521  	}
  2522  }
  2523  
  2524  func TestX509KeyPairPopulateCertificate(t *testing.T) {
  2525  	key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
  2526  	if err != nil {
  2527  		t.Fatal(err)
  2528  	}
  2529  	keyDER, err := x509.MarshalPKCS8PrivateKey(key)
  2530  	if err != nil {
  2531  		t.Fatal(err)
  2532  	}
  2533  	keyPEM := pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: keyDER})
  2534  	tmpl := &x509.Certificate{
  2535  		SerialNumber: big.NewInt(1),
  2536  		Subject:      pkix.Name{CommonName: "test"},
  2537  	}
  2538  	certDER, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, key.Public(), key)
  2539  	if err != nil {
  2540  		t.Fatal(err)
  2541  	}
  2542  	certPEM := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: certDER})
  2543  
  2544  	cert, err := X509KeyPair(certPEM, keyPEM)
  2545  	if err != nil {
  2546  		t.Fatal(err)
  2547  	}
  2548  	if cert.Leaf == nil {
  2549  		t.Fatal("Leaf should be populated")
  2550  	}
  2551  }
  2552  
  2553  func TestEarlyLargeCertMsg(t *testing.T) {
  2554  	client, server := localPipe(t)
  2555  
  2556  	go func() {
  2557  		if _, err := client.Write([]byte{byte(recordTypeHandshake), 3, 4, 0, 4, typeCertificate, 1, 255, 255}); err != nil {
  2558  			t.Log(err)
  2559  		}
  2560  	}()
  2561  
  2562  	expectedErr := "tls: handshake message of length 131071 bytes exceeds maximum of 65536 bytes"
  2563  	servConn := Server(server, testConfigServer.Clone())
  2564  	err := servConn.Handshake()
  2565  	if err == nil {
  2566  		t.Fatal("unexpected success")
  2567  	}
  2568  	if err.Error() != expectedErr {
  2569  		t.Fatalf("unexpected error: got %q, want %q", err, expectedErr)
  2570  	}
  2571  }
  2572  
  2573  func TestLargeCertMsg(t *testing.T) {
  2574  	k, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
  2575  	if err != nil {
  2576  		t.Fatal(err)
  2577  	}
  2578  	tmpl := &x509.Certificate{
  2579  		SerialNumber: big.NewInt(1),
  2580  		Subject:      pkix.Name{CommonName: "test"},
  2581  		ExtraExtensions: []pkix.Extension{
  2582  			{
  2583  				Id: asn1.ObjectIdentifier{1, 2, 3},
  2584  				// Ballast to inflate the certificate beyond the
  2585  				// regular handshake record size.
  2586  				Value: make([]byte, 65536),
  2587  			},
  2588  		},
  2589  	}
  2590  	cert, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, k.Public(), k)
  2591  	if err != nil {
  2592  		t.Fatal(err)
  2593  	}
  2594  
  2595  	clientConfig, serverConfig := testConfigClient.Clone(), testConfigServer.Clone()
  2596  	clientConfig.InsecureSkipVerify = true
  2597  	serverConfig.Certificates = []Certificate{
  2598  		{
  2599  			Certificate: [][]byte{cert},
  2600  			PrivateKey:  k,
  2601  		},
  2602  	}
  2603  	if _, _, err := testHandshake(t, clientConfig, serverConfig); err != nil {
  2604  		t.Fatalf("unexpected failure: %s", err)
  2605  	}
  2606  }
  2607  
  2608  func TestECH(t *testing.T) {
  2609  	k, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
  2610  	if err != nil {
  2611  		t.Fatal(err)
  2612  	}
  2613  	tmpl := &x509.Certificate{
  2614  		SerialNumber: big.NewInt(1),
  2615  		DNSNames:     []string{"public.example"},
  2616  		NotBefore:    time.Now().Add(-time.Hour),
  2617  		NotAfter:     time.Now().Add(time.Hour),
  2618  	}
  2619  	publicCertDER, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, k.Public(), k)
  2620  	if err != nil {
  2621  		t.Fatal(err)
  2622  	}
  2623  	publicCert, err := x509.ParseCertificate(publicCertDER)
  2624  	if err != nil {
  2625  		t.Fatal(err)
  2626  	}
  2627  	tmpl.DNSNames[0] = "secret.example"
  2628  	secretCertDER, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, k.Public(), k)
  2629  	if err != nil {
  2630  		t.Fatal(err)
  2631  	}
  2632  	secretCert, err := x509.ParseCertificate(secretCertDER)
  2633  	if err != nil {
  2634  		t.Fatal(err)
  2635  	}
  2636  
  2637  	marshalECHConfig := func(version uint16, id uint8, pubKey []byte, publicName string, maxNameLen uint8) []byte {
  2638  		builder := cryptobyte.NewBuilder(nil)
  2639  		builder.AddUint16(version)
  2640  		builder.AddUint16LengthPrefixed(func(builder *cryptobyte.Builder) {
  2641  			builder.AddUint8(id)
  2642  			builder.AddUint16(0x0020 /* DHKEM(X25519, HKDF-SHA256) */)
  2643  			builder.AddUint16LengthPrefixed(func(builder *cryptobyte.Builder) {
  2644  				builder.AddBytes(pubKey)
  2645  			})
  2646  			builder.AddUint16LengthPrefixed(func(builder *cryptobyte.Builder) {
  2647  				builder.AddUint16(0x0001 /* HKDF-SHA256 */)
  2648  				builder.AddUint16(0x0001 /* AES-128-GCM */)
  2649  			})
  2650  			builder.AddUint8(maxNameLen)
  2651  			builder.AddUint8LengthPrefixed(func(builder *cryptobyte.Builder) {
  2652  				builder.AddBytes([]byte(publicName))
  2653  			})
  2654  			builder.AddUint16(0) // extensions
  2655  		})
  2656  
  2657  		return builder.BytesOrPanic()
  2658  	}
  2659  
  2660  	echKey, err := ecdh.X25519().GenerateKey(rand.Reader)
  2661  	if err != nil {
  2662  		t.Fatal(err)
  2663  	}
  2664  
  2665  	echConfig := marshalECHConfig(extensionEncryptedClientHello, 123, echKey.PublicKey().Bytes(), "public.example", 32)
  2666  
  2667  	builder := cryptobyte.NewBuilder(nil)
  2668  	builder.AddUint16LengthPrefixed(func(builder *cryptobyte.Builder) {
  2669  		builder.AddBytes(echConfig)
  2670  	})
  2671  	echConfigList := builder.BytesOrPanic()
  2672  
  2673  	clientConfig, serverConfig := testConfigClient.Clone(), testConfigServer.Clone()
  2674  	clientConfig.Time = nil
  2675  	clientConfig.MinVersion = VersionTLS13
  2676  	clientConfig.ServerName = "secret.example"
  2677  	clientConfig.RootCAs = x509.NewCertPool()
  2678  	clientConfig.RootCAs.AddCert(secretCert)
  2679  	clientConfig.RootCAs.AddCert(publicCert)
  2680  	clientConfig.EncryptedClientHelloConfigList = echConfigList
  2681  	clientConfig.ClientSessionCache = NewLRUClientSessionCache(2)
  2682  	serverConfig.InsecureSkipVerify = false
  2683  	serverConfig.Time = nil
  2684  	serverConfig.MinVersion = VersionTLS13
  2685  	serverConfig.ServerName = "public.example"
  2686  	serverConfig.Certificates = []Certificate{
  2687  		{Certificate: [][]byte{publicCertDER}, PrivateKey: k},
  2688  		{Certificate: [][]byte{secretCertDER}, PrivateKey: k},
  2689  	}
  2690  	serverConfig.EncryptedClientHelloKeys = []EncryptedClientHelloKey{
  2691  		{Config: echConfig, PrivateKey: echKey.Bytes(), SendAsRetry: true},
  2692  	}
  2693  
  2694  	check := func() {
  2695  		ss, cs, err := testHandshake(t, clientConfig, serverConfig)
  2696  		if err != nil {
  2697  			t.Fatalf("unexpected failure: %s", err)
  2698  		}
  2699  		if !ss.ECHAccepted {
  2700  			t.Fatal("server ConnectionState shows ECH not accepted")
  2701  		}
  2702  		if !cs.ECHAccepted {
  2703  			t.Fatal("client ConnectionState shows ECH not accepted")
  2704  		}
  2705  		if cs.ServerName != "secret.example" || ss.ServerName != "secret.example" {
  2706  			t.Fatalf("unexpected ConnectionState.ServerName, want %q, got server:%q, client: %q", "secret.example", ss.ServerName, cs.ServerName)
  2707  		}
  2708  		if len(cs.VerifiedChains) != 1 {
  2709  			t.Fatal("unexpected number of certificate chains")
  2710  		}
  2711  		if len(cs.VerifiedChains[0]) != 1 {
  2712  			t.Fatal("unexpected number of certificates")
  2713  		}
  2714  		if !cs.VerifiedChains[0][0].Equal(secretCert) {
  2715  			t.Fatal("unexpected certificate")
  2716  		}
  2717  	}
  2718  
  2719  	check()
  2720  
  2721  	serverConfig.GetEncryptedClientHelloKeys = func(_ *ClientHelloInfo) ([]EncryptedClientHelloKey, error) {
  2722  		return []EncryptedClientHelloKey{{Config: echConfig, PrivateKey: echKey.Bytes(), SendAsRetry: true}}, nil
  2723  	}
  2724  	randKey, err := ecdh.X25519().GenerateKey(rand.Reader)
  2725  	if err != nil {
  2726  		t.Fatal(err)
  2727  	}
  2728  	randConfig := marshalECHConfig(extensionEncryptedClientHello, 32, randKey.PublicKey().Bytes(), "random.example", 32)
  2729  	serverConfig.EncryptedClientHelloKeys = []EncryptedClientHelloKey{
  2730  		{Config: randConfig, PrivateKey: randKey.Bytes(), SendAsRetry: true},
  2731  	}
  2732  
  2733  	check()
  2734  
  2735  	// A server configured with an unsupported-version ECHConfig ahead of a
  2736  	// usable one must skip the unusable entry (per RFC 9849 §4) and
  2737  	// trial-decrypt against the next key, rather than aborting the handshake
  2738  	// on the first entry.
  2739  	unsupportedKey, err := ecdh.X25519().GenerateKey(rand.Reader)
  2740  	if err != nil {
  2741  		t.Fatal(err)
  2742  	}
  2743  	unsupportedConfig := marshalECHConfig(0xbadd, 99, unsupportedKey.PublicKey().Bytes(), "public.example", 32)
  2744  	serverConfig.GetEncryptedClientHelloKeys = nil
  2745  	serverConfig.EncryptedClientHelloKeys = []EncryptedClientHelloKey{
  2746  		{Config: unsupportedConfig, PrivateKey: unsupportedKey.Bytes(), SendAsRetry: true},
  2747  		{Config: echConfig, PrivateKey: echKey.Bytes(), SendAsRetry: true},
  2748  	}
  2749  
  2750  	check()
  2751  }
  2752  
  2753  func TestMessageSigner(t *testing.T) {
  2754  	t.Run("TLSv10", func(t *testing.T) { testMessageSigner(t, VersionTLS10) })
  2755  	t.Run("TLSv12", func(t *testing.T) { testMessageSigner(t, VersionTLS12) })
  2756  	t.Run("TLSv13", func(t *testing.T) { testMessageSigner(t, VersionTLS13) })
  2757  }
  2758  
  2759  func testMessageSigner(t *testing.T, version uint16) {
  2760  	clientConfig, serverConfig := testConfigClient.Clone(), testConfigServer.Clone()
  2761  	serverConfig.ClientAuth = RequireAnyClientCert
  2762  	clientConfig.MinVersion = version
  2763  	clientConfig.MaxVersion = version
  2764  	serverConfig.MinVersion = version
  2765  	serverConfig.MaxVersion = version
  2766  	clientConfig.Certificates = []Certificate{{
  2767  		Certificate: testClientRSA2048Cert.Certificate,
  2768  		PrivateKey:  messageOnlySigner{testClientRSA2048Key},
  2769  	}}
  2770  	serverConfig.Certificates = []Certificate{{
  2771  		Certificate: testRSA2048Cert.Certificate,
  2772  		PrivateKey:  messageOnlySigner{testRSA2048Key},
  2773  	}}
  2774  
  2775  	_, _, err := testHandshake(t, clientConfig, serverConfig)
  2776  	if version < VersionTLS12 {
  2777  		if err == nil {
  2778  			t.Fatal("expected failure for TLS 1.0/1.1")
  2779  		}
  2780  	} else {
  2781  		if err != nil {
  2782  			t.Fatalf("unexpected failure: %s", err)
  2783  		}
  2784  	}
  2785  
  2786  	clientConfig.Certificates = []Certificate{{
  2787  		Certificate: testClientECDSAP256Cert.Certificate,
  2788  		PrivateKey:  messageOnlySigner{testClientECDSAP256Key},
  2789  	}}
  2790  	serverConfig.Certificates = []Certificate{{
  2791  		Certificate: testECDSAP256Cert.Certificate,
  2792  		PrivateKey:  messageOnlySigner{testECDSAP256Key},
  2793  	}}
  2794  
  2795  	_, _, err = testHandshake(t, clientConfig, serverConfig)
  2796  	if version < VersionTLS12 {
  2797  		if err == nil {
  2798  			t.Fatal("expected failure for TLS 1.0/1.1")
  2799  		}
  2800  	} else {
  2801  		if err != nil {
  2802  			t.Fatalf("unexpected failure: %s", err)
  2803  		}
  2804  	}
  2805  }
  2806  
  2807  type messageOnlySigner struct{ crypto.Signer }
  2808  
  2809  func (s messageOnlySigner) Public() crypto.PublicKey {
  2810  	return s.Signer.Public()
  2811  }
  2812  
  2813  func (s messageOnlySigner) Sign(rand io.Reader, msg []byte, opts crypto.SignerOpts) (signature []byte, err error) {
  2814  	return nil, errors.New("messageOnlySigner: Sign called")
  2815  }
  2816  
  2817  func (s messageOnlySigner) SignMessage(rand io.Reader, msg []byte, opts crypto.SignerOpts) (signature []byte, err error) {
  2818  	h := opts.HashFunc().New()
  2819  	h.Write(msg)
  2820  	digest := h.Sum(nil)
  2821  	return s.Signer.Sign(rand, digest, opts)
  2822  }
  2823  
  2824  // bitFlippingSigner wraps a crypto.Signer and flips a bit in the signature,
  2825  // producing an invalid signature.
  2826  type bitFlippingSigner struct{ crypto.Signer }
  2827  
  2828  func (s bitFlippingSigner) Public() crypto.PublicKey {
  2829  	return s.Signer.Public()
  2830  }
  2831  
  2832  func (s bitFlippingSigner) Sign(rand io.Reader, digest []byte, opts crypto.SignerOpts) ([]byte, error) {
  2833  	sig, err := s.Signer.Sign(rand, digest, opts)
  2834  	if err != nil {
  2835  		return nil, err
  2836  	}
  2837  	sig[0] ^= 1
  2838  	return sig, nil
  2839  }
  2840  
  2841  // TestInvalidHandshakeSignature tests that invalid handshake signatures are
  2842  // rejected for all TLS versions, for both server and client certificates,
  2843  // even when InsecureSkipVerify or RequireAnyClientCert are used (which disable
  2844  // certificate chain verification, but not signature verification).
  2845  func TestInvalidHandshakeSignature(t *testing.T) {
  2846  	t.Run("TLSv10", func(t *testing.T) {
  2847  		skipFIPS(t)
  2848  		testInvalidHandshakeSignature(t, VersionTLS10)
  2849  	})
  2850  	t.Run("TLSv12", func(t *testing.T) { testInvalidHandshakeSignature(t, VersionTLS12) })
  2851  	t.Run("TLSv13", func(t *testing.T) { testInvalidHandshakeSignature(t, VersionTLS13) })
  2852  }
  2853  
  2854  func testInvalidHandshakeSignature(t *testing.T, version uint16) {
  2855  	serverConfig := testConfigServer.Clone()
  2856  	serverConfig.MaxVersion = version
  2857  	serverConfig.MinVersion = version
  2858  	serverConfig.SessionTicketsDisabled = true
  2859  	clientConfig := testConfigClient.Clone()
  2860  	clientConfig.MaxVersion = version
  2861  	clientConfig.MinVersion = version
  2862  
  2863  	// Test that the server rejects invalid client certificate signatures,
  2864  	// even when RequireAnyClientCert is used.
  2865  	t.Run("ClientSignature", func(t *testing.T) {
  2866  		serverConfig := serverConfig.Clone()
  2867  		serverConfig.ClientAuth = RequireAnyClientCert
  2868  		clientConfig := clientConfig.Clone()
  2869  		clientConfig.Certificates = []Certificate{{
  2870  			Certificate: testClientECDSAP256Cert.Certificate,
  2871  			PrivateKey:  bitFlippingSigner{testClientECDSAP256Cert.PrivateKey.(crypto.Signer)},
  2872  		}}
  2873  
  2874  		clientErr, serverErr := testInvalidSignatureHandshake(t, clientConfig, serverConfig)
  2875  		if serverErr == nil {
  2876  			t.Fatalf("expected server to reject invalid client signature; client err = %v", clientErr)
  2877  		}
  2878  		if !strings.Contains(serverErr.Error(), "invalid signature") {
  2879  			t.Errorf("expected 'invalid signature' error, got: %v", serverErr)
  2880  		}
  2881  	})
  2882  
  2883  	// Test that the client rejects invalid server certificate signatures.
  2884  	t.Run("ServerSignature", func(t *testing.T) {
  2885  		serverConfig := serverConfig.Clone()
  2886  		serverConfig.Certificates = []Certificate{{
  2887  			Certificate: testRSA2048Cert.Certificate,
  2888  			PrivateKey:  bitFlippingSigner{testRSA2048Cert.PrivateKey.(crypto.Signer)},
  2889  		}}
  2890  
  2891  		clientErr, serverErr := testInvalidSignatureHandshake(t, clientConfig, serverConfig)
  2892  		if clientErr == nil {
  2893  			t.Fatalf("expected client to reject invalid server signature; server err = %v", serverErr)
  2894  		}
  2895  		if !strings.Contains(clientErr.Error(), "invalid signature") {
  2896  			t.Errorf("expected 'invalid signature' error, got: %v", clientErr)
  2897  		}
  2898  	})
  2899  
  2900  	// Test that InsecureSkipVerify doesn't disable server signature verification.
  2901  	t.Run("ServerSignature/InsecureSkipVerify", func(t *testing.T) {
  2902  		clientConfig := clientConfig.Clone()
  2903  		clientConfig.InsecureSkipVerify = true
  2904  		serverConfig := serverConfig.Clone()
  2905  		serverConfig.Certificates = []Certificate{{
  2906  			Certificate: testRSA2048Cert.Certificate,
  2907  			PrivateKey:  bitFlippingSigner{testRSA2048Cert.PrivateKey.(crypto.Signer)},
  2908  		}}
  2909  
  2910  		clientErr, serverErr := testInvalidSignatureHandshake(t, clientConfig, serverConfig)
  2911  		if clientErr == nil {
  2912  			t.Fatalf("expected client to reject invalid server signature despite InsecureSkipVerify; server err = %v", serverErr)
  2913  		}
  2914  		if !strings.Contains(clientErr.Error(), "invalid signature") {
  2915  			t.Errorf("expected 'invalid signature' error, got: %v", clientErr)
  2916  		}
  2917  	})
  2918  }
  2919  
  2920  // testInvalidSignatureHandshake performs a TLS handshake and returns the
  2921  // errors from both client and server. Unlike testHandshake, it doesn't try
  2922  // to exchange data after the handshake.
  2923  func testInvalidSignatureHandshake(t *testing.T, clientConfig, serverConfig *Config) (clientErr, serverErr error) {
  2924  	c, s := localPipe(t)
  2925  	done := make(chan struct{})
  2926  	go func() {
  2927  		defer close(done)
  2928  		clientErr = Client(c, clientConfig).Handshake()
  2929  		c.Close()
  2930  	}()
  2931  	serverErr = Server(s, serverConfig).Handshake()
  2932  	s.Close()
  2933  	<-done
  2934  	return
  2935  }
  2936  
  2937  func TestKeyLogWriterErr(t *testing.T) {
  2938  	var f *os.File // typed nil
  2939  	err := (&Config{KeyLogWriter: f}).writeKeyLog("CLIENT_RANDOM", make([]byte, 32), make([]byte, 48))
  2940  	if err == nil {
  2941  		t.Fatal("writeKeyLog: expected error, got nil")
  2942  	}
  2943  
  2944  	if want := os.ErrInvalid; !errors.Is(err, os.ErrInvalid) {
  2945  		t.Errorf("got %v, want %v", err, want)
  2946  	}
  2947  	if got, want := err.Error(), "KeyLogWriter"; !strings.Contains(got, want) {
  2948  		t.Errorf("got %q, want %q", got, want)
  2949  	}
  2950  }
  2951  
  2952  func testLocalCertificate(t *testing.T, version uint16, callback bool) {
  2953  	clientConfig, serverConfig := testConfigClient.Clone(), testConfigServer.Clone()
  2954  
  2955  	clientConfig.MinVersion, serverConfig.MinVersion = version, version
  2956  	clientConfig.MaxVersion, serverConfig.MaxVersion = version, version
  2957  	if version < VersionTLS12 {
  2958  		skipFIPS(t)
  2959  	}
  2960  	serverConfig.ClientAuth = RequestClientCert
  2961  
  2962  	serverCert, clientCert := testConfigServer.Certificates[0], testConfigClient.Certificates[0]
  2963  
  2964  	if callback {
  2965  		clientConfig.GetClientCertificate = func(_ *CertificateRequestInfo) (*Certificate, error) {
  2966  			return &Certificate{
  2967  				Certificate: clientCert.Certificate,
  2968  				PrivateKey:  clientCert.PrivateKey,
  2969  			}, nil
  2970  		}
  2971  		clientConfig.Certificates = nil
  2972  		serverConfig.GetCertificate = func(_ *ClientHelloInfo) (*Certificate, error) {
  2973  			return &Certificate{
  2974  				Certificate: serverCert.Certificate,
  2975  				PrivateKey:  serverCert.PrivateKey,
  2976  			}, nil
  2977  		}
  2978  		serverConfig.Certificates = nil
  2979  	}
  2980  
  2981  	ss, cs, err := testHandshake(t, clientConfig, serverConfig)
  2982  	if err != nil {
  2983  		t.Fatalf("unexpected failure: %s", err)
  2984  	}
  2985  
  2986  	if !slices.EqualFunc(ss.LocalCertificate, serverCert.Certificate, bytes.Equal) {
  2987  		t.Errorf("unexpected server local certificate: %x, want %x", ss.LocalCertificate, serverCert.Certificate)
  2988  	}
  2989  
  2990  	if !slices.EqualFunc(cs.LocalCertificate, clientCert.Certificate, bytes.Equal) {
  2991  		t.Errorf("unexpected client local certificate: %x, want %x", cs.LocalCertificate, clientCert.Certificate)
  2992  	}
  2993  }
  2994  
  2995  func TestLocalCertificate(t *testing.T) {
  2996  	for _, useCallback := range []bool{true, false} {
  2997  		name := "UseCertificates"
  2998  		if useCallback {
  2999  			name = "UseCallbacks"
  3000  		}
  3001  		t.Run(name, func(t *testing.T) {
  3002  			for _, v := range []uint16{VersionTLS10, VersionTLS11, VersionTLS12, VersionTLS13} {
  3003  				t.Run(VersionName(v), func(t *testing.T) {
  3004  					testLocalCertificate(t, v, useCallback)
  3005  				})
  3006  			}
  3007  		})
  3008  	}
  3009  }
  3010  
  3011  func testLocalCertificateResumption(t *testing.T, version uint16, callback bool) {
  3012  	clientConfig, serverConfig := testConfigClient.Clone(), testConfigServer.Clone()
  3013  
  3014  	clientConfig.MinVersion, serverConfig.MinVersion = version, version
  3015  	clientConfig.MaxVersion, serverConfig.MaxVersion = version, version
  3016  	if version < VersionTLS12 {
  3017  		skipFIPS(t)
  3018  	}
  3019  	clientConfig.ClientSessionCache = NewLRUClientSessionCache(1)
  3020  	serverConfig.ClientAuth = RequestClientCert
  3021  
  3022  	serverCert, clientCert := testConfigServer.Certificates[0], testConfigClient.Certificates[0]
  3023  
  3024  	if callback {
  3025  		clientConfig.GetClientCertificate = func(_ *CertificateRequestInfo) (*Certificate, error) {
  3026  			return &Certificate{
  3027  				Certificate: clientCert.Certificate,
  3028  				PrivateKey:  clientCert.PrivateKey,
  3029  			}, nil
  3030  		}
  3031  		clientConfig.Certificates = nil
  3032  		serverConfig.GetCertificate = func(_ *ClientHelloInfo) (*Certificate, error) {
  3033  			return &Certificate{
  3034  				Certificate: serverCert.Certificate,
  3035  				PrivateKey:  serverCert.PrivateKey,
  3036  			}, nil
  3037  		}
  3038  		serverConfig.Certificates = nil
  3039  	}
  3040  
  3041  	if _, _, err := testHandshake(t, clientConfig, serverConfig); err != nil {
  3042  		t.Fatalf("first handshake failed: %s", err)
  3043  	}
  3044  
  3045  	ss, cs, err := testHandshake(t, clientConfig, serverConfig)
  3046  	if err != nil {
  3047  		t.Fatalf("second handshake failed: %s", err)
  3048  	}
  3049  	if !ss.DidResume || !cs.DidResume {
  3050  		t.Fatalf("second handshake did not resume (server=%v client=%v)", ss.DidResume, cs.DidResume)
  3051  	}
  3052  	if ss.LocalCertificate != nil {
  3053  		t.Errorf("server LocalCertificate on resumed connection: got %x, want nil", ss.LocalCertificate)
  3054  	}
  3055  	if cs.LocalCertificate != nil {
  3056  		t.Errorf("client LocalCertificate on resumed connection: got %x, want nil", cs.LocalCertificate)
  3057  	}
  3058  }
  3059  
  3060  func TestLocalCertificateResumption(t *testing.T) {
  3061  	for _, useCallback := range []bool{true, false} {
  3062  		name := "UseCertificates"
  3063  		if useCallback {
  3064  			name = "UseCallbacks"
  3065  		}
  3066  		t.Run(name, func(t *testing.T) {
  3067  			for _, v := range []uint16{VersionTLS10, VersionTLS11, VersionTLS12, VersionTLS13} {
  3068  				t.Run(VersionName(v), func(t *testing.T) {
  3069  					testLocalCertificateResumption(t, v, useCallback)
  3070  				})
  3071  			}
  3072  		})
  3073  	}
  3074  }
  3075  

View as plain text