]> Cypherpunks.ru repositories - gostls13.git/blob - src/crypto/tls/tls_test.go
crypto/tls: remove RSA KEX ciphers from the default list
[gostls13.git] / src / crypto / tls / tls_test.go
1 // Copyright 2012 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 package tls
6
7 import (
8         "bytes"
9         "context"
10         "crypto"
11         "crypto/x509"
12         "encoding/json"
13         "errors"
14         "fmt"
15         "internal/testenv"
16         "io"
17         "math"
18         "net"
19         "os"
20         "reflect"
21         "sort"
22         "strings"
23         "testing"
24         "time"
25 )
26
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-----
39 `
40
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-----
50 `)
51
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-----
63 `)
64
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-----
78 `
79
80 var ecdsaKeyPEM = testingKey(`-----BEGIN EC PARAMETERS-----
81 BgUrgQQAIw==
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-----
90 `)
91
92 var keyPairTests = []struct {
93         algo string
94         cert string
95         key  string
96 }{
97         {"ECDSA", ecdsaCertPEM, ecdsaKeyPEM},
98         {"RSA", rsaCertPEM, rsaKeyPEM},
99         {"RSA-untyped", rsaCertPEM, keyPEM}, // golang.org/issue/4477
100 }
101
102 func TestX509KeyPair(t *testing.T) {
103         t.Parallel()
104         var pem []byte
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)
109                 }
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)
113                 }
114         }
115 }
116
117 func TestX509KeyPairErrors(t *testing.T) {
118         _, err := X509KeyPair([]byte(rsaKeyPEM), []byte(rsaCertPEM))
119         if err == nil {
120                 t.Fatalf("X509KeyPair didn't return an error when arguments were switched")
121         }
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)
124         }
125
126         _, err = X509KeyPair([]byte(rsaCertPEM), []byte(rsaCertPEM))
127         if err == nil {
128                 t.Fatalf("X509KeyPair didn't return an error when both arguments were certificates")
129         }
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)
132         }
133
134         const nonsensePEM = `
135 -----BEGIN NONSENSE-----
136 Zm9vZm9vZm9v
137 -----END NONSENSE-----
138 `
139
140         _, err = X509KeyPair([]byte(nonsensePEM), []byte(nonsensePEM))
141         if err == nil {
142                 t.Fatalf("X509KeyPair didn't return an error when both arguments were nonsense")
143         }
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)
146         }
147 }
148
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")
152         }
153         if _, err := X509KeyPair([]byte(ecdsaCertPEM), []byte(rsaKeyPEM)); err == nil {
154                 t.Error("Load of ECDSA certificate succeeded with RSA private key")
155         }
156 }
157
158 func newLocalListener(t testing.TB) net.Listener {
159         ln, err := net.Listen("tcp", "127.0.0.1:0")
160         if err != nil {
161                 ln, err = net.Listen("tcp6", "[::1]:0")
162         }
163         if err != nil {
164                 t.Fatal(err)
165         }
166         return ln
167 }
168
169 func TestDialTimeout(t *testing.T) {
170         if testing.Short() {
171                 t.Skip("skipping in short mode")
172         }
173
174         timeout := 100 * time.Microsecond
175         for !t.Failed() {
176                 acceptc := make(chan net.Conn)
177                 listener := newLocalListener(t)
178                 go func() {
179                         for {
180                                 conn, err := listener.Accept()
181                                 if err != nil {
182                                         close(acceptc)
183                                         return
184                                 }
185                                 acceptc <- conn
186                         }
187                 }()
188
189                 addr := listener.Addr().String()
190                 dialer := &net.Dialer{
191                         Timeout: timeout,
192                 }
193                 if conn, err := DialWithDialer(dialer, "tcp", addr, nil); err == nil {
194                         conn.Close()
195                         t.Errorf("DialWithTimeout unexpectedly completed successfully")
196                 } else if !isTimeoutError(err) {
197                         t.Errorf("resulting error not a timeout: %v\nType %T: %#v", err, err, err)
198                 }
199
200                 listener.Close()
201
202                 // We're looking for a timeout during the handshake, so check that the
203                 // Listener actually accepted the connection to initiate it. (If the server
204                 // takes too long to accept the connection, we might cancel before the
205                 // underlying net.Conn is ever dialed — without ever attempting a
206                 // handshake.)
207                 lconn, ok := <-acceptc
208                 if ok {
209                         // The Listener accepted a connection, so assume that it was from our
210                         // Dial: we triggered the timeout at the point where we wanted it!
211                         t.Logf("Listener accepted a connection from %s", lconn.RemoteAddr())
212                         lconn.Close()
213                 }
214                 // Close any spurious extra connecitions from the listener. (This is
215                 // possible if there are, for example, stray Dial calls from other tests.)
216                 for extraConn := range acceptc {
217                         t.Logf("spurious extra connection from %s", extraConn.RemoteAddr())
218                         extraConn.Close()
219                 }
220                 if ok {
221                         break
222                 }
223
224                 t.Logf("with timeout %v, DialWithDialer returned before listener accepted any connections; retrying", timeout)
225                 timeout *= 2
226         }
227 }
228
229 func TestDeadlineOnWrite(t *testing.T) {
230         if testing.Short() {
231                 t.Skip("skipping in short mode")
232         }
233
234         ln := newLocalListener(t)
235         defer ln.Close()
236
237         srvCh := make(chan *Conn, 1)
238
239         go func() {
240                 sconn, err := ln.Accept()
241                 if err != nil {
242                         srvCh <- nil
243                         return
244                 }
245                 srv := Server(sconn, testConfig.Clone())
246                 if err := srv.Handshake(); err != nil {
247                         srvCh <- nil
248                         return
249                 }
250                 srvCh <- srv
251         }()
252
253         clientConfig := testConfig.Clone()
254         clientConfig.MaxVersion = VersionTLS12
255         conn, err := Dial("tcp", ln.Addr().String(), clientConfig)
256         if err != nil {
257                 t.Fatal(err)
258         }
259         defer conn.Close()
260
261         srv := <-srvCh
262         if srv == nil {
263                 t.Error(err)
264         }
265
266         // Make sure the client/server is setup correctly and is able to do a typical Write/Read
267         buf := make([]byte, 6)
268         if _, err := srv.Write([]byte("foobar")); err != nil {
269                 t.Errorf("Write err: %v", err)
270         }
271         if n, err := conn.Read(buf); n != 6 || err != nil || string(buf) != "foobar" {
272                 t.Errorf("Read = %d, %v, data %q; want 6, nil, foobar", n, err, buf)
273         }
274
275         // Set a deadline which should cause Write to timeout
276         if err = srv.SetDeadline(time.Now()); err != nil {
277                 t.Fatalf("SetDeadline(time.Now()) err: %v", err)
278         }
279         if _, err = srv.Write([]byte("should fail")); err == nil {
280                 t.Fatal("Write should have timed out")
281         }
282
283         // Clear deadline and make sure it still times out
284         if err = srv.SetDeadline(time.Time{}); err != nil {
285                 t.Fatalf("SetDeadline(time.Time{}) err: %v", err)
286         }
287         if _, err = srv.Write([]byte("This connection is permanently broken")); err == nil {
288                 t.Fatal("Write which previously failed should still time out")
289         }
290
291         // Verify the error
292         if ne := err.(net.Error); ne.Temporary() != false {
293                 t.Error("Write timed out but incorrectly classified the error as Temporary")
294         }
295         if !isTimeoutError(err) {
296                 t.Error("Write timed out but did not classify the error as a Timeout")
297         }
298 }
299
300 type readerFunc func([]byte) (int, error)
301
302 func (f readerFunc) Read(b []byte) (int, error) { return f(b) }
303
304 // TestDialer tests that tls.Dialer.DialContext can abort in the middle of a handshake.
305 // (The other cases are all handled by the existing dial tests in this package, which
306 // all also flow through the same code shared code paths)
307 func TestDialer(t *testing.T) {
308         ln := newLocalListener(t)
309         defer ln.Close()
310
311         unblockServer := make(chan struct{}) // close-only
312         defer close(unblockServer)
313         go func() {
314                 conn, err := ln.Accept()
315                 if err != nil {
316                         return
317                 }
318                 defer conn.Close()
319                 <-unblockServer
320         }()
321
322         ctx, cancel := context.WithCancel(context.Background())
323         d := Dialer{Config: &Config{
324                 Rand: readerFunc(func(b []byte) (n int, err error) {
325                         // By the time crypto/tls wants randomness, that means it has a TCP
326                         // connection, so we're past the Dialer's dial and now blocked
327                         // in a handshake. Cancel our context and see if we get unstuck.
328                         // (Our TCP listener above never reads or writes, so the Handshake
329                         // would otherwise be stuck forever)
330                         cancel()
331                         return len(b), nil
332                 }),
333                 ServerName: "foo",
334         }}
335         _, err := d.DialContext(ctx, "tcp", ln.Addr().String())
336         if err != context.Canceled {
337                 t.Errorf("err = %v; want context.Canceled", err)
338         }
339 }
340
341 func isTimeoutError(err error) bool {
342         if ne, ok := err.(net.Error); ok {
343                 return ne.Timeout()
344         }
345         return false
346 }
347
348 // tests that Conn.Read returns (non-zero, io.EOF) instead of
349 // (non-zero, nil) when a Close (alertCloseNotify) is sitting right
350 // behind the application data in the buffer.
351 func TestConnReadNonzeroAndEOF(t *testing.T) {
352         // This test is racy: it assumes that after a write to a
353         // localhost TCP connection, the peer TCP connection can
354         // immediately read it. Because it's racy, we skip this test
355         // in short mode, and then retry it several times with an
356         // increasing sleep in between our final write (via srv.Close
357         // below) and the following read.
358         if testing.Short() {
359                 t.Skip("skipping in short mode")
360         }
361         var err error
362         for delay := time.Millisecond; delay <= 64*time.Millisecond; delay *= 2 {
363                 if err = testConnReadNonzeroAndEOF(t, delay); err == nil {
364                         return
365                 }
366         }
367         t.Error(err)
368 }
369
370 func testConnReadNonzeroAndEOF(t *testing.T, delay time.Duration) error {
371         ln := newLocalListener(t)
372         defer ln.Close()
373
374         srvCh := make(chan *Conn, 1)
375         var serr error
376         go func() {
377                 sconn, err := ln.Accept()
378                 if err != nil {
379                         serr = err
380                         srvCh <- nil
381                         return
382                 }
383                 serverConfig := testConfig.Clone()
384                 srv := Server(sconn, serverConfig)
385                 if err := srv.Handshake(); err != nil {
386                         serr = fmt.Errorf("handshake: %v", err)
387                         srvCh <- nil
388                         return
389                 }
390                 srvCh <- srv
391         }()
392
393         clientConfig := testConfig.Clone()
394         // In TLS 1.3, alerts are encrypted and disguised as application data, so
395         // the opportunistic peek won't work.
396         clientConfig.MaxVersion = VersionTLS12
397         conn, err := Dial("tcp", ln.Addr().String(), clientConfig)
398         if err != nil {
399                 t.Fatal(err)
400         }
401         defer conn.Close()
402
403         srv := <-srvCh
404         if srv == nil {
405                 return serr
406         }
407
408         buf := make([]byte, 6)
409
410         srv.Write([]byte("foobar"))
411         n, err := conn.Read(buf)
412         if n != 6 || err != nil || string(buf) != "foobar" {
413                 return fmt.Errorf("Read = %d, %v, data %q; want 6, nil, foobar", n, err, buf)
414         }
415
416         srv.Write([]byte("abcdef"))
417         srv.Close()
418         time.Sleep(delay)
419         n, err = conn.Read(buf)
420         if n != 6 || string(buf) != "abcdef" {
421                 return fmt.Errorf("Read = %d, buf= %q; want 6, abcdef", n, buf)
422         }
423         if err != io.EOF {
424                 return fmt.Errorf("Second Read error = %v; want io.EOF", err)
425         }
426         return nil
427 }
428
429 func TestTLSUniqueMatches(t *testing.T) {
430         ln := newLocalListener(t)
431         defer ln.Close()
432
433         serverTLSUniques := make(chan []byte)
434         parentDone := make(chan struct{})
435         childDone := make(chan struct{})
436         defer close(parentDone)
437         go func() {
438                 defer close(childDone)
439                 for i := 0; i < 2; i++ {
440                         sconn, err := ln.Accept()
441                         if err != nil {
442                                 t.Error(err)
443                                 return
444                         }
445                         serverConfig := testConfig.Clone()
446                         serverConfig.MaxVersion = VersionTLS12 // TLSUnique is not defined in TLS 1.3
447                         srv := Server(sconn, serverConfig)
448                         if err := srv.Handshake(); err != nil {
449                                 t.Error(err)
450                                 return
451                         }
452                         select {
453                         case <-parentDone:
454                                 return
455                         case serverTLSUniques <- srv.ConnectionState().TLSUnique:
456                         }
457                 }
458         }()
459
460         clientConfig := testConfig.Clone()
461         clientConfig.ClientSessionCache = NewLRUClientSessionCache(1)
462         conn, err := Dial("tcp", ln.Addr().String(), clientConfig)
463         if err != nil {
464                 t.Fatal(err)
465         }
466
467         var serverTLSUniquesValue []byte
468         select {
469         case <-childDone:
470                 return
471         case serverTLSUniquesValue = <-serverTLSUniques:
472         }
473
474         if !bytes.Equal(conn.ConnectionState().TLSUnique, serverTLSUniquesValue) {
475                 t.Error("client and server channel bindings differ")
476         }
477         if serverTLSUniquesValue == nil || bytes.Equal(serverTLSUniquesValue, make([]byte, 12)) {
478                 t.Error("tls-unique is empty or zero")
479         }
480         conn.Close()
481
482         conn, err = Dial("tcp", ln.Addr().String(), clientConfig)
483         if err != nil {
484                 t.Fatal(err)
485         }
486         defer conn.Close()
487         if !conn.ConnectionState().DidResume {
488                 t.Error("second session did not use resumption")
489         }
490
491         select {
492         case <-childDone:
493                 return
494         case serverTLSUniquesValue = <-serverTLSUniques:
495         }
496
497         if !bytes.Equal(conn.ConnectionState().TLSUnique, serverTLSUniquesValue) {
498                 t.Error("client and server channel bindings differ when session resumption is used")
499         }
500         if serverTLSUniquesValue == nil || bytes.Equal(serverTLSUniquesValue, make([]byte, 12)) {
501                 t.Error("resumption tls-unique is empty or zero")
502         }
503 }
504
505 func TestVerifyHostname(t *testing.T) {
506         testenv.MustHaveExternalNetwork(t)
507
508         c, err := Dial("tcp", "www.google.com:https", nil)
509         if err != nil {
510                 t.Fatal(err)
511         }
512         if err := c.VerifyHostname("www.google.com"); err != nil {
513                 t.Fatalf("verify www.google.com: %v", err)
514         }
515         if err := c.VerifyHostname("www.yahoo.com"); err == nil {
516                 t.Fatalf("verify www.yahoo.com succeeded")
517         }
518
519         c, err = Dial("tcp", "www.google.com:https", &Config{InsecureSkipVerify: true})
520         if err != nil {
521                 t.Fatal(err)
522         }
523         if err := c.VerifyHostname("www.google.com"); err == nil {
524                 t.Fatalf("verify www.google.com succeeded with InsecureSkipVerify=true")
525         }
526 }
527
528 func TestConnCloseBreakingWrite(t *testing.T) {
529         ln := newLocalListener(t)
530         defer ln.Close()
531
532         srvCh := make(chan *Conn, 1)
533         var serr error
534         var sconn net.Conn
535         go func() {
536                 var err error
537                 sconn, err = ln.Accept()
538                 if err != nil {
539                         serr = err
540                         srvCh <- nil
541                         return
542                 }
543                 serverConfig := testConfig.Clone()
544                 srv := Server(sconn, serverConfig)
545                 if err := srv.Handshake(); err != nil {
546                         serr = fmt.Errorf("handshake: %v", err)
547                         srvCh <- nil
548                         return
549                 }
550                 srvCh <- srv
551         }()
552
553         cconn, err := net.Dial("tcp", ln.Addr().String())
554         if err != nil {
555                 t.Fatal(err)
556         }
557         defer cconn.Close()
558
559         conn := &changeImplConn{
560                 Conn: cconn,
561         }
562
563         clientConfig := testConfig.Clone()
564         tconn := Client(conn, clientConfig)
565         if err := tconn.Handshake(); err != nil {
566                 t.Fatal(err)
567         }
568
569         srv := <-srvCh
570         if srv == nil {
571                 t.Fatal(serr)
572         }
573         defer sconn.Close()
574
575         connClosed := make(chan struct{})
576         conn.closeFunc = func() error {
577                 close(connClosed)
578                 return nil
579         }
580
581         inWrite := make(chan bool, 1)
582         var errConnClosed = errors.New("conn closed for test")
583         conn.writeFunc = func(p []byte) (n int, err error) {
584                 inWrite <- true
585                 <-connClosed
586                 return 0, errConnClosed
587         }
588
589         closeReturned := make(chan bool, 1)
590         go func() {
591                 <-inWrite
592                 tconn.Close() // test that this doesn't block forever.
593                 closeReturned <- true
594         }()
595
596         _, err = tconn.Write([]byte("foo"))
597         if err != errConnClosed {
598                 t.Errorf("Write error = %v; want errConnClosed", err)
599         }
600
601         <-closeReturned
602         if err := tconn.Close(); err != net.ErrClosed {
603                 t.Errorf("Close error = %v; want net.ErrClosed", err)
604         }
605 }
606
607 func TestConnCloseWrite(t *testing.T) {
608         ln := newLocalListener(t)
609         defer ln.Close()
610
611         clientDoneChan := make(chan struct{})
612
613         serverCloseWrite := func() error {
614                 sconn, err := ln.Accept()
615                 if err != nil {
616                         return fmt.Errorf("accept: %v", err)
617                 }
618                 defer sconn.Close()
619
620                 serverConfig := testConfig.Clone()
621                 srv := Server(sconn, serverConfig)
622                 if err := srv.Handshake(); err != nil {
623                         return fmt.Errorf("handshake: %v", err)
624                 }
625                 defer srv.Close()
626
627                 data, err := io.ReadAll(srv)
628                 if err != nil {
629                         return err
630                 }
631                 if len(data) > 0 {
632                         return fmt.Errorf("Read data = %q; want nothing", data)
633                 }
634
635                 if err := srv.CloseWrite(); err != nil {
636                         return fmt.Errorf("server CloseWrite: %v", err)
637                 }
638
639                 // Wait for clientCloseWrite to finish, so we know we
640                 // tested the CloseWrite before we defer the
641                 // sconn.Close above, which would also cause the
642                 // client to unblock like CloseWrite.
643                 <-clientDoneChan
644                 return nil
645         }
646
647         clientCloseWrite := func() error {
648                 defer close(clientDoneChan)
649
650                 clientConfig := testConfig.Clone()
651                 conn, err := Dial("tcp", ln.Addr().String(), clientConfig)
652                 if err != nil {
653                         return err
654                 }
655                 if err := conn.Handshake(); err != nil {
656                         return err
657                 }
658                 defer conn.Close()
659
660                 if err := conn.CloseWrite(); err != nil {
661                         return fmt.Errorf("client CloseWrite: %v", err)
662                 }
663
664                 if _, err := conn.Write([]byte{0}); err != errShutdown {
665                         return fmt.Errorf("CloseWrite error = %v; want errShutdown", err)
666                 }
667
668                 data, err := io.ReadAll(conn)
669                 if err != nil {
670                         return err
671                 }
672                 if len(data) > 0 {
673                         return fmt.Errorf("Read data = %q; want nothing", data)
674                 }
675                 return nil
676         }
677
678         errChan := make(chan error, 2)
679
680         go func() { errChan <- serverCloseWrite() }()
681         go func() { errChan <- clientCloseWrite() }()
682
683         for i := 0; i < 2; i++ {
684                 select {
685                 case err := <-errChan:
686                         if err != nil {
687                                 t.Fatal(err)
688                         }
689                 case <-time.After(10 * time.Second):
690                         t.Fatal("deadlock")
691                 }
692         }
693
694         // Also test CloseWrite being called before the handshake is
695         // finished:
696         {
697                 ln2 := newLocalListener(t)
698                 defer ln2.Close()
699
700                 netConn, err := net.Dial("tcp", ln2.Addr().String())
701                 if err != nil {
702                         t.Fatal(err)
703                 }
704                 defer netConn.Close()
705                 conn := Client(netConn, testConfig.Clone())
706
707                 if err := conn.CloseWrite(); err != errEarlyCloseWrite {
708                         t.Errorf("CloseWrite error = %v; want errEarlyCloseWrite", err)
709                 }
710         }
711 }
712
713 func TestWarningAlertFlood(t *testing.T) {
714         ln := newLocalListener(t)
715         defer ln.Close()
716
717         server := func() error {
718                 sconn, err := ln.Accept()
719                 if err != nil {
720                         return fmt.Errorf("accept: %v", err)
721                 }
722                 defer sconn.Close()
723
724                 serverConfig := testConfig.Clone()
725                 srv := Server(sconn, serverConfig)
726                 if err := srv.Handshake(); err != nil {
727                         return fmt.Errorf("handshake: %v", err)
728                 }
729                 defer srv.Close()
730
731                 _, err = io.ReadAll(srv)
732                 if err == nil {
733                         return errors.New("unexpected lack of error from server")
734                 }
735                 const expected = "too many ignored"
736                 if str := err.Error(); !strings.Contains(str, expected) {
737                         return fmt.Errorf("expected error containing %q, but saw: %s", expected, str)
738                 }
739
740                 return nil
741         }
742
743         errChan := make(chan error, 1)
744         go func() { errChan <- server() }()
745
746         clientConfig := testConfig.Clone()
747         clientConfig.MaxVersion = VersionTLS12 // there are no warning alerts in TLS 1.3
748         conn, err := Dial("tcp", ln.Addr().String(), clientConfig)
749         if err != nil {
750                 t.Fatal(err)
751         }
752         defer conn.Close()
753         if err := conn.Handshake(); err != nil {
754                 t.Fatal(err)
755         }
756
757         for i := 0; i < maxUselessRecords+1; i++ {
758                 conn.sendAlert(alertNoRenegotiation)
759         }
760
761         if err := <-errChan; err != nil {
762                 t.Fatal(err)
763         }
764 }
765
766 func TestCloneFuncFields(t *testing.T) {
767         const expectedCount = 8
768         called := 0
769
770         c1 := Config{
771                 Time: func() time.Time {
772                         called |= 1 << 0
773                         return time.Time{}
774                 },
775                 GetCertificate: func(*ClientHelloInfo) (*Certificate, error) {
776                         called |= 1 << 1
777                         return nil, nil
778                 },
779                 GetClientCertificate: func(*CertificateRequestInfo) (*Certificate, error) {
780                         called |= 1 << 2
781                         return nil, nil
782                 },
783                 GetConfigForClient: func(*ClientHelloInfo) (*Config, error) {
784                         called |= 1 << 3
785                         return nil, nil
786                 },
787                 VerifyPeerCertificate: func(rawCerts [][]byte, verifiedChains [][]*x509.Certificate) error {
788                         called |= 1 << 4
789                         return nil
790                 },
791                 VerifyConnection: func(ConnectionState) error {
792                         called |= 1 << 5
793                         return nil
794                 },
795                 UnwrapSession: func(identity []byte, cs ConnectionState) (*SessionState, error) {
796                         called |= 1 << 6
797                         return nil, nil
798                 },
799                 WrapSession: func(cs ConnectionState, ss *SessionState) ([]byte, error) {
800                         called |= 1 << 7
801                         return nil, nil
802                 },
803         }
804
805         c2 := c1.Clone()
806
807         c2.Time()
808         c2.GetCertificate(nil)
809         c2.GetClientCertificate(nil)
810         c2.GetConfigForClient(nil)
811         c2.VerifyPeerCertificate(nil, nil)
812         c2.VerifyConnection(ConnectionState{})
813         c2.UnwrapSession(nil, ConnectionState{})
814         c2.WrapSession(ConnectionState{}, nil)
815
816         if called != (1<<expectedCount)-1 {
817                 t.Fatalf("expected %d calls but saw calls %b", expectedCount, called)
818         }
819 }
820
821 func TestCloneNonFuncFields(t *testing.T) {
822         var c1 Config
823         v := reflect.ValueOf(&c1).Elem()
824
825         typ := v.Type()
826         for i := 0; i < typ.NumField(); i++ {
827                 f := v.Field(i)
828                 // testing/quick can't handle functions or interfaces and so
829                 // isn't used here.
830                 switch fn := typ.Field(i).Name; fn {
831                 case "Rand":
832                         f.Set(reflect.ValueOf(io.Reader(os.Stdin)))
833                 case "Time", "GetCertificate", "GetConfigForClient", "VerifyPeerCertificate", "VerifyConnection", "GetClientCertificate", "WrapSession", "UnwrapSession":
834                         // DeepEqual can't compare functions. If you add a
835                         // function field to this list, you must also change
836                         // TestCloneFuncFields to ensure that the func field is
837                         // cloned.
838                 case "Certificates":
839                         f.Set(reflect.ValueOf([]Certificate{
840                                 {Certificate: [][]byte{{'b'}}},
841                         }))
842                 case "NameToCertificate":
843                         f.Set(reflect.ValueOf(map[string]*Certificate{"a": nil}))
844                 case "RootCAs", "ClientCAs":
845                         f.Set(reflect.ValueOf(x509.NewCertPool()))
846                 case "ClientSessionCache":
847                         f.Set(reflect.ValueOf(NewLRUClientSessionCache(10)))
848                 case "KeyLogWriter":
849                         f.Set(reflect.ValueOf(io.Writer(os.Stdout)))
850                 case "NextProtos":
851                         f.Set(reflect.ValueOf([]string{"a", "b"}))
852                 case "ServerName":
853                         f.Set(reflect.ValueOf("b"))
854                 case "ClientAuth":
855                         f.Set(reflect.ValueOf(VerifyClientCertIfGiven))
856                 case "InsecureSkipVerify", "SessionTicketsDisabled", "DynamicRecordSizingDisabled", "PreferServerCipherSuites":
857                         f.Set(reflect.ValueOf(true))
858                 case "MinVersion", "MaxVersion":
859                         f.Set(reflect.ValueOf(uint16(VersionTLS12)))
860                 case "SessionTicketKey":
861                         f.Set(reflect.ValueOf([32]byte{}))
862                 case "CipherSuites":
863                         f.Set(reflect.ValueOf([]uint16{1, 2}))
864                 case "CurvePreferences":
865                         f.Set(reflect.ValueOf([]CurveID{CurveP256}))
866                 case "Renegotiation":
867                         f.Set(reflect.ValueOf(RenegotiateOnceAsClient))
868                 case "mutex", "autoSessionTicketKeys", "sessionTicketKeys":
869                         continue // these are unexported fields that are handled separately
870                 default:
871                         t.Errorf("all fields must be accounted for, but saw unknown field %q", fn)
872                 }
873         }
874         // Set the unexported fields related to session ticket keys, which are copied with Clone().
875         c1.autoSessionTicketKeys = []ticketKey{c1.ticketKeyFromBytes(c1.SessionTicketKey)}
876         c1.sessionTicketKeys = []ticketKey{c1.ticketKeyFromBytes(c1.SessionTicketKey)}
877
878         c2 := c1.Clone()
879         if !reflect.DeepEqual(&c1, c2) {
880                 t.Errorf("clone failed to copy a field")
881         }
882 }
883
884 func TestCloneNilConfig(t *testing.T) {
885         var config *Config
886         if cc := config.Clone(); cc != nil {
887                 t.Fatalf("Clone with nil should return nil, got: %+v", cc)
888         }
889 }
890
891 // changeImplConn is a net.Conn which can change its Write and Close
892 // methods.
893 type changeImplConn struct {
894         net.Conn
895         writeFunc func([]byte) (int, error)
896         closeFunc func() error
897 }
898
899 func (w *changeImplConn) Write(p []byte) (n int, err error) {
900         if w.writeFunc != nil {
901                 return w.writeFunc(p)
902         }
903         return w.Conn.Write(p)
904 }
905
906 func (w *changeImplConn) Close() error {
907         if w.closeFunc != nil {
908                 return w.closeFunc()
909         }
910         return w.Conn.Close()
911 }
912
913 func throughput(b *testing.B, version uint16, totalBytes int64, dynamicRecordSizingDisabled bool) {
914         ln := newLocalListener(b)
915         defer ln.Close()
916
917         N := b.N
918
919         // Less than 64KB because Windows appears to use a TCP rwin < 64KB.
920         // See Issue #15899.
921         const bufsize = 32 << 10
922
923         go func() {
924                 buf := make([]byte, bufsize)
925                 for i := 0; i < N; i++ {
926                         sconn, err := ln.Accept()
927                         if err != nil {
928                                 // panic rather than synchronize to avoid benchmark overhead
929                                 // (cannot call b.Fatal in goroutine)
930                                 panic(fmt.Errorf("accept: %v", err))
931                         }
932                         serverConfig := testConfig.Clone()
933                         serverConfig.CipherSuites = nil // the defaults may prefer faster ciphers
934                         serverConfig.DynamicRecordSizingDisabled = dynamicRecordSizingDisabled
935                         srv := Server(sconn, serverConfig)
936                         if err := srv.Handshake(); err != nil {
937                                 panic(fmt.Errorf("handshake: %v", err))
938                         }
939                         if _, err := io.CopyBuffer(srv, srv, buf); err != nil {
940                                 panic(fmt.Errorf("copy buffer: %v", err))
941                         }
942                 }
943         }()
944
945         b.SetBytes(totalBytes)
946         clientConfig := testConfig.Clone()
947         clientConfig.CipherSuites = nil // the defaults may prefer faster ciphers
948         clientConfig.DynamicRecordSizingDisabled = dynamicRecordSizingDisabled
949         clientConfig.MaxVersion = version
950
951         buf := make([]byte, bufsize)
952         chunks := int(math.Ceil(float64(totalBytes) / float64(len(buf))))
953         for i := 0; i < N; i++ {
954                 conn, err := Dial("tcp", ln.Addr().String(), clientConfig)
955                 if err != nil {
956                         b.Fatal(err)
957                 }
958                 for j := 0; j < chunks; j++ {
959                         _, err := conn.Write(buf)
960                         if err != nil {
961                                 b.Fatal(err)
962                         }
963                         _, err = io.ReadFull(conn, buf)
964                         if err != nil {
965                                 b.Fatal(err)
966                         }
967                 }
968                 conn.Close()
969         }
970 }
971
972 func BenchmarkThroughput(b *testing.B) {
973         for _, mode := range []string{"Max", "Dynamic"} {
974                 for size := 1; size <= 64; size <<= 1 {
975                         name := fmt.Sprintf("%sPacket/%dMB", mode, size)
976                         b.Run(name, func(b *testing.B) {
977                                 b.Run("TLSv12", func(b *testing.B) {
978                                         throughput(b, VersionTLS12, int64(size<<20), mode == "Max")
979                                 })
980                                 b.Run("TLSv13", func(b *testing.B) {
981                                         throughput(b, VersionTLS13, int64(size<<20), mode == "Max")
982                                 })
983                         })
984                 }
985         }
986 }
987
988 type slowConn struct {
989         net.Conn
990         bps int
991 }
992
993 func (c *slowConn) Write(p []byte) (int, error) {
994         if c.bps == 0 {
995                 panic("too slow")
996         }
997         t0 := time.Now()
998         wrote := 0
999         for wrote < len(p) {
1000                 time.Sleep(100 * time.Microsecond)
1001                 allowed := int(time.Since(t0).Seconds()*float64(c.bps)) / 8
1002                 if allowed > len(p) {
1003                         allowed = len(p)
1004                 }
1005                 if wrote < allowed {
1006                         n, err := c.Conn.Write(p[wrote:allowed])
1007                         wrote += n
1008                         if err != nil {
1009                                 return wrote, err
1010                         }
1011                 }
1012         }
1013         return len(p), nil
1014 }
1015
1016 func latency(b *testing.B, version uint16, bps int, dynamicRecordSizingDisabled bool) {
1017         ln := newLocalListener(b)
1018         defer ln.Close()
1019
1020         N := b.N
1021
1022         go func() {
1023                 for i := 0; i < N; i++ {
1024                         sconn, err := ln.Accept()
1025                         if err != nil {
1026                                 // panic rather than synchronize to avoid benchmark overhead
1027                                 // (cannot call b.Fatal in goroutine)
1028                                 panic(fmt.Errorf("accept: %v", err))
1029                         }
1030                         serverConfig := testConfig.Clone()
1031                         serverConfig.DynamicRecordSizingDisabled = dynamicRecordSizingDisabled
1032                         srv := Server(&slowConn{sconn, bps}, serverConfig)
1033                         if err := srv.Handshake(); err != nil {
1034                                 panic(fmt.Errorf("handshake: %v", err))
1035                         }
1036                         io.Copy(srv, srv)
1037                 }
1038         }()
1039
1040         clientConfig := testConfig.Clone()
1041         clientConfig.DynamicRecordSizingDisabled = dynamicRecordSizingDisabled
1042         clientConfig.MaxVersion = version
1043
1044         buf := make([]byte, 16384)
1045         peek := make([]byte, 1)
1046
1047         for i := 0; i < N; i++ {
1048                 conn, err := Dial("tcp", ln.Addr().String(), clientConfig)
1049                 if err != nil {
1050                         b.Fatal(err)
1051                 }
1052                 // make sure we're connected and previous connection has stopped
1053                 if _, err := conn.Write(buf[:1]); err != nil {
1054                         b.Fatal(err)
1055                 }
1056                 if _, err := io.ReadFull(conn, peek); err != nil {
1057                         b.Fatal(err)
1058                 }
1059                 if _, err := conn.Write(buf); err != nil {
1060                         b.Fatal(err)
1061                 }
1062                 if _, err = io.ReadFull(conn, peek); err != nil {
1063                         b.Fatal(err)
1064                 }
1065                 conn.Close()
1066         }
1067 }
1068
1069 func BenchmarkLatency(b *testing.B) {
1070         for _, mode := range []string{"Max", "Dynamic"} {
1071                 for _, kbps := range []int{200, 500, 1000, 2000, 5000} {
1072                         name := fmt.Sprintf("%sPacket/%dkbps", mode, kbps)
1073                         b.Run(name, func(b *testing.B) {
1074                                 b.Run("TLSv12", func(b *testing.B) {
1075                                         latency(b, VersionTLS12, kbps*1000, mode == "Max")
1076                                 })
1077                                 b.Run("TLSv13", func(b *testing.B) {
1078                                         latency(b, VersionTLS13, kbps*1000, mode == "Max")
1079                                 })
1080                         })
1081                 }
1082         }
1083 }
1084
1085 func TestConnectionStateMarshal(t *testing.T) {
1086         cs := &ConnectionState{}
1087         _, err := json.Marshal(cs)
1088         if err != nil {
1089                 t.Errorf("json.Marshal failed on ConnectionState: %v", err)
1090         }
1091 }
1092
1093 func TestConnectionState(t *testing.T) {
1094         issuer, err := x509.ParseCertificate(testRSACertificateIssuer)
1095         if err != nil {
1096                 panic(err)
1097         }
1098         rootCAs := x509.NewCertPool()
1099         rootCAs.AddCert(issuer)
1100
1101         now := func() time.Time { return time.Unix(1476984729, 0) }
1102
1103         const alpnProtocol = "golang"
1104         const serverName = "example.golang"
1105         var scts = [][]byte{[]byte("dummy sct 1"), []byte("dummy sct 2")}
1106         var ocsp = []byte("dummy ocsp")
1107
1108         for _, v := range []uint16{VersionTLS12, VersionTLS13} {
1109                 var name string
1110                 switch v {
1111                 case VersionTLS12:
1112                         name = "TLSv12"
1113                 case VersionTLS13:
1114                         name = "TLSv13"
1115                 }
1116                 t.Run(name, func(t *testing.T) {
1117                         config := &Config{
1118                                 Time:         now,
1119                                 Rand:         zeroSource{},
1120                                 Certificates: make([]Certificate, 1),
1121                                 MaxVersion:   v,
1122                                 RootCAs:      rootCAs,
1123                                 ClientCAs:    rootCAs,
1124                                 ClientAuth:   RequireAndVerifyClientCert,
1125                                 NextProtos:   []string{alpnProtocol},
1126                                 ServerName:   serverName,
1127                         }
1128                         config.Certificates[0].Certificate = [][]byte{testRSACertificate}
1129                         config.Certificates[0].PrivateKey = testRSAPrivateKey
1130                         config.Certificates[0].SignedCertificateTimestamps = scts
1131                         config.Certificates[0].OCSPStaple = ocsp
1132
1133                         ss, cs, err := testHandshake(t, config, config)
1134                         if err != nil {
1135                                 t.Fatalf("Handshake failed: %v", err)
1136                         }
1137
1138                         if ss.Version != v || cs.Version != v {
1139                                 t.Errorf("Got versions %x (server) and %x (client), expected %x", ss.Version, cs.Version, v)
1140                         }
1141
1142                         if !ss.HandshakeComplete || !cs.HandshakeComplete {
1143                                 t.Errorf("Got HandshakeComplete %v (server) and %v (client), expected true", ss.HandshakeComplete, cs.HandshakeComplete)
1144                         }
1145
1146                         if ss.DidResume || cs.DidResume {
1147                                 t.Errorf("Got DidResume %v (server) and %v (client), expected false", ss.DidResume, cs.DidResume)
1148                         }
1149
1150                         if ss.CipherSuite == 0 || cs.CipherSuite == 0 {
1151                                 t.Errorf("Got invalid cipher suite: %v (server) and %v (client)", ss.CipherSuite, cs.CipherSuite)
1152                         }
1153
1154                         if ss.NegotiatedProtocol != alpnProtocol || cs.NegotiatedProtocol != alpnProtocol {
1155                                 t.Errorf("Got negotiated protocol %q (server) and %q (client), expected %q", ss.NegotiatedProtocol, cs.NegotiatedProtocol, alpnProtocol)
1156                         }
1157
1158                         if !cs.NegotiatedProtocolIsMutual {
1159                                 t.Errorf("Got false NegotiatedProtocolIsMutual on the client side")
1160                         }
1161                         // NegotiatedProtocolIsMutual on the server side is unspecified.
1162
1163                         if ss.ServerName != serverName {
1164                                 t.Errorf("Got server name %q, expected %q", ss.ServerName, serverName)
1165                         }
1166                         if cs.ServerName != serverName {
1167                                 t.Errorf("Got server name on client connection %q, expected %q", cs.ServerName, serverName)
1168                         }
1169
1170                         if len(ss.PeerCertificates) != 1 || len(cs.PeerCertificates) != 1 {
1171                                 t.Errorf("Got %d (server) and %d (client) peer certificates, expected %d", len(ss.PeerCertificates), len(cs.PeerCertificates), 1)
1172                         }
1173
1174                         if len(ss.VerifiedChains) != 1 || len(cs.VerifiedChains) != 1 {
1175                                 t.Errorf("Got %d (server) and %d (client) verified chains, expected %d", len(ss.VerifiedChains), len(cs.VerifiedChains), 1)
1176                         } else if len(ss.VerifiedChains[0]) != 2 || len(cs.VerifiedChains[0]) != 2 {
1177                                 t.Errorf("Got %d (server) and %d (client) long verified chain, expected %d", len(ss.VerifiedChains[0]), len(cs.VerifiedChains[0]), 2)
1178                         }
1179
1180                         if len(cs.SignedCertificateTimestamps) != 2 {
1181                                 t.Errorf("Got %d SCTs, expected %d", len(cs.SignedCertificateTimestamps), 2)
1182                         }
1183                         if !bytes.Equal(cs.OCSPResponse, ocsp) {
1184                                 t.Errorf("Got OCSPs %x, expected %x", cs.OCSPResponse, ocsp)
1185                         }
1186                         // Only TLS 1.3 supports OCSP and SCTs on client certs.
1187                         if v == VersionTLS13 {
1188                                 if len(ss.SignedCertificateTimestamps) != 2 {
1189                                         t.Errorf("Got %d client SCTs, expected %d", len(ss.SignedCertificateTimestamps), 2)
1190                                 }
1191                                 if !bytes.Equal(ss.OCSPResponse, ocsp) {
1192                                         t.Errorf("Got client OCSPs %x, expected %x", ss.OCSPResponse, ocsp)
1193                                 }
1194                         }
1195
1196                         if v == VersionTLS13 {
1197                                 if ss.TLSUnique != nil || cs.TLSUnique != nil {
1198                                         t.Errorf("Got TLSUnique %x (server) and %x (client), expected nil in TLS 1.3", ss.TLSUnique, cs.TLSUnique)
1199                                 }
1200                         } else {
1201                                 if ss.TLSUnique == nil || cs.TLSUnique == nil {
1202                                         t.Errorf("Got TLSUnique %x (server) and %x (client), expected non-nil", ss.TLSUnique, cs.TLSUnique)
1203                                 }
1204                         }
1205                 })
1206         }
1207 }
1208
1209 // Issue 28744: Ensure that we don't modify memory
1210 // that Config doesn't own such as Certificates.
1211 func TestBuildNameToCertificate_doesntModifyCertificates(t *testing.T) {
1212         c0 := Certificate{
1213                 Certificate: [][]byte{testRSACertificate},
1214                 PrivateKey:  testRSAPrivateKey,
1215         }
1216         c1 := Certificate{
1217                 Certificate: [][]byte{testSNICertificate},
1218                 PrivateKey:  testRSAPrivateKey,
1219         }
1220         config := testConfig.Clone()
1221         config.Certificates = []Certificate{c0, c1}
1222
1223         config.BuildNameToCertificate()
1224         got := config.Certificates
1225         want := []Certificate{c0, c1}
1226         if !reflect.DeepEqual(got, want) {
1227                 t.Fatalf("Certificates were mutated by BuildNameToCertificate\nGot: %#v\nWant: %#v\n", got, want)
1228         }
1229 }
1230
1231 func testingKey(s string) string { return strings.ReplaceAll(s, "TESTING KEY", "PRIVATE KEY") }
1232
1233 func TestClientHelloInfo_SupportsCertificate(t *testing.T) {
1234         rsaCert := &Certificate{
1235                 Certificate: [][]byte{testRSACertificate},
1236                 PrivateKey:  testRSAPrivateKey,
1237         }
1238         pkcs1Cert := &Certificate{
1239                 Certificate:                  [][]byte{testRSACertificate},
1240                 PrivateKey:                   testRSAPrivateKey,
1241                 SupportedSignatureAlgorithms: []SignatureScheme{PKCS1WithSHA1, PKCS1WithSHA256},
1242         }
1243         ecdsaCert := &Certificate{
1244                 // ECDSA P-256 certificate
1245                 Certificate: [][]byte{testP256Certificate},
1246                 PrivateKey:  testP256PrivateKey,
1247         }
1248         ed25519Cert := &Certificate{
1249                 Certificate: [][]byte{testEd25519Certificate},
1250                 PrivateKey:  testEd25519PrivateKey,
1251         }
1252
1253         tests := []struct {
1254                 c       *Certificate
1255                 chi     *ClientHelloInfo
1256                 wantErr string
1257         }{
1258                 {rsaCert, &ClientHelloInfo{
1259                         ServerName:        "example.golang",
1260                         SignatureSchemes:  []SignatureScheme{PSSWithSHA256},
1261                         SupportedVersions: []uint16{VersionTLS13},
1262                 }, ""},
1263                 {ecdsaCert, &ClientHelloInfo{
1264                         SignatureSchemes:  []SignatureScheme{PSSWithSHA256, ECDSAWithP256AndSHA256},
1265                         SupportedVersions: []uint16{VersionTLS13, VersionTLS12},
1266                 }, ""},
1267                 {rsaCert, &ClientHelloInfo{
1268                         ServerName:        "example.com",
1269                         SignatureSchemes:  []SignatureScheme{PSSWithSHA256},
1270                         SupportedVersions: []uint16{VersionTLS13},
1271                 }, "not valid for requested server name"},
1272                 {ecdsaCert, &ClientHelloInfo{
1273                         SignatureSchemes:  []SignatureScheme{ECDSAWithP384AndSHA384},
1274                         SupportedVersions: []uint16{VersionTLS13},
1275                 }, "signature algorithms"},
1276                 {pkcs1Cert, &ClientHelloInfo{
1277                         SignatureSchemes:  []SignatureScheme{PSSWithSHA256, ECDSAWithP256AndSHA256},
1278                         SupportedVersions: []uint16{VersionTLS13},
1279                 }, "signature algorithms"},
1280
1281                 {rsaCert, &ClientHelloInfo{
1282                         CipherSuites:      []uint16{TLS_RSA_WITH_AES_128_GCM_SHA256},
1283                         SignatureSchemes:  []SignatureScheme{PKCS1WithSHA1},
1284                         SupportedVersions: []uint16{VersionTLS13, VersionTLS12},
1285                 }, "signature algorithms"},
1286                 {rsaCert, &ClientHelloInfo{
1287                         CipherSuites:      []uint16{TLS_RSA_WITH_AES_128_GCM_SHA256},
1288                         SignatureSchemes:  []SignatureScheme{PKCS1WithSHA1},
1289                         SupportedVersions: []uint16{VersionTLS13, VersionTLS12},
1290                         config: &Config{
1291                                 CipherSuites: []uint16{TLS_RSA_WITH_AES_128_GCM_SHA256},
1292                                 MaxVersion:   VersionTLS12,
1293                         },
1294                 }, ""}, // Check that mutual version selection works.
1295
1296                 {ecdsaCert, &ClientHelloInfo{
1297                         CipherSuites:      []uint16{TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256},
1298                         SupportedCurves:   []CurveID{CurveP256},
1299                         SupportedPoints:   []uint8{pointFormatUncompressed},
1300                         SignatureSchemes:  []SignatureScheme{ECDSAWithP256AndSHA256},
1301                         SupportedVersions: []uint16{VersionTLS12},
1302                 }, ""},
1303                 {ecdsaCert, &ClientHelloInfo{
1304                         CipherSuites:      []uint16{TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256},
1305                         SupportedCurves:   []CurveID{CurveP256},
1306                         SupportedPoints:   []uint8{pointFormatUncompressed},
1307                         SignatureSchemes:  []SignatureScheme{ECDSAWithP384AndSHA384},
1308                         SupportedVersions: []uint16{VersionTLS12},
1309                 }, ""}, // TLS 1.2 does not restrict curves based on the SignatureScheme.
1310                 {ecdsaCert, &ClientHelloInfo{
1311                         CipherSuites:      []uint16{TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256},
1312                         SupportedCurves:   []CurveID{CurveP256},
1313                         SupportedPoints:   []uint8{pointFormatUncompressed},
1314                         SignatureSchemes:  nil,
1315                         SupportedVersions: []uint16{VersionTLS12},
1316                 }, ""}, // TLS 1.2 comes with default signature schemes.
1317                 {ecdsaCert, &ClientHelloInfo{
1318                         CipherSuites:      []uint16{TLS_RSA_WITH_AES_128_GCM_SHA256},
1319                         SupportedCurves:   []CurveID{CurveP256},
1320                         SupportedPoints:   []uint8{pointFormatUncompressed},
1321                         SignatureSchemes:  []SignatureScheme{ECDSAWithP256AndSHA256},
1322                         SupportedVersions: []uint16{VersionTLS12},
1323                 }, "cipher suite"},
1324                 {ecdsaCert, &ClientHelloInfo{
1325                         CipherSuites:      []uint16{TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256},
1326                         SupportedCurves:   []CurveID{CurveP256},
1327                         SupportedPoints:   []uint8{pointFormatUncompressed},
1328                         SignatureSchemes:  []SignatureScheme{ECDSAWithP256AndSHA256},
1329                         SupportedVersions: []uint16{VersionTLS12},
1330                         config: &Config{
1331                                 CipherSuites: []uint16{TLS_RSA_WITH_AES_128_GCM_SHA256},
1332                         },
1333                 }, "cipher suite"},
1334                 {ecdsaCert, &ClientHelloInfo{
1335                         CipherSuites:      []uint16{TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256},
1336                         SupportedCurves:   []CurveID{CurveP384},
1337                         SupportedPoints:   []uint8{pointFormatUncompressed},
1338                         SignatureSchemes:  []SignatureScheme{ECDSAWithP256AndSHA256},
1339                         SupportedVersions: []uint16{VersionTLS12},
1340                 }, "certificate curve"},
1341                 {ecdsaCert, &ClientHelloInfo{
1342                         CipherSuites:      []uint16{TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256},
1343                         SupportedCurves:   []CurveID{CurveP256},
1344                         SupportedPoints:   []uint8{1},
1345                         SignatureSchemes:  []SignatureScheme{ECDSAWithP256AndSHA256},
1346                         SupportedVersions: []uint16{VersionTLS12},
1347                 }, "doesn't support ECDHE"},
1348                 {ecdsaCert, &ClientHelloInfo{
1349                         CipherSuites:      []uint16{TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256},
1350                         SupportedCurves:   []CurveID{CurveP256},
1351                         SupportedPoints:   []uint8{pointFormatUncompressed},
1352                         SignatureSchemes:  []SignatureScheme{PSSWithSHA256},
1353                         SupportedVersions: []uint16{VersionTLS12},
1354                 }, "signature algorithms"},
1355
1356                 {ed25519Cert, &ClientHelloInfo{
1357                         CipherSuites:      []uint16{TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256},
1358                         SupportedCurves:   []CurveID{CurveP256}, // only relevant for ECDHE support
1359                         SupportedPoints:   []uint8{pointFormatUncompressed},
1360                         SignatureSchemes:  []SignatureScheme{Ed25519},
1361                         SupportedVersions: []uint16{VersionTLS12},
1362                 }, ""},
1363                 {ed25519Cert, &ClientHelloInfo{
1364                         CipherSuites:      []uint16{TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256},
1365                         SupportedCurves:   []CurveID{CurveP256}, // only relevant for ECDHE support
1366                         SupportedPoints:   []uint8{pointFormatUncompressed},
1367                         SignatureSchemes:  []SignatureScheme{Ed25519},
1368                         SupportedVersions: []uint16{VersionTLS10},
1369                         config:            &Config{MinVersion: VersionTLS10},
1370                 }, "doesn't support Ed25519"},
1371                 {ed25519Cert, &ClientHelloInfo{
1372                         CipherSuites:      []uint16{TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256},
1373                         SupportedCurves:   []CurveID{},
1374                         SupportedPoints:   []uint8{pointFormatUncompressed},
1375                         SignatureSchemes:  []SignatureScheme{Ed25519},
1376                         SupportedVersions: []uint16{VersionTLS12},
1377                 }, "doesn't support ECDHE"},
1378
1379                 {rsaCert, &ClientHelloInfo{
1380                         CipherSuites:      []uint16{TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA},
1381                         SupportedCurves:   []CurveID{CurveP256}, // only relevant for ECDHE support
1382                         SupportedPoints:   []uint8{pointFormatUncompressed},
1383                         SupportedVersions: []uint16{VersionTLS10},
1384                         config:            &Config{MinVersion: VersionTLS10},
1385                 }, ""},
1386                 {rsaCert, &ClientHelloInfo{
1387                         CipherSuites:      []uint16{TLS_RSA_WITH_AES_128_GCM_SHA256},
1388                         SupportedVersions: []uint16{VersionTLS12},
1389                         config: &Config{
1390                                 CipherSuites: []uint16{TLS_RSA_WITH_AES_128_GCM_SHA256},
1391                         },
1392                 }, ""}, // static RSA fallback
1393         }
1394         for i, tt := range tests {
1395                 err := tt.chi.SupportsCertificate(tt.c)
1396                 switch {
1397                 case tt.wantErr == "" && err != nil:
1398                         t.Errorf("%d: unexpected error: %v", i, err)
1399                 case tt.wantErr != "" && err == nil:
1400                         t.Errorf("%d: unexpected success", i)
1401                 case tt.wantErr != "" && !strings.Contains(err.Error(), tt.wantErr):
1402                         t.Errorf("%d: got error %q, expected %q", i, err, tt.wantErr)
1403                 }
1404         }
1405 }
1406
1407 func TestCipherSuites(t *testing.T) {
1408         var lastID uint16
1409         for _, c := range CipherSuites() {
1410                 if lastID > c.ID {
1411                         t.Errorf("CipherSuites are not ordered by ID: got %#04x after %#04x", c.ID, lastID)
1412                 } else {
1413                         lastID = c.ID
1414                 }
1415
1416                 if c.Insecure {
1417                         t.Errorf("%#04x: Insecure CipherSuite returned by CipherSuites()", c.ID)
1418                 }
1419         }
1420         lastID = 0
1421         for _, c := range InsecureCipherSuites() {
1422                 if lastID > c.ID {
1423                         t.Errorf("InsecureCipherSuites are not ordered by ID: got %#04x after %#04x", c.ID, lastID)
1424                 } else {
1425                         lastID = c.ID
1426                 }
1427
1428                 if !c.Insecure {
1429                         t.Errorf("%#04x: not Insecure CipherSuite returned by InsecureCipherSuites()", c.ID)
1430                 }
1431         }
1432
1433         CipherSuiteByID := func(id uint16) *CipherSuite {
1434                 for _, c := range CipherSuites() {
1435                         if c.ID == id {
1436                                 return c
1437                         }
1438                 }
1439                 for _, c := range InsecureCipherSuites() {
1440                         if c.ID == id {
1441                                 return c
1442                         }
1443                 }
1444                 return nil
1445         }
1446
1447         for _, c := range cipherSuites {
1448                 cc := CipherSuiteByID(c.id)
1449                 if cc == nil {
1450                         t.Errorf("%#04x: no CipherSuite entry", c.id)
1451                         continue
1452                 }
1453
1454                 if tls12Only := c.flags&suiteTLS12 != 0; tls12Only && len(cc.SupportedVersions) != 1 {
1455                         t.Errorf("%#04x: suite is TLS 1.2 only, but SupportedVersions is %v", c.id, cc.SupportedVersions)
1456                 } else if !tls12Only && len(cc.SupportedVersions) != 3 {
1457                         t.Errorf("%#04x: suite TLS 1.0-1.2, but SupportedVersions is %v", c.id, cc.SupportedVersions)
1458                 }
1459
1460                 if got := CipherSuiteName(c.id); got != cc.Name {
1461                         t.Errorf("%#04x: unexpected CipherSuiteName: got %q, expected %q", c.id, got, cc.Name)
1462                 }
1463         }
1464         for _, c := range cipherSuitesTLS13 {
1465                 cc := CipherSuiteByID(c.id)
1466                 if cc == nil {
1467                         t.Errorf("%#04x: no CipherSuite entry", c.id)
1468                         continue
1469                 }
1470
1471                 if cc.Insecure {
1472                         t.Errorf("%#04x: Insecure %v, expected false", c.id, cc.Insecure)
1473                 }
1474                 if len(cc.SupportedVersions) != 1 || cc.SupportedVersions[0] != VersionTLS13 {
1475                         t.Errorf("%#04x: suite is TLS 1.3 only, but SupportedVersions is %v", c.id, cc.SupportedVersions)
1476                 }
1477
1478                 if got := CipherSuiteName(c.id); got != cc.Name {
1479                         t.Errorf("%#04x: unexpected CipherSuiteName: got %q, expected %q", c.id, got, cc.Name)
1480                 }
1481         }
1482
1483         if got := CipherSuiteName(0xabc); got != "0x0ABC" {
1484                 t.Errorf("unexpected fallback CipherSuiteName: got %q, expected 0x0ABC", got)
1485         }
1486
1487         if len(cipherSuitesPreferenceOrder) != len(cipherSuites) {
1488                 t.Errorf("cipherSuitesPreferenceOrder is not the same size as cipherSuites")
1489         }
1490         if len(cipherSuitesPreferenceOrderNoAES) != len(cipherSuitesPreferenceOrder) {
1491                 t.Errorf("cipherSuitesPreferenceOrderNoAES is not the same size as cipherSuitesPreferenceOrder")
1492         }
1493
1494         // Check that disabled suites are at the end of the preference lists, and
1495         // that they are marked insecure.
1496         for i, id := range disabledCipherSuites {
1497                 offset := len(cipherSuitesPreferenceOrder) - len(disabledCipherSuites)
1498                 if cipherSuitesPreferenceOrder[offset+i] != id {
1499                         t.Errorf("disabledCipherSuites[%d]: not at the end of cipherSuitesPreferenceOrder", i)
1500                 }
1501                 if cipherSuitesPreferenceOrderNoAES[offset+i] != id {
1502                         t.Errorf("disabledCipherSuites[%d]: not at the end of cipherSuitesPreferenceOrderNoAES", i)
1503                 }
1504                 c := CipherSuiteByID(id)
1505                 if c == nil {
1506                         t.Errorf("%#04x: no CipherSuite entry", id)
1507                         continue
1508                 }
1509                 if !c.Insecure {
1510                         t.Errorf("%#04x: disabled by default but not marked insecure", id)
1511                 }
1512         }
1513
1514         for i, prefOrder := range [][]uint16{cipherSuitesPreferenceOrder, cipherSuitesPreferenceOrderNoAES} {
1515                 // Check that insecure and HTTP/2 bad cipher suites are at the end of
1516                 // the preference lists.
1517                 var sawInsecure, sawBad bool
1518                 for _, id := range prefOrder {
1519                         c := CipherSuiteByID(id)
1520                         if c == nil {
1521                                 t.Errorf("%#04x: no CipherSuite entry", id)
1522                                 continue
1523                         }
1524
1525                         if c.Insecure {
1526                                 sawInsecure = true
1527                         } else if sawInsecure {
1528                                 t.Errorf("%#04x: secure suite after insecure one(s)", id)
1529                         }
1530
1531                         if http2isBadCipher(id) {
1532                                 sawBad = true
1533                         } else if sawBad {
1534                                 t.Errorf("%#04x: non-bad suite after bad HTTP/2 one(s)", id)
1535                         }
1536                 }
1537
1538                 // Check that the list is sorted according to the documented criteria.
1539                 isBetter := func(a, b int) bool {
1540                         aSuite, bSuite := cipherSuiteByID(prefOrder[a]), cipherSuiteByID(prefOrder[b])
1541                         aName, bName := CipherSuiteName(prefOrder[a]), CipherSuiteName(prefOrder[b])
1542                         // * < RC4
1543                         if !strings.Contains(aName, "RC4") && strings.Contains(bName, "RC4") {
1544                                 return true
1545                         } else if strings.Contains(aName, "RC4") && !strings.Contains(bName, "RC4") {
1546                                 return false
1547                         }
1548                         // * < CBC_SHA256
1549                         if !strings.Contains(aName, "CBC_SHA256") && strings.Contains(bName, "CBC_SHA256") {
1550                                 return true
1551                         } else if strings.Contains(aName, "CBC_SHA256") && !strings.Contains(bName, "CBC_SHA256") {
1552                                 return false
1553                         }
1554                         // * < 3DES
1555                         if !strings.Contains(aName, "3DES") && strings.Contains(bName, "3DES") {
1556                                 return true
1557                         } else if strings.Contains(aName, "3DES") && !strings.Contains(bName, "3DES") {
1558                                 return false
1559                         }
1560                         // ECDHE < *
1561                         if aSuite.flags&suiteECDHE != 0 && bSuite.flags&suiteECDHE == 0 {
1562                                 return true
1563                         } else if aSuite.flags&suiteECDHE == 0 && bSuite.flags&suiteECDHE != 0 {
1564                                 return false
1565                         }
1566                         // AEAD < CBC
1567                         if aSuite.aead != nil && bSuite.aead == nil {
1568                                 return true
1569                         } else if aSuite.aead == nil && bSuite.aead != nil {
1570                                 return false
1571                         }
1572                         // AES < ChaCha20
1573                         if strings.Contains(aName, "AES") && strings.Contains(bName, "CHACHA20") {
1574                                 return i == 0 // true for cipherSuitesPreferenceOrder
1575                         } else if strings.Contains(aName, "CHACHA20") && strings.Contains(bName, "AES") {
1576                                 return i != 0 // true for cipherSuitesPreferenceOrderNoAES
1577                         }
1578                         // AES-128 < AES-256
1579                         if strings.Contains(aName, "AES_128") && strings.Contains(bName, "AES_256") {
1580                                 return true
1581                         } else if strings.Contains(aName, "AES_256") && strings.Contains(bName, "AES_128") {
1582                                 return false
1583                         }
1584                         // ECDSA < RSA
1585                         if aSuite.flags&suiteECSign != 0 && bSuite.flags&suiteECSign == 0 {
1586                                 return true
1587                         } else if aSuite.flags&suiteECSign == 0 && bSuite.flags&suiteECSign != 0 {
1588                                 return false
1589                         }
1590                         t.Fatalf("two ciphersuites are equal by all criteria: %v and %v", aName, bName)
1591                         panic("unreachable")
1592                 }
1593                 if !sort.SliceIsSorted(prefOrder, isBetter) {
1594                         t.Error("preference order is not sorted according to the rules")
1595                 }
1596         }
1597 }
1598
1599 func TestVersionName(t *testing.T) {
1600         if got, exp := VersionName(VersionTLS13), "TLS 1.3"; got != exp {
1601                 t.Errorf("unexpected VersionName: got %q, expected %q", got, exp)
1602         }
1603         if got, exp := VersionName(0x12a), "0x012A"; got != exp {
1604                 t.Errorf("unexpected fallback VersionName: got %q, expected %q", got, exp)
1605         }
1606 }
1607
1608 // http2isBadCipher is copied from net/http.
1609 // TODO: if it ends up exposed somewhere, use that instead.
1610 func http2isBadCipher(cipher uint16) bool {
1611         switch cipher {
1612         case TLS_RSA_WITH_RC4_128_SHA,
1613                 TLS_RSA_WITH_3DES_EDE_CBC_SHA,
1614                 TLS_RSA_WITH_AES_128_CBC_SHA,
1615                 TLS_RSA_WITH_AES_256_CBC_SHA,
1616                 TLS_RSA_WITH_AES_128_CBC_SHA256,
1617                 TLS_RSA_WITH_AES_128_GCM_SHA256,
1618                 TLS_RSA_WITH_AES_256_GCM_SHA384,
1619                 TLS_ECDHE_ECDSA_WITH_RC4_128_SHA,
1620                 TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA,
1621                 TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA,
1622                 TLS_ECDHE_RSA_WITH_RC4_128_SHA,
1623                 TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA,
1624                 TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,
1625                 TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA,
1626                 TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256,
1627                 TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256:
1628                 return true
1629         default:
1630                 return false
1631         }
1632 }
1633
1634 type brokenSigner struct{ crypto.Signer }
1635
1636 func (s brokenSigner) Sign(rand io.Reader, digest []byte, opts crypto.SignerOpts) (signature []byte, err error) {
1637         // Replace opts with opts.HashFunc(), so rsa.PSSOptions are discarded.
1638         return s.Signer.Sign(rand, digest, opts.HashFunc())
1639 }
1640
1641 // TestPKCS1OnlyCert uses a client certificate with a broken crypto.Signer that
1642 // always makes PKCS #1 v1.5 signatures, so can't be used with RSA-PSS.
1643 func TestPKCS1OnlyCert(t *testing.T) {
1644         clientConfig := testConfig.Clone()
1645         clientConfig.Certificates = []Certificate{{
1646                 Certificate: [][]byte{testRSACertificate},
1647                 PrivateKey:  brokenSigner{testRSAPrivateKey},
1648         }}
1649         serverConfig := testConfig.Clone()
1650         serverConfig.MaxVersion = VersionTLS12 // TLS 1.3 doesn't support PKCS #1 v1.5
1651         serverConfig.ClientAuth = RequireAnyClientCert
1652
1653         // If RSA-PSS is selected, the handshake should fail.
1654         if _, _, err := testHandshake(t, clientConfig, serverConfig); err == nil {
1655                 t.Fatal("expected broken certificate to cause connection to fail")
1656         }
1657
1658         clientConfig.Certificates[0].SupportedSignatureAlgorithms =
1659                 []SignatureScheme{PKCS1WithSHA1, PKCS1WithSHA256}
1660
1661         // But if the certificate restricts supported algorithms, RSA-PSS should not
1662         // be selected, and the handshake should succeed.
1663         if _, _, err := testHandshake(t, clientConfig, serverConfig); err != nil {
1664                 t.Error(err)
1665         }
1666 }
1667
1668 func TestVerifyCertificates(t *testing.T) {
1669         // See https://go.dev/issue/31641.
1670         t.Run("TLSv12", func(t *testing.T) { testVerifyCertificates(t, VersionTLS12) })
1671         t.Run("TLSv13", func(t *testing.T) { testVerifyCertificates(t, VersionTLS13) })
1672 }
1673
1674 func testVerifyCertificates(t *testing.T, version uint16) {
1675         tests := []struct {
1676                 name string
1677
1678                 InsecureSkipVerify bool
1679                 ClientAuth         ClientAuthType
1680                 ClientCertificates bool
1681         }{
1682                 {
1683                         name: "defaults",
1684                 },
1685                 {
1686                         name:               "InsecureSkipVerify",
1687                         InsecureSkipVerify: true,
1688                 },
1689                 {
1690                         name:       "RequestClientCert with no certs",
1691                         ClientAuth: RequestClientCert,
1692                 },
1693                 {
1694                         name:               "RequestClientCert with certs",
1695                         ClientAuth:         RequestClientCert,
1696                         ClientCertificates: true,
1697                 },
1698                 {
1699                         name:               "RequireAnyClientCert",
1700                         ClientAuth:         RequireAnyClientCert,
1701                         ClientCertificates: true,
1702                 },
1703                 {
1704                         name:       "VerifyClientCertIfGiven with no certs",
1705                         ClientAuth: VerifyClientCertIfGiven,
1706                 },
1707                 {
1708                         name:               "VerifyClientCertIfGiven with certs",
1709                         ClientAuth:         VerifyClientCertIfGiven,
1710                         ClientCertificates: true,
1711                 },
1712                 {
1713                         name:               "RequireAndVerifyClientCert",
1714                         ClientAuth:         RequireAndVerifyClientCert,
1715                         ClientCertificates: true,
1716                 },
1717         }
1718
1719         issuer, err := x509.ParseCertificate(testRSACertificateIssuer)
1720         if err != nil {
1721                 t.Fatal(err)
1722         }
1723         rootCAs := x509.NewCertPool()
1724         rootCAs.AddCert(issuer)
1725
1726         for _, test := range tests {
1727                 test := test
1728                 t.Run(test.name, func(t *testing.T) {
1729                         t.Parallel()
1730
1731                         var serverVerifyConnection, clientVerifyConnection bool
1732                         var serverVerifyPeerCertificates, clientVerifyPeerCertificates bool
1733
1734                         clientConfig := testConfig.Clone()
1735                         clientConfig.Time = func() time.Time { return time.Unix(1476984729, 0) }
1736                         clientConfig.MaxVersion = version
1737                         clientConfig.MinVersion = version
1738                         clientConfig.RootCAs = rootCAs
1739                         clientConfig.ServerName = "example.golang"
1740                         clientConfig.ClientSessionCache = NewLRUClientSessionCache(1)
1741                         serverConfig := clientConfig.Clone()
1742                         serverConfig.ClientCAs = rootCAs
1743
1744                         clientConfig.VerifyConnection = func(cs ConnectionState) error {
1745                                 clientVerifyConnection = true
1746                                 return nil
1747                         }
1748                         clientConfig.VerifyPeerCertificate = func(rawCerts [][]byte, verifiedChains [][]*x509.Certificate) error {
1749                                 clientVerifyPeerCertificates = true
1750                                 return nil
1751                         }
1752                         serverConfig.VerifyConnection = func(cs ConnectionState) error {
1753                                 serverVerifyConnection = true
1754                                 return nil
1755                         }
1756                         serverConfig.VerifyPeerCertificate = func(rawCerts [][]byte, verifiedChains [][]*x509.Certificate) error {
1757                                 serverVerifyPeerCertificates = true
1758                                 return nil
1759                         }
1760
1761                         clientConfig.InsecureSkipVerify = test.InsecureSkipVerify
1762                         serverConfig.ClientAuth = test.ClientAuth
1763                         if !test.ClientCertificates {
1764                                 clientConfig.Certificates = nil
1765                         }
1766
1767                         if _, _, err := testHandshake(t, clientConfig, serverConfig); err != nil {
1768                                 t.Fatal(err)
1769                         }
1770
1771                         want := serverConfig.ClientAuth != NoClientCert
1772                         if serverVerifyPeerCertificates != want {
1773                                 t.Errorf("VerifyPeerCertificates on the server: got %v, want %v",
1774                                         serverVerifyPeerCertificates, want)
1775                         }
1776                         if !clientVerifyPeerCertificates {
1777                                 t.Errorf("VerifyPeerCertificates not called on the client")
1778                         }
1779                         if !serverVerifyConnection {
1780                                 t.Error("VerifyConnection did not get called on the server")
1781                         }
1782                         if !clientVerifyConnection {
1783                                 t.Error("VerifyConnection did not get called on the client")
1784                         }
1785
1786                         serverVerifyPeerCertificates, clientVerifyPeerCertificates = false, false
1787                         serverVerifyConnection, clientVerifyConnection = false, false
1788                         cs, _, err := testHandshake(t, clientConfig, serverConfig)
1789                         if err != nil {
1790                                 t.Fatal(err)
1791                         }
1792                         if !cs.DidResume {
1793                                 t.Error("expected resumption")
1794                         }
1795
1796                         if serverVerifyPeerCertificates {
1797                                 t.Error("VerifyPeerCertificates got called on the server on resumption")
1798                         }
1799                         if clientVerifyPeerCertificates {
1800                                 t.Error("VerifyPeerCertificates got called on the client on resumption")
1801                         }
1802                         if !serverVerifyConnection {
1803                                 t.Error("VerifyConnection did not get called on the server on resumption")
1804                         }
1805                         if !clientVerifyConnection {
1806                                 t.Error("VerifyConnection did not get called on the client on resumption")
1807                         }
1808                 })
1809         }
1810 }