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

View as plain text