Source file
src/crypto/tls/handshake_client_test.go
1
2
3
4
5 package tls
6
7 import (
8 "bytes"
9 "context"
10 "crypto/ecdsa"
11 "crypto/elliptic"
12 "crypto/rand"
13 "crypto/rsa"
14 "crypto/x509"
15 "crypto/x509/pkix"
16 "encoding/base64"
17 "encoding/hex"
18 "encoding/pem"
19 "errors"
20 "fmt"
21 "internal/byteorder"
22 "io"
23 "math/big"
24 "net"
25 "os"
26 "os/exec"
27 "path/filepath"
28 "reflect"
29 "runtime"
30 "strconv"
31 "strings"
32 "testing"
33 "time"
34 )
35
36
37
38
39
40
41 type opensslInputEvent int
42
43 const (
44
45
46 opensslRenegotiate opensslInputEvent = iota
47
48
49
50 opensslSendSentinel
51
52
53
54 opensslKeyUpdate
55 )
56
57 const opensslSentinel = "SENTINEL\n"
58
59 type opensslInput chan opensslInputEvent
60
61 func (i opensslInput) Read(buf []byte) (n int, err error) {
62 for event := range i {
63 switch event {
64 case opensslRenegotiate:
65 return copy(buf, []byte("R\n")), nil
66 case opensslKeyUpdate:
67 return copy(buf, []byte("K\n")), nil
68 case opensslSendSentinel:
69 return copy(buf, []byte(opensslSentinel)), nil
70 default:
71 panic("unknown event")
72 }
73 }
74
75 return 0, io.EOF
76 }
77
78
79
80
81 type opensslOutputSink struct {
82 handshakeComplete chan struct{}
83 readKeyUpdate chan struct{}
84 all []byte
85 line []byte
86 }
87
88 func newOpensslOutputSink() *opensslOutputSink {
89 return &opensslOutputSink{make(chan struct{}), make(chan struct{}), nil, nil}
90 }
91
92
93
94 const opensslEndOfHandshake = "SSL_accept:SSLv3/TLS write finished"
95
96
97
98 const opensslReadKeyUpdate = "SSL_accept:TLSv1.3 read client key update"
99
100 func (o *opensslOutputSink) Write(data []byte) (n int, err error) {
101 o.line = append(o.line, data...)
102 o.all = append(o.all, data...)
103
104 for {
105 line, next, ok := bytes.Cut(o.line, []byte("\n"))
106 if !ok {
107 break
108 }
109
110 if bytes.Equal([]byte(opensslEndOfHandshake), line) {
111 o.handshakeComplete <- struct{}{}
112 }
113 if bytes.Equal([]byte(opensslReadKeyUpdate), line) {
114 o.readKeyUpdate <- struct{}{}
115 }
116 o.line = next
117 }
118
119 return len(data), nil
120 }
121
122 func (o *opensslOutputSink) String() string {
123 return string(o.all)
124 }
125
126
127
128 type clientTest struct {
129
130
131 name string
132
133
134 args []string
135
136 config *Config
137
138
139 cert []byte
140
141
142 key any
143
144
145
146 extensions [][]byte
147
148
149
150 validate func(ConnectionState) error
151
152
153 numRenegotiations int
154
155
156 renegotiationExpectedToFail int
157
158
159
160 checkRenegotiationError func(renegotiationNum int, err error) error
161
162 sendKeyUpdate bool
163 }
164
165 var serverCommand = []string{"openssl", "s_server", "-no_ticket", "-num_tickets", "0"}
166
167
168
169
170
171 func (test *clientTest) connFromCommand() (conn *recordingConn, child *exec.Cmd, stdin opensslInput, stdout *opensslOutputSink, err error) {
172 cert := testRSACertificate
173 if len(test.cert) > 0 {
174 cert = test.cert
175 }
176 certPath := tempFile(string(cert))
177 defer os.Remove(certPath)
178
179 var key any = testRSAPrivateKey
180 if test.key != nil {
181 key = test.key
182 }
183 derBytes, err := x509.MarshalPKCS8PrivateKey(key)
184 if err != nil {
185 panic(err)
186 }
187
188 var pemOut bytes.Buffer
189 pem.Encode(&pemOut, &pem.Block{Type: "PRIVATE KEY", Bytes: derBytes})
190
191 keyPath := tempFile(pemOut.String())
192 defer os.Remove(keyPath)
193
194 var command []string
195 command = append(command, serverCommand...)
196 command = append(command, test.args...)
197 command = append(command, "-cert", certPath, "-certform", "DER", "-key", keyPath)
198
199
200
201
202
203 const serverPort = 24323
204 command = append(command, "-accept", strconv.Itoa(serverPort))
205
206 if len(test.extensions) > 0 {
207 var serverInfo bytes.Buffer
208 for _, ext := range test.extensions {
209 pem.Encode(&serverInfo, &pem.Block{
210 Type: fmt.Sprintf("SERVERINFO FOR EXTENSION %d", byteorder.BeUint16(ext)),
211 Bytes: ext,
212 })
213 }
214 serverInfoPath := tempFile(serverInfo.String())
215 defer os.Remove(serverInfoPath)
216 command = append(command, "-serverinfo", serverInfoPath)
217 }
218
219 if test.numRenegotiations > 0 || test.sendKeyUpdate {
220 found := false
221 for _, flag := range command[1:] {
222 if flag == "-state" {
223 found = true
224 break
225 }
226 }
227
228 if !found {
229 panic("-state flag missing to OpenSSL, you need this if testing renegotiation or KeyUpdate")
230 }
231 }
232
233 cmd := exec.Command(command[0], command[1:]...)
234 stdin = opensslInput(make(chan opensslInputEvent))
235 cmd.Stdin = stdin
236 out := newOpensslOutputSink()
237 cmd.Stdout = out
238 cmd.Stderr = out
239 if err := cmd.Start(); err != nil {
240 return nil, nil, nil, nil, err
241 }
242
243
244
245
246
247 var tcpConn net.Conn
248 for i := uint(0); i < 5; i++ {
249 tcpConn, err = net.DialTCP("tcp", nil, &net.TCPAddr{
250 IP: net.IPv4(127, 0, 0, 1),
251 Port: serverPort,
252 })
253 if err == nil {
254 break
255 }
256 time.Sleep((1 << i) * 5 * time.Millisecond)
257 }
258 if err != nil {
259 close(stdin)
260 cmd.Process.Kill()
261 err = fmt.Errorf("error connecting to the OpenSSL server: %v (%v)\n\n%s", err, cmd.Wait(), out)
262 return nil, nil, nil, nil, err
263 }
264
265 record := &recordingConn{
266 Conn: tcpConn,
267 }
268
269 return record, cmd, stdin, out, nil
270 }
271
272 func (test *clientTest) dataPath() string {
273 return filepath.Join("testdata", "Client-"+test.name)
274 }
275
276 func (test *clientTest) loadData() (flows [][]byte, err error) {
277 in, err := os.Open(test.dataPath())
278 if err != nil {
279 return nil, err
280 }
281 defer in.Close()
282 return parseTestData(in)
283 }
284
285 func (test *clientTest) run(t *testing.T, write bool) {
286 var clientConn net.Conn
287 var recordingConn *recordingConn
288 var childProcess *exec.Cmd
289 var stdin opensslInput
290 var stdout *opensslOutputSink
291
292 if write {
293 var err error
294 recordingConn, childProcess, stdin, stdout, err = test.connFromCommand()
295 if err != nil {
296 t.Fatalf("Failed to start subcommand: %s", err)
297 }
298 clientConn = recordingConn
299 defer func() {
300 if t.Failed() {
301 t.Logf("OpenSSL output:\n\n%s", stdout.all)
302 }
303 }()
304 } else {
305 flows, err := test.loadData()
306 if err != nil {
307 t.Fatalf("failed to load data from %s: %v", test.dataPath(), err)
308 }
309 clientConn = &replayingConn{t: t, flows: flows, reading: false}
310 }
311
312 config := test.config
313 if config == nil {
314 config = testConfig
315 }
316 client := Client(clientConn, config)
317 defer client.Close()
318
319 if _, err := client.Write([]byte("hello\n")); err != nil {
320 t.Errorf("Client.Write failed: %s", err)
321 return
322 }
323
324 for i := 1; i <= test.numRenegotiations; i++ {
325
326
327 if i == 1 && write {
328 <-stdout.handshakeComplete
329 }
330
331
332
333
334
335
336
337
338
339 if write {
340 stdin <- opensslRenegotiate
341 }
342
343 signalChan := make(chan struct{})
344
345 go func() {
346 defer close(signalChan)
347
348 buf := make([]byte, 256)
349 n, err := client.Read(buf)
350
351 if test.checkRenegotiationError != nil {
352 newErr := test.checkRenegotiationError(i, err)
353 if err != nil && newErr == nil {
354 return
355 }
356 err = newErr
357 }
358
359 if err != nil {
360 t.Errorf("Client.Read failed after renegotiation #%d: %s", i, err)
361 return
362 }
363
364 buf = buf[:n]
365 if !bytes.Equal([]byte(opensslSentinel), buf) {
366 t.Errorf("Client.Read returned %q, but wanted %q", string(buf), opensslSentinel)
367 }
368
369 if expected := i + 1; client.handshakes != expected {
370 t.Errorf("client should have recorded %d handshakes, but believes that %d have occurred", expected, client.handshakes)
371 }
372 }()
373
374 if write && test.renegotiationExpectedToFail != i {
375 <-stdout.handshakeComplete
376 stdin <- opensslSendSentinel
377 }
378 <-signalChan
379 }
380
381 if test.sendKeyUpdate {
382 if write {
383 <-stdout.handshakeComplete
384 stdin <- opensslKeyUpdate
385 }
386
387 doneRead := make(chan struct{})
388
389 go func() {
390 defer close(doneRead)
391
392 buf := make([]byte, 256)
393 n, err := client.Read(buf)
394
395 if err != nil {
396 t.Errorf("Client.Read failed after KeyUpdate: %s", err)
397 return
398 }
399
400 buf = buf[:n]
401 if !bytes.Equal([]byte(opensslSentinel), buf) {
402 t.Errorf("Client.Read returned %q, but wanted %q", string(buf), opensslSentinel)
403 }
404 }()
405
406 if write {
407
408
409
410 <-stdout.readKeyUpdate
411 stdin <- opensslSendSentinel
412 }
413 <-doneRead
414
415 if _, err := client.Write([]byte("hello again\n")); err != nil {
416 t.Errorf("Client.Write failed: %s", err)
417 return
418 }
419 }
420
421 if test.validate != nil {
422 if err := test.validate(client.ConnectionState()); err != nil {
423 t.Errorf("validate callback returned error: %s", err)
424 }
425 }
426
427
428
429 if write && test.renegotiationExpectedToFail == 0 {
430 if err := peekError(client); err != nil {
431 t.Errorf("final Read returned an error: %s", err)
432 }
433 }
434
435 if write {
436 clientConn.Close()
437 path := test.dataPath()
438 out, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644)
439 if err != nil {
440 t.Fatalf("Failed to create output file: %s", err)
441 }
442 defer out.Close()
443 recordingConn.Close()
444 close(stdin)
445 childProcess.Process.Kill()
446 childProcess.Wait()
447 if len(recordingConn.flows) < 3 {
448 t.Fatalf("Client connection didn't work")
449 }
450 recordingConn.WriteTo(out)
451 t.Logf("Wrote %s\n", path)
452 }
453 }
454
455
456
457 func peekError(conn net.Conn) error {
458 conn.SetReadDeadline(time.Now().Add(100 * time.Millisecond))
459 if n, err := conn.Read(make([]byte, 1)); n != 0 {
460 return errors.New("unexpectedly read data")
461 } else if err != nil {
462 if netErr, ok := err.(net.Error); !ok || !netErr.Timeout() {
463 return err
464 }
465 }
466 return nil
467 }
468
469 func runClientTestForVersion(t *testing.T, template *clientTest, version, option string) {
470
471 test := *template
472 if template.config != nil {
473 test.config = template.config.Clone()
474 }
475 test.name = version + "-" + test.name
476 test.args = append([]string{option}, test.args...)
477
478 runTestAndUpdateIfNeeded(t, version, test.run, false)
479 }
480
481 func runClientTestTLS10(t *testing.T, template *clientTest) {
482 runClientTestForVersion(t, template, "TLSv10", "-tls1")
483 }
484
485 func runClientTestTLS11(t *testing.T, template *clientTest) {
486 runClientTestForVersion(t, template, "TLSv11", "-tls1_1")
487 }
488
489 func runClientTestTLS12(t *testing.T, template *clientTest) {
490 runClientTestForVersion(t, template, "TLSv12", "-tls1_2")
491 }
492
493 func runClientTestTLS13(t *testing.T, template *clientTest) {
494 runClientTestForVersion(t, template, "TLSv13", "-tls1_3")
495 }
496
497 func TestHandshakeClientRSARC4(t *testing.T) {
498 test := &clientTest{
499 name: "RSA-RC4",
500 args: []string{"-cipher", "RC4-SHA"},
501 }
502 runClientTestTLS10(t, test)
503 runClientTestTLS11(t, test)
504 runClientTestTLS12(t, test)
505 }
506
507 func TestHandshakeClientRSAAES128GCM(t *testing.T) {
508 test := &clientTest{
509 name: "AES128-GCM-SHA256",
510 args: []string{"-cipher", "AES128-GCM-SHA256"},
511 }
512 runClientTestTLS12(t, test)
513 }
514
515 func TestHandshakeClientRSAAES256GCM(t *testing.T) {
516 test := &clientTest{
517 name: "AES256-GCM-SHA384",
518 args: []string{"-cipher", "AES256-GCM-SHA384"},
519 }
520 runClientTestTLS12(t, test)
521 }
522
523 func TestHandshakeClientECDHERSAAES(t *testing.T) {
524 test := &clientTest{
525 name: "ECDHE-RSA-AES",
526 args: []string{"-cipher", "ECDHE-RSA-AES128-SHA"},
527 }
528 runClientTestTLS10(t, test)
529 runClientTestTLS11(t, test)
530 runClientTestTLS12(t, test)
531 }
532
533 func TestHandshakeClientECDHEECDSAAES(t *testing.T) {
534 test := &clientTest{
535 name: "ECDHE-ECDSA-AES",
536 args: []string{"-cipher", "ECDHE-ECDSA-AES128-SHA"},
537 cert: testECDSACertificate,
538 key: testECDSAPrivateKey,
539 }
540 runClientTestTLS10(t, test)
541 runClientTestTLS11(t, test)
542 runClientTestTLS12(t, test)
543 }
544
545 func TestHandshakeClientECDHEECDSAAESGCM(t *testing.T) {
546 test := &clientTest{
547 name: "ECDHE-ECDSA-AES-GCM",
548 args: []string{"-cipher", "ECDHE-ECDSA-AES128-GCM-SHA256"},
549 cert: testECDSACertificate,
550 key: testECDSAPrivateKey,
551 }
552 runClientTestTLS12(t, test)
553 }
554
555 func TestHandshakeClientAES256GCMSHA384(t *testing.T) {
556 test := &clientTest{
557 name: "ECDHE-ECDSA-AES256-GCM-SHA384",
558 args: []string{"-cipher", "ECDHE-ECDSA-AES256-GCM-SHA384"},
559 cert: testECDSACertificate,
560 key: testECDSAPrivateKey,
561 }
562 runClientTestTLS12(t, test)
563 }
564
565 func TestHandshakeClientAES128CBCSHA256(t *testing.T) {
566 test := &clientTest{
567 name: "AES128-SHA256",
568 args: []string{"-cipher", "AES128-SHA256"},
569 }
570 runClientTestTLS12(t, test)
571 }
572
573 func TestHandshakeClientECDHERSAAES128CBCSHA256(t *testing.T) {
574 test := &clientTest{
575 name: "ECDHE-RSA-AES128-SHA256",
576 args: []string{"-cipher", "ECDHE-RSA-AES128-SHA256"},
577 }
578 runClientTestTLS12(t, test)
579 }
580
581 func TestHandshakeClientECDHEECDSAAES128CBCSHA256(t *testing.T) {
582 test := &clientTest{
583 name: "ECDHE-ECDSA-AES128-SHA256",
584 args: []string{"-cipher", "ECDHE-ECDSA-AES128-SHA256"},
585 cert: testECDSACertificate,
586 key: testECDSAPrivateKey,
587 }
588 runClientTestTLS12(t, test)
589 }
590
591 func TestHandshakeClientX25519(t *testing.T) {
592 config := testConfig.Clone()
593 config.CurvePreferences = []CurveID{X25519}
594
595 test := &clientTest{
596 name: "X25519-ECDHE",
597 args: []string{"-cipher", "ECDHE-RSA-AES128-GCM-SHA256", "-curves", "X25519"},
598 config: config,
599 }
600
601 runClientTestTLS12(t, test)
602 runClientTestTLS13(t, test)
603 }
604
605 func TestHandshakeClientP256(t *testing.T) {
606 config := testConfig.Clone()
607 config.CurvePreferences = []CurveID{CurveP256}
608
609 test := &clientTest{
610 name: "P256-ECDHE",
611 args: []string{"-cipher", "ECDHE-RSA-AES128-GCM-SHA256", "-curves", "P-256"},
612 config: config,
613 }
614
615 runClientTestTLS12(t, test)
616 runClientTestTLS13(t, test)
617 }
618
619 func TestHandshakeClientHelloRetryRequest(t *testing.T) {
620 config := testConfig.Clone()
621 config.CurvePreferences = []CurveID{X25519, CurveP256}
622
623 test := &clientTest{
624 name: "HelloRetryRequest",
625 args: []string{"-cipher", "ECDHE-RSA-AES128-GCM-SHA256", "-curves", "P-256"},
626 config: config,
627 validate: func(cs ConnectionState) error {
628 if !cs.testingOnlyDidHRR {
629 return errors.New("expected HelloRetryRequest")
630 }
631 return nil
632 },
633 }
634
635 runClientTestTLS13(t, test)
636 }
637
638 func TestHandshakeClientECDHERSAChaCha20(t *testing.T) {
639 config := testConfig.Clone()
640 config.CipherSuites = []uint16{TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305}
641
642 test := &clientTest{
643 name: "ECDHE-RSA-CHACHA20-POLY1305",
644 args: []string{"-cipher", "ECDHE-RSA-CHACHA20-POLY1305"},
645 config: config,
646 }
647
648 runClientTestTLS12(t, test)
649 }
650
651 func TestHandshakeClientECDHEECDSAChaCha20(t *testing.T) {
652 config := testConfig.Clone()
653 config.CipherSuites = []uint16{TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305}
654
655 test := &clientTest{
656 name: "ECDHE-ECDSA-CHACHA20-POLY1305",
657 args: []string{"-cipher", "ECDHE-ECDSA-CHACHA20-POLY1305"},
658 config: config,
659 cert: testECDSACertificate,
660 key: testECDSAPrivateKey,
661 }
662
663 runClientTestTLS12(t, test)
664 }
665
666 func TestHandshakeClientAES128SHA256(t *testing.T) {
667 test := &clientTest{
668 name: "AES128-SHA256",
669 args: []string{"-ciphersuites", "TLS_AES_128_GCM_SHA256"},
670 }
671 runClientTestTLS13(t, test)
672 }
673 func TestHandshakeClientAES256SHA384(t *testing.T) {
674 test := &clientTest{
675 name: "AES256-SHA384",
676 args: []string{"-ciphersuites", "TLS_AES_256_GCM_SHA384"},
677 }
678 runClientTestTLS13(t, test)
679 }
680 func TestHandshakeClientCHACHA20SHA256(t *testing.T) {
681 test := &clientTest{
682 name: "CHACHA20-SHA256",
683 args: []string{"-ciphersuites", "TLS_CHACHA20_POLY1305_SHA256"},
684 }
685 runClientTestTLS13(t, test)
686 }
687
688 func TestHandshakeClientECDSATLS13(t *testing.T) {
689 test := &clientTest{
690 name: "ECDSA",
691 cert: testECDSACertificate,
692 key: testECDSAPrivateKey,
693 }
694 runClientTestTLS13(t, test)
695 }
696
697 func TestHandshakeClientEd25519(t *testing.T) {
698 test := &clientTest{
699 name: "Ed25519",
700 cert: testEd25519Certificate,
701 key: testEd25519PrivateKey,
702 }
703 runClientTestTLS12(t, test)
704 runClientTestTLS13(t, test)
705
706 config := testConfig.Clone()
707 cert, _ := X509KeyPair([]byte(clientEd25519CertificatePEM), []byte(clientEd25519KeyPEM))
708 config.Certificates = []Certificate{cert}
709
710 test = &clientTest{
711 name: "ClientCert-Ed25519",
712 args: []string{"-Verify", "1"},
713 config: config,
714 }
715
716 runClientTestTLS12(t, test)
717 runClientTestTLS13(t, test)
718 }
719
720 func TestHandshakeClientCertRSA(t *testing.T) {
721 config := testConfig.Clone()
722 cert, _ := X509KeyPair([]byte(clientCertificatePEM), []byte(clientKeyPEM))
723 config.Certificates = []Certificate{cert}
724
725 test := &clientTest{
726 name: "ClientCert-RSA-RSA",
727 args: []string{"-cipher", "AES128", "-Verify", "1"},
728 config: config,
729 }
730
731 runClientTestTLS10(t, test)
732 runClientTestTLS12(t, test)
733
734 test = &clientTest{
735 name: "ClientCert-RSA-ECDSA",
736 args: []string{"-cipher", "ECDHE-ECDSA-AES128-SHA", "-Verify", "1"},
737 config: config,
738 cert: testECDSACertificate,
739 key: testECDSAPrivateKey,
740 }
741
742 runClientTestTLS10(t, test)
743 runClientTestTLS12(t, test)
744 runClientTestTLS13(t, test)
745
746 test = &clientTest{
747 name: "ClientCert-RSA-AES256-GCM-SHA384",
748 args: []string{"-cipher", "ECDHE-RSA-AES256-GCM-SHA384", "-Verify", "1"},
749 config: config,
750 cert: testRSACertificate,
751 key: testRSAPrivateKey,
752 }
753
754 runClientTestTLS12(t, test)
755 }
756
757 func TestHandshakeClientCertECDSA(t *testing.T) {
758 config := testConfig.Clone()
759 cert, _ := X509KeyPair([]byte(clientECDSACertificatePEM), []byte(clientECDSAKeyPEM))
760 config.Certificates = []Certificate{cert}
761
762 test := &clientTest{
763 name: "ClientCert-ECDSA-RSA",
764 args: []string{"-cipher", "AES128", "-Verify", "1"},
765 config: config,
766 }
767
768 runClientTestTLS10(t, test)
769 runClientTestTLS12(t, test)
770 runClientTestTLS13(t, test)
771
772 test = &clientTest{
773 name: "ClientCert-ECDSA-ECDSA",
774 args: []string{"-cipher", "ECDHE-ECDSA-AES128-SHA", "-Verify", "1"},
775 config: config,
776 cert: testECDSACertificate,
777 key: testECDSAPrivateKey,
778 }
779
780 runClientTestTLS10(t, test)
781 runClientTestTLS12(t, test)
782 }
783
784
785
786
787
788 func TestHandshakeClientCertRSAPSS(t *testing.T) {
789 cert, err := x509.ParseCertificate(testRSAPSSCertificate)
790 if err != nil {
791 panic(err)
792 }
793 rootCAs := x509.NewCertPool()
794 rootCAs.AddCert(cert)
795
796 config := testConfig.Clone()
797
798 config.GetClientCertificate = func(*CertificateRequestInfo) (*Certificate, error) {
799 return &Certificate{
800 Certificate: [][]byte{testRSAPSSCertificate},
801 PrivateKey: testRSAPrivateKey,
802 }, nil
803 }
804 config.RootCAs = rootCAs
805
806 test := &clientTest{
807 name: "ClientCert-RSA-RSAPSS",
808 args: []string{"-cipher", "AES128", "-Verify", "1", "-client_sigalgs",
809 "rsa_pss_rsae_sha256", "-sigalgs", "rsa_pss_rsae_sha256"},
810 config: config,
811 cert: testRSAPSSCertificate,
812 key: testRSAPrivateKey,
813 }
814 runClientTestTLS12(t, test)
815 runClientTestTLS13(t, test)
816 }
817
818 func TestHandshakeClientCertRSAPKCS1v15(t *testing.T) {
819 config := testConfig.Clone()
820 cert, _ := X509KeyPair([]byte(clientCertificatePEM), []byte(clientKeyPEM))
821 config.Certificates = []Certificate{cert}
822
823 test := &clientTest{
824 name: "ClientCert-RSA-RSAPKCS1v15",
825 args: []string{"-cipher", "AES128", "-Verify", "1", "-client_sigalgs",
826 "rsa_pkcs1_sha256", "-sigalgs", "rsa_pkcs1_sha256"},
827 config: config,
828 }
829
830 runClientTestTLS12(t, test)
831 }
832
833 func TestClientKeyUpdate(t *testing.T) {
834 test := &clientTest{
835 name: "KeyUpdate",
836 args: []string{"-state"},
837 sendKeyUpdate: true,
838 }
839 runClientTestTLS13(t, test)
840 }
841
842 func TestResumption(t *testing.T) {
843 t.Run("TLSv12", func(t *testing.T) { testResumption(t, VersionTLS12) })
844 t.Run("TLSv13", func(t *testing.T) { testResumption(t, VersionTLS13) })
845 }
846
847 func testResumption(t *testing.T, version uint16) {
848 if testing.Short() {
849 t.Skip("skipping in -short mode")
850 }
851 serverConfig := &Config{
852 MaxVersion: version,
853 CipherSuites: []uint16{TLS_RSA_WITH_RC4_128_SHA, TLS_ECDHE_RSA_WITH_RC4_128_SHA},
854 Certificates: testConfig.Certificates,
855 Time: testTime,
856 }
857
858 issuer, err := x509.ParseCertificate(testRSACertificateIssuer)
859 if err != nil {
860 panic(err)
861 }
862
863 rootCAs := x509.NewCertPool()
864 rootCAs.AddCert(issuer)
865
866 clientConfig := &Config{
867 MaxVersion: version,
868 CipherSuites: []uint16{TLS_RSA_WITH_RC4_128_SHA},
869 ClientSessionCache: NewLRUClientSessionCache(32),
870 RootCAs: rootCAs,
871 ServerName: "example.golang",
872 Time: testTime,
873 }
874
875 testResumeState := func(test string, didResume bool) {
876 t.Helper()
877 _, hs, err := testHandshake(t, clientConfig, serverConfig)
878 if err != nil {
879 t.Fatalf("%s: handshake failed: %s", test, err)
880 }
881 if hs.DidResume != didResume {
882 t.Fatalf("%s resumed: %v, expected: %v", test, hs.DidResume, didResume)
883 }
884 if didResume && (hs.PeerCertificates == nil || hs.VerifiedChains == nil) {
885 t.Fatalf("expected non-nil certificates after resumption. Got peerCertificates: %#v, verifiedCertificates: %#v", hs.PeerCertificates, hs.VerifiedChains)
886 }
887 if got, want := hs.ServerName, clientConfig.ServerName; got != want {
888 t.Errorf("%s: server name %s, want %s", test, got, want)
889 }
890 }
891
892 getTicket := func() []byte {
893 return clientConfig.ClientSessionCache.(*lruSessionCache).q.Front().Value.(*lruSessionCacheEntry).state.session.ticket
894 }
895 deleteTicket := func() {
896 ticketKey := clientConfig.ClientSessionCache.(*lruSessionCache).q.Front().Value.(*lruSessionCacheEntry).sessionKey
897 clientConfig.ClientSessionCache.Put(ticketKey, nil)
898 }
899 corruptTicket := func() {
900 clientConfig.ClientSessionCache.(*lruSessionCache).q.Front().Value.(*lruSessionCacheEntry).state.session.secret[0] ^= 0xff
901 }
902 randomKey := func() [32]byte {
903 var k [32]byte
904 if _, err := io.ReadFull(serverConfig.rand(), k[:]); err != nil {
905 t.Fatalf("Failed to read new SessionTicketKey: %s", err)
906 }
907 return k
908 }
909
910 testResumeState("Handshake", false)
911 ticket := getTicket()
912 testResumeState("Resume", true)
913 if bytes.Equal(ticket, getTicket()) {
914 t.Fatal("ticket didn't change after resumption")
915 }
916
917
918 ticket = getTicket()
919 serverConfig.Time = func() time.Time { return testTime().Add(24*time.Hour + time.Minute) }
920 testResumeState("ResumeWithOldTicket", true)
921 if bytes.Equal(ticket, getTicket()) {
922 t.Fatal("old first ticket matches the fresh one")
923 }
924
925
926 ticket = getTicket()
927 serverConfig.Time = func() time.Time { return testTime().Add(24*8*time.Hour + time.Minute) }
928 testResumeState("ResumeWithExpiredTicket", false)
929 if bytes.Equal(ticket, getTicket()) {
930 t.Fatal("expired first ticket matches the fresh one")
931 }
932
933 serverConfig.Time = testTime
934 key1 := randomKey()
935 serverConfig.SetSessionTicketKeys([][32]byte{key1})
936
937 testResumeState("InvalidSessionTicketKey", false)
938 testResumeState("ResumeAfterInvalidSessionTicketKey", true)
939
940 key2 := randomKey()
941 serverConfig.SetSessionTicketKeys([][32]byte{key2, key1})
942 ticket = getTicket()
943 testResumeState("KeyChange", true)
944 if bytes.Equal(ticket, getTicket()) {
945 t.Fatal("new ticket wasn't included while resuming")
946 }
947 testResumeState("KeyChangeFinish", true)
948
949
950 serverConfig.Time = func() time.Time { return testTime().Add(24*time.Hour + time.Minute) }
951 testResumeState("OldSessionTicket", true)
952 ticket = getTicket()
953
954 serverConfig.Time = func() time.Time { return testTime().Add(24*8*time.Hour + 2*time.Minute) }
955 testResumeState("ExpiredSessionTicket", false)
956 if bytes.Equal(ticket, getTicket()) {
957 t.Fatal("new ticket wasn't provided after old ticket expired")
958 }
959
960
961 d := 0 * time.Hour
962 serverConfig.Time = func() time.Time { return testTime().Add(d) }
963 deleteTicket()
964 testResumeState("GetFreshSessionTicket", false)
965 for i := 0; i < 13; i++ {
966 d += 12 * time.Hour
967 testResumeState("OldSessionTicket", true)
968 }
969
970
971
972
973 d += 12*time.Hour + time.Minute
974 if version == VersionTLS13 {
975 testResumeState("ExpiredSessionTicket", true)
976 } else {
977 testResumeState("ExpiredSessionTicket", false)
978 }
979 if bytes.Equal(ticket, getTicket()) {
980 t.Fatal("new ticket wasn't provided after old ticket expired")
981 }
982
983
984
985 serverConfig = &Config{
986 MaxVersion: version,
987 CipherSuites: []uint16{TLS_RSA_WITH_RC4_128_SHA, TLS_ECDHE_RSA_WITH_RC4_128_SHA},
988 Certificates: testConfig.Certificates,
989 Time: testTime,
990 }
991 serverConfig.SetSessionTicketKeys([][32]byte{key2})
992
993 testResumeState("FreshConfig", true)
994
995
996
997 if version != VersionTLS13 {
998 clientConfig.CipherSuites = []uint16{TLS_ECDHE_RSA_WITH_RC4_128_SHA}
999 testResumeState("DifferentCipherSuite", false)
1000 testResumeState("DifferentCipherSuiteRecovers", true)
1001 }
1002
1003 deleteTicket()
1004 testResumeState("WithoutSessionTicket", false)
1005
1006
1007
1008 if version == VersionTLS13 {
1009 deleteTicket()
1010 serverConfig = &Config{
1011
1012 CurvePreferences: []CurveID{CurveP521, CurveP384, CurveP256},
1013 MaxVersion: version,
1014 Certificates: testConfig.Certificates,
1015 Time: testTime,
1016 }
1017 testResumeState("InitialHandshake", false)
1018 testResumeState("WithHelloRetryRequest", true)
1019
1020
1021 serverConfig = &Config{
1022 MaxVersion: version,
1023 CipherSuites: []uint16{TLS_RSA_WITH_RC4_128_SHA, TLS_ECDHE_RSA_WITH_RC4_128_SHA},
1024 Certificates: testConfig.Certificates,
1025 Time: testTime,
1026 }
1027 }
1028
1029
1030 deleteTicket()
1031 serverConfig.ClientCAs = rootCAs
1032 serverConfig.ClientAuth = RequireAndVerifyClientCert
1033 clientConfig.Certificates = serverConfig.Certificates
1034 testResumeState("InitialHandshake", false)
1035 testResumeState("WithClientCertificates", true)
1036 serverConfig.ClientAuth = NoClientCert
1037
1038
1039
1040 testResumeState("FetchTicketToCorrupt", false)
1041 corruptTicket()
1042 _, _, err = testHandshake(t, clientConfig, serverConfig)
1043 if err == nil {
1044 t.Fatalf("handshake did not fail with a corrupted client secret")
1045 }
1046 testResumeState("AfterHandshakeFailure", false)
1047
1048 clientConfig.ClientSessionCache = nil
1049 testResumeState("WithoutSessionCache", false)
1050
1051 clientConfig.ClientSessionCache = &serializingClientCache{t: t}
1052 testResumeState("BeforeSerializingCache", false)
1053 testResumeState("WithSerializingCache", true)
1054 }
1055
1056 type serializingClientCache struct {
1057 t *testing.T
1058
1059 ticket, state []byte
1060 }
1061
1062 func (c *serializingClientCache) Get(sessionKey string) (session *ClientSessionState, ok bool) {
1063 if c.ticket == nil {
1064 return nil, false
1065 }
1066 state, err := ParseSessionState(c.state)
1067 if err != nil {
1068 c.t.Error(err)
1069 return nil, false
1070 }
1071 cs, err := NewResumptionState(c.ticket, state)
1072 if err != nil {
1073 c.t.Error(err)
1074 return nil, false
1075 }
1076 return cs, true
1077 }
1078
1079 func (c *serializingClientCache) Put(sessionKey string, cs *ClientSessionState) {
1080 if cs == nil {
1081 c.ticket, c.state = nil, nil
1082 return
1083 }
1084 ticket, state, err := cs.ResumptionState()
1085 if err != nil {
1086 c.t.Error(err)
1087 return
1088 }
1089 stateBytes, err := state.Bytes()
1090 if err != nil {
1091 c.t.Error(err)
1092 return
1093 }
1094 c.ticket, c.state = ticket, stateBytes
1095 }
1096
1097 func TestLRUClientSessionCache(t *testing.T) {
1098
1099 cache := NewLRUClientSessionCache(4)
1100 cs := make([]ClientSessionState, 6)
1101 keys := []string{"0", "1", "2", "3", "4", "5", "6"}
1102
1103
1104 for i := 0; i < 4; i++ {
1105 cache.Put(keys[i], &cs[i])
1106 }
1107 for i := 0; i < 4; i++ {
1108 if s, ok := cache.Get(keys[i]); !ok || s != &cs[i] {
1109 t.Fatalf("session cache failed lookup for added key: %s", keys[i])
1110 }
1111 }
1112
1113
1114 for i := 4; i < 6; i++ {
1115 cache.Put(keys[i], &cs[i])
1116 }
1117 for i := 0; i < 2; i++ {
1118 if s, ok := cache.Get(keys[i]); ok || s != nil {
1119 t.Fatalf("session cache should have evicted key: %s", keys[i])
1120 }
1121 }
1122
1123
1124 cache.Get(keys[2])
1125 cache.Put(keys[0], &cs[0])
1126 if s, ok := cache.Get(keys[3]); ok || s != nil {
1127 t.Fatalf("session cache should have evicted key 3")
1128 }
1129
1130
1131 cache.Put(keys[0], &cs[3])
1132 if s, ok := cache.Get(keys[0]); !ok || s != &cs[3] {
1133 t.Fatalf("session cache failed update for key 0")
1134 }
1135
1136
1137 cache.Put(keys[0], nil)
1138 if _, ok := cache.Get(keys[0]); ok {
1139 t.Fatalf("session cache failed to delete key 0")
1140 }
1141
1142
1143 cache.Put(keys[2], nil)
1144 if _, ok := cache.Get(keys[2]); ok {
1145 t.Fatalf("session cache failed to delete key 4")
1146 }
1147 for i := 4; i < 6; i++ {
1148 if s, ok := cache.Get(keys[i]); !ok || s != &cs[i] {
1149 t.Fatalf("session cache should not have deleted key: %s", keys[i])
1150 }
1151 }
1152 }
1153
1154 func TestKeyLogTLS12(t *testing.T) {
1155 var serverBuf, clientBuf bytes.Buffer
1156
1157 clientConfig := testConfig.Clone()
1158 clientConfig.KeyLogWriter = &clientBuf
1159 clientConfig.MaxVersion = VersionTLS12
1160
1161 serverConfig := testConfig.Clone()
1162 serverConfig.KeyLogWriter = &serverBuf
1163 serverConfig.MaxVersion = VersionTLS12
1164
1165 c, s := localPipe(t)
1166 done := make(chan bool)
1167
1168 go func() {
1169 defer close(done)
1170
1171 if err := Server(s, serverConfig).Handshake(); err != nil {
1172 t.Errorf("server: %s", err)
1173 return
1174 }
1175 s.Close()
1176 }()
1177
1178 if err := Client(c, clientConfig).Handshake(); err != nil {
1179 t.Fatalf("client: %s", err)
1180 }
1181
1182 c.Close()
1183 <-done
1184
1185 checkKeylogLine := func(side, loggedLine string) {
1186 if len(loggedLine) == 0 {
1187 t.Fatalf("%s: no keylog line was produced", side)
1188 }
1189 const expectedLen = 13 +
1190 1 +
1191 32*2 +
1192 1 +
1193 48*2 +
1194 1
1195 if len(loggedLine) != expectedLen {
1196 t.Fatalf("%s: keylog line has incorrect length (want %d, got %d): %q", side, expectedLen, len(loggedLine), loggedLine)
1197 }
1198 if !strings.HasPrefix(loggedLine, "CLIENT_RANDOM "+strings.Repeat("0", 64)+" ") {
1199 t.Fatalf("%s: keylog line has incorrect structure or nonce: %q", side, loggedLine)
1200 }
1201 }
1202
1203 checkKeylogLine("client", clientBuf.String())
1204 checkKeylogLine("server", serverBuf.String())
1205 }
1206
1207 func TestKeyLogTLS13(t *testing.T) {
1208 var serverBuf, clientBuf bytes.Buffer
1209
1210 clientConfig := testConfig.Clone()
1211 clientConfig.KeyLogWriter = &clientBuf
1212
1213 serverConfig := testConfig.Clone()
1214 serverConfig.KeyLogWriter = &serverBuf
1215
1216 c, s := localPipe(t)
1217 done := make(chan bool)
1218
1219 go func() {
1220 defer close(done)
1221
1222 if err := Server(s, serverConfig).Handshake(); err != nil {
1223 t.Errorf("server: %s", err)
1224 return
1225 }
1226 s.Close()
1227 }()
1228
1229 if err := Client(c, clientConfig).Handshake(); err != nil {
1230 t.Fatalf("client: %s", err)
1231 }
1232
1233 c.Close()
1234 <-done
1235
1236 checkKeylogLines := func(side, loggedLines string) {
1237 loggedLines = strings.TrimSpace(loggedLines)
1238 lines := strings.Split(loggedLines, "\n")
1239 if len(lines) != 4 {
1240 t.Errorf("Expected the %s to log 4 lines, got %d", side, len(lines))
1241 }
1242 }
1243
1244 checkKeylogLines("client", clientBuf.String())
1245 checkKeylogLines("server", serverBuf.String())
1246 }
1247
1248 func TestHandshakeClientALPNMatch(t *testing.T) {
1249 config := testConfig.Clone()
1250 config.NextProtos = []string{"proto2", "proto1"}
1251
1252 test := &clientTest{
1253 name: "ALPN",
1254
1255
1256 args: []string{"-alpn", "proto1,proto2"},
1257 config: config,
1258 validate: func(state ConnectionState) error {
1259
1260 if state.NegotiatedProtocol != "proto1" {
1261 return fmt.Errorf("Got protocol %q, wanted proto1", state.NegotiatedProtocol)
1262 }
1263 return nil
1264 },
1265 }
1266 runClientTestTLS12(t, test)
1267 runClientTestTLS13(t, test)
1268 }
1269
1270 func TestServerSelectingUnconfiguredApplicationProtocol(t *testing.T) {
1271
1272
1273
1274 c, s := localPipe(t)
1275 errChan := make(chan error, 1)
1276
1277 go func() {
1278 client := Client(c, &Config{
1279 ServerName: "foo",
1280 CipherSuites: []uint16{TLS_RSA_WITH_AES_128_GCM_SHA256},
1281 NextProtos: []string{"http", "something-else"},
1282 })
1283 errChan <- client.Handshake()
1284 }()
1285
1286 var header [5]byte
1287 if _, err := io.ReadFull(s, header[:]); err != nil {
1288 t.Fatal(err)
1289 }
1290 recordLen := int(header[3])<<8 | int(header[4])
1291
1292 record := make([]byte, recordLen)
1293 if _, err := io.ReadFull(s, record); err != nil {
1294 t.Fatal(err)
1295 }
1296
1297 serverHello := &serverHelloMsg{
1298 vers: VersionTLS12,
1299 random: make([]byte, 32),
1300 cipherSuite: TLS_RSA_WITH_AES_128_GCM_SHA256,
1301 alpnProtocol: "how-about-this",
1302 }
1303 serverHelloBytes := mustMarshal(t, serverHello)
1304
1305 s.Write([]byte{
1306 byte(recordTypeHandshake),
1307 byte(VersionTLS12 >> 8),
1308 byte(VersionTLS12 & 0xff),
1309 byte(len(serverHelloBytes) >> 8),
1310 byte(len(serverHelloBytes)),
1311 })
1312 s.Write(serverHelloBytes)
1313 s.Close()
1314
1315 if err := <-errChan; !strings.Contains(err.Error(), "server selected unadvertised ALPN protocol") {
1316 t.Fatalf("Expected error about unconfigured cipher suite but got %q", err)
1317 }
1318 }
1319
1320
1321 const sctsBase64 = "ABIBaQFnAHUApLkJkLQYWBSHuxOizGdwCjw1mAT5G9+443fNDsgN3BAAAAFHl5nuFgAABAMARjBEAiAcS4JdlW5nW9sElUv2zvQyPoZ6ejKrGGB03gjaBZFMLwIgc1Qbbn+hsH0RvObzhS+XZhr3iuQQJY8S9G85D9KeGPAAdgBo9pj4H2SCvjqM7rkoHUz8cVFdZ5PURNEKZ6y7T0/7xAAAAUeX4bVwAAAEAwBHMEUCIDIhFDgG2HIuADBkGuLobU5a4dlCHoJLliWJ1SYT05z6AiEAjxIoZFFPRNWMGGIjskOTMwXzQ1Wh2e7NxXE1kd1J0QsAdgDuS723dc5guuFCaR+r4Z5mow9+X7By2IMAxHuJeqj9ywAAAUhcZIqHAAAEAwBHMEUCICmJ1rBT09LpkbzxtUC+Hi7nXLR0J+2PmwLp+sJMuqK+AiEAr0NkUnEVKVhAkccIFpYDqHOlZaBsuEhWWrYpg2RtKp0="
1322
1323 func TestHandshakClientSCTs(t *testing.T) {
1324 config := testConfig.Clone()
1325
1326 scts, err := base64.StdEncoding.DecodeString(sctsBase64)
1327 if err != nil {
1328 t.Fatal(err)
1329 }
1330
1331
1332
1333 test := &clientTest{
1334 name: "SCT",
1335 config: config,
1336 extensions: [][]byte{scts},
1337 validate: func(state ConnectionState) error {
1338 expectedSCTs := [][]byte{
1339 scts[8:125],
1340 scts[127:245],
1341 scts[247:],
1342 }
1343 if n := len(state.SignedCertificateTimestamps); n != len(expectedSCTs) {
1344 return fmt.Errorf("Got %d scts, wanted %d", n, len(expectedSCTs))
1345 }
1346 for i, expected := range expectedSCTs {
1347 if sct := state.SignedCertificateTimestamps[i]; !bytes.Equal(sct, expected) {
1348 return fmt.Errorf("SCT #%d contained %x, expected %x", i, sct, expected)
1349 }
1350 }
1351 return nil
1352 },
1353 }
1354 runClientTestTLS12(t, test)
1355
1356
1357
1358 }
1359
1360 func TestRenegotiationRejected(t *testing.T) {
1361 config := testConfig.Clone()
1362 test := &clientTest{
1363 name: "RenegotiationRejected",
1364 args: []string{"-state"},
1365 config: config,
1366 numRenegotiations: 1,
1367 renegotiationExpectedToFail: 1,
1368 checkRenegotiationError: func(renegotiationNum int, err error) error {
1369 if err == nil {
1370 return errors.New("expected error from renegotiation but got nil")
1371 }
1372 if !strings.Contains(err.Error(), "no renegotiation") {
1373 return fmt.Errorf("expected renegotiation to be rejected but got %q", err)
1374 }
1375 return nil
1376 },
1377 }
1378 runClientTestTLS12(t, test)
1379 }
1380
1381 func TestRenegotiateOnce(t *testing.T) {
1382 config := testConfig.Clone()
1383 config.Renegotiation = RenegotiateOnceAsClient
1384
1385 test := &clientTest{
1386 name: "RenegotiateOnce",
1387 args: []string{"-state"},
1388 config: config,
1389 numRenegotiations: 1,
1390 }
1391
1392 runClientTestTLS12(t, test)
1393 }
1394
1395 func TestRenegotiateTwice(t *testing.T) {
1396 config := testConfig.Clone()
1397 config.Renegotiation = RenegotiateFreelyAsClient
1398
1399 test := &clientTest{
1400 name: "RenegotiateTwice",
1401 args: []string{"-state"},
1402 config: config,
1403 numRenegotiations: 2,
1404 }
1405
1406 runClientTestTLS12(t, test)
1407 }
1408
1409 func TestRenegotiateTwiceRejected(t *testing.T) {
1410 config := testConfig.Clone()
1411 config.Renegotiation = RenegotiateOnceAsClient
1412
1413 test := &clientTest{
1414 name: "RenegotiateTwiceRejected",
1415 args: []string{"-state"},
1416 config: config,
1417 numRenegotiations: 2,
1418 renegotiationExpectedToFail: 2,
1419 checkRenegotiationError: func(renegotiationNum int, err error) error {
1420 if renegotiationNum == 1 {
1421 return err
1422 }
1423
1424 if err == nil {
1425 return errors.New("expected error from renegotiation but got nil")
1426 }
1427 if !strings.Contains(err.Error(), "no renegotiation") {
1428 return fmt.Errorf("expected renegotiation to be rejected but got %q", err)
1429 }
1430 return nil
1431 },
1432 }
1433
1434 runClientTestTLS12(t, test)
1435 }
1436
1437 func TestHandshakeClientExportKeyingMaterial(t *testing.T) {
1438 test := &clientTest{
1439 name: "ExportKeyingMaterial",
1440 config: testConfig.Clone(),
1441 validate: func(state ConnectionState) error {
1442 if km, err := state.ExportKeyingMaterial("test", nil, 42); err != nil {
1443 return fmt.Errorf("ExportKeyingMaterial failed: %v", err)
1444 } else if len(km) != 42 {
1445 return fmt.Errorf("Got %d bytes from ExportKeyingMaterial, wanted %d", len(km), 42)
1446 }
1447 return nil
1448 },
1449 }
1450 runClientTestTLS10(t, test)
1451 runClientTestTLS12(t, test)
1452 runClientTestTLS13(t, test)
1453 }
1454
1455 var hostnameInSNITests = []struct {
1456 in, out string
1457 }{
1458
1459 {"", ""},
1460 {"localhost", "localhost"},
1461 {"foo, bar, baz and qux", "foo, bar, baz and qux"},
1462
1463
1464 {"golang.org", "golang.org"},
1465 {"golang.org.", "golang.org"},
1466
1467
1468 {"1.2.3.4", ""},
1469
1470
1471 {"::1", ""},
1472 {"::1%lo0", ""},
1473 {"[::1]", ""},
1474 {"[::1%lo0]", ""},
1475 }
1476
1477 func TestHostnameInSNI(t *testing.T) {
1478 for _, tt := range hostnameInSNITests {
1479 c, s := localPipe(t)
1480
1481 go func(host string) {
1482 Client(c, &Config{ServerName: host, InsecureSkipVerify: true}).Handshake()
1483 }(tt.in)
1484
1485 var header [5]byte
1486 if _, err := io.ReadFull(s, header[:]); err != nil {
1487 t.Fatal(err)
1488 }
1489 recordLen := int(header[3])<<8 | int(header[4])
1490
1491 record := make([]byte, recordLen)
1492 if _, err := io.ReadFull(s, record[:]); err != nil {
1493 t.Fatal(err)
1494 }
1495
1496 c.Close()
1497 s.Close()
1498
1499 var m clientHelloMsg
1500 if !m.unmarshal(record) {
1501 t.Errorf("unmarshaling ClientHello for %q failed", tt.in)
1502 continue
1503 }
1504 if tt.in != tt.out && m.serverName == tt.in {
1505 t.Errorf("prohibited %q found in ClientHello: %x", tt.in, record)
1506 }
1507 if m.serverName != tt.out {
1508 t.Errorf("expected %q not found in ClientHello: %x", tt.out, record)
1509 }
1510 }
1511 }
1512
1513 func TestServerSelectingUnconfiguredCipherSuite(t *testing.T) {
1514
1515
1516
1517 c, s := localPipe(t)
1518 errChan := make(chan error, 1)
1519
1520 go func() {
1521 client := Client(c, &Config{
1522 ServerName: "foo",
1523 CipherSuites: []uint16{TLS_RSA_WITH_AES_128_GCM_SHA256},
1524 })
1525 errChan <- client.Handshake()
1526 }()
1527
1528 var header [5]byte
1529 if _, err := io.ReadFull(s, header[:]); err != nil {
1530 t.Fatal(err)
1531 }
1532 recordLen := int(header[3])<<8 | int(header[4])
1533
1534 record := make([]byte, recordLen)
1535 if _, err := io.ReadFull(s, record); err != nil {
1536 t.Fatal(err)
1537 }
1538
1539
1540
1541 serverHello := &serverHelloMsg{
1542 vers: VersionTLS12,
1543 random: make([]byte, 32),
1544 cipherSuite: TLS_RSA_WITH_AES_256_GCM_SHA384,
1545 }
1546 serverHelloBytes := mustMarshal(t, serverHello)
1547
1548 s.Write([]byte{
1549 byte(recordTypeHandshake),
1550 byte(VersionTLS12 >> 8),
1551 byte(VersionTLS12 & 0xff),
1552 byte(len(serverHelloBytes) >> 8),
1553 byte(len(serverHelloBytes)),
1554 })
1555 s.Write(serverHelloBytes)
1556 s.Close()
1557
1558 if err := <-errChan; !strings.Contains(err.Error(), "unconfigured cipher") {
1559 t.Fatalf("Expected error about unconfigured cipher suite but got %q", err)
1560 }
1561 }
1562
1563 func TestVerifyConnection(t *testing.T) {
1564 t.Run("TLSv12", func(t *testing.T) { testVerifyConnection(t, VersionTLS12) })
1565 t.Run("TLSv13", func(t *testing.T) { testVerifyConnection(t, VersionTLS13) })
1566 }
1567
1568 func testVerifyConnection(t *testing.T, version uint16) {
1569 checkFields := func(c ConnectionState, called *int, errorType string) error {
1570 if c.Version != version {
1571 return fmt.Errorf("%s: got Version %v, want %v", errorType, c.Version, version)
1572 }
1573 if c.HandshakeComplete {
1574 return fmt.Errorf("%s: got HandshakeComplete, want false", errorType)
1575 }
1576 if c.ServerName != "example.golang" {
1577 return fmt.Errorf("%s: got ServerName %s, want %s", errorType, c.ServerName, "example.golang")
1578 }
1579 if c.NegotiatedProtocol != "protocol1" {
1580 return fmt.Errorf("%s: got NegotiatedProtocol %s, want %s", errorType, c.NegotiatedProtocol, "protocol1")
1581 }
1582 if c.CipherSuite == 0 {
1583 return fmt.Errorf("%s: got CipherSuite 0, want non-zero", errorType)
1584 }
1585 wantDidResume := false
1586 if *called == 2 {
1587 wantDidResume = true
1588 }
1589 if c.DidResume != wantDidResume {
1590 return fmt.Errorf("%s: got DidResume %t, want %t", errorType, c.DidResume, wantDidResume)
1591 }
1592 return nil
1593 }
1594
1595 tests := []struct {
1596 name string
1597 configureServer func(*Config, *int)
1598 configureClient func(*Config, *int)
1599 }{
1600 {
1601 name: "RequireAndVerifyClientCert",
1602 configureServer: func(config *Config, called *int) {
1603 config.ClientAuth = RequireAndVerifyClientCert
1604 config.VerifyConnection = func(c ConnectionState) error {
1605 *called++
1606 if l := len(c.PeerCertificates); l != 1 {
1607 return fmt.Errorf("server: got len(PeerCertificates) = %d, wanted 1", l)
1608 }
1609 if len(c.VerifiedChains) == 0 {
1610 return fmt.Errorf("server: got len(VerifiedChains) = 0, wanted non-zero")
1611 }
1612 return checkFields(c, called, "server")
1613 }
1614 },
1615 configureClient: func(config *Config, called *int) {
1616 config.VerifyConnection = func(c ConnectionState) error {
1617 *called++
1618 if l := len(c.PeerCertificates); l != 1 {
1619 return fmt.Errorf("client: got len(PeerCertificates) = %d, wanted 1", l)
1620 }
1621 if len(c.VerifiedChains) == 0 {
1622 return fmt.Errorf("client: got len(VerifiedChains) = 0, wanted non-zero")
1623 }
1624 if c.DidResume {
1625 return nil
1626
1627
1628 }
1629 if len(c.OCSPResponse) == 0 {
1630 return fmt.Errorf("client: got len(OCSPResponse) = 0, wanted non-zero")
1631 }
1632 if len(c.SignedCertificateTimestamps) == 0 {
1633 return fmt.Errorf("client: got len(SignedCertificateTimestamps) = 0, wanted non-zero")
1634 }
1635 return checkFields(c, called, "client")
1636 }
1637 },
1638 },
1639 {
1640 name: "InsecureSkipVerify",
1641 configureServer: func(config *Config, called *int) {
1642 config.ClientAuth = RequireAnyClientCert
1643 config.InsecureSkipVerify = true
1644 config.VerifyConnection = func(c ConnectionState) error {
1645 *called++
1646 if l := len(c.PeerCertificates); l != 1 {
1647 return fmt.Errorf("server: got len(PeerCertificates) = %d, wanted 1", l)
1648 }
1649 if c.VerifiedChains != nil {
1650 return fmt.Errorf("server: got Verified Chains %v, want nil", c.VerifiedChains)
1651 }
1652 return checkFields(c, called, "server")
1653 }
1654 },
1655 configureClient: func(config *Config, called *int) {
1656 config.InsecureSkipVerify = true
1657 config.VerifyConnection = func(c ConnectionState) error {
1658 *called++
1659 if l := len(c.PeerCertificates); l != 1 {
1660 return fmt.Errorf("client: got len(PeerCertificates) = %d, wanted 1", l)
1661 }
1662 if c.VerifiedChains != nil {
1663 return fmt.Errorf("server: got Verified Chains %v, want nil", c.VerifiedChains)
1664 }
1665 if c.DidResume {
1666 return nil
1667
1668
1669 }
1670 if len(c.OCSPResponse) == 0 {
1671 return fmt.Errorf("client: got len(OCSPResponse) = 0, wanted non-zero")
1672 }
1673 if len(c.SignedCertificateTimestamps) == 0 {
1674 return fmt.Errorf("client: got len(SignedCertificateTimestamps) = 0, wanted non-zero")
1675 }
1676 return checkFields(c, called, "client")
1677 }
1678 },
1679 },
1680 {
1681 name: "NoClientCert",
1682 configureServer: func(config *Config, called *int) {
1683 config.ClientAuth = NoClientCert
1684 config.VerifyConnection = func(c ConnectionState) error {
1685 *called++
1686 return checkFields(c, called, "server")
1687 }
1688 },
1689 configureClient: func(config *Config, called *int) {
1690 config.VerifyConnection = func(c ConnectionState) error {
1691 *called++
1692 return checkFields(c, called, "client")
1693 }
1694 },
1695 },
1696 {
1697 name: "RequestClientCert",
1698 configureServer: func(config *Config, called *int) {
1699 config.ClientAuth = RequestClientCert
1700 config.VerifyConnection = func(c ConnectionState) error {
1701 *called++
1702 return checkFields(c, called, "server")
1703 }
1704 },
1705 configureClient: func(config *Config, called *int) {
1706 config.Certificates = nil
1707 config.VerifyConnection = func(c ConnectionState) error {
1708 *called++
1709 if l := len(c.PeerCertificates); l != 1 {
1710 return fmt.Errorf("client: got len(PeerCertificates) = %d, wanted 1", l)
1711 }
1712 if len(c.VerifiedChains) == 0 {
1713 return fmt.Errorf("client: got len(VerifiedChains) = 0, wanted non-zero")
1714 }
1715 if c.DidResume {
1716 return nil
1717
1718
1719 }
1720 if len(c.OCSPResponse) == 0 {
1721 return fmt.Errorf("client: got len(OCSPResponse) = 0, wanted non-zero")
1722 }
1723 if len(c.SignedCertificateTimestamps) == 0 {
1724 return fmt.Errorf("client: got len(SignedCertificateTimestamps) = 0, wanted non-zero")
1725 }
1726 return checkFields(c, called, "client")
1727 }
1728 },
1729 },
1730 }
1731 for _, test := range tests {
1732 issuer, err := x509.ParseCertificate(testRSACertificateIssuer)
1733 if err != nil {
1734 panic(err)
1735 }
1736 rootCAs := x509.NewCertPool()
1737 rootCAs.AddCert(issuer)
1738
1739 var serverCalled, clientCalled int
1740
1741 serverConfig := &Config{
1742 MaxVersion: version,
1743 Certificates: []Certificate{testConfig.Certificates[0]},
1744 Time: testTime,
1745 ClientCAs: rootCAs,
1746 NextProtos: []string{"protocol1"},
1747 }
1748 serverConfig.Certificates[0].SignedCertificateTimestamps = [][]byte{[]byte("dummy sct 1"), []byte("dummy sct 2")}
1749 serverConfig.Certificates[0].OCSPStaple = []byte("dummy ocsp")
1750 test.configureServer(serverConfig, &serverCalled)
1751
1752 clientConfig := &Config{
1753 MaxVersion: version,
1754 ClientSessionCache: NewLRUClientSessionCache(32),
1755 RootCAs: rootCAs,
1756 ServerName: "example.golang",
1757 Certificates: []Certificate{testConfig.Certificates[0]},
1758 Time: testTime,
1759 NextProtos: []string{"protocol1"},
1760 }
1761 test.configureClient(clientConfig, &clientCalled)
1762
1763 testHandshakeState := func(name string, didResume bool) {
1764 _, hs, err := testHandshake(t, clientConfig, serverConfig)
1765 if err != nil {
1766 t.Fatalf("%s: handshake failed: %s", name, err)
1767 }
1768 if hs.DidResume != didResume {
1769 t.Errorf("%s: resumed: %v, expected: %v", name, hs.DidResume, didResume)
1770 }
1771 wantCalled := 1
1772 if didResume {
1773 wantCalled = 2
1774 }
1775 if clientCalled != wantCalled {
1776 t.Errorf("%s: expected client VerifyConnection called %d times, did %d times", name, wantCalled, clientCalled)
1777 }
1778 if serverCalled != wantCalled {
1779 t.Errorf("%s: expected server VerifyConnection called %d times, did %d times", name, wantCalled, serverCalled)
1780 }
1781 }
1782 testHandshakeState(fmt.Sprintf("%s-FullHandshake", test.name), false)
1783 testHandshakeState(fmt.Sprintf("%s-Resumption", test.name), true)
1784 }
1785 }
1786
1787 func TestVerifyPeerCertificate(t *testing.T) {
1788 t.Run("TLSv12", func(t *testing.T) { testVerifyPeerCertificate(t, VersionTLS12) })
1789 t.Run("TLSv13", func(t *testing.T) { testVerifyPeerCertificate(t, VersionTLS13) })
1790 }
1791
1792 func testVerifyPeerCertificate(t *testing.T, version uint16) {
1793 issuer, err := x509.ParseCertificate(testRSACertificateIssuer)
1794 if err != nil {
1795 panic(err)
1796 }
1797
1798 rootCAs := x509.NewCertPool()
1799 rootCAs.AddCert(issuer)
1800
1801 sentinelErr := errors.New("TestVerifyPeerCertificate")
1802
1803 verifyPeerCertificateCallback := func(called *bool, rawCerts [][]byte, validatedChains [][]*x509.Certificate) error {
1804 if l := len(rawCerts); l != 1 {
1805 return fmt.Errorf("got len(rawCerts) = %d, wanted 1", l)
1806 }
1807 if len(validatedChains) == 0 {
1808 return errors.New("got len(validatedChains) = 0, wanted non-zero")
1809 }
1810 *called = true
1811 return nil
1812 }
1813 verifyConnectionCallback := func(called *bool, isClient bool, c ConnectionState) error {
1814 if l := len(c.PeerCertificates); l != 1 {
1815 return fmt.Errorf("got len(PeerCertificates) = %d, wanted 1", l)
1816 }
1817 if len(c.VerifiedChains) == 0 {
1818 return fmt.Errorf("got len(VerifiedChains) = 0, wanted non-zero")
1819 }
1820 if isClient && len(c.OCSPResponse) == 0 {
1821 return fmt.Errorf("got len(OCSPResponse) = 0, wanted non-zero")
1822 }
1823 *called = true
1824 return nil
1825 }
1826
1827 tests := []struct {
1828 configureServer func(*Config, *bool)
1829 configureClient func(*Config, *bool)
1830 validate func(t *testing.T, testNo int, clientCalled, serverCalled bool, clientErr, serverErr error)
1831 }{
1832 {
1833 configureServer: func(config *Config, called *bool) {
1834 config.InsecureSkipVerify = false
1835 config.VerifyPeerCertificate = func(rawCerts [][]byte, validatedChains [][]*x509.Certificate) error {
1836 return verifyPeerCertificateCallback(called, rawCerts, validatedChains)
1837 }
1838 },
1839 configureClient: func(config *Config, called *bool) {
1840 config.InsecureSkipVerify = false
1841 config.VerifyPeerCertificate = func(rawCerts [][]byte, validatedChains [][]*x509.Certificate) error {
1842 return verifyPeerCertificateCallback(called, rawCerts, validatedChains)
1843 }
1844 },
1845 validate: func(t *testing.T, testNo int, clientCalled, serverCalled bool, clientErr, serverErr error) {
1846 if clientErr != nil {
1847 t.Errorf("test[%d]: client handshake failed: %v", testNo, clientErr)
1848 }
1849 if serverErr != nil {
1850 t.Errorf("test[%d]: server handshake failed: %v", testNo, serverErr)
1851 }
1852 if !clientCalled {
1853 t.Errorf("test[%d]: client did not call callback", testNo)
1854 }
1855 if !serverCalled {
1856 t.Errorf("test[%d]: server did not call callback", testNo)
1857 }
1858 },
1859 },
1860 {
1861 configureServer: func(config *Config, called *bool) {
1862 config.InsecureSkipVerify = false
1863 config.VerifyPeerCertificate = func(rawCerts [][]byte, validatedChains [][]*x509.Certificate) error {
1864 return sentinelErr
1865 }
1866 },
1867 configureClient: func(config *Config, called *bool) {
1868 config.VerifyPeerCertificate = nil
1869 },
1870 validate: func(t *testing.T, testNo int, clientCalled, serverCalled bool, clientErr, serverErr error) {
1871 if serverErr != sentinelErr {
1872 t.Errorf("#%d: got server error %v, wanted sentinelErr", testNo, serverErr)
1873 }
1874 },
1875 },
1876 {
1877 configureServer: func(config *Config, called *bool) {
1878 config.InsecureSkipVerify = false
1879 },
1880 configureClient: func(config *Config, called *bool) {
1881 config.VerifyPeerCertificate = func(rawCerts [][]byte, validatedChains [][]*x509.Certificate) error {
1882 return sentinelErr
1883 }
1884 },
1885 validate: func(t *testing.T, testNo int, clientCalled, serverCalled bool, clientErr, serverErr error) {
1886 if clientErr != sentinelErr {
1887 t.Errorf("#%d: got client error %v, wanted sentinelErr", testNo, clientErr)
1888 }
1889 },
1890 },
1891 {
1892 configureServer: func(config *Config, called *bool) {
1893 config.InsecureSkipVerify = false
1894 },
1895 configureClient: func(config *Config, called *bool) {
1896 config.InsecureSkipVerify = true
1897 config.VerifyPeerCertificate = func(rawCerts [][]byte, validatedChains [][]*x509.Certificate) error {
1898 if l := len(rawCerts); l != 1 {
1899 return fmt.Errorf("got len(rawCerts) = %d, wanted 1", l)
1900 }
1901
1902
1903
1904 if l := len(validatedChains); l != 0 {
1905 return fmt.Errorf("got len(validatedChains) = %d, wanted zero", l)
1906 }
1907 *called = true
1908 return nil
1909 }
1910 },
1911 validate: func(t *testing.T, testNo int, clientCalled, serverCalled bool, clientErr, serverErr error) {
1912 if clientErr != nil {
1913 t.Errorf("test[%d]: client handshake failed: %v", testNo, clientErr)
1914 }
1915 if serverErr != nil {
1916 t.Errorf("test[%d]: server handshake failed: %v", testNo, serverErr)
1917 }
1918 if !clientCalled {
1919 t.Errorf("test[%d]: client did not call callback", testNo)
1920 }
1921 },
1922 },
1923 {
1924 configureServer: func(config *Config, called *bool) {
1925 config.InsecureSkipVerify = false
1926 config.VerifyConnection = func(c ConnectionState) error {
1927 return verifyConnectionCallback(called, false, c)
1928 }
1929 },
1930 configureClient: func(config *Config, called *bool) {
1931 config.InsecureSkipVerify = false
1932 config.VerifyConnection = func(c ConnectionState) error {
1933 return verifyConnectionCallback(called, true, c)
1934 }
1935 },
1936 validate: func(t *testing.T, testNo int, clientCalled, serverCalled bool, clientErr, serverErr error) {
1937 if clientErr != nil {
1938 t.Errorf("test[%d]: client handshake failed: %v", testNo, clientErr)
1939 }
1940 if serverErr != nil {
1941 t.Errorf("test[%d]: server handshake failed: %v", testNo, serverErr)
1942 }
1943 if !clientCalled {
1944 t.Errorf("test[%d]: client did not call callback", testNo)
1945 }
1946 if !serverCalled {
1947 t.Errorf("test[%d]: server did not call callback", testNo)
1948 }
1949 },
1950 },
1951 {
1952 configureServer: func(config *Config, called *bool) {
1953 config.InsecureSkipVerify = false
1954 config.VerifyConnection = func(c ConnectionState) error {
1955 return sentinelErr
1956 }
1957 },
1958 configureClient: func(config *Config, called *bool) {
1959 config.InsecureSkipVerify = false
1960 config.VerifyConnection = nil
1961 },
1962 validate: func(t *testing.T, testNo int, clientCalled, serverCalled bool, clientErr, serverErr error) {
1963 if serverErr != sentinelErr {
1964 t.Errorf("#%d: got server error %v, wanted sentinelErr", testNo, serverErr)
1965 }
1966 },
1967 },
1968 {
1969 configureServer: func(config *Config, called *bool) {
1970 config.InsecureSkipVerify = false
1971 config.VerifyConnection = nil
1972 },
1973 configureClient: func(config *Config, called *bool) {
1974 config.InsecureSkipVerify = false
1975 config.VerifyConnection = func(c ConnectionState) error {
1976 return sentinelErr
1977 }
1978 },
1979 validate: func(t *testing.T, testNo int, clientCalled, serverCalled bool, clientErr, serverErr error) {
1980 if clientErr != sentinelErr {
1981 t.Errorf("#%d: got client error %v, wanted sentinelErr", testNo, clientErr)
1982 }
1983 },
1984 },
1985 {
1986 configureServer: func(config *Config, called *bool) {
1987 config.InsecureSkipVerify = false
1988 config.VerifyPeerCertificate = func(rawCerts [][]byte, validatedChains [][]*x509.Certificate) error {
1989 return verifyPeerCertificateCallback(called, rawCerts, validatedChains)
1990 }
1991 config.VerifyConnection = func(c ConnectionState) error {
1992 return sentinelErr
1993 }
1994 },
1995 configureClient: func(config *Config, called *bool) {
1996 config.InsecureSkipVerify = false
1997 config.VerifyPeerCertificate = nil
1998 config.VerifyConnection = nil
1999 },
2000 validate: func(t *testing.T, testNo int, clientCalled, serverCalled bool, clientErr, serverErr error) {
2001 if serverErr != sentinelErr {
2002 t.Errorf("#%d: got server error %v, wanted sentinelErr", testNo, serverErr)
2003 }
2004 if !serverCalled {
2005 t.Errorf("test[%d]: server did not call callback", testNo)
2006 }
2007 },
2008 },
2009 {
2010 configureServer: func(config *Config, called *bool) {
2011 config.InsecureSkipVerify = false
2012 config.VerifyPeerCertificate = nil
2013 config.VerifyConnection = nil
2014 },
2015 configureClient: func(config *Config, called *bool) {
2016 config.InsecureSkipVerify = false
2017 config.VerifyPeerCertificate = func(rawCerts [][]byte, validatedChains [][]*x509.Certificate) error {
2018 return verifyPeerCertificateCallback(called, rawCerts, validatedChains)
2019 }
2020 config.VerifyConnection = func(c ConnectionState) error {
2021 return sentinelErr
2022 }
2023 },
2024 validate: func(t *testing.T, testNo int, clientCalled, serverCalled bool, clientErr, serverErr error) {
2025 if clientErr != sentinelErr {
2026 t.Errorf("#%d: got client error %v, wanted sentinelErr", testNo, clientErr)
2027 }
2028 if !clientCalled {
2029 t.Errorf("test[%d]: client did not call callback", testNo)
2030 }
2031 },
2032 },
2033 }
2034
2035 for i, test := range tests {
2036 c, s := localPipe(t)
2037 done := make(chan error)
2038
2039 var clientCalled, serverCalled bool
2040
2041 go func() {
2042 config := testConfig.Clone()
2043 config.ServerName = "example.golang"
2044 config.ClientAuth = RequireAndVerifyClientCert
2045 config.ClientCAs = rootCAs
2046 config.Time = testTime
2047 config.MaxVersion = version
2048 config.Certificates = make([]Certificate, 1)
2049 config.Certificates[0].Certificate = [][]byte{testRSACertificate}
2050 config.Certificates[0].PrivateKey = testRSAPrivateKey
2051 config.Certificates[0].SignedCertificateTimestamps = [][]byte{[]byte("dummy sct 1"), []byte("dummy sct 2")}
2052 config.Certificates[0].OCSPStaple = []byte("dummy ocsp")
2053 test.configureServer(config, &serverCalled)
2054
2055 err = Server(s, config).Handshake()
2056 s.Close()
2057 done <- err
2058 }()
2059
2060 config := testConfig.Clone()
2061 config.ServerName = "example.golang"
2062 config.RootCAs = rootCAs
2063 config.Time = testTime
2064 config.MaxVersion = version
2065 test.configureClient(config, &clientCalled)
2066 clientErr := Client(c, config).Handshake()
2067 c.Close()
2068 serverErr := <-done
2069
2070 test.validate(t, i, clientCalled, serverCalled, clientErr, serverErr)
2071 }
2072 }
2073
2074
2075
2076 type brokenConn struct {
2077 net.Conn
2078
2079
2080
2081 breakAfter int
2082
2083
2084 numWrites int
2085 }
2086
2087
2088 var brokenConnErr = errors.New("too many writes to brokenConn")
2089
2090 func (b *brokenConn) Write(data []byte) (int, error) {
2091 if b.numWrites >= b.breakAfter {
2092 return 0, brokenConnErr
2093 }
2094
2095 b.numWrites++
2096 return b.Conn.Write(data)
2097 }
2098
2099 func TestFailedWrite(t *testing.T) {
2100
2101 for _, breakAfter := range []int{0, 1} {
2102 c, s := localPipe(t)
2103 done := make(chan bool)
2104
2105 go func() {
2106 Server(s, testConfig).Handshake()
2107 s.Close()
2108 done <- true
2109 }()
2110
2111 brokenC := &brokenConn{Conn: c, breakAfter: breakAfter}
2112 err := Client(brokenC, testConfig).Handshake()
2113 if err != brokenConnErr {
2114 t.Errorf("#%d: expected error from brokenConn but got %q", breakAfter, err)
2115 }
2116 brokenC.Close()
2117
2118 <-done
2119 }
2120 }
2121
2122
2123 type writeCountingConn struct {
2124 net.Conn
2125
2126
2127 numWrites int
2128 }
2129
2130 func (wcc *writeCountingConn) Write(data []byte) (int, error) {
2131 wcc.numWrites++
2132 return wcc.Conn.Write(data)
2133 }
2134
2135 func TestBuffering(t *testing.T) {
2136 t.Run("TLSv12", func(t *testing.T) { testBuffering(t, VersionTLS12) })
2137 t.Run("TLSv13", func(t *testing.T) { testBuffering(t, VersionTLS13) })
2138 }
2139
2140 func testBuffering(t *testing.T, version uint16) {
2141 c, s := localPipe(t)
2142 done := make(chan bool)
2143
2144 clientWCC := &writeCountingConn{Conn: c}
2145 serverWCC := &writeCountingConn{Conn: s}
2146
2147 go func() {
2148 config := testConfig.Clone()
2149 config.MaxVersion = version
2150 Server(serverWCC, config).Handshake()
2151 serverWCC.Close()
2152 done <- true
2153 }()
2154
2155 err := Client(clientWCC, testConfig).Handshake()
2156 if err != nil {
2157 t.Fatal(err)
2158 }
2159 clientWCC.Close()
2160 <-done
2161
2162 var expectedClient, expectedServer int
2163 if version == VersionTLS13 {
2164 expectedClient = 2
2165 expectedServer = 1
2166 } else {
2167 expectedClient = 2
2168 expectedServer = 2
2169 }
2170
2171 if n := clientWCC.numWrites; n != expectedClient {
2172 t.Errorf("expected client handshake to complete with %d writes, but saw %d", expectedClient, n)
2173 }
2174
2175 if n := serverWCC.numWrites; n != expectedServer {
2176 t.Errorf("expected server handshake to complete with %d writes, but saw %d", expectedServer, n)
2177 }
2178 }
2179
2180 func TestAlertFlushing(t *testing.T) {
2181 c, s := localPipe(t)
2182 done := make(chan bool)
2183
2184 clientWCC := &writeCountingConn{Conn: c}
2185 serverWCC := &writeCountingConn{Conn: s}
2186
2187 serverConfig := testConfig.Clone()
2188
2189
2190 brokenKey := rsa.PrivateKey{PublicKey: testRSAPrivateKey.PublicKey}
2191 brokenKey.D = big.NewInt(42)
2192 serverConfig.Certificates = []Certificate{{
2193 Certificate: [][]byte{testRSACertificate},
2194 PrivateKey: &brokenKey,
2195 }}
2196
2197 go func() {
2198 Server(serverWCC, serverConfig).Handshake()
2199 serverWCC.Close()
2200 done <- true
2201 }()
2202
2203 err := Client(clientWCC, testConfig).Handshake()
2204 if err == nil {
2205 t.Fatal("client unexpectedly returned no error")
2206 }
2207
2208 const expectedError = "remote error: tls: internal error"
2209 if e := err.Error(); !strings.Contains(e, expectedError) {
2210 t.Fatalf("expected to find %q in error but error was %q", expectedError, e)
2211 }
2212 clientWCC.Close()
2213 <-done
2214
2215 if n := serverWCC.numWrites; n != 1 {
2216 t.Errorf("expected server handshake to complete with one write, but saw %d", n)
2217 }
2218 }
2219
2220 func TestHandshakeRace(t *testing.T) {
2221 if testing.Short() {
2222 t.Skip("skipping in -short mode")
2223 }
2224 t.Parallel()
2225
2226
2227
2228 for i := 0; i < 32; i++ {
2229 c, s := localPipe(t)
2230
2231 go func() {
2232 server := Server(s, testConfig)
2233 if err := server.Handshake(); err != nil {
2234 panic(err)
2235 }
2236
2237 var request [1]byte
2238 if n, err := server.Read(request[:]); err != nil || n != 1 {
2239 panic(err)
2240 }
2241
2242 server.Write(request[:])
2243 server.Close()
2244 }()
2245
2246 startWrite := make(chan struct{})
2247 startRead := make(chan struct{})
2248 readDone := make(chan struct{}, 1)
2249
2250 client := Client(c, testConfig)
2251 go func() {
2252 <-startWrite
2253 var request [1]byte
2254 client.Write(request[:])
2255 }()
2256
2257 go func() {
2258 <-startRead
2259 var reply [1]byte
2260 if _, err := io.ReadFull(client, reply[:]); err != nil {
2261 panic(err)
2262 }
2263 c.Close()
2264 readDone <- struct{}{}
2265 }()
2266
2267 if i&1 == 1 {
2268 startWrite <- struct{}{}
2269 startRead <- struct{}{}
2270 } else {
2271 startRead <- struct{}{}
2272 startWrite <- struct{}{}
2273 }
2274 <-readDone
2275 }
2276 }
2277
2278 var getClientCertificateTests = []struct {
2279 setup func(*Config, *Config)
2280 expectedClientError string
2281 verify func(*testing.T, int, *ConnectionState)
2282 }{
2283 {
2284 func(clientConfig, serverConfig *Config) {
2285
2286
2287
2288 serverConfig.ClientCAs = nil
2289 clientConfig.GetClientCertificate = func(cri *CertificateRequestInfo) (*Certificate, error) {
2290 if len(cri.SignatureSchemes) == 0 {
2291 panic("empty SignatureSchemes")
2292 }
2293 if len(cri.AcceptableCAs) != 0 {
2294 panic("AcceptableCAs should have been empty")
2295 }
2296 return new(Certificate), nil
2297 }
2298 },
2299 "",
2300 func(t *testing.T, testNum int, cs *ConnectionState) {
2301 if l := len(cs.PeerCertificates); l != 0 {
2302 t.Errorf("#%d: expected no certificates but got %d", testNum, l)
2303 }
2304 },
2305 },
2306 {
2307 func(clientConfig, serverConfig *Config) {
2308
2309
2310 clientConfig.MaxVersion = VersionTLS11
2311 clientConfig.GetClientCertificate = func(cri *CertificateRequestInfo) (*Certificate, error) {
2312 if len(cri.SignatureSchemes) == 0 {
2313 panic("empty SignatureSchemes")
2314 }
2315 return new(Certificate), nil
2316 }
2317 },
2318 "",
2319 func(t *testing.T, testNum int, cs *ConnectionState) {
2320 if l := len(cs.PeerCertificates); l != 0 {
2321 t.Errorf("#%d: expected no certificates but got %d", testNum, l)
2322 }
2323 },
2324 },
2325 {
2326 func(clientConfig, serverConfig *Config) {
2327
2328
2329 clientConfig.GetClientCertificate = func(cri *CertificateRequestInfo) (*Certificate, error) {
2330 return nil, errors.New("GetClientCertificate")
2331 }
2332 },
2333 "GetClientCertificate",
2334 func(t *testing.T, testNum int, cs *ConnectionState) {
2335 },
2336 },
2337 {
2338 func(clientConfig, serverConfig *Config) {
2339 clientConfig.GetClientCertificate = func(cri *CertificateRequestInfo) (*Certificate, error) {
2340 if len(cri.AcceptableCAs) == 0 {
2341 panic("empty AcceptableCAs")
2342 }
2343 cert := &Certificate{
2344 Certificate: [][]byte{testRSACertificate},
2345 PrivateKey: testRSAPrivateKey,
2346 }
2347 return cert, nil
2348 }
2349 },
2350 "",
2351 func(t *testing.T, testNum int, cs *ConnectionState) {
2352 if len(cs.VerifiedChains) == 0 {
2353 t.Errorf("#%d: expected some verified chains, but found none", testNum)
2354 }
2355 },
2356 },
2357 }
2358
2359 func TestGetClientCertificate(t *testing.T) {
2360 t.Run("TLSv12", func(t *testing.T) { testGetClientCertificate(t, VersionTLS12) })
2361 t.Run("TLSv13", func(t *testing.T) { testGetClientCertificate(t, VersionTLS13) })
2362 }
2363
2364 func testGetClientCertificate(t *testing.T, version uint16) {
2365 issuer, err := x509.ParseCertificate(testRSACertificateIssuer)
2366 if err != nil {
2367 panic(err)
2368 }
2369
2370 for i, test := range getClientCertificateTests {
2371 serverConfig := testConfig.Clone()
2372 serverConfig.ClientAuth = VerifyClientCertIfGiven
2373 serverConfig.RootCAs = x509.NewCertPool()
2374 serverConfig.RootCAs.AddCert(issuer)
2375 serverConfig.ClientCAs = serverConfig.RootCAs
2376 serverConfig.Time = testTime
2377 serverConfig.MaxVersion = version
2378
2379 clientConfig := testConfig.Clone()
2380 clientConfig.MaxVersion = version
2381
2382 test.setup(clientConfig, serverConfig)
2383
2384 type serverResult struct {
2385 cs ConnectionState
2386 err error
2387 }
2388
2389 c, s := localPipe(t)
2390 done := make(chan serverResult)
2391
2392 go func() {
2393 defer s.Close()
2394 server := Server(s, serverConfig)
2395 err := server.Handshake()
2396
2397 var cs ConnectionState
2398 if err == nil {
2399 cs = server.ConnectionState()
2400 }
2401 done <- serverResult{cs, err}
2402 }()
2403
2404 clientErr := Client(c, clientConfig).Handshake()
2405 c.Close()
2406
2407 result := <-done
2408
2409 if clientErr != nil {
2410 if len(test.expectedClientError) == 0 {
2411 t.Errorf("#%d: client error: %v", i, clientErr)
2412 } else if got := clientErr.Error(); got != test.expectedClientError {
2413 t.Errorf("#%d: expected client error %q, but got %q", i, test.expectedClientError, got)
2414 } else {
2415 test.verify(t, i, &result.cs)
2416 }
2417 } else if len(test.expectedClientError) > 0 {
2418 t.Errorf("#%d: expected client error %q, but got no error", i, test.expectedClientError)
2419 } else if err := result.err; err != nil {
2420 t.Errorf("#%d: server error: %v", i, err)
2421 } else {
2422 test.verify(t, i, &result.cs)
2423 }
2424 }
2425 }
2426
2427 func TestRSAPSSKeyError(t *testing.T) {
2428
2429
2430
2431
2432 b, _ := pem.Decode([]byte(`
2433 -----BEGIN CERTIFICATE-----
2434 MIIDZTCCAhygAwIBAgIUCF2x0FyTgZG0CC9QTDjGWkB5vgEwPgYJKoZIhvcNAQEK
2435 MDGgDTALBglghkgBZQMEAgGhGjAYBgkqhkiG9w0BAQgwCwYJYIZIAWUDBAIBogQC
2436 AgDeMBIxEDAOBgNVBAMMB1JTQS1QU1MwHhcNMTgwNjI3MjI0NDM2WhcNMTgwNzI3
2437 MjI0NDM2WjASMRAwDgYDVQQDDAdSU0EtUFNTMIIBIDALBgkqhkiG9w0BAQoDggEP
2438 ADCCAQoCggEBANxDm0f76JdI06YzsjB3AmmjIYkwUEGxePlafmIASFjDZl/elD0Z
2439 /a7xLX468b0qGxLS5al7XCcEprSdsDR6DF5L520+pCbpfLyPOjuOvGmk9KzVX4x5
2440 b05YXYuXdsQ0Kjxcx2i3jjCday6scIhMJVgBZxTEyMj1thPQM14SHzKCd/m6HmCL
2441 QmswpH2yMAAcBRWzRpp/vdH5DeOJEB3aelq7094no731mrLUCHRiZ1htq8BDB3ou
2442 czwqgwspbqZ4dnMXl2MvfySQ5wJUxQwILbiuAKO2lVVPUbFXHE9pgtznNoPvKwQT
2443 JNcX8ee8WIZc2SEGzofjk3NpjR+2ADB2u3sCAwEAAaNTMFEwHQYDVR0OBBYEFNEz
2444 AdyJ2f+fU+vSCS6QzohnOnprMB8GA1UdIwQYMBaAFNEzAdyJ2f+fU+vSCS6Qzohn
2445 OnprMA8GA1UdEwEB/wQFMAMBAf8wPgYJKoZIhvcNAQEKMDGgDTALBglghkgBZQME
2446 AgGhGjAYBgkqhkiG9w0BAQgwCwYJYIZIAWUDBAIBogQCAgDeA4IBAQCjEdrR5aab
2447 sZmCwrMeKidXgfkmWvfuLDE+TCbaqDZp7BMWcMQXT9O0UoUT5kqgKj2ARm2pEW0Z
2448 H3Z1vj3bbds72qcDIJXp+l0fekyLGeCrX/CbgnMZXEP7+/+P416p34ChR1Wz4dU1
2449 KD3gdsUuTKKeMUog3plxlxQDhRQmiL25ygH1LmjLd6dtIt0GVRGr8lj3euVeprqZ
2450 bZ3Uq5eLfsn8oPgfC57gpO6yiN+UURRTlK3bgYvLh4VWB3XXk9UaQZ7Mq1tpXjoD
2451 HYFybkWzibkZp4WRo+Fa28rirH+/wHt0vfeN7UCceURZEx4JaxIIfe4ku7uDRhJi
2452 RwBA9Xk1KBNF
2453 -----END CERTIFICATE-----`))
2454 if b == nil {
2455 t.Fatal("Failed to decode certificate")
2456 }
2457 cert, err := x509.ParseCertificate(b.Bytes)
2458 if err != nil {
2459 return
2460 }
2461 if _, ok := cert.PublicKey.(*rsa.PublicKey); ok {
2462 t.Error("A RSASSA-PSS certificate was parsed like a PKCS#1 v1.5 one, and it will be mistakenly used with rsa_pss_rsae_* signature algorithms")
2463 }
2464 }
2465
2466 func TestCloseClientConnectionOnIdleServer(t *testing.T) {
2467 clientConn, serverConn := localPipe(t)
2468 client := Client(clientConn, testConfig.Clone())
2469 go func() {
2470 var b [1]byte
2471 serverConn.Read(b[:])
2472 client.Close()
2473 }()
2474 client.SetWriteDeadline(time.Now().Add(time.Minute))
2475 err := client.Handshake()
2476 if err != nil {
2477 if err, ok := err.(net.Error); ok && err.Timeout() {
2478 t.Errorf("Expected a closed network connection error but got '%s'", err.Error())
2479 }
2480 } else {
2481 t.Errorf("Error expected, but no error returned")
2482 }
2483 }
2484
2485 func testDowngradeCanary(t *testing.T, clientVersion, serverVersion uint16) error {
2486 defer func() { testingOnlyForceDowngradeCanary = false }()
2487 testingOnlyForceDowngradeCanary = true
2488
2489 clientConfig := testConfig.Clone()
2490 clientConfig.MaxVersion = clientVersion
2491 serverConfig := testConfig.Clone()
2492 serverConfig.MaxVersion = serverVersion
2493 _, _, err := testHandshake(t, clientConfig, serverConfig)
2494 return err
2495 }
2496
2497 func TestDowngradeCanary(t *testing.T) {
2498 if err := testDowngradeCanary(t, VersionTLS13, VersionTLS12); err == nil {
2499 t.Errorf("downgrade from TLS 1.3 to TLS 1.2 was not detected")
2500 }
2501 if testing.Short() {
2502 t.Skip("skipping the rest of the checks in short mode")
2503 }
2504 if err := testDowngradeCanary(t, VersionTLS13, VersionTLS11); err == nil {
2505 t.Errorf("downgrade from TLS 1.3 to TLS 1.1 was not detected")
2506 }
2507 if err := testDowngradeCanary(t, VersionTLS13, VersionTLS10); err == nil {
2508 t.Errorf("downgrade from TLS 1.3 to TLS 1.0 was not detected")
2509 }
2510 if err := testDowngradeCanary(t, VersionTLS12, VersionTLS11); err == nil {
2511 t.Errorf("downgrade from TLS 1.2 to TLS 1.1 was not detected")
2512 }
2513 if err := testDowngradeCanary(t, VersionTLS12, VersionTLS10); err == nil {
2514 t.Errorf("downgrade from TLS 1.2 to TLS 1.0 was not detected")
2515 }
2516 if err := testDowngradeCanary(t, VersionTLS13, VersionTLS13); err != nil {
2517 t.Errorf("server unexpectedly sent downgrade canary for TLS 1.3")
2518 }
2519 if err := testDowngradeCanary(t, VersionTLS12, VersionTLS12); err != nil {
2520 t.Errorf("client didn't ignore expected TLS 1.2 canary")
2521 }
2522 if err := testDowngradeCanary(t, VersionTLS11, VersionTLS11); err != nil {
2523 t.Errorf("client unexpectedly reacted to a canary in TLS 1.1")
2524 }
2525 if err := testDowngradeCanary(t, VersionTLS10, VersionTLS10); err != nil {
2526 t.Errorf("client unexpectedly reacted to a canary in TLS 1.0")
2527 }
2528 }
2529
2530 func TestResumptionKeepsOCSPAndSCT(t *testing.T) {
2531 t.Run("TLSv12", func(t *testing.T) { testResumptionKeepsOCSPAndSCT(t, VersionTLS12) })
2532 t.Run("TLSv13", func(t *testing.T) { testResumptionKeepsOCSPAndSCT(t, VersionTLS13) })
2533 }
2534
2535 func testResumptionKeepsOCSPAndSCT(t *testing.T, ver uint16) {
2536 issuer, err := x509.ParseCertificate(testRSACertificateIssuer)
2537 if err != nil {
2538 t.Fatalf("failed to parse test issuer")
2539 }
2540 roots := x509.NewCertPool()
2541 roots.AddCert(issuer)
2542 clientConfig := &Config{
2543 MaxVersion: ver,
2544 ClientSessionCache: NewLRUClientSessionCache(32),
2545 ServerName: "example.golang",
2546 RootCAs: roots,
2547 Time: testTime,
2548 }
2549 serverConfig := testConfig.Clone()
2550 serverConfig.MaxVersion = ver
2551 serverConfig.Certificates[0].OCSPStaple = []byte{1, 2, 3}
2552 serverConfig.Certificates[0].SignedCertificateTimestamps = [][]byte{{4, 5, 6}}
2553
2554 _, ccs, err := testHandshake(t, clientConfig, serverConfig)
2555 if err != nil {
2556 t.Fatalf("handshake failed: %s", err)
2557 }
2558
2559
2560 if !bytes.Equal(ccs.OCSPResponse, serverConfig.Certificates[0].OCSPStaple) {
2561 t.Errorf("client ConnectionState contained unexpected OCSPResponse: wanted %v, got %v",
2562 serverConfig.Certificates[0].OCSPStaple, ccs.OCSPResponse)
2563 }
2564 if !reflect.DeepEqual(ccs.SignedCertificateTimestamps, serverConfig.Certificates[0].SignedCertificateTimestamps) {
2565 t.Errorf("client ConnectionState contained unexpected SignedCertificateTimestamps: wanted %v, got %v",
2566 serverConfig.Certificates[0].SignedCertificateTimestamps, ccs.SignedCertificateTimestamps)
2567 }
2568
2569
2570 oldSCTs := serverConfig.Certificates[0].SignedCertificateTimestamps
2571 serverConfig.Certificates[0].SignedCertificateTimestamps = nil
2572 _, ccs, err = testHandshake(t, clientConfig, serverConfig)
2573 if err != nil {
2574 t.Fatalf("handshake failed: %s", err)
2575 }
2576 if !ccs.DidResume {
2577 t.Fatalf("expected session to be resumed")
2578 }
2579
2580
2581 if !bytes.Equal(ccs.OCSPResponse, serverConfig.Certificates[0].OCSPStaple) {
2582 t.Errorf("client ConnectionState contained unexpected OCSPResponse after resumption: wanted %v, got %v",
2583 serverConfig.Certificates[0].OCSPStaple, ccs.OCSPResponse)
2584 }
2585 if !reflect.DeepEqual(ccs.SignedCertificateTimestamps, oldSCTs) {
2586 t.Errorf("client ConnectionState contained unexpected SignedCertificateTimestamps after resumption: wanted %v, got %v",
2587 oldSCTs, ccs.SignedCertificateTimestamps)
2588 }
2589
2590
2591
2592 if ver == VersionTLS13 {
2593 return
2594 }
2595
2596
2597 serverConfig.Certificates[0].SignedCertificateTimestamps = [][]byte{{7, 8, 9}}
2598 _, ccs, err = testHandshake(t, clientConfig, serverConfig)
2599 if err != nil {
2600 t.Fatalf("handshake failed: %s", err)
2601 }
2602 if !ccs.DidResume {
2603 t.Fatalf("expected session to be resumed")
2604 }
2605 if !reflect.DeepEqual(ccs.SignedCertificateTimestamps, serverConfig.Certificates[0].SignedCertificateTimestamps) {
2606 t.Errorf("client ConnectionState contained unexpected SignedCertificateTimestamps after resumption: wanted %v, got %v",
2607 serverConfig.Certificates[0].SignedCertificateTimestamps, ccs.SignedCertificateTimestamps)
2608 }
2609 }
2610
2611
2612
2613
2614 func TestClientHandshakeContextCancellation(t *testing.T) {
2615 c, s := localPipe(t)
2616 ctx, cancel := context.WithCancel(context.Background())
2617 unblockServer := make(chan struct{})
2618 defer close(unblockServer)
2619 go func() {
2620 cancel()
2621 <-unblockServer
2622 _ = s.Close()
2623 }()
2624 cli := Client(c, testConfig)
2625
2626
2627 err := cli.HandshakeContext(ctx)
2628 if err == nil {
2629 t.Fatal("Client handshake did not error when the context was canceled")
2630 }
2631 if err != context.Canceled {
2632 t.Errorf("Unexpected client handshake error: %v", err)
2633 }
2634 if runtime.GOARCH == "wasm" {
2635 t.Skip("conn.Close does not error as expected when called multiple times on WASM")
2636 }
2637 err = cli.Close()
2638 if err == nil {
2639 t.Error("Client connection was not closed when the context was canceled")
2640 }
2641 }
2642
2643
2644
2645 func TestTLS13OnlyClientHelloCipherSuite(t *testing.T) {
2646 tls13Tests := []struct {
2647 name string
2648 ciphers []uint16
2649 }{
2650 {
2651 name: "nil",
2652 ciphers: nil,
2653 },
2654 {
2655 name: "empty",
2656 ciphers: []uint16{},
2657 },
2658 {
2659 name: "some TLS 1.2 cipher",
2660 ciphers: []uint16{TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256},
2661 },
2662 {
2663 name: "some TLS 1.3 cipher",
2664 ciphers: []uint16{TLS_AES_128_GCM_SHA256},
2665 },
2666 {
2667 name: "some TLS 1.2 and 1.3 ciphers",
2668 ciphers: []uint16{TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384, TLS_AES_256_GCM_SHA384},
2669 },
2670 }
2671 for _, tt := range tls13Tests {
2672 tt := tt
2673 t.Run(tt.name, func(t *testing.T) {
2674 t.Parallel()
2675 testTLS13OnlyClientHelloCipherSuite(t, tt.ciphers)
2676 })
2677 }
2678 }
2679
2680 func testTLS13OnlyClientHelloCipherSuite(t *testing.T, ciphers []uint16) {
2681 serverConfig := &Config{
2682 Certificates: testConfig.Certificates,
2683 GetConfigForClient: func(chi *ClientHelloInfo) (*Config, error) {
2684 if len(chi.CipherSuites) != len(defaultCipherSuitesTLS13NoAES) {
2685 t.Errorf("only TLS 1.3 suites should be advertised, got=%x", chi.CipherSuites)
2686 } else {
2687 for i := range defaultCipherSuitesTLS13NoAES {
2688 if want, got := defaultCipherSuitesTLS13NoAES[i], chi.CipherSuites[i]; want != got {
2689 t.Errorf("cipher at index %d does not match, want=%x, got=%x", i, want, got)
2690 }
2691 }
2692 }
2693 return nil, nil
2694 },
2695 }
2696 clientConfig := &Config{
2697 MinVersion: VersionTLS13,
2698 CipherSuites: ciphers,
2699 InsecureSkipVerify: true,
2700 }
2701 if _, _, err := testHandshake(t, clientConfig, serverConfig); err != nil {
2702 t.Fatalf("handshake failed: %s", err)
2703 }
2704 }
2705
2706
2707 type discardConn struct {
2708 net.Conn
2709 }
2710
2711 func (dc *discardConn) Write(data []byte) (int, error) {
2712 return len(data), nil
2713 }
2714
2715
2716 const largeRSAKeyCertPEM = `-----BEGIN CERTIFICATE-----
2717 MIIInjCCBIWgAwIBAgIBAjANBgkqhkiG9w0BAQsFADASMRAwDgYDVQQDEwd0ZXN0
2718 aW5nMB4XDTIzMDYwNzIxMjMzNloXDTIzMDYwNzIzMjMzNlowEjEQMA4GA1UEAxMH
2719 dGVzdGluZzCCBCIwDQYJKoZIhvcNAQEBBQADggQPADCCBAoCggQBAWdHsf6Rh2Ca
2720 n2SQwn4t4OQrOjbLLdGE1pM6TBKKrHUFy62uEL8atNjlcfXIsa4aEu3xNGiqxqur
2721 ZectlkZbm0FkaaQ1Wr9oikDY3KfjuaXdPdO/XC/h8AKNxlDOylyXwUSK/CuYb+1j
2722 gy8yF5QFvVfwW/xwTlHmhUeSkVSQPosfQ6yXNNsmMzkd+ZPWLrfq4R+wiNtwYGu0
2723 WSBcI/M9o8/vrNLnIppoiBJJ13j9CR1ToEAzOFh9wwRWLY10oZhoh1ONN1KQURx4
2724 qedzvvP2DSjZbUccdvl2rBGvZpzfOiFdm1FCnxB0c72Cqx+GTHXBFf8bsa7KHky9
2725 sNO1GUanbq17WoDNgwbY6H51bfShqv0CErxatwWox3we4EcAmFHPVTCYL1oWVMGo
2726 a3Eth91NZj+b/nGhF9lhHKGzXSv9brmLLkfvM1jA6XhNhA7BQ5Vz67lj2j3XfXdh
2727 t/BU5pBXbL4Ut4mIhT1YnKXAjX2/LF5RHQTE8Vwkx5JAEKZyUEGOReD/B+7GOrLp
2728 HduMT9vZAc5aR2k9I8qq1zBAzsL69lyQNAPaDYd1BIAjUety9gAYaSQffCgAgpRO
2729 Gt+DYvxS+7AT/yEd5h74MU2AH7KrAkbXOtlwupiGwhMVTstncDJWXMJqbBhyHPF8
2730 3UmZH0hbL4PYmzSj9LDWQQXI2tv6vrCpfts3Cqhqxz9vRpgY7t1Wu6l/r+KxYYz3
2731 1pcGpPvRmPh0DJm7cPTiXqPnZcPt+ulSaSdlxmd19OnvG5awp0fXhxryZVwuiT8G
2732 VDkhyARrxYrdjlINsZJZbQjO0t8ketXAELJOnbFXXzeCOosyOHkLwsqOO96AVJA8
2733 45ZVL5m95ClGy0RSrjVIkXsxTAMVG6SPAqKwk6vmTdRGuSPS4rhgckPVDHmccmuq
2734 dfnT2YkX+wB2/M3oCgU+s30fAHGkbGZ0pCdNbFYFZLiH0iiMbTDl/0L/z7IdK0nH
2735 GLHVE7apPraKC6xl6rPWsD2iSfrmtIPQa0+rqbIVvKP5JdfJ8J4alI+OxFw/znQe
2736 V0/Rez0j22Fe119LZFFSXhRv+ZSvcq20xDwh00mzcumPWpYuCVPozA18yIhC9tNn
2737 ALHndz0tDseIdy9vC71jQWy9iwri3ueN0DekMMF8JGzI1Z6BAFzgyAx3DkHtwHg7
2738 B7qD0jPG5hJ5+yt323fYgJsuEAYoZ8/jzZ01pkX8bt+UsVN0DGnSGsI2ktnIIk3J
2739 l+8krjmUy6EaW79nITwoOqaeHOIp8m3UkjEcoKOYrzHRKqRy+A09rY+m/cAQaafW
2740 4xp0Zv7qZPLwnu0jsqB4jD8Ll9yPB02ndsoV6U5PeHzTkVhPml19jKUAwFfs7TJg
2741 kXy+/xFhYVUCAwEAATANBgkqhkiG9w0BAQsFAAOCBAIAAQnZY77pMNeypfpba2WK
2742 aDasT7dk2JqP0eukJCVPTN24Zca+xJNPdzuBATm/8SdZK9lddIbjSnWRsKvTnO2r
2743 /rYdlPf3jM5uuJtb8+Uwwe1s+gszelGS9G/lzzq+ehWicRIq2PFcs8o3iQMfENiv
2744 qILJ+xjcrvms5ZPDNahWkfRx3KCg8Q+/at2n5p7XYjMPYiLKHnDC+RE2b1qT20IZ
2745 FhuK/fTWLmKbfYFNNga6GC4qcaZJ7x0pbm4SDTYp0tkhzcHzwKhidfNB5J2vNz6l
2746 Ur6wiYwamFTLqcOwWo7rdvI+sSn05WQBv0QZlzFX+OAu0l7WQ7yU+noOxBhjvHds
2747 14+r9qcQZg2q9kG+evopYZqYXRUNNlZKo9MRBXhfrISulFAc5lRFQIXMXnglvAu+
2748 Ipz2gomEAOcOPNNVldhKAU94GAMJd/KfN0ZP7gX3YvPzuYU6XDhag5RTohXLm18w
2749 5AF+ES3DOQ6ixu3DTf0D+6qrDuK+prdX8ivcdTQVNOQ+MIZeGSc6NWWOTaMGJ3lg
2750 aZIxJUGdo6E7GBGiC1YTjgFKFbHzek1LRTh/LX3vbSudxwaG0HQxwsU9T4DWiMqa
2751 Fkf2KteLEUA6HrR+0XlAZrhwoqAmrJ+8lCFX3V0gE9lpENfVHlFXDGyx10DpTB28
2752 DdjnY3F7EPWNzwf9P3oNT69CKW3Bk6VVr3ROOJtDxVu1ioWo3TaXltQ0VOnap2Pu
2753 sa5wfrpfwBDuAS9JCDg4ttNp2nW3F7tgXC6xPqw5pvGwUppEw9XNrqV8TZrxduuv
2754 rQ3NyZ7KSzIpmFlD3UwV/fGfz3UQmHS6Ng1evrUID9DjfYNfRqSGIGjDfxGtYD+j
2755 Z1gLJZuhjJpNtwBkKRtlNtrCWCJK2hidK/foxwD7kwAPo2I9FjpltxCRywZUs07X
2756 KwXTfBR9v6ij1LV6K58hFS+8ezZyZ05CeVBFkMQdclTOSfuPxlMkQOtjp8QWDj+F
2757 j/MYziT5KBkHvcbrjdRtUJIAi4N7zCsPZtjik918AK1WBNRVqPbrgq/XSEXMfuvs
2758 6JbfK0B76vdBDRtJFC1JsvnIrGbUztxXzyQwFLaR/AjVJqpVlysLWzPKWVX6/+SJ
2759 u1NQOl2E8P6ycyBsuGnO89p0S4F8cMRcI2X1XQsZ7/q0NBrOMaEp5T3SrWo9GiQ3
2760 o2SBdbs3Y6MBPBtTu977Z/0RO63J3M5i2tjUiDfrFy7+VRLKr7qQ7JibohyB8QaR
2761 9tedgjn2f+of7PnP/PEl1cCphUZeHM7QKUMPT8dbqwmKtlYY43EHXcvNOT5IBk3X
2762 9lwJoZk/B2i+ZMRNSP34ztAwtxmasPt6RAWGQpWCn9qmttAHAnMfDqe7F7jVR6rS
2763 u58=
2764 -----END CERTIFICATE-----`
2765
2766 func TestHandshakeRSATooBig(t *testing.T) {
2767 testCert, _ := pem.Decode([]byte(largeRSAKeyCertPEM))
2768
2769 c := &Conn{conn: &discardConn{}, config: testConfig.Clone()}
2770
2771 expectedErr := "tls: server sent certificate containing RSA key larger than 8192 bits"
2772 err := c.verifyServerCertificate([][]byte{testCert.Bytes})
2773 if err == nil || err.Error() != expectedErr {
2774 t.Errorf("Conn.verifyServerCertificate unexpected error: want %q, got %q", expectedErr, err)
2775 }
2776
2777 expectedErr = "tls: client sent certificate containing RSA key larger than 8192 bits"
2778 err = c.processCertsFromClient(Certificate{Certificate: [][]byte{testCert.Bytes}})
2779 if err == nil || err.Error() != expectedErr {
2780 t.Errorf("Conn.processCertsFromClient unexpected error: want %q, got %q", expectedErr, err)
2781 }
2782 }
2783
2784 func TestTLS13ECHRejectionCallbacks(t *testing.T) {
2785 k, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
2786 if err != nil {
2787 t.Fatal(err)
2788 }
2789 tmpl := &x509.Certificate{
2790 SerialNumber: big.NewInt(1),
2791 Subject: pkix.Name{CommonName: "test"},
2792 DNSNames: []string{"example.golang"},
2793 NotBefore: testConfig.Time().Add(-time.Hour),
2794 NotAfter: testConfig.Time().Add(time.Hour),
2795 }
2796 certDER, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, k.Public(), k)
2797 if err != nil {
2798 t.Fatal(err)
2799 }
2800 cert, err := x509.ParseCertificate(certDER)
2801 if err != nil {
2802 t.Fatal(err)
2803 }
2804
2805 clientConfig, serverConfig := testConfig.Clone(), testConfig.Clone()
2806 serverConfig.Certificates = []Certificate{
2807 {
2808 Certificate: [][]byte{certDER},
2809 PrivateKey: k,
2810 },
2811 }
2812 serverConfig.MinVersion = VersionTLS13
2813 clientConfig.RootCAs = x509.NewCertPool()
2814 clientConfig.RootCAs.AddCert(cert)
2815 clientConfig.MinVersion = VersionTLS13
2816 clientConfig.EncryptedClientHelloConfigList, _ = hex.DecodeString("0041fe0d003d0100200020204bed0a11fc0dde595a9b78d966b0011128eb83f65d3c91c1cc5ac786cd246f000400010001ff0e6578616d706c652e676f6c616e670000")
2817 clientConfig.ServerName = "example.golang"
2818
2819 for _, tc := range []struct {
2820 name string
2821 expectedErr string
2822
2823 verifyConnection func(ConnectionState) error
2824 verifyPeerCertificate func([][]byte, [][]*x509.Certificate) error
2825 encryptedClientHelloRejectionVerify func(ConnectionState) error
2826 }{
2827 {
2828 name: "no callbacks",
2829 expectedErr: "tls: server rejected ECH",
2830 },
2831 {
2832 name: "EncryptedClientHelloRejectionVerify, no err",
2833 encryptedClientHelloRejectionVerify: func(ConnectionState) error {
2834 return nil
2835 },
2836 expectedErr: "tls: server rejected ECH",
2837 },
2838 {
2839 name: "EncryptedClientHelloRejectionVerify, err",
2840 encryptedClientHelloRejectionVerify: func(ConnectionState) error {
2841 return errors.New("callback err")
2842 },
2843
2844
2845 expectedErr: "callback err",
2846 },
2847 {
2848 name: "VerifyConnection, err",
2849 verifyConnection: func(ConnectionState) error {
2850 return errors.New("callback err")
2851 },
2852 expectedErr: "tls: server rejected ECH",
2853 },
2854 {
2855 name: "VerifyPeerCertificate, err",
2856 verifyPeerCertificate: func([][]byte, [][]*x509.Certificate) error {
2857 return errors.New("callback err")
2858 },
2859 expectedErr: "tls: server rejected ECH",
2860 },
2861 } {
2862 t.Run(tc.name, func(t *testing.T) {
2863 c, s := localPipe(t)
2864 done := make(chan error)
2865
2866 go func() {
2867 serverErr := Server(s, serverConfig).Handshake()
2868 s.Close()
2869 done <- serverErr
2870 }()
2871
2872 cConfig := clientConfig.Clone()
2873 cConfig.VerifyConnection = tc.verifyConnection
2874 cConfig.VerifyPeerCertificate = tc.verifyPeerCertificate
2875 cConfig.EncryptedClientHelloRejectionVerify = tc.encryptedClientHelloRejectionVerify
2876
2877 clientErr := Client(c, cConfig).Handshake()
2878 c.Close()
2879
2880 if tc.expectedErr == "" && clientErr != nil {
2881 t.Fatalf("unexpected err: %s", clientErr)
2882 } else if clientErr != nil && tc.expectedErr != clientErr.Error() {
2883 t.Fatalf("unexpected err: got %q, want %q", clientErr, tc.expectedErr)
2884 }
2885 })
2886 }
2887 }
2888
2889 func TestECHTLS12Server(t *testing.T) {
2890 clientConfig, serverConfig := testConfig.Clone(), testConfig.Clone()
2891
2892 serverConfig.MaxVersion = VersionTLS12
2893 clientConfig.MinVersion = 0
2894
2895 clientConfig.EncryptedClientHelloConfigList, _ = hex.DecodeString("0041fe0d003d0100200020204bed0a11fc0dde595a9b78d966b0011128eb83f65d3c91c1cc5ac786cd246f000400010001ff0e6578616d706c652e676f6c616e670000")
2896
2897 expectedErr := "server: tls: client offered only unsupported versions: [304]\nclient: remote error: tls: protocol version not supported"
2898 _, _, err := testHandshake(t, clientConfig, serverConfig)
2899 if err == nil || err.Error() != expectedErr {
2900 t.Fatalf("unexpected handshake error: got %q, want %q", err, expectedErr)
2901 }
2902 }
2903
View as plain text