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