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.
27 var rsaCertPEM = `-----BEGIN CERTIFICATE-----
28 MIIB0zCCAX2gAwIBAgIJAI/M7BYjwB+uMA0GCSqGSIb3DQEBBQUAMEUxCzAJBgNV
29 BAYTAkFVMRMwEQYDVQQIDApTb21lLVN0YXRlMSEwHwYDVQQKDBhJbnRlcm5ldCBX
30 aWRnaXRzIFB0eSBMdGQwHhcNMTIwOTEyMjE1MjAyWhcNMTUwOTEyMjE1MjAyWjBF
31 MQswCQYDVQQGEwJBVTETMBEGA1UECAwKU29tZS1TdGF0ZTEhMB8GA1UECgwYSW50
32 ZXJuZXQgV2lkZ2l0cyBQdHkgTHRkMFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBANLJ
33 hPHhITqQbPklG3ibCVxwGMRfp/v4XqhfdQHdcVfHap6NQ5Wok/4xIA+ui35/MmNa
34 rtNuC+BdZ1tMuVCPFZcCAwEAAaNQME4wHQYDVR0OBBYEFJvKs8RfJaXTH08W+SGv
35 zQyKn0H8MB8GA1UdIwQYMBaAFJvKs8RfJaXTH08W+SGvzQyKn0H8MAwGA1UdEwQF
36 MAMBAf8wDQYJKoZIhvcNAQEFBQADQQBJlffJHybjDGxRMqaRmDhX0+6v02TUKZsW
37 r5QuVbpQhH6u+0UgcW0jp9QwpxoPTLTWGXEWBBBurxFwiCBhkQ+V
38 -----END CERTIFICATE-----
41 var rsaKeyPEM = testingKey(`-----BEGIN RSA TESTING KEY-----
42 MIIBOwIBAAJBANLJhPHhITqQbPklG3ibCVxwGMRfp/v4XqhfdQHdcVfHap6NQ5Wo
43 k/4xIA+ui35/MmNartNuC+BdZ1tMuVCPFZcCAwEAAQJAEJ2N+zsR0Xn8/Q6twa4G
44 6OB1M1WO+k+ztnX/1SvNeWu8D6GImtupLTYgjZcHufykj09jiHmjHx8u8ZZB/o1N
45 MQIhAPW+eyZo7ay3lMz1V01WVjNKK9QSn1MJlb06h/LuYv9FAiEA25WPedKgVyCW
46 SmUwbPw8fnTcpqDWE3yTO3vKcebqMSsCIBF3UmVue8YU3jybC3NxuXq3wNm34R8T
47 xVLHwDXh/6NJAiEAl2oHGGLz64BuAfjKrqwz7qMYr9HCLIe/YsoWq/olzScCIQDi
48 D2lWusoe2/nEqfDVVWGWlyJ7yOmqaVm/iNUN9B2N2g==
49 -----END RSA TESTING KEY-----
52 // keyPEM is the same as rsaKeyPEM, but declares itself as just
53 // "PRIVATE KEY", not "RSA PRIVATE KEY". https://golang.org/issue/4477
54 var keyPEM = testingKey(`-----BEGIN TESTING KEY-----
55 MIIBOwIBAAJBANLJhPHhITqQbPklG3ibCVxwGMRfp/v4XqhfdQHdcVfHap6NQ5Wo
56 k/4xIA+ui35/MmNartNuC+BdZ1tMuVCPFZcCAwEAAQJAEJ2N+zsR0Xn8/Q6twa4G
57 6OB1M1WO+k+ztnX/1SvNeWu8D6GImtupLTYgjZcHufykj09jiHmjHx8u8ZZB/o1N
58 MQIhAPW+eyZo7ay3lMz1V01WVjNKK9QSn1MJlb06h/LuYv9FAiEA25WPedKgVyCW
59 SmUwbPw8fnTcpqDWE3yTO3vKcebqMSsCIBF3UmVue8YU3jybC3NxuXq3wNm34R8T
60 xVLHwDXh/6NJAiEAl2oHGGLz64BuAfjKrqwz7qMYr9HCLIe/YsoWq/olzScCIQDi
61 D2lWusoe2/nEqfDVVWGWlyJ7yOmqaVm/iNUN9B2N2g==
62 -----END TESTING KEY-----
65 var ecdsaCertPEM = `-----BEGIN CERTIFICATE-----
66 MIIB/jCCAWICCQDscdUxw16XFDAJBgcqhkjOPQQBMEUxCzAJBgNVBAYTAkFVMRMw
67 EQYDVQQIEwpTb21lLVN0YXRlMSEwHwYDVQQKExhJbnRlcm5ldCBXaWRnaXRzIFB0
68 eSBMdGQwHhcNMTIxMTE0MTI0MDQ4WhcNMTUxMTE0MTI0MDQ4WjBFMQswCQYDVQQG
69 EwJBVTETMBEGA1UECBMKU29tZS1TdGF0ZTEhMB8GA1UEChMYSW50ZXJuZXQgV2lk
70 Z2l0cyBQdHkgTHRkMIGbMBAGByqGSM49AgEGBSuBBAAjA4GGAAQBY9+my9OoeSUR
71 lDQdV/x8LsOuLilthhiS1Tz4aGDHIPwC1mlvnf7fg5lecYpMCrLLhauAc1UJXcgl
72 01xoLuzgtAEAgv2P/jgytzRSpUYvgLBt1UA0leLYBy6mQQbrNEuqT3INapKIcUv8
73 XxYP0xMEUksLPq6Ca+CRSqTtrd/23uTnapkwCQYHKoZIzj0EAQOBigAwgYYCQXJo
74 A7Sl2nLVf+4Iu/tAX/IF4MavARKC4PPHK3zfuGfPR3oCCcsAoz3kAzOeijvd0iXb
75 H5jBImIxPL4WxQNiBTexAkF8D1EtpYuWdlVQ80/h/f4pBcGiXPqX5h2PQSQY7hP1
76 +jwM1FGS4fREIOvlBYr/SzzQRtwrvrzGYxDEDbsC0ZGRnA==
77 -----END CERTIFICATE-----
80 var ecdsaKeyPEM = testingKey(`-----BEGIN EC PARAMETERS-----
82 -----END EC PARAMETERS-----
83 -----BEGIN EC TESTING KEY-----
84 MIHcAgEBBEIBrsoKp0oqcv6/JovJJDoDVSGWdirrkgCWxrprGlzB9o0X8fV675X0
85 NwuBenXFfeZvVcwluO7/Q9wkYoPd/t3jGImgBwYFK4EEACOhgYkDgYYABAFj36bL
86 06h5JRGUNB1X/Hwuw64uKW2GGJLVPPhoYMcg/ALWaW+d/t+DmV5xikwKssuFq4Bz
87 VQldyCXTXGgu7OC0AQCC/Y/+ODK3NFKlRi+AsG3VQDSV4tgHLqZBBus0S6pPcg1q
88 kohxS/xfFg/TEwRSSws+roJr4JFKpO2t3/be5OdqmQ==
89 -----END EC TESTING KEY-----
92 var keyPairTests = []struct {
97 {"ECDSA", ecdsaCertPEM, ecdsaKeyPEM},
98 {"RSA", rsaCertPEM, rsaKeyPEM},
99 {"RSA-untyped", rsaCertPEM, keyPEM}, // golang.org/issue/4477
102 func TestX509KeyPair(t *testing.T) {
105 for _, test := range keyPairTests {
106 pem = []byte(test.cert + test.key)
107 if _, err := X509KeyPair(pem, pem); err != nil {
108 t.Errorf("Failed to load %s cert followed by %s key: %s", test.algo, test.algo, err)
110 pem = []byte(test.key + test.cert)
111 if _, err := X509KeyPair(pem, pem); err != nil {
112 t.Errorf("Failed to load %s key followed by %s cert: %s", test.algo, test.algo, err)
117 func TestX509KeyPairErrors(t *testing.T) {
118 _, err := X509KeyPair([]byte(rsaKeyPEM), []byte(rsaCertPEM))
120 t.Fatalf("X509KeyPair didn't return an error when arguments were switched")
122 if subStr := "been switched"; !strings.Contains(err.Error(), subStr) {
123 t.Fatalf("Expected %q in the error when switching arguments to X509KeyPair, but the error was %q", subStr, err)
126 _, err = X509KeyPair([]byte(rsaCertPEM), []byte(rsaCertPEM))
128 t.Fatalf("X509KeyPair didn't return an error when both arguments were certificates")
130 if subStr := "certificate"; !strings.Contains(err.Error(), subStr) {
131 t.Fatalf("Expected %q in the error when both arguments to X509KeyPair were certificates, but the error was %q", subStr, err)
134 const nonsensePEM = `
135 -----BEGIN NONSENSE-----
137 -----END NONSENSE-----
140 _, err = X509KeyPair([]byte(nonsensePEM), []byte(nonsensePEM))
142 t.Fatalf("X509KeyPair didn't return an error when both arguments were nonsense")
144 if subStr := "NONSENSE"; !strings.Contains(err.Error(), subStr) {
145 t.Fatalf("Expected %q in the error when both arguments to X509KeyPair were nonsense, but the error was %q", subStr, err)
149 func TestX509MixedKeyPair(t *testing.T) {
150 if _, err := X509KeyPair([]byte(rsaCertPEM), []byte(ecdsaKeyPEM)); err == nil {
151 t.Error("Load of RSA certificate succeeded with ECDSA private key")
153 if _, err := X509KeyPair([]byte(ecdsaCertPEM), []byte(rsaKeyPEM)); err == nil {
154 t.Error("Load of ECDSA certificate succeeded with RSA private key")
158 func newLocalListener(t testing.TB) net.Listener {
159 ln, err := net.Listen("tcp", "127.0.0.1:0")
161 ln, err = net.Listen("tcp6", "[::1]:0")
169 func TestDialTimeout(t *testing.T) {
171 t.Skip("skipping in short mode")
173 listener := newLocalListener(t)
175 addr := listener.Addr().String()
176 defer listener.Close()
178 complete := make(chan bool)
179 defer close(complete)
182 conn, err := listener.Accept()
191 dialer := &net.Dialer{
192 Timeout: 10 * time.Millisecond,
196 if _, err = DialWithDialer(dialer, "tcp", addr, nil); err == nil {
197 t.Fatal("DialWithTimeout completed successfully")
200 if !isTimeoutError(err) {
201 t.Errorf("resulting error not a timeout: %v\nType %T: %#v", err, err, err)
205 func TestDeadlineOnWrite(t *testing.T) {
207 t.Skip("skipping in short mode")
210 ln := newLocalListener(t)
213 srvCh := make(chan *Conn, 1)
216 sconn, err := ln.Accept()
221 srv := Server(sconn, testConfig.Clone())
222 if err := srv.Handshake(); err != nil {
229 clientConfig := testConfig.Clone()
230 clientConfig.MaxVersion = VersionTLS12
231 conn, err := Dial("tcp", ln.Addr().String(), clientConfig)
242 // Make sure the client/server is setup correctly and is able to do a typical Write/Read
243 buf := make([]byte, 6)
244 if _, err := srv.Write([]byte("foobar")); err != nil {
245 t.Errorf("Write err: %v", err)
247 if n, err := conn.Read(buf); n != 6 || err != nil || string(buf) != "foobar" {
248 t.Errorf("Read = %d, %v, data %q; want 6, nil, foobar", n, err, buf)
251 // Set a deadline which should cause Write to timeout
252 if err = srv.SetDeadline(time.Now()); err != nil {
253 t.Fatalf("SetDeadline(time.Now()) err: %v", err)
255 if _, err = srv.Write([]byte("should fail")); err == nil {
256 t.Fatal("Write should have timed out")
259 // Clear deadline and make sure it still times out
260 if err = srv.SetDeadline(time.Time{}); err != nil {
261 t.Fatalf("SetDeadline(time.Time{}) err: %v", err)
263 if _, err = srv.Write([]byte("This connection is permanently broken")); err == nil {
264 t.Fatal("Write which previously failed should still time out")
268 if ne := err.(net.Error); ne.Temporary() != false {
269 t.Error("Write timed out but incorrectly classified the error as Temporary")
271 if !isTimeoutError(err) {
272 t.Error("Write timed out but did not classify the error as a Timeout")
276 type readerFunc func([]byte) (int, error)
278 func (f readerFunc) Read(b []byte) (int, error) { return f(b) }
280 // TestDialer tests that tls.Dialer.DialContext can abort in the middle of a handshake.
281 // (The other cases are all handled by the existing dial tests in this package, which
282 // all also flow through the same code shared code paths)
283 func TestDialer(t *testing.T) {
284 ln := newLocalListener(t)
287 unblockServer := make(chan struct{}) // close-only
288 defer close(unblockServer)
290 conn, err := ln.Accept()
298 ctx, cancel := context.WithCancel(context.Background())
299 d := Dialer{Config: &Config{
300 Rand: readerFunc(func(b []byte) (n int, err error) {
301 // By the time crypto/tls wants randomness, that means it has a TCP
302 // connection, so we're past the Dialer's dial and now blocked
303 // in a handshake. Cancel our context and see if we get unstuck.
304 // (Our TCP listener above never reads or writes, so the Handshake
305 // would otherwise be stuck forever)
311 _, err := d.DialContext(ctx, "tcp", ln.Addr().String())
312 if err != context.Canceled {
313 t.Errorf("err = %v; want context.Canceled", err)
317 func isTimeoutError(err error) bool {
318 if ne, ok := err.(net.Error); ok {
324 // tests that Conn.Read returns (non-zero, io.EOF) instead of
325 // (non-zero, nil) when a Close (alertCloseNotify) is sitting right
326 // behind the application data in the buffer.
327 func TestConnReadNonzeroAndEOF(t *testing.T) {
328 // This test is racy: it assumes that after a write to a
329 // localhost TCP connection, the peer TCP connection can
330 // immediately read it. Because it's racy, we skip this test
331 // in short mode, and then retry it several times with an
332 // increasing sleep in between our final write (via srv.Close
333 // below) and the following read.
335 t.Skip("skipping in short mode")
338 for delay := time.Millisecond; delay <= 64*time.Millisecond; delay *= 2 {
339 if err = testConnReadNonzeroAndEOF(t, delay); err == nil {
346 func testConnReadNonzeroAndEOF(t *testing.T, delay time.Duration) error {
347 ln := newLocalListener(t)
350 srvCh := make(chan *Conn, 1)
353 sconn, err := ln.Accept()
359 serverConfig := testConfig.Clone()
360 srv := Server(sconn, serverConfig)
361 if err := srv.Handshake(); err != nil {
362 serr = fmt.Errorf("handshake: %v", err)
369 clientConfig := testConfig.Clone()
370 // In TLS 1.3, alerts are encrypted and disguised as application data, so
371 // the opportunistic peek won't work.
372 clientConfig.MaxVersion = VersionTLS12
373 conn, err := Dial("tcp", ln.Addr().String(), clientConfig)
384 buf := make([]byte, 6)
386 srv.Write([]byte("foobar"))
387 n, err := conn.Read(buf)
388 if n != 6 || err != nil || string(buf) != "foobar" {
389 return fmt.Errorf("Read = %d, %v, data %q; want 6, nil, foobar", n, err, buf)
392 srv.Write([]byte("abcdef"))
395 n, err = conn.Read(buf)
396 if n != 6 || string(buf) != "abcdef" {
397 return fmt.Errorf("Read = %d, buf= %q; want 6, abcdef", n, buf)
400 return fmt.Errorf("Second Read error = %v; want io.EOF", err)
405 func TestTLSUniqueMatches(t *testing.T) {
406 ln := newLocalListener(t)
409 serverTLSUniques := make(chan []byte)
410 parentDone := make(chan struct{})
411 childDone := make(chan struct{})
412 defer close(parentDone)
414 defer close(childDone)
415 for i := 0; i < 2; i++ {
416 sconn, err := ln.Accept()
421 serverConfig := testConfig.Clone()
422 serverConfig.MaxVersion = VersionTLS12 // TLSUnique is not defined in TLS 1.3
423 srv := Server(sconn, serverConfig)
424 if err := srv.Handshake(); err != nil {
431 case serverTLSUniques <- srv.ConnectionState().TLSUnique:
436 clientConfig := testConfig.Clone()
437 clientConfig.ClientSessionCache = NewLRUClientSessionCache(1)
438 conn, err := Dial("tcp", ln.Addr().String(), clientConfig)
443 var serverTLSUniquesValue []byte
447 case serverTLSUniquesValue = <-serverTLSUniques:
450 if !bytes.Equal(conn.ConnectionState().TLSUnique, serverTLSUniquesValue) {
451 t.Error("client and server channel bindings differ")
455 conn, err = Dial("tcp", ln.Addr().String(), clientConfig)
460 if !conn.ConnectionState().DidResume {
461 t.Error("second session did not use resumption")
467 case serverTLSUniquesValue = <-serverTLSUniques:
470 if !bytes.Equal(conn.ConnectionState().TLSUnique, serverTLSUniquesValue) {
471 t.Error("client and server channel bindings differ when session resumption is used")
475 func TestVerifyHostname(t *testing.T) {
476 testenv.MustHaveExternalNetwork(t)
478 c, err := Dial("tcp", "www.google.com:https", nil)
482 if err := c.VerifyHostname("www.google.com"); err != nil {
483 t.Fatalf("verify www.google.com: %v", err)
485 if err := c.VerifyHostname("www.yahoo.com"); err == nil {
486 t.Fatalf("verify www.yahoo.com succeeded")
489 c, err = Dial("tcp", "www.google.com:https", &Config{InsecureSkipVerify: true})
493 if err := c.VerifyHostname("www.google.com"); err == nil {
494 t.Fatalf("verify www.google.com succeeded with InsecureSkipVerify=true")
498 func TestConnCloseBreakingWrite(t *testing.T) {
499 ln := newLocalListener(t)
502 srvCh := make(chan *Conn, 1)
507 sconn, err = ln.Accept()
513 serverConfig := testConfig.Clone()
514 srv := Server(sconn, serverConfig)
515 if err := srv.Handshake(); err != nil {
516 serr = fmt.Errorf("handshake: %v", err)
523 cconn, err := net.Dial("tcp", ln.Addr().String())
529 conn := &changeImplConn{
533 clientConfig := testConfig.Clone()
534 tconn := Client(conn, clientConfig)
535 if err := tconn.Handshake(); err != nil {
545 connClosed := make(chan struct{})
546 conn.closeFunc = func() error {
551 inWrite := make(chan bool, 1)
552 var errConnClosed = errors.New("conn closed for test")
553 conn.writeFunc = func(p []byte) (n int, err error) {
556 return 0, errConnClosed
559 closeReturned := make(chan bool, 1)
562 tconn.Close() // test that this doesn't block forever.
563 closeReturned <- true
566 _, err = tconn.Write([]byte("foo"))
567 if err != errConnClosed {
568 t.Errorf("Write error = %v; want errConnClosed", err)
572 if err := tconn.Close(); err != errClosed {
573 t.Errorf("Close error = %v; want errClosed", err)
577 func TestConnCloseWrite(t *testing.T) {
578 ln := newLocalListener(t)
581 clientDoneChan := make(chan struct{})
583 serverCloseWrite := func() error {
584 sconn, err := ln.Accept()
586 return fmt.Errorf("accept: %v", err)
590 serverConfig := testConfig.Clone()
591 srv := Server(sconn, serverConfig)
592 if err := srv.Handshake(); err != nil {
593 return fmt.Errorf("handshake: %v", err)
597 data, err := ioutil.ReadAll(srv)
602 return fmt.Errorf("Read data = %q; want nothing", data)
605 if err := srv.CloseWrite(); err != nil {
606 return fmt.Errorf("server CloseWrite: %v", err)
609 // Wait for clientCloseWrite to finish, so we know we
610 // tested the CloseWrite before we defer the
611 // sconn.Close above, which would also cause the
612 // client to unblock like CloseWrite.
617 clientCloseWrite := func() error {
618 defer close(clientDoneChan)
620 clientConfig := testConfig.Clone()
621 conn, err := Dial("tcp", ln.Addr().String(), clientConfig)
625 if err := conn.Handshake(); err != nil {
630 if err := conn.CloseWrite(); err != nil {
631 return fmt.Errorf("client CloseWrite: %v", err)
634 if _, err := conn.Write([]byte{0}); err != errShutdown {
635 return fmt.Errorf("CloseWrite error = %v; want errShutdown", err)
638 data, err := ioutil.ReadAll(conn)
643 return fmt.Errorf("Read data = %q; want nothing", data)
648 errChan := make(chan error, 2)
650 go func() { errChan <- serverCloseWrite() }()
651 go func() { errChan <- clientCloseWrite() }()
653 for i := 0; i < 2; i++ {
655 case err := <-errChan:
659 case <-time.After(10 * time.Second):
664 // Also test CloseWrite being called before the handshake is
667 ln2 := newLocalListener(t)
670 netConn, err := net.Dial("tcp", ln2.Addr().String())
674 defer netConn.Close()
675 conn := Client(netConn, testConfig.Clone())
677 if err := conn.CloseWrite(); err != errEarlyCloseWrite {
678 t.Errorf("CloseWrite error = %v; want errEarlyCloseWrite", err)
683 func TestWarningAlertFlood(t *testing.T) {
684 ln := newLocalListener(t)
687 server := func() error {
688 sconn, err := ln.Accept()
690 return fmt.Errorf("accept: %v", err)
694 serverConfig := testConfig.Clone()
695 srv := Server(sconn, serverConfig)
696 if err := srv.Handshake(); err != nil {
697 return fmt.Errorf("handshake: %v", err)
701 _, err = ioutil.ReadAll(srv)
703 return errors.New("unexpected lack of error from server")
705 const expected = "too many ignored"
706 if str := err.Error(); !strings.Contains(str, expected) {
707 return fmt.Errorf("expected error containing %q, but saw: %s", expected, str)
713 errChan := make(chan error, 1)
714 go func() { errChan <- server() }()
716 clientConfig := testConfig.Clone()
717 clientConfig.MaxVersion = VersionTLS12 // there are no warning alerts in TLS 1.3
718 conn, err := Dial("tcp", ln.Addr().String(), clientConfig)
723 if err := conn.Handshake(); err != nil {
727 for i := 0; i < maxUselessRecords+1; i++ {
728 conn.sendAlert(alertNoRenegotiation)
731 if err := <-errChan; err != nil {
736 func TestCloneFuncFields(t *testing.T) {
737 const expectedCount = 6
741 Time: func() time.Time {
745 GetCertificate: func(*ClientHelloInfo) (*Certificate, error) {
749 GetClientCertificate: func(*CertificateRequestInfo) (*Certificate, error) {
753 GetConfigForClient: func(*ClientHelloInfo) (*Config, error) {
757 VerifyPeerCertificate: func(rawCerts [][]byte, verifiedChains [][]*x509.Certificate) error {
761 VerifyConnection: func(ConnectionState) error {
770 c2.GetCertificate(nil)
771 c2.GetClientCertificate(nil)
772 c2.GetConfigForClient(nil)
773 c2.VerifyPeerCertificate(nil, nil)
774 c2.VerifyConnection(ConnectionState{})
776 if called != (1<<expectedCount)-1 {
777 t.Fatalf("expected %d calls but saw calls %b", expectedCount, called)
781 func TestCloneNonFuncFields(t *testing.T) {
783 v := reflect.ValueOf(&c1).Elem()
786 for i := 0; i < typ.NumField(); i++ {
788 // testing/quick can't handle functions or interfaces and so
790 switch fn := typ.Field(i).Name; fn {
792 f.Set(reflect.ValueOf(io.Reader(os.Stdin)))
793 case "Time", "GetCertificate", "GetConfigForClient", "VerifyPeerCertificate", "VerifyConnection", "GetClientCertificate":
794 // DeepEqual can't compare functions. If you add a
795 // function field to this list, you must also change
796 // TestCloneFuncFields to ensure that the func field is
799 f.Set(reflect.ValueOf([]Certificate{
800 {Certificate: [][]byte{{'b'}}},
802 case "NameToCertificate":
803 f.Set(reflect.ValueOf(map[string]*Certificate{"a": nil}))
804 case "RootCAs", "ClientCAs":
805 f.Set(reflect.ValueOf(x509.NewCertPool()))
806 case "ClientSessionCache":
807 f.Set(reflect.ValueOf(NewLRUClientSessionCache(10)))
809 f.Set(reflect.ValueOf(io.Writer(os.Stdout)))
811 f.Set(reflect.ValueOf([]string{"a", "b"}))
813 f.Set(reflect.ValueOf("b"))
815 f.Set(reflect.ValueOf(VerifyClientCertIfGiven))
816 case "InsecureSkipVerify", "SessionTicketsDisabled", "DynamicRecordSizingDisabled", "PreferServerCipherSuites":
817 f.Set(reflect.ValueOf(true))
818 case "MinVersion", "MaxVersion":
819 f.Set(reflect.ValueOf(uint16(VersionTLS12)))
820 case "SessionTicketKey":
821 f.Set(reflect.ValueOf([32]byte{}))
823 f.Set(reflect.ValueOf([]uint16{1, 2}))
824 case "CurvePreferences":
825 f.Set(reflect.ValueOf([]CurveID{CurveP256}))
826 case "Renegotiation":
827 f.Set(reflect.ValueOf(RenegotiateOnceAsClient))
828 case "mutex", "autoSessionTicketKeys", "sessionTicketKeys":
829 continue // these are unexported fields that are handled separately
831 t.Errorf("all fields must be accounted for, but saw unknown field %q", fn)
834 // Set the unexported fields related to session ticket keys, which are copied with Clone().
835 c1.autoSessionTicketKeys = []ticketKey{c1.ticketKeyFromBytes(c1.SessionTicketKey)}
836 c1.sessionTicketKeys = []ticketKey{c1.ticketKeyFromBytes(c1.SessionTicketKey)}
839 if !reflect.DeepEqual(&c1, c2) {
840 t.Errorf("clone failed to copy a field")
844 // changeImplConn is a net.Conn which can change its Write and Close
846 type changeImplConn struct {
848 writeFunc func([]byte) (int, error)
849 closeFunc func() error
852 func (w *changeImplConn) Write(p []byte) (n int, err error) {
853 if w.writeFunc != nil {
854 return w.writeFunc(p)
856 return w.Conn.Write(p)
859 func (w *changeImplConn) Close() error {
860 if w.closeFunc != nil {
863 return w.Conn.Close()
866 func throughput(b *testing.B, version uint16, totalBytes int64, dynamicRecordSizingDisabled bool) {
867 ln := newLocalListener(b)
872 // Less than 64KB because Windows appears to use a TCP rwin < 64KB.
874 const bufsize = 32 << 10
877 buf := make([]byte, bufsize)
878 for i := 0; i < N; i++ {
879 sconn, err := ln.Accept()
881 // panic rather than synchronize to avoid benchmark overhead
882 // (cannot call b.Fatal in goroutine)
883 panic(fmt.Errorf("accept: %v", err))
885 serverConfig := testConfig.Clone()
886 serverConfig.CipherSuites = nil // the defaults may prefer faster ciphers
887 serverConfig.DynamicRecordSizingDisabled = dynamicRecordSizingDisabled
888 srv := Server(sconn, serverConfig)
889 if err := srv.Handshake(); err != nil {
890 panic(fmt.Errorf("handshake: %v", err))
892 if _, err := io.CopyBuffer(srv, srv, buf); err != nil {
893 panic(fmt.Errorf("copy buffer: %v", err))
898 b.SetBytes(totalBytes)
899 clientConfig := testConfig.Clone()
900 clientConfig.CipherSuites = nil // the defaults may prefer faster ciphers
901 clientConfig.DynamicRecordSizingDisabled = dynamicRecordSizingDisabled
902 clientConfig.MaxVersion = version
904 buf := make([]byte, bufsize)
905 chunks := int(math.Ceil(float64(totalBytes) / float64(len(buf))))
906 for i := 0; i < N; i++ {
907 conn, err := Dial("tcp", ln.Addr().String(), clientConfig)
911 for j := 0; j < chunks; j++ {
912 _, err := conn.Write(buf)
916 _, err = io.ReadFull(conn, buf)
925 func BenchmarkThroughput(b *testing.B) {
926 for _, mode := range []string{"Max", "Dynamic"} {
927 for size := 1; size <= 64; size <<= 1 {
928 name := fmt.Sprintf("%sPacket/%dMB", mode, size)
929 b.Run(name, func(b *testing.B) {
930 b.Run("TLSv12", func(b *testing.B) {
931 throughput(b, VersionTLS12, int64(size<<20), mode == "Max")
933 b.Run("TLSv13", func(b *testing.B) {
934 throughput(b, VersionTLS13, int64(size<<20), mode == "Max")
941 type slowConn struct {
946 func (c *slowConn) Write(p []byte) (int, error) {
953 time.Sleep(100 * time.Microsecond)
954 allowed := int(time.Since(t0).Seconds()*float64(c.bps)) / 8
955 if allowed > len(p) {
959 n, err := c.Conn.Write(p[wrote:allowed])
969 func latency(b *testing.B, version uint16, bps int, dynamicRecordSizingDisabled bool) {
970 ln := newLocalListener(b)
976 for i := 0; i < N; i++ {
977 sconn, err := ln.Accept()
979 // panic rather than synchronize to avoid benchmark overhead
980 // (cannot call b.Fatal in goroutine)
981 panic(fmt.Errorf("accept: %v", err))
983 serverConfig := testConfig.Clone()
984 serverConfig.DynamicRecordSizingDisabled = dynamicRecordSizingDisabled
985 srv := Server(&slowConn{sconn, bps}, serverConfig)
986 if err := srv.Handshake(); err != nil {
987 panic(fmt.Errorf("handshake: %v", err))
993 clientConfig := testConfig.Clone()
994 clientConfig.DynamicRecordSizingDisabled = dynamicRecordSizingDisabled
995 clientConfig.MaxVersion = version
997 buf := make([]byte, 16384)
998 peek := make([]byte, 1)
1000 for i := 0; i < N; i++ {
1001 conn, err := Dial("tcp", ln.Addr().String(), clientConfig)
1005 // make sure we're connected and previous connection has stopped
1006 if _, err := conn.Write(buf[:1]); err != nil {
1009 if _, err := io.ReadFull(conn, peek); err != nil {
1012 if _, err := conn.Write(buf); err != nil {
1015 if _, err = io.ReadFull(conn, peek); err != nil {
1022 func BenchmarkLatency(b *testing.B) {
1023 for _, mode := range []string{"Max", "Dynamic"} {
1024 for _, kbps := range []int{200, 500, 1000, 2000, 5000} {
1025 name := fmt.Sprintf("%sPacket/%dkbps", mode, kbps)
1026 b.Run(name, func(b *testing.B) {
1027 b.Run("TLSv12", func(b *testing.B) {
1028 latency(b, VersionTLS12, kbps*1000, mode == "Max")
1030 b.Run("TLSv13", func(b *testing.B) {
1031 latency(b, VersionTLS13, kbps*1000, mode == "Max")
1038 func TestConnectionStateMarshal(t *testing.T) {
1039 cs := &ConnectionState{}
1040 _, err := json.Marshal(cs)
1042 t.Errorf("json.Marshal failed on ConnectionState: %v", err)
1046 func TestConnectionState(t *testing.T) {
1047 issuer, err := x509.ParseCertificate(testRSACertificateIssuer)
1051 rootCAs := x509.NewCertPool()
1052 rootCAs.AddCert(issuer)
1054 now := func() time.Time { return time.Unix(1476984729, 0) }
1056 const alpnProtocol = "golang"
1057 const serverName = "example.golang"
1058 var scts = [][]byte{[]byte("dummy sct 1"), []byte("dummy sct 2")}
1059 var ocsp = []byte("dummy ocsp")
1061 for _, v := range []uint16{VersionTLS12, VersionTLS13} {
1069 t.Run(name, func(t *testing.T) {
1073 Certificates: make([]Certificate, 1),
1077 ClientAuth: RequireAndVerifyClientCert,
1078 NextProtos: []string{alpnProtocol},
1079 ServerName: serverName,
1081 config.Certificates[0].Certificate = [][]byte{testRSACertificate}
1082 config.Certificates[0].PrivateKey = testRSAPrivateKey
1083 config.Certificates[0].SignedCertificateTimestamps = scts
1084 config.Certificates[0].OCSPStaple = ocsp
1086 ss, cs, err := testHandshake(t, config, config)
1088 t.Fatalf("Handshake failed: %v", err)
1091 if ss.Version != v || cs.Version != v {
1092 t.Errorf("Got versions %x (server) and %x (client), expected %x", ss.Version, cs.Version, v)
1095 if !ss.HandshakeComplete || !cs.HandshakeComplete {
1096 t.Errorf("Got HandshakeComplete %v (server) and %v (client), expected true", ss.HandshakeComplete, cs.HandshakeComplete)
1099 if ss.DidResume || cs.DidResume {
1100 t.Errorf("Got DidResume %v (server) and %v (client), expected false", ss.DidResume, cs.DidResume)
1103 if ss.CipherSuite == 0 || cs.CipherSuite == 0 {
1104 t.Errorf("Got invalid cipher suite: %v (server) and %v (client)", ss.CipherSuite, cs.CipherSuite)
1107 if ss.NegotiatedProtocol != alpnProtocol || cs.NegotiatedProtocol != alpnProtocol {
1108 t.Errorf("Got negotiated protocol %q (server) and %q (client), expected %q", ss.NegotiatedProtocol, cs.NegotiatedProtocol, alpnProtocol)
1111 if !cs.NegotiatedProtocolIsMutual {
1112 t.Errorf("Got false NegotiatedProtocolIsMutual on the client side")
1114 // NegotiatedProtocolIsMutual on the server side is unspecified.
1116 if ss.ServerName != serverName {
1117 t.Errorf("Got server name %q, expected %q", ss.ServerName, serverName)
1119 if cs.ServerName != serverName {
1120 t.Errorf("Got server name on client connection %q, expected %q", cs.ServerName, serverName)
1123 if len(ss.PeerCertificates) != 1 || len(cs.PeerCertificates) != 1 {
1124 t.Errorf("Got %d (server) and %d (client) peer certificates, expected %d", len(ss.PeerCertificates), len(cs.PeerCertificates), 1)
1127 if len(ss.VerifiedChains) != 1 || len(cs.VerifiedChains) != 1 {
1128 t.Errorf("Got %d (server) and %d (client) verified chains, expected %d", len(ss.VerifiedChains), len(cs.VerifiedChains), 1)
1129 } else if len(ss.VerifiedChains[0]) != 2 || len(cs.VerifiedChains[0]) != 2 {
1130 t.Errorf("Got %d (server) and %d (client) long verified chain, expected %d", len(ss.VerifiedChains[0]), len(cs.VerifiedChains[0]), 2)
1133 if len(cs.SignedCertificateTimestamps) != 2 {
1134 t.Errorf("Got %d SCTs, expected %d", len(cs.SignedCertificateTimestamps), 2)
1136 if !bytes.Equal(cs.OCSPResponse, ocsp) {
1137 t.Errorf("Got OCSPs %x, expected %x", cs.OCSPResponse, ocsp)
1139 // Only TLS 1.3 supports OCSP and SCTs on client certs.
1140 if v == VersionTLS13 {
1141 if len(ss.SignedCertificateTimestamps) != 2 {
1142 t.Errorf("Got %d client SCTs, expected %d", len(ss.SignedCertificateTimestamps), 2)
1144 if !bytes.Equal(ss.OCSPResponse, ocsp) {
1145 t.Errorf("Got client OCSPs %x, expected %x", ss.OCSPResponse, ocsp)
1149 if v == VersionTLS13 {
1150 if ss.TLSUnique != nil || cs.TLSUnique != nil {
1151 t.Errorf("Got TLSUnique %x (server) and %x (client), expected nil in TLS 1.3", ss.TLSUnique, cs.TLSUnique)
1154 if ss.TLSUnique == nil || cs.TLSUnique == nil {
1155 t.Errorf("Got TLSUnique %x (server) and %x (client), expected non-nil", ss.TLSUnique, cs.TLSUnique)
1162 // Issue 28744: Ensure that we don't modify memory
1163 // that Config doesn't own such as Certificates.
1164 func TestBuildNameToCertificate_doesntModifyCertificates(t *testing.T) {
1166 Certificate: [][]byte{testRSACertificate},
1167 PrivateKey: testRSAPrivateKey,
1170 Certificate: [][]byte{testSNICertificate},
1171 PrivateKey: testRSAPrivateKey,
1173 config := testConfig.Clone()
1174 config.Certificates = []Certificate{c0, c1}
1176 config.BuildNameToCertificate()
1177 got := config.Certificates
1178 want := []Certificate{c0, c1}
1179 if !reflect.DeepEqual(got, want) {
1180 t.Fatalf("Certificates were mutated by BuildNameToCertificate\nGot: %#v\nWant: %#v\n", got, want)
1184 func testingKey(s string) string { return strings.ReplaceAll(s, "TESTING KEY", "PRIVATE KEY") }
1186 func TestClientHelloInfo_SupportsCertificate(t *testing.T) {
1187 rsaCert := &Certificate{
1188 Certificate: [][]byte{testRSACertificate},
1189 PrivateKey: testRSAPrivateKey,
1191 pkcs1Cert := &Certificate{
1192 Certificate: [][]byte{testRSACertificate},
1193 PrivateKey: testRSAPrivateKey,
1194 SupportedSignatureAlgorithms: []SignatureScheme{PKCS1WithSHA1, PKCS1WithSHA256},
1196 ecdsaCert := &Certificate{
1197 // ECDSA P-256 certificate
1198 Certificate: [][]byte{testP256Certificate},
1199 PrivateKey: testP256PrivateKey,
1201 ed25519Cert := &Certificate{
1202 Certificate: [][]byte{testEd25519Certificate},
1203 PrivateKey: testEd25519PrivateKey,
1208 chi *ClientHelloInfo
1211 {rsaCert, &ClientHelloInfo{
1212 ServerName: "example.golang",
1213 SignatureSchemes: []SignatureScheme{PSSWithSHA256},
1214 SupportedVersions: []uint16{VersionTLS13},
1216 {ecdsaCert, &ClientHelloInfo{
1217 SignatureSchemes: []SignatureScheme{PSSWithSHA256, ECDSAWithP256AndSHA256},
1218 SupportedVersions: []uint16{VersionTLS13, VersionTLS12},
1220 {rsaCert, &ClientHelloInfo{
1221 ServerName: "example.com",
1222 SignatureSchemes: []SignatureScheme{PSSWithSHA256},
1223 SupportedVersions: []uint16{VersionTLS13},
1224 }, "not valid for requested server name"},
1225 {ecdsaCert, &ClientHelloInfo{
1226 SignatureSchemes: []SignatureScheme{ECDSAWithP384AndSHA384},
1227 SupportedVersions: []uint16{VersionTLS13},
1228 }, "signature algorithms"},
1229 {pkcs1Cert, &ClientHelloInfo{
1230 SignatureSchemes: []SignatureScheme{PSSWithSHA256, ECDSAWithP256AndSHA256},
1231 SupportedVersions: []uint16{VersionTLS13},
1232 }, "signature algorithms"},
1234 {rsaCert, &ClientHelloInfo{
1235 CipherSuites: []uint16{TLS_RSA_WITH_AES_128_GCM_SHA256},
1236 SignatureSchemes: []SignatureScheme{PKCS1WithSHA1},
1237 SupportedVersions: []uint16{VersionTLS13, VersionTLS12},
1238 }, "signature algorithms"},
1239 {rsaCert, &ClientHelloInfo{
1240 CipherSuites: []uint16{TLS_RSA_WITH_AES_128_GCM_SHA256},
1241 SignatureSchemes: []SignatureScheme{PKCS1WithSHA1},
1242 SupportedVersions: []uint16{VersionTLS13, VersionTLS12},
1244 MaxVersion: VersionTLS12,
1246 }, ""}, // Check that mutual version selection works.
1248 {ecdsaCert, &ClientHelloInfo{
1249 CipherSuites: []uint16{TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256},
1250 SupportedCurves: []CurveID{CurveP256},
1251 SupportedPoints: []uint8{pointFormatUncompressed},
1252 SignatureSchemes: []SignatureScheme{ECDSAWithP256AndSHA256},
1253 SupportedVersions: []uint16{VersionTLS12},
1255 {ecdsaCert, &ClientHelloInfo{
1256 CipherSuites: []uint16{TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256},
1257 SupportedCurves: []CurveID{CurveP256},
1258 SupportedPoints: []uint8{pointFormatUncompressed},
1259 SignatureSchemes: []SignatureScheme{ECDSAWithP384AndSHA384},
1260 SupportedVersions: []uint16{VersionTLS12},
1261 }, ""}, // TLS 1.2 does not restrict curves based on the SignatureScheme.
1262 {ecdsaCert, &ClientHelloInfo{
1263 CipherSuites: []uint16{TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256},
1264 SupportedCurves: []CurveID{CurveP256},
1265 SupportedPoints: []uint8{pointFormatUncompressed},
1266 SignatureSchemes: nil,
1267 SupportedVersions: []uint16{VersionTLS12},
1268 }, ""}, // TLS 1.2 comes with default signature schemes.
1269 {ecdsaCert, &ClientHelloInfo{
1270 CipherSuites: []uint16{TLS_RSA_WITH_AES_128_GCM_SHA256},
1271 SupportedCurves: []CurveID{CurveP256},
1272 SupportedPoints: []uint8{pointFormatUncompressed},
1273 SignatureSchemes: []SignatureScheme{ECDSAWithP256AndSHA256},
1274 SupportedVersions: []uint16{VersionTLS12},
1276 {ecdsaCert, &ClientHelloInfo{
1277 CipherSuites: []uint16{TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256},
1278 SupportedCurves: []CurveID{CurveP256},
1279 SupportedPoints: []uint8{pointFormatUncompressed},
1280 SignatureSchemes: []SignatureScheme{ECDSAWithP256AndSHA256},
1281 SupportedVersions: []uint16{VersionTLS12},
1283 CipherSuites: []uint16{TLS_RSA_WITH_AES_128_GCM_SHA256},
1286 {ecdsaCert, &ClientHelloInfo{
1287 CipherSuites: []uint16{TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256},
1288 SupportedCurves: []CurveID{CurveP384},
1289 SupportedPoints: []uint8{pointFormatUncompressed},
1290 SignatureSchemes: []SignatureScheme{ECDSAWithP256AndSHA256},
1291 SupportedVersions: []uint16{VersionTLS12},
1292 }, "certificate curve"},
1293 {ecdsaCert, &ClientHelloInfo{
1294 CipherSuites: []uint16{TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256},
1295 SupportedCurves: []CurveID{CurveP256},
1296 SupportedPoints: []uint8{1},
1297 SignatureSchemes: []SignatureScheme{ECDSAWithP256AndSHA256},
1298 SupportedVersions: []uint16{VersionTLS12},
1299 }, "doesn't support ECDHE"},
1300 {ecdsaCert, &ClientHelloInfo{
1301 CipherSuites: []uint16{TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256},
1302 SupportedCurves: []CurveID{CurveP256},
1303 SupportedPoints: []uint8{pointFormatUncompressed},
1304 SignatureSchemes: []SignatureScheme{PSSWithSHA256},
1305 SupportedVersions: []uint16{VersionTLS12},
1306 }, "signature algorithms"},
1308 {ed25519Cert, &ClientHelloInfo{
1309 CipherSuites: []uint16{TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256},
1310 SupportedCurves: []CurveID{CurveP256}, // only relevant for ECDHE support
1311 SupportedPoints: []uint8{pointFormatUncompressed},
1312 SignatureSchemes: []SignatureScheme{Ed25519},
1313 SupportedVersions: []uint16{VersionTLS12},
1315 {ed25519Cert, &ClientHelloInfo{
1316 CipherSuites: []uint16{TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256},
1317 SupportedCurves: []CurveID{CurveP256}, // only relevant for ECDHE support
1318 SupportedPoints: []uint8{pointFormatUncompressed},
1319 SignatureSchemes: []SignatureScheme{Ed25519},
1320 SupportedVersions: []uint16{VersionTLS10},
1321 }, "doesn't support Ed25519"},
1322 {ed25519Cert, &ClientHelloInfo{
1323 CipherSuites: []uint16{TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256},
1324 SupportedCurves: []CurveID{},
1325 SupportedPoints: []uint8{pointFormatUncompressed},
1326 SignatureSchemes: []SignatureScheme{Ed25519},
1327 SupportedVersions: []uint16{VersionTLS12},
1328 }, "doesn't support ECDHE"},
1330 {rsaCert, &ClientHelloInfo{
1331 CipherSuites: []uint16{TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA},
1332 SupportedCurves: []CurveID{CurveP256}, // only relevant for ECDHE support
1333 SupportedPoints: []uint8{pointFormatUncompressed},
1334 SupportedVersions: []uint16{VersionTLS10},
1336 {rsaCert, &ClientHelloInfo{
1337 CipherSuites: []uint16{TLS_RSA_WITH_AES_128_GCM_SHA256},
1338 SupportedVersions: []uint16{VersionTLS12},
1339 }, ""}, // static RSA fallback
1341 for i, tt := range tests {
1342 err := tt.chi.SupportsCertificate(tt.c)
1344 case tt.wantErr == "" && err != nil:
1345 t.Errorf("%d: unexpected error: %v", i, err)
1346 case tt.wantErr != "" && err == nil:
1347 t.Errorf("%d: unexpected success", i)
1348 case tt.wantErr != "" && !strings.Contains(err.Error(), tt.wantErr):
1349 t.Errorf("%d: got error %q, expected %q", i, err, tt.wantErr)
1354 func TestCipherSuites(t *testing.T) {
1356 for _, c := range CipherSuites() {
1358 t.Errorf("CipherSuites are not ordered by ID: got %#04x after %#04x", c.ID, lastID)
1364 t.Errorf("%#04x: Insecure CipherSuite returned by CipherSuites()", c.ID)
1368 for _, c := range InsecureCipherSuites() {
1370 t.Errorf("InsecureCipherSuites are not ordered by ID: got %#04x after %#04x", c.ID, lastID)
1376 t.Errorf("%#04x: not Insecure CipherSuite returned by InsecureCipherSuites()", c.ID)
1380 cipherSuiteByID := func(id uint16) *CipherSuite {
1381 for _, c := range CipherSuites() {
1386 for _, c := range InsecureCipherSuites() {
1394 for _, c := range cipherSuites {
1395 cc := cipherSuiteByID(c.id)
1397 t.Errorf("%#04x: no CipherSuite entry", c.id)
1401 if defaultOff := c.flags&suiteDefaultOff != 0; defaultOff != cc.Insecure {
1402 t.Errorf("%#04x: Insecure %v, expected %v", c.id, cc.Insecure, defaultOff)
1404 if tls12Only := c.flags&suiteTLS12 != 0; tls12Only && len(cc.SupportedVersions) != 1 {
1405 t.Errorf("%#04x: suite is TLS 1.2 only, but SupportedVersions is %v", c.id, cc.SupportedVersions)
1406 } else if !tls12Only && len(cc.SupportedVersions) != 3 {
1407 t.Errorf("%#04x: suite TLS 1.0-1.2, but SupportedVersions is %v", c.id, cc.SupportedVersions)
1410 if got := CipherSuiteName(c.id); got != cc.Name {
1411 t.Errorf("%#04x: unexpected CipherSuiteName: got %q, expected %q", c.id, got, cc.Name)
1414 for _, c := range cipherSuitesTLS13 {
1415 cc := cipherSuiteByID(c.id)
1417 t.Errorf("%#04x: no CipherSuite entry", c.id)
1422 t.Errorf("%#04x: Insecure %v, expected false", c.id, cc.Insecure)
1424 if len(cc.SupportedVersions) != 1 || cc.SupportedVersions[0] != VersionTLS13 {
1425 t.Errorf("%#04x: suite is TLS 1.3 only, but SupportedVersions is %v", c.id, cc.SupportedVersions)
1428 if got := CipherSuiteName(c.id); got != cc.Name {
1429 t.Errorf("%#04x: unexpected CipherSuiteName: got %q, expected %q", c.id, got, cc.Name)
1433 if got := CipherSuiteName(0xabc); got != "0x0ABC" {
1434 t.Errorf("unexpected fallback CipherSuiteName: got %q, expected 0x0ABC", got)
1438 type brokenSigner struct{ crypto.Signer }
1440 func (s brokenSigner) Sign(rand io.Reader, digest []byte, opts crypto.SignerOpts) (signature []byte, err error) {
1441 // Replace opts with opts.HashFunc(), so rsa.PSSOptions are discarded.
1442 return s.Signer.Sign(rand, digest, opts.HashFunc())
1445 // TestPKCS1OnlyCert uses a client certificate with a broken crypto.Signer that
1446 // always makes PKCS #1 v1.5 signatures, so can't be used with RSA-PSS.
1447 func TestPKCS1OnlyCert(t *testing.T) {
1448 clientConfig := testConfig.Clone()
1449 clientConfig.Certificates = []Certificate{{
1450 Certificate: [][]byte{testRSACertificate},
1451 PrivateKey: brokenSigner{testRSAPrivateKey},
1453 serverConfig := testConfig.Clone()
1454 serverConfig.MaxVersion = VersionTLS12 // TLS 1.3 doesn't support PKCS #1 v1.5
1455 serverConfig.ClientAuth = RequireAnyClientCert
1457 // If RSA-PSS is selected, the handshake should fail.
1458 if _, _, err := testHandshake(t, clientConfig, serverConfig); err == nil {
1459 t.Fatal("expected broken certificate to cause connection to fail")
1462 clientConfig.Certificates[0].SupportedSignatureAlgorithms =
1463 []SignatureScheme{PKCS1WithSHA1, PKCS1WithSHA256}
1465 // But if the certificate restricts supported algorithms, RSA-PSS should not
1466 // be selected, and the handshake should succeed.
1467 if _, _, err := testHandshake(t, clientConfig, serverConfig); err != nil {