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