Source file
src/crypto/tls/handshake_server_test.go
1
2
3
4
5 package tls
6
7 import (
8 "bytes"
9 "context"
10 "crypto"
11 "crypto/elliptic"
12 "crypto/x509"
13 "encoding/pem"
14 "errors"
15 "fmt"
16 "io"
17 "net"
18 "os"
19 "os/exec"
20 "path/filepath"
21 "runtime"
22 "strings"
23 "testing"
24 "time"
25
26 "golang.org/x/crypto/curve25519"
27 )
28
29 func testClientHello(t *testing.T, serverConfig *Config, m handshakeMessage) {
30 testClientHelloFailure(t, serverConfig, m, "")
31 }
32
33 func testClientHelloFailure(t *testing.T, serverConfig *Config, m handshakeMessage, expectedSubStr string) {
34 c, s := localPipe(t)
35 go func() {
36 cli := Client(c, testConfig)
37 if ch, ok := m.(*clientHelloMsg); ok {
38 cli.vers = ch.vers
39 }
40 cli.writeRecord(recordTypeHandshake, m.marshal())
41 c.Close()
42 }()
43 ctx := context.Background()
44 conn := Server(s, serverConfig)
45 ch, err := conn.readClientHello(ctx)
46 hs := serverHandshakeState{
47 c: conn,
48 ctx: ctx,
49 clientHello: ch,
50 }
51 if err == nil {
52 err = hs.processClientHello()
53 }
54 if err == nil {
55 err = hs.pickCipherSuite()
56 }
57 s.Close()
58 if len(expectedSubStr) == 0 {
59 if err != nil && err != io.EOF {
60 t.Errorf("Got error: %s; expected to succeed", err)
61 }
62 } else if err == nil || !strings.Contains(err.Error(), expectedSubStr) {
63 t.Errorf("Got error: %v; expected to match substring '%s'", err, expectedSubStr)
64 }
65 }
66
67 func TestSimpleError(t *testing.T) {
68 testClientHelloFailure(t, testConfig, &serverHelloDoneMsg{}, "unexpected handshake message")
69 }
70
71 var badProtocolVersions = []uint16{0x0000, 0x0005, 0x0100, 0x0105, 0x0200, 0x0205, VersionSSL30}
72
73 func TestRejectBadProtocolVersion(t *testing.T) {
74 config := testConfig.Clone()
75 config.MinVersion = VersionSSL30
76 for _, v := range badProtocolVersions {
77 testClientHelloFailure(t, config, &clientHelloMsg{
78 vers: v,
79 random: make([]byte, 32),
80 }, "unsupported versions")
81 }
82 testClientHelloFailure(t, config, &clientHelloMsg{
83 vers: VersionTLS12,
84 supportedVersions: badProtocolVersions,
85 random: make([]byte, 32),
86 }, "unsupported versions")
87 }
88
89 func TestNoSuiteOverlap(t *testing.T) {
90 clientHello := &clientHelloMsg{
91 vers: VersionTLS10,
92 random: make([]byte, 32),
93 cipherSuites: []uint16{0xff00},
94 compressionMethods: []uint8{compressionNone},
95 }
96 testClientHelloFailure(t, testConfig, clientHello, "no cipher suite supported by both client and server")
97 }
98
99 func TestNoCompressionOverlap(t *testing.T) {
100 clientHello := &clientHelloMsg{
101 vers: VersionTLS10,
102 random: make([]byte, 32),
103 cipherSuites: []uint16{TLS_RSA_WITH_RC4_128_SHA},
104 compressionMethods: []uint8{0xff},
105 }
106 testClientHelloFailure(t, testConfig, clientHello, "client does not support uncompressed connections")
107 }
108
109 func TestNoRC4ByDefault(t *testing.T) {
110 clientHello := &clientHelloMsg{
111 vers: VersionTLS10,
112 random: make([]byte, 32),
113 cipherSuites: []uint16{TLS_RSA_WITH_RC4_128_SHA},
114 compressionMethods: []uint8{compressionNone},
115 }
116 serverConfig := testConfig.Clone()
117
118
119 serverConfig.CipherSuites = nil
120 testClientHelloFailure(t, serverConfig, clientHello, "no cipher suite supported by both client and server")
121 }
122
123 func TestRejectSNIWithTrailingDot(t *testing.T) {
124 testClientHelloFailure(t, testConfig, &clientHelloMsg{
125 vers: VersionTLS12,
126 random: make([]byte, 32),
127 serverName: "foo.com.",
128 }, "unexpected message")
129 }
130
131 func TestDontSelectECDSAWithRSAKey(t *testing.T) {
132
133
134 clientHello := &clientHelloMsg{
135 vers: VersionTLS10,
136 random: make([]byte, 32),
137 cipherSuites: []uint16{TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA},
138 compressionMethods: []uint8{compressionNone},
139 supportedCurves: []CurveID{CurveP256},
140 supportedPoints: []uint8{pointFormatUncompressed},
141 }
142 serverConfig := testConfig.Clone()
143 serverConfig.CipherSuites = clientHello.cipherSuites
144 serverConfig.Certificates = make([]Certificate, 1)
145 serverConfig.Certificates[0].Certificate = [][]byte{testECDSACertificate}
146 serverConfig.Certificates[0].PrivateKey = testECDSAPrivateKey
147 serverConfig.BuildNameToCertificate()
148
149 testClientHello(t, serverConfig, clientHello)
150
151
152
153 serverConfig.Certificates = testConfig.Certificates
154 testClientHelloFailure(t, serverConfig, clientHello, "no cipher suite supported by both client and server")
155 }
156
157 func TestDontSelectRSAWithECDSAKey(t *testing.T) {
158
159
160 clientHello := &clientHelloMsg{
161 vers: VersionTLS10,
162 random: make([]byte, 32),
163 cipherSuites: []uint16{TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA},
164 compressionMethods: []uint8{compressionNone},
165 supportedCurves: []CurveID{CurveP256},
166 supportedPoints: []uint8{pointFormatUncompressed},
167 }
168 serverConfig := testConfig.Clone()
169 serverConfig.CipherSuites = clientHello.cipherSuites
170
171 testClientHello(t, serverConfig, clientHello)
172
173
174
175 serverConfig.Certificates = make([]Certificate, 1)
176 serverConfig.Certificates[0].Certificate = [][]byte{testECDSACertificate}
177 serverConfig.Certificates[0].PrivateKey = testECDSAPrivateKey
178 serverConfig.BuildNameToCertificate()
179 testClientHelloFailure(t, serverConfig, clientHello, "no cipher suite supported by both client and server")
180 }
181
182 func TestRenegotiationExtension(t *testing.T) {
183 clientHello := &clientHelloMsg{
184 vers: VersionTLS12,
185 compressionMethods: []uint8{compressionNone},
186 random: make([]byte, 32),
187 secureRenegotiationSupported: true,
188 cipherSuites: []uint16{TLS_RSA_WITH_RC4_128_SHA},
189 }
190
191 bufChan := make(chan []byte, 1)
192 c, s := localPipe(t)
193
194 go func() {
195 cli := Client(c, testConfig)
196 cli.vers = clientHello.vers
197 cli.writeRecord(recordTypeHandshake, clientHello.marshal())
198
199 buf := make([]byte, 1024)
200 n, err := c.Read(buf)
201 if err != nil {
202 t.Errorf("Server read returned error: %s", err)
203 return
204 }
205 c.Close()
206 bufChan <- buf[:n]
207 }()
208
209 Server(s, testConfig).Handshake()
210 buf := <-bufChan
211
212 if len(buf) < 5+4 {
213 t.Fatalf("Server returned short message of length %d", len(buf))
214 }
215
216
217
218 serverHelloLen := int(buf[6])<<16 | int(buf[7])<<8 | int(buf[8])
219
220 var serverHello serverHelloMsg
221
222
223 if !serverHello.unmarshal(buf[5 : 9+serverHelloLen]) {
224 t.Fatalf("Failed to parse ServerHello")
225 }
226
227 if !serverHello.secureRenegotiationSupported {
228 t.Errorf("Secure renegotiation extension was not echoed.")
229 }
230 }
231
232 func TestTLS12OnlyCipherSuites(t *testing.T) {
233
234
235 clientHello := &clientHelloMsg{
236 vers: VersionTLS11,
237 random: make([]byte, 32),
238 cipherSuites: []uint16{
239
240
241
242
243 TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
244 TLS_RSA_WITH_RC4_128_SHA,
245 },
246 compressionMethods: []uint8{compressionNone},
247 supportedCurves: []CurveID{CurveP256, CurveP384, CurveP521},
248 supportedPoints: []uint8{pointFormatUncompressed},
249 }
250
251 c, s := localPipe(t)
252 replyChan := make(chan any)
253 go func() {
254 cli := Client(c, testConfig)
255 cli.vers = clientHello.vers
256 cli.writeRecord(recordTypeHandshake, clientHello.marshal())
257 reply, err := cli.readHandshake()
258 c.Close()
259 if err != nil {
260 replyChan <- err
261 } else {
262 replyChan <- reply
263 }
264 }()
265 config := testConfig.Clone()
266 config.CipherSuites = clientHello.cipherSuites
267 Server(s, config).Handshake()
268 s.Close()
269 reply := <-replyChan
270 if err, ok := reply.(error); ok {
271 t.Fatal(err)
272 }
273 serverHello, ok := reply.(*serverHelloMsg)
274 if !ok {
275 t.Fatalf("didn't get ServerHello message in reply. Got %v\n", reply)
276 }
277 if s := serverHello.cipherSuite; s != TLS_RSA_WITH_RC4_128_SHA {
278 t.Fatalf("bad cipher suite from server: %x", s)
279 }
280 }
281
282 func TestTLSPointFormats(t *testing.T) {
283
284
285 tests := []struct {
286 name string
287 cipherSuites []uint16
288 supportedCurves []CurveID
289 supportedPoints []uint8
290 wantSupportedPoints bool
291 }{
292 {"ECC", []uint16{TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA}, []CurveID{CurveP256}, []uint8{compressionNone}, true},
293 {"RSA", []uint16{TLS_RSA_WITH_AES_256_GCM_SHA384}, nil, nil, false},
294 }
295 for _, tt := range tests {
296 t.Run(tt.name, func(t *testing.T) {
297 clientHello := &clientHelloMsg{
298 vers: VersionTLS12,
299 random: make([]byte, 32),
300 cipherSuites: tt.cipherSuites,
301 compressionMethods: []uint8{compressionNone},
302 supportedCurves: tt.supportedCurves,
303 supportedPoints: tt.supportedPoints,
304 }
305
306 c, s := localPipe(t)
307 replyChan := make(chan any)
308 go func() {
309 cli := Client(c, testConfig)
310 cli.vers = clientHello.vers
311 cli.writeRecord(recordTypeHandshake, clientHello.marshal())
312 reply, err := cli.readHandshake()
313 c.Close()
314 if err != nil {
315 replyChan <- err
316 } else {
317 replyChan <- reply
318 }
319 }()
320 config := testConfig.Clone()
321 config.CipherSuites = clientHello.cipherSuites
322 Server(s, config).Handshake()
323 s.Close()
324 reply := <-replyChan
325 if err, ok := reply.(error); ok {
326 t.Fatal(err)
327 }
328 serverHello, ok := reply.(*serverHelloMsg)
329 if !ok {
330 t.Fatalf("didn't get ServerHello message in reply. Got %v\n", reply)
331 }
332 if tt.wantSupportedPoints {
333 if len(serverHello.supportedPoints) < 1 {
334 t.Fatal("missing ec_point_format extension from server")
335 }
336 found := false
337 for _, p := range serverHello.supportedPoints {
338 if p == pointFormatUncompressed {
339 found = true
340 break
341 }
342 }
343 if !found {
344 t.Fatal("missing uncompressed format in ec_point_format extension from server")
345 }
346 } else {
347 if len(serverHello.supportedPoints) != 0 {
348 t.Fatalf("unexcpected ec_point_format extension from server: %v", serverHello.supportedPoints)
349 }
350 }
351 })
352 }
353 }
354
355 func TestAlertForwarding(t *testing.T) {
356 c, s := localPipe(t)
357 go func() {
358 Client(c, testConfig).sendAlert(alertUnknownCA)
359 c.Close()
360 }()
361
362 err := Server(s, testConfig).Handshake()
363 s.Close()
364 var opErr *net.OpError
365 if !errors.As(err, &opErr) || opErr.Err != error(alertUnknownCA) {
366 t.Errorf("Got error: %s; expected: %s", err, error(alertUnknownCA))
367 }
368 }
369
370 func TestClose(t *testing.T) {
371 c, s := localPipe(t)
372 go c.Close()
373
374 err := Server(s, testConfig).Handshake()
375 s.Close()
376 if err != io.EOF {
377 t.Errorf("Got error: %s; expected: %s", err, io.EOF)
378 }
379 }
380
381 func TestVersion(t *testing.T) {
382 serverConfig := &Config{
383 Certificates: testConfig.Certificates,
384 MaxVersion: VersionTLS11,
385 }
386 clientConfig := &Config{
387 InsecureSkipVerify: true,
388 MinVersion: VersionTLS10,
389 }
390 state, _, err := testHandshake(t, clientConfig, serverConfig)
391 if err != nil {
392 t.Fatalf("handshake failed: %s", err)
393 }
394 if state.Version != VersionTLS11 {
395 t.Fatalf("incorrect version %x, should be %x", state.Version, VersionTLS11)
396 }
397
398 clientConfig.MinVersion = 0
399 _, _, err = testHandshake(t, clientConfig, serverConfig)
400 if err == nil {
401 t.Fatalf("expected failure to connect with TLS 1.0/1.1")
402 }
403
404 defer func(old bool) { debugEnableTLS10 = old }(debugEnableTLS10)
405 debugEnableTLS10 = true
406 _, _, err = testHandshake(t, clientConfig, serverConfig)
407 if err != nil {
408 t.Fatalf("handshake failed: %s", err)
409 }
410 if state.Version != VersionTLS11 {
411 t.Fatalf("incorrect version %x, should be %x", state.Version, VersionTLS11)
412 }
413 }
414
415 func TestCipherSuitePreference(t *testing.T) {
416 serverConfig := &Config{
417 CipherSuites: []uint16{TLS_RSA_WITH_RC4_128_SHA, TLS_AES_128_GCM_SHA256,
418 TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256},
419 Certificates: testConfig.Certificates,
420 MaxVersion: VersionTLS12,
421 GetConfigForClient: func(chi *ClientHelloInfo) (*Config, error) {
422 if chi.CipherSuites[0] != TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256 {
423 t.Error("the advertised order should not depend on Config.CipherSuites")
424 }
425 if len(chi.CipherSuites) != 2+len(defaultCipherSuitesTLS13) {
426 t.Error("the advertised TLS 1.2 suites should be filtered by Config.CipherSuites")
427 }
428 return nil, nil
429 },
430 }
431 clientConfig := &Config{
432 CipherSuites: []uint16{TLS_RSA_WITH_AES_128_CBC_SHA, TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256},
433 InsecureSkipVerify: true,
434 }
435 state, _, err := testHandshake(t, clientConfig, serverConfig)
436 if err != nil {
437 t.Fatalf("handshake failed: %s", err)
438 }
439 if state.CipherSuite != TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256 {
440 t.Error("the preference order should not depend on Config.CipherSuites")
441 }
442 }
443
444 func TestSCTHandshake(t *testing.T) {
445 t.Run("TLSv12", func(t *testing.T) { testSCTHandshake(t, VersionTLS12) })
446 t.Run("TLSv13", func(t *testing.T) { testSCTHandshake(t, VersionTLS13) })
447 }
448
449 func testSCTHandshake(t *testing.T, version uint16) {
450 expected := [][]byte{[]byte("certificate"), []byte("transparency")}
451 serverConfig := &Config{
452 Certificates: []Certificate{{
453 Certificate: [][]byte{testRSACertificate},
454 PrivateKey: testRSAPrivateKey,
455 SignedCertificateTimestamps: expected,
456 }},
457 MaxVersion: version,
458 }
459 clientConfig := &Config{
460 InsecureSkipVerify: true,
461 }
462 _, state, err := testHandshake(t, clientConfig, serverConfig)
463 if err != nil {
464 t.Fatalf("handshake failed: %s", err)
465 }
466 actual := state.SignedCertificateTimestamps
467 if len(actual) != len(expected) {
468 t.Fatalf("got %d scts, want %d", len(actual), len(expected))
469 }
470 for i, sct := range expected {
471 if !bytes.Equal(sct, actual[i]) {
472 t.Fatalf("SCT #%d was %x, but expected %x", i, actual[i], sct)
473 }
474 }
475 }
476
477 func TestCrossVersionResume(t *testing.T) {
478 t.Run("TLSv12", func(t *testing.T) { testCrossVersionResume(t, VersionTLS12) })
479 t.Run("TLSv13", func(t *testing.T) { testCrossVersionResume(t, VersionTLS13) })
480 }
481
482 func testCrossVersionResume(t *testing.T, version uint16) {
483 serverConfig := &Config{
484 CipherSuites: []uint16{TLS_RSA_WITH_AES_128_CBC_SHA},
485 Certificates: testConfig.Certificates,
486 }
487 clientConfig := &Config{
488 CipherSuites: []uint16{TLS_RSA_WITH_AES_128_CBC_SHA},
489 InsecureSkipVerify: true,
490 ClientSessionCache: NewLRUClientSessionCache(1),
491 ServerName: "servername",
492 MinVersion: VersionTLS10,
493 }
494
495
496 clientConfig.MaxVersion = VersionTLS11
497 _, _, err := testHandshake(t, clientConfig, serverConfig)
498 if err != nil {
499 t.Fatalf("handshake failed: %s", err)
500 }
501
502
503 state, _, err := testHandshake(t, clientConfig, serverConfig)
504 if err != nil {
505 t.Fatalf("handshake failed: %s", err)
506 }
507 if !state.DidResume {
508 t.Fatalf("handshake did not resume at the same version")
509 }
510
511
512 clientConfig.MaxVersion = VersionTLS10
513 state, _, err = testHandshake(t, clientConfig, serverConfig)
514 if err != nil {
515 t.Fatalf("handshake failed: %s", err)
516 }
517 if state.DidResume {
518 t.Fatalf("handshake resumed at a lower version")
519 }
520
521
522 state, _, err = testHandshake(t, clientConfig, serverConfig)
523 if err != nil {
524 t.Fatalf("handshake failed: %s", err)
525 }
526 if !state.DidResume {
527 t.Fatalf("handshake did not resume at the same version")
528 }
529
530
531 clientConfig.MaxVersion = VersionTLS11
532 state, _, err = testHandshake(t, clientConfig, serverConfig)
533 if err != nil {
534 t.Fatalf("handshake failed: %s", err)
535 }
536 if state.DidResume {
537 t.Fatalf("handshake resumed at a higher version")
538 }
539 }
540
541
542
543
544
545
546 type serverTest struct {
547
548
549 name string
550
551
552 command []string
553
554
555 expectedPeerCerts []string
556
557 config *Config
558
559
560 expectHandshakeErrorIncluding string
561
562
563
564 validate func(ConnectionState) error
565
566
567 wait bool
568 }
569
570 var defaultClientCommand = []string{"openssl", "s_client", "-no_ticket"}
571
572
573
574
575 func (test *serverTest) connFromCommand() (conn *recordingConn, child *exec.Cmd, err error) {
576 l, err := net.ListenTCP("tcp", &net.TCPAddr{
577 IP: net.IPv4(127, 0, 0, 1),
578 Port: 0,
579 })
580 if err != nil {
581 return nil, nil, err
582 }
583 defer l.Close()
584
585 port := l.Addr().(*net.TCPAddr).Port
586
587 var command []string
588 command = append(command, test.command...)
589 if len(command) == 0 {
590 command = defaultClientCommand
591 }
592 command = append(command, "-connect")
593 command = append(command, fmt.Sprintf("127.0.0.1:%d", port))
594 cmd := exec.Command(command[0], command[1:]...)
595 cmd.Stdin = nil
596 var output bytes.Buffer
597 cmd.Stdout = &output
598 cmd.Stderr = &output
599 if err := cmd.Start(); err != nil {
600 return nil, nil, err
601 }
602
603 connChan := make(chan any, 1)
604 go func() {
605 tcpConn, err := l.Accept()
606 if err != nil {
607 connChan <- err
608 return
609 }
610 connChan <- tcpConn
611 }()
612
613 var tcpConn net.Conn
614 select {
615 case connOrError := <-connChan:
616 if err, ok := connOrError.(error); ok {
617 return nil, nil, err
618 }
619 tcpConn = connOrError.(net.Conn)
620 case <-time.After(2 * time.Second):
621 return nil, nil, errors.New("timed out waiting for connection from child process")
622 }
623
624 record := &recordingConn{
625 Conn: tcpConn,
626 }
627
628 return record, cmd, nil
629 }
630
631 func (test *serverTest) dataPath() string {
632 return filepath.Join("testdata", "Server-"+test.name)
633 }
634
635 func (test *serverTest) loadData() (flows [][]byte, err error) {
636 in, err := os.Open(test.dataPath())
637 if err != nil {
638 return nil, err
639 }
640 defer in.Close()
641 return parseTestData(in)
642 }
643
644 func (test *serverTest) run(t *testing.T, write bool) {
645 var clientConn, serverConn net.Conn
646 var recordingConn *recordingConn
647 var childProcess *exec.Cmd
648
649 if write {
650 var err error
651 recordingConn, childProcess, err = test.connFromCommand()
652 if err != nil {
653 t.Fatalf("Failed to start subcommand: %s", err)
654 }
655 serverConn = recordingConn
656 defer func() {
657 if t.Failed() {
658 t.Logf("OpenSSL output:\n\n%s", childProcess.Stdout)
659 }
660 }()
661 } else {
662 clientConn, serverConn = localPipe(t)
663 }
664 config := test.config
665 if config == nil {
666 config = testConfig
667 }
668 server := Server(serverConn, config)
669 connStateChan := make(chan ConnectionState, 1)
670 go func() {
671 _, err := server.Write([]byte("hello, world\n"))
672 if len(test.expectHandshakeErrorIncluding) > 0 {
673 if err == nil {
674 t.Errorf("Error expected, but no error returned")
675 } else if s := err.Error(); !strings.Contains(s, test.expectHandshakeErrorIncluding) {
676 t.Errorf("Error expected containing '%s' but got '%s'", test.expectHandshakeErrorIncluding, s)
677 }
678 } else {
679 if err != nil {
680 t.Logf("Error from Server.Write: '%s'", err)
681 }
682 }
683 server.Close()
684 serverConn.Close()
685 connStateChan <- server.ConnectionState()
686 }()
687
688 if !write {
689 flows, err := test.loadData()
690 if err != nil {
691 t.Fatalf("%s: failed to load data from %s", test.name, test.dataPath())
692 }
693 for i, b := range flows {
694 if i%2 == 0 {
695 if *fast {
696 clientConn.SetWriteDeadline(time.Now().Add(1 * time.Second))
697 } else {
698 clientConn.SetWriteDeadline(time.Now().Add(1 * time.Minute))
699 }
700 clientConn.Write(b)
701 continue
702 }
703 bb := make([]byte, len(b))
704 if *fast {
705 clientConn.SetReadDeadline(time.Now().Add(1 * time.Second))
706 } else {
707 clientConn.SetReadDeadline(time.Now().Add(1 * time.Minute))
708 }
709 n, err := io.ReadFull(clientConn, bb)
710 if err != nil {
711 t.Fatalf("%s #%d: %s\nRead %d, wanted %d, got %x, wanted %x\n", test.name, i+1, err, n, len(bb), bb[:n], b)
712 }
713 if !bytes.Equal(b, bb) {
714 t.Fatalf("%s #%d: mismatch on read: got:%x want:%x", test.name, i+1, bb, b)
715 }
716 }
717 clientConn.Close()
718 }
719
720 connState := <-connStateChan
721 peerCerts := connState.PeerCertificates
722 if len(peerCerts) == len(test.expectedPeerCerts) {
723 for i, peerCert := range peerCerts {
724 block, _ := pem.Decode([]byte(test.expectedPeerCerts[i]))
725 if !bytes.Equal(block.Bytes, peerCert.Raw) {
726 t.Fatalf("%s: mismatch on peer cert %d", test.name, i+1)
727 }
728 }
729 } else {
730 t.Fatalf("%s: mismatch on peer list length: %d (wanted) != %d (got)", test.name, len(test.expectedPeerCerts), len(peerCerts))
731 }
732
733 if test.validate != nil {
734 if err := test.validate(connState); err != nil {
735 t.Fatalf("validate callback returned error: %s", err)
736 }
737 }
738
739 if write {
740 path := test.dataPath()
741 out, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644)
742 if err != nil {
743 t.Fatalf("Failed to create output file: %s", err)
744 }
745 defer out.Close()
746 recordingConn.Close()
747 if len(recordingConn.flows) < 3 {
748 if len(test.expectHandshakeErrorIncluding) == 0 {
749 t.Fatalf("Handshake failed")
750 }
751 }
752 recordingConn.WriteTo(out)
753 t.Logf("Wrote %s\n", path)
754 childProcess.Wait()
755 }
756 }
757
758 func runServerTestForVersion(t *testing.T, template *serverTest, version, option string) {
759
760 test := *template
761 if template.config != nil {
762 test.config = template.config.Clone()
763 }
764 test.name = version + "-" + test.name
765 if len(test.command) == 0 {
766 test.command = defaultClientCommand
767 }
768 test.command = append([]string(nil), test.command...)
769 test.command = append(test.command, option)
770
771 runTestAndUpdateIfNeeded(t, version, test.run, test.wait)
772 }
773
774 func runServerTestTLS10(t *testing.T, template *serverTest) {
775 runServerTestForVersion(t, template, "TLSv10", "-tls1")
776 }
777
778 func runServerTestTLS11(t *testing.T, template *serverTest) {
779 runServerTestForVersion(t, template, "TLSv11", "-tls1_1")
780 }
781
782 func runServerTestTLS12(t *testing.T, template *serverTest) {
783 runServerTestForVersion(t, template, "TLSv12", "-tls1_2")
784 }
785
786 func runServerTestTLS13(t *testing.T, template *serverTest) {
787 runServerTestForVersion(t, template, "TLSv13", "-tls1_3")
788 }
789
790 func TestHandshakeServerRSARC4(t *testing.T) {
791 test := &serverTest{
792 name: "RSA-RC4",
793 command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "RC4-SHA"},
794 }
795 runServerTestTLS10(t, test)
796 runServerTestTLS11(t, test)
797 runServerTestTLS12(t, test)
798 }
799
800 func TestHandshakeServerRSA3DES(t *testing.T) {
801 test := &serverTest{
802 name: "RSA-3DES",
803 command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "DES-CBC3-SHA"},
804 }
805 runServerTestTLS10(t, test)
806 runServerTestTLS12(t, test)
807 }
808
809 func TestHandshakeServerRSAAES(t *testing.T) {
810 test := &serverTest{
811 name: "RSA-AES",
812 command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "AES128-SHA"},
813 }
814 runServerTestTLS10(t, test)
815 runServerTestTLS12(t, test)
816 }
817
818 func TestHandshakeServerAESGCM(t *testing.T) {
819 test := &serverTest{
820 name: "RSA-AES-GCM",
821 command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "ECDHE-RSA-AES128-GCM-SHA256"},
822 }
823 runServerTestTLS12(t, test)
824 }
825
826 func TestHandshakeServerAES256GCMSHA384(t *testing.T) {
827 test := &serverTest{
828 name: "RSA-AES256-GCM-SHA384",
829 command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "ECDHE-RSA-AES256-GCM-SHA384"},
830 }
831 runServerTestTLS12(t, test)
832 }
833
834 func TestHandshakeServerAES128SHA256(t *testing.T) {
835 test := &serverTest{
836 name: "AES128-SHA256",
837 command: []string{"openssl", "s_client", "-no_ticket", "-ciphersuites", "TLS_AES_128_GCM_SHA256"},
838 }
839 runServerTestTLS13(t, test)
840 }
841 func TestHandshakeServerAES256SHA384(t *testing.T) {
842 test := &serverTest{
843 name: "AES256-SHA384",
844 command: []string{"openssl", "s_client", "-no_ticket", "-ciphersuites", "TLS_AES_256_GCM_SHA384"},
845 }
846 runServerTestTLS13(t, test)
847 }
848 func TestHandshakeServerCHACHA20SHA256(t *testing.T) {
849 test := &serverTest{
850 name: "CHACHA20-SHA256",
851 command: []string{"openssl", "s_client", "-no_ticket", "-ciphersuites", "TLS_CHACHA20_POLY1305_SHA256"},
852 }
853 runServerTestTLS13(t, test)
854 }
855
856 func TestHandshakeServerECDHEECDSAAES(t *testing.T) {
857 config := testConfig.Clone()
858 config.Certificates = make([]Certificate, 1)
859 config.Certificates[0].Certificate = [][]byte{testECDSACertificate}
860 config.Certificates[0].PrivateKey = testECDSAPrivateKey
861 config.BuildNameToCertificate()
862
863 test := &serverTest{
864 name: "ECDHE-ECDSA-AES",
865 command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "ECDHE-ECDSA-AES256-SHA", "-ciphersuites", "TLS_AES_128_GCM_SHA256"},
866 config: config,
867 }
868 runServerTestTLS10(t, test)
869 runServerTestTLS12(t, test)
870 runServerTestTLS13(t, test)
871 }
872
873 func TestHandshakeServerX25519(t *testing.T) {
874 config := testConfig.Clone()
875 config.CurvePreferences = []CurveID{X25519}
876
877 test := &serverTest{
878 name: "X25519",
879 command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "ECDHE-RSA-CHACHA20-POLY1305", "-ciphersuites", "TLS_CHACHA20_POLY1305_SHA256", "-curves", "X25519"},
880 config: config,
881 }
882 runServerTestTLS12(t, test)
883 runServerTestTLS13(t, test)
884 }
885
886 func TestHandshakeServerP256(t *testing.T) {
887 config := testConfig.Clone()
888 config.CurvePreferences = []CurveID{CurveP256}
889
890 test := &serverTest{
891 name: "P256",
892 command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "ECDHE-RSA-CHACHA20-POLY1305", "-ciphersuites", "TLS_CHACHA20_POLY1305_SHA256", "-curves", "P-256"},
893 config: config,
894 }
895 runServerTestTLS12(t, test)
896 runServerTestTLS13(t, test)
897 }
898
899 func TestHandshakeServerHelloRetryRequest(t *testing.T) {
900 config := testConfig.Clone()
901 config.CurvePreferences = []CurveID{CurveP256}
902
903 test := &serverTest{
904 name: "HelloRetryRequest",
905 command: []string{"openssl", "s_client", "-no_ticket", "-ciphersuites", "TLS_CHACHA20_POLY1305_SHA256", "-curves", "X25519:P-256"},
906 config: config,
907 }
908 runServerTestTLS13(t, test)
909 }
910
911 func TestHandshakeServerALPN(t *testing.T) {
912 config := testConfig.Clone()
913 config.NextProtos = []string{"proto1", "proto2"}
914
915 test := &serverTest{
916 name: "ALPN",
917
918
919 command: []string{"openssl", "s_client", "-alpn", "proto2,proto1", "-cipher", "ECDHE-RSA-CHACHA20-POLY1305", "-ciphersuites", "TLS_CHACHA20_POLY1305_SHA256"},
920 config: config,
921 validate: func(state ConnectionState) error {
922
923 if state.NegotiatedProtocol != "proto1" {
924 return fmt.Errorf("Got protocol %q, wanted proto1", state.NegotiatedProtocol)
925 }
926 return nil
927 },
928 }
929 runServerTestTLS12(t, test)
930 runServerTestTLS13(t, test)
931 }
932
933 func TestHandshakeServerALPNNoMatch(t *testing.T) {
934 config := testConfig.Clone()
935 config.NextProtos = []string{"proto3"}
936
937 test := &serverTest{
938 name: "ALPN-NoMatch",
939
940
941 command: []string{"openssl", "s_client", "-alpn", "proto2,proto1", "-cipher", "ECDHE-RSA-CHACHA20-POLY1305", "-ciphersuites", "TLS_CHACHA20_POLY1305_SHA256"},
942 config: config,
943 expectHandshakeErrorIncluding: "client requested unsupported application protocol",
944 }
945 runServerTestTLS12(t, test)
946 runServerTestTLS13(t, test)
947 }
948
949 func TestHandshakeServerALPNNotConfigured(t *testing.T) {
950 config := testConfig.Clone()
951 config.NextProtos = nil
952
953 test := &serverTest{
954 name: "ALPN-NotConfigured",
955
956
957 command: []string{"openssl", "s_client", "-alpn", "proto2,proto1", "-cipher", "ECDHE-RSA-CHACHA20-POLY1305", "-ciphersuites", "TLS_CHACHA20_POLY1305_SHA256"},
958 config: config,
959 validate: func(state ConnectionState) error {
960 if state.NegotiatedProtocol != "" {
961 return fmt.Errorf("Got protocol %q, wanted nothing", state.NegotiatedProtocol)
962 }
963 return nil
964 },
965 }
966 runServerTestTLS12(t, test)
967 runServerTestTLS13(t, test)
968 }
969
970 func TestHandshakeServerALPNFallback(t *testing.T) {
971 config := testConfig.Clone()
972 config.NextProtos = []string{"proto1", "h2", "proto2"}
973
974 test := &serverTest{
975 name: "ALPN-Fallback",
976
977
978 command: []string{"openssl", "s_client", "-alpn", "proto3,http/1.1,proto4", "-cipher", "ECDHE-RSA-CHACHA20-POLY1305", "-ciphersuites", "TLS_CHACHA20_POLY1305_SHA256"},
979 config: config,
980 validate: func(state ConnectionState) error {
981 if state.NegotiatedProtocol != "" {
982 return fmt.Errorf("Got protocol %q, wanted nothing", state.NegotiatedProtocol)
983 }
984 return nil
985 },
986 }
987 runServerTestTLS12(t, test)
988 runServerTestTLS13(t, test)
989 }
990
991
992
993
994 func TestHandshakeServerSNI(t *testing.T) {
995 test := &serverTest{
996 name: "SNI",
997 command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "AES128-SHA", "-servername", "snitest.com"},
998 }
999 runServerTestTLS12(t, test)
1000 }
1001
1002
1003
1004 func TestHandshakeServerSNIGetCertificate(t *testing.T) {
1005 config := testConfig.Clone()
1006
1007
1008 nameToCert := config.NameToCertificate
1009 config.NameToCertificate = nil
1010 config.GetCertificate = func(clientHello *ClientHelloInfo) (*Certificate, error) {
1011 cert := nameToCert[clientHello.ServerName]
1012 return cert, nil
1013 }
1014 test := &serverTest{
1015 name: "SNI-GetCertificate",
1016 command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "AES128-SHA", "-servername", "snitest.com"},
1017 config: config,
1018 }
1019 runServerTestTLS12(t, test)
1020 }
1021
1022
1023
1024
1025
1026 func TestHandshakeServerSNIGetCertificateNotFound(t *testing.T) {
1027 config := testConfig.Clone()
1028
1029 config.GetCertificate = func(clientHello *ClientHelloInfo) (*Certificate, error) {
1030 return nil, nil
1031 }
1032 test := &serverTest{
1033 name: "SNI-GetCertificateNotFound",
1034 command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "AES128-SHA", "-servername", "snitest.com"},
1035 config: config,
1036 }
1037 runServerTestTLS12(t, test)
1038 }
1039
1040
1041
1042 func TestHandshakeServerSNIGetCertificateError(t *testing.T) {
1043 const errMsg = "TestHandshakeServerSNIGetCertificateError error"
1044
1045 serverConfig := testConfig.Clone()
1046 serverConfig.GetCertificate = func(clientHello *ClientHelloInfo) (*Certificate, error) {
1047 return nil, errors.New(errMsg)
1048 }
1049
1050 clientHello := &clientHelloMsg{
1051 vers: VersionTLS10,
1052 random: make([]byte, 32),
1053 cipherSuites: []uint16{TLS_RSA_WITH_RC4_128_SHA},
1054 compressionMethods: []uint8{compressionNone},
1055 serverName: "test",
1056 }
1057 testClientHelloFailure(t, serverConfig, clientHello, errMsg)
1058 }
1059
1060
1061
1062 func TestHandshakeServerEmptyCertificates(t *testing.T) {
1063 const errMsg = "TestHandshakeServerEmptyCertificates error"
1064
1065 serverConfig := testConfig.Clone()
1066 serverConfig.GetCertificate = func(clientHello *ClientHelloInfo) (*Certificate, error) {
1067 return nil, errors.New(errMsg)
1068 }
1069 serverConfig.Certificates = nil
1070
1071 clientHello := &clientHelloMsg{
1072 vers: VersionTLS10,
1073 random: make([]byte, 32),
1074 cipherSuites: []uint16{TLS_RSA_WITH_RC4_128_SHA},
1075 compressionMethods: []uint8{compressionNone},
1076 }
1077 testClientHelloFailure(t, serverConfig, clientHello, errMsg)
1078
1079
1080
1081 serverConfig.GetCertificate = nil
1082
1083 clientHello = &clientHelloMsg{
1084 vers: VersionTLS10,
1085 random: make([]byte, 32),
1086 cipherSuites: []uint16{TLS_RSA_WITH_RC4_128_SHA},
1087 compressionMethods: []uint8{compressionNone},
1088 }
1089 testClientHelloFailure(t, serverConfig, clientHello, "no certificates")
1090 }
1091
1092 func TestServerResumption(t *testing.T) {
1093 sessionFilePath := tempFile("")
1094 defer os.Remove(sessionFilePath)
1095
1096 testIssue := &serverTest{
1097 name: "IssueTicket",
1098 command: []string{"openssl", "s_client", "-cipher", "AES128-SHA", "-ciphersuites", "TLS_AES_128_GCM_SHA256", "-sess_out", sessionFilePath},
1099 wait: true,
1100 }
1101 testResume := &serverTest{
1102 name: "Resume",
1103 command: []string{"openssl", "s_client", "-cipher", "AES128-SHA", "-ciphersuites", "TLS_AES_128_GCM_SHA256", "-sess_in", sessionFilePath},
1104 validate: func(state ConnectionState) error {
1105 if !state.DidResume {
1106 return errors.New("did not resume")
1107 }
1108 return nil
1109 },
1110 }
1111
1112 runServerTestTLS12(t, testIssue)
1113 runServerTestTLS12(t, testResume)
1114
1115 runServerTestTLS13(t, testIssue)
1116 runServerTestTLS13(t, testResume)
1117
1118 config := testConfig.Clone()
1119 config.CurvePreferences = []CurveID{CurveP256}
1120
1121 testResumeHRR := &serverTest{
1122 name: "Resume-HelloRetryRequest",
1123 command: []string{"openssl", "s_client", "-curves", "X25519:P-256", "-cipher", "AES128-SHA", "-ciphersuites",
1124 "TLS_AES_128_GCM_SHA256", "-sess_in", sessionFilePath},
1125 config: config,
1126 validate: func(state ConnectionState) error {
1127 if !state.DidResume {
1128 return errors.New("did not resume")
1129 }
1130 return nil
1131 },
1132 }
1133
1134 runServerTestTLS13(t, testResumeHRR)
1135 }
1136
1137 func TestServerResumptionDisabled(t *testing.T) {
1138 sessionFilePath := tempFile("")
1139 defer os.Remove(sessionFilePath)
1140
1141 config := testConfig.Clone()
1142
1143 testIssue := &serverTest{
1144 name: "IssueTicketPreDisable",
1145 command: []string{"openssl", "s_client", "-cipher", "AES128-SHA", "-ciphersuites", "TLS_AES_128_GCM_SHA256", "-sess_out", sessionFilePath},
1146 config: config,
1147 wait: true,
1148 }
1149 testResume := &serverTest{
1150 name: "ResumeDisabled",
1151 command: []string{"openssl", "s_client", "-cipher", "AES128-SHA", "-ciphersuites", "TLS_AES_128_GCM_SHA256", "-sess_in", sessionFilePath},
1152 config: config,
1153 validate: func(state ConnectionState) error {
1154 if state.DidResume {
1155 return errors.New("resumed with SessionTicketsDisabled")
1156 }
1157 return nil
1158 },
1159 }
1160
1161 config.SessionTicketsDisabled = false
1162 runServerTestTLS12(t, testIssue)
1163 config.SessionTicketsDisabled = true
1164 runServerTestTLS12(t, testResume)
1165
1166 config.SessionTicketsDisabled = false
1167 runServerTestTLS13(t, testIssue)
1168 config.SessionTicketsDisabled = true
1169 runServerTestTLS13(t, testResume)
1170 }
1171
1172 func TestFallbackSCSV(t *testing.T) {
1173 serverConfig := Config{
1174 Certificates: testConfig.Certificates,
1175 }
1176 test := &serverTest{
1177 name: "FallbackSCSV",
1178 config: &serverConfig,
1179
1180 command: []string{"openssl", "s_client", "-fallback_scsv"},
1181 expectHandshakeErrorIncluding: "inappropriate protocol fallback",
1182 }
1183 runServerTestTLS11(t, test)
1184 }
1185
1186 func TestHandshakeServerExportKeyingMaterial(t *testing.T) {
1187 test := &serverTest{
1188 name: "ExportKeyingMaterial",
1189 command: []string{"openssl", "s_client", "-cipher", "ECDHE-RSA-AES256-SHA", "-ciphersuites", "TLS_CHACHA20_POLY1305_SHA256"},
1190 config: testConfig.Clone(),
1191 validate: func(state ConnectionState) error {
1192 if km, err := state.ExportKeyingMaterial("test", nil, 42); err != nil {
1193 return fmt.Errorf("ExportKeyingMaterial failed: %v", err)
1194 } else if len(km) != 42 {
1195 return fmt.Errorf("Got %d bytes from ExportKeyingMaterial, wanted %d", len(km), 42)
1196 }
1197 return nil
1198 },
1199 }
1200 runServerTestTLS10(t, test)
1201 runServerTestTLS12(t, test)
1202 runServerTestTLS13(t, test)
1203 }
1204
1205 func TestHandshakeServerRSAPKCS1v15(t *testing.T) {
1206 test := &serverTest{
1207 name: "RSA-RSAPKCS1v15",
1208 command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "ECDHE-RSA-CHACHA20-POLY1305", "-sigalgs", "rsa_pkcs1_sha256"},
1209 }
1210 runServerTestTLS12(t, test)
1211 }
1212
1213 func TestHandshakeServerRSAPSS(t *testing.T) {
1214
1215
1216
1217 test := &serverTest{
1218 name: "RSA-RSAPSS",
1219 command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "ECDHE-RSA-CHACHA20-POLY1305", "-ciphersuites", "TLS_CHACHA20_POLY1305_SHA256", "-sigalgs", "rsa_pss_rsae_sha512:rsa_pss_rsae_sha256"},
1220 }
1221 runServerTestTLS12(t, test)
1222 runServerTestTLS13(t, test)
1223
1224 test = &serverTest{
1225 name: "RSA-RSAPSS-TooSmall",
1226 command: []string{"openssl", "s_client", "-no_ticket", "-ciphersuites", "TLS_CHACHA20_POLY1305_SHA256", "-sigalgs", "rsa_pss_rsae_sha512"},
1227 expectHandshakeErrorIncluding: "peer doesn't support any of the certificate's signature algorithms",
1228 }
1229 runServerTestTLS13(t, test)
1230 }
1231
1232 func TestHandshakeServerEd25519(t *testing.T) {
1233 config := testConfig.Clone()
1234 config.Certificates = make([]Certificate, 1)
1235 config.Certificates[0].Certificate = [][]byte{testEd25519Certificate}
1236 config.Certificates[0].PrivateKey = testEd25519PrivateKey
1237 config.BuildNameToCertificate()
1238
1239 test := &serverTest{
1240 name: "Ed25519",
1241 command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "ECDHE-ECDSA-CHACHA20-POLY1305", "-ciphersuites", "TLS_CHACHA20_POLY1305_SHA256"},
1242 config: config,
1243 }
1244 runServerTestTLS12(t, test)
1245 runServerTestTLS13(t, test)
1246 }
1247
1248 func benchmarkHandshakeServer(b *testing.B, version uint16, cipherSuite uint16, curve CurveID, cert []byte, key crypto.PrivateKey) {
1249 config := testConfig.Clone()
1250 config.CipherSuites = []uint16{cipherSuite}
1251 config.CurvePreferences = []CurveID{curve}
1252 config.Certificates = make([]Certificate, 1)
1253 config.Certificates[0].Certificate = [][]byte{cert}
1254 config.Certificates[0].PrivateKey = key
1255 config.BuildNameToCertificate()
1256
1257 clientConn, serverConn := localPipe(b)
1258 serverConn = &recordingConn{Conn: serverConn}
1259 go func() {
1260 config := testConfig.Clone()
1261 config.MaxVersion = version
1262 config.CurvePreferences = []CurveID{curve}
1263 client := Client(clientConn, config)
1264 client.Handshake()
1265 }()
1266 server := Server(serverConn, config)
1267 if err := server.Handshake(); err != nil {
1268 b.Fatalf("handshake failed: %v", err)
1269 }
1270 serverConn.Close()
1271 flows := serverConn.(*recordingConn).flows
1272
1273 feeder := make(chan struct{})
1274 clientConn, serverConn = localPipe(b)
1275
1276 go func() {
1277 for range feeder {
1278 for i, f := range flows {
1279 if i%2 == 0 {
1280 clientConn.Write(f)
1281 continue
1282 }
1283 ff := make([]byte, len(f))
1284 n, err := io.ReadFull(clientConn, ff)
1285 if err != nil {
1286 b.Errorf("#%d: %s\nRead %d, wanted %d, got %x, wanted %x\n", i+1, err, n, len(ff), ff[:n], f)
1287 }
1288 if !bytes.Equal(f, ff) {
1289 b.Errorf("#%d: mismatch on read: got:%x want:%x", i+1, ff, f)
1290 }
1291 }
1292 }
1293 }()
1294
1295 b.ResetTimer()
1296 for i := 0; i < b.N; i++ {
1297 feeder <- struct{}{}
1298 server := Server(serverConn, config)
1299 if err := server.Handshake(); err != nil {
1300 b.Fatalf("handshake failed: %v", err)
1301 }
1302 }
1303 close(feeder)
1304 }
1305
1306 func BenchmarkHandshakeServer(b *testing.B) {
1307 b.Run("RSA", func(b *testing.B) {
1308 benchmarkHandshakeServer(b, VersionTLS12, TLS_RSA_WITH_AES_128_GCM_SHA256,
1309 0, testRSACertificate, testRSAPrivateKey)
1310 })
1311 b.Run("ECDHE-P256-RSA", func(b *testing.B) {
1312 b.Run("TLSv13", func(b *testing.B) {
1313 benchmarkHandshakeServer(b, VersionTLS13, TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305,
1314 CurveP256, testRSACertificate, testRSAPrivateKey)
1315 })
1316 b.Run("TLSv12", func(b *testing.B) {
1317 benchmarkHandshakeServer(b, VersionTLS12, TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305,
1318 CurveP256, testRSACertificate, testRSAPrivateKey)
1319 })
1320 })
1321 b.Run("ECDHE-P256-ECDSA-P256", func(b *testing.B) {
1322 b.Run("TLSv13", func(b *testing.B) {
1323 benchmarkHandshakeServer(b, VersionTLS13, TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305,
1324 CurveP256, testP256Certificate, testP256PrivateKey)
1325 })
1326 b.Run("TLSv12", func(b *testing.B) {
1327 benchmarkHandshakeServer(b, VersionTLS12, TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305,
1328 CurveP256, testP256Certificate, testP256PrivateKey)
1329 })
1330 })
1331 b.Run("ECDHE-X25519-ECDSA-P256", func(b *testing.B) {
1332 b.Run("TLSv13", func(b *testing.B) {
1333 benchmarkHandshakeServer(b, VersionTLS13, TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305,
1334 X25519, testP256Certificate, testP256PrivateKey)
1335 })
1336 b.Run("TLSv12", func(b *testing.B) {
1337 benchmarkHandshakeServer(b, VersionTLS12, TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305,
1338 X25519, testP256Certificate, testP256PrivateKey)
1339 })
1340 })
1341 b.Run("ECDHE-P521-ECDSA-P521", func(b *testing.B) {
1342 if testECDSAPrivateKey.PublicKey.Curve != elliptic.P521() {
1343 b.Fatal("test ECDSA key doesn't use curve P-521")
1344 }
1345 b.Run("TLSv13", func(b *testing.B) {
1346 benchmarkHandshakeServer(b, VersionTLS13, TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305,
1347 CurveP521, testECDSACertificate, testECDSAPrivateKey)
1348 })
1349 b.Run("TLSv12", func(b *testing.B) {
1350 benchmarkHandshakeServer(b, VersionTLS12, TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305,
1351 CurveP521, testECDSACertificate, testECDSAPrivateKey)
1352 })
1353 })
1354 }
1355
1356 func TestClientAuth(t *testing.T) {
1357 var certPath, keyPath, ecdsaCertPath, ecdsaKeyPath, ed25519CertPath, ed25519KeyPath string
1358
1359 if *update {
1360 certPath = tempFile(clientCertificatePEM)
1361 defer os.Remove(certPath)
1362 keyPath = tempFile(clientKeyPEM)
1363 defer os.Remove(keyPath)
1364 ecdsaCertPath = tempFile(clientECDSACertificatePEM)
1365 defer os.Remove(ecdsaCertPath)
1366 ecdsaKeyPath = tempFile(clientECDSAKeyPEM)
1367 defer os.Remove(ecdsaKeyPath)
1368 ed25519CertPath = tempFile(clientEd25519CertificatePEM)
1369 defer os.Remove(ed25519CertPath)
1370 ed25519KeyPath = tempFile(clientEd25519KeyPEM)
1371 defer os.Remove(ed25519KeyPath)
1372 } else {
1373 t.Parallel()
1374 }
1375
1376 config := testConfig.Clone()
1377 config.ClientAuth = RequestClientCert
1378
1379 test := &serverTest{
1380 name: "ClientAuthRequestedNotGiven",
1381 command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "AES128-SHA", "-ciphersuites", "TLS_AES_128_GCM_SHA256"},
1382 config: config,
1383 }
1384 runServerTestTLS12(t, test)
1385 runServerTestTLS13(t, test)
1386
1387 test = &serverTest{
1388 name: "ClientAuthRequestedAndGiven",
1389 command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "AES128-SHA", "-ciphersuites", "TLS_AES_128_GCM_SHA256",
1390 "-cert", certPath, "-key", keyPath, "-client_sigalgs", "rsa_pss_rsae_sha256"},
1391 config: config,
1392 expectedPeerCerts: []string{clientCertificatePEM},
1393 }
1394 runServerTestTLS12(t, test)
1395 runServerTestTLS13(t, test)
1396
1397 test = &serverTest{
1398 name: "ClientAuthRequestedAndECDSAGiven",
1399 command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "AES128-SHA", "-ciphersuites", "TLS_AES_128_GCM_SHA256",
1400 "-cert", ecdsaCertPath, "-key", ecdsaKeyPath},
1401 config: config,
1402 expectedPeerCerts: []string{clientECDSACertificatePEM},
1403 }
1404 runServerTestTLS12(t, test)
1405 runServerTestTLS13(t, test)
1406
1407 test = &serverTest{
1408 name: "ClientAuthRequestedAndEd25519Given",
1409 command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "AES128-SHA", "-ciphersuites", "TLS_AES_128_GCM_SHA256",
1410 "-cert", ed25519CertPath, "-key", ed25519KeyPath},
1411 config: config,
1412 expectedPeerCerts: []string{clientEd25519CertificatePEM},
1413 }
1414 runServerTestTLS12(t, test)
1415 runServerTestTLS13(t, test)
1416
1417 test = &serverTest{
1418 name: "ClientAuthRequestedAndPKCS1v15Given",
1419 command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "AES128-SHA",
1420 "-cert", certPath, "-key", keyPath, "-client_sigalgs", "rsa_pkcs1_sha256"},
1421 config: config,
1422 expectedPeerCerts: []string{clientCertificatePEM},
1423 }
1424 runServerTestTLS12(t, test)
1425 }
1426
1427 func TestSNIGivenOnFailure(t *testing.T) {
1428 const expectedServerName = "test.testing"
1429
1430 clientHello := &clientHelloMsg{
1431 vers: VersionTLS10,
1432 random: make([]byte, 32),
1433 cipherSuites: []uint16{TLS_RSA_WITH_RC4_128_SHA},
1434 compressionMethods: []uint8{compressionNone},
1435 serverName: expectedServerName,
1436 }
1437
1438 serverConfig := testConfig.Clone()
1439
1440 serverConfig.CipherSuites = nil
1441
1442 c, s := localPipe(t)
1443 go func() {
1444 cli := Client(c, testConfig)
1445 cli.vers = clientHello.vers
1446 cli.writeRecord(recordTypeHandshake, clientHello.marshal())
1447 c.Close()
1448 }()
1449 conn := Server(s, serverConfig)
1450 ctx := context.Background()
1451 ch, err := conn.readClientHello(ctx)
1452 hs := serverHandshakeState{
1453 c: conn,
1454 ctx: ctx,
1455 clientHello: ch,
1456 }
1457 if err == nil {
1458 err = hs.processClientHello()
1459 }
1460 if err == nil {
1461 err = hs.pickCipherSuite()
1462 }
1463 defer s.Close()
1464
1465 if err == nil {
1466 t.Error("No error reported from server")
1467 }
1468
1469 cs := hs.c.ConnectionState()
1470 if cs.HandshakeComplete {
1471 t.Error("Handshake registered as complete")
1472 }
1473
1474 if cs.ServerName != expectedServerName {
1475 t.Errorf("Expected ServerName of %q, but got %q", expectedServerName, cs.ServerName)
1476 }
1477 }
1478
1479 var getConfigForClientTests = []struct {
1480 setup func(config *Config)
1481 callback func(clientHello *ClientHelloInfo) (*Config, error)
1482 errorSubstring string
1483 verify func(config *Config) error
1484 }{
1485 {
1486 nil,
1487 func(clientHello *ClientHelloInfo) (*Config, error) {
1488 return nil, nil
1489 },
1490 "",
1491 nil,
1492 },
1493 {
1494 nil,
1495 func(clientHello *ClientHelloInfo) (*Config, error) {
1496 return nil, errors.New("should bubble up")
1497 },
1498 "should bubble up",
1499 nil,
1500 },
1501 {
1502 nil,
1503 func(clientHello *ClientHelloInfo) (*Config, error) {
1504 config := testConfig.Clone()
1505
1506
1507 config.MaxVersion = VersionTLS11
1508 return config, nil
1509 },
1510 "client offered only unsupported versions",
1511 nil,
1512 },
1513 {
1514 func(config *Config) {
1515 for i := range config.SessionTicketKey {
1516 config.SessionTicketKey[i] = byte(i)
1517 }
1518 config.sessionTicketKeys = nil
1519 },
1520 func(clientHello *ClientHelloInfo) (*Config, error) {
1521 config := testConfig.Clone()
1522 for i := range config.SessionTicketKey {
1523 config.SessionTicketKey[i] = 0
1524 }
1525 config.sessionTicketKeys = nil
1526 return config, nil
1527 },
1528 "",
1529 func(config *Config) error {
1530 if config.SessionTicketKey == [32]byte{} {
1531 return fmt.Errorf("expected SessionTicketKey to be set")
1532 }
1533 return nil
1534 },
1535 },
1536 {
1537 func(config *Config) {
1538 var dummyKey [32]byte
1539 for i := range dummyKey {
1540 dummyKey[i] = byte(i)
1541 }
1542
1543 config.SetSessionTicketKeys([][32]byte{dummyKey})
1544 },
1545 func(clientHello *ClientHelloInfo) (*Config, error) {
1546 config := testConfig.Clone()
1547 config.sessionTicketKeys = nil
1548 return config, nil
1549 },
1550 "",
1551 func(config *Config) error {
1552 if config.SessionTicketKey == [32]byte{} {
1553 return fmt.Errorf("expected SessionTicketKey to be set")
1554 }
1555 return nil
1556 },
1557 },
1558 }
1559
1560 func TestGetConfigForClient(t *testing.T) {
1561 serverConfig := testConfig.Clone()
1562 clientConfig := testConfig.Clone()
1563 clientConfig.MinVersion = VersionTLS12
1564
1565 for i, test := range getConfigForClientTests {
1566 if test.setup != nil {
1567 test.setup(serverConfig)
1568 }
1569
1570 var configReturned *Config
1571 serverConfig.GetConfigForClient = func(clientHello *ClientHelloInfo) (*Config, error) {
1572 config, err := test.callback(clientHello)
1573 configReturned = config
1574 return config, err
1575 }
1576 c, s := localPipe(t)
1577 done := make(chan error)
1578
1579 go func() {
1580 defer s.Close()
1581 done <- Server(s, serverConfig).Handshake()
1582 }()
1583
1584 clientErr := Client(c, clientConfig).Handshake()
1585 c.Close()
1586
1587 serverErr := <-done
1588
1589 if len(test.errorSubstring) == 0 {
1590 if serverErr != nil || clientErr != nil {
1591 t.Errorf("test[%d]: expected no error but got serverErr: %q, clientErr: %q", i, serverErr, clientErr)
1592 }
1593 if test.verify != nil {
1594 if err := test.verify(configReturned); err != nil {
1595 t.Errorf("test[%d]: verify returned error: %v", i, err)
1596 }
1597 }
1598 } else {
1599 if serverErr == nil {
1600 t.Errorf("test[%d]: expected error containing %q but got no error", i, test.errorSubstring)
1601 } else if !strings.Contains(serverErr.Error(), test.errorSubstring) {
1602 t.Errorf("test[%d]: expected error to contain %q but it was %q", i, test.errorSubstring, serverErr)
1603 }
1604 }
1605 }
1606 }
1607
1608 func TestCloseServerConnectionOnIdleClient(t *testing.T) {
1609 clientConn, serverConn := localPipe(t)
1610 server := Server(serverConn, testConfig.Clone())
1611 go func() {
1612 clientConn.Write([]byte{'0'})
1613 server.Close()
1614 }()
1615 server.SetReadDeadline(time.Now().Add(time.Minute))
1616 err := server.Handshake()
1617 if err != nil {
1618 if err, ok := err.(net.Error); ok && err.Timeout() {
1619 t.Errorf("Expected a closed network connection error but got '%s'", err.Error())
1620 }
1621 } else {
1622 t.Errorf("Error expected, but no error returned")
1623 }
1624 }
1625
1626 func TestCloneHash(t *testing.T) {
1627 h1 := crypto.SHA256.New()
1628 h1.Write([]byte("test"))
1629 s1 := h1.Sum(nil)
1630 h2 := cloneHash(h1, crypto.SHA256)
1631 s2 := h2.Sum(nil)
1632 if !bytes.Equal(s1, s2) {
1633 t.Error("cloned hash generated a different sum")
1634 }
1635 }
1636
1637 func expectError(t *testing.T, err error, sub string) {
1638 if err == nil {
1639 t.Errorf(`expected error %q, got nil`, sub)
1640 } else if !strings.Contains(err.Error(), sub) {
1641 t.Errorf(`expected error %q, got %q`, sub, err)
1642 }
1643 }
1644
1645 func TestKeyTooSmallForRSAPSS(t *testing.T) {
1646 cert, err := X509KeyPair([]byte(`-----BEGIN CERTIFICATE-----
1647 MIIBcTCCARugAwIBAgIQGjQnkCFlUqaFlt6ixyz/tDANBgkqhkiG9w0BAQsFADAS
1648 MRAwDgYDVQQKEwdBY21lIENvMB4XDTE5MDExODIzMjMyOFoXDTIwMDExODIzMjMy
1649 OFowEjEQMA4GA1UEChMHQWNtZSBDbzBcMA0GCSqGSIb3DQEBAQUAA0sAMEgCQQDd
1650 ez1rFUDwax2HTxbcnFUP9AhcgEGMHVV2nn4VVEWFJB6I8C/Nkx0XyyQlrmFYBzEQ
1651 nIPhKls4T0hFoLvjJnXpAgMBAAGjTTBLMA4GA1UdDwEB/wQEAwIFoDATBgNVHSUE
1652 DDAKBggrBgEFBQcDATAMBgNVHRMBAf8EAjAAMBYGA1UdEQQPMA2CC2V4YW1wbGUu
1653 Y29tMA0GCSqGSIb3DQEBCwUAA0EAxDuUS+BrrS3c+h+k+fQPOmOScy6yTX9mHw0Q
1654 KbucGamXYEy0URIwOdO0tQ3LHPc1YGvYSPwkDjkjqECs2Vm/AA==
1655 -----END CERTIFICATE-----`), []byte(testingKey(`-----BEGIN RSA TESTING KEY-----
1656 MIIBOgIBAAJBAN17PWsVQPBrHYdPFtycVQ/0CFyAQYwdVXaefhVURYUkHojwL82T
1657 HRfLJCWuYVgHMRCcg+EqWzhPSEWgu+MmdekCAwEAAQJBALjQYNTdXF4CFBbXwUz/
1658 yt9QFDYT9B5WT/12jeGAe653gtYS6OOi/+eAkGmzg1GlRnw6fOfn+HYNFDORST7z
1659 4j0CIQDn2xz9hVWQEu9ee3vecNT3f60huDGTNoRhtqgweQGX0wIhAPSLj1VcRZEz
1660 nKpbtU22+PbIMSJ+e80fmY9LIPx5N4HTAiAthGSimMR9bloz0EY3GyuUEyqoDgMd
1661 hXxjuno2WesoJQIgemilbcALXpxsLmZLgcQ2KSmaVr7jb5ECx9R+hYKTw1sCIG4s
1662 T+E0J8wlH24pgwQHzy7Ko2qLwn1b5PW8ecrlvP1g
1663 -----END RSA TESTING KEY-----`)))
1664 if err != nil {
1665 t.Fatal(err)
1666 }
1667
1668 clientConn, serverConn := localPipe(t)
1669 client := Client(clientConn, testConfig)
1670 done := make(chan struct{})
1671 go func() {
1672 config := testConfig.Clone()
1673 config.Certificates = []Certificate{cert}
1674 config.MinVersion = VersionTLS13
1675 server := Server(serverConn, config)
1676 err := server.Handshake()
1677 expectError(t, err, "key size too small")
1678 close(done)
1679 }()
1680 err = client.Handshake()
1681 expectError(t, err, "handshake failure")
1682 <-done
1683 }
1684
1685 func TestMultipleCertificates(t *testing.T) {
1686 clientConfig := testConfig.Clone()
1687 clientConfig.CipherSuites = []uint16{TLS_RSA_WITH_AES_128_GCM_SHA256}
1688 clientConfig.MaxVersion = VersionTLS12
1689
1690 serverConfig := testConfig.Clone()
1691 serverConfig.Certificates = []Certificate{{
1692 Certificate: [][]byte{testECDSACertificate},
1693 PrivateKey: testECDSAPrivateKey,
1694 }, {
1695 Certificate: [][]byte{testRSACertificate},
1696 PrivateKey: testRSAPrivateKey,
1697 }}
1698
1699 _, clientState, err := testHandshake(t, clientConfig, serverConfig)
1700 if err != nil {
1701 t.Fatal(err)
1702 }
1703 if got := clientState.PeerCertificates[0].PublicKeyAlgorithm; got != x509.RSA {
1704 t.Errorf("expected RSA certificate, got %v", got)
1705 }
1706 }
1707
1708 func TestAESCipherReordering(t *testing.T) {
1709 currentAESSupport := hasAESGCMHardwareSupport
1710 defer func() { hasAESGCMHardwareSupport = currentAESSupport }()
1711
1712 tests := []struct {
1713 name string
1714 clientCiphers []uint16
1715 serverHasAESGCM bool
1716 serverCiphers []uint16
1717 expectedCipher uint16
1718 }{
1719 {
1720 name: "server has hardware AES, client doesn't (pick ChaCha)",
1721 clientCiphers: []uint16{
1722 TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305,
1723 TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
1724 TLS_RSA_WITH_AES_128_CBC_SHA,
1725 },
1726 serverHasAESGCM: true,
1727 expectedCipher: TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305,
1728 },
1729 {
1730 name: "client prefers AES-GCM, server doesn't have hardware AES (pick ChaCha)",
1731 clientCiphers: []uint16{
1732 TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
1733 TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305,
1734 TLS_RSA_WITH_AES_128_CBC_SHA,
1735 },
1736 serverHasAESGCM: false,
1737 expectedCipher: TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305,
1738 },
1739 {
1740 name: "client prefers AES-GCM, server has hardware AES (pick AES-GCM)",
1741 clientCiphers: []uint16{
1742 TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
1743 TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305,
1744 TLS_RSA_WITH_AES_128_CBC_SHA,
1745 },
1746 serverHasAESGCM: true,
1747 expectedCipher: TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
1748 },
1749 {
1750 name: "client prefers AES-GCM and sends GREASE, server has hardware AES (pick AES-GCM)",
1751 clientCiphers: []uint16{
1752 0x0A0A,
1753 TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
1754 TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305,
1755 TLS_RSA_WITH_AES_128_CBC_SHA,
1756 },
1757 serverHasAESGCM: true,
1758 expectedCipher: TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
1759 },
1760 {
1761 name: "client prefers AES-GCM and doesn't support ChaCha, server doesn't have hardware AES (pick AES-GCM)",
1762 clientCiphers: []uint16{
1763 TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
1764 TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
1765 TLS_RSA_WITH_AES_128_CBC_SHA,
1766 },
1767 serverHasAESGCM: false,
1768 expectedCipher: TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
1769 },
1770 {
1771 name: "client prefers AES-GCM and AES-CBC over ChaCha, server doesn't have hardware AES (pick ChaCha)",
1772 clientCiphers: []uint16{
1773 TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
1774 TLS_RSA_WITH_AES_128_CBC_SHA,
1775 TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305,
1776 },
1777 serverHasAESGCM: false,
1778 expectedCipher: TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305,
1779 },
1780 {
1781 name: "client prefers AES-GCM over ChaCha and sends GREASE, server doesn't have hardware AES (pick ChaCha)",
1782 clientCiphers: []uint16{
1783 0x0A0A,
1784 TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
1785 TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305,
1786 TLS_RSA_WITH_AES_128_CBC_SHA,
1787 },
1788 serverHasAESGCM: false,
1789 expectedCipher: TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305,
1790 },
1791 {
1792 name: "client supports multiple AES-GCM, server doesn't have hardware AES and doesn't support ChaCha (AES-GCM)",
1793 clientCiphers: []uint16{
1794 TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
1795 TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305,
1796 TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
1797 },
1798 serverHasAESGCM: false,
1799 serverCiphers: []uint16{
1800 TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
1801 TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
1802 },
1803 expectedCipher: TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
1804 },
1805 {
1806 name: "client prefers AES-GCM, server has hardware but doesn't support AES (pick ChaCha)",
1807 clientCiphers: []uint16{
1808 TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
1809 TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305,
1810 TLS_RSA_WITH_AES_128_CBC_SHA,
1811 },
1812 serverHasAESGCM: true,
1813 serverCiphers: []uint16{
1814 TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305,
1815 },
1816 expectedCipher: TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305,
1817 },
1818 }
1819
1820 for _, tc := range tests {
1821 t.Run(tc.name, func(t *testing.T) {
1822 hasAESGCMHardwareSupport = tc.serverHasAESGCM
1823 hs := &serverHandshakeState{
1824 c: &Conn{
1825 config: &Config{
1826 CipherSuites: tc.serverCiphers,
1827 },
1828 vers: VersionTLS12,
1829 },
1830 clientHello: &clientHelloMsg{
1831 cipherSuites: tc.clientCiphers,
1832 vers: VersionTLS12,
1833 },
1834 ecdheOk: true,
1835 rsaSignOk: true,
1836 rsaDecryptOk: true,
1837 }
1838
1839 err := hs.pickCipherSuite()
1840 if err != nil {
1841 t.Errorf("pickCipherSuite failed: %s", err)
1842 }
1843
1844 if tc.expectedCipher != hs.suite.id {
1845 t.Errorf("unexpected cipher chosen: want %d, got %d", tc.expectedCipher, hs.suite.id)
1846 }
1847 })
1848 }
1849 }
1850
1851 func TestAESCipherReorderingTLS13(t *testing.T) {
1852 currentAESSupport := hasAESGCMHardwareSupport
1853 defer func() { hasAESGCMHardwareSupport = currentAESSupport }()
1854
1855 tests := []struct {
1856 name string
1857 clientCiphers []uint16
1858 serverHasAESGCM bool
1859 expectedCipher uint16
1860 }{
1861 {
1862 name: "server has hardware AES, client doesn't (pick ChaCha)",
1863 clientCiphers: []uint16{
1864 TLS_CHACHA20_POLY1305_SHA256,
1865 TLS_AES_128_GCM_SHA256,
1866 },
1867 serverHasAESGCM: true,
1868 expectedCipher: TLS_CHACHA20_POLY1305_SHA256,
1869 },
1870 {
1871 name: "neither server nor client have hardware AES (pick ChaCha)",
1872 clientCiphers: []uint16{
1873 TLS_CHACHA20_POLY1305_SHA256,
1874 TLS_AES_128_GCM_SHA256,
1875 },
1876 serverHasAESGCM: false,
1877 expectedCipher: TLS_CHACHA20_POLY1305_SHA256,
1878 },
1879 {
1880 name: "client prefers AES, server doesn't have hardware (pick ChaCha)",
1881 clientCiphers: []uint16{
1882 TLS_AES_128_GCM_SHA256,
1883 TLS_CHACHA20_POLY1305_SHA256,
1884 },
1885 serverHasAESGCM: false,
1886 expectedCipher: TLS_CHACHA20_POLY1305_SHA256,
1887 },
1888 {
1889 name: "client prefers AES and sends GREASE, server doesn't have hardware (pick ChaCha)",
1890 clientCiphers: []uint16{
1891 0x0A0A,
1892 TLS_AES_128_GCM_SHA256,
1893 TLS_CHACHA20_POLY1305_SHA256,
1894 },
1895 serverHasAESGCM: false,
1896 expectedCipher: TLS_CHACHA20_POLY1305_SHA256,
1897 },
1898 {
1899 name: "client prefers AES, server has hardware AES (pick AES)",
1900 clientCiphers: []uint16{
1901 TLS_AES_128_GCM_SHA256,
1902 TLS_CHACHA20_POLY1305_SHA256,
1903 },
1904 serverHasAESGCM: true,
1905 expectedCipher: TLS_AES_128_GCM_SHA256,
1906 },
1907 {
1908 name: "client prefers AES and sends GREASE, server has hardware AES (pick AES)",
1909 clientCiphers: []uint16{
1910 0x0A0A,
1911 TLS_AES_128_GCM_SHA256,
1912 TLS_CHACHA20_POLY1305_SHA256,
1913 },
1914 serverHasAESGCM: true,
1915 expectedCipher: TLS_AES_128_GCM_SHA256,
1916 },
1917 }
1918
1919 for _, tc := range tests {
1920 t.Run(tc.name, func(t *testing.T) {
1921 hasAESGCMHardwareSupport = tc.serverHasAESGCM
1922 hs := &serverHandshakeStateTLS13{
1923 c: &Conn{
1924 config: &Config{},
1925 vers: VersionTLS13,
1926 },
1927 clientHello: &clientHelloMsg{
1928 cipherSuites: tc.clientCiphers,
1929 supportedVersions: []uint16{VersionTLS13},
1930 compressionMethods: []uint8{compressionNone},
1931 keyShares: []keyShare{{group: X25519, data: curve25519.Basepoint}},
1932 },
1933 }
1934
1935 err := hs.processClientHello()
1936 if err != nil {
1937 t.Errorf("pickCipherSuite failed: %s", err)
1938 }
1939
1940 if tc.expectedCipher != hs.suite.id {
1941 t.Errorf("unexpected cipher chosen: want %d, got %d", tc.expectedCipher, hs.suite.id)
1942 }
1943 })
1944 }
1945 }
1946
1947
1948
1949
1950 func TestServerHandshakeContextCancellation(t *testing.T) {
1951 c, s := localPipe(t)
1952 ctx, cancel := context.WithCancel(context.Background())
1953 unblockClient := make(chan struct{})
1954 defer close(unblockClient)
1955 go func() {
1956 cancel()
1957 <-unblockClient
1958 _ = c.Close()
1959 }()
1960 conn := Server(s, testConfig)
1961
1962
1963 err := conn.HandshakeContext(ctx)
1964 if err == nil {
1965 t.Fatal("Server handshake did not error when the context was canceled")
1966 }
1967 if err != context.Canceled {
1968 t.Errorf("Unexpected server handshake error: %v", err)
1969 }
1970 if runtime.GOARCH == "wasm" {
1971 t.Skip("conn.Close does not error as expected when called multiple times on WASM")
1972 }
1973 err = conn.Close()
1974 if err == nil {
1975 t.Error("Server connection was not closed when the context was canceled")
1976 }
1977 }
1978
1979
1980
1981
1982
1983
1984 func TestHandshakeContextHierarchy(t *testing.T) {
1985 c, s := localPipe(t)
1986 clientErr := make(chan error, 1)
1987 clientConfig := testConfig.Clone()
1988 serverConfig := testConfig.Clone()
1989 ctx, cancel := context.WithCancel(context.Background())
1990 defer cancel()
1991 key := struct{}{}
1992 ctx = context.WithValue(ctx, key, true)
1993 go func() {
1994 defer close(clientErr)
1995 defer c.Close()
1996 var innerCtx context.Context
1997 clientConfig.Certificates = nil
1998 clientConfig.GetClientCertificate = func(certificateRequest *CertificateRequestInfo) (*Certificate, error) {
1999 if val, ok := certificateRequest.Context().Value(key).(bool); !ok || !val {
2000 t.Errorf("GetClientCertificate context was not child of HandshakeContext")
2001 }
2002 innerCtx = certificateRequest.Context()
2003 return &Certificate{
2004 Certificate: [][]byte{testRSACertificate},
2005 PrivateKey: testRSAPrivateKey,
2006 }, nil
2007 }
2008 cli := Client(c, clientConfig)
2009 err := cli.HandshakeContext(ctx)
2010 if err != nil {
2011 clientErr <- err
2012 return
2013 }
2014 select {
2015 case <-innerCtx.Done():
2016 default:
2017 t.Errorf("GetClientCertificate context was not canceled after HandshakeContext returned.")
2018 }
2019 }()
2020 var innerCtx context.Context
2021 serverConfig.Certificates = nil
2022 serverConfig.ClientAuth = RequestClientCert
2023 serverConfig.GetCertificate = func(clientHello *ClientHelloInfo) (*Certificate, error) {
2024 if val, ok := clientHello.Context().Value(key).(bool); !ok || !val {
2025 t.Errorf("GetClientCertificate context was not child of HandshakeContext")
2026 }
2027 innerCtx = clientHello.Context()
2028 return &Certificate{
2029 Certificate: [][]byte{testRSACertificate},
2030 PrivateKey: testRSAPrivateKey,
2031 }, nil
2032 }
2033 conn := Server(s, serverConfig)
2034 err := conn.HandshakeContext(ctx)
2035 if err != nil {
2036 t.Errorf("Unexpected server handshake error: %v", err)
2037 }
2038 select {
2039 case <-innerCtx.Done():
2040 default:
2041 t.Errorf("GetCertificate context was not canceled after HandshakeContext returned.")
2042 }
2043 if err := <-clientErr; err != nil {
2044 t.Errorf("Unexpected client error: %v", err)
2045 }
2046 }
2047
View as plain text