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