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.
26 var rsaCertPEM = `-----BEGIN CERTIFICATE-----
27 MIIB0zCCAX2gAwIBAgIJAI/M7BYjwB+uMA0GCSqGSIb3DQEBBQUAMEUxCzAJBgNV
28 BAYTAkFVMRMwEQYDVQQIDApTb21lLVN0YXRlMSEwHwYDVQQKDBhJbnRlcm5ldCBX
29 aWRnaXRzIFB0eSBMdGQwHhcNMTIwOTEyMjE1MjAyWhcNMTUwOTEyMjE1MjAyWjBF
30 MQswCQYDVQQGEwJBVTETMBEGA1UECAwKU29tZS1TdGF0ZTEhMB8GA1UECgwYSW50
31 ZXJuZXQgV2lkZ2l0cyBQdHkgTHRkMFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBANLJ
32 hPHhITqQbPklG3ibCVxwGMRfp/v4XqhfdQHdcVfHap6NQ5Wok/4xIA+ui35/MmNa
33 rtNuC+BdZ1tMuVCPFZcCAwEAAaNQME4wHQYDVR0OBBYEFJvKs8RfJaXTH08W+SGv
34 zQyKn0H8MB8GA1UdIwQYMBaAFJvKs8RfJaXTH08W+SGvzQyKn0H8MAwGA1UdEwQF
35 MAMBAf8wDQYJKoZIhvcNAQEFBQADQQBJlffJHybjDGxRMqaRmDhX0+6v02TUKZsW
36 r5QuVbpQhH6u+0UgcW0jp9QwpxoPTLTWGXEWBBBurxFwiCBhkQ+V
37 -----END CERTIFICATE-----
40 var rsaKeyPEM = testingKey(`-----BEGIN RSA TESTING KEY-----
41 MIIBOwIBAAJBANLJhPHhITqQbPklG3ibCVxwGMRfp/v4XqhfdQHdcVfHap6NQ5Wo
42 k/4xIA+ui35/MmNartNuC+BdZ1tMuVCPFZcCAwEAAQJAEJ2N+zsR0Xn8/Q6twa4G
43 6OB1M1WO+k+ztnX/1SvNeWu8D6GImtupLTYgjZcHufykj09jiHmjHx8u8ZZB/o1N
44 MQIhAPW+eyZo7ay3lMz1V01WVjNKK9QSn1MJlb06h/LuYv9FAiEA25WPedKgVyCW
45 SmUwbPw8fnTcpqDWE3yTO3vKcebqMSsCIBF3UmVue8YU3jybC3NxuXq3wNm34R8T
46 xVLHwDXh/6NJAiEAl2oHGGLz64BuAfjKrqwz7qMYr9HCLIe/YsoWq/olzScCIQDi
47 D2lWusoe2/nEqfDVVWGWlyJ7yOmqaVm/iNUN9B2N2g==
48 -----END RSA TESTING KEY-----
51 // keyPEM is the same as rsaKeyPEM, but declares itself as just
52 // "PRIVATE KEY", not "RSA PRIVATE KEY". https://golang.org/issue/4477
53 var keyPEM = testingKey(`-----BEGIN 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 TESTING KEY-----
64 var ecdsaCertPEM = `-----BEGIN CERTIFICATE-----
65 MIIB/jCCAWICCQDscdUxw16XFDAJBgcqhkjOPQQBMEUxCzAJBgNVBAYTAkFVMRMw
66 EQYDVQQIEwpTb21lLVN0YXRlMSEwHwYDVQQKExhJbnRlcm5ldCBXaWRnaXRzIFB0
67 eSBMdGQwHhcNMTIxMTE0MTI0MDQ4WhcNMTUxMTE0MTI0MDQ4WjBFMQswCQYDVQQG
68 EwJBVTETMBEGA1UECBMKU29tZS1TdGF0ZTEhMB8GA1UEChMYSW50ZXJuZXQgV2lk
69 Z2l0cyBQdHkgTHRkMIGbMBAGByqGSM49AgEGBSuBBAAjA4GGAAQBY9+my9OoeSUR
70 lDQdV/x8LsOuLilthhiS1Tz4aGDHIPwC1mlvnf7fg5lecYpMCrLLhauAc1UJXcgl
71 01xoLuzgtAEAgv2P/jgytzRSpUYvgLBt1UA0leLYBy6mQQbrNEuqT3INapKIcUv8
72 XxYP0xMEUksLPq6Ca+CRSqTtrd/23uTnapkwCQYHKoZIzj0EAQOBigAwgYYCQXJo
73 A7Sl2nLVf+4Iu/tAX/IF4MavARKC4PPHK3zfuGfPR3oCCcsAoz3kAzOeijvd0iXb
74 H5jBImIxPL4WxQNiBTexAkF8D1EtpYuWdlVQ80/h/f4pBcGiXPqX5h2PQSQY7hP1
75 +jwM1FGS4fREIOvlBYr/SzzQRtwrvrzGYxDEDbsC0ZGRnA==
76 -----END CERTIFICATE-----
79 var ecdsaKeyPEM = testingKey(`-----BEGIN EC PARAMETERS-----
81 -----END EC PARAMETERS-----
82 -----BEGIN EC TESTING KEY-----
83 MIHcAgEBBEIBrsoKp0oqcv6/JovJJDoDVSGWdirrkgCWxrprGlzB9o0X8fV675X0
84 NwuBenXFfeZvVcwluO7/Q9wkYoPd/t3jGImgBwYFK4EEACOhgYkDgYYABAFj36bL
85 06h5JRGUNB1X/Hwuw64uKW2GGJLVPPhoYMcg/ALWaW+d/t+DmV5xikwKssuFq4Bz
86 VQldyCXTXGgu7OC0AQCC/Y/+ODK3NFKlRi+AsG3VQDSV4tgHLqZBBus0S6pPcg1q
87 kohxS/xfFg/TEwRSSws+roJr4JFKpO2t3/be5OdqmQ==
88 -----END EC TESTING KEY-----
91 var keyPairTests = []struct {
96 {"ECDSA", ecdsaCertPEM, ecdsaKeyPEM},
97 {"RSA", rsaCertPEM, rsaKeyPEM},
98 {"RSA-untyped", rsaCertPEM, keyPEM}, // golang.org/issue/4477
101 func TestX509KeyPair(t *testing.T) {
104 for _, test := range keyPairTests {
105 pem = []byte(test.cert + test.key)
106 if _, err := X509KeyPair(pem, pem); err != nil {
107 t.Errorf("Failed to load %s cert followed by %s key: %s", test.algo, test.algo, err)
109 pem = []byte(test.key + test.cert)
110 if _, err := X509KeyPair(pem, pem); err != nil {
111 t.Errorf("Failed to load %s key followed by %s cert: %s", test.algo, test.algo, err)
116 func TestX509KeyPairErrors(t *testing.T) {
117 _, err := X509KeyPair([]byte(rsaKeyPEM), []byte(rsaCertPEM))
119 t.Fatalf("X509KeyPair didn't return an error when arguments were switched")
121 if subStr := "been switched"; !strings.Contains(err.Error(), subStr) {
122 t.Fatalf("Expected %q in the error when switching arguments to X509KeyPair, but the error was %q", subStr, err)
125 _, err = X509KeyPair([]byte(rsaCertPEM), []byte(rsaCertPEM))
127 t.Fatalf("X509KeyPair didn't return an error when both arguments were certificates")
129 if subStr := "certificate"; !strings.Contains(err.Error(), subStr) {
130 t.Fatalf("Expected %q in the error when both arguments to X509KeyPair were certificates, but the error was %q", subStr, err)
133 const nonsensePEM = `
134 -----BEGIN NONSENSE-----
136 -----END NONSENSE-----
139 _, err = X509KeyPair([]byte(nonsensePEM), []byte(nonsensePEM))
141 t.Fatalf("X509KeyPair didn't return an error when both arguments were nonsense")
143 if subStr := "NONSENSE"; !strings.Contains(err.Error(), subStr) {
144 t.Fatalf("Expected %q in the error when both arguments to X509KeyPair were nonsense, but the error was %q", subStr, err)
148 func TestX509MixedKeyPair(t *testing.T) {
149 if _, err := X509KeyPair([]byte(rsaCertPEM), []byte(ecdsaKeyPEM)); err == nil {
150 t.Error("Load of RSA certificate succeeded with ECDSA private key")
152 if _, err := X509KeyPair([]byte(ecdsaCertPEM), []byte(rsaKeyPEM)); err == nil {
153 t.Error("Load of ECDSA certificate succeeded with RSA private key")
157 func newLocalListener(t testing.TB) net.Listener {
158 ln, err := net.Listen("tcp", "127.0.0.1:0")
160 ln, err = net.Listen("tcp6", "[::1]:0")
168 func TestDialTimeout(t *testing.T) {
170 t.Skip("skipping in short mode")
172 listener := newLocalListener(t)
174 addr := listener.Addr().String()
175 defer listener.Close()
177 complete := make(chan bool)
178 defer close(complete)
181 conn, err := listener.Accept()
190 dialer := &net.Dialer{
191 Timeout: 10 * time.Millisecond,
195 if _, err = DialWithDialer(dialer, "tcp", addr, nil); err == nil {
196 t.Fatal("DialWithTimeout completed successfully")
199 if !isTimeoutError(err) {
200 t.Errorf("resulting error not a timeout: %v\nType %T: %#v", err, err, err)
204 func isTimeoutError(err error) bool {
205 if ne, ok := err.(net.Error); ok {
211 // tests that Conn.Read returns (non-zero, io.EOF) instead of
212 // (non-zero, nil) when a Close (alertCloseNotify) is sitting right
213 // behind the application data in the buffer.
214 func TestConnReadNonzeroAndEOF(t *testing.T) {
215 // This test is racy: it assumes that after a write to a
216 // localhost TCP connection, the peer TCP connection can
217 // immediately read it. Because it's racy, we skip this test
218 // in short mode, and then retry it several times with an
219 // increasing sleep in between our final write (via srv.Close
220 // below) and the following read.
222 t.Skip("skipping in short mode")
225 for delay := time.Millisecond; delay <= 64*time.Millisecond; delay *= 2 {
226 if err = testConnReadNonzeroAndEOF(t, delay); err == nil {
233 func testConnReadNonzeroAndEOF(t *testing.T, delay time.Duration) error {
234 ln := newLocalListener(t)
237 srvCh := make(chan *Conn, 1)
240 sconn, err := ln.Accept()
246 serverConfig := testConfig.Clone()
247 srv := Server(sconn, serverConfig)
248 if err := srv.Handshake(); err != nil {
249 serr = fmt.Errorf("handshake: %v", err)
256 clientConfig := testConfig.Clone()
257 // In TLS 1.3, alerts are encrypted and disguised as application data, so
258 // the opportunistic peek won't work.
259 clientConfig.MaxVersion = VersionTLS12
260 conn, err := Dial("tcp", ln.Addr().String(), clientConfig)
271 buf := make([]byte, 6)
273 srv.Write([]byte("foobar"))
274 n, err := conn.Read(buf)
275 if n != 6 || err != nil || string(buf) != "foobar" {
276 return fmt.Errorf("Read = %d, %v, data %q; want 6, nil, foobar", n, err, buf)
279 srv.Write([]byte("abcdef"))
282 n, err = conn.Read(buf)
283 if n != 6 || string(buf) != "abcdef" {
284 return fmt.Errorf("Read = %d, buf= %q; want 6, abcdef", n, buf)
287 return fmt.Errorf("Second Read error = %v; want io.EOF", err)
292 func TestTLSUniqueMatches(t *testing.T) {
293 ln := newLocalListener(t)
296 serverTLSUniques := make(chan []byte)
297 parentDone := make(chan struct{})
298 childDone := make(chan struct{})
299 defer close(parentDone)
301 defer close(childDone)
302 for i := 0; i < 2; i++ {
303 sconn, err := ln.Accept()
308 serverConfig := testConfig.Clone()
309 serverConfig.MaxVersion = VersionTLS12 // TLSUnique is not defined in TLS 1.3
310 srv := Server(sconn, serverConfig)
311 if err := srv.Handshake(); err != nil {
318 case serverTLSUniques <- srv.ConnectionState().TLSUnique:
323 clientConfig := testConfig.Clone()
324 clientConfig.ClientSessionCache = NewLRUClientSessionCache(1)
325 conn, err := Dial("tcp", ln.Addr().String(), clientConfig)
330 var serverTLSUniquesValue []byte
334 case serverTLSUniquesValue = <-serverTLSUniques:
337 if !bytes.Equal(conn.ConnectionState().TLSUnique, serverTLSUniquesValue) {
338 t.Error("client and server channel bindings differ")
342 conn, err = Dial("tcp", ln.Addr().String(), clientConfig)
347 if !conn.ConnectionState().DidResume {
348 t.Error("second session did not use resumption")
354 case serverTLSUniquesValue = <-serverTLSUniques:
357 if !bytes.Equal(conn.ConnectionState().TLSUnique, serverTLSUniquesValue) {
358 t.Error("client and server channel bindings differ when session resumption is used")
362 func TestVerifyHostname(t *testing.T) {
363 testenv.MustHaveExternalNetwork(t)
365 c, err := Dial("tcp", "www.google.com:https", nil)
369 if err := c.VerifyHostname("www.google.com"); err != nil {
370 t.Fatalf("verify www.google.com: %v", err)
372 if err := c.VerifyHostname("www.yahoo.com"); err == nil {
373 t.Fatalf("verify www.yahoo.com succeeded")
376 c, err = Dial("tcp", "www.google.com:https", &Config{InsecureSkipVerify: true})
380 if err := c.VerifyHostname("www.google.com"); err == nil {
381 t.Fatalf("verify www.google.com succeeded with InsecureSkipVerify=true")
385 func TestConnCloseBreakingWrite(t *testing.T) {
386 ln := newLocalListener(t)
389 srvCh := make(chan *Conn, 1)
394 sconn, err = ln.Accept()
400 serverConfig := testConfig.Clone()
401 srv := Server(sconn, serverConfig)
402 if err := srv.Handshake(); err != nil {
403 serr = fmt.Errorf("handshake: %v", err)
410 cconn, err := net.Dial("tcp", ln.Addr().String())
416 conn := &changeImplConn{
420 clientConfig := testConfig.Clone()
421 tconn := Client(conn, clientConfig)
422 if err := tconn.Handshake(); err != nil {
432 connClosed := make(chan struct{})
433 conn.closeFunc = func() error {
438 inWrite := make(chan bool, 1)
439 var errConnClosed = errors.New("conn closed for test")
440 conn.writeFunc = func(p []byte) (n int, err error) {
443 return 0, errConnClosed
446 closeReturned := make(chan bool, 1)
449 tconn.Close() // test that this doesn't block forever.
450 closeReturned <- true
453 _, err = tconn.Write([]byte("foo"))
454 if err != errConnClosed {
455 t.Errorf("Write error = %v; want errConnClosed", err)
459 if err := tconn.Close(); err != errClosed {
460 t.Errorf("Close error = %v; want errClosed", err)
464 func TestConnCloseWrite(t *testing.T) {
465 ln := newLocalListener(t)
468 clientDoneChan := make(chan struct{})
470 serverCloseWrite := func() error {
471 sconn, err := ln.Accept()
473 return fmt.Errorf("accept: %v", err)
477 serverConfig := testConfig.Clone()
478 srv := Server(sconn, serverConfig)
479 if err := srv.Handshake(); err != nil {
480 return fmt.Errorf("handshake: %v", err)
484 data, err := ioutil.ReadAll(srv)
489 return fmt.Errorf("Read data = %q; want nothing", data)
492 if err := srv.CloseWrite(); err != nil {
493 return fmt.Errorf("server CloseWrite: %v", err)
496 // Wait for clientCloseWrite to finish, so we know we
497 // tested the CloseWrite before we defer the
498 // sconn.Close above, which would also cause the
499 // client to unblock like CloseWrite.
504 clientCloseWrite := func() error {
505 defer close(clientDoneChan)
507 clientConfig := testConfig.Clone()
508 conn, err := Dial("tcp", ln.Addr().String(), clientConfig)
512 if err := conn.Handshake(); err != nil {
517 if err := conn.CloseWrite(); err != nil {
518 return fmt.Errorf("client CloseWrite: %v", err)
521 if _, err := conn.Write([]byte{0}); err != errShutdown {
522 return fmt.Errorf("CloseWrite error = %v; want errShutdown", err)
525 data, err := ioutil.ReadAll(conn)
530 return fmt.Errorf("Read data = %q; want nothing", data)
535 errChan := make(chan error, 2)
537 go func() { errChan <- serverCloseWrite() }()
538 go func() { errChan <- clientCloseWrite() }()
540 for i := 0; i < 2; i++ {
542 case err := <-errChan:
546 case <-time.After(10 * time.Second):
551 // Also test CloseWrite being called before the handshake is
554 ln2 := newLocalListener(t)
557 netConn, err := net.Dial("tcp", ln2.Addr().String())
561 defer netConn.Close()
562 conn := Client(netConn, testConfig.Clone())
564 if err := conn.CloseWrite(); err != errEarlyCloseWrite {
565 t.Errorf("CloseWrite error = %v; want errEarlyCloseWrite", err)
570 func TestWarningAlertFlood(t *testing.T) {
571 ln := newLocalListener(t)
574 server := func() error {
575 sconn, err := ln.Accept()
577 return fmt.Errorf("accept: %v", err)
581 serverConfig := testConfig.Clone()
582 srv := Server(sconn, serverConfig)
583 if err := srv.Handshake(); err != nil {
584 return fmt.Errorf("handshake: %v", err)
588 _, err = ioutil.ReadAll(srv)
590 return errors.New("unexpected lack of error from server")
592 const expected = "too many ignored"
593 if str := err.Error(); !strings.Contains(str, expected) {
594 return fmt.Errorf("expected error containing %q, but saw: %s", expected, str)
600 errChan := make(chan error, 1)
601 go func() { errChan <- server() }()
603 clientConfig := testConfig.Clone()
604 clientConfig.MaxVersion = VersionTLS12 // there are no warning alerts in TLS 1.3
605 conn, err := Dial("tcp", ln.Addr().String(), clientConfig)
610 if err := conn.Handshake(); err != nil {
614 for i := 0; i < maxUselessRecords+1; i++ {
615 conn.sendAlert(alertNoRenegotiation)
618 if err := <-errChan; err != nil {
623 func TestCloneFuncFields(t *testing.T) {
624 const expectedCount = 5
628 Time: func() time.Time {
632 GetCertificate: func(*ClientHelloInfo) (*Certificate, error) {
636 GetClientCertificate: func(*CertificateRequestInfo) (*Certificate, error) {
640 GetConfigForClient: func(*ClientHelloInfo) (*Config, error) {
644 VerifyPeerCertificate: func(rawCerts [][]byte, verifiedChains [][]*x509.Certificate) error {
653 c2.GetCertificate(nil)
654 c2.GetClientCertificate(nil)
655 c2.GetConfigForClient(nil)
656 c2.VerifyPeerCertificate(nil, nil)
658 if called != (1<<expectedCount)-1 {
659 t.Fatalf("expected %d calls but saw calls %b", expectedCount, called)
663 func TestCloneNonFuncFields(t *testing.T) {
665 v := reflect.ValueOf(&c1).Elem()
668 for i := 0; i < typ.NumField(); i++ {
671 // unexported field; not cloned.
675 // testing/quick can't handle functions or interfaces and so
677 switch fn := typ.Field(i).Name; fn {
679 f.Set(reflect.ValueOf(io.Reader(os.Stdin)))
680 case "Time", "GetCertificate", "GetConfigForClient", "VerifyPeerCertificate", "GetClientCertificate":
681 // DeepEqual can't compare functions. If you add a
682 // function field to this list, you must also change
683 // TestCloneFuncFields to ensure that the func field is
686 f.Set(reflect.ValueOf([]Certificate{
687 {Certificate: [][]byte{{'b'}}},
689 case "NameToCertificate":
690 f.Set(reflect.ValueOf(map[string]*Certificate{"a": nil}))
691 case "RootCAs", "ClientCAs":
692 f.Set(reflect.ValueOf(x509.NewCertPool()))
693 case "ClientSessionCache":
694 f.Set(reflect.ValueOf(NewLRUClientSessionCache(10)))
696 f.Set(reflect.ValueOf(io.Writer(os.Stdout)))
698 f.Set(reflect.ValueOf([]string{"a", "b"}))
700 f.Set(reflect.ValueOf("b"))
702 f.Set(reflect.ValueOf(VerifyClientCertIfGiven))
703 case "InsecureSkipVerify", "SessionTicketsDisabled", "DynamicRecordSizingDisabled", "PreferServerCipherSuites":
704 f.Set(reflect.ValueOf(true))
705 case "MinVersion", "MaxVersion":
706 f.Set(reflect.ValueOf(uint16(VersionTLS12)))
707 case "SessionTicketKey":
708 f.Set(reflect.ValueOf([32]byte{}))
710 f.Set(reflect.ValueOf([]uint16{1, 2}))
711 case "CurvePreferences":
712 f.Set(reflect.ValueOf([]CurveID{CurveP256}))
713 case "Renegotiation":
714 f.Set(reflect.ValueOf(RenegotiateOnceAsClient))
716 t.Errorf("all fields must be accounted for, but saw unknown field %q", fn)
721 // DeepEqual also compares unexported fields, thus c2 needs to have run
722 // serverInit in order to be DeepEqual to c1. Cloning it and discarding
723 // the result is sufficient.
726 if !reflect.DeepEqual(&c1, c2) {
727 t.Errorf("clone failed to copy a field")
731 // changeImplConn is a net.Conn which can change its Write and Close
733 type changeImplConn struct {
735 writeFunc func([]byte) (int, error)
736 closeFunc func() error
739 func (w *changeImplConn) Write(p []byte) (n int, err error) {
740 if w.writeFunc != nil {
741 return w.writeFunc(p)
743 return w.Conn.Write(p)
746 func (w *changeImplConn) Close() error {
747 if w.closeFunc != nil {
750 return w.Conn.Close()
753 func throughput(b *testing.B, version uint16, totalBytes int64, dynamicRecordSizingDisabled bool) {
754 ln := newLocalListener(b)
759 // Less than 64KB because Windows appears to use a TCP rwin < 64KB.
761 const bufsize = 32 << 10
764 buf := make([]byte, bufsize)
765 for i := 0; i < N; i++ {
766 sconn, err := ln.Accept()
768 // panic rather than synchronize to avoid benchmark overhead
769 // (cannot call b.Fatal in goroutine)
770 panic(fmt.Errorf("accept: %v", err))
772 serverConfig := testConfig.Clone()
773 serverConfig.CipherSuites = nil // the defaults may prefer faster ciphers
774 serverConfig.DynamicRecordSizingDisabled = dynamicRecordSizingDisabled
775 srv := Server(sconn, serverConfig)
776 if err := srv.Handshake(); err != nil {
777 panic(fmt.Errorf("handshake: %v", err))
779 if _, err := io.CopyBuffer(srv, srv, buf); err != nil {
780 panic(fmt.Errorf("copy buffer: %v", err))
785 b.SetBytes(totalBytes)
786 clientConfig := testConfig.Clone()
787 clientConfig.CipherSuites = nil // the defaults may prefer faster ciphers
788 clientConfig.DynamicRecordSizingDisabled = dynamicRecordSizingDisabled
789 clientConfig.MaxVersion = version
791 buf := make([]byte, bufsize)
792 chunks := int(math.Ceil(float64(totalBytes) / float64(len(buf))))
793 for i := 0; i < N; i++ {
794 conn, err := Dial("tcp", ln.Addr().String(), clientConfig)
798 for j := 0; j < chunks; j++ {
799 _, err := conn.Write(buf)
803 _, err = io.ReadFull(conn, buf)
812 func BenchmarkThroughput(b *testing.B) {
813 for _, mode := range []string{"Max", "Dynamic"} {
814 for size := 1; size <= 64; size <<= 1 {
815 name := fmt.Sprintf("%sPacket/%dMB", mode, size)
816 b.Run(name, func(b *testing.B) {
817 b.Run("TLSv12", func(b *testing.B) {
818 throughput(b, VersionTLS12, int64(size<<20), mode == "Max")
820 b.Run("TLSv13", func(b *testing.B) {
821 throughput(b, VersionTLS13, int64(size<<20), mode == "Max")
828 type slowConn struct {
833 func (c *slowConn) Write(p []byte) (int, error) {
840 time.Sleep(100 * time.Microsecond)
841 allowed := int(time.Since(t0).Seconds()*float64(c.bps)) / 8
842 if allowed > len(p) {
846 n, err := c.Conn.Write(p[wrote:allowed])
856 func latency(b *testing.B, version uint16, bps int, dynamicRecordSizingDisabled bool) {
857 ln := newLocalListener(b)
863 for i := 0; i < N; i++ {
864 sconn, err := ln.Accept()
866 // panic rather than synchronize to avoid benchmark overhead
867 // (cannot call b.Fatal in goroutine)
868 panic(fmt.Errorf("accept: %v", err))
870 serverConfig := testConfig.Clone()
871 serverConfig.DynamicRecordSizingDisabled = dynamicRecordSizingDisabled
872 srv := Server(&slowConn{sconn, bps}, serverConfig)
873 if err := srv.Handshake(); err != nil {
874 panic(fmt.Errorf("handshake: %v", err))
880 clientConfig := testConfig.Clone()
881 clientConfig.DynamicRecordSizingDisabled = dynamicRecordSizingDisabled
882 clientConfig.MaxVersion = version
884 buf := make([]byte, 16384)
885 peek := make([]byte, 1)
887 for i := 0; i < N; i++ {
888 conn, err := Dial("tcp", ln.Addr().String(), clientConfig)
892 // make sure we're connected and previous connection has stopped
893 if _, err := conn.Write(buf[:1]); err != nil {
896 if _, err := io.ReadFull(conn, peek); err != nil {
899 if _, err := conn.Write(buf); err != nil {
902 if _, err = io.ReadFull(conn, peek); err != nil {
909 func BenchmarkLatency(b *testing.B) {
910 for _, mode := range []string{"Max", "Dynamic"} {
911 for _, kbps := range []int{200, 500, 1000, 2000, 5000} {
912 name := fmt.Sprintf("%sPacket/%dkbps", mode, kbps)
913 b.Run(name, func(b *testing.B) {
914 b.Run("TLSv12", func(b *testing.B) {
915 latency(b, VersionTLS12, kbps*1000, mode == "Max")
917 b.Run("TLSv13", func(b *testing.B) {
918 latency(b, VersionTLS13, kbps*1000, mode == "Max")
925 func TestConnectionStateMarshal(t *testing.T) {
926 cs := &ConnectionState{}
927 _, err := json.Marshal(cs)
929 t.Errorf("json.Marshal failed on ConnectionState: %v", err)
933 func TestConnectionState(t *testing.T) {
934 issuer, err := x509.ParseCertificate(testRSACertificateIssuer)
938 rootCAs := x509.NewCertPool()
939 rootCAs.AddCert(issuer)
941 now := func() time.Time { return time.Unix(1476984729, 0) }
943 const alpnProtocol = "golang"
944 const serverName = "example.golang"
945 var scts = [][]byte{[]byte("dummy sct 1"), []byte("dummy sct 2")}
946 var ocsp = []byte("dummy ocsp")
948 for _, v := range []uint16{VersionTLS12, VersionTLS13} {
956 t.Run(name, func(t *testing.T) {
960 Certificates: make([]Certificate, 1),
964 ClientAuth: RequireAndVerifyClientCert,
965 NextProtos: []string{alpnProtocol},
966 ServerName: serverName,
968 config.Certificates[0].Certificate = [][]byte{testRSACertificate}
969 config.Certificates[0].PrivateKey = testRSAPrivateKey
970 config.Certificates[0].SignedCertificateTimestamps = scts
971 config.Certificates[0].OCSPStaple = ocsp
973 ss, cs, err := testHandshake(t, config, config)
975 t.Fatalf("Handshake failed: %v", err)
978 if ss.Version != v || cs.Version != v {
979 t.Errorf("Got versions %x (server) and %x (client), expected %x", ss.Version, cs.Version, v)
982 if !ss.HandshakeComplete || !cs.HandshakeComplete {
983 t.Errorf("Got HandshakeComplete %v (server) and %v (client), expected true", ss.HandshakeComplete, cs.HandshakeComplete)
986 if ss.DidResume || cs.DidResume {
987 t.Errorf("Got DidResume %v (server) and %v (client), expected false", ss.DidResume, cs.DidResume)
990 if ss.CipherSuite == 0 || cs.CipherSuite == 0 {
991 t.Errorf("Got invalid cipher suite: %v (server) and %v (client)", ss.CipherSuite, cs.CipherSuite)
994 if ss.NegotiatedProtocol != alpnProtocol || cs.NegotiatedProtocol != alpnProtocol {
995 t.Errorf("Got negotiated protocol %q (server) and %q (client), expected %q", ss.NegotiatedProtocol, cs.NegotiatedProtocol, alpnProtocol)
998 if !cs.NegotiatedProtocolIsMutual {
999 t.Errorf("Got false NegotiatedProtocolIsMutual on the client side")
1001 // NegotiatedProtocolIsMutual on the server side is unspecified.
1003 if ss.ServerName != serverName {
1004 t.Errorf("Got server name %q, expected %q", ss.ServerName, serverName)
1006 if cs.ServerName != "" {
1007 t.Errorf("Got unexpected server name on the client side")
1010 if len(ss.PeerCertificates) != 1 || len(cs.PeerCertificates) != 1 {
1011 t.Errorf("Got %d (server) and %d (client) peer certificates, expected %d", len(ss.PeerCertificates), len(cs.PeerCertificates), 1)
1014 if len(ss.VerifiedChains) != 1 || len(cs.VerifiedChains) != 1 {
1015 t.Errorf("Got %d (server) and %d (client) verified chains, expected %d", len(ss.VerifiedChains), len(cs.VerifiedChains), 1)
1016 } else if len(ss.VerifiedChains[0]) != 2 || len(cs.VerifiedChains[0]) != 2 {
1017 t.Errorf("Got %d (server) and %d (client) long verified chain, expected %d", len(ss.VerifiedChains[0]), len(cs.VerifiedChains[0]), 2)
1020 if len(cs.SignedCertificateTimestamps) != 2 {
1021 t.Errorf("Got %d SCTs, expected %d", len(cs.SignedCertificateTimestamps), 2)
1023 if !bytes.Equal(cs.OCSPResponse, ocsp) {
1024 t.Errorf("Got OCSPs %x, expected %x", cs.OCSPResponse, ocsp)
1026 // Only TLS 1.3 supports OCSP and SCTs on client certs.
1027 if v == VersionTLS13 {
1028 if len(ss.SignedCertificateTimestamps) != 2 {
1029 t.Errorf("Got %d client SCTs, expected %d", len(ss.SignedCertificateTimestamps), 2)
1031 if !bytes.Equal(ss.OCSPResponse, ocsp) {
1032 t.Errorf("Got client OCSPs %x, expected %x", ss.OCSPResponse, ocsp)
1036 if v == VersionTLS13 {
1037 if ss.TLSUnique != nil || cs.TLSUnique != nil {
1038 t.Errorf("Got TLSUnique %x (server) and %x (client), expected nil in TLS 1.3", ss.TLSUnique, cs.TLSUnique)
1041 if ss.TLSUnique == nil || cs.TLSUnique == nil {
1042 t.Errorf("Got TLSUnique %x (server) and %x (client), expected non-nil", ss.TLSUnique, cs.TLSUnique)
1049 // Issue 28744: Ensure that we don't modify memory
1050 // that Config doesn't own such as Certificates.
1051 func TestBuildNameToCertificate_doesntModifyCertificates(t *testing.T) {
1053 Certificate: [][]byte{testRSACertificate},
1054 PrivateKey: testRSAPrivateKey,
1057 Certificate: [][]byte{testSNICertificate},
1058 PrivateKey: testRSAPrivateKey,
1060 config := testConfig.Clone()
1061 config.Certificates = []Certificate{c0, c1}
1063 config.BuildNameToCertificate()
1064 got := config.Certificates
1065 want := []Certificate{c0, c1}
1066 if !reflect.DeepEqual(got, want) {
1067 t.Fatalf("Certificates were mutated by BuildNameToCertificate\nGot: %#v\nWant: %#v\n", got, want)
1071 func testingKey(s string) string { return strings.ReplaceAll(s, "TESTING KEY", "PRIVATE KEY") }
1073 func TestClientHelloInfo_SupportsCertificate(t *testing.T) {
1074 rsaCert := &Certificate{
1075 Certificate: [][]byte{testRSACertificate},
1076 PrivateKey: testRSAPrivateKey,
1078 pkcs1Cert := &Certificate{
1079 Certificate: [][]byte{testRSACertificate},
1080 PrivateKey: testRSAPrivateKey,
1081 SupportedSignatureAlgorithms: []SignatureScheme{PKCS1WithSHA1, PKCS1WithSHA256},
1083 ecdsaCert := &Certificate{
1084 // ECDSA P-256 certificate
1085 Certificate: [][]byte{testP256Certificate},
1086 PrivateKey: testP256PrivateKey,
1088 ed25519Cert := &Certificate{
1089 Certificate: [][]byte{testEd25519Certificate},
1090 PrivateKey: testEd25519PrivateKey,
1095 chi *ClientHelloInfo
1098 {rsaCert, &ClientHelloInfo{
1099 ServerName: "example.golang",
1100 SignatureSchemes: []SignatureScheme{PSSWithSHA256},
1101 SupportedVersions: []uint16{VersionTLS13},
1103 {ecdsaCert, &ClientHelloInfo{
1104 SignatureSchemes: []SignatureScheme{PSSWithSHA256, ECDSAWithP256AndSHA256},
1105 SupportedVersions: []uint16{VersionTLS13, VersionTLS12},
1107 {rsaCert, &ClientHelloInfo{
1108 ServerName: "example.com",
1109 SignatureSchemes: []SignatureScheme{PSSWithSHA256},
1110 SupportedVersions: []uint16{VersionTLS13},
1111 }, "not valid for requested server name"},
1112 {ecdsaCert, &ClientHelloInfo{
1113 SignatureSchemes: []SignatureScheme{ECDSAWithP384AndSHA384},
1114 SupportedVersions: []uint16{VersionTLS13},
1115 }, "signature algorithms"},
1116 {pkcs1Cert, &ClientHelloInfo{
1117 SignatureSchemes: []SignatureScheme{PSSWithSHA256, ECDSAWithP256AndSHA256},
1118 SupportedVersions: []uint16{VersionTLS13},
1119 }, "signature algorithms"},
1121 {rsaCert, &ClientHelloInfo{
1122 CipherSuites: []uint16{TLS_RSA_WITH_AES_128_GCM_SHA256},
1123 SignatureSchemes: []SignatureScheme{PKCS1WithSHA1},
1124 SupportedVersions: []uint16{VersionTLS13, VersionTLS12},
1125 }, "signature algorithms"},
1126 {rsaCert, &ClientHelloInfo{
1127 CipherSuites: []uint16{TLS_RSA_WITH_AES_128_GCM_SHA256},
1128 SignatureSchemes: []SignatureScheme{PKCS1WithSHA1},
1129 SupportedVersions: []uint16{VersionTLS13, VersionTLS12},
1131 MaxVersion: VersionTLS12,
1133 }, ""}, // Check that mutual version selection works.
1135 {ecdsaCert, &ClientHelloInfo{
1136 CipherSuites: []uint16{TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256},
1137 SupportedCurves: []CurveID{CurveP256},
1138 SupportedPoints: []uint8{pointFormatUncompressed},
1139 SignatureSchemes: []SignatureScheme{ECDSAWithP256AndSHA256},
1140 SupportedVersions: []uint16{VersionTLS12},
1142 {ecdsaCert, &ClientHelloInfo{
1143 CipherSuites: []uint16{TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256},
1144 SupportedCurves: []CurveID{CurveP256},
1145 SupportedPoints: []uint8{pointFormatUncompressed},
1146 SignatureSchemes: []SignatureScheme{ECDSAWithP384AndSHA384},
1147 SupportedVersions: []uint16{VersionTLS12},
1148 }, ""}, // TLS 1.2 does not restrict curves based on the SignatureScheme.
1149 {ecdsaCert, &ClientHelloInfo{
1150 CipherSuites: []uint16{TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256},
1151 SupportedCurves: []CurveID{CurveP256},
1152 SupportedPoints: []uint8{pointFormatUncompressed},
1153 SignatureSchemes: nil,
1154 SupportedVersions: []uint16{VersionTLS12},
1155 }, ""}, // TLS 1.2 comes with default signature schemes.
1156 {ecdsaCert, &ClientHelloInfo{
1157 CipherSuites: []uint16{TLS_RSA_WITH_AES_128_GCM_SHA256},
1158 SupportedCurves: []CurveID{CurveP256},
1159 SupportedPoints: []uint8{pointFormatUncompressed},
1160 SignatureSchemes: []SignatureScheme{ECDSAWithP256AndSHA256},
1161 SupportedVersions: []uint16{VersionTLS12},
1163 {ecdsaCert, &ClientHelloInfo{
1164 CipherSuites: []uint16{TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256},
1165 SupportedCurves: []CurveID{CurveP256},
1166 SupportedPoints: []uint8{pointFormatUncompressed},
1167 SignatureSchemes: []SignatureScheme{ECDSAWithP256AndSHA256},
1168 SupportedVersions: []uint16{VersionTLS12},
1170 CipherSuites: []uint16{TLS_RSA_WITH_AES_128_GCM_SHA256},
1173 {ecdsaCert, &ClientHelloInfo{
1174 CipherSuites: []uint16{TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256},
1175 SupportedCurves: []CurveID{CurveP384},
1176 SupportedPoints: []uint8{pointFormatUncompressed},
1177 SignatureSchemes: []SignatureScheme{ECDSAWithP256AndSHA256},
1178 SupportedVersions: []uint16{VersionTLS12},
1179 }, "certificate curve"},
1180 {ecdsaCert, &ClientHelloInfo{
1181 CipherSuites: []uint16{TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256},
1182 SupportedCurves: []CurveID{CurveP256},
1183 SupportedPoints: []uint8{1},
1184 SignatureSchemes: []SignatureScheme{ECDSAWithP256AndSHA256},
1185 SupportedVersions: []uint16{VersionTLS12},
1186 }, "doesn't support ECDHE"},
1187 {ecdsaCert, &ClientHelloInfo{
1188 CipherSuites: []uint16{TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256},
1189 SupportedCurves: []CurveID{CurveP256},
1190 SupportedPoints: []uint8{pointFormatUncompressed},
1191 SignatureSchemes: []SignatureScheme{PSSWithSHA256},
1192 SupportedVersions: []uint16{VersionTLS12},
1193 }, "signature algorithms"},
1195 {ed25519Cert, &ClientHelloInfo{
1196 CipherSuites: []uint16{TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256},
1197 SupportedCurves: []CurveID{CurveP256}, // only relevant for ECDHE support
1198 SupportedPoints: []uint8{pointFormatUncompressed},
1199 SignatureSchemes: []SignatureScheme{Ed25519},
1200 SupportedVersions: []uint16{VersionTLS12},
1202 {ed25519Cert, &ClientHelloInfo{
1203 CipherSuites: []uint16{TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256},
1204 SupportedCurves: []CurveID{CurveP256}, // only relevant for ECDHE support
1205 SupportedPoints: []uint8{pointFormatUncompressed},
1206 SignatureSchemes: []SignatureScheme{Ed25519},
1207 SupportedVersions: []uint16{VersionTLS10},
1208 }, "doesn't support Ed25519"},
1209 {ed25519Cert, &ClientHelloInfo{
1210 CipherSuites: []uint16{TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256},
1211 SupportedCurves: []CurveID{},
1212 SupportedPoints: []uint8{pointFormatUncompressed},
1213 SignatureSchemes: []SignatureScheme{Ed25519},
1214 SupportedVersions: []uint16{VersionTLS12},
1215 }, "doesn't support ECDHE"},
1217 {rsaCert, &ClientHelloInfo{
1218 CipherSuites: []uint16{TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA},
1219 SupportedCurves: []CurveID{CurveP256}, // only relevant for ECDHE support
1220 SupportedPoints: []uint8{pointFormatUncompressed},
1221 SupportedVersions: []uint16{VersionTLS10},
1223 {rsaCert, &ClientHelloInfo{
1224 CipherSuites: []uint16{TLS_RSA_WITH_AES_128_GCM_SHA256},
1225 SupportedVersions: []uint16{VersionTLS12},
1226 }, ""}, // static RSA fallback
1228 for i, tt := range tests {
1229 err := tt.chi.SupportsCertificate(tt.c)
1231 case tt.wantErr == "" && err != nil:
1232 t.Errorf("%d: unexpected error: %v", i, err)
1233 case tt.wantErr != "" && err == nil:
1234 t.Errorf("%d: unexpected success", i)
1235 case tt.wantErr != "" && !strings.Contains(err.Error(), tt.wantErr):
1236 t.Errorf("%d: got error %q, expected %q", i, err, tt.wantErr)
1241 func TestCipherSuites(t *testing.T) {
1243 for _, c := range CipherSuites() {
1245 t.Errorf("CipherSuites are not ordered by ID: got %#04x after %#04x", c.ID, lastID)
1251 t.Errorf("%#04x: Insecure CipherSuite returned by CipherSuites()", c.ID)
1255 for _, c := range InsecureCipherSuites() {
1257 t.Errorf("InsecureCipherSuites are not ordered by ID: got %#04x after %#04x", c.ID, lastID)
1263 t.Errorf("%#04x: not Insecure CipherSuite returned by InsecureCipherSuites()", c.ID)
1267 cipherSuiteByID := func(id uint16) *CipherSuite {
1268 for _, c := range CipherSuites() {
1273 for _, c := range InsecureCipherSuites() {
1281 for _, c := range cipherSuites {
1282 cc := cipherSuiteByID(c.id)
1284 t.Errorf("%#04x: no CipherSuite entry", c.id)
1288 if defaultOff := c.flags&suiteDefaultOff != 0; defaultOff != cc.Insecure {
1289 t.Errorf("%#04x: Insecure %v, expected %v", c.id, cc.Insecure, defaultOff)
1291 if tls12Only := c.flags&suiteTLS12 != 0; tls12Only && len(cc.SupportedVersions) != 1 {
1292 t.Errorf("%#04x: suite is TLS 1.2 only, but SupportedVersions is %v", c.id, cc.SupportedVersions)
1293 } else if !tls12Only && len(cc.SupportedVersions) != 3 {
1294 t.Errorf("%#04x: suite TLS 1.0-1.2, but SupportedVersions is %v", c.id, cc.SupportedVersions)
1297 if got := CipherSuiteName(c.id); got != cc.Name {
1298 t.Errorf("%#04x: unexpected CipherSuiteName: got %q, expected %q", c.id, got, cc.Name)
1301 for _, c := range cipherSuitesTLS13 {
1302 cc := cipherSuiteByID(c.id)
1304 t.Errorf("%#04x: no CipherSuite entry", c.id)
1309 t.Errorf("%#04x: Insecure %v, expected false", c.id, cc.Insecure)
1311 if len(cc.SupportedVersions) != 1 || cc.SupportedVersions[0] != VersionTLS13 {
1312 t.Errorf("%#04x: suite is TLS 1.3 only, but SupportedVersions is %v", c.id, cc.SupportedVersions)
1315 if got := CipherSuiteName(c.id); got != cc.Name {
1316 t.Errorf("%#04x: unexpected CipherSuiteName: got %q, expected %q", c.id, got, cc.Name)
1320 if got := CipherSuiteName(0xabc); got != "0x0ABC" {
1321 t.Errorf("unexpected fallback CipherSuiteName: got %q, expected 0x0ABC", got)
1325 type brokenSigner struct{ crypto.Signer }
1327 func (s brokenSigner) Sign(rand io.Reader, digest []byte, opts crypto.SignerOpts) (signature []byte, err error) {
1328 // Replace opts with opts.HashFunc(), so rsa.PSSOptions are discarded.
1329 return s.Signer.Sign(rand, digest, opts.HashFunc())
1332 // TestPKCS1OnlyCert uses a client certificate with a broken crypto.Signer that
1333 // always makes PKCS#1 v1.5 signatures, so can't be used with RSA-PSS.
1334 func TestPKCS1OnlyCert(t *testing.T) {
1335 clientConfig := testConfig.Clone()
1336 clientConfig.Certificates = []Certificate{{
1337 Certificate: [][]byte{testRSACertificate},
1338 PrivateKey: brokenSigner{testRSAPrivateKey},
1340 serverConfig := testConfig.Clone()
1341 serverConfig.MaxVersion = VersionTLS12 // TLS 1.3 doesn't support PKCS#1 v1.5
1342 serverConfig.ClientAuth = RequireAnyClientCert
1344 // If RSA-PSS is selected, the handshake should fail.
1345 if _, _, err := testHandshake(t, clientConfig, serverConfig); err == nil {
1346 t.Fatal("expected broken certificate to cause connection to fail")
1349 clientConfig.Certificates[0].SupportedSignatureAlgorithms =
1350 []SignatureScheme{PKCS1WithSHA1, PKCS1WithSHA256}
1352 // But if the certificate restricts supported algorithms, RSA-PSS should not
1353 // be selected, and the handshake should succeed.
1354 if _, _, err := testHandshake(t, clientConfig, serverConfig); err != nil {