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