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