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.Clone())
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.Clone(), &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.Clone()
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.Clone(), 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.Clone(), 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.Clone()
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.Clone(), &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.Clone()
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.Clone()
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.Clone())
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.Clone()).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.Clone())
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.Clone()
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.Clone()
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.Clone()
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.Clone()).sendAlert(alertUnknownCA)
403 c.Close()
404 }()
405
406 err := Server(s, testConfigServer.Clone()).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.Clone()).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 }
709 config = config.Clone()
710 server := Server(serverConn, config)
711
712 _, err := server.Write([]byte("hello, world\n"))
713 if len(test.expectHandshakeErrorIncluding) > 0 {
714 if err == nil {
715 t.Errorf("Error expected, but no error returned")
716 } else if s := err.Error(); !strings.Contains(s, test.expectHandshakeErrorIncluding) {
717 t.Errorf("Error expected containing '%s' but got '%s'", test.expectHandshakeErrorIncluding, s)
718 }
719 } else {
720 if err != nil {
721 t.Errorf("Error from Server.Write: '%s'", err)
722 }
723 }
724 server.Close()
725
726 connState := server.ConnectionState()
727 peerCerts := connState.PeerCertificates
728 if len(peerCerts) == len(test.expectedPeerCerts) {
729 for i, peerCert := range peerCerts {
730 block, _ := pem.Decode([]byte(test.expectedPeerCerts[i]))
731 if !bytes.Equal(block.Bytes, peerCert.Raw) {
732 t.Fatalf("%s: mismatch on peer cert %d", test.name, i+1)
733 }
734 }
735 } else {
736 t.Fatalf("%s: mismatch on peer list length: %d (wanted) != %d (got)", test.name, len(test.expectedPeerCerts), len(peerCerts))
737 }
738
739 if test.validate != nil && !t.Failed() {
740 if err := test.validate(connState); err != nil {
741 t.Fatalf("validate callback returned error: %s", err)
742 }
743 }
744
745 if write {
746 serverConn.Close()
747 recordingConn.Close()
748 if err := <-childExit; err != nil && len(test.expectHandshakeErrorIncluding) == 0 {
749 t.Errorf("OpenSSL exited with error: %s", err)
750 }
751 if t.Failed() {
752 t.Logf("OpenSSL output:\n\n%s", childProcess.Stdout)
753 return
754 }
755 if len(recordingConn.flows) < 3 {
756 if len(test.expectHandshakeErrorIncluding) == 0 {
757 t.Fatalf("Handshake failed")
758 }
759 }
760 path := test.dataPath()
761 out, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644)
762 if err != nil {
763 t.Fatalf("Failed to create output file: %s", err)
764 }
765 defer out.Close()
766 recordingConn.WriteTo(out)
767 t.Logf("Wrote %s\n", path)
768 }
769 }
770
771 func runServerTestForVersion(t *testing.T, template *serverTest, version, option string) {
772 test := *template
773 if template.config != nil {
774 test.config = template.config.Clone()
775 }
776 test.name = version + "-" + test.name
777 if len(test.command) == 0 {
778 test.command = defaultClientCommand
779 }
780 test.command = append([]string(nil), test.command...)
781 test.command = append(test.command, option)
782
783 runTestAndUpdateIfNeeded(t, version, test.run)
784 }
785
786 func runServerTestTLS10(t *testing.T, template *serverTest) {
787 if template.config == nil {
788 template.config = testConfigServer.Clone()
789 }
790 if template.config.MinVersion == 0 {
791 template.config.MinVersion = VersionTLS10
792 }
793 runServerTestForVersion(t, template, "TLSv10", "-tls1")
794 }
795
796 func runServerTestTLS11(t *testing.T, template *serverTest) {
797 if template.config == nil {
798 template.config = testConfigServer.Clone()
799 }
800 if template.config.MinVersion == 0 {
801 template.config.MinVersion = VersionTLS11
802 }
803 runServerTestForVersion(t, template, "TLSv11", "-tls1_1")
804 }
805
806 func runServerTestTLS12(t *testing.T, template *serverTest) {
807 runServerTestForVersion(t, template, "TLSv12", "-tls1_2")
808 }
809
810 func runServerTestTLS13(t *testing.T, template *serverTest) {
811 runServerTestForVersion(t, template, "TLSv13", "-tls1_3")
812 }
813
814 func checkCipherSuite(want uint16) func(ConnectionState) error {
815 return func(state ConnectionState) error {
816 if state.CipherSuite != want {
817 return fmt.Errorf("got cipher suite %x, want %x", state.CipherSuite, want)
818 }
819 return nil
820 }
821 }
822
823 func TestHandshakeServerRSARC4(t *testing.T) {
824 config := testConfigServer.Clone()
825 config.CipherSuites = []uint16{TLS_RSA_WITH_RC4_128_SHA}
826 test := &serverTest{
827 name: "RSA-RC4",
828 command: append(defaultClientCommand, "-cipher", "RC4-SHA"),
829 config: config,
830 validate: checkCipherSuite(TLS_RSA_WITH_RC4_128_SHA),
831 }
832 runServerTestTLS10(t, test)
833 runServerTestTLS11(t, test)
834 runServerTestTLS12(t, test)
835 }
836
837 func TestHandshakeServerRSA3DES(t *testing.T) {
838 config := testConfigServer.Clone()
839 config.CipherSuites = []uint16{TLS_RSA_WITH_3DES_EDE_CBC_SHA}
840 test := &serverTest{
841 name: "RSA-3DES",
842 command: append(defaultClientCommand, "-cipher", "DES-CBC3-SHA"),
843 config: config,
844 validate: checkCipherSuite(TLS_RSA_WITH_3DES_EDE_CBC_SHA),
845 }
846 runServerTestTLS10(t, test)
847 runServerTestTLS12(t, test)
848 }
849
850 func TestHandshakeServerRSAAES(t *testing.T) {
851 config := testConfigServer.Clone()
852 config.CipherSuites = []uint16{TLS_RSA_WITH_AES_128_CBC_SHA}
853 test := &serverTest{
854 name: "RSA-AES",
855 command: append(defaultClientCommand, "-cipher", "AES128-SHA"),
856 config: config,
857 validate: checkCipherSuite(TLS_RSA_WITH_AES_128_CBC_SHA),
858 }
859 runServerTestTLS10(t, test)
860 runServerTestTLS12(t, test)
861 }
862
863 func TestHandshakeServerAESGCM(t *testing.T) {
864 test := &serverTest{
865 name: "RSA-AES-GCM",
866 command: append(defaultClientCommand, "-cipher", "ECDHE-RSA-AES128-GCM-SHA256"),
867 validate: checkCipherSuite(TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256),
868 }
869 runServerTestTLS12(t, test)
870 }
871
872 func TestHandshakeServerAES256GCMSHA384(t *testing.T) {
873 test := &serverTest{
874 name: "RSA-AES256-GCM-SHA384",
875 command: append(defaultClientCommand, "-cipher", "ECDHE-RSA-AES256-GCM-SHA384"),
876 validate: checkCipherSuite(TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384),
877 }
878 runServerTestTLS12(t, test)
879 }
880
881 func TestHandshakeServerAES128SHA256(t *testing.T) {
882 test := &serverTest{
883 name: "AES128-SHA256",
884 command: append(defaultClientCommand, "-ciphersuites", "TLS_AES_128_GCM_SHA256"),
885 validate: checkCipherSuite(TLS_AES_128_GCM_SHA256),
886 }
887 runServerTestTLS13(t, test)
888 }
889
890 func TestHandshakeServerAES256SHA384(t *testing.T) {
891 test := &serverTest{
892 name: "AES256-SHA384",
893 command: append(defaultClientCommand, "-ciphersuites", "TLS_AES_256_GCM_SHA384"),
894 validate: checkCipherSuite(TLS_AES_256_GCM_SHA384),
895 }
896 runServerTestTLS13(t, test)
897 }
898
899 func TestHandshakeServerCHACHA20SHA256(t *testing.T) {
900 test := &serverTest{
901 name: "CHACHA20-SHA256",
902 command: append(defaultClientCommand, "-ciphersuites", "TLS_CHACHA20_POLY1305_SHA256"),
903 validate: checkCipherSuite(TLS_CHACHA20_POLY1305_SHA256),
904 }
905 runServerTestTLS13(t, test)
906 }
907
908 func TestHandshakeServerECDHEECDSAAES(t *testing.T) {
909 test := &serverTest{
910 name: "ECDHE-ECDSA-AES",
911 command: append(defaultClientCommand, "-sigalgs", "ecdsa_secp256r1_sha256"),
912 }
913 runServerTestTLS10(t, test)
914 runServerTestTLS12(t, test)
915 runServerTestTLS13(t, test)
916 }
917
918 func checkCurveID(want CurveID) func(ConnectionState) error {
919 return func(state ConnectionState) error {
920 if state.CurveID != want {
921 return fmt.Errorf("got curve %d, want %d", state.CurveID, want)
922 }
923 return nil
924 }
925 }
926
927 func TestHandshakeServerX25519(t *testing.T) {
928 test := &serverTest{
929 name: "X25519",
930 command: append(defaultClientCommand, "-curves", "X25519"),
931 validate: checkCurveID(X25519),
932 }
933 runServerTestTLS12(t, test)
934 runServerTestTLS13(t, test)
935 }
936
937 func TestHandshakeServerP256(t *testing.T) {
938 test := &serverTest{
939 name: "P256",
940 command: append(defaultClientCommand, "-curves", "P-256"),
941 validate: checkCurveID(CurveP256),
942 }
943 runServerTestTLS12(t, test)
944 runServerTestTLS13(t, test)
945 }
946
947 func TestHandshakeServerHelloRetryRequest(t *testing.T) {
948 config := testConfigServer.Clone()
949 config.CurvePreferences = []CurveID{CurveP256}
950
951 var clientHelloInfoHRR bool
952 var getCertificateCalled bool
953 config.GetCertificate = func(clientHello *ClientHelloInfo) (*Certificate, error) {
954 getCertificateCalled = true
955 clientHelloInfoHRR = clientHello.HelloRetryRequest
956 return nil, nil
957 }
958
959 test := &serverTest{
960 name: "HelloRetryRequest",
961 command: append(defaultClientCommand, "-curves", "X25519:P-256"),
962 config: config,
963 validate: func(cs ConnectionState) error {
964 if !cs.HelloRetryRequest {
965 return errors.New("expected HelloRetryRequest")
966 }
967 if !getCertificateCalled {
968 return errors.New("expected GetCertificate to be called")
969 }
970 if !clientHelloInfoHRR {
971 return errors.New("expected ClientHelloInfo.HelloRetryRequest to be true")
972 }
973 return nil
974 },
975 }
976 runServerTestTLS13(t, test)
977 }
978
979
980
981
982 func TestHandshakeServerKeySharePreference(t *testing.T) {
983 config := testConfigServer.Clone()
984 config.CurvePreferences = []CurveID{X25519, CurveP256}
985
986
987
988 var clientHelloInfoHRR bool
989 var getCertificateCalled bool
990 config.GetCertificate = func(clientHello *ClientHelloInfo) (*Certificate, error) {
991 getCertificateCalled = true
992 clientHelloInfoHRR = clientHello.HelloRetryRequest
993 return &config.Certificates[0], nil
994 }
995
996 test := &serverTest{
997 name: "KeySharePreference",
998 command: append(defaultClientCommand, "-curves", "P-256:X25519"),
999 config: config,
1000 validate: func(cs ConnectionState) error {
1001 if cs.HelloRetryRequest {
1002 return errors.New("unexpected HelloRetryRequest")
1003 }
1004 if !getCertificateCalled {
1005 return errors.New("expected GetCertificate to be called")
1006 }
1007 if clientHelloInfoHRR {
1008 return errors.New("expected ClientHelloInfo.HelloRetryRequest to be false")
1009 }
1010 return nil
1011 },
1012 }
1013 runServerTestTLS13(t, test)
1014 }
1015
1016 func checkNegotiatedProtocol(want string) func(ConnectionState) error {
1017 return func(state ConnectionState) error {
1018 if state.NegotiatedProtocol != want {
1019 return fmt.Errorf("got protocol %q, want %q", state.NegotiatedProtocol, want)
1020 }
1021 return nil
1022 }
1023 }
1024
1025 func TestHandshakeServerALPN(t *testing.T) {
1026 config := testConfigServer.Clone()
1027 config.NextProtos = []string{"proto1", "proto2"}
1028
1029 test := &serverTest{
1030 name: "ALPN",
1031 command: append(defaultClientCommand, "-alpn", "proto2,proto1"),
1032 config: config,
1033
1034 validate: checkNegotiatedProtocol("proto1"),
1035 }
1036 runServerTestTLS12(t, test)
1037 runServerTestTLS13(t, test)
1038 }
1039
1040 func TestHandshakeServerALPNNoMatch(t *testing.T) {
1041 config := testConfigServer.Clone()
1042 config.NextProtos = []string{"proto3"}
1043
1044 test := &serverTest{
1045 name: "ALPN-NoMatch",
1046 command: append(defaultClientCommand, "-alpn", "proto2,proto1"),
1047 config: config,
1048 expectHandshakeErrorIncluding: "client requested unsupported application protocol",
1049 }
1050 runServerTestTLS12(t, test)
1051 runServerTestTLS13(t, test)
1052 }
1053
1054 func TestHandshakeServerALPNNotConfigured(t *testing.T) {
1055 config := testConfigServer.Clone()
1056 config.NextProtos = nil
1057
1058 test := &serverTest{
1059 name: "ALPN-NotConfigured",
1060 command: append(defaultClientCommand, "-alpn", "proto2,proto1"),
1061 config: config,
1062 validate: checkNegotiatedProtocol(""),
1063 }
1064 runServerTestTLS12(t, test)
1065 runServerTestTLS13(t, test)
1066 }
1067
1068 func TestHandshakeServerALPNFallback(t *testing.T) {
1069 config := testConfigServer.Clone()
1070 config.NextProtos = []string{"proto1", "h2", "proto2"}
1071
1072 test := &serverTest{
1073 name: "ALPN-Fallback",
1074 command: append(defaultClientCommand, "-alpn", "proto3,http/1.1,proto4"),
1075 config: config,
1076 validate: checkNegotiatedProtocol(""),
1077 }
1078 runServerTestTLS12(t, test)
1079 runServerTestTLS13(t, test)
1080 }
1081
1082 func checkServerName(want string) func(ConnectionState) error {
1083 return func(state ConnectionState) error {
1084 if state.ServerName != want {
1085 return fmt.Errorf("got ServerName %q, want %q", state.ServerName, want)
1086 }
1087 return nil
1088 }
1089 }
1090
1091
1092
1093
1094 func TestHandshakeServerSNI(t *testing.T) {
1095 command := slices.Clone(defaultClientCommand)
1096 command[slices.Index(command, "-servername")+1] = "different.example.com"
1097 test := &serverTest{
1098 name: "SNI",
1099 command: command,
1100 validate: checkServerName("different.example.com"),
1101 }
1102 runServerTestTLS12(t, test)
1103 runServerTestTLS13(t, test)
1104 }
1105
1106
1107
1108 func TestHandshakeServerSNIGetCertificate(t *testing.T) {
1109 config := testConfigServer.Clone()
1110 config.GetCertificate = func(clientHello *ClientHelloInfo) (*Certificate, error) {
1111 return &testSNICert, nil
1112 }
1113 command := slices.Clone(defaultClientCommand)
1114 command[slices.Index(command, "-servername")+1] = "different.example.com"
1115 test := &serverTest{
1116 name: "SNI-GetCertificate",
1117 command: command,
1118 config: config,
1119 validate: checkServerName("different.example.com"),
1120 }
1121 runServerTestTLS12(t, test)
1122 runServerTestTLS13(t, test)
1123 }
1124
1125
1126
1127
1128
1129 func TestHandshakeServerSNIGetCertificateNotFound(t *testing.T) {
1130 config := testConfigServer.Clone()
1131 config.GetCertificate = func(clientHello *ClientHelloInfo) (*Certificate, error) {
1132 return nil, nil
1133 }
1134 command := slices.Clone(defaultClientCommand)
1135 command[slices.Index(command, "-servername")+1] = "different.example.com"
1136 test := &serverTest{
1137 name: "SNI-GetCertificateNotFound",
1138 command: command,
1139 config: config,
1140 validate: checkServerName("different.example.com"),
1141 }
1142 runServerTestTLS12(t, test)
1143 runServerTestTLS13(t, test)
1144 }
1145
1146
1147
1148
1149 func TestHandshakeServerGetCertificateExtensions(t *testing.T) {
1150 const errMsg = "TestHandshakeServerGetCertificateExtensions error"
1151
1152
1153 var called atomic.Int32
1154
1155 testVersions := []uint16{VersionTLS12, VersionTLS13}
1156 for _, vers := range testVersions {
1157 t.Run(fmt.Sprintf("TLS version %04x", vers), func(t *testing.T) {
1158 pk, _ := ecdh.P256().GenerateKey(rand.Reader)
1159 clientHello := &clientHelloMsg{
1160 vers: vers,
1161 random: make([]byte, 32),
1162 cipherSuites: []uint16{TLS_AES_128_GCM_SHA256},
1163 compressionMethods: []uint8{compressionNone},
1164 serverName: "test",
1165 keyShares: []keyShare{{group: CurveP256, data: pk.PublicKey().Bytes()}},
1166 supportedCurves: []CurveID{CurveP256},
1167 supportedSignatureAlgorithms: []SignatureScheme{ECDSAWithP256AndSHA256},
1168 }
1169
1170
1171
1172 expectedExtensions := []uint16{
1173 extensionServerName,
1174 extensionSupportedCurves,
1175 extensionSignatureAlgorithms,
1176 extensionKeyShare,
1177 }
1178
1179 if vers == VersionTLS13 {
1180 clientHello.supportedVersions = []uint16{VersionTLS13}
1181 expectedExtensions = append(expectedExtensions, extensionSupportedVersions)
1182 }
1183
1184
1185 slices.Sort(expectedExtensions)
1186
1187 serverConfig := testConfigServer.Clone()
1188 serverConfig.GetCertificate = func(clientHello *ClientHelloInfo) (*Certificate, error) {
1189 if !slices.Equal(expectedExtensions, clientHello.Extensions) {
1190 t.Errorf("expected extensions on ClientHelloInfo (%v) to match clientHelloMsg (%v)", expectedExtensions, clientHello.Extensions)
1191 }
1192 called.Add(1)
1193
1194 return nil, errors.New(errMsg)
1195 }
1196 testClientHelloFailure(t, serverConfig, clientHello, errMsg)
1197 })
1198 }
1199
1200 if int(called.Load()) != len(testVersions) {
1201 t.Error("expected our GetCertificate test to be called twice")
1202 }
1203 }
1204
1205
1206
1207 func TestHandshakeServerSNIGetCertificateError(t *testing.T) {
1208 const errMsg = "TestHandshakeServerSNIGetCertificateError error"
1209
1210 serverConfig := testConfigServer.Clone()
1211 serverConfig.GetCertificate = func(clientHello *ClientHelloInfo) (*Certificate, error) {
1212 return nil, errors.New(errMsg)
1213 }
1214
1215 clientHello := &clientHelloMsg{
1216 vers: VersionTLS12,
1217 random: make([]byte, 32),
1218 cipherSuites: []uint16{TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256},
1219 compressionMethods: []uint8{compressionNone},
1220 serverName: "test",
1221 }
1222 testClientHelloFailure(t, serverConfig, clientHello, errMsg)
1223 }
1224
1225
1226
1227 func TestHandshakeServerEmptyCertificates(t *testing.T) {
1228 const errMsg = "TestHandshakeServerEmptyCertificates error"
1229
1230 serverConfig := testConfigServer.Clone()
1231 serverConfig.GetCertificate = func(clientHello *ClientHelloInfo) (*Certificate, error) {
1232 return nil, errors.New(errMsg)
1233 }
1234 serverConfig.Certificates = nil
1235
1236 clientHello := &clientHelloMsg{
1237 vers: VersionTLS12,
1238 random: make([]byte, 32),
1239 cipherSuites: []uint16{TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256},
1240 compressionMethods: []uint8{compressionNone},
1241 }
1242 testClientHelloFailure(t, serverConfig, clientHello, errMsg)
1243
1244
1245
1246 serverConfig.GetCertificate = nil
1247
1248 clientHello = &clientHelloMsg{
1249 vers: VersionTLS12,
1250 random: make([]byte, 32),
1251 cipherSuites: []uint16{TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256},
1252 compressionMethods: []uint8{compressionNone},
1253 }
1254 testClientHelloFailure(t, serverConfig, clientHello, "no certificates")
1255 }
1256
1257 func checkDidResume(want bool) func(ConnectionState) error {
1258 return func(state ConnectionState) error {
1259 if state.DidResume != want {
1260 return fmt.Errorf("got DidResume %t, want %t", state.DidResume, want)
1261 }
1262 return nil
1263 }
1264 }
1265
1266 func TestServerResumption(t *testing.T) {
1267 sessionFilePath := tempFile("")
1268 defer os.Remove(sessionFilePath)
1269
1270 command := slices.Clone(defaultClientCommand)
1271 command = slices.DeleteFunc(command, func(s string) bool { return s == "-no_ticket" })
1272
1273 testIssue := &serverTest{
1274 name: "IssueTicket",
1275 command: append(command, "-sess_out", sessionFilePath),
1276 }
1277 testResume := &serverTest{
1278 name: "Resume",
1279 command: append(command, "-sess_in", sessionFilePath),
1280 validate: checkDidResume(true),
1281 }
1282
1283 runServerTestTLS12(t, testIssue)
1284 runServerTestTLS12(t, testResume)
1285
1286 runServerTestTLS13(t, testIssue)
1287 runServerTestTLS13(t, testResume)
1288
1289 config := testConfigServer.Clone()
1290 config.CurvePreferences = []CurveID{CurveP256}
1291
1292 testResumeHRR := &serverTest{
1293 name: "Resume-HelloRetryRequest",
1294 command: append(command, "-curves", "X25519:P-256", "-sess_in", sessionFilePath),
1295 config: config,
1296 validate: func(state ConnectionState) error {
1297 if !state.DidResume {
1298 return errors.New("did not resume")
1299 }
1300 if !state.HelloRetryRequest {
1301 return errors.New("expected HelloRetryRequest")
1302 }
1303 return nil
1304 },
1305 }
1306
1307 runServerTestTLS13(t, testResumeHRR)
1308 }
1309
1310 func TestServerResumptionDisabled(t *testing.T) {
1311 sessionFilePath := tempFile("")
1312 defer os.Remove(sessionFilePath)
1313
1314 config := testConfigServer.Clone()
1315 command := slices.Clone(defaultClientCommand)
1316 command = slices.DeleteFunc(command, func(s string) bool { return s == "-no_ticket" })
1317
1318 testIssue := &serverTest{
1319 name: "IssueTicketPreDisable",
1320 command: append(command, "-sess_out", sessionFilePath),
1321 config: config,
1322 }
1323 testResume := &serverTest{
1324 name: "ResumeDisabled",
1325 command: append(command, "-sess_in", sessionFilePath),
1326 config: config,
1327 validate: checkDidResume(false),
1328 }
1329
1330 config.SessionTicketsDisabled = false
1331 runServerTestTLS12(t, testIssue)
1332 config.SessionTicketsDisabled = true
1333 runServerTestTLS12(t, testResume)
1334
1335 config.SessionTicketsDisabled = false
1336 runServerTestTLS13(t, testIssue)
1337 config.SessionTicketsDisabled = true
1338 runServerTestTLS13(t, testResume)
1339 }
1340
1341 func TestFallbackSCSV(t *testing.T) {
1342 test := &serverTest{
1343 name: "FallbackSCSV",
1344 command: append(defaultClientCommand, "--fallback_scsv"),
1345 expectHandshakeErrorIncluding: "inappropriate protocol fallback",
1346 }
1347 runServerTestTLS11(t, test)
1348 }
1349
1350 func TestHandshakeServerExportKeyingMaterial(t *testing.T) {
1351 test := &serverTest{
1352 name: "ExportKeyingMaterial",
1353 validate: func(state ConnectionState) error {
1354 if km, err := state.ExportKeyingMaterial("test", nil, 42); err != nil {
1355 return fmt.Errorf("ExportKeyingMaterial failed: %v", err)
1356 } else if len(km) != 42 {
1357 return fmt.Errorf("Got %d bytes from ExportKeyingMaterial, wanted %d", len(km), 42)
1358 }
1359 return nil
1360 },
1361 }
1362 runServerTestTLS10(t, test)
1363 runServerTestTLS12(t, test)
1364 runServerTestTLS13(t, test)
1365 }
1366
1367 func TestHandshakeServerRSAPKCS1v15(t *testing.T) {
1368 test := &serverTest{
1369 name: "RSA-RSAPKCS1v15",
1370 command: append(defaultClientCommand, "-sigalgs", "rsa_pkcs1_sha256"),
1371 }
1372 runServerTestTLS12(t, test)
1373 }
1374
1375 func TestHandshakeServerRSAPSS(t *testing.T) {
1376 config := testConfigServer.Clone()
1377 config.Certificates = []Certificate{testRSA1024Cert}
1378
1379
1380
1381
1382 test := &serverTest{
1383 name: "RSA-RSAPSS",
1384 config: config,
1385 command: append(defaultClientCommand, "-sigalgs", "rsa_pss_rsae_sha512:rsa_pss_rsae_sha256", "-auth_level", "0"),
1386 }
1387 runServerTestTLS12(t, test)
1388 runServerTestTLS13(t, test)
1389
1390 test = &serverTest{
1391 name: "RSA-RSAPSS-TooSmall",
1392 config: config,
1393 command: append(defaultClientCommand, "-sigalgs", "rsa_pss_rsae_sha512", "-auth_level", "0"),
1394 expectHandshakeErrorIncluding: "peer doesn't support any of the certificate's signature algorithms",
1395 }
1396 runServerTestTLS13(t, test)
1397 }
1398
1399 func TestHandshakeServerEd25519(t *testing.T) {
1400 test := &serverTest{
1401 name: "Ed25519",
1402 command: append(defaultClientCommand, "-sigalgs", "ed25519"),
1403 }
1404 runServerTestTLS12(t, test)
1405 runServerTestTLS13(t, test)
1406 }
1407
1408
1409 type zeroSource struct{}
1410
1411 func (zeroSource) Read(b []byte) (n int, err error) {
1412 clear(b)
1413 return len(b), nil
1414 }
1415
1416 func benchmarkHandshakeServer(b *testing.B, version uint16, cipherSuite uint16, curve CurveID, cert []byte, key crypto.PrivateKey) {
1417 config := testConfigServer.Clone()
1418
1419
1420 internalrand.SetTestingReader(zeroSource{})
1421 defer internalrand.SetTestingReader(nil)
1422
1423 config.CipherSuites = []uint16{cipherSuite}
1424 config.CurvePreferences = []CurveID{curve}
1425 config.Certificates = make([]Certificate, 1)
1426 config.Certificates[0].Certificate = [][]byte{cert}
1427 config.Certificates[0].PrivateKey = key
1428 config.BuildNameToCertificate()
1429
1430 clientConn, serverConn := localPipe(b)
1431 serverConn = &recordingConn{Conn: serverConn}
1432 go func() {
1433 config := testConfigClient.Clone()
1434 config.MaxVersion = version
1435 config.CipherSuites = []uint16{cipherSuite}
1436 config.CurvePreferences = []CurveID{curve}
1437 client := Client(clientConn, config)
1438 client.Handshake()
1439 }()
1440 server := Server(serverConn, config)
1441 if err := server.Handshake(); err != nil {
1442 b.Fatalf("handshake failed: %v", err)
1443 }
1444 serverConn.Close()
1445 flows := serverConn.(*recordingConn).flows
1446
1447 b.ResetTimer()
1448 for i := 0; i < b.N; i++ {
1449 replay := &replayingConn{t: b, flows: slices.Clone(flows), reading: true}
1450 server := Server(replay, config)
1451 if err := server.Handshake(); err != nil {
1452 b.Fatalf("handshake failed: %v", err)
1453 }
1454 }
1455 }
1456
1457 func BenchmarkHandshakeServer(b *testing.B) {
1458 b.Run("RSA", func(b *testing.B) {
1459 benchmarkHandshakeServer(b, VersionTLS12, TLS_RSA_WITH_AES_128_GCM_SHA256,
1460 0, testRSA2048Cert.Certificate[0], testRSA2048Key)
1461 })
1462 b.Run("ECDHE-P256-RSA", func(b *testing.B) {
1463 b.Run("TLSv13", func(b *testing.B) {
1464 benchmarkHandshakeServer(b, VersionTLS13, TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256,
1465 CurveP256, testRSA2048Cert.Certificate[0], testRSA2048Key)
1466 })
1467 b.Run("TLSv12", func(b *testing.B) {
1468 benchmarkHandshakeServer(b, VersionTLS12, TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256,
1469 CurveP256, testRSA2048Cert.Certificate[0], testRSA2048Key)
1470 })
1471 })
1472 b.Run("ECDHE-P256-ECDSA-P256", func(b *testing.B) {
1473 b.Run("TLSv13", func(b *testing.B) {
1474 benchmarkHandshakeServer(b, VersionTLS13, TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256,
1475 CurveP256, testECDSAP256Cert.Certificate[0], testECDSAP256Key)
1476 })
1477 b.Run("TLSv12", func(b *testing.B) {
1478 benchmarkHandshakeServer(b, VersionTLS12, TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256,
1479 CurveP256, testECDSAP256Cert.Certificate[0], testECDSAP256Key)
1480 })
1481 })
1482 b.Run("ECDHE-X25519-ECDSA-P256", func(b *testing.B) {
1483 b.Run("TLSv13", func(b *testing.B) {
1484 benchmarkHandshakeServer(b, VersionTLS13, TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256,
1485 X25519, testECDSAP256Cert.Certificate[0], testECDSAP256Key)
1486 })
1487 b.Run("TLSv12", func(b *testing.B) {
1488 benchmarkHandshakeServer(b, VersionTLS12, TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256,
1489 X25519, testECDSAP256Cert.Certificate[0], testECDSAP256Key)
1490 })
1491 })
1492 b.Run("ECDHE-P521-ECDSA-P521", func(b *testing.B) {
1493 if testECDSAP521Key.PublicKey.Curve != elliptic.P521() {
1494 b.Fatal("test ECDSA key doesn't use curve P-521")
1495 }
1496 b.Run("TLSv13", func(b *testing.B) {
1497 benchmarkHandshakeServer(b, VersionTLS13, TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256,
1498 CurveP521, testECDSAP521Cert.Certificate[0], testECDSAP521Key)
1499 })
1500 b.Run("TLSv12", func(b *testing.B) {
1501 benchmarkHandshakeServer(b, VersionTLS12, TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256,
1502 CurveP521, testECDSAP521Cert.Certificate[0], testECDSAP521Key)
1503 })
1504 })
1505 }
1506
1507 func TestClientAuth(t *testing.T) {
1508 var certPath, keyPath, ecdsaCertPath, ecdsaKeyPath, ed25519CertPath, ed25519KeyPath string
1509
1510 if *update {
1511 certPath = tempFile(testClientRSA2048CertPEM)
1512 defer os.Remove(certPath)
1513 keyPath = tempFile(testingKey(testClientRSA2048KeyPEM))
1514 defer os.Remove(keyPath)
1515 ecdsaCertPath = tempFile(testClientECDSAP256CertPEM)
1516 defer os.Remove(ecdsaCertPath)
1517 ecdsaKeyPath = tempFile(testingKey(testClientECDSAP256KeyPEM))
1518 defer os.Remove(ecdsaKeyPath)
1519 ed25519CertPath = tempFile(testClientEd25519CertPEM)
1520 defer os.Remove(ed25519CertPath)
1521 ed25519KeyPath = tempFile(testingKey(testClientEd25519KeyPEM))
1522 defer os.Remove(ed25519KeyPath)
1523 }
1524
1525 config := testConfigServer.Clone()
1526 config.ClientAuth = RequestClientCert
1527
1528 test := &serverTest{
1529 name: "ClientAuthRequestedNotGiven",
1530 config: config,
1531 }
1532 runServerTestTLS12(t, test)
1533 runServerTestTLS13(t, test)
1534
1535 test = &serverTest{
1536 name: "ClientAuthRequestedAndGiven",
1537 command: append(defaultClientCommand, "-cert", certPath, "-key", keyPath, "-client_sigalgs", "rsa_pss_rsae_sha256"),
1538 config: config,
1539 expectedPeerCerts: []string{testClientRSA2048CertPEM},
1540 }
1541 runServerTestTLS12(t, test)
1542 runServerTestTLS13(t, test)
1543
1544 test = &serverTest{
1545 name: "ClientAuthRequestedAndECDSAGiven",
1546 command: append(defaultClientCommand, "-cert", ecdsaCertPath, "-key", ecdsaKeyPath),
1547 config: config,
1548 expectedPeerCerts: []string{testClientECDSAP256CertPEM},
1549 }
1550 runServerTestTLS12(t, test)
1551 runServerTestTLS13(t, test)
1552
1553 test = &serverTest{
1554 name: "ClientAuthRequestedAndEd25519Given",
1555 command: append(defaultClientCommand, "-cert", ed25519CertPath, "-key", ed25519KeyPath),
1556 config: config,
1557 expectedPeerCerts: []string{testClientEd25519CertPEM},
1558 }
1559 runServerTestTLS12(t, test)
1560 runServerTestTLS13(t, test)
1561
1562 test = &serverTest{
1563 name: "ClientAuthRequestedAndPKCS1v15Given",
1564 command: append(defaultClientCommand, "-cert", certPath, "-key", keyPath, "-client_sigalgs", "rsa_pkcs1_sha256"),
1565 config: config,
1566 expectedPeerCerts: []string{testClientRSA2048CertPEM},
1567 }
1568 runServerTestTLS12(t, test)
1569 }
1570
1571 func TestSNIGivenOnFailure(t *testing.T) {
1572 const expectedServerName = "test.testing"
1573
1574 clientHello := &clientHelloMsg{
1575 vers: VersionTLS12,
1576 random: make([]byte, 32),
1577 cipherSuites: []uint16{TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256},
1578 compressionMethods: []uint8{compressionNone},
1579 serverName: expectedServerName,
1580 }
1581
1582 serverConfig := testConfigServer.Clone()
1583
1584 serverConfig.CipherSuites = nil
1585
1586 c, s := localPipe(t)
1587 go func() {
1588 cli := Client(c, testConfigClient.Clone())
1589 cli.vers = clientHello.vers
1590 if _, err := cli.writeHandshakeRecord(clientHello, nil); err != nil {
1591 testFatal(t, err)
1592 }
1593 c.Close()
1594 }()
1595 conn := Server(s, serverConfig)
1596 ctx := context.Background()
1597 ch, _, err := conn.readClientHello(ctx)
1598 hs := serverHandshakeState{
1599 c: conn,
1600 ctx: ctx,
1601 clientHello: ch,
1602 }
1603 if err == nil {
1604 err = hs.processClientHello()
1605 }
1606 if err == nil {
1607 err = hs.pickCipherSuite()
1608 }
1609 defer s.Close()
1610
1611 if err == nil {
1612 t.Error("No error reported from server")
1613 }
1614
1615 cs := hs.c.ConnectionState()
1616 if cs.HandshakeComplete {
1617 t.Error("Handshake registered as complete")
1618 }
1619
1620 if cs.ServerName != expectedServerName {
1621 t.Errorf("Expected ServerName of %q, but got %q", expectedServerName, cs.ServerName)
1622 }
1623 }
1624
1625 var getConfigForClientTests = []struct {
1626 setup func(config *Config)
1627 callback func(clientHello *ClientHelloInfo) (*Config, error)
1628 errorSubstring string
1629 verify func(config *Config) error
1630 }{
1631 {
1632 nil,
1633 func(clientHello *ClientHelloInfo) (*Config, error) {
1634 return nil, nil
1635 },
1636 "",
1637 nil,
1638 },
1639 {
1640 nil,
1641 func(clientHello *ClientHelloInfo) (*Config, error) {
1642 return nil, errors.New("should bubble up")
1643 },
1644 "should bubble up",
1645 nil,
1646 },
1647 {
1648 nil,
1649 func(clientHello *ClientHelloInfo) (*Config, error) {
1650 config := testConfigServer.Clone()
1651
1652
1653 config.MaxVersion = VersionTLS11
1654 return config, nil
1655 },
1656 "client offered only unsupported versions",
1657 nil,
1658 },
1659 {
1660 func(config *Config) {
1661 for i := range config.SessionTicketKey {
1662 config.SessionTicketKey[i] = byte(i)
1663 }
1664 config.sessionTicketKeys = nil
1665 },
1666 func(clientHello *ClientHelloInfo) (*Config, error) {
1667 config := testConfigServer.Clone()
1668 clear(config.SessionTicketKey[:])
1669 config.sessionTicketKeys = nil
1670 return config, nil
1671 },
1672 "",
1673 func(config *Config) error {
1674 if config.SessionTicketKey == [32]byte{} {
1675 return fmt.Errorf("expected SessionTicketKey to be set")
1676 }
1677 return nil
1678 },
1679 },
1680 {
1681 func(config *Config) {
1682 var dummyKey [32]byte
1683 for i := range dummyKey {
1684 dummyKey[i] = byte(i)
1685 }
1686
1687 config.SetSessionTicketKeys([][32]byte{dummyKey})
1688 },
1689 func(clientHello *ClientHelloInfo) (*Config, error) {
1690 config := testConfigServer.Clone()
1691 config.sessionTicketKeys = nil
1692 return config, nil
1693 },
1694 "",
1695 func(config *Config) error {
1696 if config.SessionTicketKey == [32]byte{} {
1697 return fmt.Errorf("expected SessionTicketKey to be set")
1698 }
1699 return nil
1700 },
1701 },
1702 }
1703
1704 func TestGetConfigForClient(t *testing.T) {
1705 serverConfig := testConfigServer.Clone()
1706 clientConfig := testConfigClient.Clone()
1707 clientConfig.MinVersion = VersionTLS12
1708
1709 for i, test := range getConfigForClientTests {
1710 if test.setup != nil {
1711 test.setup(serverConfig)
1712 }
1713
1714 var configReturned *Config
1715 serverConfig.GetConfigForClient = func(clientHello *ClientHelloInfo) (*Config, error) {
1716 config, err := test.callback(clientHello)
1717 configReturned = config
1718 return config, err
1719 }
1720 c, s := localPipe(t)
1721 done := make(chan error)
1722
1723 go func() {
1724 defer s.Close()
1725 done <- Server(s, serverConfig).Handshake()
1726 }()
1727
1728 clientErr := Client(c, clientConfig).Handshake()
1729 c.Close()
1730
1731 serverErr := <-done
1732
1733 if len(test.errorSubstring) == 0 {
1734 if serverErr != nil || clientErr != nil {
1735 t.Errorf("test[%d]: expected no error but got serverErr: %q, clientErr: %q", i, serverErr, clientErr)
1736 }
1737 if test.verify != nil {
1738 if err := test.verify(configReturned); err != nil {
1739 t.Errorf("test[%d]: verify returned error: %v", i, err)
1740 }
1741 }
1742 } else {
1743 if serverErr == nil {
1744 t.Errorf("test[%d]: expected error containing %q but got no error", i, test.errorSubstring)
1745 } else if !strings.Contains(serverErr.Error(), test.errorSubstring) {
1746 t.Errorf("test[%d]: expected error to contain %q but it was %q", i, test.errorSubstring, serverErr)
1747 }
1748 }
1749 }
1750 }
1751
1752 func TestCloseServerConnectionOnIdleClient(t *testing.T) {
1753 clientConn, serverConn := localPipe(t)
1754 server := Server(serverConn, testConfigServer.Clone())
1755 go func() {
1756 clientConn.Write([]byte{'0'})
1757 server.Close()
1758 }()
1759 server.SetReadDeadline(time.Now().Add(time.Minute))
1760 err := server.Handshake()
1761 if err != nil {
1762 if err, ok := err.(net.Error); ok && err.Timeout() {
1763 t.Errorf("Expected a closed network connection error but got '%s'", err.Error())
1764 }
1765 } else {
1766 t.Errorf("Error expected, but no error returned")
1767 }
1768 }
1769
1770 func TestCloneHash(t *testing.T) {
1771 h1 := crypto.SHA256.New()
1772 h1.Write([]byte("test"))
1773 s1 := h1.Sum(nil)
1774 h2 := cloneHash(h1, crypto.SHA256)
1775 s2 := h2.Sum(nil)
1776 if !bytes.Equal(s1, s2) {
1777 t.Error("cloned hash generated a different sum")
1778 }
1779 }
1780
1781 func expectError(t *testing.T, err error, sub string) {
1782 if err == nil {
1783 t.Errorf(`expected error %q, got nil`, sub)
1784 } else if !strings.Contains(err.Error(), sub) {
1785 t.Errorf(`expected error %q, got %q`, sub, err)
1786 }
1787 }
1788
1789 func TestKeyTooSmallForRSAPSS(t *testing.T) {
1790 testenv.SetGODEBUG(t, "rsa1024min=0")
1791 clientConn, serverConn := localPipe(t)
1792 client := Client(clientConn, testConfigClient.Clone())
1793 done := make(chan struct{})
1794 go func() {
1795 config := testConfigServer.Clone()
1796 config.Certificates = []Certificate{testRSA512Cert}
1797 config.MinVersion = VersionTLS13
1798 server := Server(serverConn, config)
1799 err := server.Handshake()
1800 expectError(t, err, "key size too small")
1801 close(done)
1802 }()
1803 err := client.Handshake()
1804 expectError(t, err, "handshake failure")
1805 <-done
1806 }
1807
1808 func TestMultipleCertificates(t *testing.T) {
1809 clientConfig := testConfigClient.Clone()
1810 clientConfig.CipherSuites = []uint16{TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256}
1811 clientConfig.MaxVersion = VersionTLS12
1812
1813 serverConfig := testConfigServer.Clone()
1814 serverConfig.Certificates = []Certificate{testECDSAP256Cert, testRSA2048Cert}
1815
1816 _, clientState, err := testHandshake(t, clientConfig, serverConfig)
1817 if err != nil {
1818 t.Fatal(err)
1819 }
1820 if got := clientState.PeerCertificates[0].PublicKeyAlgorithm; got != x509.RSA {
1821 t.Errorf("expected RSA certificate, got %v", got)
1822 }
1823 }
1824
1825 func TestAESCipherReordering(t *testing.T) {
1826 skipFIPS(t)
1827
1828 currentAESSupport := hasAESGCMHardwareSupport
1829 defer func() { hasAESGCMHardwareSupport = currentAESSupport }()
1830
1831 tests := []struct {
1832 name string
1833 clientCiphers []uint16
1834 serverHasAESGCM bool
1835 serverCiphers []uint16
1836 expectedCipher uint16
1837 }{
1838 {
1839 name: "server has hardware AES, client doesn't (pick ChaCha)",
1840 clientCiphers: []uint16{
1841 TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256,
1842 TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
1843 TLS_RSA_WITH_AES_128_CBC_SHA,
1844 },
1845 serverHasAESGCM: true,
1846 expectedCipher: TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256,
1847 },
1848 {
1849 name: "client prefers AES-GCM, server doesn't have hardware AES (pick ChaCha)",
1850 clientCiphers: []uint16{
1851 TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
1852 TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256,
1853 TLS_RSA_WITH_AES_128_CBC_SHA,
1854 },
1855 serverHasAESGCM: false,
1856 expectedCipher: TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256,
1857 },
1858 {
1859 name: "client prefers AES-GCM, server has hardware AES (pick AES-GCM)",
1860 clientCiphers: []uint16{
1861 TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
1862 TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256,
1863 TLS_RSA_WITH_AES_128_CBC_SHA,
1864 },
1865 serverHasAESGCM: true,
1866 expectedCipher: TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
1867 },
1868 {
1869 name: "client prefers AES-GCM and sends GREASE, server has hardware AES (pick AES-GCM)",
1870 clientCiphers: []uint16{
1871 0x0A0A,
1872 TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
1873 TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256,
1874 TLS_RSA_WITH_AES_128_CBC_SHA,
1875 },
1876 serverHasAESGCM: true,
1877 expectedCipher: TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
1878 },
1879 {
1880 name: "client prefers AES-GCM and doesn't support ChaCha, server doesn't have hardware AES (pick AES-GCM)",
1881 clientCiphers: []uint16{
1882 TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
1883 TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
1884 TLS_RSA_WITH_AES_128_CBC_SHA,
1885 },
1886 serverHasAESGCM: false,
1887 expectedCipher: TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
1888 },
1889 {
1890 name: "client prefers AES-GCM and AES-CBC over ChaCha, server doesn't have hardware AES (pick ChaCha)",
1891 clientCiphers: []uint16{
1892 TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
1893 TLS_RSA_WITH_AES_128_CBC_SHA,
1894 TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256,
1895 },
1896 serverHasAESGCM: false,
1897 expectedCipher: TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256,
1898 },
1899 {
1900 name: "client prefers AES-GCM over ChaCha and sends GREASE, server doesn't have hardware AES (pick ChaCha)",
1901 clientCiphers: []uint16{
1902 0x0A0A,
1903 TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
1904 TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256,
1905 TLS_RSA_WITH_AES_128_CBC_SHA,
1906 },
1907 serverHasAESGCM: false,
1908 expectedCipher: TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256,
1909 },
1910 {
1911 name: "client supports multiple AES-GCM, server doesn't have hardware AES and doesn't support ChaCha (AES-GCM)",
1912 clientCiphers: []uint16{
1913 TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
1914 TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256,
1915 TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
1916 },
1917 serverHasAESGCM: false,
1918 serverCiphers: []uint16{
1919 TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
1920 TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
1921 },
1922 expectedCipher: TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
1923 },
1924 {
1925 name: "client prefers AES-GCM, server has hardware but doesn't support AES (pick ChaCha)",
1926 clientCiphers: []uint16{
1927 TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
1928 TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256,
1929 TLS_RSA_WITH_AES_128_CBC_SHA,
1930 },
1931 serverHasAESGCM: true,
1932 serverCiphers: []uint16{
1933 TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256,
1934 },
1935 expectedCipher: TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256,
1936 },
1937 }
1938
1939 for _, tc := range tests {
1940 t.Run(tc.name, func(t *testing.T) {
1941 hasAESGCMHardwareSupport = tc.serverHasAESGCM
1942 hs := &serverHandshakeState{
1943 c: &Conn{
1944 config: &Config{
1945 CipherSuites: tc.serverCiphers,
1946 },
1947 vers: VersionTLS12,
1948 },
1949 clientHello: &clientHelloMsg{
1950 cipherSuites: tc.clientCiphers,
1951 vers: VersionTLS12,
1952 },
1953 ecdheOk: true,
1954 rsaSignOk: true,
1955 rsaDecryptOk: true,
1956 }
1957
1958 err := hs.pickCipherSuite()
1959 if err != nil {
1960 t.Errorf("pickCipherSuite failed: %s", err)
1961 }
1962
1963 if tc.expectedCipher != hs.suite.id {
1964 t.Errorf("unexpected cipher chosen: want %d, got %d", tc.expectedCipher, hs.suite.id)
1965 }
1966 })
1967 }
1968 }
1969
1970 func TestAESCipherReorderingTLS13(t *testing.T) {
1971 skipFIPS(t)
1972
1973 currentAESSupport := hasAESGCMHardwareSupport
1974 defer func() { hasAESGCMHardwareSupport = currentAESSupport }()
1975
1976 tests := []struct {
1977 name string
1978 clientCiphers []uint16
1979 serverHasAESGCM bool
1980 expectedCipher uint16
1981 }{
1982 {
1983 name: "server has hardware AES, client doesn't (pick ChaCha)",
1984 clientCiphers: []uint16{
1985 TLS_CHACHA20_POLY1305_SHA256,
1986 TLS_AES_128_GCM_SHA256,
1987 },
1988 serverHasAESGCM: true,
1989 expectedCipher: TLS_CHACHA20_POLY1305_SHA256,
1990 },
1991 {
1992 name: "neither server nor client have hardware AES (pick ChaCha)",
1993 clientCiphers: []uint16{
1994 TLS_CHACHA20_POLY1305_SHA256,
1995 TLS_AES_128_GCM_SHA256,
1996 },
1997 serverHasAESGCM: false,
1998 expectedCipher: TLS_CHACHA20_POLY1305_SHA256,
1999 },
2000 {
2001 name: "client prefers AES, server doesn't have hardware (pick ChaCha)",
2002 clientCiphers: []uint16{
2003 TLS_AES_128_GCM_SHA256,
2004 TLS_CHACHA20_POLY1305_SHA256,
2005 },
2006 serverHasAESGCM: false,
2007 expectedCipher: TLS_CHACHA20_POLY1305_SHA256,
2008 },
2009 {
2010 name: "client prefers AES and sends GREASE, server doesn't have hardware (pick ChaCha)",
2011 clientCiphers: []uint16{
2012 0x0A0A,
2013 TLS_AES_128_GCM_SHA256,
2014 TLS_CHACHA20_POLY1305_SHA256,
2015 },
2016 serverHasAESGCM: false,
2017 expectedCipher: TLS_CHACHA20_POLY1305_SHA256,
2018 },
2019 {
2020 name: "client prefers AES, server has hardware AES (pick AES)",
2021 clientCiphers: []uint16{
2022 TLS_AES_128_GCM_SHA256,
2023 TLS_CHACHA20_POLY1305_SHA256,
2024 },
2025 serverHasAESGCM: true,
2026 expectedCipher: TLS_AES_128_GCM_SHA256,
2027 },
2028 {
2029 name: "client prefers AES and sends GREASE, server has hardware AES (pick AES)",
2030 clientCiphers: []uint16{
2031 0x0A0A,
2032 TLS_AES_128_GCM_SHA256,
2033 TLS_CHACHA20_POLY1305_SHA256,
2034 },
2035 serverHasAESGCM: true,
2036 expectedCipher: TLS_AES_128_GCM_SHA256,
2037 },
2038 }
2039
2040 for _, tc := range tests {
2041 t.Run(tc.name, func(t *testing.T) {
2042 hasAESGCMHardwareSupport = tc.serverHasAESGCM
2043 pk, _ := ecdh.X25519().GenerateKey(rand.Reader)
2044 hs := &serverHandshakeStateTLS13{
2045 c: &Conn{
2046 config: &Config{},
2047 vers: VersionTLS13,
2048 },
2049 clientHello: &clientHelloMsg{
2050 cipherSuites: tc.clientCiphers,
2051 supportedVersions: []uint16{VersionTLS13},
2052 compressionMethods: []uint8{compressionNone},
2053 keyShares: []keyShare{{group: X25519, data: pk.PublicKey().Bytes()}},
2054 supportedCurves: []CurveID{X25519},
2055 },
2056 }
2057
2058 err := hs.processClientHello()
2059 if err != nil {
2060 t.Errorf("pickCipherSuite failed: %s", err)
2061 }
2062
2063 if tc.expectedCipher != hs.suite.id {
2064 t.Errorf("unexpected cipher chosen: want %d, got %d", tc.expectedCipher, hs.suite.id)
2065 }
2066 })
2067 }
2068 }
2069
2070
2071
2072
2073 func TestServerHandshakeContextCancellation(t *testing.T) {
2074 c, s := localPipe(t)
2075 ctx, cancel := context.WithCancel(context.Background())
2076 unblockClient := make(chan struct{})
2077 defer close(unblockClient)
2078 go func() {
2079 cancel()
2080 <-unblockClient
2081 _ = c.Close()
2082 }()
2083 conn := Server(s, testConfigServer.Clone())
2084
2085
2086 err := conn.HandshakeContext(ctx)
2087 if err == nil {
2088 t.Fatal("Server handshake did not error when the context was canceled")
2089 }
2090 if err != context.Canceled {
2091 t.Errorf("Unexpected server handshake error: %v", err)
2092 }
2093 if runtime.GOOS == "js" || runtime.GOOS == "wasip1" {
2094 t.Skip("conn.Close does not error as expected when called multiple times on GOOS=js or GOOS=wasip1")
2095 }
2096 err = conn.Close()
2097 if err == nil {
2098 t.Error("Server connection was not closed when the context was canceled")
2099 }
2100 }
2101
2102
2103
2104
2105
2106
2107 func TestHandshakeContextHierarchy(t *testing.T) {
2108 c, s := localPipe(t)
2109 clientErr := make(chan error, 1)
2110 clientConfig := testConfigClient.Clone()
2111 serverConfig := testConfigServer.Clone()
2112 ctx, cancel := context.WithCancel(context.Background())
2113 defer cancel()
2114 key := struct{}{}
2115 ctx = context.WithValue(ctx, key, true)
2116 go func() {
2117 defer close(clientErr)
2118 defer c.Close()
2119 var innerCtx context.Context
2120 clientConfig.Certificates = nil
2121 clientConfig.GetClientCertificate = func(certificateRequest *CertificateRequestInfo) (*Certificate, error) {
2122 if val, ok := certificateRequest.Context().Value(key).(bool); !ok || !val {
2123 t.Errorf("GetClientCertificate context was not child of HandshakeContext")
2124 }
2125 innerCtx = certificateRequest.Context()
2126 return &testRSA2048Cert, nil
2127 }
2128 cli := Client(c, clientConfig)
2129 err := cli.HandshakeContext(ctx)
2130 if err != nil {
2131 clientErr <- err
2132 return
2133 }
2134 select {
2135 case <-innerCtx.Done():
2136 default:
2137 t.Errorf("GetClientCertificate context was not canceled after HandshakeContext returned.")
2138 }
2139 }()
2140 var innerCtx context.Context
2141 serverConfig.Certificates = nil
2142 serverConfig.ClientAuth = RequestClientCert
2143 serverConfig.GetCertificate = func(clientHello *ClientHelloInfo) (*Certificate, error) {
2144 if val, ok := clientHello.Context().Value(key).(bool); !ok || !val {
2145 t.Errorf("GetClientCertificate context was not child of HandshakeContext")
2146 }
2147 innerCtx = clientHello.Context()
2148 return &testRSA2048Cert, nil
2149 }
2150 conn := Server(s, serverConfig)
2151 err := conn.HandshakeContext(ctx)
2152 if err != nil {
2153 t.Errorf("Unexpected server handshake error: %v", err)
2154 }
2155 select {
2156 case <-innerCtx.Done():
2157 default:
2158 t.Errorf("GetCertificate context was not canceled after HandshakeContext returned.")
2159 }
2160 if err := <-clientErr; err != nil {
2161 t.Errorf("Unexpected client error: %v", err)
2162 }
2163 }
2164
2165 func TestHandshakeChainExpiryResumption(t *testing.T) {
2166 t.Run("TLS1.2", func(t *testing.T) {
2167 testHandshakeChainExpiryResumption(t, VersionTLS12)
2168 })
2169 t.Run("TLS1.3", func(t *testing.T) {
2170 testHandshakeChainExpiryResumption(t, VersionTLS13)
2171 })
2172 }
2173
2174 func testHandshakeChainExpiryResumption(t *testing.T, version uint16) {
2175 now := time.Now()
2176
2177 createChain := func(leafNotAfter, rootNotAfter time.Time) (leafDER, expiredLeafDER []byte, root *x509.Certificate) {
2178 tmpl := &x509.Certificate{
2179 Subject: pkix.Name{CommonName: "root"},
2180 NotBefore: rootNotAfter.Add(-time.Hour * 24),
2181 NotAfter: rootNotAfter,
2182 IsCA: true,
2183 BasicConstraintsValid: true,
2184 }
2185 rootDER, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, &testECDSAP521Key.PublicKey, testECDSAP521Key)
2186 if err != nil {
2187 t.Fatalf("CreateCertificate: %v", err)
2188 }
2189 root, err = x509.ParseCertificate(rootDER)
2190 if err != nil {
2191 t.Fatalf("ParseCertificate: %v", err)
2192 }
2193
2194 tmpl = &x509.Certificate{
2195 Subject: pkix.Name{},
2196 DNSNames: []string{"expired-resume.example.com"},
2197 NotBefore: leafNotAfter.Add(-time.Hour * 24),
2198 NotAfter: leafNotAfter,
2199 KeyUsage: x509.KeyUsageDigitalSignature,
2200 }
2201 leafCertDER, err := x509.CreateCertificate(rand.Reader, tmpl, root, &testECDSAP256Key.PublicKey, testECDSAP521Key)
2202 if err != nil {
2203 t.Fatalf("CreateCertificate: %v", err)
2204 }
2205 tmpl.NotBefore, tmpl.NotAfter = leafNotAfter.Add(-time.Hour*24*365), leafNotAfter.Add(-time.Hour*24*364)
2206 expiredLeafDERCertDER, err := x509.CreateCertificate(rand.Reader, tmpl, root, &testECDSAP256Key.PublicKey, testECDSAP521Key)
2207 if err != nil {
2208 t.Fatalf("CreateCertificate: %v", err)
2209 }
2210
2211 return leafCertDER, expiredLeafDERCertDER, root
2212 }
2213 testExpiration := func(name string, leafNotAfter, rootNotAfter time.Time) {
2214 t.Run(name, func(t *testing.T) {
2215 initialLeafDER, expiredLeafDER, initialRoot := createChain(leafNotAfter, rootNotAfter)
2216
2217 serverConfig := testConfigServer.Clone()
2218 serverConfig.MaxVersion = version
2219 serverConfig.Certificates = []Certificate{{
2220 Certificate: [][]byte{initialLeafDER, expiredLeafDER},
2221 PrivateKey: testECDSAP256Key,
2222 }}
2223 serverConfig.ClientCAs = x509.NewCertPool()
2224 serverConfig.ClientCAs.AddCert(initialRoot)
2225 serverConfig.ClientAuth = RequireAndVerifyClientCert
2226 serverConfig.Time = func() time.Time {
2227 return now
2228 }
2229 serverConfig.InsecureSkipVerify = false
2230 serverConfig.ServerName = "expired-resume.example.com"
2231
2232 clientConfig := testConfigClient.Clone()
2233 clientConfig.MaxVersion = version
2234 clientConfig.Certificates = []Certificate{{
2235 Certificate: [][]byte{initialLeafDER, expiredLeafDER},
2236 PrivateKey: testECDSAP256Key,
2237 }}
2238 clientConfig.RootCAs = x509.NewCertPool()
2239 clientConfig.RootCAs.AddCert(initialRoot)
2240 clientConfig.ServerName = "expired-resume.example.com"
2241 clientConfig.ClientSessionCache = NewLRUClientSessionCache(32)
2242 clientConfig.InsecureSkipVerify = false
2243 clientConfig.ServerName = "expired-resume.example.com"
2244 clientConfig.Time = func() time.Time {
2245 return now
2246 }
2247
2248 testResume := func(t *testing.T, sc, cc *Config, expectResume bool) {
2249 t.Helper()
2250 ss, cs, err := testHandshake(t, cc, sc)
2251 if err != nil {
2252 t.Fatalf("handshake: %v", err)
2253 }
2254 if cs.DidResume != expectResume {
2255 t.Fatalf("DidResume = %v; want %v", cs.DidResume, expectResume)
2256 }
2257 if ss.DidResume != expectResume {
2258 t.Fatalf("DidResume = %v; want %v", cs.DidResume, expectResume)
2259 }
2260 }
2261
2262 testResume(t, serverConfig, clientConfig, false)
2263 testResume(t, serverConfig, clientConfig, true)
2264
2265 expiredNow := time.Unix(0, min(leafNotAfter.UnixNano(), rootNotAfter.UnixNano())).Add(time.Minute)
2266
2267 freshLeafDER, expiredLeafDER, freshRoot := createChain(expiredNow.Add(time.Hour), expiredNow.Add(time.Hour))
2268 clientConfig.Certificates = []Certificate{{
2269 Certificate: [][]byte{freshLeafDER, expiredLeafDER},
2270 PrivateKey: testECDSAP256Key,
2271 }}
2272 serverConfig.Time = func() time.Time {
2273 return expiredNow
2274 }
2275 serverConfig.ClientCAs = x509.NewCertPool()
2276 serverConfig.ClientCAs.AddCert(freshRoot)
2277
2278 testResume(t, serverConfig, clientConfig, false)
2279 })
2280 }
2281
2282 testExpiration("LeafExpiresBeforeRoot", now.Add(2*time.Hour), now.Add(3*time.Hour))
2283 testExpiration("LeafExpiresAfterRoot", now.Add(2*time.Hour), now.Add(time.Hour))
2284 }
2285
2286 func TestHandshakeGetConfigForClientDifferentClientCAs(t *testing.T) {
2287 t.Run("TLS1.2", func(t *testing.T) {
2288 testHandshakeGetConfigForClientDifferentClientCAs(t, VersionTLS12)
2289 })
2290 t.Run("TLS1.3", func(t *testing.T) {
2291 testHandshakeGetConfigForClientDifferentClientCAs(t, VersionTLS13)
2292 })
2293 }
2294
2295 func testHandshakeGetConfigForClientDifferentClientCAs(t *testing.T, version uint16) {
2296 now := time.Now()
2297 tmpl := &x509.Certificate{
2298 Subject: pkix.Name{CommonName: "root"},
2299 NotBefore: now.Add(-time.Hour * 24),
2300 NotAfter: now.Add(time.Hour * 24),
2301 IsCA: true,
2302 BasicConstraintsValid: true,
2303 }
2304 rootDER, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, &testECDSAP521Key.PublicKey, testECDSAP521Key)
2305 if err != nil {
2306 t.Fatalf("CreateCertificate: %v", err)
2307 }
2308 rootA, err := x509.ParseCertificate(rootDER)
2309 if err != nil {
2310 t.Fatalf("ParseCertificate: %v", err)
2311 }
2312 rootDER, err = x509.CreateCertificate(rand.Reader, tmpl, tmpl, &testRSA2048Key.PublicKey, testRSA2048Key)
2313 if err != nil {
2314 t.Fatalf("CreateCertificate: %v", err)
2315 }
2316 rootB, err := x509.ParseCertificate(rootDER)
2317 if err != nil {
2318 t.Fatalf("ParseCertificate: %v", err)
2319 }
2320
2321 tmpl = &x509.Certificate{
2322 Subject: pkix.Name{},
2323 DNSNames: []string{"example.com"},
2324 NotBefore: now.Add(-time.Hour * 24),
2325 NotAfter: now.Add(time.Hour * 24),
2326 KeyUsage: x509.KeyUsageDigitalSignature,
2327 }
2328 certA, err := x509.CreateCertificate(rand.Reader, tmpl, rootA, &testECDSAP256Key.PublicKey, testECDSAP521Key)
2329 if err != nil {
2330 t.Fatalf("CreateCertificate: %v", err)
2331 }
2332 certB, err := x509.CreateCertificate(rand.Reader, tmpl, rootB, &testECDSAP256Key.PublicKey, testRSA2048Key)
2333 if err != nil {
2334 t.Fatalf("CreateCertificate: %v", err)
2335 }
2336
2337 serverConfig := testConfigServer.Clone()
2338 serverConfig.MaxVersion = version
2339 serverConfig.Certificates = []Certificate{{
2340 Certificate: [][]byte{certA},
2341 PrivateKey: testECDSAP256Key,
2342 }}
2343 serverConfig.Time = func() time.Time {
2344 return now
2345 }
2346 serverConfig.ClientCAs = x509.NewCertPool()
2347 serverConfig.ClientCAs.AddCert(rootA)
2348 serverConfig.ClientAuth = RequireAndVerifyClientCert
2349 switchConfig := false
2350 serverConfig.GetConfigForClient = func(clientHello *ClientHelloInfo) (*Config, error) {
2351 if !switchConfig {
2352 return nil, nil
2353 }
2354 cfg := serverConfig.Clone()
2355 cfg.ClientCAs = x509.NewCertPool()
2356 cfg.ClientCAs.AddCert(rootB)
2357 return cfg, nil
2358 }
2359 serverConfig.InsecureSkipVerify = false
2360 serverConfig.ServerName = "example.com"
2361
2362 clientConfig := testConfigClient.Clone()
2363 clientConfig.MaxVersion = version
2364 clientConfig.Certificates = []Certificate{{
2365 Certificate: [][]byte{certA},
2366 PrivateKey: testECDSAP256Key,
2367 }}
2368 clientConfig.ClientSessionCache = NewLRUClientSessionCache(32)
2369 clientConfig.RootCAs = x509.NewCertPool()
2370 clientConfig.RootCAs.AddCert(rootA)
2371 clientConfig.Time = func() time.Time {
2372 return now
2373 }
2374 clientConfig.InsecureSkipVerify = false
2375 clientConfig.ServerName = "example.com"
2376
2377 testResume := func(t *testing.T, sc, cc *Config, expectResume bool) {
2378 t.Helper()
2379 ss, cs, err := testHandshake(t, cc, sc)
2380 if err != nil {
2381 t.Fatalf("handshake: %v", err)
2382 }
2383 if cs.DidResume != expectResume {
2384 t.Fatalf("DidResume = %v; want %v", cs.DidResume, expectResume)
2385 }
2386 if ss.DidResume != expectResume {
2387 t.Fatalf("DidResume = %v; want %v", cs.DidResume, expectResume)
2388 }
2389 }
2390
2391 testResume(t, serverConfig, clientConfig, false)
2392 testResume(t, serverConfig, clientConfig, true)
2393
2394 clientConfig.Certificates[0].Certificate = [][]byte{certB}
2395
2396
2397
2398 switchConfig = true
2399
2400 testResume(t, serverConfig, clientConfig, false)
2401 testResume(t, serverConfig, clientConfig, true)
2402 }
2403
2404 func TestHandshakeChangeRootCAsResumption(t *testing.T) {
2405 t.Run("TLS1.2", func(t *testing.T) {
2406 testHandshakeChangeRootCAsResumption(t, VersionTLS12)
2407 })
2408 t.Run("TLS1.3", func(t *testing.T) {
2409 testHandshakeChangeRootCAsResumption(t, VersionTLS13)
2410 })
2411 }
2412
2413 func testHandshakeChangeRootCAsResumption(t *testing.T, version uint16) {
2414 now := time.Now()
2415 tmpl := &x509.Certificate{
2416 Subject: pkix.Name{CommonName: "root"},
2417 NotBefore: now.Add(-time.Hour * 24),
2418 NotAfter: now.Add(time.Hour * 24),
2419 IsCA: true,
2420 BasicConstraintsValid: true,
2421 }
2422 rootDER, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, &testECDSAP521Key.PublicKey, testECDSAP521Key)
2423 if err != nil {
2424 t.Fatalf("CreateCertificate: %v", err)
2425 }
2426 rootA, err := x509.ParseCertificate(rootDER)
2427 if err != nil {
2428 t.Fatalf("ParseCertificate: %v", err)
2429 }
2430 rootDER, err = x509.CreateCertificate(rand.Reader, tmpl, tmpl, &testRSA2048Key.PublicKey, testRSA2048Key)
2431 if err != nil {
2432 t.Fatalf("CreateCertificate: %v", err)
2433 }
2434 rootB, err := x509.ParseCertificate(rootDER)
2435 if err != nil {
2436 t.Fatalf("ParseCertificate: %v", err)
2437 }
2438
2439 tmpl = &x509.Certificate{
2440 Subject: pkix.Name{},
2441 DNSNames: []string{"example.com"},
2442 NotBefore: now.Add(-time.Hour * 24),
2443 NotAfter: now.Add(time.Hour * 24),
2444 KeyUsage: x509.KeyUsageDigitalSignature,
2445 }
2446 certA, err := x509.CreateCertificate(rand.Reader, tmpl, rootA, &testECDSAP256Key.PublicKey, testECDSAP521Key)
2447 if err != nil {
2448 t.Fatalf("CreateCertificate: %v", err)
2449 }
2450 certB, err := x509.CreateCertificate(rand.Reader, tmpl, rootB, &testECDSAP256Key.PublicKey, testRSA2048Key)
2451 if err != nil {
2452 t.Fatalf("CreateCertificate: %v", err)
2453 }
2454
2455 serverConfig := testConfigServer.Clone()
2456 serverConfig.MaxVersion = version
2457 serverConfig.Certificates = []Certificate{{
2458 Certificate: [][]byte{certA},
2459 PrivateKey: testECDSAP256Key,
2460 }}
2461 serverConfig.Time = func() time.Time {
2462 return now
2463 }
2464 serverConfig.ClientCAs = x509.NewCertPool()
2465 serverConfig.ClientCAs.AddCert(rootA)
2466 serverConfig.ClientAuth = RequireAndVerifyClientCert
2467 serverConfig.InsecureSkipVerify = false
2468 serverConfig.ServerName = "example.com"
2469
2470 clientConfig := testConfigClient.Clone()
2471 clientConfig.MaxVersion = version
2472 clientConfig.Certificates = []Certificate{{
2473 Certificate: [][]byte{certA},
2474 PrivateKey: testECDSAP256Key,
2475 }}
2476 clientConfig.ClientSessionCache = NewLRUClientSessionCache(32)
2477 clientConfig.RootCAs = x509.NewCertPool()
2478 clientConfig.RootCAs.AddCert(rootA)
2479 clientConfig.Time = func() time.Time {
2480 return now
2481 }
2482 clientConfig.InsecureSkipVerify = false
2483 clientConfig.ServerName = "example.com"
2484
2485 testResume := func(t *testing.T, sc, cc *Config, expectResume bool) {
2486 t.Helper()
2487 ss, cs, err := testHandshake(t, cc, sc)
2488 if err != nil {
2489 t.Fatalf("handshake: %v", err)
2490 }
2491 if cs.DidResume != expectResume {
2492 t.Fatalf("DidResume = %v; want %v", cs.DidResume, expectResume)
2493 }
2494 if ss.DidResume != expectResume {
2495 t.Fatalf("DidResume = %v; want %v", cs.DidResume, expectResume)
2496 }
2497 }
2498
2499 testResume(t, serverConfig, clientConfig, false)
2500 testResume(t, serverConfig, clientConfig, true)
2501
2502 clientConfig = clientConfig.Clone()
2503 clientConfig.RootCAs = x509.NewCertPool()
2504 clientConfig.RootCAs.AddCert(rootB)
2505
2506 serverConfig.Certificates[0].Certificate = [][]byte{certB}
2507
2508 testResume(t, serverConfig, clientConfig, false)
2509 testResume(t, serverConfig, clientConfig, true)
2510 }
2511
View as plain text