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