github.com/rsc/go@v0.0.0-20150416155037-e040fd465409/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/ecdsa" 10 "crypto/elliptic" 11 "crypto/rsa" 12 "encoding/hex" 13 "encoding/pem" 14 "errors" 15 "fmt" 16 "io" 17 "math/big" 18 "net" 19 "os" 20 "os/exec" 21 "path/filepath" 22 "strings" 23 "testing" 24 "time" 25 ) 26 27 // zeroSource is an io.Reader that returns an unlimited number of zero bytes. 28 type zeroSource struct{} 29 30 func (zeroSource) Read(b []byte) (n int, err error) { 31 for i := range b { 32 b[i] = 0 33 } 34 35 return len(b), nil 36 } 37 38 var testConfig *Config 39 40 func allCipherSuites() []uint16 { 41 ids := make([]uint16, len(cipherSuites)) 42 for i, suite := range cipherSuites { 43 ids[i] = suite.id 44 } 45 46 return ids 47 } 48 49 func init() { 50 testConfig = &Config{ 51 Time: func() time.Time { return time.Unix(0, 0) }, 52 Rand: zeroSource{}, 53 Certificates: make([]Certificate, 2), 54 InsecureSkipVerify: true, 55 MinVersion: VersionSSL30, 56 MaxVersion: VersionTLS12, 57 CipherSuites: allCipherSuites(), 58 } 59 testConfig.Certificates[0].Certificate = [][]byte{testRSACertificate} 60 testConfig.Certificates[0].PrivateKey = testRSAPrivateKey 61 testConfig.Certificates[1].Certificate = [][]byte{testSNICertificate} 62 testConfig.Certificates[1].PrivateKey = testRSAPrivateKey 63 testConfig.BuildNameToCertificate() 64 } 65 66 func testClientHello(t *testing.T, serverConfig *Config, m handshakeMessage) { 67 testClientHelloFailure(t, serverConfig, m, "") 68 } 69 70 func testClientHelloFailure(t *testing.T, serverConfig *Config, m handshakeMessage, expectedSubStr string) { 71 // Create in-memory network connection, 72 // send message to server. Should return 73 // expected error. 74 c, s := net.Pipe() 75 go func() { 76 cli := Client(c, testConfig) 77 if ch, ok := m.(*clientHelloMsg); ok { 78 cli.vers = ch.vers 79 } 80 cli.writeRecord(recordTypeHandshake, m.marshal()) 81 c.Close() 82 }() 83 err := Server(s, serverConfig).Handshake() 84 s.Close() 85 if len(expectedSubStr) == 0 { 86 if err != nil && err != io.EOF { 87 t.Errorf("Got error: %s; expected to succeed", err, expectedSubStr) 88 } 89 } else if err == nil || !strings.Contains(err.Error(), expectedSubStr) { 90 t.Errorf("Got error: %s; expected to match substring '%s'", err, expectedSubStr) 91 } 92 } 93 94 func TestSimpleError(t *testing.T) { 95 testClientHelloFailure(t, testConfig, &serverHelloDoneMsg{}, "unexpected handshake message") 96 } 97 98 var badProtocolVersions = []uint16{0x0000, 0x0005, 0x0100, 0x0105, 0x0200, 0x0205} 99 100 func TestRejectBadProtocolVersion(t *testing.T) { 101 for _, v := range badProtocolVersions { 102 testClientHelloFailure(t, testConfig, &clientHelloMsg{vers: v}, "unsupported, maximum protocol version") 103 } 104 } 105 106 func TestNoSuiteOverlap(t *testing.T) { 107 clientHello := &clientHelloMsg{ 108 vers: 0x0301, 109 cipherSuites: []uint16{0xff00}, 110 compressionMethods: []uint8{0}, 111 } 112 testClientHelloFailure(t, testConfig, clientHello, "no cipher suite supported by both client and server") 113 } 114 115 func TestNoCompressionOverlap(t *testing.T) { 116 clientHello := &clientHelloMsg{ 117 vers: 0x0301, 118 cipherSuites: []uint16{TLS_RSA_WITH_RC4_128_SHA}, 119 compressionMethods: []uint8{0xff}, 120 } 121 testClientHelloFailure(t, testConfig, clientHello, "client does not support uncompressed connections") 122 } 123 124 func TestNoRC4ByDefault(t *testing.T) { 125 clientHello := &clientHelloMsg{ 126 vers: 0x0301, 127 cipherSuites: []uint16{TLS_RSA_WITH_RC4_128_SHA}, 128 compressionMethods: []uint8{0}, 129 } 130 serverConfig := *testConfig 131 // Reset the enabled cipher suites to nil in order to test the 132 // defaults. 133 serverConfig.CipherSuites = nil 134 testClientHelloFailure(t, &serverConfig, clientHello, "no cipher suite supported by both client and server") 135 } 136 137 func TestDontSelectECDSAWithRSAKey(t *testing.T) { 138 // Test that, even when both sides support an ECDSA cipher suite, it 139 // won't be selected if the server's private key doesn't support it. 140 clientHello := &clientHelloMsg{ 141 vers: 0x0301, 142 cipherSuites: []uint16{TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA}, 143 compressionMethods: []uint8{0}, 144 supportedCurves: []CurveID{CurveP256}, 145 supportedPoints: []uint8{pointFormatUncompressed}, 146 } 147 serverConfig := *testConfig 148 serverConfig.CipherSuites = clientHello.cipherSuites 149 serverConfig.Certificates = make([]Certificate, 1) 150 serverConfig.Certificates[0].Certificate = [][]byte{testECDSACertificate} 151 serverConfig.Certificates[0].PrivateKey = testECDSAPrivateKey 152 serverConfig.BuildNameToCertificate() 153 // First test that it *does* work when the server's key is ECDSA. 154 testClientHello(t, &serverConfig, clientHello) 155 156 // Now test that switching to an RSA key causes the expected error (and 157 // not an internal error about a signing failure). 158 serverConfig.Certificates = testConfig.Certificates 159 testClientHelloFailure(t, &serverConfig, clientHello, "no cipher suite supported by both client and server") 160 } 161 162 func TestDontSelectRSAWithECDSAKey(t *testing.T) { 163 // Test that, even when both sides support an RSA cipher suite, it 164 // won't be selected if the server's private key doesn't support it. 165 clientHello := &clientHelloMsg{ 166 vers: 0x0301, 167 cipherSuites: []uint16{TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA}, 168 compressionMethods: []uint8{0}, 169 supportedCurves: []CurveID{CurveP256}, 170 supportedPoints: []uint8{pointFormatUncompressed}, 171 } 172 serverConfig := *testConfig 173 serverConfig.CipherSuites = clientHello.cipherSuites 174 // First test that it *does* work when the server's key is RSA. 175 testClientHello(t, &serverConfig, clientHello) 176 177 // Now test that switching to an ECDSA key causes the expected error 178 // (and not an internal error about a signing failure). 179 serverConfig.Certificates = make([]Certificate, 1) 180 serverConfig.Certificates[0].Certificate = [][]byte{testECDSACertificate} 181 serverConfig.Certificates[0].PrivateKey = testECDSAPrivateKey 182 serverConfig.BuildNameToCertificate() 183 testClientHelloFailure(t, &serverConfig, clientHello, "no cipher suite supported by both client and server") 184 } 185 186 func TestRenegotiationExtension(t *testing.T) { 187 clientHello := &clientHelloMsg{ 188 vers: VersionTLS12, 189 compressionMethods: []uint8{compressionNone}, 190 random: make([]byte, 32), 191 secureRenegotiation: true, 192 cipherSuites: []uint16{TLS_RSA_WITH_RC4_128_SHA}, 193 } 194 195 var buf []byte 196 c, s := net.Pipe() 197 198 go func() { 199 cli := Client(c, testConfig) 200 cli.vers = clientHello.vers 201 cli.writeRecord(recordTypeHandshake, clientHello.marshal()) 202 203 buf = make([]byte, 1024) 204 n, err := c.Read(buf) 205 if err != nil { 206 t.Fatalf("Server read returned error: %s", err) 207 } 208 buf = buf[:n] 209 c.Close() 210 }() 211 212 Server(s, testConfig).Handshake() 213 214 if len(buf) < 5+4 { 215 t.Fatalf("Server returned short message of length %d", len(buf)) 216 } 217 // buf contains a TLS record, with a 5 byte record header and a 4 byte 218 // handshake header. The length of the ServerHello is taken from the 219 // handshake header. 220 serverHelloLen := int(buf[6])<<16 | int(buf[7])<<8 | int(buf[8]) 221 222 var serverHello serverHelloMsg 223 // unmarshal expects to be given the handshake header, but 224 // serverHelloLen doesn't include it. 225 if !serverHello.unmarshal(buf[5 : 9+serverHelloLen]) { 226 t.Fatalf("Failed to parse ServerHello") 227 } 228 229 if !serverHello.secureRenegotiation { 230 t.Errorf("Secure renegotiation extension was not echoed.") 231 } 232 } 233 234 func TestTLS12OnlyCipherSuites(t *testing.T) { 235 // Test that a Server doesn't select a TLS 1.2-only cipher suite when 236 // the client negotiates TLS 1.1. 237 var zeros [32]byte 238 239 clientHello := &clientHelloMsg{ 240 vers: VersionTLS11, 241 random: zeros[:], 242 cipherSuites: []uint16{ 243 // The Server, by default, will use the client's 244 // preference order. So the GCM cipher suite 245 // will be selected unless it's excluded because 246 // of the version in this ClientHello. 247 TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, 248 TLS_RSA_WITH_RC4_128_SHA, 249 }, 250 compressionMethods: []uint8{compressionNone}, 251 supportedCurves: []CurveID{CurveP256, CurveP384, CurveP521}, 252 supportedPoints: []uint8{pointFormatUncompressed}, 253 } 254 255 c, s := net.Pipe() 256 var reply interface{} 257 var clientErr error 258 go func() { 259 cli := Client(c, testConfig) 260 cli.vers = clientHello.vers 261 cli.writeRecord(recordTypeHandshake, clientHello.marshal()) 262 reply, clientErr = cli.readHandshake() 263 c.Close() 264 }() 265 config := *testConfig 266 config.CipherSuites = clientHello.cipherSuites 267 Server(s, &config).Handshake() 268 s.Close() 269 if clientErr != nil { 270 t.Fatal(clientErr) 271 } 272 serverHello, ok := reply.(*serverHelloMsg) 273 if !ok { 274 t.Fatalf("didn't get ServerHello message in reply. Got %v\n", reply) 275 } 276 if s := serverHello.cipherSuite; s != TLS_RSA_WITH_RC4_128_SHA { 277 t.Fatalf("bad cipher suite from server: %x", s) 278 } 279 } 280 281 func TestAlertForwarding(t *testing.T) { 282 c, s := net.Pipe() 283 go func() { 284 Client(c, testConfig).sendAlert(alertUnknownCA) 285 c.Close() 286 }() 287 288 err := Server(s, testConfig).Handshake() 289 s.Close() 290 if e, ok := err.(*net.OpError); !ok || e.Err != error(alertUnknownCA) { 291 t.Errorf("Got error: %s; expected: %s", err, error(alertUnknownCA)) 292 } 293 } 294 295 func TestClose(t *testing.T) { 296 c, s := net.Pipe() 297 go c.Close() 298 299 err := Server(s, testConfig).Handshake() 300 s.Close() 301 if err != io.EOF { 302 t.Errorf("Got error: %s; expected: %s", err, io.EOF) 303 } 304 } 305 306 func testHandshake(clientConfig, serverConfig *Config) (state ConnectionState, err error) { 307 c, s := net.Pipe() 308 done := make(chan bool) 309 go func() { 310 cli := Client(c, clientConfig) 311 cli.Handshake() 312 c.Close() 313 done <- true 314 }() 315 server := Server(s, serverConfig) 316 err = server.Handshake() 317 if err == nil { 318 state = server.ConnectionState() 319 } 320 s.Close() 321 <-done 322 return 323 } 324 325 func TestVersion(t *testing.T) { 326 serverConfig := &Config{ 327 Certificates: testConfig.Certificates, 328 MaxVersion: VersionTLS11, 329 } 330 clientConfig := &Config{ 331 InsecureSkipVerify: true, 332 } 333 state, err := testHandshake(clientConfig, serverConfig) 334 if err != nil { 335 t.Fatalf("handshake failed: %s", err) 336 } 337 if state.Version != VersionTLS11 { 338 t.Fatalf("Incorrect version %x, should be %x", state.Version, VersionTLS11) 339 } 340 } 341 342 func TestCipherSuitePreference(t *testing.T) { 343 serverConfig := &Config{ 344 CipherSuites: []uint16{TLS_RSA_WITH_RC4_128_SHA, TLS_RSA_WITH_AES_128_CBC_SHA, TLS_ECDHE_RSA_WITH_RC4_128_SHA}, 345 Certificates: testConfig.Certificates, 346 MaxVersion: VersionTLS11, 347 } 348 clientConfig := &Config{ 349 CipherSuites: []uint16{TLS_RSA_WITH_AES_128_CBC_SHA, TLS_RSA_WITH_RC4_128_SHA}, 350 InsecureSkipVerify: true, 351 } 352 state, err := testHandshake(clientConfig, serverConfig) 353 if err != nil { 354 t.Fatalf("handshake failed: %s", err) 355 } 356 if state.CipherSuite != TLS_RSA_WITH_AES_128_CBC_SHA { 357 // By default the server should use the client's preference. 358 t.Fatalf("Client's preference was not used, got %x", state.CipherSuite) 359 } 360 361 serverConfig.PreferServerCipherSuites = true 362 state, err = testHandshake(clientConfig, serverConfig) 363 if err != nil { 364 t.Fatalf("handshake failed: %s", err) 365 } 366 if state.CipherSuite != TLS_RSA_WITH_RC4_128_SHA { 367 t.Fatalf("Server's preference was not used, got %x", state.CipherSuite) 368 } 369 } 370 371 // Note: see comment in handshake_test.go for details of how the reference 372 // tests work. 373 374 // serverTest represents a test of the TLS server handshake against a reference 375 // implementation. 376 type serverTest struct { 377 // name is a freeform string identifying the test and the file in which 378 // the expected results will be stored. 379 name string 380 // command, if not empty, contains a series of arguments for the 381 // command to run for the reference server. 382 command []string 383 // expectedPeerCerts contains a list of PEM blocks of expected 384 // certificates from the client. 385 expectedPeerCerts []string 386 // config, if not nil, contains a custom Config to use for this test. 387 config *Config 388 // expectAlert, if true, indicates that a fatal alert should be returned 389 // when handshaking with the server. 390 expectAlert bool 391 // expectHandshakeErrorIncluding, when not empty, contains a string 392 // that must be a substring of the error resulting from the handshake. 393 expectHandshakeErrorIncluding string 394 // validate, if not nil, is a function that will be called with the 395 // ConnectionState of the resulting connection. It returns false if the 396 // ConnectionState is unacceptable. 397 validate func(ConnectionState) error 398 } 399 400 var defaultClientCommand = []string{"openssl", "s_client", "-no_ticket"} 401 402 // connFromCommand starts opens a listening socket and starts the reference 403 // client to connect to it. It returns a recordingConn that wraps the resulting 404 // connection. 405 func (test *serverTest) connFromCommand() (conn *recordingConn, child *exec.Cmd, err error) { 406 l, err := net.ListenTCP("tcp", &net.TCPAddr{ 407 IP: net.IPv4(127, 0, 0, 1), 408 Port: 0, 409 }) 410 if err != nil { 411 return nil, nil, err 412 } 413 defer l.Close() 414 415 port := l.Addr().(*net.TCPAddr).Port 416 417 var command []string 418 command = append(command, test.command...) 419 if len(command) == 0 { 420 command = defaultClientCommand 421 } 422 command = append(command, "-connect") 423 command = append(command, fmt.Sprintf("127.0.0.1:%d", port)) 424 cmd := exec.Command(command[0], command[1:]...) 425 cmd.Stdin = nil 426 var output bytes.Buffer 427 cmd.Stdout = &output 428 cmd.Stderr = &output 429 if err := cmd.Start(); err != nil { 430 return nil, nil, err 431 } 432 433 connChan := make(chan interface{}) 434 go func() { 435 tcpConn, err := l.Accept() 436 if err != nil { 437 connChan <- err 438 } 439 connChan <- tcpConn 440 }() 441 442 var tcpConn net.Conn 443 select { 444 case connOrError := <-connChan: 445 if err, ok := connOrError.(error); ok { 446 return nil, nil, err 447 } 448 tcpConn = connOrError.(net.Conn) 449 case <-time.After(2 * time.Second): 450 output.WriteTo(os.Stdout) 451 return nil, nil, errors.New("timed out waiting for connection from child process") 452 } 453 454 record := &recordingConn{ 455 Conn: tcpConn, 456 } 457 458 return record, cmd, nil 459 } 460 461 func (test *serverTest) dataPath() string { 462 return filepath.Join("testdata", "Server-"+test.name) 463 } 464 465 func (test *serverTest) loadData() (flows [][]byte, err error) { 466 in, err := os.Open(test.dataPath()) 467 if err != nil { 468 return nil, err 469 } 470 defer in.Close() 471 return parseTestData(in) 472 } 473 474 func (test *serverTest) run(t *testing.T, write bool) { 475 var clientConn, serverConn net.Conn 476 var recordingConn *recordingConn 477 var childProcess *exec.Cmd 478 479 if write { 480 var err error 481 recordingConn, childProcess, err = test.connFromCommand() 482 if err != nil { 483 t.Fatalf("Failed to start subcommand: %s", err) 484 } 485 serverConn = recordingConn 486 } else { 487 clientConn, serverConn = net.Pipe() 488 } 489 config := test.config 490 if config == nil { 491 config = testConfig 492 } 493 server := Server(serverConn, config) 494 connStateChan := make(chan ConnectionState, 1) 495 go func() { 496 var err error 497 if _, err = server.Write([]byte("hello, world\n")); err != nil { 498 t.Logf("Error from Server.Write: %s", err) 499 } 500 if len(test.expectHandshakeErrorIncluding) > 0 { 501 if err == nil { 502 t.Errorf("Error expected, but no error returned") 503 } else if s := err.Error(); !strings.Contains(s, test.expectHandshakeErrorIncluding) { 504 t.Errorf("Error expected containing '%s' but got '%s'", test.expectHandshakeErrorIncluding, s) 505 } 506 } 507 server.Close() 508 serverConn.Close() 509 connStateChan <- server.ConnectionState() 510 }() 511 512 if !write { 513 flows, err := test.loadData() 514 if err != nil { 515 if !test.expectAlert { 516 t.Fatalf("%s: failed to load data from %s", test.name, test.dataPath()) 517 } 518 } 519 for i, b := range flows { 520 if i%2 == 0 { 521 clientConn.Write(b) 522 continue 523 } 524 bb := make([]byte, len(b)) 525 n, err := io.ReadFull(clientConn, bb) 526 if test.expectAlert { 527 if err == nil { 528 t.Fatal("Expected read failure but read succeeded") 529 } 530 } else { 531 if err != nil { 532 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) 533 } 534 if !bytes.Equal(b, bb) { 535 t.Fatalf("%s #%d: mismatch on read: got:%x want:%x", test.name, i+1, bb, b) 536 } 537 } 538 } 539 clientConn.Close() 540 } 541 542 connState := <-connStateChan 543 peerCerts := connState.PeerCertificates 544 if len(peerCerts) == len(test.expectedPeerCerts) { 545 for i, peerCert := range peerCerts { 546 block, _ := pem.Decode([]byte(test.expectedPeerCerts[i])) 547 if !bytes.Equal(block.Bytes, peerCert.Raw) { 548 t.Fatalf("%s: mismatch on peer cert %d", test.name, i+1) 549 } 550 } 551 } else { 552 t.Fatalf("%s: mismatch on peer list length: %d (wanted) != %d (got)", test.name, len(test.expectedPeerCerts), len(peerCerts)) 553 } 554 555 if test.validate != nil { 556 if err := test.validate(connState); err != nil { 557 t.Fatalf("validate callback returned error: %s", err) 558 } 559 } 560 561 if write { 562 path := test.dataPath() 563 out, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644) 564 if err != nil { 565 t.Fatalf("Failed to create output file: %s", err) 566 } 567 defer out.Close() 568 recordingConn.Close() 569 if len(recordingConn.flows) < 3 { 570 childProcess.Stdout.(*bytes.Buffer).WriteTo(os.Stdout) 571 if len(test.expectHandshakeErrorIncluding) == 0 { 572 t.Fatalf("Handshake failed") 573 } 574 } 575 recordingConn.WriteTo(out) 576 fmt.Printf("Wrote %s\n", path) 577 childProcess.Wait() 578 } 579 } 580 581 func runServerTestForVersion(t *testing.T, template *serverTest, prefix, option string) { 582 test := *template 583 test.name = prefix + test.name 584 if len(test.command) == 0 { 585 test.command = defaultClientCommand 586 } 587 test.command = append([]string(nil), test.command...) 588 test.command = append(test.command, option) 589 test.run(t, *update) 590 } 591 592 func runServerTestSSLv3(t *testing.T, template *serverTest) { 593 runServerTestForVersion(t, template, "SSLv3-", "-ssl3") 594 } 595 596 func runServerTestTLS10(t *testing.T, template *serverTest) { 597 runServerTestForVersion(t, template, "TLSv10-", "-tls1") 598 } 599 600 func runServerTestTLS11(t *testing.T, template *serverTest) { 601 runServerTestForVersion(t, template, "TLSv11-", "-tls1_1") 602 } 603 604 func runServerTestTLS12(t *testing.T, template *serverTest) { 605 runServerTestForVersion(t, template, "TLSv12-", "-tls1_2") 606 } 607 608 func TestHandshakeServerRSARC4(t *testing.T) { 609 test := &serverTest{ 610 name: "RSA-RC4", 611 command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "RC4-SHA"}, 612 } 613 runServerTestSSLv3(t, test) 614 runServerTestTLS10(t, test) 615 runServerTestTLS11(t, test) 616 runServerTestTLS12(t, test) 617 } 618 619 func TestHandshakeServerRSA3DES(t *testing.T) { 620 test := &serverTest{ 621 name: "RSA-3DES", 622 command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "DES-CBC3-SHA"}, 623 } 624 runServerTestSSLv3(t, test) 625 runServerTestTLS10(t, test) 626 runServerTestTLS12(t, test) 627 } 628 629 func TestHandshakeServerRSAAES(t *testing.T) { 630 test := &serverTest{ 631 name: "RSA-AES", 632 command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "AES128-SHA"}, 633 } 634 runServerTestSSLv3(t, test) 635 runServerTestTLS10(t, test) 636 runServerTestTLS12(t, test) 637 } 638 639 func TestHandshakeServerAESGCM(t *testing.T) { 640 test := &serverTest{ 641 name: "RSA-AES-GCM", 642 command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "ECDHE-RSA-AES128-GCM-SHA256"}, 643 } 644 runServerTestTLS12(t, test) 645 } 646 647 func TestHandshakeServerAES256GCMSHA384(t *testing.T) { 648 test := &serverTest{ 649 name: "RSA-AES256-GCM-SHA384", 650 command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "ECDHE-RSA-AES256-GCM-SHA384"}, 651 } 652 runServerTestTLS12(t, test) 653 } 654 655 func TestHandshakeServerECDHEECDSAAES(t *testing.T) { 656 config := *testConfig 657 config.Certificates = make([]Certificate, 1) 658 config.Certificates[0].Certificate = [][]byte{testECDSACertificate} 659 config.Certificates[0].PrivateKey = testECDSAPrivateKey 660 config.BuildNameToCertificate() 661 662 test := &serverTest{ 663 name: "ECDHE-ECDSA-AES", 664 command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "ECDHE-ECDSA-AES256-SHA"}, 665 config: &config, 666 } 667 runServerTestTLS10(t, test) 668 runServerTestTLS12(t, test) 669 } 670 671 func TestHandshakeServerALPN(t *testing.T) { 672 config := *testConfig 673 config.NextProtos = []string{"proto1", "proto2"} 674 675 test := &serverTest{ 676 name: "ALPN", 677 // Note that this needs OpenSSL 1.0.2 because that is the first 678 // version that supports the -alpn flag. 679 command: []string{"openssl", "s_client", "-alpn", "proto2,proto1"}, 680 config: &config, 681 validate: func(state ConnectionState) error { 682 // The server's preferences should override the client. 683 if state.NegotiatedProtocol != "proto1" { 684 return fmt.Errorf("Got protocol %q, wanted proto1", state.NegotiatedProtocol) 685 } 686 return nil 687 }, 688 } 689 runServerTestTLS12(t, test) 690 } 691 692 func TestHandshakeServerALPNNoMatch(t *testing.T) { 693 config := *testConfig 694 config.NextProtos = []string{"proto3"} 695 696 test := &serverTest{ 697 name: "ALPN-NoMatch", 698 // Note that this needs OpenSSL 1.0.2 because that is the first 699 // version that supports the -alpn flag. 700 command: []string{"openssl", "s_client", "-alpn", "proto2,proto1"}, 701 config: &config, 702 validate: func(state ConnectionState) error { 703 // Rather than reject the connection, Go doesn't select 704 // a protocol when there is no overlap. 705 if state.NegotiatedProtocol != "" { 706 return fmt.Errorf("Got protocol %q, wanted ''", state.NegotiatedProtocol) 707 } 708 return nil 709 }, 710 } 711 runServerTestTLS12(t, test) 712 } 713 714 // TestHandshakeServerSNI involves a client sending an SNI extension of 715 // "snitest.com", which happens to match the CN of testSNICertificate. The test 716 // verifies that the server correctly selects that certificate. 717 func TestHandshakeServerSNI(t *testing.T) { 718 test := &serverTest{ 719 name: "SNI", 720 command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "AES128-SHA", "-servername", "snitest.com"}, 721 } 722 runServerTestTLS12(t, test) 723 } 724 725 // TestHandshakeServerSNICertForName is similar to TestHandshakeServerSNI, but 726 // tests the dynamic GetCertificate method 727 func TestHandshakeServerSNIGetCertificate(t *testing.T) { 728 config := *testConfig 729 730 // Replace the NameToCertificate map with a GetCertificate function 731 nameToCert := config.NameToCertificate 732 config.NameToCertificate = nil 733 config.GetCertificate = func(clientHello *ClientHelloInfo) (*Certificate, error) { 734 cert, _ := nameToCert[clientHello.ServerName] 735 return cert, nil 736 } 737 test := &serverTest{ 738 name: "SNI", 739 command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "AES128-SHA", "-servername", "snitest.com"}, 740 config: &config, 741 } 742 runServerTestTLS12(t, test) 743 } 744 745 // TestHandshakeServerSNICertForNameNotFound is similar to 746 // TestHandshakeServerSNICertForName, but tests to make sure that when the 747 // GetCertificate method doesn't return a cert, we fall back to what's in 748 // the NameToCertificate map. 749 func TestHandshakeServerSNIGetCertificateNotFound(t *testing.T) { 750 config := *testConfig 751 752 config.GetCertificate = func(clientHello *ClientHelloInfo) (*Certificate, error) { 753 return nil, nil 754 } 755 test := &serverTest{ 756 name: "SNI", 757 command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "AES128-SHA", "-servername", "snitest.com"}, 758 config: &config, 759 } 760 runServerTestTLS12(t, test) 761 } 762 763 // TestHandshakeServerSNICertForNameError tests to make sure that errors in 764 // GetCertificate result in a tls alert. 765 func TestHandshakeServerSNIGetCertificateError(t *testing.T) { 766 config := *testConfig 767 768 config.GetCertificate = func(clientHello *ClientHelloInfo) (*Certificate, error) { 769 return nil, fmt.Errorf("Test error in GetCertificate") 770 } 771 test := &serverTest{ 772 name: "SNI", 773 command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "AES128-SHA", "-servername", "snitest.com"}, 774 config: &config, 775 expectAlert: true, 776 } 777 runServerTestTLS12(t, test) 778 } 779 780 // TestCipherSuiteCertPreferance ensures that we select an RSA ciphersuite with 781 // an RSA certificate and an ECDSA ciphersuite with an ECDSA certificate. 782 func TestCipherSuiteCertPreferenceECDSA(t *testing.T) { 783 config := *testConfig 784 config.CipherSuites = []uint16{TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA} 785 config.PreferServerCipherSuites = true 786 787 test := &serverTest{ 788 name: "CipherSuiteCertPreferenceRSA", 789 config: &config, 790 } 791 runServerTestTLS12(t, test) 792 793 config = *testConfig 794 config.CipherSuites = []uint16{TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA, TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA} 795 config.Certificates = []Certificate{ 796 { 797 Certificate: [][]byte{testECDSACertificate}, 798 PrivateKey: testECDSAPrivateKey, 799 }, 800 } 801 config.BuildNameToCertificate() 802 config.PreferServerCipherSuites = true 803 804 test = &serverTest{ 805 name: "CipherSuiteCertPreferenceECDSA", 806 config: &config, 807 } 808 runServerTestTLS12(t, test) 809 } 810 811 func TestResumption(t *testing.T) { 812 sessionFilePath := tempFile("") 813 defer os.Remove(sessionFilePath) 814 815 test := &serverTest{ 816 name: "IssueTicket", 817 command: []string{"openssl", "s_client", "-cipher", "RC4-SHA", "-sess_out", sessionFilePath}, 818 } 819 runServerTestTLS12(t, test) 820 821 test = &serverTest{ 822 name: "Resume", 823 command: []string{"openssl", "s_client", "-cipher", "RC4-SHA", "-sess_in", sessionFilePath}, 824 } 825 runServerTestTLS12(t, test) 826 } 827 828 func TestResumptionDisabled(t *testing.T) { 829 sessionFilePath := tempFile("") 830 defer os.Remove(sessionFilePath) 831 832 config := *testConfig 833 834 test := &serverTest{ 835 name: "IssueTicketPreDisable", 836 command: []string{"openssl", "s_client", "-cipher", "RC4-SHA", "-sess_out", sessionFilePath}, 837 config: &config, 838 } 839 runServerTestTLS12(t, test) 840 841 config.SessionTicketsDisabled = true 842 843 test = &serverTest{ 844 name: "ResumeDisabled", 845 command: []string{"openssl", "s_client", "-cipher", "RC4-SHA", "-sess_in", sessionFilePath}, 846 config: &config, 847 } 848 runServerTestTLS12(t, test) 849 850 // One needs to manually confirm that the handshake in the golden data 851 // file for ResumeDisabled does not include a resumption handshake. 852 } 853 854 func TestFallbackSCSV(t *testing.T) { 855 serverConfig := &Config{ 856 Certificates: testConfig.Certificates, 857 } 858 test := &serverTest{ 859 name: "FallbackSCSV", 860 config: serverConfig, 861 // OpenSSL 1.0.1j is needed for the -fallback_scsv option. 862 command: []string{"openssl", "s_client", "-fallback_scsv"}, 863 expectHandshakeErrorIncluding: "inappropriate protocol fallback", 864 } 865 runServerTestTLS11(t, test) 866 } 867 868 // cert.pem and key.pem were generated with generate_cert.go 869 // Thus, they have no ExtKeyUsage fields and trigger an error 870 // when verification is turned on. 871 872 const clientCertificatePEM = ` 873 -----BEGIN CERTIFICATE----- 874 MIIB7TCCAVigAwIBAgIBADALBgkqhkiG9w0BAQUwJjEQMA4GA1UEChMHQWNtZSBD 875 bzESMBAGA1UEAxMJMTI3LjAuMC4xMB4XDTExMTIwODA3NTUxMloXDTEyMTIwNzA4 876 MDAxMlowJjEQMA4GA1UEChMHQWNtZSBDbzESMBAGA1UEAxMJMTI3LjAuMC4xMIGc 877 MAsGCSqGSIb3DQEBAQOBjAAwgYgCgYBO0Hsx44Jk2VnAwoekXh6LczPHY1PfZpIG 878 hPZk1Y/kNqcdK+izIDZFI7Xjla7t4PUgnI2V339aEu+H5Fto5OkOdOwEin/ekyfE 879 ARl6vfLcPRSr0FTKIQzQTW6HLlzF0rtNS0/Otiz3fojsfNcCkXSmHgwa2uNKWi7e 880 E5xMQIhZkwIDAQABozIwMDAOBgNVHQ8BAf8EBAMCAKAwDQYDVR0OBAYEBAECAwQw 881 DwYDVR0jBAgwBoAEAQIDBDALBgkqhkiG9w0BAQUDgYEANh+zegx1yW43RmEr1b3A 882 p0vMRpqBWHyFeSnIyMZn3TJWRSt1tukkqVCavh9a+hoV2cxVlXIWg7nCto/9iIw4 883 hB2rXZIxE0/9gzvGnfERYraL7KtnvshksBFQRlgXa5kc0x38BvEO5ZaoDPl4ILdE 884 GFGNEH5PlGffo05wc46QkYU= 885 -----END CERTIFICATE-----` 886 887 const clientKeyPEM = ` 888 -----BEGIN RSA PRIVATE KEY----- 889 MIICWgIBAAKBgE7QezHjgmTZWcDCh6ReHotzM8djU99mkgaE9mTVj+Q2px0r6LMg 890 NkUjteOVru3g9SCcjZXff1oS74fkW2jk6Q507ASKf96TJ8QBGXq98tw9FKvQVMoh 891 DNBNbocuXMXSu01LT862LPd+iOx81wKRdKYeDBra40paLt4TnExAiFmTAgMBAAEC 892 gYBxvXd8yNteFTns8A/2yomEMC4yeosJJSpp1CsN3BJ7g8/qTnrVPxBy+RU+qr63 893 t2WquaOu/cr5P8iEsa6lk20tf8pjKLNXeX0b1RTzK8rJLbS7nGzP3tvOhL096VtQ 894 dAo4ROEaro0TzYpHmpciSvxVIeEIAAdFDObDJPKqcJAxyQJBAJizfYgK8Gzx9fsx 895 hxp+VteCbVPg2euASH5Yv3K5LukRdKoSzHE2grUVQgN/LafC0eZibRanxHegYSr7 896 7qaswKUCQQCEIWor/X4XTMdVj3Oj+vpiw75y/S9gh682+myZL+d/02IEkwnB098P 897 RkKVpenBHyrGg0oeN5La7URILWKj7CPXAkBKo6F+d+phNjwIFoN1Xb/RA32w/D1I 898 saG9sF+UEhRt9AxUfW/U/tIQ9V0ZHHcSg1XaCM5Nvp934brdKdvTOKnJAkBD5h/3 899 Rybatlvg/fzBEaJFyq09zhngkxlZOUtBVTqzl17RVvY2orgH02U4HbCHy4phxOn7 900 qTdQRYlHRftgnWK1AkANibn9PRYJ7mJyJ9Dyj2QeNcSkSTzrt0tPvUMf4+meJymN 901 1Ntu5+S1DLLzfxlaljWG6ylW6DNxujCyuXIV2rvA 902 -----END RSA PRIVATE KEY-----` 903 904 const clientECDSACertificatePEM = ` 905 -----BEGIN CERTIFICATE----- 906 MIIB/DCCAV4CCQCaMIRsJjXZFzAJBgcqhkjOPQQBMEUxCzAJBgNVBAYTAkFVMRMw 907 EQYDVQQIEwpTb21lLVN0YXRlMSEwHwYDVQQKExhJbnRlcm5ldCBXaWRnaXRzIFB0 908 eSBMdGQwHhcNMTIxMTE0MTMyNTUzWhcNMjIxMTEyMTMyNTUzWjBBMQswCQYDVQQG 909 EwJBVTEMMAoGA1UECBMDTlNXMRAwDgYDVQQHEwdQeXJtb250MRIwEAYDVQQDEwlK 910 b2VsIFNpbmcwgZswEAYHKoZIzj0CAQYFK4EEACMDgYYABACVjJF1FMBexFe01MNv 911 ja5oHt1vzobhfm6ySD6B5U7ixohLZNz1MLvT/2XMW/TdtWo+PtAd3kfDdq0Z9kUs 912 jLzYHQFMH3CQRnZIi4+DzEpcj0B22uCJ7B0rxE4wdihBsmKo+1vx+U56jb0JuK7q 913 ixgnTy5w/hOWusPTQBbNZU6sER7m8TAJBgcqhkjOPQQBA4GMADCBiAJCAOAUxGBg 914 C3JosDJdYUoCdFzCgbkWqD8pyDbHgf9stlvZcPE4O1BIKJTLCRpS8V3ujfK58PDa 915 2RU6+b0DeoeiIzXsAkIBo9SKeDUcSpoj0gq+KxAxnZxfvuiRs9oa9V2jI/Umi0Vw 916 jWVim34BmT0Y9hCaOGGbLlfk+syxis7iI6CH8OFnUes= 917 -----END CERTIFICATE-----` 918 919 const clientECDSAKeyPEM = ` 920 -----BEGIN EC PARAMETERS----- 921 BgUrgQQAIw== 922 -----END EC PARAMETERS----- 923 -----BEGIN EC PRIVATE KEY----- 924 MIHcAgEBBEIBkJN9X4IqZIguiEVKMqeBUP5xtRsEv4HJEtOpOGLELwO53SD78Ew8 925 k+wLWoqizS3NpQyMtrU8JFdWfj+C57UNkOugBwYFK4EEACOhgYkDgYYABACVjJF1 926 FMBexFe01MNvja5oHt1vzobhfm6ySD6B5U7ixohLZNz1MLvT/2XMW/TdtWo+PtAd 927 3kfDdq0Z9kUsjLzYHQFMH3CQRnZIi4+DzEpcj0B22uCJ7B0rxE4wdihBsmKo+1vx 928 +U56jb0JuK7qixgnTy5w/hOWusPTQBbNZU6sER7m8Q== 929 -----END EC PRIVATE KEY-----` 930 931 func TestClientAuth(t *testing.T) { 932 var certPath, keyPath, ecdsaCertPath, ecdsaKeyPath string 933 934 if *update { 935 certPath = tempFile(clientCertificatePEM) 936 defer os.Remove(certPath) 937 keyPath = tempFile(clientKeyPEM) 938 defer os.Remove(keyPath) 939 ecdsaCertPath = tempFile(clientECDSACertificatePEM) 940 defer os.Remove(ecdsaCertPath) 941 ecdsaKeyPath = tempFile(clientECDSAKeyPEM) 942 defer os.Remove(ecdsaKeyPath) 943 } 944 945 config := *testConfig 946 config.ClientAuth = RequestClientCert 947 948 test := &serverTest{ 949 name: "ClientAuthRequestedNotGiven", 950 command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "RC4-SHA"}, 951 config: &config, 952 } 953 runServerTestTLS12(t, test) 954 955 test = &serverTest{ 956 name: "ClientAuthRequestedAndGiven", 957 command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "RC4-SHA", "-cert", certPath, "-key", keyPath}, 958 config: &config, 959 expectedPeerCerts: []string{clientCertificatePEM}, 960 } 961 runServerTestTLS12(t, test) 962 963 test = &serverTest{ 964 name: "ClientAuthRequestedAndECDSAGiven", 965 command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "RC4-SHA", "-cert", ecdsaCertPath, "-key", ecdsaKeyPath}, 966 config: &config, 967 expectedPeerCerts: []string{clientECDSACertificatePEM}, 968 } 969 runServerTestTLS12(t, test) 970 } 971 972 func bigFromString(s string) *big.Int { 973 ret := new(big.Int) 974 ret.SetString(s, 10) 975 return ret 976 } 977 978 func fromHex(s string) []byte { 979 b, _ := hex.DecodeString(s) 980 return b 981 } 982 983 var testRSACertificate = fromHex("308202b030820219a00302010202090085b0bba48a7fb8ca300d06092a864886f70d01010505003045310b3009060355040613024155311330110603550408130a536f6d652d53746174653121301f060355040a1318496e7465726e6574205769646769747320507479204c7464301e170d3130303432343039303933385a170d3131303432343039303933385a3045310b3009060355040613024155311330110603550408130a536f6d652d53746174653121301f060355040a1318496e7465726e6574205769646769747320507479204c746430819f300d06092a864886f70d010101050003818d0030818902818100bb79d6f517b5e5bf4610d0dc69bee62b07435ad0032d8a7a4385b71452e7a5654c2c78b8238cb5b482e5de1f953b7e62a52ca533d6fe125c7a56fcf506bffa587b263fb5cd04d3d0c921964ac7f4549f5abfef427100fe1899077f7e887d7df10439c4a22edb51c97ce3c04c3b326601cfafb11db8719a1ddbdb896baeda2d790203010001a381a73081a4301d0603551d0e04160414b1ade2855acfcb28db69ce2369ded3268e18883930750603551d23046e306c8014b1ade2855acfcb28db69ce2369ded3268e188839a149a4473045310b3009060355040613024155311330110603550408130a536f6d652d53746174653121301f060355040a1318496e7465726e6574205769646769747320507479204c746482090085b0bba48a7fb8ca300c0603551d13040530030101ff300d06092a864886f70d010105050003818100086c4524c76bb159ab0c52ccf2b014d7879d7a6475b55a9566e4c52b8eae12661feb4f38b36e60d392fdf74108b52513b1187a24fb301dbaed98b917ece7d73159db95d31d78ea50565cd5825a2d5a5f33c4b6d8c97590968c0f5298b5cd981f89205ff2a01ca31b9694dda9fd57e970e8266d71999b266e3850296c90a7bdd9") 984 985 var testECDSACertificate = fromHex("3082020030820162020900b8bf2d47a0d2ebf4300906072a8648ce3d04013045310b3009060355040613024155311330110603550408130a536f6d652d53746174653121301f060355040a1318496e7465726e6574205769646769747320507479204c7464301e170d3132313132323135303633325a170d3232313132303135303633325a3045310b3009060355040613024155311330110603550408130a536f6d652d53746174653121301f060355040a1318496e7465726e6574205769646769747320507479204c746430819b301006072a8648ce3d020106052b81040023038186000400c4a1edbe98f90b4873367ec316561122f23d53c33b4d213dcd6b75e6f6b0dc9adf26c1bcb287f072327cb3642f1c90bcea6823107efee325c0483a69e0286dd33700ef0462dd0da09c706283d881d36431aa9e9731bd96b068c09b23de76643f1a5c7fe9120e5858b65f70dd9bd8ead5d7f5d5ccb9b69f30665b669a20e227e5bffe3b300906072a8648ce3d040103818c0030818802420188a24febe245c5487d1bacf5ed989dae4770c05e1bb62fbdf1b64db76140d311a2ceee0b7e927eff769dc33b7ea53fcefa10e259ec472d7cacda4e970e15a06fd00242014dfcbe67139c2d050ebd3fa38c25c13313830d9406bbd4377af6ec7ac9862eddd711697f857c56defb31782be4c7780daecbbe9e4e3624317b6a0f399512078f2a") 986 987 var testSNICertificate = fromHex("308201f23082015da003020102020100300b06092a864886f70d01010530283110300e060355040a130741636d6520436f311430120603550403130b736e69746573742e636f6d301e170d3132303431313137343033355a170d3133303431313137343533355a30283110300e060355040a130741636d6520436f311430120603550403130b736e69746573742e636f6d30819d300b06092a864886f70d01010103818d0030818902818100bb79d6f517b5e5bf4610d0dc69bee62b07435ad0032d8a7a4385b71452e7a5654c2c78b8238cb5b482e5de1f953b7e62a52ca533d6fe125c7a56fcf506bffa587b263fb5cd04d3d0c921964ac7f4549f5abfef427100fe1899077f7e887d7df10439c4a22edb51c97ce3c04c3b326601cfafb11db8719a1ddbdb896baeda2d790203010001a3323030300e0603551d0f0101ff0404030200a0300d0603551d0e0406040401020304300f0603551d2304083006800401020304300b06092a864886f70d0101050381810089c6455f1c1f5ef8eb1ab174ee2439059f5c4259bb1a8d86cdb1d056f56a717da40e95ab90f59e8deaf627c157995094db0802266eb34fc6842dea8a4b68d9c1389103ab84fb9e1f85d9b5d23ff2312c8670fbb540148245a4ebafe264d90c8a4cf4f85b0fac12ac2fc4a3154bad52462868af96c62c6525d652b6e31845bdcc") 988 989 var testRSAPrivateKey = &rsa.PrivateKey{ 990 PublicKey: rsa.PublicKey{ 991 N: bigFromString("131650079503776001033793877885499001334664249354723305978524647182322416328664556247316495448366990052837680518067798333412266673813370895702118944398081598789828837447552603077848001020611640547221687072142537202428102790818451901395596882588063427854225330436740647715202971973145151161964464812406232198521"), 992 E: 65537, 993 }, 994 D: bigFromString("29354450337804273969007277378287027274721892607543397931919078829901848876371746653677097639302788129485893852488285045793268732234230875671682624082413996177431586734171663258657462237320300610850244186316880055243099640544518318093544057213190320837094958164973959123058337475052510833916491060913053867729"), 995 Primes: []*big.Int{ 996 bigFromString("11969277782311800166562047708379380720136961987713178380670422671426759650127150688426177829077494755200794297055316163155755835813760102405344560929062149"), 997 bigFromString("10998999429884441391899182616418192492905073053684657075974935218461686523870125521822756579792315215543092255516093840728890783887287417039645833477273829"), 998 }, 999 } 1000 1001 var testECDSAPrivateKey = &ecdsa.PrivateKey{ 1002 PublicKey: ecdsa.PublicKey{ 1003 Curve: elliptic.P521(), 1004 X: bigFromString("2636411247892461147287360222306590634450676461695221912739908880441342231985950069527906976759812296359387337367668045707086543273113073382714101597903639351"), 1005 Y: bigFromString("3204695818431246682253994090650952614555094516658732116404513121125038617915183037601737180082382202488628239201196033284060130040574800684774115478859677243"), 1006 }, 1007 D: bigFromString("5477294338614160138026852784385529180817726002953041720191098180813046231640184669647735805135001309477695746518160084669446643325196003346204701381388769751"), 1008 }