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 "sync/atomic"
27 "testing"
28 "time"
29 )
30
31 func testClientHello(t *testing.T, serverConfig *Config, m handshakeMessage) {
32 t.Helper()
33 testClientHelloFailure(t, serverConfig, m, "")
34 }
35
36
37
38 func testFatal(t *testing.T, err error) {
39 t.Helper()
40 t.Fatal(err)
41 }
42
43 func testClientHelloFailure(t *testing.T, serverConfig *Config, m handshakeMessage, expectedSubStr string) {
44 c, s := localPipe(t)
45 go func() {
46 cli := Client(c, testConfig)
47 if ch, ok := m.(*clientHelloMsg); ok {
48 cli.vers = ch.vers
49 }
50 if _, err := cli.writeHandshakeRecord(m, nil); err != nil {
51 testFatal(t, err)
52 }
53 c.Close()
54 }()
55 ctx := context.Background()
56 conn := Server(s, serverConfig)
57 ch, err := conn.readClientHello(ctx)
58 if conn.vers == VersionTLS13 {
59 hs := serverHandshakeStateTLS13{
60 c: conn,
61 ctx: ctx,
62 clientHello: ch,
63 }
64 if err == nil {
65 err = hs.processClientHello()
66 }
67 if err == nil {
68 err = hs.checkForResumption()
69 }
70 if err == nil {
71 err = hs.pickCertificate()
72 }
73 } else {
74 hs := serverHandshakeState{
75 c: conn,
76 ctx: ctx,
77 clientHello: ch,
78 }
79 if err == nil {
80 err = hs.processClientHello()
81 }
82 if err == nil {
83 err = hs.pickCipherSuite()
84 }
85 }
86 s.Close()
87 t.Helper()
88 if len(expectedSubStr) == 0 {
89 if err != nil && err != io.EOF {
90 t.Errorf("Got error: %s; expected to succeed", err)
91 }
92 } else if err == nil || !strings.Contains(err.Error(), expectedSubStr) {
93 t.Errorf("Got error: %v; expected to match substring '%s'", err, expectedSubStr)
94 }
95 }
96
97 func TestSimpleError(t *testing.T) {
98 testClientHelloFailure(t, testConfig, &serverHelloDoneMsg{}, "unexpected handshake message")
99 }
100
101 var badProtocolVersions = []uint16{0x0000, 0x0005, 0x0100, 0x0105, 0x0200, 0x0205, VersionSSL30}
102
103 func TestRejectBadProtocolVersion(t *testing.T) {
104 config := testConfig.Clone()
105 config.MinVersion = VersionSSL30
106 for _, v := range badProtocolVersions {
107 testClientHelloFailure(t, config, &clientHelloMsg{
108 vers: v,
109 random: make([]byte, 32),
110 }, "unsupported versions")
111 }
112 testClientHelloFailure(t, config, &clientHelloMsg{
113 vers: VersionTLS12,
114 supportedVersions: badProtocolVersions,
115 random: make([]byte, 32),
116 }, "unsupported versions")
117 }
118
119 func TestNoSuiteOverlap(t *testing.T) {
120 clientHello := &clientHelloMsg{
121 vers: VersionTLS10,
122 random: make([]byte, 32),
123 cipherSuites: []uint16{0xff00},
124 compressionMethods: []uint8{compressionNone},
125 }
126 testClientHelloFailure(t, testConfig, clientHello, "no cipher suite supported by both client and server")
127 }
128
129 func TestNoCompressionOverlap(t *testing.T) {
130 clientHello := &clientHelloMsg{
131 vers: VersionTLS10,
132 random: make([]byte, 32),
133 cipherSuites: []uint16{TLS_RSA_WITH_RC4_128_SHA},
134 compressionMethods: []uint8{0xff},
135 }
136 testClientHelloFailure(t, testConfig, clientHello, "client does not support uncompressed connections")
137 }
138
139 func TestNoRC4ByDefault(t *testing.T) {
140 clientHello := &clientHelloMsg{
141 vers: VersionTLS10,
142 random: make([]byte, 32),
143 cipherSuites: []uint16{TLS_RSA_WITH_RC4_128_SHA},
144 compressionMethods: []uint8{compressionNone},
145 }
146 serverConfig := testConfig.Clone()
147
148
149 serverConfig.CipherSuites = nil
150 testClientHelloFailure(t, serverConfig, clientHello, "no cipher suite supported by both client and server")
151 }
152
153 func TestRejectSNIWithTrailingDot(t *testing.T) {
154 testClientHelloFailure(t, testConfig, &clientHelloMsg{
155 vers: VersionTLS12,
156 random: make([]byte, 32),
157 serverName: "foo.com.",
158 }, "unexpected message")
159 }
160
161 func TestDontSelectECDSAWithRSAKey(t *testing.T) {
162
163
164 clientHello := &clientHelloMsg{
165 vers: VersionTLS10,
166 random: make([]byte, 32),
167 cipherSuites: []uint16{TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA},
168 compressionMethods: []uint8{compressionNone},
169 supportedCurves: []CurveID{CurveP256},
170 supportedPoints: []uint8{pointFormatUncompressed},
171 }
172 serverConfig := testConfig.Clone()
173 serverConfig.CipherSuites = clientHello.cipherSuites
174 serverConfig.Certificates = make([]Certificate, 1)
175 serverConfig.Certificates[0].Certificate = [][]byte{testECDSACertificate}
176 serverConfig.Certificates[0].PrivateKey = testECDSAPrivateKey
177 serverConfig.BuildNameToCertificate()
178
179 testClientHello(t, serverConfig, clientHello)
180
181
182
183 serverConfig.Certificates = testConfig.Certificates
184 testClientHelloFailure(t, serverConfig, clientHello, "no cipher suite supported by both client and server")
185 }
186
187 func TestDontSelectRSAWithECDSAKey(t *testing.T) {
188
189
190 clientHello := &clientHelloMsg{
191 vers: VersionTLS10,
192 random: make([]byte, 32),
193 cipherSuites: []uint16{TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA},
194 compressionMethods: []uint8{compressionNone},
195 supportedCurves: []CurveID{CurveP256},
196 supportedPoints: []uint8{pointFormatUncompressed},
197 }
198 serverConfig := testConfig.Clone()
199 serverConfig.CipherSuites = clientHello.cipherSuites
200
201 testClientHello(t, serverConfig, clientHello)
202
203
204
205 serverConfig.Certificates = make([]Certificate, 1)
206 serverConfig.Certificates[0].Certificate = [][]byte{testECDSACertificate}
207 serverConfig.Certificates[0].PrivateKey = testECDSAPrivateKey
208 serverConfig.BuildNameToCertificate()
209 testClientHelloFailure(t, serverConfig, clientHello, "no cipher suite supported by both client and server")
210 }
211
212 func TestRenegotiationExtension(t *testing.T) {
213 clientHello := &clientHelloMsg{
214 vers: VersionTLS12,
215 compressionMethods: []uint8{compressionNone},
216 random: make([]byte, 32),
217 secureRenegotiationSupported: true,
218 cipherSuites: []uint16{TLS_RSA_WITH_RC4_128_SHA},
219 }
220
221 bufChan := make(chan []byte, 1)
222 c, s := localPipe(t)
223
224 go func() {
225 cli := Client(c, testConfig)
226 cli.vers = clientHello.vers
227 if _, err := cli.writeHandshakeRecord(clientHello, nil); err != nil {
228 testFatal(t, err)
229 }
230
231 buf := make([]byte, 1024)
232 n, err := c.Read(buf)
233 if err != nil {
234 t.Errorf("Server read returned error: %s", err)
235 return
236 }
237 c.Close()
238 bufChan <- buf[:n]
239 }()
240
241 Server(s, testConfig).Handshake()
242 buf := <-bufChan
243
244 if len(buf) < 5+4 {
245 t.Fatalf("Server returned short message of length %d", len(buf))
246 }
247
248
249
250 serverHelloLen := int(buf[6])<<16 | int(buf[7])<<8 | int(buf[8])
251
252 var serverHello serverHelloMsg
253
254
255 if !serverHello.unmarshal(buf[5 : 9+serverHelloLen]) {
256 t.Fatalf("Failed to parse ServerHello")
257 }
258
259 if !serverHello.secureRenegotiationSupported {
260 t.Errorf("Secure renegotiation extension was not echoed.")
261 }
262 }
263
264 func TestTLS12OnlyCipherSuites(t *testing.T) {
265
266
267 clientHello := &clientHelloMsg{
268 vers: VersionTLS11,
269 random: make([]byte, 32),
270 cipherSuites: []uint16{
271
272
273
274
275 TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
276 TLS_RSA_WITH_RC4_128_SHA,
277 },
278 compressionMethods: []uint8{compressionNone},
279 supportedCurves: []CurveID{CurveP256, CurveP384, CurveP521},
280 supportedPoints: []uint8{pointFormatUncompressed},
281 }
282
283 c, s := localPipe(t)
284 replyChan := make(chan any)
285 go func() {
286 cli := Client(c, testConfig)
287 cli.vers = clientHello.vers
288 if _, err := cli.writeHandshakeRecord(clientHello, nil); err != nil {
289 testFatal(t, err)
290 }
291 reply, err := cli.readHandshake(nil)
292 c.Close()
293 if err != nil {
294 replyChan <- err
295 } else {
296 replyChan <- reply
297 }
298 }()
299 config := testConfig.Clone()
300 config.CipherSuites = clientHello.cipherSuites
301 Server(s, config).Handshake()
302 s.Close()
303 reply := <-replyChan
304 if err, ok := reply.(error); ok {
305 t.Fatal(err)
306 }
307 serverHello, ok := reply.(*serverHelloMsg)
308 if !ok {
309 t.Fatalf("didn't get ServerHello message in reply. Got %v\n", reply)
310 }
311 if s := serverHello.cipherSuite; s != TLS_RSA_WITH_RC4_128_SHA {
312 t.Fatalf("bad cipher suite from server: %x", s)
313 }
314 }
315
316 func TestTLSPointFormats(t *testing.T) {
317
318
319 tests := []struct {
320 name string
321 cipherSuites []uint16
322 supportedCurves []CurveID
323 supportedPoints []uint8
324 wantSupportedPoints bool
325 }{
326 {"ECC", []uint16{TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA}, []CurveID{CurveP256}, []uint8{pointFormatUncompressed}, true},
327 {"ECC without ec_point_format", []uint16{TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA}, []CurveID{CurveP256}, nil, false},
328 {"ECC with extra values", []uint16{TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA}, []CurveID{CurveP256}, []uint8{13, 37, pointFormatUncompressed, 42}, true},
329 {"RSA", []uint16{TLS_RSA_WITH_AES_256_GCM_SHA384}, nil, nil, false},
330 {"RSA with ec_point_format", []uint16{TLS_RSA_WITH_AES_256_GCM_SHA384}, nil, []uint8{pointFormatUncompressed}, false},
331 }
332 for _, tt := range tests {
333 t.Run(tt.name, func(t *testing.T) {
334 clientHello := &clientHelloMsg{
335 vers: VersionTLS12,
336 random: make([]byte, 32),
337 cipherSuites: tt.cipherSuites,
338 compressionMethods: []uint8{compressionNone},
339 supportedCurves: tt.supportedCurves,
340 supportedPoints: tt.supportedPoints,
341 }
342
343 c, s := localPipe(t)
344 replyChan := make(chan any)
345 go func() {
346 cli := Client(c, testConfig)
347 cli.vers = clientHello.vers
348 if _, err := cli.writeHandshakeRecord(clientHello, nil); err != nil {
349 testFatal(t, err)
350 }
351 reply, err := cli.readHandshake(nil)
352 c.Close()
353 if err != nil {
354 replyChan <- err
355 } else {
356 replyChan <- reply
357 }
358 }()
359 config := testConfig.Clone()
360 config.CipherSuites = clientHello.cipherSuites
361 Server(s, config).Handshake()
362 s.Close()
363 reply := <-replyChan
364 if err, ok := reply.(error); ok {
365 t.Fatal(err)
366 }
367 serverHello, ok := reply.(*serverHelloMsg)
368 if !ok {
369 t.Fatalf("didn't get ServerHello message in reply. Got %v\n", reply)
370 }
371 if tt.wantSupportedPoints {
372 if !bytes.Equal(serverHello.supportedPoints, []uint8{pointFormatUncompressed}) {
373 t.Fatal("incorrect ec_point_format extension from server")
374 }
375 } else {
376 if len(serverHello.supportedPoints) != 0 {
377 t.Fatalf("unexpected ec_point_format extension from server: %v", serverHello.supportedPoints)
378 }
379 }
380 })
381 }
382 }
383
384 func TestAlertForwarding(t *testing.T) {
385 c, s := localPipe(t)
386 go func() {
387 Client(c, testConfig).sendAlert(alertUnknownCA)
388 c.Close()
389 }()
390
391 err := Server(s, testConfig).Handshake()
392 s.Close()
393 var opErr *net.OpError
394 if !errors.As(err, &opErr) || opErr.Err != error(alertUnknownCA) {
395 t.Errorf("Got error: %s; expected: %s", err, error(alertUnknownCA))
396 }
397 }
398
399 func TestClose(t *testing.T) {
400 c, s := localPipe(t)
401 go c.Close()
402
403 err := Server(s, testConfig).Handshake()
404 s.Close()
405 if err != io.EOF {
406 t.Errorf("Got error: %s; expected: %s", err, io.EOF)
407 }
408 }
409
410 func TestVersion(t *testing.T) {
411 serverConfig := &Config{
412 Certificates: testConfig.Certificates,
413 MaxVersion: VersionTLS13,
414 }
415 clientConfig := &Config{
416 InsecureSkipVerify: true,
417 MinVersion: VersionTLS12,
418 }
419 state, _, err := testHandshake(t, clientConfig, serverConfig)
420 if err != nil {
421 t.Fatalf("handshake failed: %s", err)
422 }
423 if state.Version != VersionTLS13 {
424 t.Fatalf("incorrect version %x, should be %x", state.Version, VersionTLS11)
425 }
426
427 clientConfig.MinVersion = 0
428 serverConfig.MaxVersion = VersionTLS11
429 _, _, err = testHandshake(t, clientConfig, serverConfig)
430 if err == nil {
431 t.Fatalf("expected failure to connect with TLS 1.0/1.1")
432 }
433 }
434
435 func TestCipherSuitePreference(t *testing.T) {
436 serverConfig := &Config{
437 CipherSuites: []uint16{TLS_RSA_WITH_RC4_128_SHA, TLS_AES_128_GCM_SHA256,
438 TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256},
439 Certificates: testConfig.Certificates,
440 MaxVersion: VersionTLS12,
441 GetConfigForClient: func(chi *ClientHelloInfo) (*Config, error) {
442 if chi.CipherSuites[0] != TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256 {
443 t.Error("the advertised order should not depend on Config.CipherSuites")
444 }
445 if len(chi.CipherSuites) != 2+len(defaultCipherSuitesTLS13) {
446 t.Error("the advertised TLS 1.2 suites should be filtered by Config.CipherSuites")
447 }
448 return nil, nil
449 },
450 }
451 clientConfig := &Config{
452 CipherSuites: []uint16{TLS_RSA_WITH_AES_128_CBC_SHA, TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256},
453 InsecureSkipVerify: true,
454 }
455 state, _, err := testHandshake(t, clientConfig, serverConfig)
456 if err != nil {
457 t.Fatalf("handshake failed: %s", err)
458 }
459 if state.CipherSuite != TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256 {
460 t.Error("the preference order should not depend on Config.CipherSuites")
461 }
462 }
463
464 func TestSCTHandshake(t *testing.T) {
465 t.Run("TLSv12", func(t *testing.T) { testSCTHandshake(t, VersionTLS12) })
466 t.Run("TLSv13", func(t *testing.T) { testSCTHandshake(t, VersionTLS13) })
467 }
468
469 func testSCTHandshake(t *testing.T, version uint16) {
470 expected := [][]byte{[]byte("certificate"), []byte("transparency")}
471 serverConfig := &Config{
472 Certificates: []Certificate{{
473 Certificate: [][]byte{testRSACertificate},
474 PrivateKey: testRSAPrivateKey,
475 SignedCertificateTimestamps: expected,
476 }},
477 MaxVersion: version,
478 }
479 clientConfig := &Config{
480 InsecureSkipVerify: true,
481 }
482 _, state, err := testHandshake(t, clientConfig, serverConfig)
483 if err != nil {
484 t.Fatalf("handshake failed: %s", err)
485 }
486 actual := state.SignedCertificateTimestamps
487 if len(actual) != len(expected) {
488 t.Fatalf("got %d scts, want %d", len(actual), len(expected))
489 }
490 for i, sct := range expected {
491 if !bytes.Equal(sct, actual[i]) {
492 t.Fatalf("SCT #%d was %x, but expected %x", i, actual[i], sct)
493 }
494 }
495 }
496
497 func TestCrossVersionResume(t *testing.T) {
498 t.Run("TLSv12", func(t *testing.T) { testCrossVersionResume(t, VersionTLS12) })
499 t.Run("TLSv13", func(t *testing.T) { testCrossVersionResume(t, VersionTLS13) })
500 }
501
502 func testCrossVersionResume(t *testing.T, version uint16) {
503 serverConfig := &Config{
504 CipherSuites: []uint16{TLS_RSA_WITH_AES_128_CBC_SHA},
505 Certificates: testConfig.Certificates,
506 }
507 clientConfig := &Config{
508 CipherSuites: []uint16{TLS_RSA_WITH_AES_128_CBC_SHA},
509 InsecureSkipVerify: true,
510 ClientSessionCache: NewLRUClientSessionCache(1),
511 ServerName: "servername",
512 MinVersion: VersionTLS12,
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
1074 func TestHandshakeServerGetCertificateExtensions(t *testing.T) {
1075 const errMsg = "TestHandshakeServerGetCertificateExtensions error"
1076
1077
1078 var called atomic.Int32
1079
1080 testVersions := []uint16{VersionTLS12, VersionTLS13}
1081 for _, vers := range testVersions {
1082 t.Run(fmt.Sprintf("TLS version %04x", vers), func(t *testing.T) {
1083 pk, _ := ecdh.X25519().GenerateKey(rand.Reader)
1084 clientHello := &clientHelloMsg{
1085 vers: vers,
1086 random: make([]byte, 32),
1087 cipherSuites: []uint16{TLS_CHACHA20_POLY1305_SHA256},
1088 compressionMethods: []uint8{compressionNone},
1089 serverName: "test",
1090 keyShares: []keyShare{{group: X25519, data: pk.PublicKey().Bytes()}},
1091 supportedCurves: []CurveID{X25519},
1092 supportedSignatureAlgorithms: []SignatureScheme{Ed25519},
1093 }
1094
1095
1096
1097 expectedExtensions := []uint16{
1098 extensionServerName,
1099 extensionSupportedCurves,
1100 extensionSignatureAlgorithms,
1101 extensionKeyShare,
1102 }
1103
1104 if vers == VersionTLS13 {
1105 clientHello.supportedVersions = []uint16{VersionTLS13}
1106 expectedExtensions = append(expectedExtensions, extensionSupportedVersions)
1107 }
1108
1109
1110 slices.Sort(expectedExtensions)
1111
1112 serverConfig := testConfig.Clone()
1113 serverConfig.GetCertificate = func(clientHello *ClientHelloInfo) (*Certificate, error) {
1114 if !slices.Equal(expectedExtensions, clientHello.Extensions) {
1115 t.Errorf("expected extensions on ClientHelloInfo (%v) to match clientHelloMsg (%v)", expectedExtensions, clientHello.Extensions)
1116 }
1117 called.Add(1)
1118
1119 return nil, errors.New(errMsg)
1120 }
1121 testClientHelloFailure(t, serverConfig, clientHello, errMsg)
1122 })
1123 }
1124
1125 if int(called.Load()) != len(testVersions) {
1126 t.Error("expected our GetCertificate test to be called twice")
1127 }
1128 }
1129
1130
1131
1132 func TestHandshakeServerSNIGetCertificateError(t *testing.T) {
1133 const errMsg = "TestHandshakeServerSNIGetCertificateError error"
1134
1135 serverConfig := testConfig.Clone()
1136 serverConfig.GetCertificate = func(clientHello *ClientHelloInfo) (*Certificate, error) {
1137 return nil, errors.New(errMsg)
1138 }
1139
1140 clientHello := &clientHelloMsg{
1141 vers: VersionTLS10,
1142 random: make([]byte, 32),
1143 cipherSuites: []uint16{TLS_RSA_WITH_RC4_128_SHA},
1144 compressionMethods: []uint8{compressionNone},
1145 serverName: "test",
1146 }
1147 testClientHelloFailure(t, serverConfig, clientHello, errMsg)
1148 }
1149
1150
1151
1152 func TestHandshakeServerEmptyCertificates(t *testing.T) {
1153 const errMsg = "TestHandshakeServerEmptyCertificates error"
1154
1155 serverConfig := testConfig.Clone()
1156 serverConfig.GetCertificate = func(clientHello *ClientHelloInfo) (*Certificate, error) {
1157 return nil, errors.New(errMsg)
1158 }
1159 serverConfig.Certificates = nil
1160
1161 clientHello := &clientHelloMsg{
1162 vers: VersionTLS10,
1163 random: make([]byte, 32),
1164 cipherSuites: []uint16{TLS_RSA_WITH_RC4_128_SHA},
1165 compressionMethods: []uint8{compressionNone},
1166 }
1167 testClientHelloFailure(t, serverConfig, clientHello, errMsg)
1168
1169
1170
1171 serverConfig.GetCertificate = nil
1172
1173 clientHello = &clientHelloMsg{
1174 vers: VersionTLS10,
1175 random: make([]byte, 32),
1176 cipherSuites: []uint16{TLS_RSA_WITH_RC4_128_SHA},
1177 compressionMethods: []uint8{compressionNone},
1178 }
1179 testClientHelloFailure(t, serverConfig, clientHello, "no certificates")
1180 }
1181
1182 func TestServerResumption(t *testing.T) {
1183 sessionFilePath := tempFile("")
1184 defer os.Remove(sessionFilePath)
1185
1186 testIssue := &serverTest{
1187 name: "IssueTicket",
1188 command: []string{"openssl", "s_client", "-cipher", "AES128-SHA", "-ciphersuites", "TLS_AES_128_GCM_SHA256", "-sess_out", sessionFilePath},
1189 wait: true,
1190 }
1191 testResume := &serverTest{
1192 name: "Resume",
1193 command: []string{"openssl", "s_client", "-cipher", "AES128-SHA", "-ciphersuites", "TLS_AES_128_GCM_SHA256", "-sess_in", sessionFilePath},
1194 validate: func(state ConnectionState) error {
1195 if !state.DidResume {
1196 return errors.New("did not resume")
1197 }
1198 return nil
1199 },
1200 }
1201
1202 runServerTestTLS12(t, testIssue)
1203 runServerTestTLS12(t, testResume)
1204
1205 runServerTestTLS13(t, testIssue)
1206 runServerTestTLS13(t, testResume)
1207
1208 config := testConfig.Clone()
1209 config.CurvePreferences = []CurveID{CurveP256}
1210
1211 testResumeHRR := &serverTest{
1212 name: "Resume-HelloRetryRequest",
1213 command: []string{"openssl", "s_client", "-curves", "X25519:P-256", "-cipher", "AES128-SHA", "-ciphersuites",
1214 "TLS_AES_128_GCM_SHA256", "-sess_in", sessionFilePath},
1215 config: config,
1216 validate: func(state ConnectionState) error {
1217 if !state.DidResume {
1218 return errors.New("did not resume")
1219 }
1220 return nil
1221 },
1222 }
1223
1224 runServerTestTLS13(t, testResumeHRR)
1225 }
1226
1227 func TestServerResumptionDisabled(t *testing.T) {
1228 sessionFilePath := tempFile("")
1229 defer os.Remove(sessionFilePath)
1230
1231 config := testConfig.Clone()
1232
1233 testIssue := &serverTest{
1234 name: "IssueTicketPreDisable",
1235 command: []string{"openssl", "s_client", "-cipher", "AES128-SHA", "-ciphersuites", "TLS_AES_128_GCM_SHA256", "-sess_out", sessionFilePath},
1236 config: config,
1237 wait: true,
1238 }
1239 testResume := &serverTest{
1240 name: "ResumeDisabled",
1241 command: []string{"openssl", "s_client", "-cipher", "AES128-SHA", "-ciphersuites", "TLS_AES_128_GCM_SHA256", "-sess_in", sessionFilePath},
1242 config: config,
1243 validate: func(state ConnectionState) error {
1244 if state.DidResume {
1245 return errors.New("resumed with SessionTicketsDisabled")
1246 }
1247 return nil
1248 },
1249 }
1250
1251 config.SessionTicketsDisabled = false
1252 runServerTestTLS12(t, testIssue)
1253 config.SessionTicketsDisabled = true
1254 runServerTestTLS12(t, testResume)
1255
1256 config.SessionTicketsDisabled = false
1257 runServerTestTLS13(t, testIssue)
1258 config.SessionTicketsDisabled = true
1259 runServerTestTLS13(t, testResume)
1260 }
1261
1262 func TestFallbackSCSV(t *testing.T) {
1263 serverConfig := Config{
1264 Certificates: testConfig.Certificates,
1265 MinVersion: VersionTLS11,
1266 }
1267 test := &serverTest{
1268 name: "FallbackSCSV",
1269 config: &serverConfig,
1270
1271 command: []string{"openssl", "s_client", "-fallback_scsv"},
1272 expectHandshakeErrorIncluding: "inappropriate protocol fallback",
1273 }
1274 runServerTestTLS11(t, test)
1275 }
1276
1277 func TestHandshakeServerExportKeyingMaterial(t *testing.T) {
1278 test := &serverTest{
1279 name: "ExportKeyingMaterial",
1280 command: []string{"openssl", "s_client", "-cipher", "ECDHE-RSA-AES256-SHA", "-ciphersuites", "TLS_CHACHA20_POLY1305_SHA256"},
1281 config: testConfig.Clone(),
1282 validate: func(state ConnectionState) error {
1283 if km, err := state.ExportKeyingMaterial("test", nil, 42); err != nil {
1284 return fmt.Errorf("ExportKeyingMaterial failed: %v", err)
1285 } else if len(km) != 42 {
1286 return fmt.Errorf("Got %d bytes from ExportKeyingMaterial, wanted %d", len(km), 42)
1287 }
1288 return nil
1289 },
1290 }
1291 runServerTestTLS10(t, test)
1292 runServerTestTLS12(t, test)
1293 runServerTestTLS13(t, test)
1294 }
1295
1296 func TestHandshakeServerRSAPKCS1v15(t *testing.T) {
1297 test := &serverTest{
1298 name: "RSA-RSAPKCS1v15",
1299 command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "ECDHE-RSA-CHACHA20-POLY1305", "-sigalgs", "rsa_pkcs1_sha256"},
1300 }
1301 runServerTestTLS12(t, test)
1302 }
1303
1304 func TestHandshakeServerRSAPSS(t *testing.T) {
1305
1306
1307
1308 test := &serverTest{
1309 name: "RSA-RSAPSS",
1310 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"},
1311 }
1312 runServerTestTLS12(t, test)
1313 runServerTestTLS13(t, test)
1314
1315 test = &serverTest{
1316 name: "RSA-RSAPSS-TooSmall",
1317 command: []string{"openssl", "s_client", "-no_ticket", "-ciphersuites", "TLS_CHACHA20_POLY1305_SHA256", "-sigalgs", "rsa_pss_rsae_sha512"},
1318 expectHandshakeErrorIncluding: "peer doesn't support any of the certificate's signature algorithms",
1319 }
1320 runServerTestTLS13(t, test)
1321 }
1322
1323 func TestHandshakeServerEd25519(t *testing.T) {
1324 config := testConfig.Clone()
1325 config.Certificates = make([]Certificate, 1)
1326 config.Certificates[0].Certificate = [][]byte{testEd25519Certificate}
1327 config.Certificates[0].PrivateKey = testEd25519PrivateKey
1328 config.BuildNameToCertificate()
1329
1330 test := &serverTest{
1331 name: "Ed25519",
1332 command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "ECDHE-ECDSA-CHACHA20-POLY1305", "-ciphersuites", "TLS_CHACHA20_POLY1305_SHA256"},
1333 config: config,
1334 }
1335 runServerTestTLS12(t, test)
1336 runServerTestTLS13(t, test)
1337 }
1338
1339 func benchmarkHandshakeServer(b *testing.B, version uint16, cipherSuite uint16, curve CurveID, cert []byte, key crypto.PrivateKey) {
1340 config := testConfig.Clone()
1341 config.CipherSuites = []uint16{cipherSuite}
1342 config.CurvePreferences = []CurveID{curve}
1343 config.Certificates = make([]Certificate, 1)
1344 config.Certificates[0].Certificate = [][]byte{cert}
1345 config.Certificates[0].PrivateKey = key
1346 config.BuildNameToCertificate()
1347
1348 clientConn, serverConn := localPipe(b)
1349 serverConn = &recordingConn{Conn: serverConn}
1350 go func() {
1351 config := testConfig.Clone()
1352 config.MaxVersion = version
1353 config.CurvePreferences = []CurveID{curve}
1354 client := Client(clientConn, config)
1355 client.Handshake()
1356 }()
1357 server := Server(serverConn, config)
1358 if err := server.Handshake(); err != nil {
1359 b.Fatalf("handshake failed: %v", err)
1360 }
1361 serverConn.Close()
1362 flows := serverConn.(*recordingConn).flows
1363
1364 b.ResetTimer()
1365 for i := 0; i < b.N; i++ {
1366 replay := &replayingConn{t: b, flows: slices.Clone(flows), reading: true}
1367 server := Server(replay, config)
1368 if err := server.Handshake(); err != nil {
1369 b.Fatalf("handshake failed: %v", err)
1370 }
1371 }
1372 }
1373
1374 func BenchmarkHandshakeServer(b *testing.B) {
1375 b.Run("RSA", func(b *testing.B) {
1376 benchmarkHandshakeServer(b, VersionTLS12, TLS_RSA_WITH_AES_128_GCM_SHA256,
1377 0, testRSACertificate, testRSAPrivateKey)
1378 })
1379 b.Run("ECDHE-P256-RSA", func(b *testing.B) {
1380 b.Run("TLSv13", func(b *testing.B) {
1381 benchmarkHandshakeServer(b, VersionTLS13, TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305,
1382 CurveP256, testRSACertificate, testRSAPrivateKey)
1383 })
1384 b.Run("TLSv12", func(b *testing.B) {
1385 benchmarkHandshakeServer(b, VersionTLS12, TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305,
1386 CurveP256, testRSACertificate, testRSAPrivateKey)
1387 })
1388 })
1389 b.Run("ECDHE-P256-ECDSA-P256", func(b *testing.B) {
1390 b.Run("TLSv13", func(b *testing.B) {
1391 benchmarkHandshakeServer(b, VersionTLS13, TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305,
1392 CurveP256, testP256Certificate, testP256PrivateKey)
1393 })
1394 b.Run("TLSv12", func(b *testing.B) {
1395 benchmarkHandshakeServer(b, VersionTLS12, TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305,
1396 CurveP256, testP256Certificate, testP256PrivateKey)
1397 })
1398 })
1399 b.Run("ECDHE-X25519-ECDSA-P256", func(b *testing.B) {
1400 b.Run("TLSv13", func(b *testing.B) {
1401 benchmarkHandshakeServer(b, VersionTLS13, TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305,
1402 X25519, testP256Certificate, testP256PrivateKey)
1403 })
1404 b.Run("TLSv12", func(b *testing.B) {
1405 benchmarkHandshakeServer(b, VersionTLS12, TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305,
1406 X25519, testP256Certificate, testP256PrivateKey)
1407 })
1408 })
1409 b.Run("ECDHE-P521-ECDSA-P521", func(b *testing.B) {
1410 if testECDSAPrivateKey.PublicKey.Curve != elliptic.P521() {
1411 b.Fatal("test ECDSA key doesn't use curve P-521")
1412 }
1413 b.Run("TLSv13", func(b *testing.B) {
1414 benchmarkHandshakeServer(b, VersionTLS13, TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305,
1415 CurveP521, testECDSACertificate, testECDSAPrivateKey)
1416 })
1417 b.Run("TLSv12", func(b *testing.B) {
1418 benchmarkHandshakeServer(b, VersionTLS12, TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305,
1419 CurveP521, testECDSACertificate, testECDSAPrivateKey)
1420 })
1421 })
1422 }
1423
1424 func TestClientAuth(t *testing.T) {
1425 var certPath, keyPath, ecdsaCertPath, ecdsaKeyPath, ed25519CertPath, ed25519KeyPath string
1426
1427 if *update {
1428 certPath = tempFile(clientCertificatePEM)
1429 defer os.Remove(certPath)
1430 keyPath = tempFile(clientKeyPEM)
1431 defer os.Remove(keyPath)
1432 ecdsaCertPath = tempFile(clientECDSACertificatePEM)
1433 defer os.Remove(ecdsaCertPath)
1434 ecdsaKeyPath = tempFile(clientECDSAKeyPEM)
1435 defer os.Remove(ecdsaKeyPath)
1436 ed25519CertPath = tempFile(clientEd25519CertificatePEM)
1437 defer os.Remove(ed25519CertPath)
1438 ed25519KeyPath = tempFile(clientEd25519KeyPEM)
1439 defer os.Remove(ed25519KeyPath)
1440 } else {
1441 t.Parallel()
1442 }
1443
1444 config := testConfig.Clone()
1445 config.ClientAuth = RequestClientCert
1446
1447 test := &serverTest{
1448 name: "ClientAuthRequestedNotGiven",
1449 command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "AES128-SHA", "-ciphersuites", "TLS_AES_128_GCM_SHA256"},
1450 config: config,
1451 }
1452 runServerTestTLS12(t, test)
1453 runServerTestTLS13(t, test)
1454
1455 test = &serverTest{
1456 name: "ClientAuthRequestedAndGiven",
1457 command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "AES128-SHA", "-ciphersuites", "TLS_AES_128_GCM_SHA256",
1458 "-cert", certPath, "-key", keyPath, "-client_sigalgs", "rsa_pss_rsae_sha256"},
1459 config: config,
1460 expectedPeerCerts: []string{clientCertificatePEM},
1461 }
1462 runServerTestTLS12(t, test)
1463 runServerTestTLS13(t, test)
1464
1465 test = &serverTest{
1466 name: "ClientAuthRequestedAndECDSAGiven",
1467 command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "AES128-SHA", "-ciphersuites", "TLS_AES_128_GCM_SHA256",
1468 "-cert", ecdsaCertPath, "-key", ecdsaKeyPath},
1469 config: config,
1470 expectedPeerCerts: []string{clientECDSACertificatePEM},
1471 }
1472 runServerTestTLS12(t, test)
1473 runServerTestTLS13(t, test)
1474
1475 test = &serverTest{
1476 name: "ClientAuthRequestedAndEd25519Given",
1477 command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "AES128-SHA", "-ciphersuites", "TLS_AES_128_GCM_SHA256",
1478 "-cert", ed25519CertPath, "-key", ed25519KeyPath},
1479 config: config,
1480 expectedPeerCerts: []string{clientEd25519CertificatePEM},
1481 }
1482 runServerTestTLS12(t, test)
1483 runServerTestTLS13(t, test)
1484
1485 test = &serverTest{
1486 name: "ClientAuthRequestedAndPKCS1v15Given",
1487 command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "AES128-SHA",
1488 "-cert", certPath, "-key", keyPath, "-client_sigalgs", "rsa_pkcs1_sha256"},
1489 config: config,
1490 expectedPeerCerts: []string{clientCertificatePEM},
1491 }
1492 runServerTestTLS12(t, test)
1493 }
1494
1495 func TestSNIGivenOnFailure(t *testing.T) {
1496 const expectedServerName = "test.testing"
1497
1498 clientHello := &clientHelloMsg{
1499 vers: VersionTLS10,
1500 random: make([]byte, 32),
1501 cipherSuites: []uint16{TLS_RSA_WITH_RC4_128_SHA},
1502 compressionMethods: []uint8{compressionNone},
1503 serverName: expectedServerName,
1504 }
1505
1506 serverConfig := testConfig.Clone()
1507
1508 serverConfig.CipherSuites = nil
1509
1510 c, s := localPipe(t)
1511 go func() {
1512 cli := Client(c, testConfig)
1513 cli.vers = clientHello.vers
1514 if _, err := cli.writeHandshakeRecord(clientHello, nil); err != nil {
1515 testFatal(t, err)
1516 }
1517 c.Close()
1518 }()
1519 conn := Server(s, serverConfig)
1520 ctx := context.Background()
1521 ch, err := conn.readClientHello(ctx)
1522 hs := serverHandshakeState{
1523 c: conn,
1524 ctx: ctx,
1525 clientHello: ch,
1526 }
1527 if err == nil {
1528 err = hs.processClientHello()
1529 }
1530 if err == nil {
1531 err = hs.pickCipherSuite()
1532 }
1533 defer s.Close()
1534
1535 if err == nil {
1536 t.Error("No error reported from server")
1537 }
1538
1539 cs := hs.c.ConnectionState()
1540 if cs.HandshakeComplete {
1541 t.Error("Handshake registered as complete")
1542 }
1543
1544 if cs.ServerName != expectedServerName {
1545 t.Errorf("Expected ServerName of %q, but got %q", expectedServerName, cs.ServerName)
1546 }
1547 }
1548
1549 var getConfigForClientTests = []struct {
1550 setup func(config *Config)
1551 callback func(clientHello *ClientHelloInfo) (*Config, error)
1552 errorSubstring string
1553 verify func(config *Config) error
1554 }{
1555 {
1556 nil,
1557 func(clientHello *ClientHelloInfo) (*Config, error) {
1558 return nil, nil
1559 },
1560 "",
1561 nil,
1562 },
1563 {
1564 nil,
1565 func(clientHello *ClientHelloInfo) (*Config, error) {
1566 return nil, errors.New("should bubble up")
1567 },
1568 "should bubble up",
1569 nil,
1570 },
1571 {
1572 nil,
1573 func(clientHello *ClientHelloInfo) (*Config, error) {
1574 config := testConfig.Clone()
1575
1576
1577 config.MaxVersion = VersionTLS11
1578 return config, nil
1579 },
1580 "client offered only unsupported versions",
1581 nil,
1582 },
1583 {
1584 func(config *Config) {
1585 for i := range config.SessionTicketKey {
1586 config.SessionTicketKey[i] = byte(i)
1587 }
1588 config.sessionTicketKeys = nil
1589 },
1590 func(clientHello *ClientHelloInfo) (*Config, error) {
1591 config := testConfig.Clone()
1592 for i := range config.SessionTicketKey {
1593 config.SessionTicketKey[i] = 0
1594 }
1595 config.sessionTicketKeys = nil
1596 return config, nil
1597 },
1598 "",
1599 func(config *Config) error {
1600 if config.SessionTicketKey == [32]byte{} {
1601 return fmt.Errorf("expected SessionTicketKey to be set")
1602 }
1603 return nil
1604 },
1605 },
1606 {
1607 func(config *Config) {
1608 var dummyKey [32]byte
1609 for i := range dummyKey {
1610 dummyKey[i] = byte(i)
1611 }
1612
1613 config.SetSessionTicketKeys([][32]byte{dummyKey})
1614 },
1615 func(clientHello *ClientHelloInfo) (*Config, error) {
1616 config := testConfig.Clone()
1617 config.sessionTicketKeys = nil
1618 return config, nil
1619 },
1620 "",
1621 func(config *Config) error {
1622 if config.SessionTicketKey == [32]byte{} {
1623 return fmt.Errorf("expected SessionTicketKey to be set")
1624 }
1625 return nil
1626 },
1627 },
1628 }
1629
1630 func TestGetConfigForClient(t *testing.T) {
1631 serverConfig := testConfig.Clone()
1632 clientConfig := testConfig.Clone()
1633 clientConfig.MinVersion = VersionTLS12
1634
1635 for i, test := range getConfigForClientTests {
1636 if test.setup != nil {
1637 test.setup(serverConfig)
1638 }
1639
1640 var configReturned *Config
1641 serverConfig.GetConfigForClient = func(clientHello *ClientHelloInfo) (*Config, error) {
1642 config, err := test.callback(clientHello)
1643 configReturned = config
1644 return config, err
1645 }
1646 c, s := localPipe(t)
1647 done := make(chan error)
1648
1649 go func() {
1650 defer s.Close()
1651 done <- Server(s, serverConfig).Handshake()
1652 }()
1653
1654 clientErr := Client(c, clientConfig).Handshake()
1655 c.Close()
1656
1657 serverErr := <-done
1658
1659 if len(test.errorSubstring) == 0 {
1660 if serverErr != nil || clientErr != nil {
1661 t.Errorf("test[%d]: expected no error but got serverErr: %q, clientErr: %q", i, serverErr, clientErr)
1662 }
1663 if test.verify != nil {
1664 if err := test.verify(configReturned); err != nil {
1665 t.Errorf("test[%d]: verify returned error: %v", i, err)
1666 }
1667 }
1668 } else {
1669 if serverErr == nil {
1670 t.Errorf("test[%d]: expected error containing %q but got no error", i, test.errorSubstring)
1671 } else if !strings.Contains(serverErr.Error(), test.errorSubstring) {
1672 t.Errorf("test[%d]: expected error to contain %q but it was %q", i, test.errorSubstring, serverErr)
1673 }
1674 }
1675 }
1676 }
1677
1678 func TestCloseServerConnectionOnIdleClient(t *testing.T) {
1679 clientConn, serverConn := localPipe(t)
1680 server := Server(serverConn, testConfig.Clone())
1681 go func() {
1682 clientConn.Write([]byte{'0'})
1683 server.Close()
1684 }()
1685 server.SetReadDeadline(time.Now().Add(time.Minute))
1686 err := server.Handshake()
1687 if err != nil {
1688 if err, ok := err.(net.Error); ok && err.Timeout() {
1689 t.Errorf("Expected a closed network connection error but got '%s'", err.Error())
1690 }
1691 } else {
1692 t.Errorf("Error expected, but no error returned")
1693 }
1694 }
1695
1696 func TestCloneHash(t *testing.T) {
1697 h1 := crypto.SHA256.New()
1698 h1.Write([]byte("test"))
1699 s1 := h1.Sum(nil)
1700 h2 := cloneHash(h1, crypto.SHA256)
1701 s2 := h2.Sum(nil)
1702 if !bytes.Equal(s1, s2) {
1703 t.Error("cloned hash generated a different sum")
1704 }
1705 }
1706
1707 func expectError(t *testing.T, err error, sub string) {
1708 if err == nil {
1709 t.Errorf(`expected error %q, got nil`, sub)
1710 } else if !strings.Contains(err.Error(), sub) {
1711 t.Errorf(`expected error %q, got %q`, sub, err)
1712 }
1713 }
1714
1715 func TestKeyTooSmallForRSAPSS(t *testing.T) {
1716 cert, err := X509KeyPair([]byte(`-----BEGIN CERTIFICATE-----
1717 MIIBcTCCARugAwIBAgIQGjQnkCFlUqaFlt6ixyz/tDANBgkqhkiG9w0BAQsFADAS
1718 MRAwDgYDVQQKEwdBY21lIENvMB4XDTE5MDExODIzMjMyOFoXDTIwMDExODIzMjMy
1719 OFowEjEQMA4GA1UEChMHQWNtZSBDbzBcMA0GCSqGSIb3DQEBAQUAA0sAMEgCQQDd
1720 ez1rFUDwax2HTxbcnFUP9AhcgEGMHVV2nn4VVEWFJB6I8C/Nkx0XyyQlrmFYBzEQ
1721 nIPhKls4T0hFoLvjJnXpAgMBAAGjTTBLMA4GA1UdDwEB/wQEAwIFoDATBgNVHSUE
1722 DDAKBggrBgEFBQcDATAMBgNVHRMBAf8EAjAAMBYGA1UdEQQPMA2CC2V4YW1wbGUu
1723 Y29tMA0GCSqGSIb3DQEBCwUAA0EAxDuUS+BrrS3c+h+k+fQPOmOScy6yTX9mHw0Q
1724 KbucGamXYEy0URIwOdO0tQ3LHPc1YGvYSPwkDjkjqECs2Vm/AA==
1725 -----END CERTIFICATE-----`), []byte(testingKey(`-----BEGIN RSA TESTING KEY-----
1726 MIIBOgIBAAJBAN17PWsVQPBrHYdPFtycVQ/0CFyAQYwdVXaefhVURYUkHojwL82T
1727 HRfLJCWuYVgHMRCcg+EqWzhPSEWgu+MmdekCAwEAAQJBALjQYNTdXF4CFBbXwUz/
1728 yt9QFDYT9B5WT/12jeGAe653gtYS6OOi/+eAkGmzg1GlRnw6fOfn+HYNFDORST7z
1729 4j0CIQDn2xz9hVWQEu9ee3vecNT3f60huDGTNoRhtqgweQGX0wIhAPSLj1VcRZEz
1730 nKpbtU22+PbIMSJ+e80fmY9LIPx5N4HTAiAthGSimMR9bloz0EY3GyuUEyqoDgMd
1731 hXxjuno2WesoJQIgemilbcALXpxsLmZLgcQ2KSmaVr7jb5ECx9R+hYKTw1sCIG4s
1732 T+E0J8wlH24pgwQHzy7Ko2qLwn1b5PW8ecrlvP1g
1733 -----END RSA TESTING KEY-----`)))
1734 if err != nil {
1735 t.Fatal(err)
1736 }
1737
1738 clientConn, serverConn := localPipe(t)
1739 client := Client(clientConn, testConfig)
1740 done := make(chan struct{})
1741 go func() {
1742 config := testConfig.Clone()
1743 config.Certificates = []Certificate{cert}
1744 config.MinVersion = VersionTLS13
1745 server := Server(serverConn, config)
1746 err := server.Handshake()
1747 expectError(t, err, "key size too small")
1748 close(done)
1749 }()
1750 err = client.Handshake()
1751 expectError(t, err, "handshake failure")
1752 <-done
1753 }
1754
1755 func TestMultipleCertificates(t *testing.T) {
1756 clientConfig := testConfig.Clone()
1757 clientConfig.CipherSuites = []uint16{TLS_RSA_WITH_AES_128_GCM_SHA256}
1758 clientConfig.MaxVersion = VersionTLS12
1759
1760 serverConfig := testConfig.Clone()
1761 serverConfig.Certificates = []Certificate{{
1762 Certificate: [][]byte{testECDSACertificate},
1763 PrivateKey: testECDSAPrivateKey,
1764 }, {
1765 Certificate: [][]byte{testRSACertificate},
1766 PrivateKey: testRSAPrivateKey,
1767 }}
1768
1769 _, clientState, err := testHandshake(t, clientConfig, serverConfig)
1770 if err != nil {
1771 t.Fatal(err)
1772 }
1773 if got := clientState.PeerCertificates[0].PublicKeyAlgorithm; got != x509.RSA {
1774 t.Errorf("expected RSA certificate, got %v", got)
1775 }
1776 }
1777
1778 func TestAESCipherReordering(t *testing.T) {
1779 currentAESSupport := hasAESGCMHardwareSupport
1780 defer func() { hasAESGCMHardwareSupport = currentAESSupport }()
1781
1782 tests := []struct {
1783 name string
1784 clientCiphers []uint16
1785 serverHasAESGCM bool
1786 serverCiphers []uint16
1787 expectedCipher uint16
1788 }{
1789 {
1790 name: "server has hardware AES, client doesn't (pick ChaCha)",
1791 clientCiphers: []uint16{
1792 TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305,
1793 TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
1794 TLS_RSA_WITH_AES_128_CBC_SHA,
1795 },
1796 serverHasAESGCM: true,
1797 expectedCipher: TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305,
1798 },
1799 {
1800 name: "client prefers AES-GCM, server doesn't have hardware AES (pick ChaCha)",
1801 clientCiphers: []uint16{
1802 TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
1803 TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305,
1804 TLS_RSA_WITH_AES_128_CBC_SHA,
1805 },
1806 serverHasAESGCM: false,
1807 expectedCipher: TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305,
1808 },
1809 {
1810 name: "client prefers AES-GCM, server has hardware AES (pick AES-GCM)",
1811 clientCiphers: []uint16{
1812 TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
1813 TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305,
1814 TLS_RSA_WITH_AES_128_CBC_SHA,
1815 },
1816 serverHasAESGCM: true,
1817 expectedCipher: TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
1818 },
1819 {
1820 name: "client prefers AES-GCM and sends GREASE, server has hardware AES (pick AES-GCM)",
1821 clientCiphers: []uint16{
1822 0x0A0A,
1823 TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
1824 TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305,
1825 TLS_RSA_WITH_AES_128_CBC_SHA,
1826 },
1827 serverHasAESGCM: true,
1828 expectedCipher: TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
1829 },
1830 {
1831 name: "client prefers AES-GCM and doesn't support ChaCha, server doesn't have hardware AES (pick AES-GCM)",
1832 clientCiphers: []uint16{
1833 TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
1834 TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
1835 TLS_RSA_WITH_AES_128_CBC_SHA,
1836 },
1837 serverHasAESGCM: false,
1838 expectedCipher: TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
1839 },
1840 {
1841 name: "client prefers AES-GCM and AES-CBC over ChaCha, server doesn't have hardware AES (pick ChaCha)",
1842 clientCiphers: []uint16{
1843 TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
1844 TLS_RSA_WITH_AES_128_CBC_SHA,
1845 TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305,
1846 },
1847 serverHasAESGCM: false,
1848 expectedCipher: TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305,
1849 },
1850 {
1851 name: "client prefers AES-GCM over ChaCha and sends GREASE, server doesn't have hardware AES (pick ChaCha)",
1852 clientCiphers: []uint16{
1853 0x0A0A,
1854 TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
1855 TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305,
1856 TLS_RSA_WITH_AES_128_CBC_SHA,
1857 },
1858 serverHasAESGCM: false,
1859 expectedCipher: TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305,
1860 },
1861 {
1862 name: "client supports multiple AES-GCM, server doesn't have hardware AES and doesn't support ChaCha (AES-GCM)",
1863 clientCiphers: []uint16{
1864 TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
1865 TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305,
1866 TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
1867 },
1868 serverHasAESGCM: false,
1869 serverCiphers: []uint16{
1870 TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
1871 TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
1872 },
1873 expectedCipher: TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
1874 },
1875 {
1876 name: "client prefers AES-GCM, server has hardware but doesn't support AES (pick ChaCha)",
1877 clientCiphers: []uint16{
1878 TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
1879 TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305,
1880 TLS_RSA_WITH_AES_128_CBC_SHA,
1881 },
1882 serverHasAESGCM: true,
1883 serverCiphers: []uint16{
1884 TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305,
1885 },
1886 expectedCipher: TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305,
1887 },
1888 }
1889
1890 for _, tc := range tests {
1891 t.Run(tc.name, func(t *testing.T) {
1892 hasAESGCMHardwareSupport = tc.serverHasAESGCM
1893 hs := &serverHandshakeState{
1894 c: &Conn{
1895 config: &Config{
1896 CipherSuites: tc.serverCiphers,
1897 },
1898 vers: VersionTLS12,
1899 },
1900 clientHello: &clientHelloMsg{
1901 cipherSuites: tc.clientCiphers,
1902 vers: VersionTLS12,
1903 },
1904 ecdheOk: true,
1905 rsaSignOk: true,
1906 rsaDecryptOk: true,
1907 }
1908
1909 err := hs.pickCipherSuite()
1910 if err != nil {
1911 t.Errorf("pickCipherSuite failed: %s", err)
1912 }
1913
1914 if tc.expectedCipher != hs.suite.id {
1915 t.Errorf("unexpected cipher chosen: want %d, got %d", tc.expectedCipher, hs.suite.id)
1916 }
1917 })
1918 }
1919 }
1920
1921 func TestAESCipherReorderingTLS13(t *testing.T) {
1922 currentAESSupport := hasAESGCMHardwareSupport
1923 defer func() { hasAESGCMHardwareSupport = currentAESSupport }()
1924
1925 tests := []struct {
1926 name string
1927 clientCiphers []uint16
1928 serverHasAESGCM bool
1929 expectedCipher uint16
1930 }{
1931 {
1932 name: "server has hardware AES, client doesn't (pick ChaCha)",
1933 clientCiphers: []uint16{
1934 TLS_CHACHA20_POLY1305_SHA256,
1935 TLS_AES_128_GCM_SHA256,
1936 },
1937 serverHasAESGCM: true,
1938 expectedCipher: TLS_CHACHA20_POLY1305_SHA256,
1939 },
1940 {
1941 name: "neither server nor client have hardware AES (pick ChaCha)",
1942 clientCiphers: []uint16{
1943 TLS_CHACHA20_POLY1305_SHA256,
1944 TLS_AES_128_GCM_SHA256,
1945 },
1946 serverHasAESGCM: false,
1947 expectedCipher: TLS_CHACHA20_POLY1305_SHA256,
1948 },
1949 {
1950 name: "client prefers AES, server doesn't have hardware (pick ChaCha)",
1951 clientCiphers: []uint16{
1952 TLS_AES_128_GCM_SHA256,
1953 TLS_CHACHA20_POLY1305_SHA256,
1954 },
1955 serverHasAESGCM: false,
1956 expectedCipher: TLS_CHACHA20_POLY1305_SHA256,
1957 },
1958 {
1959 name: "client prefers AES and sends GREASE, server doesn't have hardware (pick ChaCha)",
1960 clientCiphers: []uint16{
1961 0x0A0A,
1962 TLS_AES_128_GCM_SHA256,
1963 TLS_CHACHA20_POLY1305_SHA256,
1964 },
1965 serverHasAESGCM: false,
1966 expectedCipher: TLS_CHACHA20_POLY1305_SHA256,
1967 },
1968 {
1969 name: "client prefers AES, server has hardware AES (pick AES)",
1970 clientCiphers: []uint16{
1971 TLS_AES_128_GCM_SHA256,
1972 TLS_CHACHA20_POLY1305_SHA256,
1973 },
1974 serverHasAESGCM: true,
1975 expectedCipher: TLS_AES_128_GCM_SHA256,
1976 },
1977 {
1978 name: "client prefers AES and sends GREASE, server has hardware AES (pick AES)",
1979 clientCiphers: []uint16{
1980 0x0A0A,
1981 TLS_AES_128_GCM_SHA256,
1982 TLS_CHACHA20_POLY1305_SHA256,
1983 },
1984 serverHasAESGCM: true,
1985 expectedCipher: TLS_AES_128_GCM_SHA256,
1986 },
1987 }
1988
1989 for _, tc := range tests {
1990 t.Run(tc.name, func(t *testing.T) {
1991 hasAESGCMHardwareSupport = tc.serverHasAESGCM
1992 pk, _ := ecdh.X25519().GenerateKey(rand.Reader)
1993 hs := &serverHandshakeStateTLS13{
1994 c: &Conn{
1995 config: &Config{},
1996 vers: VersionTLS13,
1997 },
1998 clientHello: &clientHelloMsg{
1999 cipherSuites: tc.clientCiphers,
2000 supportedVersions: []uint16{VersionTLS13},
2001 compressionMethods: []uint8{compressionNone},
2002 keyShares: []keyShare{{group: X25519, data: pk.PublicKey().Bytes()}},
2003 supportedCurves: []CurveID{X25519},
2004 },
2005 }
2006
2007 err := hs.processClientHello()
2008 if err != nil {
2009 t.Errorf("pickCipherSuite failed: %s", err)
2010 }
2011
2012 if tc.expectedCipher != hs.suite.id {
2013 t.Errorf("unexpected cipher chosen: want %d, got %d", tc.expectedCipher, hs.suite.id)
2014 }
2015 })
2016 }
2017 }
2018
2019
2020
2021
2022 func TestServerHandshakeContextCancellation(t *testing.T) {
2023 c, s := localPipe(t)
2024 ctx, cancel := context.WithCancel(context.Background())
2025 unblockClient := make(chan struct{})
2026 defer close(unblockClient)
2027 go func() {
2028 cancel()
2029 <-unblockClient
2030 _ = c.Close()
2031 }()
2032 conn := Server(s, testConfig)
2033
2034
2035 err := conn.HandshakeContext(ctx)
2036 if err == nil {
2037 t.Fatal("Server handshake did not error when the context was canceled")
2038 }
2039 if err != context.Canceled {
2040 t.Errorf("Unexpected server handshake error: %v", err)
2041 }
2042 if runtime.GOARCH == "wasm" {
2043 t.Skip("conn.Close does not error as expected when called multiple times on WASM")
2044 }
2045 err = conn.Close()
2046 if err == nil {
2047 t.Error("Server connection was not closed when the context was canceled")
2048 }
2049 }
2050
2051
2052
2053
2054
2055
2056 func TestHandshakeContextHierarchy(t *testing.T) {
2057 c, s := localPipe(t)
2058 clientErr := make(chan error, 1)
2059 clientConfig := testConfig.Clone()
2060 serverConfig := testConfig.Clone()
2061 ctx, cancel := context.WithCancel(context.Background())
2062 defer cancel()
2063 key := struct{}{}
2064 ctx = context.WithValue(ctx, key, true)
2065 go func() {
2066 defer close(clientErr)
2067 defer c.Close()
2068 var innerCtx context.Context
2069 clientConfig.Certificates = nil
2070 clientConfig.GetClientCertificate = func(certificateRequest *CertificateRequestInfo) (*Certificate, error) {
2071 if val, ok := certificateRequest.Context().Value(key).(bool); !ok || !val {
2072 t.Errorf("GetClientCertificate context was not child of HandshakeContext")
2073 }
2074 innerCtx = certificateRequest.Context()
2075 return &Certificate{
2076 Certificate: [][]byte{testRSACertificate},
2077 PrivateKey: testRSAPrivateKey,
2078 }, nil
2079 }
2080 cli := Client(c, clientConfig)
2081 err := cli.HandshakeContext(ctx)
2082 if err != nil {
2083 clientErr <- err
2084 return
2085 }
2086 select {
2087 case <-innerCtx.Done():
2088 default:
2089 t.Errorf("GetClientCertificate context was not canceled after HandshakeContext returned.")
2090 }
2091 }()
2092 var innerCtx context.Context
2093 serverConfig.Certificates = nil
2094 serverConfig.ClientAuth = RequestClientCert
2095 serverConfig.GetCertificate = func(clientHello *ClientHelloInfo) (*Certificate, error) {
2096 if val, ok := clientHello.Context().Value(key).(bool); !ok || !val {
2097 t.Errorf("GetClientCertificate context was not child of HandshakeContext")
2098 }
2099 innerCtx = clientHello.Context()
2100 return &Certificate{
2101 Certificate: [][]byte{testRSACertificate},
2102 PrivateKey: testRSAPrivateKey,
2103 }, nil
2104 }
2105 conn := Server(s, serverConfig)
2106 err := conn.HandshakeContext(ctx)
2107 if err != nil {
2108 t.Errorf("Unexpected server handshake error: %v", err)
2109 }
2110 select {
2111 case <-innerCtx.Done():
2112 default:
2113 t.Errorf("GetCertificate context was not canceled after HandshakeContext returned.")
2114 }
2115 if err := <-clientErr; err != nil {
2116 t.Errorf("Unexpected client error: %v", err)
2117 }
2118 }
2119
View as plain text