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