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 != net.ErrClosed {
573 t.Errorf("Close error = %v; want net.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 := io.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 := io.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 = io.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 func TestCloneNilConfig(t *testing.T) {
846 if cc := config.Clone(); cc != nil {
847 t.Fatalf("Clone with nil should return nil, got: %+v", cc)
851 // changeImplConn is a net.Conn which can change its Write and Close
853 type changeImplConn struct {
855 writeFunc func([]byte) (int, error)
856 closeFunc func() error
859 func (w *changeImplConn) Write(p []byte) (n int, err error) {
860 if w.writeFunc != nil {
861 return w.writeFunc(p)
863 return w.Conn.Write(p)
866 func (w *changeImplConn) Close() error {
867 if w.closeFunc != nil {
870 return w.Conn.Close()
873 func throughput(b *testing.B, version uint16, totalBytes int64, dynamicRecordSizingDisabled bool) {
874 ln := newLocalListener(b)
879 // Less than 64KB because Windows appears to use a TCP rwin < 64KB.
881 const bufsize = 32 << 10
884 buf := make([]byte, bufsize)
885 for i := 0; i < N; i++ {
886 sconn, err := ln.Accept()
888 // panic rather than synchronize to avoid benchmark overhead
889 // (cannot call b.Fatal in goroutine)
890 panic(fmt.Errorf("accept: %v", err))
892 serverConfig := testConfig.Clone()
893 serverConfig.CipherSuites = nil // the defaults may prefer faster ciphers
894 serverConfig.DynamicRecordSizingDisabled = dynamicRecordSizingDisabled
895 srv := Server(sconn, serverConfig)
896 if err := srv.Handshake(); err != nil {
897 panic(fmt.Errorf("handshake: %v", err))
899 if _, err := io.CopyBuffer(srv, srv, buf); err != nil {
900 panic(fmt.Errorf("copy buffer: %v", err))
905 b.SetBytes(totalBytes)
906 clientConfig := testConfig.Clone()
907 clientConfig.CipherSuites = nil // the defaults may prefer faster ciphers
908 clientConfig.DynamicRecordSizingDisabled = dynamicRecordSizingDisabled
909 clientConfig.MaxVersion = version
911 buf := make([]byte, bufsize)
912 chunks := int(math.Ceil(float64(totalBytes) / float64(len(buf))))
913 for i := 0; i < N; i++ {
914 conn, err := Dial("tcp", ln.Addr().String(), clientConfig)
918 for j := 0; j < chunks; j++ {
919 _, err := conn.Write(buf)
923 _, err = io.ReadFull(conn, buf)
932 func BenchmarkThroughput(b *testing.B) {
933 for _, mode := range []string{"Max", "Dynamic"} {
934 for size := 1; size <= 64; size <<= 1 {
935 name := fmt.Sprintf("%sPacket/%dMB", mode, size)
936 b.Run(name, func(b *testing.B) {
937 b.Run("TLSv12", func(b *testing.B) {
938 throughput(b, VersionTLS12, int64(size<<20), mode == "Max")
940 b.Run("TLSv13", func(b *testing.B) {
941 throughput(b, VersionTLS13, int64(size<<20), mode == "Max")
948 type slowConn struct {
953 func (c *slowConn) Write(p []byte) (int, error) {
960 time.Sleep(100 * time.Microsecond)
961 allowed := int(time.Since(t0).Seconds()*float64(c.bps)) / 8
962 if allowed > len(p) {
966 n, err := c.Conn.Write(p[wrote:allowed])
976 func latency(b *testing.B, version uint16, bps int, dynamicRecordSizingDisabled bool) {
977 ln := newLocalListener(b)
983 for i := 0; i < N; i++ {
984 sconn, err := ln.Accept()
986 // panic rather than synchronize to avoid benchmark overhead
987 // (cannot call b.Fatal in goroutine)
988 panic(fmt.Errorf("accept: %v", err))
990 serverConfig := testConfig.Clone()
991 serverConfig.DynamicRecordSizingDisabled = dynamicRecordSizingDisabled
992 srv := Server(&slowConn{sconn, bps}, serverConfig)
993 if err := srv.Handshake(); err != nil {
994 panic(fmt.Errorf("handshake: %v", err))
1000 clientConfig := testConfig.Clone()
1001 clientConfig.DynamicRecordSizingDisabled = dynamicRecordSizingDisabled
1002 clientConfig.MaxVersion = version
1004 buf := make([]byte, 16384)
1005 peek := make([]byte, 1)
1007 for i := 0; i < N; i++ {
1008 conn, err := Dial("tcp", ln.Addr().String(), clientConfig)
1012 // make sure we're connected and previous connection has stopped
1013 if _, err := conn.Write(buf[:1]); err != nil {
1016 if _, err := io.ReadFull(conn, peek); err != nil {
1019 if _, err := conn.Write(buf); err != nil {
1022 if _, err = io.ReadFull(conn, peek); err != nil {
1029 func BenchmarkLatency(b *testing.B) {
1030 for _, mode := range []string{"Max", "Dynamic"} {
1031 for _, kbps := range []int{200, 500, 1000, 2000, 5000} {
1032 name := fmt.Sprintf("%sPacket/%dkbps", mode, kbps)
1033 b.Run(name, func(b *testing.B) {
1034 b.Run("TLSv12", func(b *testing.B) {
1035 latency(b, VersionTLS12, kbps*1000, mode == "Max")
1037 b.Run("TLSv13", func(b *testing.B) {
1038 latency(b, VersionTLS13, kbps*1000, mode == "Max")
1045 func TestConnectionStateMarshal(t *testing.T) {
1046 cs := &ConnectionState{}
1047 _, err := json.Marshal(cs)
1049 t.Errorf("json.Marshal failed on ConnectionState: %v", err)
1053 func TestConnectionState(t *testing.T) {
1054 issuer, err := x509.ParseCertificate(testRSACertificateIssuer)
1058 rootCAs := x509.NewCertPool()
1059 rootCAs.AddCert(issuer)
1061 now := func() time.Time { return time.Unix(1476984729, 0) }
1063 const alpnProtocol = "golang"
1064 const serverName = "example.golang"
1065 var scts = [][]byte{[]byte("dummy sct 1"), []byte("dummy sct 2")}
1066 var ocsp = []byte("dummy ocsp")
1068 for _, v := range []uint16{VersionTLS12, VersionTLS13} {
1076 t.Run(name, func(t *testing.T) {
1080 Certificates: make([]Certificate, 1),
1084 ClientAuth: RequireAndVerifyClientCert,
1085 NextProtos: []string{alpnProtocol},
1086 ServerName: serverName,
1088 config.Certificates[0].Certificate = [][]byte{testRSACertificate}
1089 config.Certificates[0].PrivateKey = testRSAPrivateKey
1090 config.Certificates[0].SignedCertificateTimestamps = scts
1091 config.Certificates[0].OCSPStaple = ocsp
1093 ss, cs, err := testHandshake(t, config, config)
1095 t.Fatalf("Handshake failed: %v", err)
1098 if ss.Version != v || cs.Version != v {
1099 t.Errorf("Got versions %x (server) and %x (client), expected %x", ss.Version, cs.Version, v)
1102 if !ss.HandshakeComplete || !cs.HandshakeComplete {
1103 t.Errorf("Got HandshakeComplete %v (server) and %v (client), expected true", ss.HandshakeComplete, cs.HandshakeComplete)
1106 if ss.DidResume || cs.DidResume {
1107 t.Errorf("Got DidResume %v (server) and %v (client), expected false", ss.DidResume, cs.DidResume)
1110 if ss.CipherSuite == 0 || cs.CipherSuite == 0 {
1111 t.Errorf("Got invalid cipher suite: %v (server) and %v (client)", ss.CipherSuite, cs.CipherSuite)
1114 if ss.NegotiatedProtocol != alpnProtocol || cs.NegotiatedProtocol != alpnProtocol {
1115 t.Errorf("Got negotiated protocol %q (server) and %q (client), expected %q", ss.NegotiatedProtocol, cs.NegotiatedProtocol, alpnProtocol)
1118 if !cs.NegotiatedProtocolIsMutual {
1119 t.Errorf("Got false NegotiatedProtocolIsMutual on the client side")
1121 // NegotiatedProtocolIsMutual on the server side is unspecified.
1123 if ss.ServerName != serverName {
1124 t.Errorf("Got server name %q, expected %q", ss.ServerName, serverName)
1126 if cs.ServerName != serverName {
1127 t.Errorf("Got server name on client connection %q, expected %q", cs.ServerName, serverName)
1130 if len(ss.PeerCertificates) != 1 || len(cs.PeerCertificates) != 1 {
1131 t.Errorf("Got %d (server) and %d (client) peer certificates, expected %d", len(ss.PeerCertificates), len(cs.PeerCertificates), 1)
1134 if len(ss.VerifiedChains) != 1 || len(cs.VerifiedChains) != 1 {
1135 t.Errorf("Got %d (server) and %d (client) verified chains, expected %d", len(ss.VerifiedChains), len(cs.VerifiedChains), 1)
1136 } else if len(ss.VerifiedChains[0]) != 2 || len(cs.VerifiedChains[0]) != 2 {
1137 t.Errorf("Got %d (server) and %d (client) long verified chain, expected %d", len(ss.VerifiedChains[0]), len(cs.VerifiedChains[0]), 2)
1140 if len(cs.SignedCertificateTimestamps) != 2 {
1141 t.Errorf("Got %d SCTs, expected %d", len(cs.SignedCertificateTimestamps), 2)
1143 if !bytes.Equal(cs.OCSPResponse, ocsp) {
1144 t.Errorf("Got OCSPs %x, expected %x", cs.OCSPResponse, ocsp)
1146 // Only TLS 1.3 supports OCSP and SCTs on client certs.
1147 if v == VersionTLS13 {
1148 if len(ss.SignedCertificateTimestamps) != 2 {
1149 t.Errorf("Got %d client SCTs, expected %d", len(ss.SignedCertificateTimestamps), 2)
1151 if !bytes.Equal(ss.OCSPResponse, ocsp) {
1152 t.Errorf("Got client OCSPs %x, expected %x", ss.OCSPResponse, ocsp)
1156 if v == VersionTLS13 {
1157 if ss.TLSUnique != nil || cs.TLSUnique != nil {
1158 t.Errorf("Got TLSUnique %x (server) and %x (client), expected nil in TLS 1.3", ss.TLSUnique, cs.TLSUnique)
1161 if ss.TLSUnique == nil || cs.TLSUnique == nil {
1162 t.Errorf("Got TLSUnique %x (server) and %x (client), expected non-nil", ss.TLSUnique, cs.TLSUnique)
1169 // Issue 28744: Ensure that we don't modify memory
1170 // that Config doesn't own such as Certificates.
1171 func TestBuildNameToCertificate_doesntModifyCertificates(t *testing.T) {
1173 Certificate: [][]byte{testRSACertificate},
1174 PrivateKey: testRSAPrivateKey,
1177 Certificate: [][]byte{testSNICertificate},
1178 PrivateKey: testRSAPrivateKey,
1180 config := testConfig.Clone()
1181 config.Certificates = []Certificate{c0, c1}
1183 config.BuildNameToCertificate()
1184 got := config.Certificates
1185 want := []Certificate{c0, c1}
1186 if !reflect.DeepEqual(got, want) {
1187 t.Fatalf("Certificates were mutated by BuildNameToCertificate\nGot: %#v\nWant: %#v\n", got, want)
1191 func testingKey(s string) string { return strings.ReplaceAll(s, "TESTING KEY", "PRIVATE KEY") }
1193 func TestClientHelloInfo_SupportsCertificate(t *testing.T) {
1194 rsaCert := &Certificate{
1195 Certificate: [][]byte{testRSACertificate},
1196 PrivateKey: testRSAPrivateKey,
1198 pkcs1Cert := &Certificate{
1199 Certificate: [][]byte{testRSACertificate},
1200 PrivateKey: testRSAPrivateKey,
1201 SupportedSignatureAlgorithms: []SignatureScheme{PKCS1WithSHA1, PKCS1WithSHA256},
1203 ecdsaCert := &Certificate{
1204 // ECDSA P-256 certificate
1205 Certificate: [][]byte{testP256Certificate},
1206 PrivateKey: testP256PrivateKey,
1208 ed25519Cert := &Certificate{
1209 Certificate: [][]byte{testEd25519Certificate},
1210 PrivateKey: testEd25519PrivateKey,
1215 chi *ClientHelloInfo
1218 {rsaCert, &ClientHelloInfo{
1219 ServerName: "example.golang",
1220 SignatureSchemes: []SignatureScheme{PSSWithSHA256},
1221 SupportedVersions: []uint16{VersionTLS13},
1223 {ecdsaCert, &ClientHelloInfo{
1224 SignatureSchemes: []SignatureScheme{PSSWithSHA256, ECDSAWithP256AndSHA256},
1225 SupportedVersions: []uint16{VersionTLS13, VersionTLS12},
1227 {rsaCert, &ClientHelloInfo{
1228 ServerName: "example.com",
1229 SignatureSchemes: []SignatureScheme{PSSWithSHA256},
1230 SupportedVersions: []uint16{VersionTLS13},
1231 }, "not valid for requested server name"},
1232 {ecdsaCert, &ClientHelloInfo{
1233 SignatureSchemes: []SignatureScheme{ECDSAWithP384AndSHA384},
1234 SupportedVersions: []uint16{VersionTLS13},
1235 }, "signature algorithms"},
1236 {pkcs1Cert, &ClientHelloInfo{
1237 SignatureSchemes: []SignatureScheme{PSSWithSHA256, ECDSAWithP256AndSHA256},
1238 SupportedVersions: []uint16{VersionTLS13},
1239 }, "signature algorithms"},
1241 {rsaCert, &ClientHelloInfo{
1242 CipherSuites: []uint16{TLS_RSA_WITH_AES_128_GCM_SHA256},
1243 SignatureSchemes: []SignatureScheme{PKCS1WithSHA1},
1244 SupportedVersions: []uint16{VersionTLS13, VersionTLS12},
1245 }, "signature algorithms"},
1246 {rsaCert, &ClientHelloInfo{
1247 CipherSuites: []uint16{TLS_RSA_WITH_AES_128_GCM_SHA256},
1248 SignatureSchemes: []SignatureScheme{PKCS1WithSHA1},
1249 SupportedVersions: []uint16{VersionTLS13, VersionTLS12},
1251 MaxVersion: VersionTLS12,
1253 }, ""}, // Check that mutual version selection works.
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{ECDSAWithP256AndSHA256},
1260 SupportedVersions: []uint16{VersionTLS12},
1262 {ecdsaCert, &ClientHelloInfo{
1263 CipherSuites: []uint16{TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256},
1264 SupportedCurves: []CurveID{CurveP256},
1265 SupportedPoints: []uint8{pointFormatUncompressed},
1266 SignatureSchemes: []SignatureScheme{ECDSAWithP384AndSHA384},
1267 SupportedVersions: []uint16{VersionTLS12},
1268 }, ""}, // TLS 1.2 does not restrict curves based on the SignatureScheme.
1269 {ecdsaCert, &ClientHelloInfo{
1270 CipherSuites: []uint16{TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256},
1271 SupportedCurves: []CurveID{CurveP256},
1272 SupportedPoints: []uint8{pointFormatUncompressed},
1273 SignatureSchemes: nil,
1274 SupportedVersions: []uint16{VersionTLS12},
1275 }, ""}, // TLS 1.2 comes with default signature schemes.
1276 {ecdsaCert, &ClientHelloInfo{
1277 CipherSuites: []uint16{TLS_RSA_WITH_AES_128_GCM_SHA256},
1278 SupportedCurves: []CurveID{CurveP256},
1279 SupportedPoints: []uint8{pointFormatUncompressed},
1280 SignatureSchemes: []SignatureScheme{ECDSAWithP256AndSHA256},
1281 SupportedVersions: []uint16{VersionTLS12},
1283 {ecdsaCert, &ClientHelloInfo{
1284 CipherSuites: []uint16{TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256},
1285 SupportedCurves: []CurveID{CurveP256},
1286 SupportedPoints: []uint8{pointFormatUncompressed},
1287 SignatureSchemes: []SignatureScheme{ECDSAWithP256AndSHA256},
1288 SupportedVersions: []uint16{VersionTLS12},
1290 CipherSuites: []uint16{TLS_RSA_WITH_AES_128_GCM_SHA256},
1293 {ecdsaCert, &ClientHelloInfo{
1294 CipherSuites: []uint16{TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256},
1295 SupportedCurves: []CurveID{CurveP384},
1296 SupportedPoints: []uint8{pointFormatUncompressed},
1297 SignatureSchemes: []SignatureScheme{ECDSAWithP256AndSHA256},
1298 SupportedVersions: []uint16{VersionTLS12},
1299 }, "certificate curve"},
1300 {ecdsaCert, &ClientHelloInfo{
1301 CipherSuites: []uint16{TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256},
1302 SupportedCurves: []CurveID{CurveP256},
1303 SupportedPoints: []uint8{1},
1304 SignatureSchemes: []SignatureScheme{ECDSAWithP256AndSHA256},
1305 SupportedVersions: []uint16{VersionTLS12},
1306 }, "doesn't support ECDHE"},
1307 {ecdsaCert, &ClientHelloInfo{
1308 CipherSuites: []uint16{TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256},
1309 SupportedCurves: []CurveID{CurveP256},
1310 SupportedPoints: []uint8{pointFormatUncompressed},
1311 SignatureSchemes: []SignatureScheme{PSSWithSHA256},
1312 SupportedVersions: []uint16{VersionTLS12},
1313 }, "signature algorithms"},
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{VersionTLS12},
1322 {ed25519Cert, &ClientHelloInfo{
1323 CipherSuites: []uint16{TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256},
1324 SupportedCurves: []CurveID{CurveP256}, // only relevant for ECDHE support
1325 SupportedPoints: []uint8{pointFormatUncompressed},
1326 SignatureSchemes: []SignatureScheme{Ed25519},
1327 SupportedVersions: []uint16{VersionTLS10},
1328 }, "doesn't support Ed25519"},
1329 {ed25519Cert, &ClientHelloInfo{
1330 CipherSuites: []uint16{TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256},
1331 SupportedCurves: []CurveID{},
1332 SupportedPoints: []uint8{pointFormatUncompressed},
1333 SignatureSchemes: []SignatureScheme{Ed25519},
1334 SupportedVersions: []uint16{VersionTLS12},
1335 }, "doesn't support ECDHE"},
1337 {rsaCert, &ClientHelloInfo{
1338 CipherSuites: []uint16{TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA},
1339 SupportedCurves: []CurveID{CurveP256}, // only relevant for ECDHE support
1340 SupportedPoints: []uint8{pointFormatUncompressed},
1341 SupportedVersions: []uint16{VersionTLS10},
1343 {rsaCert, &ClientHelloInfo{
1344 CipherSuites: []uint16{TLS_RSA_WITH_AES_128_GCM_SHA256},
1345 SupportedVersions: []uint16{VersionTLS12},
1346 }, ""}, // static RSA fallback
1348 for i, tt := range tests {
1349 err := tt.chi.SupportsCertificate(tt.c)
1351 case tt.wantErr == "" && err != nil:
1352 t.Errorf("%d: unexpected error: %v", i, err)
1353 case tt.wantErr != "" && err == nil:
1354 t.Errorf("%d: unexpected success", i)
1355 case tt.wantErr != "" && !strings.Contains(err.Error(), tt.wantErr):
1356 t.Errorf("%d: got error %q, expected %q", i, err, tt.wantErr)
1361 func TestCipherSuites(t *testing.T) {
1363 for _, c := range CipherSuites() {
1365 t.Errorf("CipherSuites are not ordered by ID: got %#04x after %#04x", c.ID, lastID)
1371 t.Errorf("%#04x: Insecure CipherSuite returned by CipherSuites()", c.ID)
1375 for _, c := range InsecureCipherSuites() {
1377 t.Errorf("InsecureCipherSuites are not ordered by ID: got %#04x after %#04x", c.ID, lastID)
1383 t.Errorf("%#04x: not Insecure CipherSuite returned by InsecureCipherSuites()", c.ID)
1387 CipherSuiteByID := func(id uint16) *CipherSuite {
1388 for _, c := range CipherSuites() {
1393 for _, c := range InsecureCipherSuites() {
1401 for _, c := range cipherSuites {
1402 cc := CipherSuiteByID(c.id)
1404 t.Errorf("%#04x: no CipherSuite entry", c.id)
1408 if tls12Only := c.flags&suiteTLS12 != 0; tls12Only && len(cc.SupportedVersions) != 1 {
1409 t.Errorf("%#04x: suite is TLS 1.2 only, but SupportedVersions is %v", c.id, cc.SupportedVersions)
1410 } else if !tls12Only && len(cc.SupportedVersions) != 3 {
1411 t.Errorf("%#04x: suite TLS 1.0-1.2, but SupportedVersions is %v", c.id, cc.SupportedVersions)
1414 if got := CipherSuiteName(c.id); got != cc.Name {
1415 t.Errorf("%#04x: unexpected CipherSuiteName: got %q, expected %q", c.id, got, cc.Name)
1418 for _, c := range cipherSuitesTLS13 {
1419 cc := CipherSuiteByID(c.id)
1421 t.Errorf("%#04x: no CipherSuite entry", c.id)
1426 t.Errorf("%#04x: Insecure %v, expected false", c.id, cc.Insecure)
1428 if len(cc.SupportedVersions) != 1 || cc.SupportedVersions[0] != VersionTLS13 {
1429 t.Errorf("%#04x: suite is TLS 1.3 only, but SupportedVersions is %v", c.id, cc.SupportedVersions)
1432 if got := CipherSuiteName(c.id); got != cc.Name {
1433 t.Errorf("%#04x: unexpected CipherSuiteName: got %q, expected %q", c.id, got, cc.Name)
1437 if got := CipherSuiteName(0xabc); got != "0x0ABC" {
1438 t.Errorf("unexpected fallback CipherSuiteName: got %q, expected 0x0ABC", got)
1441 if len(cipherSuitesPreferenceOrder) != len(cipherSuites) {
1442 t.Errorf("cipherSuitesPreferenceOrder is not the same size as cipherSuites")
1444 if len(cipherSuitesPreferenceOrderNoAES) != len(cipherSuitesPreferenceOrder) {
1445 t.Errorf("cipherSuitesPreferenceOrderNoAES is not the same size as cipherSuitesPreferenceOrder")
1448 // Check that disabled suites are at the end of the preference lists, and
1449 // that they are marked insecure.
1450 for i, id := range disabledCipherSuites {
1451 offset := len(cipherSuitesPreferenceOrder) - len(disabledCipherSuites)
1452 if cipherSuitesPreferenceOrder[offset+i] != id {
1453 t.Errorf("disabledCipherSuites[%d]: not at the end of cipherSuitesPreferenceOrder", i)
1455 if cipherSuitesPreferenceOrderNoAES[offset+i] != id {
1456 t.Errorf("disabledCipherSuites[%d]: not at the end of cipherSuitesPreferenceOrderNoAES", i)
1458 c := CipherSuiteByID(id)
1460 t.Errorf("%#04x: no CipherSuite entry", id)
1464 t.Errorf("%#04x: disabled by default but not marked insecure", id)
1468 for i, prefOrder := range [][]uint16{cipherSuitesPreferenceOrder, cipherSuitesPreferenceOrderNoAES} {
1469 // Check that insecure and HTTP/2 bad cipher suites are at the end of
1470 // the preference lists.
1471 var sawInsecure, sawBad bool
1472 for _, id := range prefOrder {
1473 c := CipherSuiteByID(id)
1475 t.Errorf("%#04x: no CipherSuite entry", id)
1481 } else if sawInsecure {
1482 t.Errorf("%#04x: secure suite after insecure one(s)", id)
1485 if http2isBadCipher(id) {
1488 t.Errorf("%#04x: non-bad suite after bad HTTP/2 one(s)", id)
1492 // Check that the list is sorted according to the documented criteria.
1493 isBetter := func(a, b int) bool {
1494 aSuite, bSuite := cipherSuiteByID(prefOrder[a]), cipherSuiteByID(prefOrder[b])
1495 aName, bName := CipherSuiteName(prefOrder[a]), CipherSuiteName(prefOrder[b])
1497 if !strings.Contains(aName, "RC4") && strings.Contains(bName, "RC4") {
1499 } else if strings.Contains(aName, "RC4") && !strings.Contains(bName, "RC4") {
1503 if !strings.Contains(aName, "CBC_SHA256") && strings.Contains(bName, "CBC_SHA256") {
1505 } else if strings.Contains(aName, "CBC_SHA256") && !strings.Contains(bName, "CBC_SHA256") {
1509 if !strings.Contains(aName, "3DES") && strings.Contains(bName, "3DES") {
1511 } else if strings.Contains(aName, "3DES") && !strings.Contains(bName, "3DES") {
1515 if aSuite.flags&suiteECDHE != 0 && bSuite.flags&suiteECDHE == 0 {
1517 } else if aSuite.flags&suiteECDHE == 0 && bSuite.flags&suiteECDHE != 0 {
1521 if aSuite.aead != nil && bSuite.aead == nil {
1523 } else if aSuite.aead == nil && bSuite.aead != nil {
1527 if strings.Contains(aName, "AES") && strings.Contains(bName, "CHACHA20") {
1528 return i == 0 // true for cipherSuitesPreferenceOrder
1529 } else if strings.Contains(aName, "CHACHA20") && strings.Contains(bName, "AES") {
1530 return i != 0 // true for cipherSuitesPreferenceOrderNoAES
1532 // AES-128 < AES-256
1533 if strings.Contains(aName, "AES_128") && strings.Contains(bName, "AES_256") {
1535 } else if strings.Contains(aName, "AES_256") && strings.Contains(bName, "AES_128") {
1539 if aSuite.flags&suiteECSign != 0 && bSuite.flags&suiteECSign == 0 {
1541 } else if aSuite.flags&suiteECSign == 0 && bSuite.flags&suiteECSign != 0 {
1544 t.Fatalf("two ciphersuites are equal by all criteria: %v and %v", aName, bName)
1545 panic("unreachable")
1547 if !sort.SliceIsSorted(prefOrder, isBetter) {
1548 t.Error("preference order is not sorted according to the rules")
1553 // http2isBadCipher is copied from net/http.
1554 // TODO: if it ends up exposed somewhere, use that instead.
1555 func http2isBadCipher(cipher uint16) bool {
1557 case TLS_RSA_WITH_RC4_128_SHA,
1558 TLS_RSA_WITH_3DES_EDE_CBC_SHA,
1559 TLS_RSA_WITH_AES_128_CBC_SHA,
1560 TLS_RSA_WITH_AES_256_CBC_SHA,
1561 TLS_RSA_WITH_AES_128_CBC_SHA256,
1562 TLS_RSA_WITH_AES_128_GCM_SHA256,
1563 TLS_RSA_WITH_AES_256_GCM_SHA384,
1564 TLS_ECDHE_ECDSA_WITH_RC4_128_SHA,
1565 TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA,
1566 TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA,
1567 TLS_ECDHE_RSA_WITH_RC4_128_SHA,
1568 TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA,
1569 TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,
1570 TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA,
1571 TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256,
1572 TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256:
1579 type brokenSigner struct{ crypto.Signer }
1581 func (s brokenSigner) Sign(rand io.Reader, digest []byte, opts crypto.SignerOpts) (signature []byte, err error) {
1582 // Replace opts with opts.HashFunc(), so rsa.PSSOptions are discarded.
1583 return s.Signer.Sign(rand, digest, opts.HashFunc())
1586 // TestPKCS1OnlyCert uses a client certificate with a broken crypto.Signer that
1587 // always makes PKCS #1 v1.5 signatures, so can't be used with RSA-PSS.
1588 func TestPKCS1OnlyCert(t *testing.T) {
1589 clientConfig := testConfig.Clone()
1590 clientConfig.Certificates = []Certificate{{
1591 Certificate: [][]byte{testRSACertificate},
1592 PrivateKey: brokenSigner{testRSAPrivateKey},
1594 serverConfig := testConfig.Clone()
1595 serverConfig.MaxVersion = VersionTLS12 // TLS 1.3 doesn't support PKCS #1 v1.5
1596 serverConfig.ClientAuth = RequireAnyClientCert
1598 // If RSA-PSS is selected, the handshake should fail.
1599 if _, _, err := testHandshake(t, clientConfig, serverConfig); err == nil {
1600 t.Fatal("expected broken certificate to cause connection to fail")
1603 clientConfig.Certificates[0].SupportedSignatureAlgorithms =
1604 []SignatureScheme{PKCS1WithSHA1, PKCS1WithSHA256}
1606 // But if the certificate restricts supported algorithms, RSA-PSS should not
1607 // be selected, and the handshake should succeed.
1608 if _, _, err := testHandshake(t, clientConfig, serverConfig); err != nil {