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 TestConnCloseBreakingWrite(t *testing.T) {
576 ln := newLocalListener(t)
577 defer ln.Close()
578
579 srvCh := make(chan *Conn, 1)
580 var serr error
581 var sconn net.Conn
582 go func() {
583 var err error
584 sconn, err = ln.Accept()
585 if err != nil {
586 serr = err
587 srvCh <- nil
588 return
589 }
590 serverConfig := testConfig.Clone()
591 srv := Server(sconn, serverConfig)
592 if err := srv.Handshake(); err != nil {
593 serr = fmt.Errorf("handshake: %v", err)
594 srvCh <- nil
595 return
596 }
597 srvCh <- srv
598 }()
599
600 cconn, err := net.Dial("tcp", ln.Addr().String())
601 if err != nil {
602 t.Fatal(err)
603 }
604 defer cconn.Close()
605
606 conn := &changeImplConn{
607 Conn: cconn,
608 }
609
610 clientConfig := testConfig.Clone()
611 tconn := Client(conn, clientConfig)
612 if err := tconn.Handshake(); err != nil {
613 t.Fatal(err)
614 }
615
616 srv := <-srvCh
617 if srv == nil {
618 t.Fatal(serr)
619 }
620 defer sconn.Close()
621
622 connClosed := make(chan struct{})
623 conn.closeFunc = func() error {
624 close(connClosed)
625 return nil
626 }
627
628 inWrite := make(chan bool, 1)
629 var errConnClosed = errors.New("conn closed for test")
630 conn.writeFunc = func(p []byte) (n int, err error) {
631 inWrite <- true
632 <-connClosed
633 return 0, errConnClosed
634 }
635
636 closeReturned := make(chan bool, 1)
637 go func() {
638 <-inWrite
639 tconn.Close()
640 closeReturned <- true
641 }()
642
643 _, err = tconn.Write([]byte("foo"))
644 if err != errConnClosed {
645 t.Errorf("Write error = %v; want errConnClosed", err)
646 }
647
648 <-closeReturned
649 if err := tconn.Close(); err != net.ErrClosed {
650 t.Errorf("Close error = %v; want net.ErrClosed", err)
651 }
652 }
653
654 func TestConnCloseWrite(t *testing.T) {
655 ln := newLocalListener(t)
656 defer ln.Close()
657
658 clientDoneChan := make(chan struct{})
659
660 serverCloseWrite := func() error {
661 sconn, err := ln.Accept()
662 if err != nil {
663 return fmt.Errorf("accept: %v", err)
664 }
665 defer sconn.Close()
666
667 serverConfig := testConfig.Clone()
668 srv := Server(sconn, serverConfig)
669 if err := srv.Handshake(); err != nil {
670 return fmt.Errorf("handshake: %v", err)
671 }
672 defer srv.Close()
673
674 data, err := io.ReadAll(srv)
675 if err != nil {
676 return err
677 }
678 if len(data) > 0 {
679 return fmt.Errorf("Read data = %q; want nothing", data)
680 }
681
682 if err := srv.CloseWrite(); err != nil {
683 return fmt.Errorf("server CloseWrite: %v", err)
684 }
685
686
687
688
689
690 <-clientDoneChan
691 return nil
692 }
693
694 clientCloseWrite := func() error {
695 defer close(clientDoneChan)
696
697 clientConfig := testConfig.Clone()
698 conn, err := Dial("tcp", ln.Addr().String(), clientConfig)
699 if err != nil {
700 return err
701 }
702 if err := conn.Handshake(); err != nil {
703 return err
704 }
705 defer conn.Close()
706
707 if err := conn.CloseWrite(); err != nil {
708 return fmt.Errorf("client CloseWrite: %v", err)
709 }
710
711 if _, err := conn.Write([]byte{0}); err != errShutdown {
712 return fmt.Errorf("CloseWrite error = %v; want errShutdown", err)
713 }
714
715 data, err := io.ReadAll(conn)
716 if err != nil {
717 return err
718 }
719 if len(data) > 0 {
720 return fmt.Errorf("Read data = %q; want nothing", data)
721 }
722 return nil
723 }
724
725 errChan := make(chan error, 2)
726
727 go func() { errChan <- serverCloseWrite() }()
728 go func() { errChan <- clientCloseWrite() }()
729
730 for i := 0; i < 2; i++ {
731 select {
732 case err := <-errChan:
733 if err != nil {
734 t.Fatal(err)
735 }
736 case <-time.After(10 * time.Second):
737 t.Fatal("deadlock")
738 }
739 }
740
741
742
743 {
744 ln2 := newLocalListener(t)
745 defer ln2.Close()
746
747 netConn, err := net.Dial("tcp", ln2.Addr().String())
748 if err != nil {
749 t.Fatal(err)
750 }
751 defer netConn.Close()
752 conn := Client(netConn, testConfig.Clone())
753
754 if err := conn.CloseWrite(); err != errEarlyCloseWrite {
755 t.Errorf("CloseWrite error = %v; want errEarlyCloseWrite", err)
756 }
757 }
758 }
759
760 func TestWarningAlertFlood(t *testing.T) {
761 ln := newLocalListener(t)
762 defer ln.Close()
763
764 server := func() error {
765 sconn, err := ln.Accept()
766 if err != nil {
767 return fmt.Errorf("accept: %v", err)
768 }
769 defer sconn.Close()
770
771 serverConfig := testConfig.Clone()
772 srv := Server(sconn, serverConfig)
773 if err := srv.Handshake(); err != nil {
774 return fmt.Errorf("handshake: %v", err)
775 }
776 defer srv.Close()
777
778 _, err = io.ReadAll(srv)
779 if err == nil {
780 return errors.New("unexpected lack of error from server")
781 }
782 const expected = "too many ignored"
783 if str := err.Error(); !strings.Contains(str, expected) {
784 return fmt.Errorf("expected error containing %q, but saw: %s", expected, str)
785 }
786
787 return nil
788 }
789
790 errChan := make(chan error, 1)
791 go func() { errChan <- server() }()
792
793 clientConfig := testConfig.Clone()
794 clientConfig.MaxVersion = VersionTLS12
795 conn, err := Dial("tcp", ln.Addr().String(), clientConfig)
796 if err != nil {
797 t.Fatal(err)
798 }
799 defer conn.Close()
800 if err := conn.Handshake(); err != nil {
801 t.Fatal(err)
802 }
803
804 for i := 0; i < maxUselessRecords+1; i++ {
805 conn.sendAlert(alertNoRenegotiation)
806 }
807
808 if err := <-errChan; err != nil {
809 t.Fatal(err)
810 }
811 }
812
813 func TestCloneFuncFields(t *testing.T) {
814 const expectedCount = 9
815 called := 0
816
817 c1 := Config{
818 Time: func() time.Time {
819 called |= 1 << 0
820 return time.Time{}
821 },
822 GetCertificate: func(*ClientHelloInfo) (*Certificate, error) {
823 called |= 1 << 1
824 return nil, nil
825 },
826 GetClientCertificate: func(*CertificateRequestInfo) (*Certificate, error) {
827 called |= 1 << 2
828 return nil, nil
829 },
830 GetConfigForClient: func(*ClientHelloInfo) (*Config, error) {
831 called |= 1 << 3
832 return nil, nil
833 },
834 VerifyPeerCertificate: func(rawCerts [][]byte, verifiedChains [][]*x509.Certificate) error {
835 called |= 1 << 4
836 return nil
837 },
838 VerifyConnection: func(ConnectionState) error {
839 called |= 1 << 5
840 return nil
841 },
842 UnwrapSession: func(identity []byte, cs ConnectionState) (*SessionState, error) {
843 called |= 1 << 6
844 return nil, nil
845 },
846 WrapSession: func(cs ConnectionState, ss *SessionState) ([]byte, error) {
847 called |= 1 << 7
848 return nil, nil
849 },
850 EncryptedClientHelloRejectionVerify: func(ConnectionState) error {
851 called |= 1 << 8
852 return nil
853 },
854 }
855
856 c2 := c1.Clone()
857
858 c2.Time()
859 c2.GetCertificate(nil)
860 c2.GetClientCertificate(nil)
861 c2.GetConfigForClient(nil)
862 c2.VerifyPeerCertificate(nil, nil)
863 c2.VerifyConnection(ConnectionState{})
864 c2.UnwrapSession(nil, ConnectionState{})
865 c2.WrapSession(ConnectionState{}, nil)
866 c2.EncryptedClientHelloRejectionVerify(ConnectionState{})
867
868 if called != (1<<expectedCount)-1 {
869 t.Fatalf("expected %d calls but saw calls %b", expectedCount, called)
870 }
871 }
872
873 func TestCloneNonFuncFields(t *testing.T) {
874 var c1 Config
875 v := reflect.ValueOf(&c1).Elem()
876
877 typ := v.Type()
878 for i := 0; i < typ.NumField(); i++ {
879 f := v.Field(i)
880
881
882 switch fn := typ.Field(i).Name; fn {
883 case "Rand":
884 f.Set(reflect.ValueOf(io.Reader(os.Stdin)))
885 case "Time", "GetCertificate", "GetConfigForClient", "VerifyPeerCertificate", "VerifyConnection", "GetClientCertificate", "WrapSession", "UnwrapSession", "EncryptedClientHelloRejectionVerify":
886
887
888
889
890 case "Certificates":
891 f.Set(reflect.ValueOf([]Certificate{
892 {Certificate: [][]byte{{'b'}}},
893 }))
894 case "NameToCertificate":
895 f.Set(reflect.ValueOf(map[string]*Certificate{"a": nil}))
896 case "RootCAs", "ClientCAs":
897 f.Set(reflect.ValueOf(x509.NewCertPool()))
898 case "ClientSessionCache":
899 f.Set(reflect.ValueOf(NewLRUClientSessionCache(10)))
900 case "KeyLogWriter":
901 f.Set(reflect.ValueOf(io.Writer(os.Stdout)))
902 case "NextProtos":
903 f.Set(reflect.ValueOf([]string{"a", "b"}))
904 case "ServerName":
905 f.Set(reflect.ValueOf("b"))
906 case "ClientAuth":
907 f.Set(reflect.ValueOf(VerifyClientCertIfGiven))
908 case "InsecureSkipVerify", "SessionTicketsDisabled", "DynamicRecordSizingDisabled", "PreferServerCipherSuites":
909 f.Set(reflect.ValueOf(true))
910 case "MinVersion", "MaxVersion":
911 f.Set(reflect.ValueOf(uint16(VersionTLS12)))
912 case "SessionTicketKey":
913 f.Set(reflect.ValueOf([32]byte{}))
914 case "CipherSuites":
915 f.Set(reflect.ValueOf([]uint16{1, 2}))
916 case "CurvePreferences":
917 f.Set(reflect.ValueOf([]CurveID{CurveP256}))
918 case "Renegotiation":
919 f.Set(reflect.ValueOf(RenegotiateOnceAsClient))
920 case "EncryptedClientHelloConfigList":
921 f.Set(reflect.ValueOf([]byte{'x'}))
922 case "EncryptedClientHelloKeys":
923 f.Set(reflect.ValueOf([]EncryptedClientHelloKey{
924 {Config: []byte{1}, PrivateKey: []byte{1}},
925 }))
926 case "mutex", "autoSessionTicketKeys", "sessionTicketKeys":
927 continue
928 default:
929 t.Errorf("all fields must be accounted for, but saw unknown field %q", fn)
930 }
931 }
932
933 c1.autoSessionTicketKeys = []ticketKey{c1.ticketKeyFromBytes(c1.SessionTicketKey)}
934 c1.sessionTicketKeys = []ticketKey{c1.ticketKeyFromBytes(c1.SessionTicketKey)}
935
936 c2 := c1.Clone()
937 if !reflect.DeepEqual(&c1, c2) {
938 t.Errorf("clone failed to copy a field")
939 }
940 }
941
942 func TestCloneNilConfig(t *testing.T) {
943 var config *Config
944 if cc := config.Clone(); cc != nil {
945 t.Fatalf("Clone with nil should return nil, got: %+v", cc)
946 }
947 }
948
949
950
951 type changeImplConn struct {
952 net.Conn
953 writeFunc func([]byte) (int, error)
954 closeFunc func() error
955 }
956
957 func (w *changeImplConn) Write(p []byte) (n int, err error) {
958 if w.writeFunc != nil {
959 return w.writeFunc(p)
960 }
961 return w.Conn.Write(p)
962 }
963
964 func (w *changeImplConn) Close() error {
965 if w.closeFunc != nil {
966 return w.closeFunc()
967 }
968 return w.Conn.Close()
969 }
970
971 func throughput(b *testing.B, version uint16, totalBytes int64, dynamicRecordSizingDisabled bool) {
972 ln := newLocalListener(b)
973 defer ln.Close()
974
975 N := b.N
976
977
978
979 const bufsize = 32 << 10
980
981 go func() {
982 buf := make([]byte, bufsize)
983 for i := 0; i < N; i++ {
984 sconn, err := ln.Accept()
985 if err != nil {
986
987
988 panic(fmt.Errorf("accept: %v", err))
989 }
990 serverConfig := testConfig.Clone()
991 serverConfig.CipherSuites = nil
992 serverConfig.DynamicRecordSizingDisabled = dynamicRecordSizingDisabled
993 srv := Server(sconn, serverConfig)
994 if err := srv.Handshake(); err != nil {
995 panic(fmt.Errorf("handshake: %v", err))
996 }
997 if _, err := io.CopyBuffer(srv, srv, buf); err != nil {
998 panic(fmt.Errorf("copy buffer: %v", err))
999 }
1000 }
1001 }()
1002
1003 b.SetBytes(totalBytes)
1004 clientConfig := testConfig.Clone()
1005 clientConfig.CipherSuites = nil
1006 clientConfig.DynamicRecordSizingDisabled = dynamicRecordSizingDisabled
1007 clientConfig.MaxVersion = version
1008
1009 buf := make([]byte, bufsize)
1010 chunks := int(math.Ceil(float64(totalBytes) / float64(len(buf))))
1011 for i := 0; i < N; i++ {
1012 conn, err := Dial("tcp", ln.Addr().String(), clientConfig)
1013 if err != nil {
1014 b.Fatal(err)
1015 }
1016 for j := 0; j < chunks; j++ {
1017 _, err := conn.Write(buf)
1018 if err != nil {
1019 b.Fatal(err)
1020 }
1021 _, err = io.ReadFull(conn, buf)
1022 if err != nil {
1023 b.Fatal(err)
1024 }
1025 }
1026 conn.Close()
1027 }
1028 }
1029
1030 func BenchmarkThroughput(b *testing.B) {
1031 for _, mode := range []string{"Max", "Dynamic"} {
1032 for size := 1; size <= 64; size <<= 1 {
1033 name := fmt.Sprintf("%sPacket/%dMB", mode, size)
1034 b.Run(name, func(b *testing.B) {
1035 b.Run("TLSv12", func(b *testing.B) {
1036 throughput(b, VersionTLS12, int64(size<<20), mode == "Max")
1037 })
1038 b.Run("TLSv13", func(b *testing.B) {
1039 throughput(b, VersionTLS13, int64(size<<20), mode == "Max")
1040 })
1041 })
1042 }
1043 }
1044 }
1045
1046 type slowConn struct {
1047 net.Conn
1048 bps int
1049 }
1050
1051 func (c *slowConn) Write(p []byte) (int, error) {
1052 if c.bps == 0 {
1053 panic("too slow")
1054 }
1055 t0 := time.Now()
1056 wrote := 0
1057 for wrote < len(p) {
1058 time.Sleep(100 * time.Microsecond)
1059 allowed := int(time.Since(t0).Seconds()*float64(c.bps)) / 8
1060 if allowed > len(p) {
1061 allowed = len(p)
1062 }
1063 if wrote < allowed {
1064 n, err := c.Conn.Write(p[wrote:allowed])
1065 wrote += n
1066 if err != nil {
1067 return wrote, err
1068 }
1069 }
1070 }
1071 return len(p), nil
1072 }
1073
1074 func latency(b *testing.B, version uint16, bps int, dynamicRecordSizingDisabled bool) {
1075 ln := newLocalListener(b)
1076 defer ln.Close()
1077
1078 N := b.N
1079
1080 go func() {
1081 for i := 0; i < N; i++ {
1082 sconn, err := ln.Accept()
1083 if err != nil {
1084
1085
1086 panic(fmt.Errorf("accept: %v", err))
1087 }
1088 serverConfig := testConfig.Clone()
1089 serverConfig.DynamicRecordSizingDisabled = dynamicRecordSizingDisabled
1090 srv := Server(&slowConn{sconn, bps}, serverConfig)
1091 if err := srv.Handshake(); err != nil {
1092 panic(fmt.Errorf("handshake: %v", err))
1093 }
1094 io.Copy(srv, srv)
1095 }
1096 }()
1097
1098 clientConfig := testConfig.Clone()
1099 clientConfig.DynamicRecordSizingDisabled = dynamicRecordSizingDisabled
1100 clientConfig.MaxVersion = version
1101
1102 buf := make([]byte, 16384)
1103 peek := make([]byte, 1)
1104
1105 for i := 0; i < N; i++ {
1106 conn, err := Dial("tcp", ln.Addr().String(), clientConfig)
1107 if err != nil {
1108 b.Fatal(err)
1109 }
1110
1111 if _, err := conn.Write(buf[:1]); err != nil {
1112 b.Fatal(err)
1113 }
1114 if _, err := io.ReadFull(conn, peek); err != nil {
1115 b.Fatal(err)
1116 }
1117 if _, err := conn.Write(buf); err != nil {
1118 b.Fatal(err)
1119 }
1120 if _, err = io.ReadFull(conn, peek); err != nil {
1121 b.Fatal(err)
1122 }
1123 conn.Close()
1124 }
1125 }
1126
1127 func BenchmarkLatency(b *testing.B) {
1128 for _, mode := range []string{"Max", "Dynamic"} {
1129 for _, kbps := range []int{200, 500, 1000, 2000, 5000} {
1130 name := fmt.Sprintf("%sPacket/%dkbps", mode, kbps)
1131 b.Run(name, func(b *testing.B) {
1132 b.Run("TLSv12", func(b *testing.B) {
1133 latency(b, VersionTLS12, kbps*1000, mode == "Max")
1134 })
1135 b.Run("TLSv13", func(b *testing.B) {
1136 latency(b, VersionTLS13, kbps*1000, mode == "Max")
1137 })
1138 })
1139 }
1140 }
1141 }
1142
1143 func TestConnectionStateMarshal(t *testing.T) {
1144 cs := &ConnectionState{}
1145 _, err := json.Marshal(cs)
1146 if err != nil {
1147 t.Errorf("json.Marshal failed on ConnectionState: %v", err)
1148 }
1149 }
1150
1151 func TestConnectionState(t *testing.T) {
1152 issuer, err := x509.ParseCertificate(testRSA2048CertificateIssuer)
1153 if err != nil {
1154 panic(err)
1155 }
1156 rootCAs := x509.NewCertPool()
1157 rootCAs.AddCert(issuer)
1158
1159 const alpnProtocol = "golang"
1160 const serverName = "example.golang"
1161 var scts = [][]byte{[]byte("dummy sct 1"), []byte("dummy sct 2")}
1162 var ocsp = []byte("dummy ocsp")
1163
1164 checkConnectionState := func(t *testing.T, cs ConnectionState, version uint16, isClient bool) {
1165 if cs.Version != version {
1166 t.Errorf("got Version %x, expected %x", cs.Version, version)
1167 }
1168
1169 if !cs.HandshakeComplete {
1170 t.Errorf("got HandshakeComplete %v, expected true", cs.HandshakeComplete)
1171 }
1172
1173 if cs.DidResume {
1174 t.Errorf("got DidResume %v, expected false", cs.DidResume)
1175 }
1176
1177 if cs.CipherSuite == 0 {
1178 t.Errorf("got zero CipherSuite")
1179 }
1180
1181 if cs.CurveID == 0 {
1182 t.Errorf("got zero CurveID")
1183 }
1184
1185 if cs.NegotiatedProtocol != alpnProtocol {
1186 t.Errorf("got ALPN protocol %q, expected %q", cs.NegotiatedProtocol, alpnProtocol)
1187 }
1188
1189 if !cs.NegotiatedProtocolIsMutual {
1190 t.Errorf("got NegotiatedProtocolIsMutual %v, expected true", cs.NegotiatedProtocolIsMutual)
1191 }
1192
1193 if cs.ServerName != serverName {
1194 t.Errorf("got ServerName %q, expected %q", cs.ServerName, serverName)
1195 }
1196
1197 if len(cs.PeerCertificates) != 1 {
1198 t.Errorf("got %d PeerCertificates, expected %d", len(cs.PeerCertificates), 1)
1199 } else if !bytes.Equal(cs.PeerCertificates[0].Raw, testRSA2048Certificate) {
1200 t.Errorf("got PeerCertificates %x, expected %x", cs.PeerCertificates[0].Raw, testRSA2048Certificate)
1201 }
1202
1203 if len(cs.VerifiedChains) != 1 {
1204 t.Errorf("got %d long verified chain, expected %d", len(cs.VerifiedChains), 1)
1205 } else if len(cs.VerifiedChains[0]) != 2 {
1206 t.Errorf("got %d verified chain, expected %d", len(cs.VerifiedChains[0]), 2)
1207 } else if !bytes.Equal(cs.VerifiedChains[0][0].Raw, testRSA2048Certificate) {
1208 t.Errorf("got verified chain[0][0] %x, expected %x", cs.VerifiedChains[0][0].Raw, testRSA2048Certificate)
1209 } else if !bytes.Equal(cs.VerifiedChains[0][1].Raw, testRSA2048CertificateIssuer) {
1210 t.Errorf("got verified chain[0][1] %x, expected %x", cs.VerifiedChains[0][1].Raw, testRSA2048CertificateIssuer)
1211 }
1212
1213
1214 if isClient || version == VersionTLS13 {
1215 if len(cs.SignedCertificateTimestamps) != 2 {
1216 t.Errorf("got %d SCTs, expected %d", len(cs.SignedCertificateTimestamps), 2)
1217 } else if !bytes.Equal(cs.SignedCertificateTimestamps[0], scts[0]) {
1218 t.Errorf("got SCTs %x, expected %x", cs.SignedCertificateTimestamps[0], scts[0])
1219 } else if !bytes.Equal(cs.SignedCertificateTimestamps[1], scts[1]) {
1220 t.Errorf("got SCTs %x, expected %x", cs.SignedCertificateTimestamps[1], scts[1])
1221 }
1222 if !bytes.Equal(cs.OCSPResponse, ocsp) {
1223 t.Errorf("got OCSP %x, expected %x", cs.OCSPResponse, ocsp)
1224 }
1225 } else {
1226 if cs.SignedCertificateTimestamps != nil {
1227 t.Errorf("got %d SCTs, expected nil", len(cs.SignedCertificateTimestamps))
1228 }
1229 if cs.OCSPResponse != nil {
1230 t.Errorf("got OCSP %x, expected nil", cs.OCSPResponse)
1231 }
1232 }
1233
1234 if version == VersionTLS13 {
1235 if cs.TLSUnique != nil {
1236 t.Errorf("got TLSUnique %x, expected nil", cs.TLSUnique)
1237 }
1238 } else {
1239 if cs.TLSUnique == nil {
1240 t.Errorf("got nil TLSUnique")
1241 }
1242 }
1243 }
1244
1245 compareConnectionStates := func(t *testing.T, cs1, cs2 ConnectionState) {
1246 if cs1.Version != cs2.Version {
1247 t.Errorf("Version mismatch: %x != %x", cs1.Version, cs2.Version)
1248 }
1249 if cs1.HandshakeComplete != cs2.HandshakeComplete {
1250 t.Errorf("HandshakeComplete mismatch: %v != %v", cs1.HandshakeComplete, cs2.HandshakeComplete)
1251 }
1252
1253 if cs1.CipherSuite != cs2.CipherSuite {
1254 t.Errorf("CipherSuite mismatch: %x != %x", cs1.CipherSuite, cs2.CipherSuite)
1255 }
1256 if cs1.CurveID != cs2.CurveID {
1257 t.Errorf("CurveID mismatch: %s != %s", cs1.CurveID, cs2.CurveID)
1258 }
1259 if cs1.NegotiatedProtocol != cs2.NegotiatedProtocol {
1260 t.Errorf("NegotiatedProtocol mismatch: %q != %q", cs1.NegotiatedProtocol, cs2.NegotiatedProtocol)
1261 }
1262 if cs1.NegotiatedProtocolIsMutual != cs2.NegotiatedProtocolIsMutual {
1263 t.Errorf("NegotiatedProtocolIsMutual mismatch: %v != %v", cs1.NegotiatedProtocolIsMutual, cs2.NegotiatedProtocolIsMutual)
1264 }
1265 if cs1.ServerName != cs2.ServerName {
1266 t.Errorf("ServerName mismatch: %q != %q", cs1.ServerName, cs2.ServerName)
1267 }
1268 if !reflect.DeepEqual(cs1.PeerCertificates, cs2.PeerCertificates) {
1269 t.Errorf("PeerCertificates mismatch")
1270 }
1271 if !reflect.DeepEqual(cs1.VerifiedChains, cs2.VerifiedChains) {
1272 t.Errorf("VerifiedChains mismatch")
1273 }
1274 if !reflect.DeepEqual(cs1.SignedCertificateTimestamps, cs2.SignedCertificateTimestamps) {
1275 t.Errorf("SignedCertificateTimestamps mismatch: %x != %x", cs1.SignedCertificateTimestamps, cs2.SignedCertificateTimestamps)
1276 }
1277 if !bytes.Equal(cs1.OCSPResponse, cs2.OCSPResponse) {
1278 t.Errorf("OCSPResponse mismatch: %x != %x", cs1.OCSPResponse, cs2.OCSPResponse)
1279 }
1280
1281 }
1282
1283 for _, v := range []uint16{VersionTLS10, VersionTLS12, VersionTLS13} {
1284 if !isFIPSVersion(v) && fips140tls.Required() {
1285 t.Skipf("skipping test in FIPS 140-3 mode for non-FIPS version %x", v)
1286 }
1287 var name string
1288 switch v {
1289 case VersionTLS10:
1290 name = "TLSv10"
1291 case VersionTLS12:
1292 name = "TLSv12"
1293 case VersionTLS13:
1294 name = "TLSv13"
1295 }
1296 t.Run(name, func(t *testing.T) {
1297 config := &Config{
1298 Time: testTime,
1299 Certificates: make([]Certificate, 1),
1300 MinVersion: v,
1301 MaxVersion: v,
1302 RootCAs: rootCAs,
1303 ClientCAs: rootCAs,
1304 ClientAuth: RequireAndVerifyClientCert,
1305 NextProtos: []string{alpnProtocol},
1306 ServerName: serverName,
1307 ClientSessionCache: NewLRUClientSessionCache(1),
1308 }
1309 config.Certificates[0].Certificate = [][]byte{testRSA2048Certificate}
1310 config.Certificates[0].PrivateKey = testRSA2048PrivateKey
1311 config.Certificates[0].SignedCertificateTimestamps = scts
1312 config.Certificates[0].OCSPStaple = ocsp
1313
1314 ss, cs, err := testHandshake(t, config, config)
1315 if err != nil {
1316 t.Fatalf("handshake failed: %v", err)
1317 }
1318
1319 t.Run("Client", func(t *testing.T) { checkConnectionState(t, cs, v, true) })
1320 t.Run("Server", func(t *testing.T) { checkConnectionState(t, ss, v, false) })
1321
1322 t.Run("Resume", func(t *testing.T) {
1323
1324
1325
1326 ss1, cs1, err := testHandshake(t, config, config)
1327 if err != nil {
1328 t.Fatalf("handshake failed: %v", err)
1329 }
1330
1331 if !cs1.DidResume || !ss1.DidResume {
1332 t.Errorf("DidResume is false")
1333 }
1334
1335 t.Run("Client", func(t *testing.T) { compareConnectionStates(t, cs, cs1) })
1336 t.Run("Server", func(t *testing.T) { compareConnectionStates(t, ss, ss1) })
1337 })
1338 })
1339 }
1340 }
1341
1342
1343
1344 func TestBuildNameToCertificate_doesntModifyCertificates(t *testing.T) {
1345 c0 := Certificate{
1346 Certificate: [][]byte{testRSACertificate},
1347 PrivateKey: testRSAPrivateKey,
1348 }
1349 c1 := Certificate{
1350 Certificate: [][]byte{testSNICertificate},
1351 PrivateKey: testRSAPrivateKey,
1352 }
1353 config := testConfig.Clone()
1354 config.Certificates = []Certificate{c0, c1}
1355
1356 config.BuildNameToCertificate()
1357 got := config.Certificates
1358 want := []Certificate{c0, c1}
1359 if !reflect.DeepEqual(got, want) {
1360 t.Fatalf("Certificates were mutated by BuildNameToCertificate\nGot: %#v\nWant: %#v\n", got, want)
1361 }
1362 }
1363
1364 func testingKey(s string) string { return strings.ReplaceAll(s, "TESTING KEY", "PRIVATE KEY") }
1365
1366 func TestClientHelloInfo_SupportsCertificate(t *testing.T) {
1367 skipFIPS(t)
1368
1369 rsaCert := &Certificate{
1370 Certificate: [][]byte{testRSACertificate},
1371 PrivateKey: testRSAPrivateKey,
1372 }
1373 pkcs1Cert := &Certificate{
1374 Certificate: [][]byte{testRSACertificate},
1375 PrivateKey: testRSAPrivateKey,
1376 SupportedSignatureAlgorithms: []SignatureScheme{PKCS1WithSHA1, PKCS1WithSHA256},
1377 }
1378 ecdsaCert := &Certificate{
1379
1380 Certificate: [][]byte{testP256Certificate},
1381 PrivateKey: testP256PrivateKey,
1382 }
1383 ed25519Cert := &Certificate{
1384 Certificate: [][]byte{testEd25519Certificate},
1385 PrivateKey: testEd25519PrivateKey,
1386 }
1387
1388 tests := []struct {
1389 c *Certificate
1390 chi *ClientHelloInfo
1391 wantErr string
1392 }{
1393 {rsaCert, &ClientHelloInfo{
1394 ServerName: "example.golang",
1395 SignatureSchemes: []SignatureScheme{PSSWithSHA256},
1396 SupportedVersions: []uint16{VersionTLS13},
1397 }, ""},
1398 {ecdsaCert, &ClientHelloInfo{
1399 SignatureSchemes: []SignatureScheme{PSSWithSHA256, ECDSAWithP256AndSHA256},
1400 SupportedVersions: []uint16{VersionTLS13, VersionTLS12},
1401 }, ""},
1402 {rsaCert, &ClientHelloInfo{
1403 ServerName: "example.com",
1404 SignatureSchemes: []SignatureScheme{PSSWithSHA256},
1405 SupportedVersions: []uint16{VersionTLS13},
1406 }, "not valid for requested server name"},
1407 {ecdsaCert, &ClientHelloInfo{
1408 SignatureSchemes: []SignatureScheme{ECDSAWithP384AndSHA384},
1409 SupportedVersions: []uint16{VersionTLS13},
1410 }, "signature algorithms"},
1411 {pkcs1Cert, &ClientHelloInfo{
1412 SignatureSchemes: []SignatureScheme{PSSWithSHA256, ECDSAWithP256AndSHA256},
1413 SupportedVersions: []uint16{VersionTLS13},
1414 }, "signature algorithms"},
1415
1416 {rsaCert, &ClientHelloInfo{
1417 CipherSuites: []uint16{TLS_RSA_WITH_AES_128_GCM_SHA256},
1418 SignatureSchemes: []SignatureScheme{PKCS1WithSHA1},
1419 SupportedVersions: []uint16{VersionTLS13, VersionTLS12},
1420 }, "signature algorithms"},
1421 {rsaCert, &ClientHelloInfo{
1422 CipherSuites: []uint16{TLS_RSA_WITH_AES_128_GCM_SHA256},
1423 SignatureSchemes: []SignatureScheme{PKCS1WithSHA1},
1424 SupportedVersions: []uint16{VersionTLS13, VersionTLS12},
1425 config: &Config{
1426 CipherSuites: []uint16{TLS_RSA_WITH_AES_128_GCM_SHA256},
1427 MaxVersion: VersionTLS12,
1428 },
1429 }, ""},
1430
1431 {ecdsaCert, &ClientHelloInfo{
1432 CipherSuites: []uint16{TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256},
1433 SupportedCurves: []CurveID{CurveP256},
1434 SupportedPoints: []uint8{pointFormatUncompressed},
1435 SignatureSchemes: []SignatureScheme{ECDSAWithP256AndSHA256},
1436 SupportedVersions: []uint16{VersionTLS12},
1437 }, ""},
1438 {ecdsaCert, &ClientHelloInfo{
1439 CipherSuites: []uint16{TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256},
1440 SupportedCurves: []CurveID{CurveP256},
1441 SupportedPoints: []uint8{pointFormatUncompressed},
1442 SignatureSchemes: []SignatureScheme{ECDSAWithP384AndSHA384},
1443 SupportedVersions: []uint16{VersionTLS12},
1444 }, ""},
1445 {ecdsaCert, &ClientHelloInfo{
1446 CipherSuites: []uint16{TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256},
1447 SupportedCurves: []CurveID{CurveP256},
1448 SupportedPoints: []uint8{pointFormatUncompressed},
1449 SignatureSchemes: nil,
1450 SupportedVersions: []uint16{VersionTLS12},
1451 }, ""},
1452 {ecdsaCert, &ClientHelloInfo{
1453 CipherSuites: []uint16{TLS_RSA_WITH_AES_128_GCM_SHA256},
1454 SupportedCurves: []CurveID{CurveP256},
1455 SupportedPoints: []uint8{pointFormatUncompressed},
1456 SignatureSchemes: []SignatureScheme{ECDSAWithP256AndSHA256},
1457 SupportedVersions: []uint16{VersionTLS12},
1458 }, "cipher suite"},
1459 {ecdsaCert, &ClientHelloInfo{
1460 CipherSuites: []uint16{TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256},
1461 SupportedCurves: []CurveID{CurveP256},
1462 SupportedPoints: []uint8{pointFormatUncompressed},
1463 SignatureSchemes: []SignatureScheme{ECDSAWithP256AndSHA256},
1464 SupportedVersions: []uint16{VersionTLS12},
1465 config: &Config{
1466 CipherSuites: []uint16{TLS_RSA_WITH_AES_128_GCM_SHA256},
1467 },
1468 }, "cipher suite"},
1469 {ecdsaCert, &ClientHelloInfo{
1470 CipherSuites: []uint16{TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256},
1471 SupportedCurves: []CurveID{CurveP384},
1472 SupportedPoints: []uint8{pointFormatUncompressed},
1473 SignatureSchemes: []SignatureScheme{ECDSAWithP256AndSHA256},
1474 SupportedVersions: []uint16{VersionTLS12},
1475 }, "certificate curve"},
1476 {ecdsaCert, &ClientHelloInfo{
1477 CipherSuites: []uint16{TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256},
1478 SupportedCurves: []CurveID{CurveP256},
1479 SupportedPoints: []uint8{1},
1480 SignatureSchemes: []SignatureScheme{ECDSAWithP256AndSHA256},
1481 SupportedVersions: []uint16{VersionTLS12},
1482 }, "doesn't support ECDHE"},
1483 {ecdsaCert, &ClientHelloInfo{
1484 CipherSuites: []uint16{TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256},
1485 SupportedCurves: []CurveID{CurveP256},
1486 SupportedPoints: []uint8{pointFormatUncompressed},
1487 SignatureSchemes: []SignatureScheme{PSSWithSHA256},
1488 SupportedVersions: []uint16{VersionTLS12},
1489 }, "signature algorithms"},
1490
1491 {ed25519Cert, &ClientHelloInfo{
1492 CipherSuites: []uint16{TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256},
1493 SupportedCurves: []CurveID{CurveP256},
1494 SupportedPoints: []uint8{pointFormatUncompressed},
1495 SignatureSchemes: []SignatureScheme{Ed25519},
1496 SupportedVersions: []uint16{VersionTLS12},
1497 }, ""},
1498 {ed25519Cert, &ClientHelloInfo{
1499 CipherSuites: []uint16{TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256},
1500 SupportedCurves: []CurveID{CurveP256},
1501 SupportedPoints: []uint8{pointFormatUncompressed},
1502 SignatureSchemes: []SignatureScheme{Ed25519},
1503 SupportedVersions: []uint16{VersionTLS10},
1504 config: &Config{MinVersion: VersionTLS10},
1505 }, "doesn't support Ed25519"},
1506 {ed25519Cert, &ClientHelloInfo{
1507 CipherSuites: []uint16{TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256},
1508 SupportedCurves: []CurveID{},
1509 SupportedPoints: []uint8{pointFormatUncompressed},
1510 SignatureSchemes: []SignatureScheme{Ed25519},
1511 SupportedVersions: []uint16{VersionTLS12},
1512 }, "doesn't support ECDHE"},
1513
1514 {rsaCert, &ClientHelloInfo{
1515 CipherSuites: []uint16{TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA},
1516 SupportedCurves: []CurveID{CurveP256},
1517 SupportedPoints: []uint8{pointFormatUncompressed},
1518 SupportedVersions: []uint16{VersionTLS10},
1519 config: &Config{MinVersion: VersionTLS10},
1520 }, ""},
1521 {rsaCert, &ClientHelloInfo{
1522 CipherSuites: []uint16{TLS_RSA_WITH_AES_128_GCM_SHA256},
1523 SupportedVersions: []uint16{VersionTLS12},
1524 config: &Config{
1525 CipherSuites: []uint16{TLS_RSA_WITH_AES_128_GCM_SHA256},
1526 },
1527 }, ""},
1528 }
1529 for i, tt := range tests {
1530 err := tt.chi.SupportsCertificate(tt.c)
1531 switch {
1532 case tt.wantErr == "" && err != nil:
1533 t.Errorf("%d: unexpected error: %v", i, err)
1534 case tt.wantErr != "" && err == nil:
1535 t.Errorf("%d: unexpected success", i)
1536 case tt.wantErr != "" && !strings.Contains(err.Error(), tt.wantErr):
1537 t.Errorf("%d: got error %q, expected %q", i, err, tt.wantErr)
1538 }
1539 }
1540 }
1541
1542 func TestCipherSuites(t *testing.T) {
1543 var lastID uint16
1544 for _, c := range CipherSuites() {
1545 if lastID > c.ID {
1546 t.Errorf("CipherSuites are not ordered by ID: got %#04x after %#04x", c.ID, lastID)
1547 } else {
1548 lastID = c.ID
1549 }
1550
1551 if c.Insecure {
1552 t.Errorf("%#04x: Insecure CipherSuite returned by CipherSuites()", c.ID)
1553 }
1554 }
1555 lastID = 0
1556 for _, c := range InsecureCipherSuites() {
1557 if lastID > c.ID {
1558 t.Errorf("InsecureCipherSuites are not ordered by ID: got %#04x after %#04x", c.ID, lastID)
1559 } else {
1560 lastID = c.ID
1561 }
1562
1563 if !c.Insecure {
1564 t.Errorf("%#04x: not Insecure CipherSuite returned by InsecureCipherSuites()", c.ID)
1565 }
1566 }
1567
1568 CipherSuiteByID := func(id uint16) *CipherSuite {
1569 for _, c := range CipherSuites() {
1570 if c.ID == id {
1571 return c
1572 }
1573 }
1574 for _, c := range InsecureCipherSuites() {
1575 if c.ID == id {
1576 return c
1577 }
1578 }
1579 return nil
1580 }
1581
1582 for _, c := range cipherSuites {
1583 cc := CipherSuiteByID(c.id)
1584 if cc == nil {
1585 t.Errorf("%#04x: no CipherSuite entry", c.id)
1586 continue
1587 }
1588
1589 if tls12Only := c.flags&suiteTLS12 != 0; tls12Only && len(cc.SupportedVersions) != 1 {
1590 t.Errorf("%#04x: suite is TLS 1.2 only, but SupportedVersions is %v", c.id, cc.SupportedVersions)
1591 } else if !tls12Only && len(cc.SupportedVersions) != 3 {
1592 t.Errorf("%#04x: suite TLS 1.0-1.2, but SupportedVersions is %v", c.id, cc.SupportedVersions)
1593 }
1594
1595 if cc.Insecure {
1596 if slices.Contains(defaultCipherSuites(false), c.id) {
1597 t.Errorf("%#04x: insecure suite in default list", c.id)
1598 }
1599 } else {
1600 if !slices.Contains(defaultCipherSuites(false), c.id) {
1601 t.Errorf("%#04x: secure suite not in default list", c.id)
1602 }
1603 }
1604
1605 if got := CipherSuiteName(c.id); got != cc.Name {
1606 t.Errorf("%#04x: unexpected CipherSuiteName: got %q, expected %q", c.id, got, cc.Name)
1607 }
1608 }
1609 for _, c := range cipherSuitesTLS13 {
1610 cc := CipherSuiteByID(c.id)
1611 if cc == nil {
1612 t.Errorf("%#04x: no CipherSuite entry", c.id)
1613 continue
1614 }
1615
1616 if cc.Insecure {
1617 t.Errorf("%#04x: Insecure %v, expected false", c.id, cc.Insecure)
1618 }
1619 if len(cc.SupportedVersions) != 1 || cc.SupportedVersions[0] != VersionTLS13 {
1620 t.Errorf("%#04x: suite is TLS 1.3 only, but SupportedVersions is %v", c.id, cc.SupportedVersions)
1621 }
1622
1623 if got := CipherSuiteName(c.id); got != cc.Name {
1624 t.Errorf("%#04x: unexpected CipherSuiteName: got %q, expected %q", c.id, got, cc.Name)
1625 }
1626 }
1627
1628 if got := CipherSuiteName(0xabc); got != "0x0ABC" {
1629 t.Errorf("unexpected fallback CipherSuiteName: got %q, expected 0x0ABC", got)
1630 }
1631
1632 if len(cipherSuitesPreferenceOrder) != len(cipherSuites) {
1633 t.Errorf("cipherSuitesPreferenceOrder is not the same size as cipherSuites")
1634 }
1635 if len(cipherSuitesPreferenceOrderNoAES) != len(cipherSuitesPreferenceOrder) {
1636 t.Errorf("cipherSuitesPreferenceOrderNoAES is not the same size as cipherSuitesPreferenceOrder")
1637 }
1638
1639
1640 for _, badSuites := range []map[uint16]bool{disabledCipherSuites, rsaKexCiphers} {
1641 for id := range badSuites {
1642 c := CipherSuiteByID(id)
1643 if c == nil {
1644 t.Errorf("%#04x: no CipherSuite entry", id)
1645 continue
1646 }
1647 if !c.Insecure {
1648 t.Errorf("%#04x: disabled by default but not marked insecure", id)
1649 }
1650 }
1651 }
1652
1653 for i, prefOrder := range [][]uint16{cipherSuitesPreferenceOrder, cipherSuitesPreferenceOrderNoAES} {
1654
1655
1656 var sawInsecure, sawBad bool
1657 for _, id := range prefOrder {
1658 c := CipherSuiteByID(id)
1659 if c == nil {
1660 t.Errorf("%#04x: no CipherSuite entry", id)
1661 continue
1662 }
1663
1664 if c.Insecure {
1665 sawInsecure = true
1666 } else if sawInsecure {
1667 t.Errorf("%#04x: secure suite after insecure one(s)", id)
1668 }
1669
1670 if http2isBadCipher(id) {
1671 sawBad = true
1672 } else if sawBad {
1673 t.Errorf("%#04x: non-bad suite after bad HTTP/2 one(s)", id)
1674 }
1675 }
1676
1677
1678 isBetter := func(a, b uint16) int {
1679 aSuite, bSuite := cipherSuiteByID(a), cipherSuiteByID(b)
1680 aName, bName := CipherSuiteName(a), CipherSuiteName(b)
1681
1682 if !strings.Contains(aName, "RC4") && strings.Contains(bName, "RC4") {
1683 return -1
1684 } else if strings.Contains(aName, "RC4") && !strings.Contains(bName, "RC4") {
1685 return +1
1686 }
1687
1688 if !strings.Contains(aName, "CBC_SHA256") && strings.Contains(bName, "CBC_SHA256") {
1689 return -1
1690 } else if strings.Contains(aName, "CBC_SHA256") && !strings.Contains(bName, "CBC_SHA256") {
1691 return +1
1692 }
1693
1694 if !strings.Contains(aName, "3DES") && strings.Contains(bName, "3DES") {
1695 return -1
1696 } else if strings.Contains(aName, "3DES") && !strings.Contains(bName, "3DES") {
1697 return +1
1698 }
1699
1700 if aSuite.flags&suiteECDHE != 0 && bSuite.flags&suiteECDHE == 0 {
1701 return -1
1702 } else if aSuite.flags&suiteECDHE == 0 && bSuite.flags&suiteECDHE != 0 {
1703 return +1
1704 }
1705
1706 if aSuite.aead != nil && bSuite.aead == nil {
1707 return -1
1708 } else if aSuite.aead == nil && bSuite.aead != nil {
1709 return +1
1710 }
1711
1712 if strings.Contains(aName, "AES") && strings.Contains(bName, "CHACHA20") {
1713
1714 if i == 0 {
1715 return -1
1716 } else {
1717 return +1
1718 }
1719 } else if strings.Contains(aName, "CHACHA20") && strings.Contains(bName, "AES") {
1720
1721 if i != 0 {
1722 return -1
1723 } else {
1724 return +1
1725 }
1726 }
1727
1728 if strings.Contains(aName, "AES_128") && strings.Contains(bName, "AES_256") {
1729 return -1
1730 } else if strings.Contains(aName, "AES_256") && strings.Contains(bName, "AES_128") {
1731 return +1
1732 }
1733
1734 if aSuite.flags&suiteECSign != 0 && bSuite.flags&suiteECSign == 0 {
1735 return -1
1736 } else if aSuite.flags&suiteECSign == 0 && bSuite.flags&suiteECSign != 0 {
1737 return +1
1738 }
1739 t.Fatalf("two ciphersuites are equal by all criteria: %v and %v", aName, bName)
1740 panic("unreachable")
1741 }
1742 if !slices.IsSortedFunc(prefOrder, isBetter) {
1743 t.Error("preference order is not sorted according to the rules")
1744 }
1745 }
1746 }
1747
1748 func TestVersionName(t *testing.T) {
1749 if got, exp := VersionName(VersionTLS13), "TLS 1.3"; got != exp {
1750 t.Errorf("unexpected VersionName: got %q, expected %q", got, exp)
1751 }
1752 if got, exp := VersionName(0x12a), "0x012A"; got != exp {
1753 t.Errorf("unexpected fallback VersionName: got %q, expected %q", got, exp)
1754 }
1755 }
1756
1757
1758
1759 func http2isBadCipher(cipher uint16) bool {
1760 switch cipher {
1761 case TLS_RSA_WITH_RC4_128_SHA,
1762 TLS_RSA_WITH_3DES_EDE_CBC_SHA,
1763 TLS_RSA_WITH_AES_128_CBC_SHA,
1764 TLS_RSA_WITH_AES_256_CBC_SHA,
1765 TLS_RSA_WITH_AES_128_CBC_SHA256,
1766 TLS_RSA_WITH_AES_128_GCM_SHA256,
1767 TLS_RSA_WITH_AES_256_GCM_SHA384,
1768 TLS_ECDHE_ECDSA_WITH_RC4_128_SHA,
1769 TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA,
1770 TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA,
1771 TLS_ECDHE_RSA_WITH_RC4_128_SHA,
1772 TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA,
1773 TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,
1774 TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA,
1775 TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256,
1776 TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256:
1777 return true
1778 default:
1779 return false
1780 }
1781 }
1782
1783 type brokenSigner struct{ crypto.Signer }
1784
1785 func (s brokenSigner) Sign(rand io.Reader, digest []byte, opts crypto.SignerOpts) (signature []byte, err error) {
1786
1787 return s.Signer.Sign(rand, digest, opts.HashFunc())
1788 }
1789
1790
1791
1792 func TestPKCS1OnlyCert(t *testing.T) {
1793 clientConfig := testConfig.Clone()
1794 clientConfig.Certificates = []Certificate{{
1795 Certificate: [][]byte{testRSACertificate},
1796 PrivateKey: brokenSigner{testRSAPrivateKey},
1797 }}
1798 serverConfig := testConfig.Clone()
1799 serverConfig.MaxVersion = VersionTLS12
1800 serverConfig.ClientAuth = RequireAnyClientCert
1801
1802
1803 if _, _, err := testHandshake(t, clientConfig, serverConfig); err == nil {
1804 t.Fatal("expected broken certificate to cause connection to fail")
1805 }
1806
1807 clientConfig.Certificates[0].SupportedSignatureAlgorithms =
1808 []SignatureScheme{PKCS1WithSHA1, PKCS1WithSHA256}
1809
1810
1811
1812 if _, _, err := testHandshake(t, clientConfig, serverConfig); err != nil {
1813 t.Error(err)
1814 }
1815 }
1816
1817 func TestVerifyCertificates(t *testing.T) {
1818 skipFIPS(t)
1819
1820
1821 t.Run("TLSv12", func(t *testing.T) { testVerifyCertificates(t, VersionTLS12) })
1822 t.Run("TLSv13", func(t *testing.T) { testVerifyCertificates(t, VersionTLS13) })
1823 }
1824
1825 func testVerifyCertificates(t *testing.T, version uint16) {
1826 tests := []struct {
1827 name string
1828
1829 InsecureSkipVerify bool
1830 ClientAuth ClientAuthType
1831 ClientCertificates bool
1832 }{
1833 {
1834 name: "defaults",
1835 },
1836 {
1837 name: "InsecureSkipVerify",
1838 InsecureSkipVerify: true,
1839 },
1840 {
1841 name: "RequestClientCert with no certs",
1842 ClientAuth: RequestClientCert,
1843 },
1844 {
1845 name: "RequestClientCert with certs",
1846 ClientAuth: RequestClientCert,
1847 ClientCertificates: true,
1848 },
1849 {
1850 name: "RequireAnyClientCert",
1851 ClientAuth: RequireAnyClientCert,
1852 ClientCertificates: true,
1853 },
1854 {
1855 name: "VerifyClientCertIfGiven with no certs",
1856 ClientAuth: VerifyClientCertIfGiven,
1857 },
1858 {
1859 name: "VerifyClientCertIfGiven with certs",
1860 ClientAuth: VerifyClientCertIfGiven,
1861 ClientCertificates: true,
1862 },
1863 {
1864 name: "RequireAndVerifyClientCert",
1865 ClientAuth: RequireAndVerifyClientCert,
1866 ClientCertificates: true,
1867 },
1868 }
1869
1870 issuer, err := x509.ParseCertificate(testRSACertificateIssuer)
1871 if err != nil {
1872 t.Fatal(err)
1873 }
1874 rootCAs := x509.NewCertPool()
1875 rootCAs.AddCert(issuer)
1876
1877 for _, test := range tests {
1878 test := test
1879 t.Run(test.name, func(t *testing.T) {
1880 t.Parallel()
1881
1882 var serverVerifyConnection, clientVerifyConnection bool
1883 var serverVerifyPeerCertificates, clientVerifyPeerCertificates bool
1884
1885 clientConfig := testConfig.Clone()
1886 clientConfig.Time = testTime
1887 clientConfig.MaxVersion = version
1888 clientConfig.MinVersion = version
1889 clientConfig.RootCAs = rootCAs
1890 clientConfig.ServerName = "example.golang"
1891 clientConfig.ClientSessionCache = NewLRUClientSessionCache(1)
1892 serverConfig := clientConfig.Clone()
1893 serverConfig.ClientCAs = rootCAs
1894
1895 clientConfig.VerifyConnection = func(cs ConnectionState) error {
1896 clientVerifyConnection = true
1897 return nil
1898 }
1899 clientConfig.VerifyPeerCertificate = func(rawCerts [][]byte, verifiedChains [][]*x509.Certificate) error {
1900 clientVerifyPeerCertificates = true
1901 return nil
1902 }
1903 serverConfig.VerifyConnection = func(cs ConnectionState) error {
1904 serverVerifyConnection = true
1905 return nil
1906 }
1907 serverConfig.VerifyPeerCertificate = func(rawCerts [][]byte, verifiedChains [][]*x509.Certificate) error {
1908 serverVerifyPeerCertificates = true
1909 return nil
1910 }
1911
1912 clientConfig.InsecureSkipVerify = test.InsecureSkipVerify
1913 serverConfig.ClientAuth = test.ClientAuth
1914 if !test.ClientCertificates {
1915 clientConfig.Certificates = nil
1916 }
1917
1918 if _, _, err := testHandshake(t, clientConfig, serverConfig); err != nil {
1919 t.Fatal(err)
1920 }
1921
1922 want := serverConfig.ClientAuth != NoClientCert
1923 if serverVerifyPeerCertificates != want {
1924 t.Errorf("VerifyPeerCertificates on the server: got %v, want %v",
1925 serverVerifyPeerCertificates, want)
1926 }
1927 if !clientVerifyPeerCertificates {
1928 t.Errorf("VerifyPeerCertificates not called on the client")
1929 }
1930 if !serverVerifyConnection {
1931 t.Error("VerifyConnection did not get called on the server")
1932 }
1933 if !clientVerifyConnection {
1934 t.Error("VerifyConnection did not get called on the client")
1935 }
1936
1937 serverVerifyPeerCertificates, clientVerifyPeerCertificates = false, false
1938 serverVerifyConnection, clientVerifyConnection = false, false
1939 cs, _, err := testHandshake(t, clientConfig, serverConfig)
1940 if err != nil {
1941 t.Fatal(err)
1942 }
1943 if !cs.DidResume {
1944 t.Error("expected resumption")
1945 }
1946
1947 if serverVerifyPeerCertificates {
1948 t.Error("VerifyPeerCertificates got called on the server on resumption")
1949 }
1950 if clientVerifyPeerCertificates {
1951 t.Error("VerifyPeerCertificates got called on the client on resumption")
1952 }
1953 if !serverVerifyConnection {
1954 t.Error("VerifyConnection did not get called on the server on resumption")
1955 }
1956 if !clientVerifyConnection {
1957 t.Error("VerifyConnection did not get called on the client on resumption")
1958 }
1959 })
1960 }
1961 }
1962
1963 func TestHandshakeMLKEM(t *testing.T) {
1964 skipFIPS(t)
1965 var tests = []struct {
1966 name string
1967 clientConfig func(*Config)
1968 serverConfig func(*Config)
1969 preparation func(*testing.T)
1970 expectClientSupport bool
1971 expectMLKEM bool
1972 expectHRR bool
1973 }{
1974 {
1975 name: "Default",
1976 expectClientSupport: true,
1977 expectMLKEM: true,
1978 expectHRR: false,
1979 },
1980 {
1981 name: "ClientCurvePreferences",
1982 clientConfig: func(config *Config) {
1983 config.CurvePreferences = []CurveID{X25519}
1984 },
1985 expectClientSupport: false,
1986 },
1987 {
1988 name: "ServerCurvePreferencesX25519",
1989 serverConfig: func(config *Config) {
1990 config.CurvePreferences = []CurveID{X25519}
1991 },
1992 expectClientSupport: true,
1993 expectMLKEM: false,
1994 expectHRR: false,
1995 },
1996 {
1997 name: "ServerCurvePreferencesHRR",
1998 serverConfig: func(config *Config) {
1999 config.CurvePreferences = []CurveID{CurveP256}
2000 },
2001 expectClientSupport: true,
2002 expectMLKEM: false,
2003 expectHRR: true,
2004 },
2005 {
2006 name: "ClientMLKEMOnly",
2007 clientConfig: func(config *Config) {
2008 config.CurvePreferences = []CurveID{X25519MLKEM768}
2009 },
2010 expectClientSupport: true,
2011 expectMLKEM: true,
2012 },
2013 {
2014 name: "ClientSortedCurvePreferences",
2015 clientConfig: func(config *Config) {
2016 config.CurvePreferences = []CurveID{CurveP256, X25519MLKEM768}
2017 },
2018 expectClientSupport: true,
2019 expectMLKEM: true,
2020 },
2021 {
2022 name: "ClientTLSv12",
2023 clientConfig: func(config *Config) {
2024 config.MaxVersion = VersionTLS12
2025 },
2026 expectClientSupport: false,
2027 },
2028 {
2029 name: "ServerTLSv12",
2030 serverConfig: func(config *Config) {
2031 config.MaxVersion = VersionTLS12
2032 },
2033 expectClientSupport: true,
2034 expectMLKEM: false,
2035 },
2036 {
2037 name: "GODEBUG",
2038 preparation: func(t *testing.T) {
2039 t.Setenv("GODEBUG", "tlsmlkem=0")
2040 },
2041 expectClientSupport: false,
2042 },
2043 }
2044
2045 baseConfig := testConfig.Clone()
2046 baseConfig.CurvePreferences = nil
2047 for _, test := range tests {
2048 t.Run(test.name, func(t *testing.T) {
2049 if test.preparation != nil {
2050 test.preparation(t)
2051 } else {
2052 t.Parallel()
2053 }
2054 serverConfig := baseConfig.Clone()
2055 if test.serverConfig != nil {
2056 test.serverConfig(serverConfig)
2057 }
2058 serverConfig.GetConfigForClient = func(hello *ClientHelloInfo) (*Config, error) {
2059 if !test.expectClientSupport && slices.Contains(hello.SupportedCurves, X25519MLKEM768) {
2060 return nil, errors.New("client supports X25519MLKEM768")
2061 } else if test.expectClientSupport && !slices.Contains(hello.SupportedCurves, X25519MLKEM768) {
2062 return nil, errors.New("client does not support X25519MLKEM768")
2063 }
2064 return nil, nil
2065 }
2066 clientConfig := baseConfig.Clone()
2067 if test.clientConfig != nil {
2068 test.clientConfig(clientConfig)
2069 }
2070 ss, cs, err := testHandshake(t, clientConfig, serverConfig)
2071 if err != nil {
2072 t.Fatal(err)
2073 }
2074 if test.expectMLKEM {
2075 if ss.CurveID != X25519MLKEM768 {
2076 t.Errorf("got CurveID %v (server), expected %v", ss.CurveID, X25519MLKEM768)
2077 }
2078 if cs.CurveID != X25519MLKEM768 {
2079 t.Errorf("got CurveID %v (client), expected %v", cs.CurveID, X25519MLKEM768)
2080 }
2081 } else {
2082 if ss.CurveID == X25519MLKEM768 {
2083 t.Errorf("got CurveID %v (server), expected not X25519MLKEM768", ss.CurveID)
2084 }
2085 if cs.CurveID == X25519MLKEM768 {
2086 t.Errorf("got CurveID %v (client), expected not X25519MLKEM768", cs.CurveID)
2087 }
2088 }
2089 if test.expectHRR {
2090 if !ss.testingOnlyDidHRR {
2091 t.Error("server did not use HRR")
2092 }
2093 if !cs.testingOnlyDidHRR {
2094 t.Error("client did not use HRR")
2095 }
2096 } else {
2097 if ss.testingOnlyDidHRR {
2098 t.Error("server used HRR")
2099 }
2100 if cs.testingOnlyDidHRR {
2101 t.Error("client used HRR")
2102 }
2103 }
2104 })
2105 }
2106 }
2107
2108 func TestX509KeyPairPopulateCertificate(t *testing.T) {
2109 key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
2110 if err != nil {
2111 t.Fatal(err)
2112 }
2113 keyDER, err := x509.MarshalPKCS8PrivateKey(key)
2114 if err != nil {
2115 t.Fatal(err)
2116 }
2117 keyPEM := pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: keyDER})
2118 tmpl := &x509.Certificate{
2119 SerialNumber: big.NewInt(1),
2120 Subject: pkix.Name{CommonName: "test"},
2121 }
2122 certDER, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, key.Public(), key)
2123 if err != nil {
2124 t.Fatal(err)
2125 }
2126 certPEM := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: certDER})
2127
2128 t.Run("x509keypairleaf=0", func(t *testing.T) {
2129 t.Setenv("GODEBUG", "x509keypairleaf=0")
2130 cert, err := X509KeyPair(certPEM, keyPEM)
2131 if err != nil {
2132 t.Fatal(err)
2133 }
2134 if cert.Leaf != nil {
2135 t.Fatal("Leaf should not be populated")
2136 }
2137 })
2138 t.Run("x509keypairleaf=1", func(t *testing.T) {
2139 t.Setenv("GODEBUG", "x509keypairleaf=1")
2140 cert, err := X509KeyPair(certPEM, keyPEM)
2141 if err != nil {
2142 t.Fatal(err)
2143 }
2144 if cert.Leaf == nil {
2145 t.Fatal("Leaf should be populated")
2146 }
2147 })
2148 t.Run("GODEBUG unset", func(t *testing.T) {
2149 cert, err := X509KeyPair(certPEM, keyPEM)
2150 if err != nil {
2151 t.Fatal(err)
2152 }
2153 if cert.Leaf == nil {
2154 t.Fatal("Leaf should be populated")
2155 }
2156 })
2157 }
2158
2159 func TestEarlyLargeCertMsg(t *testing.T) {
2160 client, server := localPipe(t)
2161
2162 go func() {
2163 if _, err := client.Write([]byte{byte(recordTypeHandshake), 3, 4, 0, 4, typeCertificate, 1, 255, 255}); err != nil {
2164 t.Log(err)
2165 }
2166 }()
2167
2168 expectedErr := "tls: handshake message of length 131071 bytes exceeds maximum of 65536 bytes"
2169 servConn := Server(server, testConfig)
2170 err := servConn.Handshake()
2171 if err == nil {
2172 t.Fatal("unexpected success")
2173 }
2174 if err.Error() != expectedErr {
2175 t.Fatalf("unexpected error: got %q, want %q", err, expectedErr)
2176 }
2177 }
2178
2179 func TestLargeCertMsg(t *testing.T) {
2180 k, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
2181 if err != nil {
2182 t.Fatal(err)
2183 }
2184 tmpl := &x509.Certificate{
2185 SerialNumber: big.NewInt(1),
2186 Subject: pkix.Name{CommonName: "test"},
2187 ExtraExtensions: []pkix.Extension{
2188 {
2189 Id: asn1.ObjectIdentifier{1, 2, 3},
2190
2191
2192 Value: make([]byte, 65536),
2193 },
2194 },
2195 }
2196 cert, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, k.Public(), k)
2197 if err != nil {
2198 t.Fatal(err)
2199 }
2200
2201 clientConfig, serverConfig := testConfig.Clone(), testConfig.Clone()
2202 clientConfig.InsecureSkipVerify = true
2203 serverConfig.Certificates = []Certificate{
2204 {
2205 Certificate: [][]byte{cert},
2206 PrivateKey: k,
2207 },
2208 }
2209 if _, _, err := testHandshake(t, clientConfig, serverConfig); err != nil {
2210 t.Fatalf("unexpected failure: %s", err)
2211 }
2212 }
2213
2214 func TestECH(t *testing.T) {
2215 k, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
2216 if err != nil {
2217 t.Fatal(err)
2218 }
2219 tmpl := &x509.Certificate{
2220 SerialNumber: big.NewInt(1),
2221 DNSNames: []string{"public.example"},
2222 NotBefore: time.Now().Add(-time.Hour),
2223 NotAfter: time.Now().Add(time.Hour),
2224 }
2225 publicCertDER, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, k.Public(), k)
2226 if err != nil {
2227 t.Fatal(err)
2228 }
2229 publicCert, err := x509.ParseCertificate(publicCertDER)
2230 if err != nil {
2231 t.Fatal(err)
2232 }
2233 tmpl.DNSNames[0] = "secret.example"
2234 secretCertDER, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, k.Public(), k)
2235 if err != nil {
2236 t.Fatal(err)
2237 }
2238 secretCert, err := x509.ParseCertificate(secretCertDER)
2239 if err != nil {
2240 t.Fatal(err)
2241 }
2242
2243 marshalECHConfig := func(id uint8, pubKey []byte, publicName string, maxNameLen uint8) []byte {
2244 builder := cryptobyte.NewBuilder(nil)
2245 builder.AddUint16(extensionEncryptedClientHello)
2246 builder.AddUint16LengthPrefixed(func(builder *cryptobyte.Builder) {
2247 builder.AddUint8(id)
2248 builder.AddUint16(hpke.DHKEM_X25519_HKDF_SHA256)
2249 builder.AddUint16LengthPrefixed(func(builder *cryptobyte.Builder) {
2250 builder.AddBytes(pubKey)
2251 })
2252 builder.AddUint16LengthPrefixed(func(builder *cryptobyte.Builder) {
2253 for _, aeadID := range sortedSupportedAEADs {
2254 builder.AddUint16(hpke.KDF_HKDF_SHA256)
2255 builder.AddUint16(aeadID)
2256 }
2257 })
2258 builder.AddUint8(maxNameLen)
2259 builder.AddUint8LengthPrefixed(func(builder *cryptobyte.Builder) {
2260 builder.AddBytes([]byte(publicName))
2261 })
2262 builder.AddUint16(0)
2263 })
2264
2265 return builder.BytesOrPanic()
2266 }
2267
2268 echKey, err := ecdh.X25519().GenerateKey(rand.Reader)
2269 if err != nil {
2270 t.Fatal(err)
2271 }
2272
2273 echConfig := marshalECHConfig(123, echKey.PublicKey().Bytes(), "public.example", 32)
2274
2275 builder := cryptobyte.NewBuilder(nil)
2276 builder.AddUint16LengthPrefixed(func(builder *cryptobyte.Builder) {
2277 builder.AddBytes(echConfig)
2278 })
2279 echConfigList := builder.BytesOrPanic()
2280
2281 clientConfig, serverConfig := testConfig.Clone(), testConfig.Clone()
2282 clientConfig.InsecureSkipVerify = false
2283 clientConfig.Rand = rand.Reader
2284 clientConfig.Time = nil
2285 clientConfig.MinVersion = VersionTLS13
2286 clientConfig.ServerName = "secret.example"
2287 clientConfig.RootCAs = x509.NewCertPool()
2288 clientConfig.RootCAs.AddCert(secretCert)
2289 clientConfig.RootCAs.AddCert(publicCert)
2290 clientConfig.EncryptedClientHelloConfigList = echConfigList
2291 serverConfig.InsecureSkipVerify = false
2292 serverConfig.Rand = rand.Reader
2293 serverConfig.Time = nil
2294 serverConfig.MinVersion = VersionTLS13
2295 serverConfig.ServerName = "public.example"
2296 serverConfig.Certificates = []Certificate{
2297 {Certificate: [][]byte{publicCertDER}, PrivateKey: k},
2298 {Certificate: [][]byte{secretCertDER}, PrivateKey: k},
2299 }
2300 serverConfig.EncryptedClientHelloKeys = []EncryptedClientHelloKey{
2301 {Config: echConfig, PrivateKey: echKey.Bytes(), SendAsRetry: true},
2302 }
2303
2304 ss, cs, err := testHandshake(t, clientConfig, serverConfig)
2305 if err != nil {
2306 t.Fatalf("unexpected failure: %s", err)
2307 }
2308 if !ss.ECHAccepted {
2309 t.Fatal("server ConnectionState shows ECH not accepted")
2310 }
2311 if !cs.ECHAccepted {
2312 t.Fatal("client ConnectionState shows ECH not accepted")
2313 }
2314 if cs.ServerName != "secret.example" || ss.ServerName != "secret.example" {
2315 t.Fatalf("unexpected ConnectionState.ServerName, want %q, got server:%q, client: %q", "secret.example", ss.ServerName, cs.ServerName)
2316 }
2317 if len(cs.VerifiedChains) != 1 {
2318 t.Fatal("unexpect number of certificate chains")
2319 }
2320 if len(cs.VerifiedChains[0]) != 1 {
2321 t.Fatal("unexpect number of certificates")
2322 }
2323 if !cs.VerifiedChains[0][0].Equal(secretCert) {
2324 t.Fatal("unexpected certificate")
2325 }
2326 }
2327
View as plain text