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