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