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