Debian Codegraph @

libgo/go/crypto/tls/handshake_client_test.go

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