github.com/hikaru7719/go@v0.0.0-20181025140707-c8b2ac68906a/src/crypto/tls/handshake_client_test.go (about) 1 // Copyright 2010 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/rsa" 11 "crypto/x509" 12 "encoding/base64" 13 "encoding/binary" 14 "encoding/pem" 15 "errors" 16 "fmt" 17 "io" 18 "math/big" 19 "net" 20 "os" 21 "os/exec" 22 "path/filepath" 23 "strconv" 24 "strings" 25 "sync" 26 "testing" 27 "time" 28 ) 29 30 // Note: see comment in handshake_test.go for details of how the reference 31 // tests work. 32 33 // opensslInputEvent enumerates possible inputs that can be sent to an `openssl 34 // s_client` process. 35 type opensslInputEvent int 36 37 const ( 38 // opensslRenegotiate causes OpenSSL to request a renegotiation of the 39 // connection. 40 opensslRenegotiate opensslInputEvent = iota 41 42 // opensslSendBanner causes OpenSSL to send the contents of 43 // opensslSentinel on the connection. 44 opensslSendSentinel 45 ) 46 47 const opensslSentinel = "SENTINEL\n" 48 49 type opensslInput chan opensslInputEvent 50 51 func (i opensslInput) Read(buf []byte) (n int, err error) { 52 for event := range i { 53 switch event { 54 case opensslRenegotiate: 55 return copy(buf, []byte("R\n")), nil 56 case opensslSendSentinel: 57 return copy(buf, []byte(opensslSentinel)), nil 58 default: 59 panic("unknown event") 60 } 61 } 62 63 return 0, io.EOF 64 } 65 66 // opensslOutputSink is an io.Writer that receives the stdout and stderr from 67 // an `openssl` process and sends a value to handshakeComplete when it sees a 68 // log message from a completed server handshake. 69 type opensslOutputSink struct { 70 handshakeComplete chan struct{} 71 all []byte 72 line []byte 73 } 74 75 func newOpensslOutputSink() *opensslOutputSink { 76 return &opensslOutputSink{make(chan struct{}), nil, nil} 77 } 78 79 // opensslEndOfHandshake is a message that the “openssl s_server” tool will 80 // print when a handshake completes if run with “-state”. 81 const opensslEndOfHandshake = "SSL_accept:SSLv3/TLS write finished" 82 83 func (o *opensslOutputSink) Write(data []byte) (n int, err error) { 84 o.line = append(o.line, data...) 85 o.all = append(o.all, data...) 86 87 for { 88 i := bytes.IndexByte(o.line, '\n') 89 if i < 0 { 90 break 91 } 92 93 if bytes.Equal([]byte(opensslEndOfHandshake), o.line[:i]) { 94 o.handshakeComplete <- struct{}{} 95 } 96 o.line = o.line[i+1:] 97 } 98 99 return len(data), nil 100 } 101 102 func (o *opensslOutputSink) WriteTo(w io.Writer) (int64, error) { 103 n, err := w.Write(o.all) 104 return int64(n), err 105 } 106 107 // clientTest represents a test of the TLS client handshake against a reference 108 // implementation. 109 type clientTest struct { 110 // name is a freeform string identifying the test and the file in which 111 // the expected results will be stored. 112 name string 113 // command, if not empty, contains a series of arguments for the 114 // command to run for the reference server. 115 command []string 116 // config, if not nil, contains a custom Config to use for this test. 117 config *Config 118 // cert, if not empty, contains a DER-encoded certificate for the 119 // reference server. 120 cert []byte 121 // key, if not nil, contains either a *rsa.PrivateKey or 122 // *ecdsa.PrivateKey which is the private key for the reference server. 123 key interface{} 124 // extensions, if not nil, contains a list of extension data to be returned 125 // from the ServerHello. The data should be in standard TLS format with 126 // a 2-byte uint16 type, 2-byte data length, followed by the extension data. 127 extensions [][]byte 128 // validate, if not nil, is a function that will be called with the 129 // ConnectionState of the resulting connection. It returns a non-nil 130 // error if the ConnectionState is unacceptable. 131 validate func(ConnectionState) error 132 // numRenegotiations is the number of times that the connection will be 133 // renegotiated. 134 numRenegotiations int 135 // renegotiationExpectedToFail, if not zero, is the number of the 136 // renegotiation attempt that is expected to fail. 137 renegotiationExpectedToFail int 138 // checkRenegotiationError, if not nil, is called with any error 139 // arising from renegotiation. It can map expected errors to nil to 140 // ignore them. 141 checkRenegotiationError func(renegotiationNum int, err error) error 142 } 143 144 var defaultServerCommand = []string{"openssl", "s_server"} 145 146 // connFromCommand starts the reference server process, connects to it and 147 // returns a recordingConn for the connection. The stdin return value is an 148 // opensslInput for the stdin of the child process. It must be closed before 149 // Waiting for child. 150 func (test *clientTest) connFromCommand() (conn *recordingConn, child *exec.Cmd, stdin opensslInput, stdout *opensslOutputSink, err error) { 151 cert := testRSACertificate 152 if len(test.cert) > 0 { 153 cert = test.cert 154 } 155 certPath := tempFile(string(cert)) 156 defer os.Remove(certPath) 157 158 var key interface{} = testRSAPrivateKey 159 if test.key != nil { 160 key = test.key 161 } 162 var pemType string 163 var derBytes []byte 164 switch key := key.(type) { 165 case *rsa.PrivateKey: 166 pemType = "RSA" 167 derBytes = x509.MarshalPKCS1PrivateKey(key) 168 case *ecdsa.PrivateKey: 169 pemType = "EC" 170 var err error 171 derBytes, err = x509.MarshalECPrivateKey(key) 172 if err != nil { 173 panic(err) 174 } 175 default: 176 panic("unknown key type") 177 } 178 179 var pemOut bytes.Buffer 180 pem.Encode(&pemOut, &pem.Block{Type: pemType + " PRIVATE KEY", Bytes: derBytes}) 181 182 keyPath := tempFile(pemOut.String()) 183 defer os.Remove(keyPath) 184 185 var command []string 186 if len(test.command) > 0 { 187 command = append(command, test.command...) 188 } else { 189 command = append(command, defaultServerCommand...) 190 } 191 command = append(command, "-cert", certPath, "-certform", "DER", "-key", keyPath) 192 // serverPort contains the port that OpenSSL will listen on. OpenSSL 193 // can't take "0" as an argument here so we have to pick a number and 194 // hope that it's not in use on the machine. Since this only occurs 195 // when -update is given and thus when there's a human watching the 196 // test, this isn't too bad. 197 const serverPort = 24323 198 command = append(command, "-accept", strconv.Itoa(serverPort)) 199 200 if len(test.extensions) > 0 { 201 var serverInfo bytes.Buffer 202 for _, ext := range test.extensions { 203 pem.Encode(&serverInfo, &pem.Block{ 204 Type: fmt.Sprintf("SERVERINFO FOR EXTENSION %d", binary.BigEndian.Uint16(ext)), 205 Bytes: ext, 206 }) 207 } 208 serverInfoPath := tempFile(serverInfo.String()) 209 defer os.Remove(serverInfoPath) 210 command = append(command, "-serverinfo", serverInfoPath) 211 } 212 213 if test.numRenegotiations > 0 { 214 found := false 215 for _, flag := range command[1:] { 216 if flag == "-state" { 217 found = true 218 break 219 } 220 } 221 222 if !found { 223 panic("-state flag missing to OpenSSL. You need this if testing renegotiation") 224 } 225 } 226 227 cmd := exec.Command(command[0], command[1:]...) 228 stdin = opensslInput(make(chan opensslInputEvent)) 229 cmd.Stdin = stdin 230 out := newOpensslOutputSink() 231 cmd.Stdout = out 232 cmd.Stderr = out 233 if err := cmd.Start(); err != nil { 234 return nil, nil, nil, nil, err 235 } 236 237 // OpenSSL does print an "ACCEPT" banner, but it does so *before* 238 // opening the listening socket, so we can't use that to wait until it 239 // has started listening. Thus we are forced to poll until we get a 240 // connection. 241 var tcpConn net.Conn 242 for i := uint(0); i < 5; i++ { 243 tcpConn, err = net.DialTCP("tcp", nil, &net.TCPAddr{ 244 IP: net.IPv4(127, 0, 0, 1), 245 Port: serverPort, 246 }) 247 if err == nil { 248 break 249 } 250 time.Sleep((1 << i) * 5 * time.Millisecond) 251 } 252 if err != nil { 253 close(stdin) 254 out.WriteTo(os.Stdout) 255 cmd.Process.Kill() 256 return nil, nil, nil, nil, cmd.Wait() 257 } 258 259 record := &recordingConn{ 260 Conn: tcpConn, 261 } 262 263 return record, cmd, stdin, out, nil 264 } 265 266 func (test *clientTest) dataPath() string { 267 return filepath.Join("testdata", "Client-"+test.name) 268 } 269 270 func (test *clientTest) loadData() (flows [][]byte, err error) { 271 in, err := os.Open(test.dataPath()) 272 if err != nil { 273 return nil, err 274 } 275 defer in.Close() 276 return parseTestData(in) 277 } 278 279 func (test *clientTest) run(t *testing.T, write bool) { 280 checkOpenSSLVersion(t) 281 282 var clientConn, serverConn net.Conn 283 var recordingConn *recordingConn 284 var childProcess *exec.Cmd 285 var stdin opensslInput 286 var stdout *opensslOutputSink 287 288 if write { 289 var err error 290 recordingConn, childProcess, stdin, stdout, err = test.connFromCommand() 291 if err != nil { 292 t.Fatalf("Failed to start subcommand: %s", err) 293 } 294 clientConn = recordingConn 295 } else { 296 clientConn, serverConn = localPipe(t) 297 } 298 299 config := test.config 300 if config == nil { 301 config = testConfig 302 } 303 client := Client(clientConn, config) 304 305 doneChan := make(chan bool) 306 go func() { 307 defer func() { doneChan <- true }() 308 defer clientConn.Close() 309 defer client.Close() 310 311 if _, err := client.Write([]byte("hello\n")); err != nil { 312 t.Errorf("Client.Write failed: %s", err) 313 return 314 } 315 316 for i := 1; i <= test.numRenegotiations; i++ { 317 // The initial handshake will generate a 318 // handshakeComplete signal which needs to be quashed. 319 if i == 1 && write { 320 <-stdout.handshakeComplete 321 } 322 323 // OpenSSL will try to interleave application data and 324 // a renegotiation if we send both concurrently. 325 // Therefore: ask OpensSSL to start a renegotiation, run 326 // a goroutine to call client.Read and thus process the 327 // renegotiation request, watch for OpenSSL's stdout to 328 // indicate that the handshake is complete and, 329 // finally, have OpenSSL write something to cause 330 // client.Read to complete. 331 if write { 332 stdin <- opensslRenegotiate 333 } 334 335 signalChan := make(chan struct{}) 336 337 go func() { 338 defer func() { signalChan <- struct{}{} }() 339 340 buf := make([]byte, 256) 341 n, err := client.Read(buf) 342 343 if test.checkRenegotiationError != nil { 344 newErr := test.checkRenegotiationError(i, err) 345 if err != nil && newErr == nil { 346 return 347 } 348 err = newErr 349 } 350 351 if err != nil { 352 t.Errorf("Client.Read failed after renegotiation #%d: %s", i, err) 353 return 354 } 355 356 buf = buf[:n] 357 if !bytes.Equal([]byte(opensslSentinel), buf) { 358 t.Errorf("Client.Read returned %q, but wanted %q", string(buf), opensslSentinel) 359 } 360 361 if expected := i + 1; client.handshakes != expected { 362 t.Errorf("client should have recorded %d handshakes, but believes that %d have occurred", expected, client.handshakes) 363 } 364 }() 365 366 if write && test.renegotiationExpectedToFail != i { 367 <-stdout.handshakeComplete 368 stdin <- opensslSendSentinel 369 } 370 <-signalChan 371 } 372 373 if test.validate != nil { 374 if err := test.validate(client.ConnectionState()); err != nil { 375 t.Errorf("validate callback returned error: %s", err) 376 } 377 } 378 }() 379 380 if !write { 381 flows, err := test.loadData() 382 if err != nil { 383 t.Fatalf("%s: failed to load data from %s: %v", test.name, test.dataPath(), err) 384 } 385 for i, b := range flows { 386 if i%2 == 1 { 387 serverConn.Write(b) 388 continue 389 } 390 bb := make([]byte, len(b)) 391 _, err := io.ReadFull(serverConn, bb) 392 if err != nil { 393 t.Fatalf("%s #%d: %s", test.name, i, err) 394 } 395 if !bytes.Equal(b, bb) { 396 t.Fatalf("%s #%d: mismatch on read: got:%x want:%x", test.name, i, bb, b) 397 } 398 } 399 serverConn.Close() 400 } 401 402 <-doneChan 403 404 if write { 405 path := test.dataPath() 406 out, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644) 407 if err != nil { 408 t.Fatalf("Failed to create output file: %s", err) 409 } 410 defer out.Close() 411 recordingConn.Close() 412 close(stdin) 413 childProcess.Process.Kill() 414 childProcess.Wait() 415 if len(recordingConn.flows) < 3 { 416 os.Stdout.Write(childProcess.Stdout.(*opensslOutputSink).all) 417 t.Fatalf("Client connection didn't work") 418 } 419 recordingConn.WriteTo(out) 420 fmt.Printf("Wrote %s\n", path) 421 } 422 } 423 424 var ( 425 didParMu sync.Mutex 426 didPar = map[*testing.T]bool{} 427 ) 428 429 // setParallel calls t.Parallel once. If you call it twice, it would 430 // panic. 431 func setParallel(t *testing.T) { 432 didParMu.Lock() 433 v := didPar[t] 434 didPar[t] = true 435 didParMu.Unlock() 436 if !v { 437 t.Parallel() 438 } 439 } 440 441 func runClientTestForVersion(t *testing.T, template *clientTest, prefix, option string) { 442 setParallel(t) 443 444 test := *template 445 test.name = prefix + test.name 446 if len(test.command) == 0 { 447 test.command = defaultClientCommand 448 } 449 test.command = append([]string(nil), test.command...) 450 test.command = append(test.command, option) 451 test.run(t, *update) 452 } 453 454 func runClientTestTLS10(t *testing.T, template *clientTest) { 455 runClientTestForVersion(t, template, "TLSv10-", "-tls1") 456 } 457 458 func runClientTestTLS11(t *testing.T, template *clientTest) { 459 runClientTestForVersion(t, template, "TLSv11-", "-tls1_1") 460 } 461 462 func runClientTestTLS12(t *testing.T, template *clientTest) { 463 runClientTestForVersion(t, template, "TLSv12-", "-tls1_2") 464 } 465 466 func TestHandshakeClientRSARC4(t *testing.T) { 467 test := &clientTest{ 468 name: "RSA-RC4", 469 command: []string{"openssl", "s_server", "-cipher", "RC4-SHA"}, 470 } 471 runClientTestTLS10(t, test) 472 runClientTestTLS11(t, test) 473 runClientTestTLS12(t, test) 474 } 475 476 func TestHandshakeClientRSAAES128GCM(t *testing.T) { 477 test := &clientTest{ 478 name: "AES128-GCM-SHA256", 479 command: []string{"openssl", "s_server", "-cipher", "AES128-GCM-SHA256"}, 480 } 481 runClientTestTLS12(t, test) 482 } 483 484 func TestHandshakeClientRSAAES256GCM(t *testing.T) { 485 test := &clientTest{ 486 name: "AES256-GCM-SHA384", 487 command: []string{"openssl", "s_server", "-cipher", "AES256-GCM-SHA384"}, 488 } 489 runClientTestTLS12(t, test) 490 } 491 492 func TestHandshakeClientECDHERSAAES(t *testing.T) { 493 test := &clientTest{ 494 name: "ECDHE-RSA-AES", 495 command: []string{"openssl", "s_server", "-cipher", "ECDHE-RSA-AES128-SHA"}, 496 } 497 runClientTestTLS10(t, test) 498 runClientTestTLS11(t, test) 499 runClientTestTLS12(t, test) 500 } 501 502 func TestHandshakeClientECDHEECDSAAES(t *testing.T) { 503 test := &clientTest{ 504 name: "ECDHE-ECDSA-AES", 505 command: []string{"openssl", "s_server", "-cipher", "ECDHE-ECDSA-AES128-SHA"}, 506 cert: testECDSACertificate, 507 key: testECDSAPrivateKey, 508 } 509 runClientTestTLS10(t, test) 510 runClientTestTLS11(t, test) 511 runClientTestTLS12(t, test) 512 } 513 514 func TestHandshakeClientECDHEECDSAAESGCM(t *testing.T) { 515 test := &clientTest{ 516 name: "ECDHE-ECDSA-AES-GCM", 517 command: []string{"openssl", "s_server", "-cipher", "ECDHE-ECDSA-AES128-GCM-SHA256"}, 518 cert: testECDSACertificate, 519 key: testECDSAPrivateKey, 520 } 521 runClientTestTLS12(t, test) 522 } 523 524 func TestHandshakeClientAES256GCMSHA384(t *testing.T) { 525 test := &clientTest{ 526 name: "ECDHE-ECDSA-AES256-GCM-SHA384", 527 command: []string{"openssl", "s_server", "-cipher", "ECDHE-ECDSA-AES256-GCM-SHA384"}, 528 cert: testECDSACertificate, 529 key: testECDSAPrivateKey, 530 } 531 runClientTestTLS12(t, test) 532 } 533 534 func TestHandshakeClientAES128CBCSHA256(t *testing.T) { 535 test := &clientTest{ 536 name: "AES128-SHA256", 537 command: []string{"openssl", "s_server", "-cipher", "AES128-SHA256"}, 538 } 539 runClientTestTLS12(t, test) 540 } 541 542 func TestHandshakeClientECDHERSAAES128CBCSHA256(t *testing.T) { 543 test := &clientTest{ 544 name: "ECDHE-RSA-AES128-SHA256", 545 command: []string{"openssl", "s_server", "-cipher", "ECDHE-RSA-AES128-SHA256"}, 546 } 547 runClientTestTLS12(t, test) 548 } 549 550 func TestHandshakeClientECDHEECDSAAES128CBCSHA256(t *testing.T) { 551 test := &clientTest{ 552 name: "ECDHE-ECDSA-AES128-SHA256", 553 command: []string{"openssl", "s_server", "-cipher", "ECDHE-ECDSA-AES128-SHA256"}, 554 cert: testECDSACertificate, 555 key: testECDSAPrivateKey, 556 } 557 runClientTestTLS12(t, test) 558 } 559 560 func TestHandshakeClientX25519(t *testing.T) { 561 config := testConfig.Clone() 562 config.CurvePreferences = []CurveID{X25519} 563 564 test := &clientTest{ 565 name: "X25519-ECDHE-RSA-AES-GCM", 566 command: []string{"openssl", "s_server", "-cipher", "ECDHE-RSA-AES128-GCM-SHA256"}, 567 config: config, 568 } 569 570 runClientTestTLS12(t, test) 571 } 572 573 func TestHandshakeClientECDHERSAChaCha20(t *testing.T) { 574 config := testConfig.Clone() 575 config.CipherSuites = []uint16{TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305} 576 577 test := &clientTest{ 578 name: "ECDHE-RSA-CHACHA20-POLY1305", 579 command: []string{"openssl", "s_server", "-cipher", "ECDHE-RSA-CHACHA20-POLY1305"}, 580 config: config, 581 } 582 583 runClientTestTLS12(t, test) 584 } 585 586 func TestHandshakeClientECDHEECDSAChaCha20(t *testing.T) { 587 config := testConfig.Clone() 588 config.CipherSuites = []uint16{TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305} 589 590 test := &clientTest{ 591 name: "ECDHE-ECDSA-CHACHA20-POLY1305", 592 command: []string{"openssl", "s_server", "-cipher", "ECDHE-ECDSA-CHACHA20-POLY1305"}, 593 config: config, 594 cert: testECDSACertificate, 595 key: testECDSAPrivateKey, 596 } 597 598 runClientTestTLS12(t, test) 599 } 600 601 func TestHandshakeClientCertRSA(t *testing.T) { 602 config := testConfig.Clone() 603 cert, _ := X509KeyPair([]byte(clientCertificatePEM), []byte(clientKeyPEM)) 604 config.Certificates = []Certificate{cert} 605 606 test := &clientTest{ 607 name: "ClientCert-RSA-RSA", 608 command: []string{"openssl", "s_server", "-cipher", "AES128", "-verify", "1"}, 609 config: config, 610 } 611 612 runClientTestTLS10(t, test) 613 runClientTestTLS12(t, test) 614 615 test = &clientTest{ 616 name: "ClientCert-RSA-ECDSA", 617 command: []string{"openssl", "s_server", "-cipher", "ECDHE-ECDSA-AES128-SHA", "-verify", "1"}, 618 config: config, 619 cert: testECDSACertificate, 620 key: testECDSAPrivateKey, 621 } 622 623 runClientTestTLS10(t, test) 624 runClientTestTLS12(t, test) 625 626 test = &clientTest{ 627 name: "ClientCert-RSA-AES256-GCM-SHA384", 628 command: []string{"openssl", "s_server", "-cipher", "ECDHE-RSA-AES256-GCM-SHA384", "-verify", "1"}, 629 config: config, 630 cert: testRSACertificate, 631 key: testRSAPrivateKey, 632 } 633 634 runClientTestTLS12(t, test) 635 } 636 637 func TestHandshakeClientCertECDSA(t *testing.T) { 638 config := testConfig.Clone() 639 cert, _ := X509KeyPair([]byte(clientECDSACertificatePEM), []byte(clientECDSAKeyPEM)) 640 config.Certificates = []Certificate{cert} 641 642 test := &clientTest{ 643 name: "ClientCert-ECDSA-RSA", 644 command: []string{"openssl", "s_server", "-cipher", "AES128", "-verify", "1"}, 645 config: config, 646 } 647 648 runClientTestTLS10(t, test) 649 runClientTestTLS12(t, test) 650 651 test = &clientTest{ 652 name: "ClientCert-ECDSA-ECDSA", 653 command: []string{"openssl", "s_server", "-cipher", "ECDHE-ECDSA-AES128-SHA", "-verify", "1"}, 654 config: config, 655 cert: testECDSACertificate, 656 key: testECDSAPrivateKey, 657 } 658 659 runClientTestTLS10(t, test) 660 runClientTestTLS12(t, test) 661 } 662 663 func TestClientResumption(t *testing.T) { 664 serverConfig := &Config{ 665 CipherSuites: []uint16{TLS_RSA_WITH_RC4_128_SHA, TLS_ECDHE_RSA_WITH_RC4_128_SHA}, 666 Certificates: testConfig.Certificates, 667 } 668 669 issuer, err := x509.ParseCertificate(testRSACertificateIssuer) 670 if err != nil { 671 panic(err) 672 } 673 674 rootCAs := x509.NewCertPool() 675 rootCAs.AddCert(issuer) 676 677 clientConfig := &Config{ 678 CipherSuites: []uint16{TLS_RSA_WITH_RC4_128_SHA}, 679 ClientSessionCache: NewLRUClientSessionCache(32), 680 RootCAs: rootCAs, 681 ServerName: "example.golang", 682 } 683 684 testResumeState := func(test string, didResume bool) { 685 _, hs, err := testHandshake(t, clientConfig, serverConfig) 686 if err != nil { 687 t.Fatalf("%s: handshake failed: %s", test, err) 688 } 689 if hs.DidResume != didResume { 690 t.Fatalf("%s resumed: %v, expected: %v", test, hs.DidResume, didResume) 691 } 692 if didResume && (hs.PeerCertificates == nil || hs.VerifiedChains == nil) { 693 t.Fatalf("expected non-nil certificates after resumption. Got peerCertificates: %#v, verifiedCertificates: %#v", hs.PeerCertificates, hs.VerifiedChains) 694 } 695 } 696 697 getTicket := func() []byte { 698 return clientConfig.ClientSessionCache.(*lruSessionCache).q.Front().Value.(*lruSessionCacheEntry).state.sessionTicket 699 } 700 randomKey := func() [32]byte { 701 var k [32]byte 702 if _, err := io.ReadFull(serverConfig.rand(), k[:]); err != nil { 703 t.Fatalf("Failed to read new SessionTicketKey: %s", err) 704 } 705 return k 706 } 707 708 testResumeState("Handshake", false) 709 ticket := getTicket() 710 testResumeState("Resume", true) 711 if !bytes.Equal(ticket, getTicket()) { 712 t.Fatal("first ticket doesn't match ticket after resumption") 713 } 714 715 key1 := randomKey() 716 serverConfig.SetSessionTicketKeys([][32]byte{key1}) 717 718 testResumeState("InvalidSessionTicketKey", false) 719 testResumeState("ResumeAfterInvalidSessionTicketKey", true) 720 721 key2 := randomKey() 722 serverConfig.SetSessionTicketKeys([][32]byte{key2, key1}) 723 ticket = getTicket() 724 testResumeState("KeyChange", true) 725 if bytes.Equal(ticket, getTicket()) { 726 t.Fatal("new ticket wasn't included while resuming") 727 } 728 testResumeState("KeyChangeFinish", true) 729 730 // Reset serverConfig to ensure that calling SetSessionTicketKeys 731 // before the serverConfig is used works. 732 serverConfig = &Config{ 733 CipherSuites: []uint16{TLS_RSA_WITH_RC4_128_SHA, TLS_ECDHE_RSA_WITH_RC4_128_SHA}, 734 Certificates: testConfig.Certificates, 735 } 736 serverConfig.SetSessionTicketKeys([][32]byte{key2}) 737 738 testResumeState("FreshConfig", true) 739 740 clientConfig.CipherSuites = []uint16{TLS_ECDHE_RSA_WITH_RC4_128_SHA} 741 testResumeState("DifferentCipherSuite", false) 742 testResumeState("DifferentCipherSuiteRecovers", true) 743 744 clientConfig.ClientSessionCache = nil 745 testResumeState("WithoutSessionCache", false) 746 } 747 748 func TestLRUClientSessionCache(t *testing.T) { 749 // Initialize cache of capacity 4. 750 cache := NewLRUClientSessionCache(4) 751 cs := make([]ClientSessionState, 6) 752 keys := []string{"0", "1", "2", "3", "4", "5", "6"} 753 754 // Add 4 entries to the cache and look them up. 755 for i := 0; i < 4; i++ { 756 cache.Put(keys[i], &cs[i]) 757 } 758 for i := 0; i < 4; i++ { 759 if s, ok := cache.Get(keys[i]); !ok || s != &cs[i] { 760 t.Fatalf("session cache failed lookup for added key: %s", keys[i]) 761 } 762 } 763 764 // Add 2 more entries to the cache. First 2 should be evicted. 765 for i := 4; i < 6; i++ { 766 cache.Put(keys[i], &cs[i]) 767 } 768 for i := 0; i < 2; i++ { 769 if s, ok := cache.Get(keys[i]); ok || s != nil { 770 t.Fatalf("session cache should have evicted key: %s", keys[i]) 771 } 772 } 773 774 // Touch entry 2. LRU should evict 3 next. 775 cache.Get(keys[2]) 776 cache.Put(keys[0], &cs[0]) 777 if s, ok := cache.Get(keys[3]); ok || s != nil { 778 t.Fatalf("session cache should have evicted key 3") 779 } 780 781 // Update entry 0 in place. 782 cache.Put(keys[0], &cs[3]) 783 if s, ok := cache.Get(keys[0]); !ok || s != &cs[3] { 784 t.Fatalf("session cache failed update for key 0") 785 } 786 787 // Adding a nil entry is valid. 788 cache.Put(keys[0], nil) 789 if s, ok := cache.Get(keys[0]); !ok || s != nil { 790 t.Fatalf("failed to add nil entry to cache") 791 } 792 } 793 794 func TestKeyLog(t *testing.T) { 795 var serverBuf, clientBuf bytes.Buffer 796 797 clientConfig := testConfig.Clone() 798 clientConfig.KeyLogWriter = &clientBuf 799 800 serverConfig := testConfig.Clone() 801 serverConfig.KeyLogWriter = &serverBuf 802 803 c, s := localPipe(t) 804 done := make(chan bool) 805 806 go func() { 807 defer close(done) 808 809 if err := Server(s, serverConfig).Handshake(); err != nil { 810 t.Errorf("server: %s", err) 811 return 812 } 813 s.Close() 814 }() 815 816 if err := Client(c, clientConfig).Handshake(); err != nil { 817 t.Fatalf("client: %s", err) 818 } 819 820 c.Close() 821 <-done 822 823 checkKeylogLine := func(side, loggedLine string) { 824 if len(loggedLine) == 0 { 825 t.Fatalf("%s: no keylog line was produced", side) 826 } 827 const expectedLen = 13 /* "CLIENT_RANDOM" */ + 828 1 /* space */ + 829 32*2 /* hex client nonce */ + 830 1 /* space */ + 831 48*2 /* hex master secret */ + 832 1 /* new line */ 833 if len(loggedLine) != expectedLen { 834 t.Fatalf("%s: keylog line has incorrect length (want %d, got %d): %q", side, expectedLen, len(loggedLine), loggedLine) 835 } 836 if !strings.HasPrefix(loggedLine, "CLIENT_RANDOM "+strings.Repeat("0", 64)+" ") { 837 t.Fatalf("%s: keylog line has incorrect structure or nonce: %q", side, loggedLine) 838 } 839 } 840 841 checkKeylogLine("client", clientBuf.String()) 842 checkKeylogLine("server", serverBuf.String()) 843 } 844 845 func TestHandshakeClientALPNMatch(t *testing.T) { 846 config := testConfig.Clone() 847 config.NextProtos = []string{"proto2", "proto1"} 848 849 test := &clientTest{ 850 name: "ALPN", 851 // Note that this needs OpenSSL 1.0.2 because that is the first 852 // version that supports the -alpn flag. 853 command: []string{"openssl", "s_server", "-alpn", "proto1,proto2"}, 854 config: config, 855 validate: func(state ConnectionState) error { 856 // The server's preferences should override the client. 857 if state.NegotiatedProtocol != "proto1" { 858 return fmt.Errorf("Got protocol %q, wanted proto1", state.NegotiatedProtocol) 859 } 860 return nil 861 }, 862 } 863 runClientTestTLS12(t, test) 864 } 865 866 // sctsBase64 contains data from `openssl s_client -serverinfo 18 -connect ritter.vg:443` 867 const sctsBase64 = "ABIBaQFnAHUApLkJkLQYWBSHuxOizGdwCjw1mAT5G9+443fNDsgN3BAAAAFHl5nuFgAABAMARjBEAiAcS4JdlW5nW9sElUv2zvQyPoZ6ejKrGGB03gjaBZFMLwIgc1Qbbn+hsH0RvObzhS+XZhr3iuQQJY8S9G85D9KeGPAAdgBo9pj4H2SCvjqM7rkoHUz8cVFdZ5PURNEKZ6y7T0/7xAAAAUeX4bVwAAAEAwBHMEUCIDIhFDgG2HIuADBkGuLobU5a4dlCHoJLliWJ1SYT05z6AiEAjxIoZFFPRNWMGGIjskOTMwXzQ1Wh2e7NxXE1kd1J0QsAdgDuS723dc5guuFCaR+r4Z5mow9+X7By2IMAxHuJeqj9ywAAAUhcZIqHAAAEAwBHMEUCICmJ1rBT09LpkbzxtUC+Hi7nXLR0J+2PmwLp+sJMuqK+AiEAr0NkUnEVKVhAkccIFpYDqHOlZaBsuEhWWrYpg2RtKp0=" 868 869 func TestHandshakClientSCTs(t *testing.T) { 870 config := testConfig.Clone() 871 872 scts, err := base64.StdEncoding.DecodeString(sctsBase64) 873 if err != nil { 874 t.Fatal(err) 875 } 876 877 test := &clientTest{ 878 name: "SCT", 879 // Note that this needs OpenSSL 1.0.2 because that is the first 880 // version that supports the -serverinfo flag. 881 command: []string{"openssl", "s_server"}, 882 config: config, 883 extensions: [][]byte{scts}, 884 validate: func(state ConnectionState) error { 885 expectedSCTs := [][]byte{ 886 scts[8:125], 887 scts[127:245], 888 scts[247:], 889 } 890 if n := len(state.SignedCertificateTimestamps); n != len(expectedSCTs) { 891 return fmt.Errorf("Got %d scts, wanted %d", n, len(expectedSCTs)) 892 } 893 for i, expected := range expectedSCTs { 894 if sct := state.SignedCertificateTimestamps[i]; !bytes.Equal(sct, expected) { 895 return fmt.Errorf("SCT #%d contained %x, expected %x", i, sct, expected) 896 } 897 } 898 return nil 899 }, 900 } 901 runClientTestTLS12(t, test) 902 } 903 904 func TestRenegotiationRejected(t *testing.T) { 905 config := testConfig.Clone() 906 test := &clientTest{ 907 name: "RenegotiationRejected", 908 command: []string{"openssl", "s_server", "-state"}, 909 config: config, 910 numRenegotiations: 1, 911 renegotiationExpectedToFail: 1, 912 checkRenegotiationError: func(renegotiationNum int, err error) error { 913 if err == nil { 914 return errors.New("expected error from renegotiation but got nil") 915 } 916 if !strings.Contains(err.Error(), "no renegotiation") { 917 return fmt.Errorf("expected renegotiation to be rejected but got %q", err) 918 } 919 return nil 920 }, 921 } 922 923 runClientTestTLS12(t, test) 924 } 925 926 func TestRenegotiateOnce(t *testing.T) { 927 config := testConfig.Clone() 928 config.Renegotiation = RenegotiateOnceAsClient 929 930 test := &clientTest{ 931 name: "RenegotiateOnce", 932 command: []string{"openssl", "s_server", "-state"}, 933 config: config, 934 numRenegotiations: 1, 935 } 936 937 runClientTestTLS12(t, test) 938 } 939 940 func TestRenegotiateTwice(t *testing.T) { 941 config := testConfig.Clone() 942 config.Renegotiation = RenegotiateFreelyAsClient 943 944 test := &clientTest{ 945 name: "RenegotiateTwice", 946 command: []string{"openssl", "s_server", "-state"}, 947 config: config, 948 numRenegotiations: 2, 949 } 950 951 runClientTestTLS12(t, test) 952 } 953 954 func TestRenegotiateTwiceRejected(t *testing.T) { 955 config := testConfig.Clone() 956 config.Renegotiation = RenegotiateOnceAsClient 957 958 test := &clientTest{ 959 name: "RenegotiateTwiceRejected", 960 command: []string{"openssl", "s_server", "-state"}, 961 config: config, 962 numRenegotiations: 2, 963 renegotiationExpectedToFail: 2, 964 checkRenegotiationError: func(renegotiationNum int, err error) error { 965 if renegotiationNum == 1 { 966 return err 967 } 968 969 if err == nil { 970 return errors.New("expected error from renegotiation but got nil") 971 } 972 if !strings.Contains(err.Error(), "no renegotiation") { 973 return fmt.Errorf("expected renegotiation to be rejected but got %q", err) 974 } 975 return nil 976 }, 977 } 978 979 runClientTestTLS12(t, test) 980 } 981 982 func TestHandshakeClientExportKeyingMaterial(t *testing.T) { 983 test := &clientTest{ 984 name: "ExportKeyingMaterial", 985 command: []string{"openssl", "s_server"}, 986 config: testConfig.Clone(), 987 validate: func(state ConnectionState) error { 988 if km, err := state.ExportKeyingMaterial("test", nil, 42); err != nil { 989 return fmt.Errorf("ExportKeyingMaterial failed: %v", err) 990 } else if len(km) != 42 { 991 return fmt.Errorf("Got %d bytes from ExportKeyingMaterial, wanted %d", len(km), 42) 992 } 993 return nil 994 }, 995 } 996 runClientTestTLS10(t, test) 997 runClientTestTLS12(t, test) 998 } 999 1000 var hostnameInSNITests = []struct { 1001 in, out string 1002 }{ 1003 // Opaque string 1004 {"", ""}, 1005 {"localhost", "localhost"}, 1006 {"foo, bar, baz and qux", "foo, bar, baz and qux"}, 1007 1008 // DNS hostname 1009 {"golang.org", "golang.org"}, 1010 {"golang.org.", "golang.org"}, 1011 1012 // Literal IPv4 address 1013 {"1.2.3.4", ""}, 1014 1015 // Literal IPv6 address 1016 {"::1", ""}, 1017 {"::1%lo0", ""}, // with zone identifier 1018 {"[::1]", ""}, // as per RFC 5952 we allow the [] style as IPv6 literal 1019 {"[::1%lo0]", ""}, 1020 } 1021 1022 func TestHostnameInSNI(t *testing.T) { 1023 for _, tt := range hostnameInSNITests { 1024 c, s := localPipe(t) 1025 1026 go func(host string) { 1027 Client(c, &Config{ServerName: host, InsecureSkipVerify: true}).Handshake() 1028 }(tt.in) 1029 1030 var header [5]byte 1031 if _, err := io.ReadFull(s, header[:]); err != nil { 1032 t.Fatal(err) 1033 } 1034 recordLen := int(header[3])<<8 | int(header[4]) 1035 1036 record := make([]byte, recordLen) 1037 if _, err := io.ReadFull(s, record[:]); err != nil { 1038 t.Fatal(err) 1039 } 1040 1041 c.Close() 1042 s.Close() 1043 1044 var m clientHelloMsg 1045 if !m.unmarshal(record) { 1046 t.Errorf("unmarshaling ClientHello for %q failed", tt.in) 1047 continue 1048 } 1049 if tt.in != tt.out && m.serverName == tt.in { 1050 t.Errorf("prohibited %q found in ClientHello: %x", tt.in, record) 1051 } 1052 if m.serverName != tt.out { 1053 t.Errorf("expected %q not found in ClientHello: %x", tt.out, record) 1054 } 1055 } 1056 } 1057 1058 func TestServerSelectingUnconfiguredCipherSuite(t *testing.T) { 1059 // This checks that the server can't select a cipher suite that the 1060 // client didn't offer. See #13174. 1061 1062 c, s := localPipe(t) 1063 errChan := make(chan error, 1) 1064 1065 go func() { 1066 client := Client(c, &Config{ 1067 ServerName: "foo", 1068 CipherSuites: []uint16{TLS_RSA_WITH_AES_128_GCM_SHA256}, 1069 }) 1070 errChan <- client.Handshake() 1071 }() 1072 1073 var header [5]byte 1074 if _, err := io.ReadFull(s, header[:]); err != nil { 1075 t.Fatal(err) 1076 } 1077 recordLen := int(header[3])<<8 | int(header[4]) 1078 1079 record := make([]byte, recordLen) 1080 if _, err := io.ReadFull(s, record); err != nil { 1081 t.Fatal(err) 1082 } 1083 1084 // Create a ServerHello that selects a different cipher suite than the 1085 // sole one that the client offered. 1086 serverHello := &serverHelloMsg{ 1087 vers: VersionTLS12, 1088 random: make([]byte, 32), 1089 cipherSuite: TLS_RSA_WITH_AES_256_GCM_SHA384, 1090 } 1091 serverHelloBytes := serverHello.marshal() 1092 1093 s.Write([]byte{ 1094 byte(recordTypeHandshake), 1095 byte(VersionTLS12 >> 8), 1096 byte(VersionTLS12 & 0xff), 1097 byte(len(serverHelloBytes) >> 8), 1098 byte(len(serverHelloBytes)), 1099 }) 1100 s.Write(serverHelloBytes) 1101 s.Close() 1102 1103 if err := <-errChan; !strings.Contains(err.Error(), "unconfigured cipher") { 1104 t.Fatalf("Expected error about unconfigured cipher suite but got %q", err) 1105 } 1106 } 1107 1108 func TestVerifyPeerCertificate(t *testing.T) { 1109 issuer, err := x509.ParseCertificate(testRSACertificateIssuer) 1110 if err != nil { 1111 panic(err) 1112 } 1113 1114 rootCAs := x509.NewCertPool() 1115 rootCAs.AddCert(issuer) 1116 1117 now := func() time.Time { return time.Unix(1476984729, 0) } 1118 1119 sentinelErr := errors.New("TestVerifyPeerCertificate") 1120 1121 verifyCallback := func(called *bool, rawCerts [][]byte, validatedChains [][]*x509.Certificate) error { 1122 if l := len(rawCerts); l != 1 { 1123 return fmt.Errorf("got len(rawCerts) = %d, wanted 1", l) 1124 } 1125 if len(validatedChains) == 0 { 1126 return errors.New("got len(validatedChains) = 0, wanted non-zero") 1127 } 1128 *called = true 1129 return nil 1130 } 1131 1132 tests := []struct { 1133 configureServer func(*Config, *bool) 1134 configureClient func(*Config, *bool) 1135 validate func(t *testing.T, testNo int, clientCalled, serverCalled bool, clientErr, serverErr error) 1136 }{ 1137 { 1138 configureServer: func(config *Config, called *bool) { 1139 config.InsecureSkipVerify = false 1140 config.VerifyPeerCertificate = func(rawCerts [][]byte, validatedChains [][]*x509.Certificate) error { 1141 return verifyCallback(called, rawCerts, validatedChains) 1142 } 1143 }, 1144 configureClient: func(config *Config, called *bool) { 1145 config.InsecureSkipVerify = false 1146 config.VerifyPeerCertificate = func(rawCerts [][]byte, validatedChains [][]*x509.Certificate) error { 1147 return verifyCallback(called, rawCerts, validatedChains) 1148 } 1149 }, 1150 validate: func(t *testing.T, testNo int, clientCalled, serverCalled bool, clientErr, serverErr error) { 1151 if clientErr != nil { 1152 t.Errorf("test[%d]: client handshake failed: %v", testNo, clientErr) 1153 } 1154 if serverErr != nil { 1155 t.Errorf("test[%d]: server handshake failed: %v", testNo, serverErr) 1156 } 1157 if !clientCalled { 1158 t.Errorf("test[%d]: client did not call callback", testNo) 1159 } 1160 if !serverCalled { 1161 t.Errorf("test[%d]: server did not call callback", testNo) 1162 } 1163 }, 1164 }, 1165 { 1166 configureServer: func(config *Config, called *bool) { 1167 config.InsecureSkipVerify = false 1168 config.VerifyPeerCertificate = func(rawCerts [][]byte, validatedChains [][]*x509.Certificate) error { 1169 return sentinelErr 1170 } 1171 }, 1172 configureClient: func(config *Config, called *bool) { 1173 config.VerifyPeerCertificate = nil 1174 }, 1175 validate: func(t *testing.T, testNo int, clientCalled, serverCalled bool, clientErr, serverErr error) { 1176 if serverErr != sentinelErr { 1177 t.Errorf("#%d: got server error %v, wanted sentinelErr", testNo, serverErr) 1178 } 1179 }, 1180 }, 1181 { 1182 configureServer: func(config *Config, called *bool) { 1183 config.InsecureSkipVerify = false 1184 }, 1185 configureClient: func(config *Config, called *bool) { 1186 config.VerifyPeerCertificate = func(rawCerts [][]byte, validatedChains [][]*x509.Certificate) error { 1187 return sentinelErr 1188 } 1189 }, 1190 validate: func(t *testing.T, testNo int, clientCalled, serverCalled bool, clientErr, serverErr error) { 1191 if clientErr != sentinelErr { 1192 t.Errorf("#%d: got client error %v, wanted sentinelErr", testNo, clientErr) 1193 } 1194 }, 1195 }, 1196 { 1197 configureServer: func(config *Config, called *bool) { 1198 config.InsecureSkipVerify = false 1199 }, 1200 configureClient: func(config *Config, called *bool) { 1201 config.InsecureSkipVerify = true 1202 config.VerifyPeerCertificate = func(rawCerts [][]byte, validatedChains [][]*x509.Certificate) error { 1203 if l := len(rawCerts); l != 1 { 1204 return fmt.Errorf("got len(rawCerts) = %d, wanted 1", l) 1205 } 1206 // With InsecureSkipVerify set, this 1207 // callback should still be called but 1208 // validatedChains must be empty. 1209 if l := len(validatedChains); l != 0 { 1210 return fmt.Errorf("got len(validatedChains) = %d, wanted zero", l) 1211 } 1212 *called = true 1213 return nil 1214 } 1215 }, 1216 validate: func(t *testing.T, testNo int, clientCalled, serverCalled bool, clientErr, serverErr error) { 1217 if clientErr != nil { 1218 t.Errorf("test[%d]: client handshake failed: %v", testNo, clientErr) 1219 } 1220 if serverErr != nil { 1221 t.Errorf("test[%d]: server handshake failed: %v", testNo, serverErr) 1222 } 1223 if !clientCalled { 1224 t.Errorf("test[%d]: client did not call callback", testNo) 1225 } 1226 }, 1227 }, 1228 } 1229 1230 for i, test := range tests { 1231 c, s := localPipe(t) 1232 done := make(chan error) 1233 1234 var clientCalled, serverCalled bool 1235 1236 go func() { 1237 config := testConfig.Clone() 1238 config.ServerName = "example.golang" 1239 config.ClientAuth = RequireAndVerifyClientCert 1240 config.ClientCAs = rootCAs 1241 config.Time = now 1242 test.configureServer(config, &serverCalled) 1243 1244 err = Server(s, config).Handshake() 1245 s.Close() 1246 done <- err 1247 }() 1248 1249 config := testConfig.Clone() 1250 config.ServerName = "example.golang" 1251 config.RootCAs = rootCAs 1252 config.Time = now 1253 test.configureClient(config, &clientCalled) 1254 clientErr := Client(c, config).Handshake() 1255 c.Close() 1256 serverErr := <-done 1257 1258 test.validate(t, i, clientCalled, serverCalled, clientErr, serverErr) 1259 } 1260 } 1261 1262 // brokenConn wraps a net.Conn and causes all Writes after a certain number to 1263 // fail with brokenConnErr. 1264 type brokenConn struct { 1265 net.Conn 1266 1267 // breakAfter is the number of successful writes that will be allowed 1268 // before all subsequent writes fail. 1269 breakAfter int 1270 1271 // numWrites is the number of writes that have been done. 1272 numWrites int 1273 } 1274 1275 // brokenConnErr is the error that brokenConn returns once exhausted. 1276 var brokenConnErr = errors.New("too many writes to brokenConn") 1277 1278 func (b *brokenConn) Write(data []byte) (int, error) { 1279 if b.numWrites >= b.breakAfter { 1280 return 0, brokenConnErr 1281 } 1282 1283 b.numWrites++ 1284 return b.Conn.Write(data) 1285 } 1286 1287 func TestFailedWrite(t *testing.T) { 1288 // Test that a write error during the handshake is returned. 1289 for _, breakAfter := range []int{0, 1} { 1290 c, s := localPipe(t) 1291 done := make(chan bool) 1292 1293 go func() { 1294 Server(s, testConfig).Handshake() 1295 s.Close() 1296 done <- true 1297 }() 1298 1299 brokenC := &brokenConn{Conn: c, breakAfter: breakAfter} 1300 err := Client(brokenC, testConfig).Handshake() 1301 if err != brokenConnErr { 1302 t.Errorf("#%d: expected error from brokenConn but got %q", breakAfter, err) 1303 } 1304 brokenC.Close() 1305 1306 <-done 1307 } 1308 } 1309 1310 // writeCountingConn wraps a net.Conn and counts the number of Write calls. 1311 type writeCountingConn struct { 1312 net.Conn 1313 1314 // numWrites is the number of writes that have been done. 1315 numWrites int 1316 } 1317 1318 func (wcc *writeCountingConn) Write(data []byte) (int, error) { 1319 wcc.numWrites++ 1320 return wcc.Conn.Write(data) 1321 } 1322 1323 func TestBuffering(t *testing.T) { 1324 c, s := localPipe(t) 1325 done := make(chan bool) 1326 1327 clientWCC := &writeCountingConn{Conn: c} 1328 serverWCC := &writeCountingConn{Conn: s} 1329 1330 go func() { 1331 Server(serverWCC, testConfig).Handshake() 1332 serverWCC.Close() 1333 done <- true 1334 }() 1335 1336 err := Client(clientWCC, testConfig).Handshake() 1337 if err != nil { 1338 t.Fatal(err) 1339 } 1340 clientWCC.Close() 1341 <-done 1342 1343 if n := clientWCC.numWrites; n != 2 { 1344 t.Errorf("expected client handshake to complete with only two writes, but saw %d", n) 1345 } 1346 1347 if n := serverWCC.numWrites; n != 2 { 1348 t.Errorf("expected server handshake to complete with only two writes, but saw %d", n) 1349 } 1350 } 1351 1352 func TestAlertFlushing(t *testing.T) { 1353 c, s := localPipe(t) 1354 done := make(chan bool) 1355 1356 clientWCC := &writeCountingConn{Conn: c} 1357 serverWCC := &writeCountingConn{Conn: s} 1358 1359 serverConfig := testConfig.Clone() 1360 1361 // Cause a signature-time error 1362 brokenKey := rsa.PrivateKey{PublicKey: testRSAPrivateKey.PublicKey} 1363 brokenKey.D = big.NewInt(42) 1364 serverConfig.Certificates = []Certificate{{ 1365 Certificate: [][]byte{testRSACertificate}, 1366 PrivateKey: &brokenKey, 1367 }} 1368 1369 go func() { 1370 Server(serverWCC, serverConfig).Handshake() 1371 serverWCC.Close() 1372 done <- true 1373 }() 1374 1375 err := Client(clientWCC, testConfig).Handshake() 1376 if err == nil { 1377 t.Fatal("client unexpectedly returned no error") 1378 } 1379 1380 const expectedError = "remote error: tls: handshake failure" 1381 if e := err.Error(); !strings.Contains(e, expectedError) { 1382 t.Fatalf("expected to find %q in error but error was %q", expectedError, e) 1383 } 1384 clientWCC.Close() 1385 <-done 1386 1387 if n := clientWCC.numWrites; n != 1 { 1388 t.Errorf("expected client handshake to complete with one write, but saw %d", n) 1389 } 1390 1391 if n := serverWCC.numWrites; n != 1 { 1392 t.Errorf("expected server handshake to complete with one write, but saw %d", n) 1393 } 1394 } 1395 1396 func TestHandshakeRace(t *testing.T) { 1397 t.Parallel() 1398 // This test races a Read and Write to try and complete a handshake in 1399 // order to provide some evidence that there are no races or deadlocks 1400 // in the handshake locking. 1401 for i := 0; i < 32; i++ { 1402 c, s := localPipe(t) 1403 1404 go func() { 1405 server := Server(s, testConfig) 1406 if err := server.Handshake(); err != nil { 1407 panic(err) 1408 } 1409 1410 var request [1]byte 1411 if n, err := server.Read(request[:]); err != nil || n != 1 { 1412 panic(err) 1413 } 1414 1415 server.Write(request[:]) 1416 server.Close() 1417 }() 1418 1419 startWrite := make(chan struct{}) 1420 startRead := make(chan struct{}) 1421 readDone := make(chan struct{}) 1422 1423 client := Client(c, testConfig) 1424 go func() { 1425 <-startWrite 1426 var request [1]byte 1427 client.Write(request[:]) 1428 }() 1429 1430 go func() { 1431 <-startRead 1432 var reply [1]byte 1433 if _, err := io.ReadFull(client, reply[:]); err != nil { 1434 panic(err) 1435 } 1436 c.Close() 1437 readDone <- struct{}{} 1438 }() 1439 1440 if i&1 == 1 { 1441 startWrite <- struct{}{} 1442 startRead <- struct{}{} 1443 } else { 1444 startRead <- struct{}{} 1445 startWrite <- struct{}{} 1446 } 1447 <-readDone 1448 } 1449 } 1450 1451 func TestTLS11SignatureSchemes(t *testing.T) { 1452 expected := tls11SignatureSchemesNumECDSA + tls11SignatureSchemesNumRSA 1453 if expected != len(tls11SignatureSchemes) { 1454 t.Errorf("expected to find %d TLS 1.1 signature schemes, but found %d", expected, len(tls11SignatureSchemes)) 1455 } 1456 } 1457 1458 var getClientCertificateTests = []struct { 1459 setup func(*Config, *Config) 1460 expectedClientError string 1461 verify func(*testing.T, int, *ConnectionState) 1462 }{ 1463 { 1464 func(clientConfig, serverConfig *Config) { 1465 // Returning a Certificate with no certificate data 1466 // should result in an empty message being sent to the 1467 // server. 1468 serverConfig.ClientCAs = nil 1469 clientConfig.GetClientCertificate = func(cri *CertificateRequestInfo) (*Certificate, error) { 1470 if len(cri.SignatureSchemes) == 0 { 1471 panic("empty SignatureSchemes") 1472 } 1473 if len(cri.AcceptableCAs) != 0 { 1474 panic("AcceptableCAs should have been empty") 1475 } 1476 return new(Certificate), nil 1477 } 1478 }, 1479 "", 1480 func(t *testing.T, testNum int, cs *ConnectionState) { 1481 if l := len(cs.PeerCertificates); l != 0 { 1482 t.Errorf("#%d: expected no certificates but got %d", testNum, l) 1483 } 1484 }, 1485 }, 1486 { 1487 func(clientConfig, serverConfig *Config) { 1488 // With TLS 1.1, the SignatureSchemes should be 1489 // synthesised from the supported certificate types. 1490 clientConfig.MaxVersion = VersionTLS11 1491 clientConfig.GetClientCertificate = func(cri *CertificateRequestInfo) (*Certificate, error) { 1492 if len(cri.SignatureSchemes) == 0 { 1493 panic("empty SignatureSchemes") 1494 } 1495 return new(Certificate), nil 1496 } 1497 }, 1498 "", 1499 func(t *testing.T, testNum int, cs *ConnectionState) { 1500 if l := len(cs.PeerCertificates); l != 0 { 1501 t.Errorf("#%d: expected no certificates but got %d", testNum, l) 1502 } 1503 }, 1504 }, 1505 { 1506 func(clientConfig, serverConfig *Config) { 1507 // Returning an error should abort the handshake with 1508 // that error. 1509 clientConfig.GetClientCertificate = func(cri *CertificateRequestInfo) (*Certificate, error) { 1510 return nil, errors.New("GetClientCertificate") 1511 } 1512 }, 1513 "GetClientCertificate", 1514 func(t *testing.T, testNum int, cs *ConnectionState) { 1515 }, 1516 }, 1517 { 1518 func(clientConfig, serverConfig *Config) { 1519 clientConfig.GetClientCertificate = func(cri *CertificateRequestInfo) (*Certificate, error) { 1520 if len(cri.AcceptableCAs) == 0 { 1521 panic("empty AcceptableCAs") 1522 } 1523 cert := &Certificate{ 1524 Certificate: [][]byte{testRSACertificate}, 1525 PrivateKey: testRSAPrivateKey, 1526 } 1527 return cert, nil 1528 } 1529 }, 1530 "", 1531 func(t *testing.T, testNum int, cs *ConnectionState) { 1532 if len(cs.VerifiedChains) == 0 { 1533 t.Errorf("#%d: expected some verified chains, but found none", testNum) 1534 } 1535 }, 1536 }, 1537 } 1538 1539 func TestGetClientCertificate(t *testing.T) { 1540 issuer, err := x509.ParseCertificate(testRSACertificateIssuer) 1541 if err != nil { 1542 panic(err) 1543 } 1544 1545 for i, test := range getClientCertificateTests { 1546 serverConfig := testConfig.Clone() 1547 serverConfig.ClientAuth = VerifyClientCertIfGiven 1548 serverConfig.RootCAs = x509.NewCertPool() 1549 serverConfig.RootCAs.AddCert(issuer) 1550 serverConfig.ClientCAs = serverConfig.RootCAs 1551 serverConfig.Time = func() time.Time { return time.Unix(1476984729, 0) } 1552 1553 clientConfig := testConfig.Clone() 1554 1555 test.setup(clientConfig, serverConfig) 1556 1557 type serverResult struct { 1558 cs ConnectionState 1559 err error 1560 } 1561 1562 c, s := localPipe(t) 1563 done := make(chan serverResult) 1564 1565 go func() { 1566 defer s.Close() 1567 server := Server(s, serverConfig) 1568 err := server.Handshake() 1569 1570 var cs ConnectionState 1571 if err == nil { 1572 cs = server.ConnectionState() 1573 } 1574 done <- serverResult{cs, err} 1575 }() 1576 1577 clientErr := Client(c, clientConfig).Handshake() 1578 c.Close() 1579 1580 result := <-done 1581 1582 if clientErr != nil { 1583 if len(test.expectedClientError) == 0 { 1584 t.Errorf("#%d: client error: %v", i, clientErr) 1585 } else if got := clientErr.Error(); got != test.expectedClientError { 1586 t.Errorf("#%d: expected client error %q, but got %q", i, test.expectedClientError, got) 1587 } else { 1588 test.verify(t, i, &result.cs) 1589 } 1590 } else if len(test.expectedClientError) > 0 { 1591 t.Errorf("#%d: expected client error %q, but got no error", i, test.expectedClientError) 1592 } else if err := result.err; err != nil { 1593 t.Errorf("#%d: server error: %v", i, err) 1594 } else { 1595 test.verify(t, i, &result.cs) 1596 } 1597 } 1598 } 1599 1600 func TestRSAPSSKeyError(t *testing.T) { 1601 // crypto/tls does not support the rsa_pss_pss_xxx SignatureSchemes. If support for 1602 // public keys with OID RSASSA-PSS is added to crypto/x509, they will be misused with 1603 // the rsa_pss_rsae_xxx SignatureSchemes. Assert that RSASSA-PSS certificates don't 1604 // parse, or that they don't carry *rsa.PublicKey keys. 1605 b, _ := pem.Decode([]byte(` 1606 -----BEGIN CERTIFICATE----- 1607 MIIDZTCCAhygAwIBAgIUCF2x0FyTgZG0CC9QTDjGWkB5vgEwPgYJKoZIhvcNAQEK 1608 MDGgDTALBglghkgBZQMEAgGhGjAYBgkqhkiG9w0BAQgwCwYJYIZIAWUDBAIBogQC 1609 AgDeMBIxEDAOBgNVBAMMB1JTQS1QU1MwHhcNMTgwNjI3MjI0NDM2WhcNMTgwNzI3 1610 MjI0NDM2WjASMRAwDgYDVQQDDAdSU0EtUFNTMIIBIDALBgkqhkiG9w0BAQoDggEP 1611 ADCCAQoCggEBANxDm0f76JdI06YzsjB3AmmjIYkwUEGxePlafmIASFjDZl/elD0Z 1612 /a7xLX468b0qGxLS5al7XCcEprSdsDR6DF5L520+pCbpfLyPOjuOvGmk9KzVX4x5 1613 b05YXYuXdsQ0Kjxcx2i3jjCday6scIhMJVgBZxTEyMj1thPQM14SHzKCd/m6HmCL 1614 QmswpH2yMAAcBRWzRpp/vdH5DeOJEB3aelq7094no731mrLUCHRiZ1htq8BDB3ou 1615 czwqgwspbqZ4dnMXl2MvfySQ5wJUxQwILbiuAKO2lVVPUbFXHE9pgtznNoPvKwQT 1616 JNcX8ee8WIZc2SEGzofjk3NpjR+2ADB2u3sCAwEAAaNTMFEwHQYDVR0OBBYEFNEz 1617 AdyJ2f+fU+vSCS6QzohnOnprMB8GA1UdIwQYMBaAFNEzAdyJ2f+fU+vSCS6Qzohn 1618 OnprMA8GA1UdEwEB/wQFMAMBAf8wPgYJKoZIhvcNAQEKMDGgDTALBglghkgBZQME 1619 AgGhGjAYBgkqhkiG9w0BAQgwCwYJYIZIAWUDBAIBogQCAgDeA4IBAQCjEdrR5aab 1620 sZmCwrMeKidXgfkmWvfuLDE+TCbaqDZp7BMWcMQXT9O0UoUT5kqgKj2ARm2pEW0Z 1621 H3Z1vj3bbds72qcDIJXp+l0fekyLGeCrX/CbgnMZXEP7+/+P416p34ChR1Wz4dU1 1622 KD3gdsUuTKKeMUog3plxlxQDhRQmiL25ygH1LmjLd6dtIt0GVRGr8lj3euVeprqZ 1623 bZ3Uq5eLfsn8oPgfC57gpO6yiN+UURRTlK3bgYvLh4VWB3XXk9UaQZ7Mq1tpXjoD 1624 HYFybkWzibkZp4WRo+Fa28rirH+/wHt0vfeN7UCceURZEx4JaxIIfe4ku7uDRhJi 1625 RwBA9Xk1KBNF 1626 -----END CERTIFICATE-----`)) 1627 if b == nil { 1628 t.Fatal("Failed to decode certificate") 1629 } 1630 cert, err := x509.ParseCertificate(b.Bytes) 1631 if err != nil { 1632 return 1633 } 1634 if _, ok := cert.PublicKey.(*rsa.PublicKey); ok { 1635 t.Error("A RSA-PSS certificate was parsed like a PKCS1 one, and it will be mistakenly used with rsa_pss_rsae_xxx signature algorithms") 1636 } 1637 } 1638 1639 func TestCloseClientConnectionOnIdleServer(t *testing.T) { 1640 clientConn, serverConn := localPipe(t) 1641 client := Client(clientConn, testConfig.Clone()) 1642 go func() { 1643 var b [1]byte 1644 serverConn.Read(b[:]) 1645 client.Close() 1646 }() 1647 client.SetWriteDeadline(time.Now().Add(time.Second)) 1648 err := client.Handshake() 1649 if err != nil { 1650 if err, ok := err.(net.Error); ok && err.Timeout() { 1651 t.Errorf("Expected a closed network connection error but got '%s'", err.Error()) 1652 } 1653 } else { 1654 t.Errorf("Error expected, but no error returned") 1655 } 1656 }