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