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/internal/hpke"
    15  	"crypto/rand"
    16  	"crypto/tls/internal/fips140tls"
    17  	"crypto/x509"
    18  	"crypto/x509/pkix"
    19  	"encoding/asn1"
    20  	"encoding/json"
    21  	"encoding/pem"
    22  	"errors"
    23  	"fmt"
    24  	"internal/testenv"
    25  	"io"
    26  	"math"
    27  	"math/big"
    28  	"net"
    29  	"os"
    30  	"reflect"
    31  	"slices"
    32  	"strings"
    33  	"testing"
    34  	"time"
    35  
    36  	"golang.org/x/crypto/cryptobyte"
    37  )
    38  
    39  var rsaCertPEM = `-----BEGIN CERTIFICATE-----
    40  MIIB0zCCAX2gAwIBAgIJAI/M7BYjwB+uMA0GCSqGSIb3DQEBBQUAMEUxCzAJBgNV
    41  BAYTAkFVMRMwEQYDVQQIDApTb21lLVN0YXRlMSEwHwYDVQQKDBhJbnRlcm5ldCBX
    42  aWRnaXRzIFB0eSBMdGQwHhcNMTIwOTEyMjE1MjAyWhcNMTUwOTEyMjE1MjAyWjBF
    43  MQswCQYDVQQGEwJBVTETMBEGA1UECAwKU29tZS1TdGF0ZTEhMB8GA1UECgwYSW50
    44  ZXJuZXQgV2lkZ2l0cyBQdHkgTHRkMFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBANLJ
    45  hPHhITqQbPklG3ibCVxwGMRfp/v4XqhfdQHdcVfHap6NQ5Wok/4xIA+ui35/MmNa
    46  rtNuC+BdZ1tMuVCPFZcCAwEAAaNQME4wHQYDVR0OBBYEFJvKs8RfJaXTH08W+SGv
    47  zQyKn0H8MB8GA1UdIwQYMBaAFJvKs8RfJaXTH08W+SGvzQyKn0H8MAwGA1UdEwQF
    48  MAMBAf8wDQYJKoZIhvcNAQEFBQADQQBJlffJHybjDGxRMqaRmDhX0+6v02TUKZsW
    49  r5QuVbpQhH6u+0UgcW0jp9QwpxoPTLTWGXEWBBBurxFwiCBhkQ+V
    50  -----END CERTIFICATE-----
    51  `
    52  
    53  var rsaKeyPEM = testingKey(`-----BEGIN RSA TESTING KEY-----
    54  MIIBOwIBAAJBANLJhPHhITqQbPklG3ibCVxwGMRfp/v4XqhfdQHdcVfHap6NQ5Wo
    55  k/4xIA+ui35/MmNartNuC+BdZ1tMuVCPFZcCAwEAAQJAEJ2N+zsR0Xn8/Q6twa4G
    56  6OB1M1WO+k+ztnX/1SvNeWu8D6GImtupLTYgjZcHufykj09jiHmjHx8u8ZZB/o1N
    57  MQIhAPW+eyZo7ay3lMz1V01WVjNKK9QSn1MJlb06h/LuYv9FAiEA25WPedKgVyCW
    58  SmUwbPw8fnTcpqDWE3yTO3vKcebqMSsCIBF3UmVue8YU3jybC3NxuXq3wNm34R8T
    59  xVLHwDXh/6NJAiEAl2oHGGLz64BuAfjKrqwz7qMYr9HCLIe/YsoWq/olzScCIQDi
    60  D2lWusoe2/nEqfDVVWGWlyJ7yOmqaVm/iNUN9B2N2g==
    61  -----END RSA TESTING KEY-----
    62  `)
    63  
    64  // keyPEM is the same as rsaKeyPEM, but declares itself as just
    65  // "PRIVATE KEY", not "RSA PRIVATE KEY".  https://golang.org/issue/4477
    66  var keyPEM = testingKey(`-----BEGIN TESTING KEY-----
    67  MIIBOwIBAAJBANLJhPHhITqQbPklG3ibCVxwGMRfp/v4XqhfdQHdcVfHap6NQ5Wo
    68  k/4xIA+ui35/MmNartNuC+BdZ1tMuVCPFZcCAwEAAQJAEJ2N+zsR0Xn8/Q6twa4G
    69  6OB1M1WO+k+ztnX/1SvNeWu8D6GImtupLTYgjZcHufykj09jiHmjHx8u8ZZB/o1N
    70  MQIhAPW+eyZo7ay3lMz1V01WVjNKK9QSn1MJlb06h/LuYv9FAiEA25WPedKgVyCW
    71  SmUwbPw8fnTcpqDWE3yTO3vKcebqMSsCIBF3UmVue8YU3jybC3NxuXq3wNm34R8T
    72  xVLHwDXh/6NJAiEAl2oHGGLz64BuAfjKrqwz7qMYr9HCLIe/YsoWq/olzScCIQDi
    73  D2lWusoe2/nEqfDVVWGWlyJ7yOmqaVm/iNUN9B2N2g==
    74  -----END TESTING KEY-----
    75  `)
    76  
    77  var ecdsaCertPEM = `-----BEGIN CERTIFICATE-----
    78  MIIB/jCCAWICCQDscdUxw16XFDAJBgcqhkjOPQQBMEUxCzAJBgNVBAYTAkFVMRMw
    79  EQYDVQQIEwpTb21lLVN0YXRlMSEwHwYDVQQKExhJbnRlcm5ldCBXaWRnaXRzIFB0
    80  eSBMdGQwHhcNMTIxMTE0MTI0MDQ4WhcNMTUxMTE0MTI0MDQ4WjBFMQswCQYDVQQG
    81  EwJBVTETMBEGA1UECBMKU29tZS1TdGF0ZTEhMB8GA1UEChMYSW50ZXJuZXQgV2lk
    82  Z2l0cyBQdHkgTHRkMIGbMBAGByqGSM49AgEGBSuBBAAjA4GGAAQBY9+my9OoeSUR
    83  lDQdV/x8LsOuLilthhiS1Tz4aGDHIPwC1mlvnf7fg5lecYpMCrLLhauAc1UJXcgl
    84  01xoLuzgtAEAgv2P/jgytzRSpUYvgLBt1UA0leLYBy6mQQbrNEuqT3INapKIcUv8
    85  XxYP0xMEUksLPq6Ca+CRSqTtrd/23uTnapkwCQYHKoZIzj0EAQOBigAwgYYCQXJo
    86  A7Sl2nLVf+4Iu/tAX/IF4MavARKC4PPHK3zfuGfPR3oCCcsAoz3kAzOeijvd0iXb
    87  H5jBImIxPL4WxQNiBTexAkF8D1EtpYuWdlVQ80/h/f4pBcGiXPqX5h2PQSQY7hP1
    88  +jwM1FGS4fREIOvlBYr/SzzQRtwrvrzGYxDEDbsC0ZGRnA==
    89  -----END CERTIFICATE-----
    90  `
    91  
    92  var ecdsaKeyPEM = testingKey(`-----BEGIN EC PARAMETERS-----
    93  BgUrgQQAIw==
    94  -----END EC PARAMETERS-----
    95  -----BEGIN EC TESTING KEY-----
    96  MIHcAgEBBEIBrsoKp0oqcv6/JovJJDoDVSGWdirrkgCWxrprGlzB9o0X8fV675X0
    97  NwuBenXFfeZvVcwluO7/Q9wkYoPd/t3jGImgBwYFK4EEACOhgYkDgYYABAFj36bL
    98  06h5JRGUNB1X/Hwuw64uKW2GGJLVPPhoYMcg/ALWaW+d/t+DmV5xikwKssuFq4Bz
    99  VQldyCXTXGgu7OC0AQCC/Y/+ODK3NFKlRi+AsG3VQDSV4tgHLqZBBus0S6pPcg1q
   100  kohxS/xfFg/TEwRSSws+roJr4JFKpO2t3/be5OdqmQ==
   101  -----END EC TESTING KEY-----
   102  `)
   103  
   104  var keyPairTests = []struct {
   105  	algo string
   106  	cert string
   107  	key  string
   108  }{
   109  	{"ECDSA", ecdsaCertPEM, ecdsaKeyPEM},
   110  	{"RSA", rsaCertPEM, rsaKeyPEM},
   111  	{"RSA-untyped", rsaCertPEM, keyPEM}, // golang.org/issue/4477
   112  }
   113  
   114  func TestX509KeyPair(t *testing.T) {
   115  	t.Parallel()
   116  	var pem []byte
   117  	for _, test := range keyPairTests {
   118  		pem = []byte(test.cert + test.key)
   119  		if _, err := X509KeyPair(pem, pem); err != nil {
   120  			t.Errorf("Failed to load %s cert followed by %s key: %s", test.algo, test.algo, err)
   121  		}
   122  		pem = []byte(test.key + test.cert)
   123  		if _, err := X509KeyPair(pem, pem); err != nil {
   124  			t.Errorf("Failed to load %s key followed by %s cert: %s", test.algo, test.algo, err)
   125  		}
   126  	}
   127  }
   128  
   129  func TestX509KeyPairErrors(t *testing.T) {
   130  	_, err := X509KeyPair([]byte(rsaKeyPEM), []byte(rsaCertPEM))
   131  	if err == nil {
   132  		t.Fatalf("X509KeyPair didn't return an error when arguments were switched")
   133  	}
   134  	if subStr := "been switched"; !strings.Contains(err.Error(), subStr) {
   135  		t.Fatalf("Expected %q in the error when switching arguments to X509KeyPair, but the error was %q", subStr, err)
   136  	}
   137  
   138  	_, err = X509KeyPair([]byte(rsaCertPEM), []byte(rsaCertPEM))
   139  	if err == nil {
   140  		t.Fatalf("X509KeyPair didn't return an error when both arguments were certificates")
   141  	}
   142  	if subStr := "certificate"; !strings.Contains(err.Error(), subStr) {
   143  		t.Fatalf("Expected %q in the error when both arguments to X509KeyPair were certificates, but the error was %q", subStr, err)
   144  	}
   145  
   146  	const nonsensePEM = `
   147  -----BEGIN NONSENSE-----
   148  Zm9vZm9vZm9v
   149  -----END NONSENSE-----
   150  `
   151  
   152  	_, err = X509KeyPair([]byte(nonsensePEM), []byte(nonsensePEM))
   153  	if err == nil {
   154  		t.Fatalf("X509KeyPair didn't return an error when both arguments were nonsense")
   155  	}
   156  	if subStr := "NONSENSE"; !strings.Contains(err.Error(), subStr) {
   157  		t.Fatalf("Expected %q in the error when both arguments to X509KeyPair were nonsense, but the error was %q", subStr, err)
   158  	}
   159  }
   160  
   161  func TestX509MixedKeyPair(t *testing.T) {
   162  	if _, err := X509KeyPair([]byte(rsaCertPEM), []byte(ecdsaKeyPEM)); err == nil {
   163  		t.Error("Load of RSA certificate succeeded with ECDSA private key")
   164  	}
   165  	if _, err := X509KeyPair([]byte(ecdsaCertPEM), []byte(rsaKeyPEM)); err == nil {
   166  		t.Error("Load of ECDSA certificate succeeded with RSA private key")
   167  	}
   168  }
   169  
   170  func newLocalListener(t testing.TB) net.Listener {
   171  	t.Helper()
   172  	ln, err := net.Listen("tcp", "127.0.0.1:0")
   173  	if err != nil {
   174  		ln, err = net.Listen("tcp6", "[::1]:0")
   175  	}
   176  	if err != nil {
   177  		t.Fatal(err)
   178  	}
   179  	return ln
   180  }
   181  
   182  func runWithFIPSEnabled(t *testing.T, testFunc func(t *testing.T)) {
   183  	originalFIPS := fips140tls.Required()
   184  	defer func() {
   185  		if originalFIPS {
   186  			fips140tls.Force()
   187  		} else {
   188  			fips140tls.TestingOnlyAbandon()
   189  		}
   190  	}()
   191  
   192  	fips140tls.Force()
   193  	t.Run("fips140tls", testFunc)
   194  }
   195  
   196  func runWithFIPSDisabled(t *testing.T, testFunc func(t *testing.T)) {
   197  	originalFIPS := fips140tls.Required()
   198  	defer func() {
   199  		if originalFIPS {
   200  			fips140tls.Force()
   201  		} else {
   202  			fips140tls.TestingOnlyAbandon()
   203  		}
   204  	}()
   205  
   206  	fips140tls.TestingOnlyAbandon()
   207  	t.Run("no-fips140tls", testFunc)
   208  }
   209  
   210  func skipFIPS(t *testing.T) {
   211  	if fips140tls.Required() {
   212  		t.Skip("skipping test in FIPS mode")
   213  	}
   214  }
   215  
   216  func TestDialTimeout(t *testing.T) {
   217  	if testing.Short() {
   218  		t.Skip("skipping in short mode")
   219  	}
   220  
   221  	timeout := 100 * time.Microsecond
   222  	for !t.Failed() {
   223  		acceptc := make(chan net.Conn)
   224  		listener := newLocalListener(t)
   225  		go func() {
   226  			for {
   227  				conn, err := listener.Accept()
   228  				if err != nil {
   229  					close(acceptc)
   230  					return
   231  				}
   232  				acceptc <- conn
   233  			}
   234  		}()
   235  
   236  		addr := listener.Addr().String()
   237  		dialer := &net.Dialer{
   238  			Timeout: timeout,
   239  		}
   240  		if conn, err := DialWithDialer(dialer, "tcp", addr, nil); err == nil {
   241  			conn.Close()
   242  			t.Errorf("DialWithTimeout unexpectedly completed successfully")
   243  		} else if !isTimeoutError(err) {
   244  			t.Errorf("resulting error not a timeout: %v\nType %T: %#v", err, err, err)
   245  		}
   246  
   247  		listener.Close()
   248  
   249  		// We're looking for a timeout during the handshake, so check that the
   250  		// Listener actually accepted the connection to initiate it. (If the server
   251  		// takes too long to accept the connection, we might cancel before the
   252  		// underlying net.Conn is ever dialed — without ever attempting a
   253  		// handshake.)
   254  		lconn, ok := <-acceptc
   255  		if ok {
   256  			// The Listener accepted a connection, so assume that it was from our
   257  			// Dial: we triggered the timeout at the point where we wanted it!
   258  			t.Logf("Listener accepted a connection from %s", lconn.RemoteAddr())
   259  			lconn.Close()
   260  		}
   261  		// Close any spurious extra connections from the listener. (This is
   262  		// possible if there are, for example, stray Dial calls from other tests.)
   263  		for extraConn := range acceptc {
   264  			t.Logf("spurious extra connection from %s", extraConn.RemoteAddr())
   265  			extraConn.Close()
   266  		}
   267  		if ok {
   268  			break
   269  		}
   270  
   271  		t.Logf("with timeout %v, DialWithDialer returned before listener accepted any connections; retrying", timeout)
   272  		timeout *= 2
   273  	}
   274  }
   275  
   276  func TestDeadlineOnWrite(t *testing.T) {
   277  	if testing.Short() {
   278  		t.Skip("skipping in short mode")
   279  	}
   280  
   281  	ln := newLocalListener(t)
   282  	defer ln.Close()
   283  
   284  	srvCh := make(chan *Conn, 1)
   285  
   286  	go func() {
   287  		sconn, err := ln.Accept()
   288  		if err != nil {
   289  			srvCh <- nil
   290  			return
   291  		}
   292  		srv := Server(sconn, testConfig.Clone())
   293  		if err := srv.Handshake(); err != nil {
   294  			srvCh <- nil
   295  			return
   296  		}
   297  		srvCh <- srv
   298  	}()
   299  
   300  	clientConfig := testConfig.Clone()
   301  	clientConfig.MaxVersion = VersionTLS12
   302  	conn, err := Dial("tcp", ln.Addr().String(), clientConfig)
   303  	if err != nil {
   304  		t.Fatal(err)
   305  	}
   306  	defer conn.Close()
   307  
   308  	srv := <-srvCh
   309  	if srv == nil {
   310  		t.Error(err)
   311  	}
   312  
   313  	// Make sure the client/server is setup correctly and is able to do a typical Write/Read
   314  	buf := make([]byte, 6)
   315  	if _, err := srv.Write([]byte("foobar")); err != nil {
   316  		t.Errorf("Write err: %v", err)
   317  	}
   318  	if n, err := conn.Read(buf); n != 6 || err != nil || string(buf) != "foobar" {
   319  		t.Errorf("Read = %d, %v, data %q; want 6, nil, foobar", n, err, buf)
   320  	}
   321  
   322  	// Set a deadline which should cause Write to timeout
   323  	if err = srv.SetDeadline(time.Now()); err != nil {
   324  		t.Fatalf("SetDeadline(time.Now()) err: %v", err)
   325  	}
   326  	if _, err = srv.Write([]byte("should fail")); err == nil {
   327  		t.Fatal("Write should have timed out")
   328  	}
   329  
   330  	// Clear deadline and make sure it still times out
   331  	if err = srv.SetDeadline(time.Time{}); err != nil {
   332  		t.Fatalf("SetDeadline(time.Time{}) err: %v", err)
   333  	}
   334  	if _, err = srv.Write([]byte("This connection is permanently broken")); err == nil {
   335  		t.Fatal("Write which previously failed should still time out")
   336  	}
   337  
   338  	// Verify the error
   339  	if ne := err.(net.Error); ne.Temporary() != false {
   340  		t.Error("Write timed out but incorrectly classified the error as Temporary")
   341  	}
   342  	if !isTimeoutError(err) {
   343  		t.Error("Write timed out but did not classify the error as a Timeout")
   344  	}
   345  }
   346  
   347  type readerFunc func([]byte) (int, error)
   348  
   349  func (f readerFunc) Read(b []byte) (int, error) { return f(b) }
   350  
   351  // TestDialer tests that tls.Dialer.DialContext can abort in the middle of a handshake.
   352  // (The other cases are all handled by the existing dial tests in this package, which
   353  // all also flow through the same code shared code paths)
   354  func TestDialer(t *testing.T) {
   355  	ln := newLocalListener(t)
   356  	defer ln.Close()
   357  
   358  	unblockServer := make(chan struct{}) // close-only
   359  	defer close(unblockServer)
   360  	go func() {
   361  		conn, err := ln.Accept()
   362  		if err != nil {
   363  			return
   364  		}
   365  		defer conn.Close()
   366  		<-unblockServer
   367  	}()
   368  
   369  	ctx, cancel := context.WithCancel(context.Background())
   370  	d := Dialer{Config: &Config{
   371  		Rand: readerFunc(func(b []byte) (n int, err error) {
   372  			// By the time crypto/tls wants randomness, that means it has a TCP
   373  			// connection, so we're past the Dialer's dial and now blocked
   374  			// in a handshake. Cancel our context and see if we get unstuck.
   375  			// (Our TCP listener above never reads or writes, so the Handshake
   376  			// would otherwise be stuck forever)
   377  			cancel()
   378  			return len(b), nil
   379  		}),
   380  		ServerName: "foo",
   381  	}}
   382  	_, err := d.DialContext(ctx, "tcp", ln.Addr().String())
   383  	if err != context.Canceled {
   384  		t.Errorf("err = %v; want context.Canceled", err)
   385  	}
   386  }
   387  
   388  func isTimeoutError(err error) bool {
   389  	if ne, ok := err.(net.Error); ok {
   390  		return ne.Timeout()
   391  	}
   392  	return false
   393  }
   394  
   395  // tests that Conn.Read returns (non-zero, io.EOF) instead of
   396  // (non-zero, nil) when a Close (alertCloseNotify) is sitting right
   397  // behind the application data in the buffer.
   398  func TestConnReadNonzeroAndEOF(t *testing.T) {
   399  	// This test is racy: it assumes that after a write to a
   400  	// localhost TCP connection, the peer TCP connection can
   401  	// immediately read it. Because it's racy, we skip this test
   402  	// in short mode, and then retry it several times with an
   403  	// increasing sleep in between our final write (via srv.Close
   404  	// below) and the following read.
   405  	if testing.Short() {
   406  		t.Skip("skipping in short mode")
   407  	}
   408  	var err error
   409  	for delay := time.Millisecond; delay <= 64*time.Millisecond; delay *= 2 {
   410  		if err = testConnReadNonzeroAndEOF(t, delay); err == nil {
   411  			return
   412  		}
   413  	}
   414  	t.Error(err)
   415  }
   416  
   417  func testConnReadNonzeroAndEOF(t *testing.T, delay time.Duration) error {
   418  	ln := newLocalListener(t)
   419  	defer ln.Close()
   420  
   421  	srvCh := make(chan *Conn, 1)
   422  	var serr error
   423  	go func() {
   424  		sconn, err := ln.Accept()
   425  		if err != nil {
   426  			serr = err
   427  			srvCh <- nil
   428  			return
   429  		}
   430  		serverConfig := testConfig.Clone()
   431  		srv := Server(sconn, serverConfig)
   432  		if err := srv.Handshake(); err != nil {
   433  			serr = fmt.Errorf("handshake: %v", err)
   434  			srvCh <- nil
   435  			return
   436  		}
   437  		srvCh <- srv
   438  	}()
   439  
   440  	clientConfig := testConfig.Clone()
   441  	// In TLS 1.3, alerts are encrypted and disguised as application data, so
   442  	// the opportunistic peek won't work.
   443  	clientConfig.MaxVersion = VersionTLS12
   444  	conn, err := Dial("tcp", ln.Addr().String(), clientConfig)
   445  	if err != nil {
   446  		t.Fatal(err)
   447  	}
   448  	defer conn.Close()
   449  
   450  	srv := <-srvCh
   451  	if srv == nil {
   452  		return serr
   453  	}
   454  
   455  	buf := make([]byte, 6)
   456  
   457  	srv.Write([]byte("foobar"))
   458  	n, err := conn.Read(buf)
   459  	if n != 6 || err != nil || string(buf) != "foobar" {
   460  		return fmt.Errorf("Read = %d, %v, data %q; want 6, nil, foobar", n, err, buf)
   461  	}
   462  
   463  	srv.Write([]byte("abcdef"))
   464  	srv.Close()
   465  	time.Sleep(delay)
   466  	n, err = conn.Read(buf)
   467  	if n != 6 || string(buf) != "abcdef" {
   468  		return fmt.Errorf("Read = %d, buf= %q; want 6, abcdef", n, buf)
   469  	}
   470  	if err != io.EOF {
   471  		return fmt.Errorf("Second Read error = %v; want io.EOF", err)
   472  	}
   473  	return nil
   474  }
   475  
   476  func TestTLSUniqueMatches(t *testing.T) {
   477  	ln := newLocalListener(t)
   478  	defer ln.Close()
   479  
   480  	serverTLSUniques := make(chan []byte)
   481  	parentDone := make(chan struct{})
   482  	childDone := make(chan struct{})
   483  	defer close(parentDone)
   484  	go func() {
   485  		defer close(childDone)
   486  		for i := 0; i < 2; i++ {
   487  			sconn, err := ln.Accept()
   488  			if err != nil {
   489  				t.Error(err)
   490  				return
   491  			}
   492  			serverConfig := testConfig.Clone()
   493  			serverConfig.MaxVersion = VersionTLS12 // TLSUnique is not defined in TLS 1.3
   494  			srv := Server(sconn, serverConfig)
   495  			if err := srv.Handshake(); err != nil {
   496  				t.Error(err)
   497  				return
   498  			}
   499  			select {
   500  			case <-parentDone:
   501  				return
   502  			case serverTLSUniques <- srv.ConnectionState().TLSUnique:
   503  			}
   504  		}
   505  	}()
   506  
   507  	clientConfig := testConfig.Clone()
   508  	clientConfig.ClientSessionCache = NewLRUClientSessionCache(1)
   509  	conn, err := Dial("tcp", ln.Addr().String(), clientConfig)
   510  	if err != nil {
   511  		t.Fatal(err)
   512  	}
   513  
   514  	var serverTLSUniquesValue []byte
   515  	select {
   516  	case <-childDone:
   517  		return
   518  	case serverTLSUniquesValue = <-serverTLSUniques:
   519  	}
   520  
   521  	if !bytes.Equal(conn.ConnectionState().TLSUnique, serverTLSUniquesValue) {
   522  		t.Error("client and server channel bindings differ")
   523  	}
   524  	if serverTLSUniquesValue == nil || bytes.Equal(serverTLSUniquesValue, make([]byte, 12)) {
   525  		t.Error("tls-unique is empty or zero")
   526  	}
   527  	conn.Close()
   528  
   529  	conn, err = Dial("tcp", ln.Addr().String(), clientConfig)
   530  	if err != nil {
   531  		t.Fatal(err)
   532  	}
   533  	defer conn.Close()
   534  	if !conn.ConnectionState().DidResume {
   535  		t.Error("second session did not use resumption")
   536  	}
   537  
   538  	select {
   539  	case <-childDone:
   540  		return
   541  	case serverTLSUniquesValue = <-serverTLSUniques:
   542  	}
   543  
   544  	if !bytes.Equal(conn.ConnectionState().TLSUnique, serverTLSUniquesValue) {
   545  		t.Error("client and server channel bindings differ when session resumption is used")
   546  	}
   547  	if serverTLSUniquesValue == nil || bytes.Equal(serverTLSUniquesValue, make([]byte, 12)) {
   548  		t.Error("resumption tls-unique is empty or zero")
   549  	}
   550  }
   551  
   552  func TestVerifyHostname(t *testing.T) {
   553  	testenv.MustHaveExternalNetwork(t)
   554  
   555  	c, err := Dial("tcp", "www.google.com:https", nil)
   556  	if err != nil {
   557  		t.Fatal(err)
   558  	}
   559  	if err := c.VerifyHostname("www.google.com"); err != nil {
   560  		t.Fatalf("verify www.google.com: %v", err)
   561  	}
   562  	if err := c.VerifyHostname("www.yahoo.com"); err == nil {
   563  		t.Fatalf("verify www.yahoo.com succeeded")
   564  	}
   565  
   566  	c, err = Dial("tcp", "www.google.com:https", &Config{InsecureSkipVerify: true})
   567  	if err != nil {
   568  		t.Fatal(err)
   569  	}
   570  	if err := c.VerifyHostname("www.google.com"); err == nil {
   571  		t.Fatalf("verify www.google.com succeeded with InsecureSkipVerify=true")
   572  	}
   573  }
   574  
   575  func TestConnCloseBreakingWrite(t *testing.T) {
   576  	ln := newLocalListener(t)
   577  	defer ln.Close()
   578  
   579  	srvCh := make(chan *Conn, 1)
   580  	var serr error
   581  	var sconn net.Conn
   582  	go func() {
   583  		var err error
   584  		sconn, err = ln.Accept()
   585  		if err != nil {
   586  			serr = err
   587  			srvCh <- nil
   588  			return
   589  		}
   590  		serverConfig := testConfig.Clone()
   591  		srv := Server(sconn, serverConfig)
   592  		if err := srv.Handshake(); err != nil {
   593  			serr = fmt.Errorf("handshake: %v", err)
   594  			srvCh <- nil
   595  			return
   596  		}
   597  		srvCh <- srv
   598  	}()
   599  
   600  	cconn, err := net.Dial("tcp", ln.Addr().String())
   601  	if err != nil {
   602  		t.Fatal(err)
   603  	}
   604  	defer cconn.Close()
   605  
   606  	conn := &changeImplConn{
   607  		Conn: cconn,
   608  	}
   609  
   610  	clientConfig := testConfig.Clone()
   611  	tconn := Client(conn, clientConfig)
   612  	if err := tconn.Handshake(); err != nil {
   613  		t.Fatal(err)
   614  	}
   615  
   616  	srv := <-srvCh
   617  	if srv == nil {
   618  		t.Fatal(serr)
   619  	}
   620  	defer sconn.Close()
   621  
   622  	connClosed := make(chan struct{})
   623  	conn.closeFunc = func() error {
   624  		close(connClosed)
   625  		return nil
   626  	}
   627  
   628  	inWrite := make(chan bool, 1)
   629  	var errConnClosed = errors.New("conn closed for test")
   630  	conn.writeFunc = func(p []byte) (n int, err error) {
   631  		inWrite <- true
   632  		<-connClosed
   633  		return 0, errConnClosed
   634  	}
   635  
   636  	closeReturned := make(chan bool, 1)
   637  	go func() {
   638  		<-inWrite
   639  		tconn.Close() // test that this doesn't block forever.
   640  		closeReturned <- true
   641  	}()
   642  
   643  	_, err = tconn.Write([]byte("foo"))
   644  	if err != errConnClosed {
   645  		t.Errorf("Write error = %v; want errConnClosed", err)
   646  	}
   647  
   648  	<-closeReturned
   649  	if err := tconn.Close(); err != net.ErrClosed {
   650  		t.Errorf("Close error = %v; want net.ErrClosed", err)
   651  	}
   652  }
   653  
   654  func TestConnCloseWrite(t *testing.T) {
   655  	ln := newLocalListener(t)
   656  	defer ln.Close()
   657  
   658  	clientDoneChan := make(chan struct{})
   659  
   660  	serverCloseWrite := func() error {
   661  		sconn, err := ln.Accept()
   662  		if err != nil {
   663  			return fmt.Errorf("accept: %v", err)
   664  		}
   665  		defer sconn.Close()
   666  
   667  		serverConfig := testConfig.Clone()
   668  		srv := Server(sconn, serverConfig)
   669  		if err := srv.Handshake(); err != nil {
   670  			return fmt.Errorf("handshake: %v", err)
   671  		}
   672  		defer srv.Close()
   673  
   674  		data, err := io.ReadAll(srv)
   675  		if err != nil {
   676  			return err
   677  		}
   678  		if len(data) > 0 {
   679  			return fmt.Errorf("Read data = %q; want nothing", data)
   680  		}
   681  
   682  		if err := srv.CloseWrite(); err != nil {
   683  			return fmt.Errorf("server CloseWrite: %v", err)
   684  		}
   685  
   686  		// Wait for clientCloseWrite to finish, so we know we
   687  		// tested the CloseWrite before we defer the
   688  		// sconn.Close above, which would also cause the
   689  		// client to unblock like CloseWrite.
   690  		<-clientDoneChan
   691  		return nil
   692  	}
   693  
   694  	clientCloseWrite := func() error {
   695  		defer close(clientDoneChan)
   696  
   697  		clientConfig := testConfig.Clone()
   698  		conn, err := Dial("tcp", ln.Addr().String(), clientConfig)
   699  		if err != nil {
   700  			return err
   701  		}
   702  		if err := conn.Handshake(); err != nil {
   703  			return err
   704  		}
   705  		defer conn.Close()
   706  
   707  		if err := conn.CloseWrite(); err != nil {
   708  			return fmt.Errorf("client CloseWrite: %v", err)
   709  		}
   710  
   711  		if _, err := conn.Write([]byte{0}); err != errShutdown {
   712  			return fmt.Errorf("CloseWrite error = %v; want errShutdown", err)
   713  		}
   714  
   715  		data, err := io.ReadAll(conn)
   716  		if err != nil {
   717  			return err
   718  		}
   719  		if len(data) > 0 {
   720  			return fmt.Errorf("Read data = %q; want nothing", data)
   721  		}
   722  		return nil
   723  	}
   724  
   725  	errChan := make(chan error, 2)
   726  
   727  	go func() { errChan <- serverCloseWrite() }()
   728  	go func() { errChan <- clientCloseWrite() }()
   729  
   730  	for i := 0; i < 2; i++ {
   731  		select {
   732  		case err := <-errChan:
   733  			if err != nil {
   734  				t.Fatal(err)
   735  			}
   736  		case <-time.After(10 * time.Second):
   737  			t.Fatal("deadlock")
   738  		}
   739  	}
   740  
   741  	// Also test CloseWrite being called before the handshake is
   742  	// finished:
   743  	{
   744  		ln2 := newLocalListener(t)
   745  		defer ln2.Close()
   746  
   747  		netConn, err := net.Dial("tcp", ln2.Addr().String())
   748  		if err != nil {
   749  			t.Fatal(err)
   750  		}
   751  		defer netConn.Close()
   752  		conn := Client(netConn, testConfig.Clone())
   753  
   754  		if err := conn.CloseWrite(); err != errEarlyCloseWrite {
   755  			t.Errorf("CloseWrite error = %v; want errEarlyCloseWrite", err)
   756  		}
   757  	}
   758  }
   759  
   760  func TestWarningAlertFlood(t *testing.T) {
   761  	ln := newLocalListener(t)
   762  	defer ln.Close()
   763  
   764  	server := func() error {
   765  		sconn, err := ln.Accept()
   766  		if err != nil {
   767  			return fmt.Errorf("accept: %v", err)
   768  		}
   769  		defer sconn.Close()
   770  
   771  		serverConfig := testConfig.Clone()
   772  		srv := Server(sconn, serverConfig)
   773  		if err := srv.Handshake(); err != nil {
   774  			return fmt.Errorf("handshake: %v", err)
   775  		}
   776  		defer srv.Close()
   777  
   778  		_, err = io.ReadAll(srv)
   779  		if err == nil {
   780  			return errors.New("unexpected lack of error from server")
   781  		}
   782  		const expected = "too many ignored"
   783  		if str := err.Error(); !strings.Contains(str, expected) {
   784  			return fmt.Errorf("expected error containing %q, but saw: %s", expected, str)
   785  		}
   786  
   787  		return nil
   788  	}
   789  
   790  	errChan := make(chan error, 1)
   791  	go func() { errChan <- server() }()
   792  
   793  	clientConfig := testConfig.Clone()
   794  	clientConfig.MaxVersion = VersionTLS12 // there are no warning alerts in TLS 1.3
   795  	conn, err := Dial("tcp", ln.Addr().String(), clientConfig)
   796  	if err != nil {
   797  		t.Fatal(err)
   798  	}
   799  	defer conn.Close()
   800  	if err := conn.Handshake(); err != nil {
   801  		t.Fatal(err)
   802  	}
   803  
   804  	for i := 0; i < maxUselessRecords+1; i++ {
   805  		conn.sendAlert(alertNoRenegotiation)
   806  	}
   807  
   808  	if err := <-errChan; err != nil {
   809  		t.Fatal(err)
   810  	}
   811  }
   812  
   813  func TestCloneFuncFields(t *testing.T) {
   814  	const expectedCount = 9
   815  	called := 0
   816  
   817  	c1 := Config{
   818  		Time: func() time.Time {
   819  			called |= 1 << 0
   820  			return time.Time{}
   821  		},
   822  		GetCertificate: func(*ClientHelloInfo) (*Certificate, error) {
   823  			called |= 1 << 1
   824  			return nil, nil
   825  		},
   826  		GetClientCertificate: func(*CertificateRequestInfo) (*Certificate, error) {
   827  			called |= 1 << 2
   828  			return nil, nil
   829  		},
   830  		GetConfigForClient: func(*ClientHelloInfo) (*Config, error) {
   831  			called |= 1 << 3
   832  			return nil, nil
   833  		},
   834  		VerifyPeerCertificate: func(rawCerts [][]byte, verifiedChains [][]*x509.Certificate) error {
   835  			called |= 1 << 4
   836  			return nil
   837  		},
   838  		VerifyConnection: func(ConnectionState) error {
   839  			called |= 1 << 5
   840  			return nil
   841  		},
   842  		UnwrapSession: func(identity []byte, cs ConnectionState) (*SessionState, error) {
   843  			called |= 1 << 6
   844  			return nil, nil
   845  		},
   846  		WrapSession: func(cs ConnectionState, ss *SessionState) ([]byte, error) {
   847  			called |= 1 << 7
   848  			return nil, nil
   849  		},
   850  		EncryptedClientHelloRejectionVerify: func(ConnectionState) error {
   851  			called |= 1 << 8
   852  			return nil
   853  		},
   854  	}
   855  
   856  	c2 := c1.Clone()
   857  
   858  	c2.Time()
   859  	c2.GetCertificate(nil)
   860  	c2.GetClientCertificate(nil)
   861  	c2.GetConfigForClient(nil)
   862  	c2.VerifyPeerCertificate(nil, nil)
   863  	c2.VerifyConnection(ConnectionState{})
   864  	c2.UnwrapSession(nil, ConnectionState{})
   865  	c2.WrapSession(ConnectionState{}, nil)
   866  	c2.EncryptedClientHelloRejectionVerify(ConnectionState{})
   867  
   868  	if called != (1<<expectedCount)-1 {
   869  		t.Fatalf("expected %d calls but saw calls %b", expectedCount, called)
   870  	}
   871  }
   872  
   873  func TestCloneNonFuncFields(t *testing.T) {
   874  	var c1 Config
   875  	v := reflect.ValueOf(&c1).Elem()
   876  
   877  	typ := v.Type()
   878  	for i := 0; i < typ.NumField(); i++ {
   879  		f := v.Field(i)
   880  		// testing/quick can't handle functions or interfaces and so
   881  		// isn't used here.
   882  		switch fn := typ.Field(i).Name; fn {
   883  		case "Rand":
   884  			f.Set(reflect.ValueOf(io.Reader(os.Stdin)))
   885  		case "Time", "GetCertificate", "GetConfigForClient", "VerifyPeerCertificate", "VerifyConnection", "GetClientCertificate", "WrapSession", "UnwrapSession", "EncryptedClientHelloRejectionVerify":
   886  			// DeepEqual can't compare functions. If you add a
   887  			// function field to this list, you must also change
   888  			// TestCloneFuncFields to ensure that the func field is
   889  			// cloned.
   890  		case "Certificates":
   891  			f.Set(reflect.ValueOf([]Certificate{
   892  				{Certificate: [][]byte{{'b'}}},
   893  			}))
   894  		case "NameToCertificate":
   895  			f.Set(reflect.ValueOf(map[string]*Certificate{"a": nil}))
   896  		case "RootCAs", "ClientCAs":
   897  			f.Set(reflect.ValueOf(x509.NewCertPool()))
   898  		case "ClientSessionCache":
   899  			f.Set(reflect.ValueOf(NewLRUClientSessionCache(10)))
   900  		case "KeyLogWriter":
   901  			f.Set(reflect.ValueOf(io.Writer(os.Stdout)))
   902  		case "NextProtos":
   903  			f.Set(reflect.ValueOf([]string{"a", "b"}))
   904  		case "ServerName":
   905  			f.Set(reflect.ValueOf("b"))
   906  		case "ClientAuth":
   907  			f.Set(reflect.ValueOf(VerifyClientCertIfGiven))
   908  		case "InsecureSkipVerify", "SessionTicketsDisabled", "DynamicRecordSizingDisabled", "PreferServerCipherSuites":
   909  			f.Set(reflect.ValueOf(true))
   910  		case "MinVersion", "MaxVersion":
   911  			f.Set(reflect.ValueOf(uint16(VersionTLS12)))
   912  		case "SessionTicketKey":
   913  			f.Set(reflect.ValueOf([32]byte{}))
   914  		case "CipherSuites":
   915  			f.Set(reflect.ValueOf([]uint16{1, 2}))
   916  		case "CurvePreferences":
   917  			f.Set(reflect.ValueOf([]CurveID{CurveP256}))
   918  		case "Renegotiation":
   919  			f.Set(reflect.ValueOf(RenegotiateOnceAsClient))
   920  		case "EncryptedClientHelloConfigList":
   921  			f.Set(reflect.ValueOf([]byte{'x'}))
   922  		case "EncryptedClientHelloKeys":
   923  			f.Set(reflect.ValueOf([]EncryptedClientHelloKey{
   924  				{Config: []byte{1}, PrivateKey: []byte{1}},
   925  			}))
   926  		case "mutex", "autoSessionTicketKeys", "sessionTicketKeys":
   927  			continue // these are unexported fields that are handled separately
   928  		default:
   929  			t.Errorf("all fields must be accounted for, but saw unknown field %q", fn)
   930  		}
   931  	}
   932  	// Set the unexported fields related to session ticket keys, which are copied with Clone().
   933  	c1.autoSessionTicketKeys = []ticketKey{c1.ticketKeyFromBytes(c1.SessionTicketKey)}
   934  	c1.sessionTicketKeys = []ticketKey{c1.ticketKeyFromBytes(c1.SessionTicketKey)}
   935  
   936  	c2 := c1.Clone()
   937  	if !reflect.DeepEqual(&c1, c2) {
   938  		t.Errorf("clone failed to copy a field")
   939  	}
   940  }
   941  
   942  func TestCloneNilConfig(t *testing.T) {
   943  	var config *Config
   944  	if cc := config.Clone(); cc != nil {
   945  		t.Fatalf("Clone with nil should return nil, got: %+v", cc)
   946  	}
   947  }
   948  
   949  // changeImplConn is a net.Conn which can change its Write and Close
   950  // methods.
   951  type changeImplConn struct {
   952  	net.Conn
   953  	writeFunc func([]byte) (int, error)
   954  	closeFunc func() error
   955  }
   956  
   957  func (w *changeImplConn) Write(p []byte) (n int, err error) {
   958  	if w.writeFunc != nil {
   959  		return w.writeFunc(p)
   960  	}
   961  	return w.Conn.Write(p)
   962  }
   963  
   964  func (w *changeImplConn) Close() error {
   965  	if w.closeFunc != nil {
   966  		return w.closeFunc()
   967  	}
   968  	return w.Conn.Close()
   969  }
   970  
   971  func throughput(b *testing.B, version uint16, totalBytes int64, dynamicRecordSizingDisabled bool) {
   972  	ln := newLocalListener(b)
   973  	defer ln.Close()
   974  
   975  	N := b.N
   976  
   977  	// Less than 64KB because Windows appears to use a TCP rwin < 64KB.
   978  	// See Issue #15899.
   979  	const bufsize = 32 << 10
   980  
   981  	go func() {
   982  		buf := make([]byte, bufsize)
   983  		for i := 0; i < N; i++ {
   984  			sconn, err := ln.Accept()
   985  			if err != nil {
   986  				// panic rather than synchronize to avoid benchmark overhead
   987  				// (cannot call b.Fatal in goroutine)
   988  				panic(fmt.Errorf("accept: %v", err))
   989  			}
   990  			serverConfig := testConfig.Clone()
   991  			serverConfig.CipherSuites = nil // the defaults may prefer faster ciphers
   992  			serverConfig.DynamicRecordSizingDisabled = dynamicRecordSizingDisabled
   993  			srv := Server(sconn, serverConfig)
   994  			if err := srv.Handshake(); err != nil {
   995  				panic(fmt.Errorf("handshake: %v", err))
   996  			}
   997  			if _, err := io.CopyBuffer(srv, srv, buf); err != nil {
   998  				panic(fmt.Errorf("copy buffer: %v", err))
   999  			}
  1000  		}
  1001  	}()
  1002  
  1003  	b.SetBytes(totalBytes)
  1004  	clientConfig := testConfig.Clone()
  1005  	clientConfig.CipherSuites = nil // the defaults may prefer faster ciphers
  1006  	clientConfig.DynamicRecordSizingDisabled = dynamicRecordSizingDisabled
  1007  	clientConfig.MaxVersion = version
  1008  
  1009  	buf := make([]byte, bufsize)
  1010  	chunks := int(math.Ceil(float64(totalBytes) / float64(len(buf))))
  1011  	for i := 0; i < N; i++ {
  1012  		conn, err := Dial("tcp", ln.Addr().String(), clientConfig)
  1013  		if err != nil {
  1014  			b.Fatal(err)
  1015  		}
  1016  		for j := 0; j < chunks; j++ {
  1017  			_, err := conn.Write(buf)
  1018  			if err != nil {
  1019  				b.Fatal(err)
  1020  			}
  1021  			_, err = io.ReadFull(conn, buf)
  1022  			if err != nil {
  1023  				b.Fatal(err)
  1024  			}
  1025  		}
  1026  		conn.Close()
  1027  	}
  1028  }
  1029  
  1030  func BenchmarkThroughput(b *testing.B) {
  1031  	for _, mode := range []string{"Max", "Dynamic"} {
  1032  		for size := 1; size <= 64; size <<= 1 {
  1033  			name := fmt.Sprintf("%sPacket/%dMB", mode, size)
  1034  			b.Run(name, func(b *testing.B) {
  1035  				b.Run("TLSv12", func(b *testing.B) {
  1036  					throughput(b, VersionTLS12, int64(size<<20), mode == "Max")
  1037  				})
  1038  				b.Run("TLSv13", func(b *testing.B) {
  1039  					throughput(b, VersionTLS13, int64(size<<20), mode == "Max")
  1040  				})
  1041  			})
  1042  		}
  1043  	}
  1044  }
  1045  
  1046  type slowConn struct {
  1047  	net.Conn
  1048  	bps int
  1049  }
  1050  
  1051  func (c *slowConn) Write(p []byte) (int, error) {
  1052  	if c.bps == 0 {
  1053  		panic("too slow")
  1054  	}
  1055  	t0 := time.Now()
  1056  	wrote := 0
  1057  	for wrote < len(p) {
  1058  		time.Sleep(100 * time.Microsecond)
  1059  		allowed := int(time.Since(t0).Seconds()*float64(c.bps)) / 8
  1060  		if allowed > len(p) {
  1061  			allowed = len(p)
  1062  		}
  1063  		if wrote < allowed {
  1064  			n, err := c.Conn.Write(p[wrote:allowed])
  1065  			wrote += n
  1066  			if err != nil {
  1067  				return wrote, err
  1068  			}
  1069  		}
  1070  	}
  1071  	return len(p), nil
  1072  }
  1073  
  1074  func latency(b *testing.B, version uint16, bps int, dynamicRecordSizingDisabled bool) {
  1075  	ln := newLocalListener(b)
  1076  	defer ln.Close()
  1077  
  1078  	N := b.N
  1079  
  1080  	go func() {
  1081  		for i := 0; i < N; i++ {
  1082  			sconn, err := ln.Accept()
  1083  			if err != nil {
  1084  				// panic rather than synchronize to avoid benchmark overhead
  1085  				// (cannot call b.Fatal in goroutine)
  1086  				panic(fmt.Errorf("accept: %v", err))
  1087  			}
  1088  			serverConfig := testConfig.Clone()
  1089  			serverConfig.DynamicRecordSizingDisabled = dynamicRecordSizingDisabled
  1090  			srv := Server(&slowConn{sconn, bps}, serverConfig)
  1091  			if err := srv.Handshake(); err != nil {
  1092  				panic(fmt.Errorf("handshake: %v", err))
  1093  			}
  1094  			io.Copy(srv, srv)
  1095  		}
  1096  	}()
  1097  
  1098  	clientConfig := testConfig.Clone()
  1099  	clientConfig.DynamicRecordSizingDisabled = dynamicRecordSizingDisabled
  1100  	clientConfig.MaxVersion = version
  1101  
  1102  	buf := make([]byte, 16384)
  1103  	peek := make([]byte, 1)
  1104  
  1105  	for i := 0; i < N; i++ {
  1106  		conn, err := Dial("tcp", ln.Addr().String(), clientConfig)
  1107  		if err != nil {
  1108  			b.Fatal(err)
  1109  		}
  1110  		// make sure we're connected and previous connection has stopped
  1111  		if _, err := conn.Write(buf[:1]); err != nil {
  1112  			b.Fatal(err)
  1113  		}
  1114  		if _, err := io.ReadFull(conn, peek); err != nil {
  1115  			b.Fatal(err)
  1116  		}
  1117  		if _, err := conn.Write(buf); err != nil {
  1118  			b.Fatal(err)
  1119  		}
  1120  		if _, err = io.ReadFull(conn, peek); err != nil {
  1121  			b.Fatal(err)
  1122  		}
  1123  		conn.Close()
  1124  	}
  1125  }
  1126  
  1127  func BenchmarkLatency(b *testing.B) {
  1128  	for _, mode := range []string{"Max", "Dynamic"} {
  1129  		for _, kbps := range []int{200, 500, 1000, 2000, 5000} {
  1130  			name := fmt.Sprintf("%sPacket/%dkbps", mode, kbps)
  1131  			b.Run(name, func(b *testing.B) {
  1132  				b.Run("TLSv12", func(b *testing.B) {
  1133  					latency(b, VersionTLS12, kbps*1000, mode == "Max")
  1134  				})
  1135  				b.Run("TLSv13", func(b *testing.B) {
  1136  					latency(b, VersionTLS13, kbps*1000, mode == "Max")
  1137  				})
  1138  			})
  1139  		}
  1140  	}
  1141  }
  1142  
  1143  func TestConnectionStateMarshal(t *testing.T) {
  1144  	cs := &ConnectionState{}
  1145  	_, err := json.Marshal(cs)
  1146  	if err != nil {
  1147  		t.Errorf("json.Marshal failed on ConnectionState: %v", err)
  1148  	}
  1149  }
  1150  
  1151  func TestConnectionState(t *testing.T) {
  1152  	skipFIPS(t) // Test certificates not FIPS compatible.
  1153  
  1154  	issuer, err := x509.ParseCertificate(testRSACertificateIssuer)
  1155  	if err != nil {
  1156  		panic(err)
  1157  	}
  1158  	rootCAs := x509.NewCertPool()
  1159  	rootCAs.AddCert(issuer)
  1160  
  1161  	const alpnProtocol = "golang"
  1162  	const serverName = "example.golang"
  1163  	var scts = [][]byte{[]byte("dummy sct 1"), []byte("dummy sct 2")}
  1164  	var ocsp = []byte("dummy ocsp")
  1165  
  1166  	for _, v := range []uint16{VersionTLS12, VersionTLS13} {
  1167  		var name string
  1168  		switch v {
  1169  		case VersionTLS12:
  1170  			name = "TLSv12"
  1171  		case VersionTLS13:
  1172  			name = "TLSv13"
  1173  		}
  1174  		t.Run(name, func(t *testing.T) {
  1175  			config := &Config{
  1176  				Time:         testTime,
  1177  				Rand:         zeroSource{},
  1178  				Certificates: make([]Certificate, 1),
  1179  				MaxVersion:   v,
  1180  				RootCAs:      rootCAs,
  1181  				ClientCAs:    rootCAs,
  1182  				ClientAuth:   RequireAndVerifyClientCert,
  1183  				NextProtos:   []string{alpnProtocol},
  1184  				ServerName:   serverName,
  1185  			}
  1186  			config.Certificates[0].Certificate = [][]byte{testRSACertificate}
  1187  			config.Certificates[0].PrivateKey = testRSAPrivateKey
  1188  			config.Certificates[0].SignedCertificateTimestamps = scts
  1189  			config.Certificates[0].OCSPStaple = ocsp
  1190  
  1191  			ss, cs, err := testHandshake(t, config, config)
  1192  			if err != nil {
  1193  				t.Fatalf("Handshake failed: %v", err)
  1194  			}
  1195  
  1196  			if ss.Version != v || cs.Version != v {
  1197  				t.Errorf("Got versions %x (server) and %x (client), expected %x", ss.Version, cs.Version, v)
  1198  			}
  1199  
  1200  			if !ss.HandshakeComplete || !cs.HandshakeComplete {
  1201  				t.Errorf("Got HandshakeComplete %v (server) and %v (client), expected true", ss.HandshakeComplete, cs.HandshakeComplete)
  1202  			}
  1203  
  1204  			if ss.DidResume || cs.DidResume {
  1205  				t.Errorf("Got DidResume %v (server) and %v (client), expected false", ss.DidResume, cs.DidResume)
  1206  			}
  1207  
  1208  			if ss.CipherSuite == 0 || cs.CipherSuite == 0 {
  1209  				t.Errorf("Got invalid cipher suite: %v (server) and %v (client)", ss.CipherSuite, cs.CipherSuite)
  1210  			}
  1211  
  1212  			if ss.NegotiatedProtocol != alpnProtocol || cs.NegotiatedProtocol != alpnProtocol {
  1213  				t.Errorf("Got negotiated protocol %q (server) and %q (client), expected %q", ss.NegotiatedProtocol, cs.NegotiatedProtocol, alpnProtocol)
  1214  			}
  1215  
  1216  			if !cs.NegotiatedProtocolIsMutual {
  1217  				t.Errorf("Got false NegotiatedProtocolIsMutual on the client side")
  1218  			}
  1219  			// NegotiatedProtocolIsMutual on the server side is unspecified.
  1220  
  1221  			if ss.ServerName != serverName {
  1222  				t.Errorf("Got server name %q, expected %q", ss.ServerName, serverName)
  1223  			}
  1224  			if cs.ServerName != serverName {
  1225  				t.Errorf("Got server name on client connection %q, expected %q", cs.ServerName, serverName)
  1226  			}
  1227  
  1228  			if len(ss.PeerCertificates) != 1 || len(cs.PeerCertificates) != 1 {
  1229  				t.Errorf("Got %d (server) and %d (client) peer certificates, expected %d", len(ss.PeerCertificates), len(cs.PeerCertificates), 1)
  1230  			}
  1231  
  1232  			if len(ss.VerifiedChains) != 1 || len(cs.VerifiedChains) != 1 {
  1233  				t.Errorf("Got %d (server) and %d (client) verified chains, expected %d", len(ss.VerifiedChains), len(cs.VerifiedChains), 1)
  1234  			} else if len(ss.VerifiedChains[0]) != 2 || len(cs.VerifiedChains[0]) != 2 {
  1235  				t.Errorf("Got %d (server) and %d (client) long verified chain, expected %d", len(ss.VerifiedChains[0]), len(cs.VerifiedChains[0]), 2)
  1236  			}
  1237  
  1238  			if len(cs.SignedCertificateTimestamps) != 2 {
  1239  				t.Errorf("Got %d SCTs, expected %d", len(cs.SignedCertificateTimestamps), 2)
  1240  			}
  1241  			if !bytes.Equal(cs.OCSPResponse, ocsp) {
  1242  				t.Errorf("Got OCSPs %x, expected %x", cs.OCSPResponse, ocsp)
  1243  			}
  1244  			// Only TLS 1.3 supports OCSP and SCTs on client certs.
  1245  			if v == VersionTLS13 {
  1246  				if len(ss.SignedCertificateTimestamps) != 2 {
  1247  					t.Errorf("Got %d client SCTs, expected %d", len(ss.SignedCertificateTimestamps), 2)
  1248  				}
  1249  				if !bytes.Equal(ss.OCSPResponse, ocsp) {
  1250  					t.Errorf("Got client OCSPs %x, expected %x", ss.OCSPResponse, ocsp)
  1251  				}
  1252  			}
  1253  
  1254  			if v == VersionTLS13 {
  1255  				if ss.TLSUnique != nil || cs.TLSUnique != nil {
  1256  					t.Errorf("Got TLSUnique %x (server) and %x (client), expected nil in TLS 1.3", ss.TLSUnique, cs.TLSUnique)
  1257  				}
  1258  			} else {
  1259  				if ss.TLSUnique == nil || cs.TLSUnique == nil {
  1260  					t.Errorf("Got TLSUnique %x (server) and %x (client), expected non-nil", ss.TLSUnique, cs.TLSUnique)
  1261  				}
  1262  			}
  1263  		})
  1264  	}
  1265  }
  1266  
  1267  // Issue 28744: Ensure that we don't modify memory
  1268  // that Config doesn't own such as Certificates.
  1269  func TestBuildNameToCertificate_doesntModifyCertificates(t *testing.T) {
  1270  	c0 := Certificate{
  1271  		Certificate: [][]byte{testRSACertificate},
  1272  		PrivateKey:  testRSAPrivateKey,
  1273  	}
  1274  	c1 := Certificate{
  1275  		Certificate: [][]byte{testSNICertificate},
  1276  		PrivateKey:  testRSAPrivateKey,
  1277  	}
  1278  	config := testConfig.Clone()
  1279  	config.Certificates = []Certificate{c0, c1}
  1280  
  1281  	config.BuildNameToCertificate()
  1282  	got := config.Certificates
  1283  	want := []Certificate{c0, c1}
  1284  	if !reflect.DeepEqual(got, want) {
  1285  		t.Fatalf("Certificates were mutated by BuildNameToCertificate\nGot: %#v\nWant: %#v\n", got, want)
  1286  	}
  1287  }
  1288  
  1289  func testingKey(s string) string { return strings.ReplaceAll(s, "TESTING KEY", "PRIVATE KEY") }
  1290  
  1291  func TestClientHelloInfo_SupportsCertificate(t *testing.T) {
  1292  	skipFIPS(t) // Test certificates not FIPS compatible.
  1293  
  1294  	rsaCert := &Certificate{
  1295  		Certificate: [][]byte{testRSACertificate},
  1296  		PrivateKey:  testRSAPrivateKey,
  1297  	}
  1298  	pkcs1Cert := &Certificate{
  1299  		Certificate:                  [][]byte{testRSACertificate},
  1300  		PrivateKey:                   testRSAPrivateKey,
  1301  		SupportedSignatureAlgorithms: []SignatureScheme{PKCS1WithSHA1, PKCS1WithSHA256},
  1302  	}
  1303  	ecdsaCert := &Certificate{
  1304  		// ECDSA P-256 certificate
  1305  		Certificate: [][]byte{testP256Certificate},
  1306  		PrivateKey:  testP256PrivateKey,
  1307  	}
  1308  	ed25519Cert := &Certificate{
  1309  		Certificate: [][]byte{testEd25519Certificate},
  1310  		PrivateKey:  testEd25519PrivateKey,
  1311  	}
  1312  
  1313  	tests := []struct {
  1314  		c       *Certificate
  1315  		chi     *ClientHelloInfo
  1316  		wantErr string
  1317  	}{
  1318  		{rsaCert, &ClientHelloInfo{
  1319  			ServerName:        "example.golang",
  1320  			SignatureSchemes:  []SignatureScheme{PSSWithSHA256},
  1321  			SupportedVersions: []uint16{VersionTLS13},
  1322  		}, ""},
  1323  		{ecdsaCert, &ClientHelloInfo{
  1324  			SignatureSchemes:  []SignatureScheme{PSSWithSHA256, ECDSAWithP256AndSHA256},
  1325  			SupportedVersions: []uint16{VersionTLS13, VersionTLS12},
  1326  		}, ""},
  1327  		{rsaCert, &ClientHelloInfo{
  1328  			ServerName:        "example.com",
  1329  			SignatureSchemes:  []SignatureScheme{PSSWithSHA256},
  1330  			SupportedVersions: []uint16{VersionTLS13},
  1331  		}, "not valid for requested server name"},
  1332  		{ecdsaCert, &ClientHelloInfo{
  1333  			SignatureSchemes:  []SignatureScheme{ECDSAWithP384AndSHA384},
  1334  			SupportedVersions: []uint16{VersionTLS13},
  1335  		}, "signature algorithms"},
  1336  		{pkcs1Cert, &ClientHelloInfo{
  1337  			SignatureSchemes:  []SignatureScheme{PSSWithSHA256, ECDSAWithP256AndSHA256},
  1338  			SupportedVersions: []uint16{VersionTLS13},
  1339  		}, "signature algorithms"},
  1340  
  1341  		{rsaCert, &ClientHelloInfo{
  1342  			CipherSuites:      []uint16{TLS_RSA_WITH_AES_128_GCM_SHA256},
  1343  			SignatureSchemes:  []SignatureScheme{PKCS1WithSHA1},
  1344  			SupportedVersions: []uint16{VersionTLS13, VersionTLS12},
  1345  		}, "signature algorithms"},
  1346  		{rsaCert, &ClientHelloInfo{
  1347  			CipherSuites:      []uint16{TLS_RSA_WITH_AES_128_GCM_SHA256},
  1348  			SignatureSchemes:  []SignatureScheme{PKCS1WithSHA1},
  1349  			SupportedVersions: []uint16{VersionTLS13, VersionTLS12},
  1350  			config: &Config{
  1351  				CipherSuites: []uint16{TLS_RSA_WITH_AES_128_GCM_SHA256},
  1352  				MaxVersion:   VersionTLS12,
  1353  			},
  1354  		}, ""}, // Check that mutual version selection works.
  1355  
  1356  		{ecdsaCert, &ClientHelloInfo{
  1357  			CipherSuites:      []uint16{TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256},
  1358  			SupportedCurves:   []CurveID{CurveP256},
  1359  			SupportedPoints:   []uint8{pointFormatUncompressed},
  1360  			SignatureSchemes:  []SignatureScheme{ECDSAWithP256AndSHA256},
  1361  			SupportedVersions: []uint16{VersionTLS12},
  1362  		}, ""},
  1363  		{ecdsaCert, &ClientHelloInfo{
  1364  			CipherSuites:      []uint16{TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256},
  1365  			SupportedCurves:   []CurveID{CurveP256},
  1366  			SupportedPoints:   []uint8{pointFormatUncompressed},
  1367  			SignatureSchemes:  []SignatureScheme{ECDSAWithP384AndSHA384},
  1368  			SupportedVersions: []uint16{VersionTLS12},
  1369  		}, ""}, // TLS 1.2 does not restrict curves based on the SignatureScheme.
  1370  		{ecdsaCert, &ClientHelloInfo{
  1371  			CipherSuites:      []uint16{TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256},
  1372  			SupportedCurves:   []CurveID{CurveP256},
  1373  			SupportedPoints:   []uint8{pointFormatUncompressed},
  1374  			SignatureSchemes:  nil,
  1375  			SupportedVersions: []uint16{VersionTLS12},
  1376  		}, ""}, // TLS 1.2 comes with default signature schemes.
  1377  		{ecdsaCert, &ClientHelloInfo{
  1378  			CipherSuites:      []uint16{TLS_RSA_WITH_AES_128_GCM_SHA256},
  1379  			SupportedCurves:   []CurveID{CurveP256},
  1380  			SupportedPoints:   []uint8{pointFormatUncompressed},
  1381  			SignatureSchemes:  []SignatureScheme{ECDSAWithP256AndSHA256},
  1382  			SupportedVersions: []uint16{VersionTLS12},
  1383  		}, "cipher suite"},
  1384  		{ecdsaCert, &ClientHelloInfo{
  1385  			CipherSuites:      []uint16{TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256},
  1386  			SupportedCurves:   []CurveID{CurveP256},
  1387  			SupportedPoints:   []uint8{pointFormatUncompressed},
  1388  			SignatureSchemes:  []SignatureScheme{ECDSAWithP256AndSHA256},
  1389  			SupportedVersions: []uint16{VersionTLS12},
  1390  			config: &Config{
  1391  				CipherSuites: []uint16{TLS_RSA_WITH_AES_128_GCM_SHA256},
  1392  			},
  1393  		}, "cipher suite"},
  1394  		{ecdsaCert, &ClientHelloInfo{
  1395  			CipherSuites:      []uint16{TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256},
  1396  			SupportedCurves:   []CurveID{CurveP384},
  1397  			SupportedPoints:   []uint8{pointFormatUncompressed},
  1398  			SignatureSchemes:  []SignatureScheme{ECDSAWithP256AndSHA256},
  1399  			SupportedVersions: []uint16{VersionTLS12},
  1400  		}, "certificate curve"},
  1401  		{ecdsaCert, &ClientHelloInfo{
  1402  			CipherSuites:      []uint16{TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256},
  1403  			SupportedCurves:   []CurveID{CurveP256},
  1404  			SupportedPoints:   []uint8{1},
  1405  			SignatureSchemes:  []SignatureScheme{ECDSAWithP256AndSHA256},
  1406  			SupportedVersions: []uint16{VersionTLS12},
  1407  		}, "doesn't support ECDHE"},
  1408  		{ecdsaCert, &ClientHelloInfo{
  1409  			CipherSuites:      []uint16{TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256},
  1410  			SupportedCurves:   []CurveID{CurveP256},
  1411  			SupportedPoints:   []uint8{pointFormatUncompressed},
  1412  			SignatureSchemes:  []SignatureScheme{PSSWithSHA256},
  1413  			SupportedVersions: []uint16{VersionTLS12},
  1414  		}, "signature algorithms"},
  1415  
  1416  		{ed25519Cert, &ClientHelloInfo{
  1417  			CipherSuites:      []uint16{TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256},
  1418  			SupportedCurves:   []CurveID{CurveP256}, // only relevant for ECDHE support
  1419  			SupportedPoints:   []uint8{pointFormatUncompressed},
  1420  			SignatureSchemes:  []SignatureScheme{Ed25519},
  1421  			SupportedVersions: []uint16{VersionTLS12},
  1422  		}, ""},
  1423  		{ed25519Cert, &ClientHelloInfo{
  1424  			CipherSuites:      []uint16{TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256},
  1425  			SupportedCurves:   []CurveID{CurveP256}, // only relevant for ECDHE support
  1426  			SupportedPoints:   []uint8{pointFormatUncompressed},
  1427  			SignatureSchemes:  []SignatureScheme{Ed25519},
  1428  			SupportedVersions: []uint16{VersionTLS10},
  1429  			config:            &Config{MinVersion: VersionTLS10},
  1430  		}, "doesn't support Ed25519"},
  1431  		{ed25519Cert, &ClientHelloInfo{
  1432  			CipherSuites:      []uint16{TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256},
  1433  			SupportedCurves:   []CurveID{},
  1434  			SupportedPoints:   []uint8{pointFormatUncompressed},
  1435  			SignatureSchemes:  []SignatureScheme{Ed25519},
  1436  			SupportedVersions: []uint16{VersionTLS12},
  1437  		}, "doesn't support ECDHE"},
  1438  
  1439  		{rsaCert, &ClientHelloInfo{
  1440  			CipherSuites:      []uint16{TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA},
  1441  			SupportedCurves:   []CurveID{CurveP256}, // only relevant for ECDHE support
  1442  			SupportedPoints:   []uint8{pointFormatUncompressed},
  1443  			SupportedVersions: []uint16{VersionTLS10},
  1444  			config:            &Config{MinVersion: VersionTLS10},
  1445  		}, ""},
  1446  		{rsaCert, &ClientHelloInfo{
  1447  			CipherSuites:      []uint16{TLS_RSA_WITH_AES_128_GCM_SHA256},
  1448  			SupportedVersions: []uint16{VersionTLS12},
  1449  			config: &Config{
  1450  				CipherSuites: []uint16{TLS_RSA_WITH_AES_128_GCM_SHA256},
  1451  			},
  1452  		}, ""}, // static RSA fallback
  1453  	}
  1454  	for i, tt := range tests {
  1455  		err := tt.chi.SupportsCertificate(tt.c)
  1456  		switch {
  1457  		case tt.wantErr == "" && err != nil:
  1458  			t.Errorf("%d: unexpected error: %v", i, err)
  1459  		case tt.wantErr != "" && err == nil:
  1460  			t.Errorf("%d: unexpected success", i)
  1461  		case tt.wantErr != "" && !strings.Contains(err.Error(), tt.wantErr):
  1462  			t.Errorf("%d: got error %q, expected %q", i, err, tt.wantErr)
  1463  		}
  1464  	}
  1465  }
  1466  
  1467  func TestCipherSuites(t *testing.T) {
  1468  	var lastID uint16
  1469  	for _, c := range CipherSuites() {
  1470  		if lastID > c.ID {
  1471  			t.Errorf("CipherSuites are not ordered by ID: got %#04x after %#04x", c.ID, lastID)
  1472  		} else {
  1473  			lastID = c.ID
  1474  		}
  1475  
  1476  		if c.Insecure {
  1477  			t.Errorf("%#04x: Insecure CipherSuite returned by CipherSuites()", c.ID)
  1478  		}
  1479  	}
  1480  	lastID = 0
  1481  	for _, c := range InsecureCipherSuites() {
  1482  		if lastID > c.ID {
  1483  			t.Errorf("InsecureCipherSuites are not ordered by ID: got %#04x after %#04x", c.ID, lastID)
  1484  		} else {
  1485  			lastID = c.ID
  1486  		}
  1487  
  1488  		if !c.Insecure {
  1489  			t.Errorf("%#04x: not Insecure CipherSuite returned by InsecureCipherSuites()", c.ID)
  1490  		}
  1491  	}
  1492  
  1493  	CipherSuiteByID := func(id uint16) *CipherSuite {
  1494  		for _, c := range CipherSuites() {
  1495  			if c.ID == id {
  1496  				return c
  1497  			}
  1498  		}
  1499  		for _, c := range InsecureCipherSuites() {
  1500  			if c.ID == id {
  1501  				return c
  1502  			}
  1503  		}
  1504  		return nil
  1505  	}
  1506  
  1507  	for _, c := range cipherSuites {
  1508  		cc := CipherSuiteByID(c.id)
  1509  		if cc == nil {
  1510  			t.Errorf("%#04x: no CipherSuite entry", c.id)
  1511  			continue
  1512  		}
  1513  
  1514  		if tls12Only := c.flags&suiteTLS12 != 0; tls12Only && len(cc.SupportedVersions) != 1 {
  1515  			t.Errorf("%#04x: suite is TLS 1.2 only, but SupportedVersions is %v", c.id, cc.SupportedVersions)
  1516  		} else if !tls12Only && len(cc.SupportedVersions) != 3 {
  1517  			t.Errorf("%#04x: suite TLS 1.0-1.2, but SupportedVersions is %v", c.id, cc.SupportedVersions)
  1518  		}
  1519  
  1520  		if cc.Insecure {
  1521  			if slices.Contains(defaultCipherSuites(), c.id) {
  1522  				t.Errorf("%#04x: insecure suite in default list", c.id)
  1523  			}
  1524  		} else {
  1525  			if !slices.Contains(defaultCipherSuites(), c.id) {
  1526  				t.Errorf("%#04x: secure suite not in default list", c.id)
  1527  			}
  1528  		}
  1529  
  1530  		if got := CipherSuiteName(c.id); got != cc.Name {
  1531  			t.Errorf("%#04x: unexpected CipherSuiteName: got %q, expected %q", c.id, got, cc.Name)
  1532  		}
  1533  	}
  1534  	for _, c := range cipherSuitesTLS13 {
  1535  		cc := CipherSuiteByID(c.id)
  1536  		if cc == nil {
  1537  			t.Errorf("%#04x: no CipherSuite entry", c.id)
  1538  			continue
  1539  		}
  1540  
  1541  		if cc.Insecure {
  1542  			t.Errorf("%#04x: Insecure %v, expected false", c.id, cc.Insecure)
  1543  		}
  1544  		if len(cc.SupportedVersions) != 1 || cc.SupportedVersions[0] != VersionTLS13 {
  1545  			t.Errorf("%#04x: suite is TLS 1.3 only, but SupportedVersions is %v", c.id, cc.SupportedVersions)
  1546  		}
  1547  
  1548  		if got := CipherSuiteName(c.id); got != cc.Name {
  1549  			t.Errorf("%#04x: unexpected CipherSuiteName: got %q, expected %q", c.id, got, cc.Name)
  1550  		}
  1551  	}
  1552  
  1553  	if got := CipherSuiteName(0xabc); got != "0x0ABC" {
  1554  		t.Errorf("unexpected fallback CipherSuiteName: got %q, expected 0x0ABC", got)
  1555  	}
  1556  
  1557  	if len(cipherSuitesPreferenceOrder) != len(cipherSuites) {
  1558  		t.Errorf("cipherSuitesPreferenceOrder is not the same size as cipherSuites")
  1559  	}
  1560  	if len(cipherSuitesPreferenceOrderNoAES) != len(cipherSuitesPreferenceOrder) {
  1561  		t.Errorf("cipherSuitesPreferenceOrderNoAES is not the same size as cipherSuitesPreferenceOrder")
  1562  	}
  1563  
  1564  	// Check that disabled suites are marked insecure.
  1565  	for _, badSuites := range []map[uint16]bool{disabledCipherSuites, rsaKexCiphers} {
  1566  		for id := range badSuites {
  1567  			c := CipherSuiteByID(id)
  1568  			if c == nil {
  1569  				t.Errorf("%#04x: no CipherSuite entry", id)
  1570  				continue
  1571  			}
  1572  			if !c.Insecure {
  1573  				t.Errorf("%#04x: disabled by default but not marked insecure", id)
  1574  			}
  1575  		}
  1576  	}
  1577  
  1578  	for i, prefOrder := range [][]uint16{cipherSuitesPreferenceOrder, cipherSuitesPreferenceOrderNoAES} {
  1579  		// Check that insecure and HTTP/2 bad cipher suites are at the end of
  1580  		// the preference lists.
  1581  		var sawInsecure, sawBad bool
  1582  		for _, id := range prefOrder {
  1583  			c := CipherSuiteByID(id)
  1584  			if c == nil {
  1585  				t.Errorf("%#04x: no CipherSuite entry", id)
  1586  				continue
  1587  			}
  1588  
  1589  			if c.Insecure {
  1590  				sawInsecure = true
  1591  			} else if sawInsecure {
  1592  				t.Errorf("%#04x: secure suite after insecure one(s)", id)
  1593  			}
  1594  
  1595  			if http2isBadCipher(id) {
  1596  				sawBad = true
  1597  			} else if sawBad {
  1598  				t.Errorf("%#04x: non-bad suite after bad HTTP/2 one(s)", id)
  1599  			}
  1600  		}
  1601  
  1602  		// Check that the list is sorted according to the documented criteria.
  1603  		isBetter := func(a, b uint16) int {
  1604  			aSuite, bSuite := cipherSuiteByID(a), cipherSuiteByID(b)
  1605  			aName, bName := CipherSuiteName(a), CipherSuiteName(b)
  1606  			// * < RC4
  1607  			if !strings.Contains(aName, "RC4") && strings.Contains(bName, "RC4") {
  1608  				return -1
  1609  			} else if strings.Contains(aName, "RC4") && !strings.Contains(bName, "RC4") {
  1610  				return +1
  1611  			}
  1612  			// * < CBC_SHA256
  1613  			if !strings.Contains(aName, "CBC_SHA256") && strings.Contains(bName, "CBC_SHA256") {
  1614  				return -1
  1615  			} else if strings.Contains(aName, "CBC_SHA256") && !strings.Contains(bName, "CBC_SHA256") {
  1616  				return +1
  1617  			}
  1618  			// * < 3DES
  1619  			if !strings.Contains(aName, "3DES") && strings.Contains(bName, "3DES") {
  1620  				return -1
  1621  			} else if strings.Contains(aName, "3DES") && !strings.Contains(bName, "3DES") {
  1622  				return +1
  1623  			}
  1624  			// ECDHE < *
  1625  			if aSuite.flags&suiteECDHE != 0 && bSuite.flags&suiteECDHE == 0 {
  1626  				return -1
  1627  			} else if aSuite.flags&suiteECDHE == 0 && bSuite.flags&suiteECDHE != 0 {
  1628  				return +1
  1629  			}
  1630  			// AEAD < CBC
  1631  			if aSuite.aead != nil && bSuite.aead == nil {
  1632  				return -1
  1633  			} else if aSuite.aead == nil && bSuite.aead != nil {
  1634  				return +1
  1635  			}
  1636  			// AES < ChaCha20
  1637  			if strings.Contains(aName, "AES") && strings.Contains(bName, "CHACHA20") {
  1638  				// negative for cipherSuitesPreferenceOrder
  1639  				if i == 0 {
  1640  					return -1
  1641  				} else {
  1642  					return +1
  1643  				}
  1644  			} else if strings.Contains(aName, "CHACHA20") && strings.Contains(bName, "AES") {
  1645  				// negative for cipherSuitesPreferenceOrderNoAES
  1646  				if i != 0 {
  1647  					return -1
  1648  				} else {
  1649  					return +1
  1650  				}
  1651  			}
  1652  			// AES-128 < AES-256
  1653  			if strings.Contains(aName, "AES_128") && strings.Contains(bName, "AES_256") {
  1654  				return -1
  1655  			} else if strings.Contains(aName, "AES_256") && strings.Contains(bName, "AES_128") {
  1656  				return +1
  1657  			}
  1658  			// ECDSA < RSA
  1659  			if aSuite.flags&suiteECSign != 0 && bSuite.flags&suiteECSign == 0 {
  1660  				return -1
  1661  			} else if aSuite.flags&suiteECSign == 0 && bSuite.flags&suiteECSign != 0 {
  1662  				return +1
  1663  			}
  1664  			t.Fatalf("two ciphersuites are equal by all criteria: %v and %v", aName, bName)
  1665  			panic("unreachable")
  1666  		}
  1667  		if !slices.IsSortedFunc(prefOrder, isBetter) {
  1668  			t.Error("preference order is not sorted according to the rules")
  1669  		}
  1670  	}
  1671  }
  1672  
  1673  func TestVersionName(t *testing.T) {
  1674  	if got, exp := VersionName(VersionTLS13), "TLS 1.3"; got != exp {
  1675  		t.Errorf("unexpected VersionName: got %q, expected %q", got, exp)
  1676  	}
  1677  	if got, exp := VersionName(0x12a), "0x012A"; got != exp {
  1678  		t.Errorf("unexpected fallback VersionName: got %q, expected %q", got, exp)
  1679  	}
  1680  }
  1681  
  1682  // http2isBadCipher is copied from net/http.
  1683  // TODO: if it ends up exposed somewhere, use that instead.
  1684  func http2isBadCipher(cipher uint16) bool {
  1685  	switch cipher {
  1686  	case TLS_RSA_WITH_RC4_128_SHA,
  1687  		TLS_RSA_WITH_3DES_EDE_CBC_SHA,
  1688  		TLS_RSA_WITH_AES_128_CBC_SHA,
  1689  		TLS_RSA_WITH_AES_256_CBC_SHA,
  1690  		TLS_RSA_WITH_AES_128_CBC_SHA256,
  1691  		TLS_RSA_WITH_AES_128_GCM_SHA256,
  1692  		TLS_RSA_WITH_AES_256_GCM_SHA384,
  1693  		TLS_ECDHE_ECDSA_WITH_RC4_128_SHA,
  1694  		TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA,
  1695  		TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA,
  1696  		TLS_ECDHE_RSA_WITH_RC4_128_SHA,
  1697  		TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA,
  1698  		TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,
  1699  		TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA,
  1700  		TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256,
  1701  		TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256:
  1702  		return true
  1703  	default:
  1704  		return false
  1705  	}
  1706  }
  1707  
  1708  type brokenSigner struct{ crypto.Signer }
  1709  
  1710  func (s brokenSigner) Sign(rand io.Reader, digest []byte, opts crypto.SignerOpts) (signature []byte, err error) {
  1711  	// Replace opts with opts.HashFunc(), so rsa.PSSOptions are discarded.
  1712  	return s.Signer.Sign(rand, digest, opts.HashFunc())
  1713  }
  1714  
  1715  // TestPKCS1OnlyCert uses a client certificate with a broken crypto.Signer that
  1716  // always makes PKCS #1 v1.5 signatures, so can't be used with RSA-PSS.
  1717  func TestPKCS1OnlyCert(t *testing.T) {
  1718  	clientConfig := testConfig.Clone()
  1719  	clientConfig.Certificates = []Certificate{{
  1720  		Certificate: [][]byte{testRSACertificate},
  1721  		PrivateKey:  brokenSigner{testRSAPrivateKey},
  1722  	}}
  1723  	serverConfig := testConfig.Clone()
  1724  	serverConfig.MaxVersion = VersionTLS12 // TLS 1.3 doesn't support PKCS #1 v1.5
  1725  	serverConfig.ClientAuth = RequireAnyClientCert
  1726  
  1727  	// If RSA-PSS is selected, the handshake should fail.
  1728  	if _, _, err := testHandshake(t, clientConfig, serverConfig); err == nil {
  1729  		t.Fatal("expected broken certificate to cause connection to fail")
  1730  	}
  1731  
  1732  	clientConfig.Certificates[0].SupportedSignatureAlgorithms =
  1733  		[]SignatureScheme{PKCS1WithSHA1, PKCS1WithSHA256}
  1734  
  1735  	// But if the certificate restricts supported algorithms, RSA-PSS should not
  1736  	// be selected, and the handshake should succeed.
  1737  	if _, _, err := testHandshake(t, clientConfig, serverConfig); err != nil {
  1738  		t.Error(err)
  1739  	}
  1740  }
  1741  
  1742  func TestVerifyCertificates(t *testing.T) {
  1743  	skipFIPS(t) // Test certificates not FIPS compatible.
  1744  
  1745  	// See https://go.dev/issue/31641.
  1746  	t.Run("TLSv12", func(t *testing.T) { testVerifyCertificates(t, VersionTLS12) })
  1747  	t.Run("TLSv13", func(t *testing.T) { testVerifyCertificates(t, VersionTLS13) })
  1748  }
  1749  
  1750  func testVerifyCertificates(t *testing.T, version uint16) {
  1751  	tests := []struct {
  1752  		name string
  1753  
  1754  		InsecureSkipVerify bool
  1755  		ClientAuth         ClientAuthType
  1756  		ClientCertificates bool
  1757  	}{
  1758  		{
  1759  			name: "defaults",
  1760  		},
  1761  		{
  1762  			name:               "InsecureSkipVerify",
  1763  			InsecureSkipVerify: true,
  1764  		},
  1765  		{
  1766  			name:       "RequestClientCert with no certs",
  1767  			ClientAuth: RequestClientCert,
  1768  		},
  1769  		{
  1770  			name:               "RequestClientCert with certs",
  1771  			ClientAuth:         RequestClientCert,
  1772  			ClientCertificates: true,
  1773  		},
  1774  		{
  1775  			name:               "RequireAnyClientCert",
  1776  			ClientAuth:         RequireAnyClientCert,
  1777  			ClientCertificates: true,
  1778  		},
  1779  		{
  1780  			name:       "VerifyClientCertIfGiven with no certs",
  1781  			ClientAuth: VerifyClientCertIfGiven,
  1782  		},
  1783  		{
  1784  			name:               "VerifyClientCertIfGiven with certs",
  1785  			ClientAuth:         VerifyClientCertIfGiven,
  1786  			ClientCertificates: true,
  1787  		},
  1788  		{
  1789  			name:               "RequireAndVerifyClientCert",
  1790  			ClientAuth:         RequireAndVerifyClientCert,
  1791  			ClientCertificates: true,
  1792  		},
  1793  	}
  1794  
  1795  	issuer, err := x509.ParseCertificate(testRSACertificateIssuer)
  1796  	if err != nil {
  1797  		t.Fatal(err)
  1798  	}
  1799  	rootCAs := x509.NewCertPool()
  1800  	rootCAs.AddCert(issuer)
  1801  
  1802  	for _, test := range tests {
  1803  		test := test
  1804  		t.Run(test.name, func(t *testing.T) {
  1805  			t.Parallel()
  1806  
  1807  			var serverVerifyConnection, clientVerifyConnection bool
  1808  			var serverVerifyPeerCertificates, clientVerifyPeerCertificates bool
  1809  
  1810  			clientConfig := testConfig.Clone()
  1811  			clientConfig.Time = testTime
  1812  			clientConfig.MaxVersion = version
  1813  			clientConfig.MinVersion = version
  1814  			clientConfig.RootCAs = rootCAs
  1815  			clientConfig.ServerName = "example.golang"
  1816  			clientConfig.ClientSessionCache = NewLRUClientSessionCache(1)
  1817  			serverConfig := clientConfig.Clone()
  1818  			serverConfig.ClientCAs = rootCAs
  1819  
  1820  			clientConfig.VerifyConnection = func(cs ConnectionState) error {
  1821  				clientVerifyConnection = true
  1822  				return nil
  1823  			}
  1824  			clientConfig.VerifyPeerCertificate = func(rawCerts [][]byte, verifiedChains [][]*x509.Certificate) error {
  1825  				clientVerifyPeerCertificates = true
  1826  				return nil
  1827  			}
  1828  			serverConfig.VerifyConnection = func(cs ConnectionState) error {
  1829  				serverVerifyConnection = true
  1830  				return nil
  1831  			}
  1832  			serverConfig.VerifyPeerCertificate = func(rawCerts [][]byte, verifiedChains [][]*x509.Certificate) error {
  1833  				serverVerifyPeerCertificates = true
  1834  				return nil
  1835  			}
  1836  
  1837  			clientConfig.InsecureSkipVerify = test.InsecureSkipVerify
  1838  			serverConfig.ClientAuth = test.ClientAuth
  1839  			if !test.ClientCertificates {
  1840  				clientConfig.Certificates = nil
  1841  			}
  1842  
  1843  			if _, _, err := testHandshake(t, clientConfig, serverConfig); err != nil {
  1844  				t.Fatal(err)
  1845  			}
  1846  
  1847  			want := serverConfig.ClientAuth != NoClientCert
  1848  			if serverVerifyPeerCertificates != want {
  1849  				t.Errorf("VerifyPeerCertificates on the server: got %v, want %v",
  1850  					serverVerifyPeerCertificates, want)
  1851  			}
  1852  			if !clientVerifyPeerCertificates {
  1853  				t.Errorf("VerifyPeerCertificates not called on the client")
  1854  			}
  1855  			if !serverVerifyConnection {
  1856  				t.Error("VerifyConnection did not get called on the server")
  1857  			}
  1858  			if !clientVerifyConnection {
  1859  				t.Error("VerifyConnection did not get called on the client")
  1860  			}
  1861  
  1862  			serverVerifyPeerCertificates, clientVerifyPeerCertificates = false, false
  1863  			serverVerifyConnection, clientVerifyConnection = false, false
  1864  			cs, _, err := testHandshake(t, clientConfig, serverConfig)
  1865  			if err != nil {
  1866  				t.Fatal(err)
  1867  			}
  1868  			if !cs.DidResume {
  1869  				t.Error("expected resumption")
  1870  			}
  1871  
  1872  			if serverVerifyPeerCertificates {
  1873  				t.Error("VerifyPeerCertificates got called on the server on resumption")
  1874  			}
  1875  			if clientVerifyPeerCertificates {
  1876  				t.Error("VerifyPeerCertificates got called on the client on resumption")
  1877  			}
  1878  			if !serverVerifyConnection {
  1879  				t.Error("VerifyConnection did not get called on the server on resumption")
  1880  			}
  1881  			if !clientVerifyConnection {
  1882  				t.Error("VerifyConnection did not get called on the client on resumption")
  1883  			}
  1884  		})
  1885  	}
  1886  }
  1887  
  1888  func TestHandshakeMLKEM(t *testing.T) {
  1889  	skipFIPS(t) // No X25519MLKEM768 in FIPS
  1890  	var tests = []struct {
  1891  		name                string
  1892  		clientConfig        func(*Config)
  1893  		serverConfig        func(*Config)
  1894  		preparation         func(*testing.T)
  1895  		expectClientSupport bool
  1896  		expectMLKEM         bool
  1897  		expectHRR           bool
  1898  	}{
  1899  		{
  1900  			name:                "Default",
  1901  			expectClientSupport: true,
  1902  			expectMLKEM:         true,
  1903  			expectHRR:           false,
  1904  		},
  1905  		{
  1906  			name: "ClientCurvePreferences",
  1907  			clientConfig: func(config *Config) {
  1908  				config.CurvePreferences = []CurveID{X25519}
  1909  			},
  1910  			expectClientSupport: false,
  1911  		},
  1912  		{
  1913  			name: "ServerCurvePreferencesX25519",
  1914  			serverConfig: func(config *Config) {
  1915  				config.CurvePreferences = []CurveID{X25519}
  1916  			},
  1917  			expectClientSupport: true,
  1918  			expectMLKEM:         false,
  1919  			expectHRR:           false,
  1920  		},
  1921  		{
  1922  			name: "ServerCurvePreferencesHRR",
  1923  			serverConfig: func(config *Config) {
  1924  				config.CurvePreferences = []CurveID{CurveP256}
  1925  			},
  1926  			expectClientSupport: true,
  1927  			expectMLKEM:         false,
  1928  			expectHRR:           true,
  1929  		},
  1930  		{
  1931  			name: "ClientMLKEMOnly",
  1932  			clientConfig: func(config *Config) {
  1933  				config.CurvePreferences = []CurveID{X25519MLKEM768}
  1934  			},
  1935  			expectClientSupport: true,
  1936  			expectMLKEM:         true,
  1937  		},
  1938  		{
  1939  			name: "ClientSortedCurvePreferences",
  1940  			clientConfig: func(config *Config) {
  1941  				config.CurvePreferences = []CurveID{CurveP256, X25519MLKEM768}
  1942  			},
  1943  			expectClientSupport: true,
  1944  			expectMLKEM:         true,
  1945  		},
  1946  		{
  1947  			name: "ClientTLSv12",
  1948  			clientConfig: func(config *Config) {
  1949  				config.MaxVersion = VersionTLS12
  1950  			},
  1951  			expectClientSupport: false,
  1952  		},
  1953  		{
  1954  			name: "ServerTLSv12",
  1955  			serverConfig: func(config *Config) {
  1956  				config.MaxVersion = VersionTLS12
  1957  			},
  1958  			expectClientSupport: true,
  1959  			expectMLKEM:         false,
  1960  		},
  1961  		{
  1962  			name: "GODEBUG",
  1963  			preparation: func(t *testing.T) {
  1964  				t.Setenv("GODEBUG", "tlsmlkem=0")
  1965  			},
  1966  			expectClientSupport: false,
  1967  		},
  1968  	}
  1969  
  1970  	baseConfig := testConfig.Clone()
  1971  	baseConfig.CurvePreferences = nil
  1972  	for _, test := range tests {
  1973  		t.Run(test.name, func(t *testing.T) {
  1974  			if test.preparation != nil {
  1975  				test.preparation(t)
  1976  			} else {
  1977  				t.Parallel()
  1978  			}
  1979  			serverConfig := baseConfig.Clone()
  1980  			if test.serverConfig != nil {
  1981  				test.serverConfig(serverConfig)
  1982  			}
  1983  			serverConfig.GetConfigForClient = func(hello *ClientHelloInfo) (*Config, error) {
  1984  				if !test.expectClientSupport && slices.Contains(hello.SupportedCurves, X25519MLKEM768) {
  1985  					return nil, errors.New("client supports X25519MLKEM768")
  1986  				} else if test.expectClientSupport && !slices.Contains(hello.SupportedCurves, X25519MLKEM768) {
  1987  					return nil, errors.New("client does not support X25519MLKEM768")
  1988  				}
  1989  				return nil, nil
  1990  			}
  1991  			clientConfig := baseConfig.Clone()
  1992  			if test.clientConfig != nil {
  1993  				test.clientConfig(clientConfig)
  1994  			}
  1995  			ss, cs, err := testHandshake(t, clientConfig, serverConfig)
  1996  			if err != nil {
  1997  				t.Fatal(err)
  1998  			}
  1999  			if test.expectMLKEM {
  2000  				if ss.testingOnlyCurveID != X25519MLKEM768 {
  2001  					t.Errorf("got CurveID %v (server), expected %v", ss.testingOnlyCurveID, X25519MLKEM768)
  2002  				}
  2003  				if cs.testingOnlyCurveID != X25519MLKEM768 {
  2004  					t.Errorf("got CurveID %v (client), expected %v", cs.testingOnlyCurveID, X25519MLKEM768)
  2005  				}
  2006  			} else {
  2007  				if ss.testingOnlyCurveID == X25519MLKEM768 {
  2008  					t.Errorf("got CurveID %v (server), expected not X25519MLKEM768", ss.testingOnlyCurveID)
  2009  				}
  2010  				if cs.testingOnlyCurveID == X25519MLKEM768 {
  2011  					t.Errorf("got CurveID %v (client), expected not X25519MLKEM768", cs.testingOnlyCurveID)
  2012  				}
  2013  			}
  2014  			if test.expectHRR {
  2015  				if !ss.testingOnlyDidHRR {
  2016  					t.Error("server did not use HRR")
  2017  				}
  2018  				if !cs.testingOnlyDidHRR {
  2019  					t.Error("client did not use HRR")
  2020  				}
  2021  			} else {
  2022  				if ss.testingOnlyDidHRR {
  2023  					t.Error("server used HRR")
  2024  				}
  2025  				if cs.testingOnlyDidHRR {
  2026  					t.Error("client used HRR")
  2027  				}
  2028  			}
  2029  		})
  2030  	}
  2031  }
  2032  
  2033  func TestX509KeyPairPopulateCertificate(t *testing.T) {
  2034  	key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
  2035  	if err != nil {
  2036  		t.Fatal(err)
  2037  	}
  2038  	keyDER, err := x509.MarshalPKCS8PrivateKey(key)
  2039  	if err != nil {
  2040  		t.Fatal(err)
  2041  	}
  2042  	keyPEM := pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: keyDER})
  2043  	tmpl := &x509.Certificate{
  2044  		SerialNumber: big.NewInt(1),
  2045  		Subject:      pkix.Name{CommonName: "test"},
  2046  	}
  2047  	certDER, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, key.Public(), key)
  2048  	if err != nil {
  2049  		t.Fatal(err)
  2050  	}
  2051  	certPEM := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: certDER})
  2052  
  2053  	t.Run("x509keypairleaf=0", func(t *testing.T) {
  2054  		t.Setenv("GODEBUG", "x509keypairleaf=0")
  2055  		cert, err := X509KeyPair(certPEM, keyPEM)
  2056  		if err != nil {
  2057  			t.Fatal(err)
  2058  		}
  2059  		if cert.Leaf != nil {
  2060  			t.Fatal("Leaf should not be populated")
  2061  		}
  2062  	})
  2063  	t.Run("x509keypairleaf=1", func(t *testing.T) {
  2064  		t.Setenv("GODEBUG", "x509keypairleaf=1")
  2065  		cert, err := X509KeyPair(certPEM, keyPEM)
  2066  		if err != nil {
  2067  			t.Fatal(err)
  2068  		}
  2069  		if cert.Leaf == nil {
  2070  			t.Fatal("Leaf should be populated")
  2071  		}
  2072  	})
  2073  	t.Run("GODEBUG unset", func(t *testing.T) {
  2074  		cert, err := X509KeyPair(certPEM, keyPEM)
  2075  		if err != nil {
  2076  			t.Fatal(err)
  2077  		}
  2078  		if cert.Leaf == nil {
  2079  			t.Fatal("Leaf should be populated")
  2080  		}
  2081  	})
  2082  }
  2083  
  2084  func TestEarlyLargeCertMsg(t *testing.T) {
  2085  	client, server := localPipe(t)
  2086  
  2087  	go func() {
  2088  		if _, err := client.Write([]byte{byte(recordTypeHandshake), 3, 4, 0, 4, typeCertificate, 1, 255, 255}); err != nil {
  2089  			t.Log(err)
  2090  		}
  2091  	}()
  2092  
  2093  	expectedErr := "tls: handshake message of length 131071 bytes exceeds maximum of 65536 bytes"
  2094  	servConn := Server(server, testConfig)
  2095  	err := servConn.Handshake()
  2096  	if err == nil {
  2097  		t.Fatal("unexpected success")
  2098  	}
  2099  	if err.Error() != expectedErr {
  2100  		t.Fatalf("unexpected error: got %q, want %q", err, expectedErr)
  2101  	}
  2102  }
  2103  
  2104  func TestLargeCertMsg(t *testing.T) {
  2105  	k, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
  2106  	if err != nil {
  2107  		t.Fatal(err)
  2108  	}
  2109  	tmpl := &x509.Certificate{
  2110  		SerialNumber: big.NewInt(1),
  2111  		Subject:      pkix.Name{CommonName: "test"},
  2112  		ExtraExtensions: []pkix.Extension{
  2113  			{
  2114  				Id: asn1.ObjectIdentifier{1, 2, 3},
  2115  				// Ballast to inflate the certificate beyond the
  2116  				// regular handshake record size.
  2117  				Value: make([]byte, 65536),
  2118  			},
  2119  		},
  2120  	}
  2121  	cert, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, k.Public(), k)
  2122  	if err != nil {
  2123  		t.Fatal(err)
  2124  	}
  2125  
  2126  	clientConfig, serverConfig := testConfig.Clone(), testConfig.Clone()
  2127  	clientConfig.InsecureSkipVerify = true
  2128  	serverConfig.Certificates = []Certificate{
  2129  		{
  2130  			Certificate: [][]byte{cert},
  2131  			PrivateKey:  k,
  2132  		},
  2133  	}
  2134  	if _, _, err := testHandshake(t, clientConfig, serverConfig); err != nil {
  2135  		t.Fatalf("unexpected failure: %s", err)
  2136  	}
  2137  }
  2138  
  2139  func TestECH(t *testing.T) {
  2140  	k, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
  2141  	if err != nil {
  2142  		t.Fatal(err)
  2143  	}
  2144  	tmpl := &x509.Certificate{
  2145  		SerialNumber: big.NewInt(1),
  2146  		DNSNames:     []string{"public.example"},
  2147  		NotBefore:    time.Now().Add(-time.Hour),
  2148  		NotAfter:     time.Now().Add(time.Hour),
  2149  	}
  2150  	publicCertDER, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, k.Public(), k)
  2151  	if err != nil {
  2152  		t.Fatal(err)
  2153  	}
  2154  	publicCert, err := x509.ParseCertificate(publicCertDER)
  2155  	if err != nil {
  2156  		t.Fatal(err)
  2157  	}
  2158  	tmpl.DNSNames[0] = "secret.example"
  2159  	secretCertDER, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, k.Public(), k)
  2160  	if err != nil {
  2161  		t.Fatal(err)
  2162  	}
  2163  	secretCert, err := x509.ParseCertificate(secretCertDER)
  2164  	if err != nil {
  2165  		t.Fatal(err)
  2166  	}
  2167  
  2168  	marshalECHConfig := func(id uint8, pubKey []byte, publicName string, maxNameLen uint8) []byte {
  2169  		builder := cryptobyte.NewBuilder(nil)
  2170  		builder.AddUint16(extensionEncryptedClientHello)
  2171  		builder.AddUint16LengthPrefixed(func(builder *cryptobyte.Builder) {
  2172  			builder.AddUint8(id)
  2173  			builder.AddUint16(hpke.DHKEM_X25519_HKDF_SHA256) // The only DHKEM we support
  2174  			builder.AddUint16LengthPrefixed(func(builder *cryptobyte.Builder) {
  2175  				builder.AddBytes(pubKey)
  2176  			})
  2177  			builder.AddUint16LengthPrefixed(func(builder *cryptobyte.Builder) {
  2178  				for _, aeadID := range sortedSupportedAEADs {
  2179  					builder.AddUint16(hpke.KDF_HKDF_SHA256) // The only KDF we support
  2180  					builder.AddUint16(aeadID)
  2181  				}
  2182  			})
  2183  			builder.AddUint8(maxNameLen)
  2184  			builder.AddUint8LengthPrefixed(func(builder *cryptobyte.Builder) {
  2185  				builder.AddBytes([]byte(publicName))
  2186  			})
  2187  			builder.AddUint16(0) // extensions
  2188  		})
  2189  
  2190  		return builder.BytesOrPanic()
  2191  	}
  2192  
  2193  	echKey, err := ecdh.X25519().GenerateKey(rand.Reader)
  2194  	if err != nil {
  2195  		t.Fatal(err)
  2196  	}
  2197  
  2198  	echConfig := marshalECHConfig(123, echKey.PublicKey().Bytes(), "public.example", 32)
  2199  
  2200  	builder := cryptobyte.NewBuilder(nil)
  2201  	builder.AddUint16LengthPrefixed(func(builder *cryptobyte.Builder) {
  2202  		builder.AddBytes(echConfig)
  2203  	})
  2204  	echConfigList := builder.BytesOrPanic()
  2205  
  2206  	clientConfig, serverConfig := testConfig.Clone(), testConfig.Clone()
  2207  	clientConfig.InsecureSkipVerify = false
  2208  	clientConfig.Rand = rand.Reader
  2209  	clientConfig.Time = nil
  2210  	clientConfig.MinVersion = VersionTLS13
  2211  	clientConfig.ServerName = "secret.example"
  2212  	clientConfig.RootCAs = x509.NewCertPool()
  2213  	clientConfig.RootCAs.AddCert(secretCert)
  2214  	clientConfig.RootCAs.AddCert(publicCert)
  2215  	clientConfig.EncryptedClientHelloConfigList = echConfigList
  2216  	serverConfig.InsecureSkipVerify = false
  2217  	serverConfig.Rand = rand.Reader
  2218  	serverConfig.Time = nil
  2219  	serverConfig.MinVersion = VersionTLS13
  2220  	serverConfig.ServerName = "public.example"
  2221  	serverConfig.Certificates = []Certificate{
  2222  		{Certificate: [][]byte{publicCertDER}, PrivateKey: k},
  2223  		{Certificate: [][]byte{secretCertDER}, PrivateKey: k},
  2224  	}
  2225  	serverConfig.EncryptedClientHelloKeys = []EncryptedClientHelloKey{
  2226  		{Config: echConfig, PrivateKey: echKey.Bytes(), SendAsRetry: true},
  2227  	}
  2228  
  2229  	ss, cs, err := testHandshake(t, clientConfig, serverConfig)
  2230  	if err != nil {
  2231  		t.Fatalf("unexpected failure: %s", err)
  2232  	}
  2233  	if !ss.ECHAccepted {
  2234  		t.Fatal("server ConnectionState shows ECH not accepted")
  2235  	}
  2236  	if !cs.ECHAccepted {
  2237  		t.Fatal("client ConnectionState shows ECH not accepted")
  2238  	}
  2239  	if cs.ServerName != "secret.example" || ss.ServerName != "secret.example" {
  2240  		t.Fatalf("unexpected ConnectionState.ServerName, want %q, got server:%q, client: %q", "secret.example", ss.ServerName, cs.ServerName)
  2241  	}
  2242  	if len(cs.VerifiedChains) != 1 {
  2243  		t.Fatal("unexpect number of certificate chains")
  2244  	}
  2245  	if len(cs.VerifiedChains[0]) != 1 {
  2246  		t.Fatal("unexpect number of certificates")
  2247  	}
  2248  	if !cs.VerifiedChains[0][0].Equal(secretCert) {
  2249  		t.Fatal("unexpected certificate")
  2250  	}
  2251  }
  2252  

View as plain text