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