github.com/hlts2/go@v0.0.0-20170904000733-812b34efaed8/src/crypto/tls/handshake_server_test.go (about) 1 // Copyright 2009 The Go Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 package tls 6 7 import ( 8 "bytes" 9 "crypto" 10 "crypto/ecdsa" 11 "crypto/elliptic" 12 "crypto/rsa" 13 "crypto/x509" 14 "encoding/hex" 15 "encoding/pem" 16 "errors" 17 "fmt" 18 "io" 19 "math/big" 20 "net" 21 "os" 22 "os/exec" 23 "path/filepath" 24 "strings" 25 "testing" 26 "time" 27 ) 28 29 // zeroSource is an io.Reader that returns an unlimited number of zero bytes. 30 type zeroSource struct{} 31 32 func (zeroSource) Read(b []byte) (n int, err error) { 33 for i := range b { 34 b[i] = 0 35 } 36 37 return len(b), nil 38 } 39 40 var testConfig *Config 41 42 func allCipherSuites() []uint16 { 43 ids := make([]uint16, len(cipherSuites)) 44 for i, suite := range cipherSuites { 45 ids[i] = suite.id 46 } 47 48 return ids 49 } 50 51 func init() { 52 testConfig = &Config{ 53 Time: func() time.Time { return time.Unix(0, 0) }, 54 Rand: zeroSource{}, 55 Certificates: make([]Certificate, 2), 56 InsecureSkipVerify: true, 57 MinVersion: VersionSSL30, 58 MaxVersion: VersionTLS12, 59 CipherSuites: allCipherSuites(), 60 } 61 testConfig.Certificates[0].Certificate = [][]byte{testRSACertificate} 62 testConfig.Certificates[0].PrivateKey = testRSAPrivateKey 63 testConfig.Certificates[1].Certificate = [][]byte{testSNICertificate} 64 testConfig.Certificates[1].PrivateKey = testRSAPrivateKey 65 testConfig.BuildNameToCertificate() 66 } 67 68 func testClientHello(t *testing.T, serverConfig *Config, m handshakeMessage) { 69 testClientHelloFailure(t, serverConfig, m, "") 70 } 71 72 func testClientHelloFailure(t *testing.T, serverConfig *Config, m handshakeMessage, expectedSubStr string) { 73 // Create in-memory network connection, 74 // send message to server. Should return 75 // expected error. 76 c, s := net.Pipe() 77 go func() { 78 cli := Client(c, testConfig) 79 if ch, ok := m.(*clientHelloMsg); ok { 80 cli.vers = ch.vers 81 } 82 cli.writeRecord(recordTypeHandshake, m.marshal()) 83 c.Close() 84 }() 85 hs := serverHandshakeState{ 86 c: Server(s, serverConfig), 87 } 88 _, err := hs.readClientHello() 89 s.Close() 90 if len(expectedSubStr) == 0 { 91 if err != nil && err != io.EOF { 92 t.Errorf("Got error: %s; expected to succeed", err) 93 } 94 } else if err == nil || !strings.Contains(err.Error(), expectedSubStr) { 95 t.Errorf("Got error: %s; expected to match substring '%s'", err, expectedSubStr) 96 } 97 } 98 99 func TestSimpleError(t *testing.T) { 100 testClientHelloFailure(t, testConfig, &serverHelloDoneMsg{}, "unexpected handshake message") 101 } 102 103 var badProtocolVersions = []uint16{0x0000, 0x0005, 0x0100, 0x0105, 0x0200, 0x0205} 104 105 func TestRejectBadProtocolVersion(t *testing.T) { 106 for _, v := range badProtocolVersions { 107 testClientHelloFailure(t, testConfig, &clientHelloMsg{vers: v}, "unsupported, maximum protocol version") 108 } 109 } 110 111 func TestNoSuiteOverlap(t *testing.T) { 112 clientHello := &clientHelloMsg{ 113 vers: VersionTLS10, 114 cipherSuites: []uint16{0xff00}, 115 compressionMethods: []uint8{compressionNone}, 116 } 117 testClientHelloFailure(t, testConfig, clientHello, "no cipher suite supported by both client and server") 118 } 119 120 func TestNoCompressionOverlap(t *testing.T) { 121 clientHello := &clientHelloMsg{ 122 vers: VersionTLS10, 123 cipherSuites: []uint16{TLS_RSA_WITH_RC4_128_SHA}, 124 compressionMethods: []uint8{0xff}, 125 } 126 testClientHelloFailure(t, testConfig, clientHello, "client does not support uncompressed connections") 127 } 128 129 func TestNoRC4ByDefault(t *testing.T) { 130 clientHello := &clientHelloMsg{ 131 vers: VersionTLS10, 132 cipherSuites: []uint16{TLS_RSA_WITH_RC4_128_SHA}, 133 compressionMethods: []uint8{compressionNone}, 134 } 135 serverConfig := testConfig.Clone() 136 // Reset the enabled cipher suites to nil in order to test the 137 // defaults. 138 serverConfig.CipherSuites = nil 139 testClientHelloFailure(t, serverConfig, clientHello, "no cipher suite supported by both client and server") 140 } 141 142 func TestRejectSNIWithTrailingDot(t *testing.T) { 143 testClientHelloFailure(t, testConfig, &clientHelloMsg{vers: VersionTLS12, serverName: "foo.com."}, "unexpected message") 144 } 145 146 func TestDontSelectECDSAWithRSAKey(t *testing.T) { 147 // Test that, even when both sides support an ECDSA cipher suite, it 148 // won't be selected if the server's private key doesn't support it. 149 clientHello := &clientHelloMsg{ 150 vers: VersionTLS10, 151 cipherSuites: []uint16{TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA}, 152 compressionMethods: []uint8{compressionNone}, 153 supportedCurves: []CurveID{CurveP256}, 154 supportedPoints: []uint8{pointFormatUncompressed}, 155 } 156 serverConfig := testConfig.Clone() 157 serverConfig.CipherSuites = clientHello.cipherSuites 158 serverConfig.Certificates = make([]Certificate, 1) 159 serverConfig.Certificates[0].Certificate = [][]byte{testECDSACertificate} 160 serverConfig.Certificates[0].PrivateKey = testECDSAPrivateKey 161 serverConfig.BuildNameToCertificate() 162 // First test that it *does* work when the server's key is ECDSA. 163 testClientHello(t, serverConfig, clientHello) 164 165 // Now test that switching to an RSA key causes the expected error (and 166 // not an internal error about a signing failure). 167 serverConfig.Certificates = testConfig.Certificates 168 testClientHelloFailure(t, serverConfig, clientHello, "no cipher suite supported by both client and server") 169 } 170 171 func TestDontSelectRSAWithECDSAKey(t *testing.T) { 172 // Test that, even when both sides support an RSA cipher suite, it 173 // won't be selected if the server's private key doesn't support it. 174 clientHello := &clientHelloMsg{ 175 vers: VersionTLS10, 176 cipherSuites: []uint16{TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA}, 177 compressionMethods: []uint8{compressionNone}, 178 supportedCurves: []CurveID{CurveP256}, 179 supportedPoints: []uint8{pointFormatUncompressed}, 180 } 181 serverConfig := testConfig.Clone() 182 serverConfig.CipherSuites = clientHello.cipherSuites 183 // First test that it *does* work when the server's key is RSA. 184 testClientHello(t, serverConfig, clientHello) 185 186 // Now test that switching to an ECDSA key causes the expected error 187 // (and not an internal error about a signing failure). 188 serverConfig.Certificates = make([]Certificate, 1) 189 serverConfig.Certificates[0].Certificate = [][]byte{testECDSACertificate} 190 serverConfig.Certificates[0].PrivateKey = testECDSAPrivateKey 191 serverConfig.BuildNameToCertificate() 192 testClientHelloFailure(t, serverConfig, clientHello, "no cipher suite supported by both client and server") 193 } 194 195 func TestRenegotiationExtension(t *testing.T) { 196 clientHello := &clientHelloMsg{ 197 vers: VersionTLS12, 198 compressionMethods: []uint8{compressionNone}, 199 random: make([]byte, 32), 200 secureRenegotiationSupported: true, 201 cipherSuites: []uint16{TLS_RSA_WITH_RC4_128_SHA}, 202 } 203 204 var buf []byte 205 c, s := net.Pipe() 206 207 go func() { 208 cli := Client(c, testConfig) 209 cli.vers = clientHello.vers 210 cli.writeRecord(recordTypeHandshake, clientHello.marshal()) 211 212 buf = make([]byte, 1024) 213 n, err := c.Read(buf) 214 if err != nil { 215 t.Errorf("Server read returned error: %s", err) 216 return 217 } 218 buf = buf[:n] 219 c.Close() 220 }() 221 222 Server(s, testConfig).Handshake() 223 224 if len(buf) < 5+4 { 225 t.Fatalf("Server returned short message of length %d", len(buf)) 226 } 227 // buf contains a TLS record, with a 5 byte record header and a 4 byte 228 // handshake header. The length of the ServerHello is taken from the 229 // handshake header. 230 serverHelloLen := int(buf[6])<<16 | int(buf[7])<<8 | int(buf[8]) 231 232 var serverHello serverHelloMsg 233 // unmarshal expects to be given the handshake header, but 234 // serverHelloLen doesn't include it. 235 if !serverHello.unmarshal(buf[5 : 9+serverHelloLen]) { 236 t.Fatalf("Failed to parse ServerHello") 237 } 238 239 if !serverHello.secureRenegotiationSupported { 240 t.Errorf("Secure renegotiation extension was not echoed.") 241 } 242 } 243 244 func TestTLS12OnlyCipherSuites(t *testing.T) { 245 // Test that a Server doesn't select a TLS 1.2-only cipher suite when 246 // the client negotiates TLS 1.1. 247 var zeros [32]byte 248 249 clientHello := &clientHelloMsg{ 250 vers: VersionTLS11, 251 random: zeros[:], 252 cipherSuites: []uint16{ 253 // The Server, by default, will use the client's 254 // preference order. So the GCM cipher suite 255 // will be selected unless it's excluded because 256 // of the version in this ClientHello. 257 TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, 258 TLS_RSA_WITH_RC4_128_SHA, 259 }, 260 compressionMethods: []uint8{compressionNone}, 261 supportedCurves: []CurveID{CurveP256, CurveP384, CurveP521}, 262 supportedPoints: []uint8{pointFormatUncompressed}, 263 } 264 265 c, s := net.Pipe() 266 var reply interface{} 267 var clientErr error 268 go func() { 269 cli := Client(c, testConfig) 270 cli.vers = clientHello.vers 271 cli.writeRecord(recordTypeHandshake, clientHello.marshal()) 272 reply, clientErr = cli.readHandshake() 273 c.Close() 274 }() 275 config := testConfig.Clone() 276 config.CipherSuites = clientHello.cipherSuites 277 Server(s, config).Handshake() 278 s.Close() 279 if clientErr != nil { 280 t.Fatal(clientErr) 281 } 282 serverHello, ok := reply.(*serverHelloMsg) 283 if !ok { 284 t.Fatalf("didn't get ServerHello message in reply. Got %v\n", reply) 285 } 286 if s := serverHello.cipherSuite; s != TLS_RSA_WITH_RC4_128_SHA { 287 t.Fatalf("bad cipher suite from server: %x", s) 288 } 289 } 290 291 func TestAlertForwarding(t *testing.T) { 292 c, s := net.Pipe() 293 go func() { 294 Client(c, testConfig).sendAlert(alertUnknownCA) 295 c.Close() 296 }() 297 298 err := Server(s, testConfig).Handshake() 299 s.Close() 300 if e, ok := err.(*net.OpError); !ok || e.Err != error(alertUnknownCA) { 301 t.Errorf("Got error: %s; expected: %s", err, error(alertUnknownCA)) 302 } 303 } 304 305 func TestClose(t *testing.T) { 306 c, s := net.Pipe() 307 go c.Close() 308 309 err := Server(s, testConfig).Handshake() 310 s.Close() 311 if err != io.EOF { 312 t.Errorf("Got error: %s; expected: %s", err, io.EOF) 313 } 314 } 315 316 func testHandshake(clientConfig, serverConfig *Config) (serverState, clientState ConnectionState, err error) { 317 c, s := net.Pipe() 318 done := make(chan bool) 319 go func() { 320 cli := Client(c, clientConfig) 321 cli.Handshake() 322 clientState = cli.ConnectionState() 323 c.Close() 324 done <- true 325 }() 326 server := Server(s, serverConfig) 327 err = server.Handshake() 328 if err == nil { 329 serverState = server.ConnectionState() 330 } 331 s.Close() 332 <-done 333 return 334 } 335 336 func TestVersion(t *testing.T) { 337 serverConfig := &Config{ 338 Certificates: testConfig.Certificates, 339 MaxVersion: VersionTLS11, 340 } 341 clientConfig := &Config{ 342 InsecureSkipVerify: true, 343 } 344 state, _, err := testHandshake(clientConfig, serverConfig) 345 if err != nil { 346 t.Fatalf("handshake failed: %s", err) 347 } 348 if state.Version != VersionTLS11 { 349 t.Fatalf("Incorrect version %x, should be %x", state.Version, VersionTLS11) 350 } 351 } 352 353 func TestCipherSuitePreference(t *testing.T) { 354 serverConfig := &Config{ 355 CipherSuites: []uint16{TLS_RSA_WITH_RC4_128_SHA, TLS_RSA_WITH_AES_128_CBC_SHA, TLS_ECDHE_RSA_WITH_RC4_128_SHA}, 356 Certificates: testConfig.Certificates, 357 MaxVersion: VersionTLS11, 358 } 359 clientConfig := &Config{ 360 CipherSuites: []uint16{TLS_RSA_WITH_AES_128_CBC_SHA, TLS_RSA_WITH_RC4_128_SHA}, 361 InsecureSkipVerify: true, 362 } 363 state, _, err := testHandshake(clientConfig, serverConfig) 364 if err != nil { 365 t.Fatalf("handshake failed: %s", err) 366 } 367 if state.CipherSuite != TLS_RSA_WITH_AES_128_CBC_SHA { 368 // By default the server should use the client's preference. 369 t.Fatalf("Client's preference was not used, got %x", state.CipherSuite) 370 } 371 372 serverConfig.PreferServerCipherSuites = true 373 state, _, err = testHandshake(clientConfig, serverConfig) 374 if err != nil { 375 t.Fatalf("handshake failed: %s", err) 376 } 377 if state.CipherSuite != TLS_RSA_WITH_RC4_128_SHA { 378 t.Fatalf("Server's preference was not used, got %x", state.CipherSuite) 379 } 380 } 381 382 func TestSCTHandshake(t *testing.T) { 383 expected := [][]byte{[]byte("certificate"), []byte("transparency")} 384 serverConfig := &Config{ 385 Certificates: []Certificate{{ 386 Certificate: [][]byte{testRSACertificate}, 387 PrivateKey: testRSAPrivateKey, 388 SignedCertificateTimestamps: expected, 389 }}, 390 } 391 clientConfig := &Config{ 392 InsecureSkipVerify: true, 393 } 394 _, state, err := testHandshake(clientConfig, serverConfig) 395 if err != nil { 396 t.Fatalf("handshake failed: %s", err) 397 } 398 actual := state.SignedCertificateTimestamps 399 if len(actual) != len(expected) { 400 t.Fatalf("got %d scts, want %d", len(actual), len(expected)) 401 } 402 for i, sct := range expected { 403 if !bytes.Equal(sct, actual[i]) { 404 t.Fatalf("SCT #%d was %x, but expected %x", i, actual[i], sct) 405 } 406 } 407 } 408 409 func TestCrossVersionResume(t *testing.T) { 410 serverConfig := &Config{ 411 CipherSuites: []uint16{TLS_RSA_WITH_AES_128_CBC_SHA}, 412 Certificates: testConfig.Certificates, 413 } 414 clientConfig := &Config{ 415 CipherSuites: []uint16{TLS_RSA_WITH_AES_128_CBC_SHA}, 416 InsecureSkipVerify: true, 417 ClientSessionCache: NewLRUClientSessionCache(1), 418 ServerName: "servername", 419 } 420 421 // Establish a session at TLS 1.1. 422 clientConfig.MaxVersion = VersionTLS11 423 _, _, err := testHandshake(clientConfig, serverConfig) 424 if err != nil { 425 t.Fatalf("handshake failed: %s", err) 426 } 427 428 // The client session cache now contains a TLS 1.1 session. 429 state, _, err := testHandshake(clientConfig, serverConfig) 430 if err != nil { 431 t.Fatalf("handshake failed: %s", err) 432 } 433 if !state.DidResume { 434 t.Fatalf("handshake did not resume at the same version") 435 } 436 437 // Test that the server will decline to resume at a lower version. 438 clientConfig.MaxVersion = VersionTLS10 439 state, _, err = testHandshake(clientConfig, serverConfig) 440 if err != nil { 441 t.Fatalf("handshake failed: %s", err) 442 } 443 if state.DidResume { 444 t.Fatalf("handshake resumed at a lower version") 445 } 446 447 // The client session cache now contains a TLS 1.0 session. 448 state, _, err = testHandshake(clientConfig, serverConfig) 449 if err != nil { 450 t.Fatalf("handshake failed: %s", err) 451 } 452 if !state.DidResume { 453 t.Fatalf("handshake did not resume at the same version") 454 } 455 456 // Test that the server will decline to resume at a higher version. 457 clientConfig.MaxVersion = VersionTLS11 458 state, _, err = testHandshake(clientConfig, serverConfig) 459 if err != nil { 460 t.Fatalf("handshake failed: %s", err) 461 } 462 if state.DidResume { 463 t.Fatalf("handshake resumed at a higher version") 464 } 465 } 466 467 // Note: see comment in handshake_test.go for details of how the reference 468 // tests work. 469 470 // serverTest represents a test of the TLS server handshake against a reference 471 // implementation. 472 type serverTest struct { 473 // name is a freeform string identifying the test and the file in which 474 // the expected results will be stored. 475 name string 476 // command, if not empty, contains a series of arguments for the 477 // command to run for the reference server. 478 command []string 479 // expectedPeerCerts contains a list of PEM blocks of expected 480 // certificates from the client. 481 expectedPeerCerts []string 482 // config, if not nil, contains a custom Config to use for this test. 483 config *Config 484 // expectHandshakeErrorIncluding, when not empty, contains a string 485 // that must be a substring of the error resulting from the handshake. 486 expectHandshakeErrorIncluding string 487 // validate, if not nil, is a function that will be called with the 488 // ConnectionState of the resulting connection. It returns false if the 489 // ConnectionState is unacceptable. 490 validate func(ConnectionState) error 491 } 492 493 var defaultClientCommand = []string{"openssl", "s_client", "-no_ticket"} 494 495 // connFromCommand starts opens a listening socket and starts the reference 496 // client to connect to it. It returns a recordingConn that wraps the resulting 497 // connection. 498 func (test *serverTest) connFromCommand() (conn *recordingConn, child *exec.Cmd, err error) { 499 l, err := net.ListenTCP("tcp", &net.TCPAddr{ 500 IP: net.IPv4(127, 0, 0, 1), 501 Port: 0, 502 }) 503 if err != nil { 504 return nil, nil, err 505 } 506 defer l.Close() 507 508 port := l.Addr().(*net.TCPAddr).Port 509 510 var command []string 511 command = append(command, test.command...) 512 if len(command) == 0 { 513 command = defaultClientCommand 514 } 515 command = append(command, "-connect") 516 command = append(command, fmt.Sprintf("127.0.0.1:%d", port)) 517 cmd := exec.Command(command[0], command[1:]...) 518 cmd.Stdin = nil 519 var output bytes.Buffer 520 cmd.Stdout = &output 521 cmd.Stderr = &output 522 if err := cmd.Start(); err != nil { 523 return nil, nil, err 524 } 525 526 connChan := make(chan interface{}) 527 go func() { 528 tcpConn, err := l.Accept() 529 if err != nil { 530 connChan <- err 531 } 532 connChan <- tcpConn 533 }() 534 535 var tcpConn net.Conn 536 select { 537 case connOrError := <-connChan: 538 if err, ok := connOrError.(error); ok { 539 return nil, nil, err 540 } 541 tcpConn = connOrError.(net.Conn) 542 case <-time.After(2 * time.Second): 543 output.WriteTo(os.Stdout) 544 return nil, nil, errors.New("timed out waiting for connection from child process") 545 } 546 547 record := &recordingConn{ 548 Conn: tcpConn, 549 } 550 551 return record, cmd, nil 552 } 553 554 func (test *serverTest) dataPath() string { 555 return filepath.Join("testdata", "Server-"+test.name) 556 } 557 558 func (test *serverTest) loadData() (flows [][]byte, err error) { 559 in, err := os.Open(test.dataPath()) 560 if err != nil { 561 return nil, err 562 } 563 defer in.Close() 564 return parseTestData(in) 565 } 566 567 func (test *serverTest) run(t *testing.T, write bool) { 568 checkOpenSSLVersion(t) 569 570 var clientConn, serverConn net.Conn 571 var recordingConn *recordingConn 572 var childProcess *exec.Cmd 573 574 if write { 575 var err error 576 recordingConn, childProcess, err = test.connFromCommand() 577 if err != nil { 578 t.Fatalf("Failed to start subcommand: %s", err) 579 } 580 serverConn = recordingConn 581 } else { 582 clientConn, serverConn = net.Pipe() 583 } 584 config := test.config 585 if config == nil { 586 config = testConfig 587 } 588 server := Server(serverConn, config) 589 connStateChan := make(chan ConnectionState, 1) 590 go func() { 591 _, err := server.Write([]byte("hello, world\n")) 592 if len(test.expectHandshakeErrorIncluding) > 0 { 593 if err == nil { 594 t.Errorf("Error expected, but no error returned") 595 } else if s := err.Error(); !strings.Contains(s, test.expectHandshakeErrorIncluding) { 596 t.Errorf("Error expected containing '%s' but got '%s'", test.expectHandshakeErrorIncluding, s) 597 } 598 } else { 599 if err != nil { 600 t.Logf("Error from Server.Write: '%s'", err) 601 } 602 } 603 server.Close() 604 serverConn.Close() 605 connStateChan <- server.ConnectionState() 606 }() 607 608 if !write { 609 flows, err := test.loadData() 610 if err != nil { 611 t.Fatalf("%s: failed to load data from %s", test.name, test.dataPath()) 612 } 613 for i, b := range flows { 614 if i%2 == 0 { 615 clientConn.Write(b) 616 continue 617 } 618 bb := make([]byte, len(b)) 619 n, err := io.ReadFull(clientConn, bb) 620 if err != nil { 621 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) 622 } 623 if !bytes.Equal(b, bb) { 624 t.Fatalf("%s #%d: mismatch on read: got:%x want:%x", test.name, i+1, bb, b) 625 } 626 } 627 clientConn.Close() 628 } 629 630 connState := <-connStateChan 631 peerCerts := connState.PeerCertificates 632 if len(peerCerts) == len(test.expectedPeerCerts) { 633 for i, peerCert := range peerCerts { 634 block, _ := pem.Decode([]byte(test.expectedPeerCerts[i])) 635 if !bytes.Equal(block.Bytes, peerCert.Raw) { 636 t.Fatalf("%s: mismatch on peer cert %d", test.name, i+1) 637 } 638 } 639 } else { 640 t.Fatalf("%s: mismatch on peer list length: %d (wanted) != %d (got)", test.name, len(test.expectedPeerCerts), len(peerCerts)) 641 } 642 643 if test.validate != nil { 644 if err := test.validate(connState); err != nil { 645 t.Fatalf("validate callback returned error: %s", err) 646 } 647 } 648 649 if write { 650 path := test.dataPath() 651 out, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644) 652 if err != nil { 653 t.Fatalf("Failed to create output file: %s", err) 654 } 655 defer out.Close() 656 recordingConn.Close() 657 if len(recordingConn.flows) < 3 { 658 childProcess.Stdout.(*bytes.Buffer).WriteTo(os.Stdout) 659 if len(test.expectHandshakeErrorIncluding) == 0 { 660 t.Fatalf("Handshake failed") 661 } 662 } 663 recordingConn.WriteTo(out) 664 fmt.Printf("Wrote %s\n", path) 665 childProcess.Wait() 666 } 667 } 668 669 func runServerTestForVersion(t *testing.T, template *serverTest, prefix, option string) { 670 setParallel(t) 671 test := *template 672 test.name = prefix + test.name 673 if len(test.command) == 0 { 674 test.command = defaultClientCommand 675 } 676 test.command = append([]string(nil), test.command...) 677 test.command = append(test.command, option) 678 test.run(t, *update) 679 } 680 681 func runServerTestSSLv3(t *testing.T, template *serverTest) { 682 runServerTestForVersion(t, template, "SSLv3-", "-ssl3") 683 } 684 685 func runServerTestTLS10(t *testing.T, template *serverTest) { 686 runServerTestForVersion(t, template, "TLSv10-", "-tls1") 687 } 688 689 func runServerTestTLS11(t *testing.T, template *serverTest) { 690 runServerTestForVersion(t, template, "TLSv11-", "-tls1_1") 691 } 692 693 func runServerTestTLS12(t *testing.T, template *serverTest) { 694 runServerTestForVersion(t, template, "TLSv12-", "-tls1_2") 695 } 696 697 func TestHandshakeServerRSARC4(t *testing.T) { 698 test := &serverTest{ 699 name: "RSA-RC4", 700 command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "RC4-SHA"}, 701 } 702 runServerTestSSLv3(t, test) 703 runServerTestTLS10(t, test) 704 runServerTestTLS11(t, test) 705 runServerTestTLS12(t, test) 706 } 707 708 func TestHandshakeServerRSA3DES(t *testing.T) { 709 test := &serverTest{ 710 name: "RSA-3DES", 711 command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "DES-CBC3-SHA"}, 712 } 713 runServerTestSSLv3(t, test) 714 runServerTestTLS10(t, test) 715 runServerTestTLS12(t, test) 716 } 717 718 func TestHandshakeServerRSAAES(t *testing.T) { 719 test := &serverTest{ 720 name: "RSA-AES", 721 command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "AES128-SHA"}, 722 } 723 runServerTestSSLv3(t, test) 724 runServerTestTLS10(t, test) 725 runServerTestTLS12(t, test) 726 } 727 728 func TestHandshakeServerAESGCM(t *testing.T) { 729 test := &serverTest{ 730 name: "RSA-AES-GCM", 731 command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "ECDHE-RSA-AES128-GCM-SHA256"}, 732 } 733 runServerTestTLS12(t, test) 734 } 735 736 func TestHandshakeServerAES256GCMSHA384(t *testing.T) { 737 test := &serverTest{ 738 name: "RSA-AES256-GCM-SHA384", 739 command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "ECDHE-RSA-AES256-GCM-SHA384"}, 740 } 741 runServerTestTLS12(t, test) 742 } 743 744 func TestHandshakeServerECDHEECDSAAES(t *testing.T) { 745 config := testConfig.Clone() 746 config.Certificates = make([]Certificate, 1) 747 config.Certificates[0].Certificate = [][]byte{testECDSACertificate} 748 config.Certificates[0].PrivateKey = testECDSAPrivateKey 749 config.BuildNameToCertificate() 750 751 test := &serverTest{ 752 name: "ECDHE-ECDSA-AES", 753 command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "ECDHE-ECDSA-AES256-SHA"}, 754 config: config, 755 } 756 runServerTestTLS10(t, test) 757 runServerTestTLS12(t, test) 758 } 759 760 func TestHandshakeServerX25519(t *testing.T) { 761 config := testConfig.Clone() 762 config.CurvePreferences = []CurveID{X25519} 763 764 test := &serverTest{ 765 name: "X25519-ECDHE-RSA-AES-GCM", 766 command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "ECDHE-RSA-AES128-GCM-SHA256"}, 767 config: config, 768 } 769 runServerTestTLS12(t, test) 770 } 771 772 func TestHandshakeServerALPN(t *testing.T) { 773 config := testConfig.Clone() 774 config.NextProtos = []string{"proto1", "proto2"} 775 776 test := &serverTest{ 777 name: "ALPN", 778 // Note that this needs OpenSSL 1.0.2 because that is the first 779 // version that supports the -alpn flag. 780 command: []string{"openssl", "s_client", "-alpn", "proto2,proto1"}, 781 config: config, 782 validate: func(state ConnectionState) error { 783 // The server's preferences should override the client. 784 if state.NegotiatedProtocol != "proto1" { 785 return fmt.Errorf("Got protocol %q, wanted proto1", state.NegotiatedProtocol) 786 } 787 return nil 788 }, 789 } 790 runServerTestTLS12(t, test) 791 } 792 793 func TestHandshakeServerALPNNoMatch(t *testing.T) { 794 config := testConfig.Clone() 795 config.NextProtos = []string{"proto3"} 796 797 test := &serverTest{ 798 name: "ALPN-NoMatch", 799 // Note that this needs OpenSSL 1.0.2 because that is the first 800 // version that supports the -alpn flag. 801 command: []string{"openssl", "s_client", "-alpn", "proto2,proto1"}, 802 config: config, 803 validate: func(state ConnectionState) error { 804 // Rather than reject the connection, Go doesn't select 805 // a protocol when there is no overlap. 806 if state.NegotiatedProtocol != "" { 807 return fmt.Errorf("Got protocol %q, wanted ''", state.NegotiatedProtocol) 808 } 809 return nil 810 }, 811 } 812 runServerTestTLS12(t, test) 813 } 814 815 // TestHandshakeServerSNI involves a client sending an SNI extension of 816 // "snitest.com", which happens to match the CN of testSNICertificate. The test 817 // verifies that the server correctly selects that certificate. 818 func TestHandshakeServerSNI(t *testing.T) { 819 test := &serverTest{ 820 name: "SNI", 821 command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "AES128-SHA", "-servername", "snitest.com"}, 822 } 823 runServerTestTLS12(t, test) 824 } 825 826 // TestHandshakeServerSNICertForName is similar to TestHandshakeServerSNI, but 827 // tests the dynamic GetCertificate method 828 func TestHandshakeServerSNIGetCertificate(t *testing.T) { 829 config := testConfig.Clone() 830 831 // Replace the NameToCertificate map with a GetCertificate function 832 nameToCert := config.NameToCertificate 833 config.NameToCertificate = nil 834 config.GetCertificate = func(clientHello *ClientHelloInfo) (*Certificate, error) { 835 cert, _ := nameToCert[clientHello.ServerName] 836 return cert, nil 837 } 838 test := &serverTest{ 839 name: "SNI-GetCertificate", 840 command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "AES128-SHA", "-servername", "snitest.com"}, 841 config: config, 842 } 843 runServerTestTLS12(t, test) 844 } 845 846 // TestHandshakeServerSNICertForNameNotFound is similar to 847 // TestHandshakeServerSNICertForName, but tests to make sure that when the 848 // GetCertificate method doesn't return a cert, we fall back to what's in 849 // the NameToCertificate map. 850 func TestHandshakeServerSNIGetCertificateNotFound(t *testing.T) { 851 config := testConfig.Clone() 852 853 config.GetCertificate = func(clientHello *ClientHelloInfo) (*Certificate, error) { 854 return nil, nil 855 } 856 test := &serverTest{ 857 name: "SNI-GetCertificateNotFound", 858 command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "AES128-SHA", "-servername", "snitest.com"}, 859 config: config, 860 } 861 runServerTestTLS12(t, test) 862 } 863 864 // TestHandshakeServerSNICertForNameError tests to make sure that errors in 865 // GetCertificate result in a tls alert. 866 func TestHandshakeServerSNIGetCertificateError(t *testing.T) { 867 const errMsg = "TestHandshakeServerSNIGetCertificateError error" 868 869 serverConfig := testConfig.Clone() 870 serverConfig.GetCertificate = func(clientHello *ClientHelloInfo) (*Certificate, error) { 871 return nil, errors.New(errMsg) 872 } 873 874 clientHello := &clientHelloMsg{ 875 vers: VersionTLS10, 876 cipherSuites: []uint16{TLS_RSA_WITH_RC4_128_SHA}, 877 compressionMethods: []uint8{compressionNone}, 878 serverName: "test", 879 } 880 testClientHelloFailure(t, serverConfig, clientHello, errMsg) 881 } 882 883 // TestHandshakeServerEmptyCertificates tests that GetCertificates is called in 884 // the case that Certificates is empty, even without SNI. 885 func TestHandshakeServerEmptyCertificates(t *testing.T) { 886 const errMsg = "TestHandshakeServerEmptyCertificates error" 887 888 serverConfig := testConfig.Clone() 889 serverConfig.GetCertificate = func(clientHello *ClientHelloInfo) (*Certificate, error) { 890 return nil, errors.New(errMsg) 891 } 892 serverConfig.Certificates = nil 893 894 clientHello := &clientHelloMsg{ 895 vers: VersionTLS10, 896 cipherSuites: []uint16{TLS_RSA_WITH_RC4_128_SHA}, 897 compressionMethods: []uint8{compressionNone}, 898 } 899 testClientHelloFailure(t, serverConfig, clientHello, errMsg) 900 901 // With an empty Certificates and a nil GetCertificate, the server 902 // should always return a “no certificates” error. 903 serverConfig.GetCertificate = nil 904 905 clientHello = &clientHelloMsg{ 906 vers: VersionTLS10, 907 cipherSuites: []uint16{TLS_RSA_WITH_RC4_128_SHA}, 908 compressionMethods: []uint8{compressionNone}, 909 } 910 testClientHelloFailure(t, serverConfig, clientHello, "no certificates") 911 } 912 913 // TestCipherSuiteCertPreferance ensures that we select an RSA ciphersuite with 914 // an RSA certificate and an ECDSA ciphersuite with an ECDSA certificate. 915 func TestCipherSuiteCertPreferenceECDSA(t *testing.T) { 916 config := testConfig.Clone() 917 config.CipherSuites = []uint16{TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA} 918 config.PreferServerCipherSuites = true 919 920 test := &serverTest{ 921 name: "CipherSuiteCertPreferenceRSA", 922 config: config, 923 } 924 runServerTestTLS12(t, test) 925 926 config = testConfig.Clone() 927 config.CipherSuites = []uint16{TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA, TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA} 928 config.Certificates = []Certificate{ 929 { 930 Certificate: [][]byte{testECDSACertificate}, 931 PrivateKey: testECDSAPrivateKey, 932 }, 933 } 934 config.BuildNameToCertificate() 935 config.PreferServerCipherSuites = true 936 937 test = &serverTest{ 938 name: "CipherSuiteCertPreferenceECDSA", 939 config: config, 940 } 941 runServerTestTLS12(t, test) 942 } 943 944 func TestResumption(t *testing.T) { 945 sessionFilePath := tempFile("") 946 defer os.Remove(sessionFilePath) 947 948 test := &serverTest{ 949 name: "IssueTicket", 950 command: []string{"openssl", "s_client", "-cipher", "AES128-SHA", "-sess_out", sessionFilePath}, 951 } 952 runServerTestTLS12(t, test) 953 954 test = &serverTest{ 955 name: "Resume", 956 command: []string{"openssl", "s_client", "-cipher", "AES128-SHA", "-sess_in", sessionFilePath}, 957 } 958 runServerTestTLS12(t, test) 959 } 960 961 func TestResumptionDisabled(t *testing.T) { 962 sessionFilePath := tempFile("") 963 defer os.Remove(sessionFilePath) 964 965 config := testConfig.Clone() 966 967 test := &serverTest{ 968 name: "IssueTicketPreDisable", 969 command: []string{"openssl", "s_client", "-cipher", "AES128-SHA", "-sess_out", sessionFilePath}, 970 config: config, 971 } 972 runServerTestTLS12(t, test) 973 974 config.SessionTicketsDisabled = true 975 976 test = &serverTest{ 977 name: "ResumeDisabled", 978 command: []string{"openssl", "s_client", "-cipher", "AES128-SHA", "-sess_in", sessionFilePath}, 979 config: config, 980 } 981 runServerTestTLS12(t, test) 982 983 // One needs to manually confirm that the handshake in the golden data 984 // file for ResumeDisabled does not include a resumption handshake. 985 } 986 987 func TestFallbackSCSV(t *testing.T) { 988 serverConfig := Config{ 989 Certificates: testConfig.Certificates, 990 } 991 test := &serverTest{ 992 name: "FallbackSCSV", 993 config: &serverConfig, 994 // OpenSSL 1.0.1j is needed for the -fallback_scsv option. 995 command: []string{"openssl", "s_client", "-fallback_scsv"}, 996 expectHandshakeErrorIncluding: "inappropriate protocol fallback", 997 } 998 runServerTestTLS11(t, test) 999 } 1000 1001 func benchmarkHandshakeServer(b *testing.B, cipherSuite uint16, curve CurveID, cert []byte, key crypto.PrivateKey) { 1002 config := testConfig.Clone() 1003 config.CipherSuites = []uint16{cipherSuite} 1004 config.CurvePreferences = []CurveID{curve} 1005 config.Certificates = make([]Certificate, 1) 1006 config.Certificates[0].Certificate = [][]byte{cert} 1007 config.Certificates[0].PrivateKey = key 1008 config.BuildNameToCertificate() 1009 1010 clientConn, serverConn := net.Pipe() 1011 serverConn = &recordingConn{Conn: serverConn} 1012 go func() { 1013 client := Client(clientConn, testConfig) 1014 client.Handshake() 1015 }() 1016 server := Server(serverConn, config) 1017 if err := server.Handshake(); err != nil { 1018 b.Fatalf("handshake failed: %v", err) 1019 } 1020 serverConn.Close() 1021 flows := serverConn.(*recordingConn).flows 1022 1023 feeder := make(chan struct{}) 1024 clientConn, serverConn = net.Pipe() 1025 1026 go func() { 1027 for range feeder { 1028 for i, f := range flows { 1029 if i%2 == 0 { 1030 clientConn.Write(f) 1031 continue 1032 } 1033 ff := make([]byte, len(f)) 1034 n, err := io.ReadFull(clientConn, ff) 1035 if err != nil { 1036 b.Fatalf("#%d: %s\nRead %d, wanted %d, got %x, wanted %x\n", i+1, err, n, len(ff), ff[:n], f) 1037 } 1038 if !bytes.Equal(f, ff) { 1039 b.Fatalf("#%d: mismatch on read: got:%x want:%x", i+1, ff, f) 1040 } 1041 } 1042 } 1043 }() 1044 1045 b.ResetTimer() 1046 for i := 0; i < b.N; i++ { 1047 feeder <- struct{}{} 1048 server := Server(serverConn, config) 1049 if err := server.Handshake(); err != nil { 1050 b.Fatalf("handshake failed: %v", err) 1051 } 1052 } 1053 close(feeder) 1054 } 1055 1056 func BenchmarkHandshakeServer(b *testing.B) { 1057 b.Run("RSA", func(b *testing.B) { 1058 benchmarkHandshakeServer(b, TLS_RSA_WITH_AES_128_GCM_SHA256, 1059 0, testRSACertificate, testRSAPrivateKey) 1060 }) 1061 b.Run("ECDHE-P256-RSA", func(b *testing.B) { 1062 benchmarkHandshakeServer(b, TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305, 1063 CurveP256, testRSACertificate, testRSAPrivateKey) 1064 }) 1065 b.Run("ECDHE-P256-ECDSA-P256", func(b *testing.B) { 1066 benchmarkHandshakeServer(b, TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305, 1067 CurveP256, testP256Certificate, testP256PrivateKey) 1068 }) 1069 b.Run("ECDHE-X25519-ECDSA-P256", func(b *testing.B) { 1070 benchmarkHandshakeServer(b, TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305, 1071 X25519, testP256Certificate, testP256PrivateKey) 1072 }) 1073 b.Run("ECDHE-P521-ECDSA-P521", func(b *testing.B) { 1074 if testECDSAPrivateKey.PublicKey.Curve != elliptic.P521() { 1075 b.Fatal("test ECDSA key doesn't use curve P-521") 1076 } 1077 benchmarkHandshakeServer(b, TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305, 1078 CurveP521, testECDSACertificate, testECDSAPrivateKey) 1079 }) 1080 } 1081 1082 // clientCertificatePEM and clientKeyPEM were generated with generate_cert.go 1083 // Thus, they have no ExtKeyUsage fields and trigger an error when verification 1084 // is turned on. 1085 1086 const clientCertificatePEM = ` 1087 -----BEGIN CERTIFICATE----- 1088 MIIB7zCCAVigAwIBAgIQXBnBiWWDVW/cC8m5k5/pvDANBgkqhkiG9w0BAQsFADAS 1089 MRAwDgYDVQQKEwdBY21lIENvMB4XDTE2MDgxNzIxNTIzMVoXDTE3MDgxNzIxNTIz 1090 MVowEjEQMA4GA1UEChMHQWNtZSBDbzCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkC 1091 gYEAum+qhr3Pv5/y71yUYHhv6BPy0ZZvzdkybiI3zkH5yl0prOEn2mGi7oHLEMff 1092 NFiVhuk9GeZcJ3NgyI14AvQdpJgJoxlwaTwlYmYqqyIjxXuFOE8uCXMyp70+m63K 1093 hAfmDzr/d8WdQYUAirab7rCkPy1MTOZCPrtRyN1IVPQMjkcCAwEAAaNGMEQwDgYD 1094 VR0PAQH/BAQDAgWgMBMGA1UdJQQMMAoGCCsGAQUFBwMBMAwGA1UdEwEB/wQCMAAw 1095 DwYDVR0RBAgwBocEfwAAATANBgkqhkiG9w0BAQsFAAOBgQBGq0Si+yhU+Fpn+GKU 1096 8ZqyGJ7ysd4dfm92lam6512oFmyc9wnTN+RLKzZ8Aa1B0jLYw9KT+RBrjpW5LBeK 1097 o0RIvFkTgxYEiKSBXCUNmAysEbEoVr4dzWFihAm/1oDGRY2CLLTYg5vbySK3KhIR 1098 e/oCO8HJ/+rJnahJ05XX1Q7lNQ== 1099 -----END CERTIFICATE-----` 1100 1101 const clientKeyPEM = ` 1102 -----BEGIN RSA PRIVATE KEY----- 1103 MIICXQIBAAKBgQC6b6qGvc+/n/LvXJRgeG/oE/LRlm/N2TJuIjfOQfnKXSms4Sfa 1104 YaLugcsQx980WJWG6T0Z5lwnc2DIjXgC9B2kmAmjGXBpPCViZiqrIiPFe4U4Ty4J 1105 czKnvT6brcqEB+YPOv93xZ1BhQCKtpvusKQ/LUxM5kI+u1HI3UhU9AyORwIDAQAB 1106 AoGAEJZ03q4uuMb7b26WSQsOMeDsftdatT747LGgs3pNRkMJvTb/O7/qJjxoG+Mc 1107 qeSj0TAZXp+PXXc3ikCECAc+R8rVMfWdmp903XgO/qYtmZGCorxAHEmR80SrfMXv 1108 PJnznLQWc8U9nphQErR+tTESg7xWEzmFcPKwnZd1xg8ERYkCQQDTGtrFczlB2b/Z 1109 9TjNMqUlMnTLIk/a/rPE2fLLmAYhK5sHnJdvDURaH2mF4nso0EGtENnTsh6LATnY 1110 dkrxXGm9AkEA4hXHG2q3MnhgK1Z5hjv+Fnqd+8bcbII9WW4flFs15EKoMgS1w/PJ 1111 zbsySaSy5IVS8XeShmT9+3lrleed4sy+UwJBAJOOAbxhfXP5r4+5R6ql66jES75w 1112 jUCVJzJA5ORJrn8g64u2eGK28z/LFQbv9wXgCwfc72R468BdawFSLa/m2EECQGbZ 1113 rWiFla26IVXV0xcD98VWJsTBZMlgPnSOqoMdM1kSEd4fUmlAYI/dFzV1XYSkOmVr 1114 FhdZnklmpVDeu27P4c0CQQCuCOup0FlJSBpWY1TTfun/KMBkBatMz0VMA3d7FKIU 1115 csPezl677Yjo8u1r/KzeI6zLg87Z8E6r6ZWNc9wBSZK6 1116 -----END RSA PRIVATE KEY-----` 1117 1118 const clientECDSACertificatePEM = ` 1119 -----BEGIN CERTIFICATE----- 1120 MIIB/DCCAV4CCQCaMIRsJjXZFzAJBgcqhkjOPQQBMEUxCzAJBgNVBAYTAkFVMRMw 1121 EQYDVQQIEwpTb21lLVN0YXRlMSEwHwYDVQQKExhJbnRlcm5ldCBXaWRnaXRzIFB0 1122 eSBMdGQwHhcNMTIxMTE0MTMyNTUzWhcNMjIxMTEyMTMyNTUzWjBBMQswCQYDVQQG 1123 EwJBVTEMMAoGA1UECBMDTlNXMRAwDgYDVQQHEwdQeXJtb250MRIwEAYDVQQDEwlK 1124 b2VsIFNpbmcwgZswEAYHKoZIzj0CAQYFK4EEACMDgYYABACVjJF1FMBexFe01MNv 1125 ja5oHt1vzobhfm6ySD6B5U7ixohLZNz1MLvT/2XMW/TdtWo+PtAd3kfDdq0Z9kUs 1126 jLzYHQFMH3CQRnZIi4+DzEpcj0B22uCJ7B0rxE4wdihBsmKo+1vx+U56jb0JuK7q 1127 ixgnTy5w/hOWusPTQBbNZU6sER7m8TAJBgcqhkjOPQQBA4GMADCBiAJCAOAUxGBg 1128 C3JosDJdYUoCdFzCgbkWqD8pyDbHgf9stlvZcPE4O1BIKJTLCRpS8V3ujfK58PDa 1129 2RU6+b0DeoeiIzXsAkIBo9SKeDUcSpoj0gq+KxAxnZxfvuiRs9oa9V2jI/Umi0Vw 1130 jWVim34BmT0Y9hCaOGGbLlfk+syxis7iI6CH8OFnUes= 1131 -----END CERTIFICATE-----` 1132 1133 const clientECDSAKeyPEM = ` 1134 -----BEGIN EC PARAMETERS----- 1135 BgUrgQQAIw== 1136 -----END EC PARAMETERS----- 1137 -----BEGIN EC PRIVATE KEY----- 1138 MIHcAgEBBEIBkJN9X4IqZIguiEVKMqeBUP5xtRsEv4HJEtOpOGLELwO53SD78Ew8 1139 k+wLWoqizS3NpQyMtrU8JFdWfj+C57UNkOugBwYFK4EEACOhgYkDgYYABACVjJF1 1140 FMBexFe01MNvja5oHt1vzobhfm6ySD6B5U7ixohLZNz1MLvT/2XMW/TdtWo+PtAd 1141 3kfDdq0Z9kUsjLzYHQFMH3CQRnZIi4+DzEpcj0B22uCJ7B0rxE4wdihBsmKo+1vx 1142 +U56jb0JuK7qixgnTy5w/hOWusPTQBbNZU6sER7m8Q== 1143 -----END EC PRIVATE KEY-----` 1144 1145 func TestClientAuth(t *testing.T) { 1146 setParallel(t) 1147 var certPath, keyPath, ecdsaCertPath, ecdsaKeyPath string 1148 1149 if *update { 1150 certPath = tempFile(clientCertificatePEM) 1151 defer os.Remove(certPath) 1152 keyPath = tempFile(clientKeyPEM) 1153 defer os.Remove(keyPath) 1154 ecdsaCertPath = tempFile(clientECDSACertificatePEM) 1155 defer os.Remove(ecdsaCertPath) 1156 ecdsaKeyPath = tempFile(clientECDSAKeyPEM) 1157 defer os.Remove(ecdsaKeyPath) 1158 } 1159 1160 config := testConfig.Clone() 1161 config.ClientAuth = RequestClientCert 1162 1163 test := &serverTest{ 1164 name: "ClientAuthRequestedNotGiven", 1165 command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "AES128-SHA"}, 1166 config: config, 1167 } 1168 runServerTestTLS12(t, test) 1169 1170 test = &serverTest{ 1171 name: "ClientAuthRequestedAndGiven", 1172 command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "AES128-SHA", "-cert", certPath, "-key", keyPath}, 1173 config: config, 1174 expectedPeerCerts: []string{clientCertificatePEM}, 1175 } 1176 runServerTestTLS12(t, test) 1177 1178 test = &serverTest{ 1179 name: "ClientAuthRequestedAndECDSAGiven", 1180 command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "AES128-SHA", "-cert", ecdsaCertPath, "-key", ecdsaKeyPath}, 1181 config: config, 1182 expectedPeerCerts: []string{clientECDSACertificatePEM}, 1183 } 1184 runServerTestTLS12(t, test) 1185 } 1186 1187 func TestSNIGivenOnFailure(t *testing.T) { 1188 const expectedServerName = "test.testing" 1189 1190 clientHello := &clientHelloMsg{ 1191 vers: VersionTLS10, 1192 cipherSuites: []uint16{TLS_RSA_WITH_RC4_128_SHA}, 1193 compressionMethods: []uint8{compressionNone}, 1194 serverName: expectedServerName, 1195 } 1196 1197 serverConfig := testConfig.Clone() 1198 // Erase the server's cipher suites to ensure the handshake fails. 1199 serverConfig.CipherSuites = nil 1200 1201 c, s := net.Pipe() 1202 go func() { 1203 cli := Client(c, testConfig) 1204 cli.vers = clientHello.vers 1205 cli.writeRecord(recordTypeHandshake, clientHello.marshal()) 1206 c.Close() 1207 }() 1208 hs := serverHandshakeState{ 1209 c: Server(s, serverConfig), 1210 } 1211 _, err := hs.readClientHello() 1212 defer s.Close() 1213 1214 if err == nil { 1215 t.Error("No error reported from server") 1216 } 1217 1218 cs := hs.c.ConnectionState() 1219 if cs.HandshakeComplete { 1220 t.Error("Handshake registered as complete") 1221 } 1222 1223 if cs.ServerName != expectedServerName { 1224 t.Errorf("Expected ServerName of %q, but got %q", expectedServerName, cs.ServerName) 1225 } 1226 } 1227 1228 var getConfigForClientTests = []struct { 1229 setup func(config *Config) 1230 callback func(clientHello *ClientHelloInfo) (*Config, error) 1231 errorSubstring string 1232 verify func(config *Config) error 1233 }{ 1234 { 1235 nil, 1236 func(clientHello *ClientHelloInfo) (*Config, error) { 1237 return nil, nil 1238 }, 1239 "", 1240 nil, 1241 }, 1242 { 1243 nil, 1244 func(clientHello *ClientHelloInfo) (*Config, error) { 1245 return nil, errors.New("should bubble up") 1246 }, 1247 "should bubble up", 1248 nil, 1249 }, 1250 { 1251 nil, 1252 func(clientHello *ClientHelloInfo) (*Config, error) { 1253 config := testConfig.Clone() 1254 // Setting a maximum version of TLS 1.1 should cause 1255 // the handshake to fail. 1256 config.MaxVersion = VersionTLS11 1257 return config, nil 1258 }, 1259 "version 301 when expecting version 302", 1260 nil, 1261 }, 1262 { 1263 func(config *Config) { 1264 for i := range config.SessionTicketKey { 1265 config.SessionTicketKey[i] = byte(i) 1266 } 1267 config.sessionTicketKeys = nil 1268 }, 1269 func(clientHello *ClientHelloInfo) (*Config, error) { 1270 config := testConfig.Clone() 1271 for i := range config.SessionTicketKey { 1272 config.SessionTicketKey[i] = 0 1273 } 1274 config.sessionTicketKeys = nil 1275 return config, nil 1276 }, 1277 "", 1278 func(config *Config) error { 1279 // The value of SessionTicketKey should have been 1280 // duplicated into the per-connection Config. 1281 for i := range config.SessionTicketKey { 1282 if b := config.SessionTicketKey[i]; b != byte(i) { 1283 return fmt.Errorf("SessionTicketKey was not duplicated from original Config: byte %d has value %d", i, b) 1284 } 1285 } 1286 return nil 1287 }, 1288 }, 1289 { 1290 func(config *Config) { 1291 var dummyKey [32]byte 1292 for i := range dummyKey { 1293 dummyKey[i] = byte(i) 1294 } 1295 1296 config.SetSessionTicketKeys([][32]byte{dummyKey}) 1297 }, 1298 func(clientHello *ClientHelloInfo) (*Config, error) { 1299 config := testConfig.Clone() 1300 config.sessionTicketKeys = nil 1301 return config, nil 1302 }, 1303 "", 1304 func(config *Config) error { 1305 // The session ticket keys should have been duplicated 1306 // into the per-connection Config. 1307 if l := len(config.sessionTicketKeys); l != 1 { 1308 return fmt.Errorf("got len(sessionTicketKeys) == %d, wanted 1", l) 1309 } 1310 return nil 1311 }, 1312 }, 1313 } 1314 1315 func TestGetConfigForClient(t *testing.T) { 1316 serverConfig := testConfig.Clone() 1317 clientConfig := testConfig.Clone() 1318 clientConfig.MinVersion = VersionTLS12 1319 1320 for i, test := range getConfigForClientTests { 1321 if test.setup != nil { 1322 test.setup(serverConfig) 1323 } 1324 1325 var configReturned *Config 1326 serverConfig.GetConfigForClient = func(clientHello *ClientHelloInfo) (*Config, error) { 1327 config, err := test.callback(clientHello) 1328 configReturned = config 1329 return config, err 1330 } 1331 c, s := net.Pipe() 1332 done := make(chan error) 1333 1334 go func() { 1335 defer s.Close() 1336 done <- Server(s, serverConfig).Handshake() 1337 }() 1338 1339 clientErr := Client(c, clientConfig).Handshake() 1340 c.Close() 1341 1342 serverErr := <-done 1343 1344 if len(test.errorSubstring) == 0 { 1345 if serverErr != nil || clientErr != nil { 1346 t.Errorf("test[%d]: expected no error but got serverErr: %q, clientErr: %q", i, serverErr, clientErr) 1347 } 1348 if test.verify != nil { 1349 if err := test.verify(configReturned); err != nil { 1350 t.Errorf("test[%d]: verify returned error: %v", i, err) 1351 } 1352 } 1353 } else { 1354 if serverErr == nil { 1355 t.Errorf("test[%d]: expected error containing %q but got no error", i, test.errorSubstring) 1356 } else if !strings.Contains(serverErr.Error(), test.errorSubstring) { 1357 t.Errorf("test[%d]: expected error to contain %q but it was %q", i, test.errorSubstring, serverErr) 1358 } 1359 } 1360 } 1361 } 1362 1363 func bigFromString(s string) *big.Int { 1364 ret := new(big.Int) 1365 ret.SetString(s, 10) 1366 return ret 1367 } 1368 1369 func fromHex(s string) []byte { 1370 b, _ := hex.DecodeString(s) 1371 return b 1372 } 1373 1374 var testRSACertificate = fromHex("3082024b308201b4a003020102020900e8f09d3fe25beaa6300d06092a864886f70d01010b0500301f310b3009060355040a1302476f3110300e06035504031307476f20526f6f74301e170d3136303130313030303030305a170d3235303130313030303030305a301a310b3009060355040a1302476f310b300906035504031302476f30819f300d06092a864886f70d010101050003818d0030818902818100db467d932e12270648bc062821ab7ec4b6a25dfe1e5245887a3647a5080d92425bc281c0be97799840fb4f6d14fd2b138bc2a52e67d8d4099ed62238b74a0b74732bc234f1d193e596d9747bf3589f6c613cc0b041d4d92b2b2423775b1c3bbd755dce2054cfa163871d1e24c4f31d1a508baab61443ed97a77562f414c852d70203010001a38193308190300e0603551d0f0101ff0404030205a0301d0603551d250416301406082b0601050507030106082b06010505070302300c0603551d130101ff0402300030190603551d0e041204109f91161f43433e49a6de6db680d79f60301b0603551d230414301280104813494d137e1631bba301d5acab6e7b30190603551d1104123010820e6578616d706c652e676f6c616e67300d06092a864886f70d01010b0500038181009d30cc402b5b50a061cbbae55358e1ed8328a9581aa938a495a1ac315a1a84663d43d32dd90bf297dfd320643892243a00bccf9c7db74020015faad3166109a276fd13c3cce10c5ceeb18782f16c04ed73bbb343778d0c1cf10fa1d8408361c94c722b9daedb4606064df4c1b33ec0d1bd42d4dbfe3d1360845c21d33be9fae7") 1375 1376 var testRSACertificateIssuer = fromHex("3082021930820182a003020102020900ca5e4e811a965964300d06092a864886f70d01010b0500301f310b3009060355040a1302476f3110300e06035504031307476f20526f6f74301e170d3136303130313030303030305a170d3235303130313030303030305a301f310b3009060355040a1302476f3110300e06035504031307476f20526f6f7430819f300d06092a864886f70d010101050003818d0030818902818100d667b378bb22f34143b6cd2008236abefaf2852adf3ab05e01329e2c14834f5105df3f3073f99dab5442d45ee5f8f57b0111c8cb682fbb719a86944eebfffef3406206d898b8c1b1887797c9c5006547bb8f00e694b7a063f10839f269f2c34fff7a1f4b21fbcd6bfdfb13ac792d1d11f277b5c5b48600992203059f2a8f8cc50203010001a35d305b300e0603551d0f0101ff040403020204301d0603551d250416301406082b0601050507030106082b06010505070302300f0603551d130101ff040530030101ff30190603551d0e041204104813494d137e1631bba301d5acab6e7b300d06092a864886f70d01010b050003818100c1154b4bab5266221f293766ae4138899bd4c5e36b13cee670ceeaa4cbdf4f6679017e2fe649765af545749fe4249418a56bd38a04b81e261f5ce86b8d5c65413156a50d12449554748c59a30c515bc36a59d38bddf51173e899820b282e40aa78c806526fd184fb6b4cf186ec728edffa585440d2b3225325f7ab580e87dd76") 1377 1378 var testECDSACertificate = fromHex("3082020030820162020900b8bf2d47a0d2ebf4300906072a8648ce3d04013045310b3009060355040613024155311330110603550408130a536f6d652d53746174653121301f060355040a1318496e7465726e6574205769646769747320507479204c7464301e170d3132313132323135303633325a170d3232313132303135303633325a3045310b3009060355040613024155311330110603550408130a536f6d652d53746174653121301f060355040a1318496e7465726e6574205769646769747320507479204c746430819b301006072a8648ce3d020106052b81040023038186000400c4a1edbe98f90b4873367ec316561122f23d53c33b4d213dcd6b75e6f6b0dc9adf26c1bcb287f072327cb3642f1c90bcea6823107efee325c0483a69e0286dd33700ef0462dd0da09c706283d881d36431aa9e9731bd96b068c09b23de76643f1a5c7fe9120e5858b65f70dd9bd8ead5d7f5d5ccb9b69f30665b669a20e227e5bffe3b300906072a8648ce3d040103818c0030818802420188a24febe245c5487d1bacf5ed989dae4770c05e1bb62fbdf1b64db76140d311a2ceee0b7e927eff769dc33b7ea53fcefa10e259ec472d7cacda4e970e15a06fd00242014dfcbe67139c2d050ebd3fa38c25c13313830d9406bbd4377af6ec7ac9862eddd711697f857c56defb31782be4c7780daecbbe9e4e3624317b6a0f399512078f2a") 1379 1380 var testSNICertificate = fromHex("0441883421114c81480804c430820237308201a0a003020102020900e8f09d3fe25beaa6300d06092a864886f70d01010b0500301f310b3009060355040a1302476f3110300e06035504031307476f20526f6f74301e170d3136303130313030303030305a170d3235303130313030303030305a3023310b3009060355040a1302476f311430120603550403130b736e69746573742e636f6d30819f300d06092a864886f70d010101050003818d0030818902818100db467d932e12270648bc062821ab7ec4b6a25dfe1e5245887a3647a5080d92425bc281c0be97799840fb4f6d14fd2b138bc2a52e67d8d4099ed62238b74a0b74732bc234f1d193e596d9747bf3589f6c613cc0b041d4d92b2b2423775b1c3bbd755dce2054cfa163871d1e24c4f31d1a508baab61443ed97a77562f414c852d70203010001a3773075300e0603551d0f0101ff0404030205a0301d0603551d250416301406082b0601050507030106082b06010505070302300c0603551d130101ff0402300030190603551d0e041204109f91161f43433e49a6de6db680d79f60301b0603551d230414301280104813494d137e1631bba301d5acab6e7b300d06092a864886f70d01010b0500038181007beeecff0230dbb2e7a334af65430b7116e09f327c3bbf918107fc9c66cb497493207ae9b4dbb045cb63d605ec1b5dd485bb69124d68fa298dc776699b47632fd6d73cab57042acb26f083c4087459bc5a3bb3ca4d878d7fe31016b7bc9a627438666566e3389bfaeebe6becc9a0093ceed18d0f9ac79d56f3a73f18188988ed") 1381 1382 var testP256Certificate = fromHex("308201693082010ea00302010202105012dc24e1124ade4f3e153326ff27bf300a06082a8648ce3d04030230123110300e060355040a130741636d6520436f301e170d3137303533313232343934375a170d3138303533313232343934375a30123110300e060355040a130741636d6520436f3059301306072a8648ce3d020106082a8648ce3d03010703420004c02c61c9b16283bbcc14956d886d79b358aa614596975f78cece787146abf74c2d5dc578c0992b4f3c631373479ebf3892efe53d21c4f4f1cc9a11c3536b7f75a3463044300e0603551d0f0101ff0404030205a030130603551d25040c300a06082b06010505070301300c0603551d130101ff04023000300f0603551d1104083006820474657374300a06082a8648ce3d0403020349003046022100963712d6226c7b2bef41512d47e1434131aaca3ba585d666c924df71ac0448b3022100f4d05c725064741aef125f243cdbccaa2a5d485927831f221c43023bd5ae471a") 1383 1384 var testRSAPrivateKey = &rsa.PrivateKey{ 1385 PublicKey: rsa.PublicKey{ 1386 N: bigFromString("153980389784927331788354528594524332344709972855165340650588877572729725338415474372475094155672066328274535240275856844648695200875763869073572078279316458648124537905600131008790701752441155668003033945258023841165089852359980273279085783159654751552359397986180318708491098942831252291841441726305535546071"), 1387 E: 65537, 1388 }, 1389 D: bigFromString("7746362285745539358014631136245887418412633787074173796862711588221766398229333338511838891484974940633857861775630560092874987828057333663969469797013996401149696897591265769095952887917296740109742927689053276850469671231961384712725169432413343763989564437170644270643461665184965150423819594083121075825"), 1390 Primes: []*big.Int{ 1391 bigFromString("13299275414352936908236095374926261633419699590839189494995965049151460173257838079863316944311313904000258169883815802963543635820059341150014695560313417"), 1392 bigFromString("11578103692682951732111718237224894755352163854919244905974423810539077224889290605729035287537520656160688625383765857517518932447378594964220731750802463"), 1393 }, 1394 } 1395 1396 var testECDSAPrivateKey = &ecdsa.PrivateKey{ 1397 PublicKey: ecdsa.PublicKey{ 1398 Curve: elliptic.P521(), 1399 X: bigFromString("2636411247892461147287360222306590634450676461695221912739908880441342231985950069527906976759812296359387337367668045707086543273113073382714101597903639351"), 1400 Y: bigFromString("3204695818431246682253994090650952614555094516658732116404513121125038617915183037601737180082382202488628239201196033284060130040574800684774115478859677243"), 1401 }, 1402 D: bigFromString("5477294338614160138026852784385529180817726002953041720191098180813046231640184669647735805135001309477695746518160084669446643325196003346204701381388769751"), 1403 } 1404 1405 var testP256PrivateKey, _ = x509.ParseECPrivateKey(fromHex("30770201010420012f3b52bc54c36ba3577ad45034e2e8efe1e6999851284cb848725cfe029991a00a06082a8648ce3d030107a14403420004c02c61c9b16283bbcc14956d886d79b358aa614596975f78cece787146abf74c2d5dc578c0992b4f3c631373479ebf3892efe53d21c4f4f1cc9a11c3536b7f75"))