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