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