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