github.com/twelsh-aw/go/src@v0.0.0-20230516233729-a56fe86a7c81/crypto/tls/handshake_client_test.go (about) 1 // Copyright 2010 The Go Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 package tls 6 7 import ( 8 "bytes" 9 "context" 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 "reflect" 24 "runtime" 25 "strconv" 26 "strings" 27 "testing" 28 "time" 29 ) 30 31 // Note: see comment in handshake_test.go for details of how the reference 32 // tests work. 33 34 // opensslInputEvent enumerates possible inputs that can be sent to an `openssl 35 // s_client` process. 36 type opensslInputEvent int 37 38 const ( 39 // opensslRenegotiate causes OpenSSL to request a renegotiation of the 40 // connection. 41 opensslRenegotiate opensslInputEvent = iota 42 43 // opensslSendBanner causes OpenSSL to send the contents of 44 // opensslSentinel on the connection. 45 opensslSendSentinel 46 47 // opensslKeyUpdate causes OpenSSL to send a key update message to the 48 // client and request one back. 49 opensslKeyUpdate 50 ) 51 52 const opensslSentinel = "SENTINEL\n" 53 54 type opensslInput chan opensslInputEvent 55 56 func (i opensslInput) Read(buf []byte) (n int, err error) { 57 for event := range i { 58 switch event { 59 case opensslRenegotiate: 60 return copy(buf, []byte("R\n")), nil 61 case opensslKeyUpdate: 62 return copy(buf, []byte("K\n")), nil 63 case opensslSendSentinel: 64 return copy(buf, []byte(opensslSentinel)), nil 65 default: 66 panic("unknown event") 67 } 68 } 69 70 return 0, io.EOF 71 } 72 73 // opensslOutputSink is an io.Writer that receives the stdout and stderr from an 74 // `openssl` process and sends a value to handshakeComplete or readKeyUpdate 75 // when certain messages are seen. 76 type opensslOutputSink struct { 77 handshakeComplete chan struct{} 78 readKeyUpdate chan struct{} 79 all []byte 80 line []byte 81 } 82 83 func newOpensslOutputSink() *opensslOutputSink { 84 return &opensslOutputSink{make(chan struct{}), make(chan struct{}), nil, nil} 85 } 86 87 // opensslEndOfHandshake is a message that the “openssl s_server” tool will 88 // print when a handshake completes if run with “-state”. 89 const opensslEndOfHandshake = "SSL_accept:SSLv3/TLS write finished" 90 91 // opensslReadKeyUpdate is a message that the “openssl s_server” tool will 92 // print when a KeyUpdate message is received if run with “-state”. 93 const opensslReadKeyUpdate = "SSL_accept:TLSv1.3 read client key update" 94 95 func (o *opensslOutputSink) Write(data []byte) (n int, err error) { 96 o.line = append(o.line, data...) 97 o.all = append(o.all, data...) 98 99 for { 100 line, next, ok := bytes.Cut(o.line, []byte("\n")) 101 if !ok { 102 break 103 } 104 105 if bytes.Equal([]byte(opensslEndOfHandshake), line) { 106 o.handshakeComplete <- struct{}{} 107 } 108 if bytes.Equal([]byte(opensslReadKeyUpdate), line) { 109 o.readKeyUpdate <- struct{}{} 110 } 111 o.line = next 112 } 113 114 return len(data), nil 115 } 116 117 func (o *opensslOutputSink) String() string { 118 return string(o.all) 119 } 120 121 // clientTest represents a test of the TLS client handshake against a reference 122 // implementation. 123 type clientTest struct { 124 // name is a freeform string identifying the test and the file in which 125 // the expected results will be stored. 126 name string 127 // args, if not empty, contains a series of arguments for the 128 // command to run for the reference server. 129 args []string 130 // config, if not nil, contains a custom Config to use for this test. 131 config *Config 132 // cert, if not empty, contains a DER-encoded certificate for the 133 // reference server. 134 cert []byte 135 // key, if not nil, contains either a *rsa.PrivateKey, ed25519.PrivateKey or 136 // *ecdsa.PrivateKey which is the private key for the reference server. 137 key any 138 // extensions, if not nil, contains a list of extension data to be returned 139 // from the ServerHello. The data should be in standard TLS format with 140 // a 2-byte uint16 type, 2-byte data length, followed by the extension data. 141 extensions [][]byte 142 // validate, if not nil, is a function that will be called with the 143 // ConnectionState of the resulting connection. It returns a non-nil 144 // error if the ConnectionState is unacceptable. 145 validate func(ConnectionState) error 146 // numRenegotiations is the number of times that the connection will be 147 // renegotiated. 148 numRenegotiations int 149 // renegotiationExpectedToFail, if not zero, is the number of the 150 // renegotiation attempt that is expected to fail. 151 renegotiationExpectedToFail int 152 // checkRenegotiationError, if not nil, is called with any error 153 // arising from renegotiation. It can map expected errors to nil to 154 // ignore them. 155 checkRenegotiationError func(renegotiationNum int, err error) error 156 // sendKeyUpdate will cause the server to send a KeyUpdate message. 157 sendKeyUpdate bool 158 } 159 160 var serverCommand = []string{"openssl", "s_server", "-no_ticket", "-num_tickets", "0"} 161 162 // connFromCommand starts the reference server process, connects to it and 163 // returns a recordingConn for the connection. The stdin return value is an 164 // opensslInput for the stdin of the child process. It must be closed before 165 // Waiting for child. 166 func (test *clientTest) connFromCommand() (conn *recordingConn, child *exec.Cmd, stdin opensslInput, stdout *opensslOutputSink, err error) { 167 cert := testRSACertificate 168 if len(test.cert) > 0 { 169 cert = test.cert 170 } 171 certPath := tempFile(string(cert)) 172 defer os.Remove(certPath) 173 174 var key any = testRSAPrivateKey 175 if test.key != nil { 176 key = test.key 177 } 178 derBytes, err := x509.MarshalPKCS8PrivateKey(key) 179 if err != nil { 180 panic(err) 181 } 182 183 var pemOut bytes.Buffer 184 pem.Encode(&pemOut, &pem.Block{Type: "PRIVATE KEY", Bytes: derBytes}) 185 186 keyPath := tempFile(pemOut.String()) 187 defer os.Remove(keyPath) 188 189 var command []string 190 command = append(command, serverCommand...) 191 command = append(command, test.args...) 192 command = append(command, "-cert", certPath, "-certform", "DER", "-key", keyPath) 193 // serverPort contains the port that OpenSSL will listen on. OpenSSL 194 // can't take "0" as an argument here so we have to pick a number and 195 // hope that it's not in use on the machine. Since this only occurs 196 // when -update is given and thus when there's a human watching the 197 // test, this isn't too bad. 198 const serverPort = 24323 199 command = append(command, "-accept", strconv.Itoa(serverPort)) 200 201 if len(test.extensions) > 0 { 202 var serverInfo bytes.Buffer 203 for _, ext := range test.extensions { 204 pem.Encode(&serverInfo, &pem.Block{ 205 Type: fmt.Sprintf("SERVERINFO FOR EXTENSION %d", binary.BigEndian.Uint16(ext)), 206 Bytes: ext, 207 }) 208 } 209 serverInfoPath := tempFile(serverInfo.String()) 210 defer os.Remove(serverInfoPath) 211 command = append(command, "-serverinfo", serverInfoPath) 212 } 213 214 if test.numRenegotiations > 0 || test.sendKeyUpdate { 215 found := false 216 for _, flag := range command[1:] { 217 if flag == "-state" { 218 found = true 219 break 220 } 221 } 222 223 if !found { 224 panic("-state flag missing to OpenSSL, you need this if testing renegotiation or KeyUpdate") 225 } 226 } 227 228 cmd := exec.Command(command[0], command[1:]...) 229 stdin = opensslInput(make(chan opensslInputEvent)) 230 cmd.Stdin = stdin 231 out := newOpensslOutputSink() 232 cmd.Stdout = out 233 cmd.Stderr = out 234 if err := cmd.Start(); err != nil { 235 return nil, nil, nil, nil, err 236 } 237 238 // OpenSSL does print an "ACCEPT" banner, but it does so *before* 239 // opening the listening socket, so we can't use that to wait until it 240 // has started listening. Thus we are forced to poll until we get a 241 // connection. 242 var tcpConn net.Conn 243 for i := uint(0); i < 5; i++ { 244 tcpConn, err = net.DialTCP("tcp", nil, &net.TCPAddr{ 245 IP: net.IPv4(127, 0, 0, 1), 246 Port: serverPort, 247 }) 248 if err == nil { 249 break 250 } 251 time.Sleep((1 << i) * 5 * time.Millisecond) 252 } 253 if err != nil { 254 close(stdin) 255 cmd.Process.Kill() 256 err = fmt.Errorf("error connecting to the OpenSSL server: %v (%v)\n\n%s", err, cmd.Wait(), out) 257 return nil, nil, nil, nil, err 258 } 259 260 record := &recordingConn{ 261 Conn: tcpConn, 262 } 263 264 return record, cmd, stdin, out, nil 265 } 266 267 func (test *clientTest) dataPath() string { 268 return filepath.Join("testdata", "Client-"+test.name) 269 } 270 271 func (test *clientTest) loadData() (flows [][]byte, err error) { 272 in, err := os.Open(test.dataPath()) 273 if err != nil { 274 return nil, err 275 } 276 defer in.Close() 277 return parseTestData(in) 278 } 279 280 func (test *clientTest) run(t *testing.T, write bool) { 281 var clientConn, serverConn net.Conn 282 var recordingConn *recordingConn 283 var childProcess *exec.Cmd 284 var stdin opensslInput 285 var stdout *opensslOutputSink 286 287 if write { 288 var err error 289 recordingConn, childProcess, stdin, stdout, err = test.connFromCommand() 290 if err != nil { 291 t.Fatalf("Failed to start subcommand: %s", err) 292 } 293 clientConn = recordingConn 294 defer func() { 295 if t.Failed() { 296 t.Logf("OpenSSL output:\n\n%s", stdout.all) 297 } 298 }() 299 } else { 300 clientConn, serverConn = localPipe(t) 301 } 302 303 doneChan := make(chan bool) 304 defer func() { 305 clientConn.Close() 306 <-doneChan 307 }() 308 go func() { 309 defer close(doneChan) 310 311 config := test.config 312 if config == nil { 313 config = testConfig 314 } 315 client := Client(clientConn, config) 316 defer client.Close() 317 318 if _, err := client.Write([]byte("hello\n")); err != nil { 319 t.Errorf("Client.Write failed: %s", err) 320 return 321 } 322 323 for i := 1; i <= test.numRenegotiations; i++ { 324 // The initial handshake will generate a 325 // handshakeComplete signal which needs to be quashed. 326 if i == 1 && write { 327 <-stdout.handshakeComplete 328 } 329 330 // OpenSSL will try to interleave application data and 331 // a renegotiation if we send both concurrently. 332 // Therefore: ask OpensSSL to start a renegotiation, run 333 // a goroutine to call client.Read and thus process the 334 // renegotiation request, watch for OpenSSL's stdout to 335 // indicate that the handshake is complete and, 336 // finally, have OpenSSL write something to cause 337 // client.Read to complete. 338 if write { 339 stdin <- opensslRenegotiate 340 } 341 342 signalChan := make(chan struct{}) 343 344 go func() { 345 defer close(signalChan) 346 347 buf := make([]byte, 256) 348 n, err := client.Read(buf) 349 350 if test.checkRenegotiationError != nil { 351 newErr := test.checkRenegotiationError(i, err) 352 if err != nil && newErr == nil { 353 return 354 } 355 err = newErr 356 } 357 358 if err != nil { 359 t.Errorf("Client.Read failed after renegotiation #%d: %s", i, err) 360 return 361 } 362 363 buf = buf[:n] 364 if !bytes.Equal([]byte(opensslSentinel), buf) { 365 t.Errorf("Client.Read returned %q, but wanted %q", string(buf), opensslSentinel) 366 } 367 368 if expected := i + 1; client.handshakes != expected { 369 t.Errorf("client should have recorded %d handshakes, but believes that %d have occurred", expected, client.handshakes) 370 } 371 }() 372 373 if write && test.renegotiationExpectedToFail != i { 374 <-stdout.handshakeComplete 375 stdin <- opensslSendSentinel 376 } 377 <-signalChan 378 } 379 380 if test.sendKeyUpdate { 381 if write { 382 <-stdout.handshakeComplete 383 stdin <- opensslKeyUpdate 384 } 385 386 doneRead := make(chan struct{}) 387 388 go func() { 389 defer close(doneRead) 390 391 buf := make([]byte, 256) 392 n, err := client.Read(buf) 393 394 if err != nil { 395 t.Errorf("Client.Read failed after KeyUpdate: %s", err) 396 return 397 } 398 399 buf = buf[:n] 400 if !bytes.Equal([]byte(opensslSentinel), buf) { 401 t.Errorf("Client.Read returned %q, but wanted %q", string(buf), opensslSentinel) 402 } 403 }() 404 405 if write { 406 // There's no real reason to wait for the client KeyUpdate to 407 // send data with the new server keys, except that s_server 408 // drops writes if they are sent at the wrong time. 409 <-stdout.readKeyUpdate 410 stdin <- opensslSendSentinel 411 } 412 <-doneRead 413 414 if _, err := client.Write([]byte("hello again\n")); err != nil { 415 t.Errorf("Client.Write failed: %s", err) 416 return 417 } 418 } 419 420 if test.validate != nil { 421 if err := test.validate(client.ConnectionState()); err != nil { 422 t.Errorf("validate callback returned error: %s", err) 423 } 424 } 425 426 // If the server sent us an alert after our last flight, give it a 427 // chance to arrive. 428 if write && test.renegotiationExpectedToFail == 0 { 429 if err := peekError(client); err != nil { 430 t.Errorf("final Read returned an error: %s", err) 431 } 432 } 433 }() 434 435 if !write { 436 flows, err := test.loadData() 437 if err != nil { 438 t.Fatalf("%s: failed to load data from %s: %v", test.name, test.dataPath(), err) 439 } 440 for i, b := range flows { 441 if i%2 == 1 { 442 if *fast { 443 serverConn.SetWriteDeadline(time.Now().Add(1 * time.Second)) 444 } else { 445 serverConn.SetWriteDeadline(time.Now().Add(1 * time.Minute)) 446 } 447 serverConn.Write(b) 448 continue 449 } 450 bb := make([]byte, len(b)) 451 if *fast { 452 serverConn.SetReadDeadline(time.Now().Add(1 * time.Second)) 453 } else { 454 serverConn.SetReadDeadline(time.Now().Add(1 * time.Minute)) 455 } 456 _, err := io.ReadFull(serverConn, bb) 457 if err != nil { 458 t.Fatalf("%s, flow %d: %s", test.name, i+1, err) 459 } 460 if !bytes.Equal(b, bb) { 461 t.Fatalf("%s, flow %d: mismatch on read: got:%x want:%x", test.name, i+1, bb, b) 462 } 463 } 464 } 465 466 <-doneChan 467 if !write { 468 serverConn.Close() 469 } 470 471 if write { 472 path := test.dataPath() 473 out, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644) 474 if err != nil { 475 t.Fatalf("Failed to create output file: %s", err) 476 } 477 defer out.Close() 478 recordingConn.Close() 479 close(stdin) 480 childProcess.Process.Kill() 481 childProcess.Wait() 482 if len(recordingConn.flows) < 3 { 483 t.Fatalf("Client connection didn't work") 484 } 485 recordingConn.WriteTo(out) 486 t.Logf("Wrote %s\n", path) 487 } 488 } 489 490 // peekError does a read with a short timeout to check if the next read would 491 // cause an error, for example if there is an alert waiting on the wire. 492 func peekError(conn net.Conn) error { 493 conn.SetReadDeadline(time.Now().Add(100 * time.Millisecond)) 494 if n, err := conn.Read(make([]byte, 1)); n != 0 { 495 return errors.New("unexpectedly read data") 496 } else if err != nil { 497 if netErr, ok := err.(net.Error); !ok || !netErr.Timeout() { 498 return err 499 } 500 } 501 return nil 502 } 503 504 func runClientTestForVersion(t *testing.T, template *clientTest, version, option string) { 505 // Make a deep copy of the template before going parallel. 506 test := *template 507 if template.config != nil { 508 test.config = template.config.Clone() 509 } 510 test.name = version + "-" + test.name 511 test.args = append([]string{option}, test.args...) 512 513 runTestAndUpdateIfNeeded(t, version, test.run, false) 514 } 515 516 func runClientTestTLS10(t *testing.T, template *clientTest) { 517 runClientTestForVersion(t, template, "TLSv10", "-tls1") 518 } 519 520 func runClientTestTLS11(t *testing.T, template *clientTest) { 521 runClientTestForVersion(t, template, "TLSv11", "-tls1_1") 522 } 523 524 func runClientTestTLS12(t *testing.T, template *clientTest) { 525 runClientTestForVersion(t, template, "TLSv12", "-tls1_2") 526 } 527 528 func runClientTestTLS13(t *testing.T, template *clientTest) { 529 runClientTestForVersion(t, template, "TLSv13", "-tls1_3") 530 } 531 532 func TestHandshakeClientRSARC4(t *testing.T) { 533 test := &clientTest{ 534 name: "RSA-RC4", 535 args: []string{"-cipher", "RC4-SHA"}, 536 } 537 runClientTestTLS10(t, test) 538 runClientTestTLS11(t, test) 539 runClientTestTLS12(t, test) 540 } 541 542 func TestHandshakeClientRSAAES128GCM(t *testing.T) { 543 test := &clientTest{ 544 name: "AES128-GCM-SHA256", 545 args: []string{"-cipher", "AES128-GCM-SHA256"}, 546 } 547 runClientTestTLS12(t, test) 548 } 549 550 func TestHandshakeClientRSAAES256GCM(t *testing.T) { 551 test := &clientTest{ 552 name: "AES256-GCM-SHA384", 553 args: []string{"-cipher", "AES256-GCM-SHA384"}, 554 } 555 runClientTestTLS12(t, test) 556 } 557 558 func TestHandshakeClientECDHERSAAES(t *testing.T) { 559 test := &clientTest{ 560 name: "ECDHE-RSA-AES", 561 args: []string{"-cipher", "ECDHE-RSA-AES128-SHA"}, 562 } 563 runClientTestTLS10(t, test) 564 runClientTestTLS11(t, test) 565 runClientTestTLS12(t, test) 566 } 567 568 func TestHandshakeClientECDHEECDSAAES(t *testing.T) { 569 test := &clientTest{ 570 name: "ECDHE-ECDSA-AES", 571 args: []string{"-cipher", "ECDHE-ECDSA-AES128-SHA"}, 572 cert: testECDSACertificate, 573 key: testECDSAPrivateKey, 574 } 575 runClientTestTLS10(t, test) 576 runClientTestTLS11(t, test) 577 runClientTestTLS12(t, test) 578 } 579 580 func TestHandshakeClientECDHEECDSAAESGCM(t *testing.T) { 581 test := &clientTest{ 582 name: "ECDHE-ECDSA-AES-GCM", 583 args: []string{"-cipher", "ECDHE-ECDSA-AES128-GCM-SHA256"}, 584 cert: testECDSACertificate, 585 key: testECDSAPrivateKey, 586 } 587 runClientTestTLS12(t, test) 588 } 589 590 func TestHandshakeClientAES256GCMSHA384(t *testing.T) { 591 test := &clientTest{ 592 name: "ECDHE-ECDSA-AES256-GCM-SHA384", 593 args: []string{"-cipher", "ECDHE-ECDSA-AES256-GCM-SHA384"}, 594 cert: testECDSACertificate, 595 key: testECDSAPrivateKey, 596 } 597 runClientTestTLS12(t, test) 598 } 599 600 func TestHandshakeClientAES128CBCSHA256(t *testing.T) { 601 test := &clientTest{ 602 name: "AES128-SHA256", 603 args: []string{"-cipher", "AES128-SHA256"}, 604 } 605 runClientTestTLS12(t, test) 606 } 607 608 func TestHandshakeClientECDHERSAAES128CBCSHA256(t *testing.T) { 609 test := &clientTest{ 610 name: "ECDHE-RSA-AES128-SHA256", 611 args: []string{"-cipher", "ECDHE-RSA-AES128-SHA256"}, 612 } 613 runClientTestTLS12(t, test) 614 } 615 616 func TestHandshakeClientECDHEECDSAAES128CBCSHA256(t *testing.T) { 617 test := &clientTest{ 618 name: "ECDHE-ECDSA-AES128-SHA256", 619 args: []string{"-cipher", "ECDHE-ECDSA-AES128-SHA256"}, 620 cert: testECDSACertificate, 621 key: testECDSAPrivateKey, 622 } 623 runClientTestTLS12(t, test) 624 } 625 626 func TestHandshakeClientX25519(t *testing.T) { 627 config := testConfig.Clone() 628 config.CurvePreferences = []CurveID{X25519} 629 630 test := &clientTest{ 631 name: "X25519-ECDHE", 632 args: []string{"-cipher", "ECDHE-RSA-AES128-GCM-SHA256", "-curves", "X25519"}, 633 config: config, 634 } 635 636 runClientTestTLS12(t, test) 637 runClientTestTLS13(t, test) 638 } 639 640 func TestHandshakeClientP256(t *testing.T) { 641 config := testConfig.Clone() 642 config.CurvePreferences = []CurveID{CurveP256} 643 644 test := &clientTest{ 645 name: "P256-ECDHE", 646 args: []string{"-cipher", "ECDHE-RSA-AES128-GCM-SHA256", "-curves", "P-256"}, 647 config: config, 648 } 649 650 runClientTestTLS12(t, test) 651 runClientTestTLS13(t, test) 652 } 653 654 func TestHandshakeClientHelloRetryRequest(t *testing.T) { 655 config := testConfig.Clone() 656 config.CurvePreferences = []CurveID{X25519, CurveP256} 657 658 test := &clientTest{ 659 name: "HelloRetryRequest", 660 args: []string{"-cipher", "ECDHE-RSA-AES128-GCM-SHA256", "-curves", "P-256"}, 661 config: config, 662 } 663 664 runClientTestTLS13(t, test) 665 } 666 667 func TestHandshakeClientECDHERSAChaCha20(t *testing.T) { 668 config := testConfig.Clone() 669 config.CipherSuites = []uint16{TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305} 670 671 test := &clientTest{ 672 name: "ECDHE-RSA-CHACHA20-POLY1305", 673 args: []string{"-cipher", "ECDHE-RSA-CHACHA20-POLY1305"}, 674 config: config, 675 } 676 677 runClientTestTLS12(t, test) 678 } 679 680 func TestHandshakeClientECDHEECDSAChaCha20(t *testing.T) { 681 config := testConfig.Clone() 682 config.CipherSuites = []uint16{TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305} 683 684 test := &clientTest{ 685 name: "ECDHE-ECDSA-CHACHA20-POLY1305", 686 args: []string{"-cipher", "ECDHE-ECDSA-CHACHA20-POLY1305"}, 687 config: config, 688 cert: testECDSACertificate, 689 key: testECDSAPrivateKey, 690 } 691 692 runClientTestTLS12(t, test) 693 } 694 695 func TestHandshakeClientAES128SHA256(t *testing.T) { 696 test := &clientTest{ 697 name: "AES128-SHA256", 698 args: []string{"-ciphersuites", "TLS_AES_128_GCM_SHA256"}, 699 } 700 runClientTestTLS13(t, test) 701 } 702 func TestHandshakeClientAES256SHA384(t *testing.T) { 703 test := &clientTest{ 704 name: "AES256-SHA384", 705 args: []string{"-ciphersuites", "TLS_AES_256_GCM_SHA384"}, 706 } 707 runClientTestTLS13(t, test) 708 } 709 func TestHandshakeClientCHACHA20SHA256(t *testing.T) { 710 test := &clientTest{ 711 name: "CHACHA20-SHA256", 712 args: []string{"-ciphersuites", "TLS_CHACHA20_POLY1305_SHA256"}, 713 } 714 runClientTestTLS13(t, test) 715 } 716 717 func TestHandshakeClientECDSATLS13(t *testing.T) { 718 test := &clientTest{ 719 name: "ECDSA", 720 cert: testECDSACertificate, 721 key: testECDSAPrivateKey, 722 } 723 runClientTestTLS13(t, test) 724 } 725 726 func TestHandshakeClientEd25519(t *testing.T) { 727 test := &clientTest{ 728 name: "Ed25519", 729 cert: testEd25519Certificate, 730 key: testEd25519PrivateKey, 731 } 732 runClientTestTLS12(t, test) 733 runClientTestTLS13(t, test) 734 735 config := testConfig.Clone() 736 cert, _ := X509KeyPair([]byte(clientEd25519CertificatePEM), []byte(clientEd25519KeyPEM)) 737 config.Certificates = []Certificate{cert} 738 739 test = &clientTest{ 740 name: "ClientCert-Ed25519", 741 args: []string{"-Verify", "1"}, 742 config: config, 743 } 744 745 runClientTestTLS12(t, test) 746 runClientTestTLS13(t, test) 747 } 748 749 func TestHandshakeClientCertRSA(t *testing.T) { 750 config := testConfig.Clone() 751 cert, _ := X509KeyPair([]byte(clientCertificatePEM), []byte(clientKeyPEM)) 752 config.Certificates = []Certificate{cert} 753 754 test := &clientTest{ 755 name: "ClientCert-RSA-RSA", 756 args: []string{"-cipher", "AES128", "-Verify", "1"}, 757 config: config, 758 } 759 760 runClientTestTLS10(t, test) 761 runClientTestTLS12(t, test) 762 763 test = &clientTest{ 764 name: "ClientCert-RSA-ECDSA", 765 args: []string{"-cipher", "ECDHE-ECDSA-AES128-SHA", "-Verify", "1"}, 766 config: config, 767 cert: testECDSACertificate, 768 key: testECDSAPrivateKey, 769 } 770 771 runClientTestTLS10(t, test) 772 runClientTestTLS12(t, test) 773 runClientTestTLS13(t, test) 774 775 test = &clientTest{ 776 name: "ClientCert-RSA-AES256-GCM-SHA384", 777 args: []string{"-cipher", "ECDHE-RSA-AES256-GCM-SHA384", "-Verify", "1"}, 778 config: config, 779 cert: testRSACertificate, 780 key: testRSAPrivateKey, 781 } 782 783 runClientTestTLS12(t, test) 784 } 785 786 func TestHandshakeClientCertECDSA(t *testing.T) { 787 config := testConfig.Clone() 788 cert, _ := X509KeyPair([]byte(clientECDSACertificatePEM), []byte(clientECDSAKeyPEM)) 789 config.Certificates = []Certificate{cert} 790 791 test := &clientTest{ 792 name: "ClientCert-ECDSA-RSA", 793 args: []string{"-cipher", "AES128", "-Verify", "1"}, 794 config: config, 795 } 796 797 runClientTestTLS10(t, test) 798 runClientTestTLS12(t, test) 799 runClientTestTLS13(t, test) 800 801 test = &clientTest{ 802 name: "ClientCert-ECDSA-ECDSA", 803 args: []string{"-cipher", "ECDHE-ECDSA-AES128-SHA", "-Verify", "1"}, 804 config: config, 805 cert: testECDSACertificate, 806 key: testECDSAPrivateKey, 807 } 808 809 runClientTestTLS10(t, test) 810 runClientTestTLS12(t, test) 811 } 812 813 // TestHandshakeClientCertRSAPSS tests rsa_pss_rsae_sha256 signatures from both 814 // client and server certificates. It also serves from both sides a certificate 815 // signed itself with RSA-PSS, mostly to check that crypto/x509 chain validation 816 // works. 817 func TestHandshakeClientCertRSAPSS(t *testing.T) { 818 cert, err := x509.ParseCertificate(testRSAPSSCertificate) 819 if err != nil { 820 panic(err) 821 } 822 rootCAs := x509.NewCertPool() 823 rootCAs.AddCert(cert) 824 825 config := testConfig.Clone() 826 // Use GetClientCertificate to bypass the client certificate selection logic. 827 config.GetClientCertificate = func(*CertificateRequestInfo) (*Certificate, error) { 828 return &Certificate{ 829 Certificate: [][]byte{testRSAPSSCertificate}, 830 PrivateKey: testRSAPrivateKey, 831 }, nil 832 } 833 config.RootCAs = rootCAs 834 835 test := &clientTest{ 836 name: "ClientCert-RSA-RSAPSS", 837 args: []string{"-cipher", "AES128", "-Verify", "1", "-client_sigalgs", 838 "rsa_pss_rsae_sha256", "-sigalgs", "rsa_pss_rsae_sha256"}, 839 config: config, 840 cert: testRSAPSSCertificate, 841 key: testRSAPrivateKey, 842 } 843 runClientTestTLS12(t, test) 844 runClientTestTLS13(t, test) 845 } 846 847 func TestHandshakeClientCertRSAPKCS1v15(t *testing.T) { 848 config := testConfig.Clone() 849 cert, _ := X509KeyPair([]byte(clientCertificatePEM), []byte(clientKeyPEM)) 850 config.Certificates = []Certificate{cert} 851 852 test := &clientTest{ 853 name: "ClientCert-RSA-RSAPKCS1v15", 854 args: []string{"-cipher", "AES128", "-Verify", "1", "-client_sigalgs", 855 "rsa_pkcs1_sha256", "-sigalgs", "rsa_pkcs1_sha256"}, 856 config: config, 857 } 858 859 runClientTestTLS12(t, test) 860 } 861 862 func TestClientKeyUpdate(t *testing.T) { 863 test := &clientTest{ 864 name: "KeyUpdate", 865 args: []string{"-state"}, 866 sendKeyUpdate: true, 867 } 868 runClientTestTLS13(t, test) 869 } 870 871 func TestResumption(t *testing.T) { 872 t.Run("TLSv12", func(t *testing.T) { testResumption(t, VersionTLS12) }) 873 t.Run("TLSv13", func(t *testing.T) { testResumption(t, VersionTLS13) }) 874 } 875 876 func testResumption(t *testing.T, version uint16) { 877 if testing.Short() { 878 t.Skip("skipping in -short mode") 879 } 880 serverConfig := &Config{ 881 MaxVersion: version, 882 CipherSuites: []uint16{TLS_RSA_WITH_RC4_128_SHA, TLS_ECDHE_RSA_WITH_RC4_128_SHA}, 883 Certificates: testConfig.Certificates, 884 } 885 886 issuer, err := x509.ParseCertificate(testRSACertificateIssuer) 887 if err != nil { 888 panic(err) 889 } 890 891 rootCAs := x509.NewCertPool() 892 rootCAs.AddCert(issuer) 893 894 clientConfig := &Config{ 895 MaxVersion: version, 896 CipherSuites: []uint16{TLS_RSA_WITH_RC4_128_SHA}, 897 ClientSessionCache: NewLRUClientSessionCache(32), 898 RootCAs: rootCAs, 899 ServerName: "example.golang", 900 } 901 902 testResumeState := func(test string, didResume bool) { 903 _, hs, err := testHandshake(t, clientConfig, serverConfig) 904 if err != nil { 905 t.Fatalf("%s: handshake failed: %s", test, err) 906 } 907 if hs.DidResume != didResume { 908 t.Fatalf("%s resumed: %v, expected: %v", test, hs.DidResume, didResume) 909 } 910 if didResume && (hs.PeerCertificates == nil || hs.VerifiedChains == nil) { 911 t.Fatalf("expected non-nil certificates after resumption. Got peerCertificates: %#v, verifiedCertificates: %#v", hs.PeerCertificates, hs.VerifiedChains) 912 } 913 if got, want := hs.ServerName, clientConfig.ServerName; got != want { 914 t.Errorf("%s: server name %s, want %s", test, got, want) 915 } 916 } 917 918 getTicket := func() []byte { 919 return clientConfig.ClientSessionCache.(*lruSessionCache).q.Front().Value.(*lruSessionCacheEntry).state.sessionTicket 920 } 921 deleteTicket := func() { 922 ticketKey := clientConfig.ClientSessionCache.(*lruSessionCache).q.Front().Value.(*lruSessionCacheEntry).sessionKey 923 clientConfig.ClientSessionCache.Put(ticketKey, nil) 924 } 925 corruptTicket := func() { 926 clientConfig.ClientSessionCache.(*lruSessionCache).q.Front().Value.(*lruSessionCacheEntry).state.masterSecret[0] ^= 0xff 927 } 928 randomKey := func() [32]byte { 929 var k [32]byte 930 if _, err := io.ReadFull(serverConfig.rand(), k[:]); err != nil { 931 t.Fatalf("Failed to read new SessionTicketKey: %s", err) 932 } 933 return k 934 } 935 936 testResumeState("Handshake", false) 937 ticket := getTicket() 938 testResumeState("Resume", true) 939 if !bytes.Equal(ticket, getTicket()) && version != VersionTLS13 { 940 t.Fatal("first ticket doesn't match ticket after resumption") 941 } 942 if bytes.Equal(ticket, getTicket()) && version == VersionTLS13 { 943 t.Fatal("ticket didn't change after resumption") 944 } 945 946 // An old session ticket can resume, but the server will provide a ticket encrypted with a fresh key. 947 serverConfig.Time = func() time.Time { return time.Now().Add(24*time.Hour + time.Minute) } 948 testResumeState("ResumeWithOldTicket", true) 949 if bytes.Equal(ticket[:ticketKeyNameLen], getTicket()[:ticketKeyNameLen]) { 950 t.Fatal("old first ticket matches the fresh one") 951 } 952 953 // Now the session tickey key is expired, so a full handshake should occur. 954 serverConfig.Time = func() time.Time { return time.Now().Add(24*8*time.Hour + time.Minute) } 955 testResumeState("ResumeWithExpiredTicket", false) 956 if bytes.Equal(ticket, getTicket()) { 957 t.Fatal("expired first ticket matches the fresh one") 958 } 959 960 serverConfig.Time = func() time.Time { return time.Now() } // reset the time back 961 key1 := randomKey() 962 serverConfig.SetSessionTicketKeys([][32]byte{key1}) 963 964 testResumeState("InvalidSessionTicketKey", false) 965 testResumeState("ResumeAfterInvalidSessionTicketKey", true) 966 967 key2 := randomKey() 968 serverConfig.SetSessionTicketKeys([][32]byte{key2, key1}) 969 ticket = getTicket() 970 testResumeState("KeyChange", true) 971 if bytes.Equal(ticket, getTicket()) { 972 t.Fatal("new ticket wasn't included while resuming") 973 } 974 testResumeState("KeyChangeFinish", true) 975 976 // Age the session ticket a bit, but not yet expired. 977 serverConfig.Time = func() time.Time { return time.Now().Add(24*time.Hour + time.Minute) } 978 testResumeState("OldSessionTicket", true) 979 ticket = getTicket() 980 // Expire the session ticket, which would force a full handshake. 981 serverConfig.Time = func() time.Time { return time.Now().Add(24*8*time.Hour + time.Minute) } 982 testResumeState("ExpiredSessionTicket", false) 983 if bytes.Equal(ticket, getTicket()) { 984 t.Fatal("new ticket wasn't provided after old ticket expired") 985 } 986 987 // Age the session ticket a bit at a time, but don't expire it. 988 d := 0 * time.Hour 989 for i := 0; i < 13; i++ { 990 d += 12 * time.Hour 991 serverConfig.Time = func() time.Time { return time.Now().Add(d) } 992 testResumeState("OldSessionTicket", true) 993 } 994 // Expire it (now a little more than 7 days) and make sure a full 995 // handshake occurs for TLS 1.2. Resumption should still occur for 996 // TLS 1.3 since the client should be using a fresh ticket sent over 997 // by the server. 998 d += 12 * time.Hour 999 serverConfig.Time = func() time.Time { return time.Now().Add(d) } 1000 if version == VersionTLS13 { 1001 testResumeState("ExpiredSessionTicket", true) 1002 } else { 1003 testResumeState("ExpiredSessionTicket", false) 1004 } 1005 if bytes.Equal(ticket, getTicket()) { 1006 t.Fatal("new ticket wasn't provided after old ticket expired") 1007 } 1008 1009 // Reset serverConfig to ensure that calling SetSessionTicketKeys 1010 // before the serverConfig is used works. 1011 serverConfig = &Config{ 1012 MaxVersion: version, 1013 CipherSuites: []uint16{TLS_RSA_WITH_RC4_128_SHA, TLS_ECDHE_RSA_WITH_RC4_128_SHA}, 1014 Certificates: testConfig.Certificates, 1015 } 1016 serverConfig.SetSessionTicketKeys([][32]byte{key2}) 1017 1018 testResumeState("FreshConfig", true) 1019 1020 // In TLS 1.3, cross-cipher suite resumption is allowed as long as the KDF 1021 // hash matches. Also, Config.CipherSuites does not apply to TLS 1.3. 1022 if version != VersionTLS13 { 1023 clientConfig.CipherSuites = []uint16{TLS_ECDHE_RSA_WITH_RC4_128_SHA} 1024 testResumeState("DifferentCipherSuite", false) 1025 testResumeState("DifferentCipherSuiteRecovers", true) 1026 } 1027 1028 deleteTicket() 1029 testResumeState("WithoutSessionTicket", false) 1030 1031 // In TLS 1.3, HelloRetryRequest is sent after incorrect key share. 1032 // See https://www.rfc-editor.org/rfc/rfc8446#page-14. 1033 if version == VersionTLS13 { 1034 deleteTicket() 1035 serverConfig = &Config{ 1036 // Use a different curve than the client to force a HelloRetryRequest. 1037 CurvePreferences: []CurveID{CurveP521, CurveP384, CurveP256}, 1038 MaxVersion: version, 1039 Certificates: testConfig.Certificates, 1040 } 1041 testResumeState("InitialHandshake", false) 1042 testResumeState("WithHelloRetryRequest", true) 1043 1044 // Reset serverConfig back. 1045 serverConfig = &Config{ 1046 MaxVersion: version, 1047 CipherSuites: []uint16{TLS_RSA_WITH_RC4_128_SHA, TLS_ECDHE_RSA_WITH_RC4_128_SHA}, 1048 Certificates: testConfig.Certificates, 1049 } 1050 } 1051 1052 // Session resumption should work when using client certificates 1053 deleteTicket() 1054 serverConfig.ClientCAs = rootCAs 1055 serverConfig.ClientAuth = RequireAndVerifyClientCert 1056 clientConfig.Certificates = serverConfig.Certificates 1057 testResumeState("InitialHandshake", false) 1058 testResumeState("WithClientCertificates", true) 1059 serverConfig.ClientAuth = NoClientCert 1060 1061 // Tickets should be removed from the session cache on TLS handshake 1062 // failure, and the client should recover from a corrupted PSK 1063 testResumeState("FetchTicketToCorrupt", false) 1064 corruptTicket() 1065 _, _, err = testHandshake(t, clientConfig, serverConfig) 1066 if err == nil { 1067 t.Fatalf("handshake did not fail with a corrupted client secret") 1068 } 1069 testResumeState("AfterHandshakeFailure", false) 1070 1071 clientConfig.ClientSessionCache = nil 1072 testResumeState("WithoutSessionCache", false) 1073 } 1074 1075 func TestLRUClientSessionCache(t *testing.T) { 1076 // Initialize cache of capacity 4. 1077 cache := NewLRUClientSessionCache(4) 1078 cs := make([]ClientSessionState, 6) 1079 keys := []string{"0", "1", "2", "3", "4", "5", "6"} 1080 1081 // Add 4 entries to the cache and look them up. 1082 for i := 0; i < 4; i++ { 1083 cache.Put(keys[i], &cs[i]) 1084 } 1085 for i := 0; i < 4; i++ { 1086 if s, ok := cache.Get(keys[i]); !ok || s != &cs[i] { 1087 t.Fatalf("session cache failed lookup for added key: %s", keys[i]) 1088 } 1089 } 1090 1091 // Add 2 more entries to the cache. First 2 should be evicted. 1092 for i := 4; i < 6; i++ { 1093 cache.Put(keys[i], &cs[i]) 1094 } 1095 for i := 0; i < 2; i++ { 1096 if s, ok := cache.Get(keys[i]); ok || s != nil { 1097 t.Fatalf("session cache should have evicted key: %s", keys[i]) 1098 } 1099 } 1100 1101 // Touch entry 2. LRU should evict 3 next. 1102 cache.Get(keys[2]) 1103 cache.Put(keys[0], &cs[0]) 1104 if s, ok := cache.Get(keys[3]); ok || s != nil { 1105 t.Fatalf("session cache should have evicted key 3") 1106 } 1107 1108 // Update entry 0 in place. 1109 cache.Put(keys[0], &cs[3]) 1110 if s, ok := cache.Get(keys[0]); !ok || s != &cs[3] { 1111 t.Fatalf("session cache failed update for key 0") 1112 } 1113 1114 // Calling Put with a nil entry deletes the key. 1115 cache.Put(keys[0], nil) 1116 if _, ok := cache.Get(keys[0]); ok { 1117 t.Fatalf("session cache failed to delete key 0") 1118 } 1119 1120 // Delete entry 2. LRU should keep 4 and 5 1121 cache.Put(keys[2], nil) 1122 if _, ok := cache.Get(keys[2]); ok { 1123 t.Fatalf("session cache failed to delete key 4") 1124 } 1125 for i := 4; i < 6; i++ { 1126 if s, ok := cache.Get(keys[i]); !ok || s != &cs[i] { 1127 t.Fatalf("session cache should not have deleted key: %s", keys[i]) 1128 } 1129 } 1130 } 1131 1132 func TestKeyLogTLS12(t *testing.T) { 1133 var serverBuf, clientBuf bytes.Buffer 1134 1135 clientConfig := testConfig.Clone() 1136 clientConfig.KeyLogWriter = &clientBuf 1137 clientConfig.MaxVersion = VersionTLS12 1138 1139 serverConfig := testConfig.Clone() 1140 serverConfig.KeyLogWriter = &serverBuf 1141 serverConfig.MaxVersion = VersionTLS12 1142 1143 c, s := localPipe(t) 1144 done := make(chan bool) 1145 1146 go func() { 1147 defer close(done) 1148 1149 if err := Server(s, serverConfig).Handshake(); err != nil { 1150 t.Errorf("server: %s", err) 1151 return 1152 } 1153 s.Close() 1154 }() 1155 1156 if err := Client(c, clientConfig).Handshake(); err != nil { 1157 t.Fatalf("client: %s", err) 1158 } 1159 1160 c.Close() 1161 <-done 1162 1163 checkKeylogLine := func(side, loggedLine string) { 1164 if len(loggedLine) == 0 { 1165 t.Fatalf("%s: no keylog line was produced", side) 1166 } 1167 const expectedLen = 13 /* "CLIENT_RANDOM" */ + 1168 1 /* space */ + 1169 32*2 /* hex client nonce */ + 1170 1 /* space */ + 1171 48*2 /* hex master secret */ + 1172 1 /* new line */ 1173 if len(loggedLine) != expectedLen { 1174 t.Fatalf("%s: keylog line has incorrect length (want %d, got %d): %q", side, expectedLen, len(loggedLine), loggedLine) 1175 } 1176 if !strings.HasPrefix(loggedLine, "CLIENT_RANDOM "+strings.Repeat("0", 64)+" ") { 1177 t.Fatalf("%s: keylog line has incorrect structure or nonce: %q", side, loggedLine) 1178 } 1179 } 1180 1181 checkKeylogLine("client", clientBuf.String()) 1182 checkKeylogLine("server", serverBuf.String()) 1183 } 1184 1185 func TestKeyLogTLS13(t *testing.T) { 1186 var serverBuf, clientBuf bytes.Buffer 1187 1188 clientConfig := testConfig.Clone() 1189 clientConfig.KeyLogWriter = &clientBuf 1190 1191 serverConfig := testConfig.Clone() 1192 serverConfig.KeyLogWriter = &serverBuf 1193 1194 c, s := localPipe(t) 1195 done := make(chan bool) 1196 1197 go func() { 1198 defer close(done) 1199 1200 if err := Server(s, serverConfig).Handshake(); err != nil { 1201 t.Errorf("server: %s", err) 1202 return 1203 } 1204 s.Close() 1205 }() 1206 1207 if err := Client(c, clientConfig).Handshake(); err != nil { 1208 t.Fatalf("client: %s", err) 1209 } 1210 1211 c.Close() 1212 <-done 1213 1214 checkKeylogLines := func(side, loggedLines string) { 1215 loggedLines = strings.TrimSpace(loggedLines) 1216 lines := strings.Split(loggedLines, "\n") 1217 if len(lines) != 4 { 1218 t.Errorf("Expected the %s to log 4 lines, got %d", side, len(lines)) 1219 } 1220 } 1221 1222 checkKeylogLines("client", clientBuf.String()) 1223 checkKeylogLines("server", serverBuf.String()) 1224 } 1225 1226 func TestHandshakeClientALPNMatch(t *testing.T) { 1227 config := testConfig.Clone() 1228 config.NextProtos = []string{"proto2", "proto1"} 1229 1230 test := &clientTest{ 1231 name: "ALPN", 1232 // Note that this needs OpenSSL 1.0.2 because that is the first 1233 // version that supports the -alpn flag. 1234 args: []string{"-alpn", "proto1,proto2"}, 1235 config: config, 1236 validate: func(state ConnectionState) error { 1237 // The server's preferences should override the client. 1238 if state.NegotiatedProtocol != "proto1" { 1239 return fmt.Errorf("Got protocol %q, wanted proto1", state.NegotiatedProtocol) 1240 } 1241 return nil 1242 }, 1243 } 1244 runClientTestTLS12(t, test) 1245 runClientTestTLS13(t, test) 1246 } 1247 1248 func TestServerSelectingUnconfiguredApplicationProtocol(t *testing.T) { 1249 // This checks that the server can't select an application protocol that the 1250 // client didn't offer. 1251 1252 c, s := localPipe(t) 1253 errChan := make(chan error, 1) 1254 1255 go func() { 1256 client := Client(c, &Config{ 1257 ServerName: "foo", 1258 CipherSuites: []uint16{TLS_RSA_WITH_AES_128_GCM_SHA256}, 1259 NextProtos: []string{"http", "something-else"}, 1260 }) 1261 errChan <- client.Handshake() 1262 }() 1263 1264 var header [5]byte 1265 if _, err := io.ReadFull(s, header[:]); err != nil { 1266 t.Fatal(err) 1267 } 1268 recordLen := int(header[3])<<8 | int(header[4]) 1269 1270 record := make([]byte, recordLen) 1271 if _, err := io.ReadFull(s, record); err != nil { 1272 t.Fatal(err) 1273 } 1274 1275 serverHello := &serverHelloMsg{ 1276 vers: VersionTLS12, 1277 random: make([]byte, 32), 1278 cipherSuite: TLS_RSA_WITH_AES_128_GCM_SHA256, 1279 alpnProtocol: "how-about-this", 1280 } 1281 serverHelloBytes := mustMarshal(t, serverHello) 1282 1283 s.Write([]byte{ 1284 byte(recordTypeHandshake), 1285 byte(VersionTLS12 >> 8), 1286 byte(VersionTLS12 & 0xff), 1287 byte(len(serverHelloBytes) >> 8), 1288 byte(len(serverHelloBytes)), 1289 }) 1290 s.Write(serverHelloBytes) 1291 s.Close() 1292 1293 if err := <-errChan; !strings.Contains(err.Error(), "server selected unadvertised ALPN protocol") { 1294 t.Fatalf("Expected error about unconfigured cipher suite but got %q", err) 1295 } 1296 } 1297 1298 // sctsBase64 contains data from `openssl s_client -serverinfo 18 -connect ritter.vg:443` 1299 const sctsBase64 = "ABIBaQFnAHUApLkJkLQYWBSHuxOizGdwCjw1mAT5G9+443fNDsgN3BAAAAFHl5nuFgAABAMARjBEAiAcS4JdlW5nW9sElUv2zvQyPoZ6ejKrGGB03gjaBZFMLwIgc1Qbbn+hsH0RvObzhS+XZhr3iuQQJY8S9G85D9KeGPAAdgBo9pj4H2SCvjqM7rkoHUz8cVFdZ5PURNEKZ6y7T0/7xAAAAUeX4bVwAAAEAwBHMEUCIDIhFDgG2HIuADBkGuLobU5a4dlCHoJLliWJ1SYT05z6AiEAjxIoZFFPRNWMGGIjskOTMwXzQ1Wh2e7NxXE1kd1J0QsAdgDuS723dc5guuFCaR+r4Z5mow9+X7By2IMAxHuJeqj9ywAAAUhcZIqHAAAEAwBHMEUCICmJ1rBT09LpkbzxtUC+Hi7nXLR0J+2PmwLp+sJMuqK+AiEAr0NkUnEVKVhAkccIFpYDqHOlZaBsuEhWWrYpg2RtKp0=" 1300 1301 func TestHandshakClientSCTs(t *testing.T) { 1302 config := testConfig.Clone() 1303 1304 scts, err := base64.StdEncoding.DecodeString(sctsBase64) 1305 if err != nil { 1306 t.Fatal(err) 1307 } 1308 1309 // Note that this needs OpenSSL 1.0.2 because that is the first 1310 // version that supports the -serverinfo flag. 1311 test := &clientTest{ 1312 name: "SCT", 1313 config: config, 1314 extensions: [][]byte{scts}, 1315 validate: func(state ConnectionState) error { 1316 expectedSCTs := [][]byte{ 1317 scts[8:125], 1318 scts[127:245], 1319 scts[247:], 1320 } 1321 if n := len(state.SignedCertificateTimestamps); n != len(expectedSCTs) { 1322 return fmt.Errorf("Got %d scts, wanted %d", n, len(expectedSCTs)) 1323 } 1324 for i, expected := range expectedSCTs { 1325 if sct := state.SignedCertificateTimestamps[i]; !bytes.Equal(sct, expected) { 1326 return fmt.Errorf("SCT #%d contained %x, expected %x", i, sct, expected) 1327 } 1328 } 1329 return nil 1330 }, 1331 } 1332 runClientTestTLS12(t, test) 1333 1334 // TLS 1.3 moved SCTs to the Certificate extensions and -serverinfo only 1335 // supports ServerHello extensions. 1336 } 1337 1338 func TestRenegotiationRejected(t *testing.T) { 1339 config := testConfig.Clone() 1340 test := &clientTest{ 1341 name: "RenegotiationRejected", 1342 args: []string{"-state"}, 1343 config: config, 1344 numRenegotiations: 1, 1345 renegotiationExpectedToFail: 1, 1346 checkRenegotiationError: func(renegotiationNum int, err error) error { 1347 if err == nil { 1348 return errors.New("expected error from renegotiation but got nil") 1349 } 1350 if !strings.Contains(err.Error(), "no renegotiation") { 1351 return fmt.Errorf("expected renegotiation to be rejected but got %q", err) 1352 } 1353 return nil 1354 }, 1355 } 1356 runClientTestTLS12(t, test) 1357 } 1358 1359 func TestRenegotiateOnce(t *testing.T) { 1360 config := testConfig.Clone() 1361 config.Renegotiation = RenegotiateOnceAsClient 1362 1363 test := &clientTest{ 1364 name: "RenegotiateOnce", 1365 args: []string{"-state"}, 1366 config: config, 1367 numRenegotiations: 1, 1368 } 1369 1370 runClientTestTLS12(t, test) 1371 } 1372 1373 func TestRenegotiateTwice(t *testing.T) { 1374 config := testConfig.Clone() 1375 config.Renegotiation = RenegotiateFreelyAsClient 1376 1377 test := &clientTest{ 1378 name: "RenegotiateTwice", 1379 args: []string{"-state"}, 1380 config: config, 1381 numRenegotiations: 2, 1382 } 1383 1384 runClientTestTLS12(t, test) 1385 } 1386 1387 func TestRenegotiateTwiceRejected(t *testing.T) { 1388 config := testConfig.Clone() 1389 config.Renegotiation = RenegotiateOnceAsClient 1390 1391 test := &clientTest{ 1392 name: "RenegotiateTwiceRejected", 1393 args: []string{"-state"}, 1394 config: config, 1395 numRenegotiations: 2, 1396 renegotiationExpectedToFail: 2, 1397 checkRenegotiationError: func(renegotiationNum int, err error) error { 1398 if renegotiationNum == 1 { 1399 return err 1400 } 1401 1402 if err == nil { 1403 return errors.New("expected error from renegotiation but got nil") 1404 } 1405 if !strings.Contains(err.Error(), "no renegotiation") { 1406 return fmt.Errorf("expected renegotiation to be rejected but got %q", err) 1407 } 1408 return nil 1409 }, 1410 } 1411 1412 runClientTestTLS12(t, test) 1413 } 1414 1415 func TestHandshakeClientExportKeyingMaterial(t *testing.T) { 1416 test := &clientTest{ 1417 name: "ExportKeyingMaterial", 1418 config: testConfig.Clone(), 1419 validate: func(state ConnectionState) error { 1420 if km, err := state.ExportKeyingMaterial("test", nil, 42); err != nil { 1421 return fmt.Errorf("ExportKeyingMaterial failed: %v", err) 1422 } else if len(km) != 42 { 1423 return fmt.Errorf("Got %d bytes from ExportKeyingMaterial, wanted %d", len(km), 42) 1424 } 1425 return nil 1426 }, 1427 } 1428 runClientTestTLS10(t, test) 1429 runClientTestTLS12(t, test) 1430 runClientTestTLS13(t, test) 1431 } 1432 1433 var hostnameInSNITests = []struct { 1434 in, out string 1435 }{ 1436 // Opaque string 1437 {"", ""}, 1438 {"localhost", "localhost"}, 1439 {"foo, bar, baz and qux", "foo, bar, baz and qux"}, 1440 1441 // DNS hostname 1442 {"golang.org", "golang.org"}, 1443 {"golang.org.", "golang.org"}, 1444 1445 // Literal IPv4 address 1446 {"1.2.3.4", ""}, 1447 1448 // Literal IPv6 address 1449 {"::1", ""}, 1450 {"::1%lo0", ""}, // with zone identifier 1451 {"[::1]", ""}, // as per RFC 5952 we allow the [] style as IPv6 literal 1452 {"[::1%lo0]", ""}, 1453 } 1454 1455 func TestHostnameInSNI(t *testing.T) { 1456 for _, tt := range hostnameInSNITests { 1457 c, s := localPipe(t) 1458 1459 go func(host string) { 1460 Client(c, &Config{ServerName: host, InsecureSkipVerify: true}).Handshake() 1461 }(tt.in) 1462 1463 var header [5]byte 1464 if _, err := io.ReadFull(s, header[:]); err != nil { 1465 t.Fatal(err) 1466 } 1467 recordLen := int(header[3])<<8 | int(header[4]) 1468 1469 record := make([]byte, recordLen) 1470 if _, err := io.ReadFull(s, record[:]); err != nil { 1471 t.Fatal(err) 1472 } 1473 1474 c.Close() 1475 s.Close() 1476 1477 var m clientHelloMsg 1478 if !m.unmarshal(record) { 1479 t.Errorf("unmarshaling ClientHello for %q failed", tt.in) 1480 continue 1481 } 1482 if tt.in != tt.out && m.serverName == tt.in { 1483 t.Errorf("prohibited %q found in ClientHello: %x", tt.in, record) 1484 } 1485 if m.serverName != tt.out { 1486 t.Errorf("expected %q not found in ClientHello: %x", tt.out, record) 1487 } 1488 } 1489 } 1490 1491 func TestServerSelectingUnconfiguredCipherSuite(t *testing.T) { 1492 // This checks that the server can't select a cipher suite that the 1493 // client didn't offer. See #13174. 1494 1495 c, s := localPipe(t) 1496 errChan := make(chan error, 1) 1497 1498 go func() { 1499 client := Client(c, &Config{ 1500 ServerName: "foo", 1501 CipherSuites: []uint16{TLS_RSA_WITH_AES_128_GCM_SHA256}, 1502 }) 1503 errChan <- client.Handshake() 1504 }() 1505 1506 var header [5]byte 1507 if _, err := io.ReadFull(s, header[:]); err != nil { 1508 t.Fatal(err) 1509 } 1510 recordLen := int(header[3])<<8 | int(header[4]) 1511 1512 record := make([]byte, recordLen) 1513 if _, err := io.ReadFull(s, record); err != nil { 1514 t.Fatal(err) 1515 } 1516 1517 // Create a ServerHello that selects a different cipher suite than the 1518 // sole one that the client offered. 1519 serverHello := &serverHelloMsg{ 1520 vers: VersionTLS12, 1521 random: make([]byte, 32), 1522 cipherSuite: TLS_RSA_WITH_AES_256_GCM_SHA384, 1523 } 1524 serverHelloBytes := mustMarshal(t, serverHello) 1525 1526 s.Write([]byte{ 1527 byte(recordTypeHandshake), 1528 byte(VersionTLS12 >> 8), 1529 byte(VersionTLS12 & 0xff), 1530 byte(len(serverHelloBytes) >> 8), 1531 byte(len(serverHelloBytes)), 1532 }) 1533 s.Write(serverHelloBytes) 1534 s.Close() 1535 1536 if err := <-errChan; !strings.Contains(err.Error(), "unconfigured cipher") { 1537 t.Fatalf("Expected error about unconfigured cipher suite but got %q", err) 1538 } 1539 } 1540 1541 func TestVerifyConnection(t *testing.T) { 1542 t.Run("TLSv12", func(t *testing.T) { testVerifyConnection(t, VersionTLS12) }) 1543 t.Run("TLSv13", func(t *testing.T) { testVerifyConnection(t, VersionTLS13) }) 1544 } 1545 1546 func testVerifyConnection(t *testing.T, version uint16) { 1547 checkFields := func(c ConnectionState, called *int, errorType string) error { 1548 if c.Version != version { 1549 return fmt.Errorf("%s: got Version %v, want %v", errorType, c.Version, version) 1550 } 1551 if c.HandshakeComplete { 1552 return fmt.Errorf("%s: got HandshakeComplete, want false", errorType) 1553 } 1554 if c.ServerName != "example.golang" { 1555 return fmt.Errorf("%s: got ServerName %s, want %s", errorType, c.ServerName, "example.golang") 1556 } 1557 if c.NegotiatedProtocol != "protocol1" { 1558 return fmt.Errorf("%s: got NegotiatedProtocol %s, want %s", errorType, c.NegotiatedProtocol, "protocol1") 1559 } 1560 if c.CipherSuite == 0 { 1561 return fmt.Errorf("%s: got CipherSuite 0, want non-zero", errorType) 1562 } 1563 wantDidResume := false 1564 if *called == 2 { // if this is the second time, then it should be a resumption 1565 wantDidResume = true 1566 } 1567 if c.DidResume != wantDidResume { 1568 return fmt.Errorf("%s: got DidResume %t, want %t", errorType, c.DidResume, wantDidResume) 1569 } 1570 return nil 1571 } 1572 1573 tests := []struct { 1574 name string 1575 configureServer func(*Config, *int) 1576 configureClient func(*Config, *int) 1577 }{ 1578 { 1579 name: "RequireAndVerifyClientCert", 1580 configureServer: func(config *Config, called *int) { 1581 config.ClientAuth = RequireAndVerifyClientCert 1582 config.VerifyConnection = func(c ConnectionState) error { 1583 *called++ 1584 if l := len(c.PeerCertificates); l != 1 { 1585 return fmt.Errorf("server: got len(PeerCertificates) = %d, wanted 1", l) 1586 } 1587 if len(c.VerifiedChains) == 0 { 1588 return fmt.Errorf("server: got len(VerifiedChains) = 0, wanted non-zero") 1589 } 1590 return checkFields(c, called, "server") 1591 } 1592 }, 1593 configureClient: func(config *Config, called *int) { 1594 config.VerifyConnection = func(c ConnectionState) error { 1595 *called++ 1596 if l := len(c.PeerCertificates); l != 1 { 1597 return fmt.Errorf("client: got len(PeerCertificates) = %d, wanted 1", l) 1598 } 1599 if len(c.VerifiedChains) == 0 { 1600 return fmt.Errorf("client: got len(VerifiedChains) = 0, wanted non-zero") 1601 } 1602 if c.DidResume { 1603 return nil 1604 // The SCTs and OCSP Response are dropped on resumption. 1605 // See http://golang.org/issue/39075. 1606 } 1607 if len(c.OCSPResponse) == 0 { 1608 return fmt.Errorf("client: got len(OCSPResponse) = 0, wanted non-zero") 1609 } 1610 if len(c.SignedCertificateTimestamps) == 0 { 1611 return fmt.Errorf("client: got len(SignedCertificateTimestamps) = 0, wanted non-zero") 1612 } 1613 return checkFields(c, called, "client") 1614 } 1615 }, 1616 }, 1617 { 1618 name: "InsecureSkipVerify", 1619 configureServer: func(config *Config, called *int) { 1620 config.ClientAuth = RequireAnyClientCert 1621 config.InsecureSkipVerify = true 1622 config.VerifyConnection = func(c ConnectionState) error { 1623 *called++ 1624 if l := len(c.PeerCertificates); l != 1 { 1625 return fmt.Errorf("server: got len(PeerCertificates) = %d, wanted 1", l) 1626 } 1627 if c.VerifiedChains != nil { 1628 return fmt.Errorf("server: got Verified Chains %v, want nil", c.VerifiedChains) 1629 } 1630 return checkFields(c, called, "server") 1631 } 1632 }, 1633 configureClient: func(config *Config, called *int) { 1634 config.InsecureSkipVerify = true 1635 config.VerifyConnection = func(c ConnectionState) error { 1636 *called++ 1637 if l := len(c.PeerCertificates); l != 1 { 1638 return fmt.Errorf("client: got len(PeerCertificates) = %d, wanted 1", l) 1639 } 1640 if c.VerifiedChains != nil { 1641 return fmt.Errorf("server: got Verified Chains %v, want nil", c.VerifiedChains) 1642 } 1643 if c.DidResume { 1644 return nil 1645 // The SCTs and OCSP Response are dropped on resumption. 1646 // See http://golang.org/issue/39075. 1647 } 1648 if len(c.OCSPResponse) == 0 { 1649 return fmt.Errorf("client: got len(OCSPResponse) = 0, wanted non-zero") 1650 } 1651 if len(c.SignedCertificateTimestamps) == 0 { 1652 return fmt.Errorf("client: got len(SignedCertificateTimestamps) = 0, wanted non-zero") 1653 } 1654 return checkFields(c, called, "client") 1655 } 1656 }, 1657 }, 1658 { 1659 name: "NoClientCert", 1660 configureServer: func(config *Config, called *int) { 1661 config.ClientAuth = NoClientCert 1662 config.VerifyConnection = func(c ConnectionState) error { 1663 *called++ 1664 return checkFields(c, called, "server") 1665 } 1666 }, 1667 configureClient: func(config *Config, called *int) { 1668 config.VerifyConnection = func(c ConnectionState) error { 1669 *called++ 1670 return checkFields(c, called, "client") 1671 } 1672 }, 1673 }, 1674 { 1675 name: "RequestClientCert", 1676 configureServer: func(config *Config, called *int) { 1677 config.ClientAuth = RequestClientCert 1678 config.VerifyConnection = func(c ConnectionState) error { 1679 *called++ 1680 return checkFields(c, called, "server") 1681 } 1682 }, 1683 configureClient: func(config *Config, called *int) { 1684 config.Certificates = nil // clear the client cert 1685 config.VerifyConnection = func(c ConnectionState) error { 1686 *called++ 1687 if l := len(c.PeerCertificates); l != 1 { 1688 return fmt.Errorf("client: got len(PeerCertificates) = %d, wanted 1", l) 1689 } 1690 if len(c.VerifiedChains) == 0 { 1691 return fmt.Errorf("client: got len(VerifiedChains) = 0, wanted non-zero") 1692 } 1693 if c.DidResume { 1694 return nil 1695 // The SCTs and OCSP Response are dropped on resumption. 1696 // See http://golang.org/issue/39075. 1697 } 1698 if len(c.OCSPResponse) == 0 { 1699 return fmt.Errorf("client: got len(OCSPResponse) = 0, wanted non-zero") 1700 } 1701 if len(c.SignedCertificateTimestamps) == 0 { 1702 return fmt.Errorf("client: got len(SignedCertificateTimestamps) = 0, wanted non-zero") 1703 } 1704 return checkFields(c, called, "client") 1705 } 1706 }, 1707 }, 1708 } 1709 for _, test := range tests { 1710 issuer, err := x509.ParseCertificate(testRSACertificateIssuer) 1711 if err != nil { 1712 panic(err) 1713 } 1714 rootCAs := x509.NewCertPool() 1715 rootCAs.AddCert(issuer) 1716 1717 var serverCalled, clientCalled int 1718 1719 serverConfig := &Config{ 1720 MaxVersion: version, 1721 Certificates: []Certificate{testConfig.Certificates[0]}, 1722 ClientCAs: rootCAs, 1723 NextProtos: []string{"protocol1"}, 1724 } 1725 serverConfig.Certificates[0].SignedCertificateTimestamps = [][]byte{[]byte("dummy sct 1"), []byte("dummy sct 2")} 1726 serverConfig.Certificates[0].OCSPStaple = []byte("dummy ocsp") 1727 test.configureServer(serverConfig, &serverCalled) 1728 1729 clientConfig := &Config{ 1730 MaxVersion: version, 1731 ClientSessionCache: NewLRUClientSessionCache(32), 1732 RootCAs: rootCAs, 1733 ServerName: "example.golang", 1734 Certificates: []Certificate{testConfig.Certificates[0]}, 1735 NextProtos: []string{"protocol1"}, 1736 } 1737 test.configureClient(clientConfig, &clientCalled) 1738 1739 testHandshakeState := func(name string, didResume bool) { 1740 _, hs, err := testHandshake(t, clientConfig, serverConfig) 1741 if err != nil { 1742 t.Fatalf("%s: handshake failed: %s", name, err) 1743 } 1744 if hs.DidResume != didResume { 1745 t.Errorf("%s: resumed: %v, expected: %v", name, hs.DidResume, didResume) 1746 } 1747 wantCalled := 1 1748 if didResume { 1749 wantCalled = 2 // resumption would mean this is the second time it was called in this test 1750 } 1751 if clientCalled != wantCalled { 1752 t.Errorf("%s: expected client VerifyConnection called %d times, did %d times", name, wantCalled, clientCalled) 1753 } 1754 if serverCalled != wantCalled { 1755 t.Errorf("%s: expected server VerifyConnection called %d times, did %d times", name, wantCalled, serverCalled) 1756 } 1757 } 1758 testHandshakeState(fmt.Sprintf("%s-FullHandshake", test.name), false) 1759 testHandshakeState(fmt.Sprintf("%s-Resumption", test.name), true) 1760 } 1761 } 1762 1763 func TestVerifyPeerCertificate(t *testing.T) { 1764 t.Run("TLSv12", func(t *testing.T) { testVerifyPeerCertificate(t, VersionTLS12) }) 1765 t.Run("TLSv13", func(t *testing.T) { testVerifyPeerCertificate(t, VersionTLS13) }) 1766 } 1767 1768 func testVerifyPeerCertificate(t *testing.T, version uint16) { 1769 issuer, err := x509.ParseCertificate(testRSACertificateIssuer) 1770 if err != nil { 1771 panic(err) 1772 } 1773 1774 rootCAs := x509.NewCertPool() 1775 rootCAs.AddCert(issuer) 1776 1777 now := func() time.Time { return time.Unix(1476984729, 0) } 1778 1779 sentinelErr := errors.New("TestVerifyPeerCertificate") 1780 1781 verifyPeerCertificateCallback := func(called *bool, rawCerts [][]byte, validatedChains [][]*x509.Certificate) error { 1782 if l := len(rawCerts); l != 1 { 1783 return fmt.Errorf("got len(rawCerts) = %d, wanted 1", l) 1784 } 1785 if len(validatedChains) == 0 { 1786 return errors.New("got len(validatedChains) = 0, wanted non-zero") 1787 } 1788 *called = true 1789 return nil 1790 } 1791 verifyConnectionCallback := func(called *bool, isClient bool, c ConnectionState) error { 1792 if l := len(c.PeerCertificates); l != 1 { 1793 return fmt.Errorf("got len(PeerCertificates) = %d, wanted 1", l) 1794 } 1795 if len(c.VerifiedChains) == 0 { 1796 return fmt.Errorf("got len(VerifiedChains) = 0, wanted non-zero") 1797 } 1798 if isClient && len(c.OCSPResponse) == 0 { 1799 return fmt.Errorf("got len(OCSPResponse) = 0, wanted non-zero") 1800 } 1801 *called = true 1802 return nil 1803 } 1804 1805 tests := []struct { 1806 configureServer func(*Config, *bool) 1807 configureClient func(*Config, *bool) 1808 validate func(t *testing.T, testNo int, clientCalled, serverCalled bool, clientErr, serverErr error) 1809 }{ 1810 { 1811 configureServer: func(config *Config, called *bool) { 1812 config.InsecureSkipVerify = false 1813 config.VerifyPeerCertificate = func(rawCerts [][]byte, validatedChains [][]*x509.Certificate) error { 1814 return verifyPeerCertificateCallback(called, rawCerts, validatedChains) 1815 } 1816 }, 1817 configureClient: func(config *Config, called *bool) { 1818 config.InsecureSkipVerify = false 1819 config.VerifyPeerCertificate = func(rawCerts [][]byte, validatedChains [][]*x509.Certificate) error { 1820 return verifyPeerCertificateCallback(called, rawCerts, validatedChains) 1821 } 1822 }, 1823 validate: func(t *testing.T, testNo int, clientCalled, serverCalled bool, clientErr, serverErr error) { 1824 if clientErr != nil { 1825 t.Errorf("test[%d]: client handshake failed: %v", testNo, clientErr) 1826 } 1827 if serverErr != nil { 1828 t.Errorf("test[%d]: server handshake failed: %v", testNo, serverErr) 1829 } 1830 if !clientCalled { 1831 t.Errorf("test[%d]: client did not call callback", testNo) 1832 } 1833 if !serverCalled { 1834 t.Errorf("test[%d]: server did not call callback", testNo) 1835 } 1836 }, 1837 }, 1838 { 1839 configureServer: func(config *Config, called *bool) { 1840 config.InsecureSkipVerify = false 1841 config.VerifyPeerCertificate = func(rawCerts [][]byte, validatedChains [][]*x509.Certificate) error { 1842 return sentinelErr 1843 } 1844 }, 1845 configureClient: func(config *Config, called *bool) { 1846 config.VerifyPeerCertificate = nil 1847 }, 1848 validate: func(t *testing.T, testNo int, clientCalled, serverCalled bool, clientErr, serverErr error) { 1849 if serverErr != sentinelErr { 1850 t.Errorf("#%d: got server error %v, wanted sentinelErr", testNo, serverErr) 1851 } 1852 }, 1853 }, 1854 { 1855 configureServer: func(config *Config, called *bool) { 1856 config.InsecureSkipVerify = false 1857 }, 1858 configureClient: func(config *Config, called *bool) { 1859 config.VerifyPeerCertificate = func(rawCerts [][]byte, validatedChains [][]*x509.Certificate) error { 1860 return sentinelErr 1861 } 1862 }, 1863 validate: func(t *testing.T, testNo int, clientCalled, serverCalled bool, clientErr, serverErr error) { 1864 if clientErr != sentinelErr { 1865 t.Errorf("#%d: got client error %v, wanted sentinelErr", testNo, clientErr) 1866 } 1867 }, 1868 }, 1869 { 1870 configureServer: func(config *Config, called *bool) { 1871 config.InsecureSkipVerify = false 1872 }, 1873 configureClient: func(config *Config, called *bool) { 1874 config.InsecureSkipVerify = true 1875 config.VerifyPeerCertificate = func(rawCerts [][]byte, validatedChains [][]*x509.Certificate) error { 1876 if l := len(rawCerts); l != 1 { 1877 return fmt.Errorf("got len(rawCerts) = %d, wanted 1", l) 1878 } 1879 // With InsecureSkipVerify set, this 1880 // callback should still be called but 1881 // validatedChains must be empty. 1882 if l := len(validatedChains); l != 0 { 1883 return fmt.Errorf("got len(validatedChains) = %d, wanted zero", l) 1884 } 1885 *called = true 1886 return nil 1887 } 1888 }, 1889 validate: func(t *testing.T, testNo int, clientCalled, serverCalled bool, clientErr, serverErr error) { 1890 if clientErr != nil { 1891 t.Errorf("test[%d]: client handshake failed: %v", testNo, clientErr) 1892 } 1893 if serverErr != nil { 1894 t.Errorf("test[%d]: server handshake failed: %v", testNo, serverErr) 1895 } 1896 if !clientCalled { 1897 t.Errorf("test[%d]: client did not call callback", testNo) 1898 } 1899 }, 1900 }, 1901 { 1902 configureServer: func(config *Config, called *bool) { 1903 config.InsecureSkipVerify = false 1904 config.VerifyConnection = func(c ConnectionState) error { 1905 return verifyConnectionCallback(called, false, c) 1906 } 1907 }, 1908 configureClient: func(config *Config, called *bool) { 1909 config.InsecureSkipVerify = false 1910 config.VerifyConnection = func(c ConnectionState) error { 1911 return verifyConnectionCallback(called, true, c) 1912 } 1913 }, 1914 validate: func(t *testing.T, testNo int, clientCalled, serverCalled bool, clientErr, serverErr error) { 1915 if clientErr != nil { 1916 t.Errorf("test[%d]: client handshake failed: %v", testNo, clientErr) 1917 } 1918 if serverErr != nil { 1919 t.Errorf("test[%d]: server handshake failed: %v", testNo, serverErr) 1920 } 1921 if !clientCalled { 1922 t.Errorf("test[%d]: client did not call callback", testNo) 1923 } 1924 if !serverCalled { 1925 t.Errorf("test[%d]: server did not call callback", testNo) 1926 } 1927 }, 1928 }, 1929 { 1930 configureServer: func(config *Config, called *bool) { 1931 config.InsecureSkipVerify = false 1932 config.VerifyConnection = func(c ConnectionState) error { 1933 return sentinelErr 1934 } 1935 }, 1936 configureClient: func(config *Config, called *bool) { 1937 config.InsecureSkipVerify = false 1938 config.VerifyConnection = nil 1939 }, 1940 validate: func(t *testing.T, testNo int, clientCalled, serverCalled bool, clientErr, serverErr error) { 1941 if serverErr != sentinelErr { 1942 t.Errorf("#%d: got server error %v, wanted sentinelErr", testNo, serverErr) 1943 } 1944 }, 1945 }, 1946 { 1947 configureServer: func(config *Config, called *bool) { 1948 config.InsecureSkipVerify = false 1949 config.VerifyConnection = nil 1950 }, 1951 configureClient: func(config *Config, called *bool) { 1952 config.InsecureSkipVerify = false 1953 config.VerifyConnection = func(c ConnectionState) error { 1954 return sentinelErr 1955 } 1956 }, 1957 validate: func(t *testing.T, testNo int, clientCalled, serverCalled bool, clientErr, serverErr error) { 1958 if clientErr != sentinelErr { 1959 t.Errorf("#%d: got client error %v, wanted sentinelErr", testNo, clientErr) 1960 } 1961 }, 1962 }, 1963 { 1964 configureServer: func(config *Config, called *bool) { 1965 config.InsecureSkipVerify = false 1966 config.VerifyPeerCertificate = func(rawCerts [][]byte, validatedChains [][]*x509.Certificate) error { 1967 return verifyPeerCertificateCallback(called, rawCerts, validatedChains) 1968 } 1969 config.VerifyConnection = func(c ConnectionState) error { 1970 return sentinelErr 1971 } 1972 }, 1973 configureClient: func(config *Config, called *bool) { 1974 config.InsecureSkipVerify = false 1975 config.VerifyPeerCertificate = nil 1976 config.VerifyConnection = nil 1977 }, 1978 validate: func(t *testing.T, testNo int, clientCalled, serverCalled bool, clientErr, serverErr error) { 1979 if serverErr != sentinelErr { 1980 t.Errorf("#%d: got server error %v, wanted sentinelErr", testNo, serverErr) 1981 } 1982 if !serverCalled { 1983 t.Errorf("test[%d]: server did not call callback", testNo) 1984 } 1985 }, 1986 }, 1987 { 1988 configureServer: func(config *Config, called *bool) { 1989 config.InsecureSkipVerify = false 1990 config.VerifyPeerCertificate = nil 1991 config.VerifyConnection = nil 1992 }, 1993 configureClient: func(config *Config, called *bool) { 1994 config.InsecureSkipVerify = false 1995 config.VerifyPeerCertificate = func(rawCerts [][]byte, validatedChains [][]*x509.Certificate) error { 1996 return verifyPeerCertificateCallback(called, rawCerts, validatedChains) 1997 } 1998 config.VerifyConnection = func(c ConnectionState) error { 1999 return sentinelErr 2000 } 2001 }, 2002 validate: func(t *testing.T, testNo int, clientCalled, serverCalled bool, clientErr, serverErr error) { 2003 if clientErr != sentinelErr { 2004 t.Errorf("#%d: got client error %v, wanted sentinelErr", testNo, clientErr) 2005 } 2006 if !clientCalled { 2007 t.Errorf("test[%d]: client did not call callback", testNo) 2008 } 2009 }, 2010 }, 2011 } 2012 2013 for i, test := range tests { 2014 c, s := localPipe(t) 2015 done := make(chan error) 2016 2017 var clientCalled, serverCalled bool 2018 2019 go func() { 2020 config := testConfig.Clone() 2021 config.ServerName = "example.golang" 2022 config.ClientAuth = RequireAndVerifyClientCert 2023 config.ClientCAs = rootCAs 2024 config.Time = now 2025 config.MaxVersion = version 2026 config.Certificates = make([]Certificate, 1) 2027 config.Certificates[0].Certificate = [][]byte{testRSACertificate} 2028 config.Certificates[0].PrivateKey = testRSAPrivateKey 2029 config.Certificates[0].SignedCertificateTimestamps = [][]byte{[]byte("dummy sct 1"), []byte("dummy sct 2")} 2030 config.Certificates[0].OCSPStaple = []byte("dummy ocsp") 2031 test.configureServer(config, &serverCalled) 2032 2033 err = Server(s, config).Handshake() 2034 s.Close() 2035 done <- err 2036 }() 2037 2038 config := testConfig.Clone() 2039 config.ServerName = "example.golang" 2040 config.RootCAs = rootCAs 2041 config.Time = now 2042 config.MaxVersion = version 2043 test.configureClient(config, &clientCalled) 2044 clientErr := Client(c, config).Handshake() 2045 c.Close() 2046 serverErr := <-done 2047 2048 test.validate(t, i, clientCalled, serverCalled, clientErr, serverErr) 2049 } 2050 } 2051 2052 // brokenConn wraps a net.Conn and causes all Writes after a certain number to 2053 // fail with brokenConnErr. 2054 type brokenConn struct { 2055 net.Conn 2056 2057 // breakAfter is the number of successful writes that will be allowed 2058 // before all subsequent writes fail. 2059 breakAfter int 2060 2061 // numWrites is the number of writes that have been done. 2062 numWrites int 2063 } 2064 2065 // brokenConnErr is the error that brokenConn returns once exhausted. 2066 var brokenConnErr = errors.New("too many writes to brokenConn") 2067 2068 func (b *brokenConn) Write(data []byte) (int, error) { 2069 if b.numWrites >= b.breakAfter { 2070 return 0, brokenConnErr 2071 } 2072 2073 b.numWrites++ 2074 return b.Conn.Write(data) 2075 } 2076 2077 func TestFailedWrite(t *testing.T) { 2078 // Test that a write error during the handshake is returned. 2079 for _, breakAfter := range []int{0, 1} { 2080 c, s := localPipe(t) 2081 done := make(chan bool) 2082 2083 go func() { 2084 Server(s, testConfig).Handshake() 2085 s.Close() 2086 done <- true 2087 }() 2088 2089 brokenC := &brokenConn{Conn: c, breakAfter: breakAfter} 2090 err := Client(brokenC, testConfig).Handshake() 2091 if err != brokenConnErr { 2092 t.Errorf("#%d: expected error from brokenConn but got %q", breakAfter, err) 2093 } 2094 brokenC.Close() 2095 2096 <-done 2097 } 2098 } 2099 2100 // writeCountingConn wraps a net.Conn and counts the number of Write calls. 2101 type writeCountingConn struct { 2102 net.Conn 2103 2104 // numWrites is the number of writes that have been done. 2105 numWrites int 2106 } 2107 2108 func (wcc *writeCountingConn) Write(data []byte) (int, error) { 2109 wcc.numWrites++ 2110 return wcc.Conn.Write(data) 2111 } 2112 2113 func TestBuffering(t *testing.T) { 2114 t.Run("TLSv12", func(t *testing.T) { testBuffering(t, VersionTLS12) }) 2115 t.Run("TLSv13", func(t *testing.T) { testBuffering(t, VersionTLS13) }) 2116 } 2117 2118 func testBuffering(t *testing.T, version uint16) { 2119 c, s := localPipe(t) 2120 done := make(chan bool) 2121 2122 clientWCC := &writeCountingConn{Conn: c} 2123 serverWCC := &writeCountingConn{Conn: s} 2124 2125 go func() { 2126 config := testConfig.Clone() 2127 config.MaxVersion = version 2128 Server(serverWCC, config).Handshake() 2129 serverWCC.Close() 2130 done <- true 2131 }() 2132 2133 err := Client(clientWCC, testConfig).Handshake() 2134 if err != nil { 2135 t.Fatal(err) 2136 } 2137 clientWCC.Close() 2138 <-done 2139 2140 var expectedClient, expectedServer int 2141 if version == VersionTLS13 { 2142 expectedClient = 2 2143 expectedServer = 1 2144 } else { 2145 expectedClient = 2 2146 expectedServer = 2 2147 } 2148 2149 if n := clientWCC.numWrites; n != expectedClient { 2150 t.Errorf("expected client handshake to complete with %d writes, but saw %d", expectedClient, n) 2151 } 2152 2153 if n := serverWCC.numWrites; n != expectedServer { 2154 t.Errorf("expected server handshake to complete with %d writes, but saw %d", expectedServer, n) 2155 } 2156 } 2157 2158 func TestAlertFlushing(t *testing.T) { 2159 c, s := localPipe(t) 2160 done := make(chan bool) 2161 2162 clientWCC := &writeCountingConn{Conn: c} 2163 serverWCC := &writeCountingConn{Conn: s} 2164 2165 serverConfig := testConfig.Clone() 2166 2167 // Cause a signature-time error 2168 brokenKey := rsa.PrivateKey{PublicKey: testRSAPrivateKey.PublicKey} 2169 brokenKey.D = big.NewInt(42) 2170 serverConfig.Certificates = []Certificate{{ 2171 Certificate: [][]byte{testRSACertificate}, 2172 PrivateKey: &brokenKey, 2173 }} 2174 2175 go func() { 2176 Server(serverWCC, serverConfig).Handshake() 2177 serverWCC.Close() 2178 done <- true 2179 }() 2180 2181 err := Client(clientWCC, testConfig).Handshake() 2182 if err == nil { 2183 t.Fatal("client unexpectedly returned no error") 2184 } 2185 2186 const expectedError = "remote error: tls: internal error" 2187 if e := err.Error(); !strings.Contains(e, expectedError) { 2188 t.Fatalf("expected to find %q in error but error was %q", expectedError, e) 2189 } 2190 clientWCC.Close() 2191 <-done 2192 2193 if n := serverWCC.numWrites; n != 1 { 2194 t.Errorf("expected server handshake to complete with one write, but saw %d", n) 2195 } 2196 } 2197 2198 func TestHandshakeRace(t *testing.T) { 2199 if testing.Short() { 2200 t.Skip("skipping in -short mode") 2201 } 2202 t.Parallel() 2203 // This test races a Read and Write to try and complete a handshake in 2204 // order to provide some evidence that there are no races or deadlocks 2205 // in the handshake locking. 2206 for i := 0; i < 32; i++ { 2207 c, s := localPipe(t) 2208 2209 go func() { 2210 server := Server(s, testConfig) 2211 if err := server.Handshake(); err != nil { 2212 panic(err) 2213 } 2214 2215 var request [1]byte 2216 if n, err := server.Read(request[:]); err != nil || n != 1 { 2217 panic(err) 2218 } 2219 2220 server.Write(request[:]) 2221 server.Close() 2222 }() 2223 2224 startWrite := make(chan struct{}) 2225 startRead := make(chan struct{}) 2226 readDone := make(chan struct{}, 1) 2227 2228 client := Client(c, testConfig) 2229 go func() { 2230 <-startWrite 2231 var request [1]byte 2232 client.Write(request[:]) 2233 }() 2234 2235 go func() { 2236 <-startRead 2237 var reply [1]byte 2238 if _, err := io.ReadFull(client, reply[:]); err != nil { 2239 panic(err) 2240 } 2241 c.Close() 2242 readDone <- struct{}{} 2243 }() 2244 2245 if i&1 == 1 { 2246 startWrite <- struct{}{} 2247 startRead <- struct{}{} 2248 } else { 2249 startRead <- struct{}{} 2250 startWrite <- struct{}{} 2251 } 2252 <-readDone 2253 } 2254 } 2255 2256 var getClientCertificateTests = []struct { 2257 setup func(*Config, *Config) 2258 expectedClientError string 2259 verify func(*testing.T, int, *ConnectionState) 2260 }{ 2261 { 2262 func(clientConfig, serverConfig *Config) { 2263 // Returning a Certificate with no certificate data 2264 // should result in an empty message being sent to the 2265 // server. 2266 serverConfig.ClientCAs = nil 2267 clientConfig.GetClientCertificate = func(cri *CertificateRequestInfo) (*Certificate, error) { 2268 if len(cri.SignatureSchemes) == 0 { 2269 panic("empty SignatureSchemes") 2270 } 2271 if len(cri.AcceptableCAs) != 0 { 2272 panic("AcceptableCAs should have been empty") 2273 } 2274 return new(Certificate), nil 2275 } 2276 }, 2277 "", 2278 func(t *testing.T, testNum int, cs *ConnectionState) { 2279 if l := len(cs.PeerCertificates); l != 0 { 2280 t.Errorf("#%d: expected no certificates but got %d", testNum, l) 2281 } 2282 }, 2283 }, 2284 { 2285 func(clientConfig, serverConfig *Config) { 2286 // With TLS 1.1, the SignatureSchemes should be 2287 // synthesised from the supported certificate types. 2288 clientConfig.MaxVersion = VersionTLS11 2289 clientConfig.GetClientCertificate = func(cri *CertificateRequestInfo) (*Certificate, error) { 2290 if len(cri.SignatureSchemes) == 0 { 2291 panic("empty SignatureSchemes") 2292 } 2293 return new(Certificate), nil 2294 } 2295 }, 2296 "", 2297 func(t *testing.T, testNum int, cs *ConnectionState) { 2298 if l := len(cs.PeerCertificates); l != 0 { 2299 t.Errorf("#%d: expected no certificates but got %d", testNum, l) 2300 } 2301 }, 2302 }, 2303 { 2304 func(clientConfig, serverConfig *Config) { 2305 // Returning an error should abort the handshake with 2306 // that error. 2307 clientConfig.GetClientCertificate = func(cri *CertificateRequestInfo) (*Certificate, error) { 2308 return nil, errors.New("GetClientCertificate") 2309 } 2310 }, 2311 "GetClientCertificate", 2312 func(t *testing.T, testNum int, cs *ConnectionState) { 2313 }, 2314 }, 2315 { 2316 func(clientConfig, serverConfig *Config) { 2317 clientConfig.GetClientCertificate = func(cri *CertificateRequestInfo) (*Certificate, error) { 2318 if len(cri.AcceptableCAs) == 0 { 2319 panic("empty AcceptableCAs") 2320 } 2321 cert := &Certificate{ 2322 Certificate: [][]byte{testRSACertificate}, 2323 PrivateKey: testRSAPrivateKey, 2324 } 2325 return cert, nil 2326 } 2327 }, 2328 "", 2329 func(t *testing.T, testNum int, cs *ConnectionState) { 2330 if len(cs.VerifiedChains) == 0 { 2331 t.Errorf("#%d: expected some verified chains, but found none", testNum) 2332 } 2333 }, 2334 }, 2335 } 2336 2337 func TestGetClientCertificate(t *testing.T) { 2338 t.Run("TLSv12", func(t *testing.T) { testGetClientCertificate(t, VersionTLS12) }) 2339 t.Run("TLSv13", func(t *testing.T) { testGetClientCertificate(t, VersionTLS13) }) 2340 } 2341 2342 func testGetClientCertificate(t *testing.T, version uint16) { 2343 issuer, err := x509.ParseCertificate(testRSACertificateIssuer) 2344 if err != nil { 2345 panic(err) 2346 } 2347 2348 for i, test := range getClientCertificateTests { 2349 serverConfig := testConfig.Clone() 2350 serverConfig.ClientAuth = VerifyClientCertIfGiven 2351 serverConfig.RootCAs = x509.NewCertPool() 2352 serverConfig.RootCAs.AddCert(issuer) 2353 serverConfig.ClientCAs = serverConfig.RootCAs 2354 serverConfig.Time = func() time.Time { return time.Unix(1476984729, 0) } 2355 serverConfig.MaxVersion = version 2356 2357 clientConfig := testConfig.Clone() 2358 clientConfig.MaxVersion = version 2359 2360 test.setup(clientConfig, serverConfig) 2361 2362 type serverResult struct { 2363 cs ConnectionState 2364 err error 2365 } 2366 2367 c, s := localPipe(t) 2368 done := make(chan serverResult) 2369 2370 go func() { 2371 defer s.Close() 2372 server := Server(s, serverConfig) 2373 err := server.Handshake() 2374 2375 var cs ConnectionState 2376 if err == nil { 2377 cs = server.ConnectionState() 2378 } 2379 done <- serverResult{cs, err} 2380 }() 2381 2382 clientErr := Client(c, clientConfig).Handshake() 2383 c.Close() 2384 2385 result := <-done 2386 2387 if clientErr != nil { 2388 if len(test.expectedClientError) == 0 { 2389 t.Errorf("#%d: client error: %v", i, clientErr) 2390 } else if got := clientErr.Error(); got != test.expectedClientError { 2391 t.Errorf("#%d: expected client error %q, but got %q", i, test.expectedClientError, got) 2392 } else { 2393 test.verify(t, i, &result.cs) 2394 } 2395 } else if len(test.expectedClientError) > 0 { 2396 t.Errorf("#%d: expected client error %q, but got no error", i, test.expectedClientError) 2397 } else if err := result.err; err != nil { 2398 t.Errorf("#%d: server error: %v", i, err) 2399 } else { 2400 test.verify(t, i, &result.cs) 2401 } 2402 } 2403 } 2404 2405 func TestRSAPSSKeyError(t *testing.T) { 2406 // crypto/tls does not support the rsa_pss_pss_* SignatureSchemes. If support for 2407 // public keys with OID RSASSA-PSS is added to crypto/x509, they will be misused with 2408 // the rsa_pss_rsae_* SignatureSchemes. Assert that RSASSA-PSS certificates don't 2409 // parse, or that they don't carry *rsa.PublicKey keys. 2410 b, _ := pem.Decode([]byte(` 2411 -----BEGIN CERTIFICATE----- 2412 MIIDZTCCAhygAwIBAgIUCF2x0FyTgZG0CC9QTDjGWkB5vgEwPgYJKoZIhvcNAQEK 2413 MDGgDTALBglghkgBZQMEAgGhGjAYBgkqhkiG9w0BAQgwCwYJYIZIAWUDBAIBogQC 2414 AgDeMBIxEDAOBgNVBAMMB1JTQS1QU1MwHhcNMTgwNjI3MjI0NDM2WhcNMTgwNzI3 2415 MjI0NDM2WjASMRAwDgYDVQQDDAdSU0EtUFNTMIIBIDALBgkqhkiG9w0BAQoDggEP 2416 ADCCAQoCggEBANxDm0f76JdI06YzsjB3AmmjIYkwUEGxePlafmIASFjDZl/elD0Z 2417 /a7xLX468b0qGxLS5al7XCcEprSdsDR6DF5L520+pCbpfLyPOjuOvGmk9KzVX4x5 2418 b05YXYuXdsQ0Kjxcx2i3jjCday6scIhMJVgBZxTEyMj1thPQM14SHzKCd/m6HmCL 2419 QmswpH2yMAAcBRWzRpp/vdH5DeOJEB3aelq7094no731mrLUCHRiZ1htq8BDB3ou 2420 czwqgwspbqZ4dnMXl2MvfySQ5wJUxQwILbiuAKO2lVVPUbFXHE9pgtznNoPvKwQT 2421 JNcX8ee8WIZc2SEGzofjk3NpjR+2ADB2u3sCAwEAAaNTMFEwHQYDVR0OBBYEFNEz 2422 AdyJ2f+fU+vSCS6QzohnOnprMB8GA1UdIwQYMBaAFNEzAdyJ2f+fU+vSCS6Qzohn 2423 OnprMA8GA1UdEwEB/wQFMAMBAf8wPgYJKoZIhvcNAQEKMDGgDTALBglghkgBZQME 2424 AgGhGjAYBgkqhkiG9w0BAQgwCwYJYIZIAWUDBAIBogQCAgDeA4IBAQCjEdrR5aab 2425 sZmCwrMeKidXgfkmWvfuLDE+TCbaqDZp7BMWcMQXT9O0UoUT5kqgKj2ARm2pEW0Z 2426 H3Z1vj3bbds72qcDIJXp+l0fekyLGeCrX/CbgnMZXEP7+/+P416p34ChR1Wz4dU1 2427 KD3gdsUuTKKeMUog3plxlxQDhRQmiL25ygH1LmjLd6dtIt0GVRGr8lj3euVeprqZ 2428 bZ3Uq5eLfsn8oPgfC57gpO6yiN+UURRTlK3bgYvLh4VWB3XXk9UaQZ7Mq1tpXjoD 2429 HYFybkWzibkZp4WRo+Fa28rirH+/wHt0vfeN7UCceURZEx4JaxIIfe4ku7uDRhJi 2430 RwBA9Xk1KBNF 2431 -----END CERTIFICATE-----`)) 2432 if b == nil { 2433 t.Fatal("Failed to decode certificate") 2434 } 2435 cert, err := x509.ParseCertificate(b.Bytes) 2436 if err != nil { 2437 return 2438 } 2439 if _, ok := cert.PublicKey.(*rsa.PublicKey); ok { 2440 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") 2441 } 2442 } 2443 2444 func TestCloseClientConnectionOnIdleServer(t *testing.T) { 2445 clientConn, serverConn := localPipe(t) 2446 client := Client(clientConn, testConfig.Clone()) 2447 go func() { 2448 var b [1]byte 2449 serverConn.Read(b[:]) 2450 client.Close() 2451 }() 2452 client.SetWriteDeadline(time.Now().Add(time.Minute)) 2453 err := client.Handshake() 2454 if err != nil { 2455 if err, ok := err.(net.Error); ok && err.Timeout() { 2456 t.Errorf("Expected a closed network connection error but got '%s'", err.Error()) 2457 } 2458 } else { 2459 t.Errorf("Error expected, but no error returned") 2460 } 2461 } 2462 2463 func testDowngradeCanary(t *testing.T, clientVersion, serverVersion uint16) error { 2464 defer func() { testingOnlyForceDowngradeCanary = false }() 2465 testingOnlyForceDowngradeCanary = true 2466 2467 clientConfig := testConfig.Clone() 2468 clientConfig.MaxVersion = clientVersion 2469 serverConfig := testConfig.Clone() 2470 serverConfig.MaxVersion = serverVersion 2471 _, _, err := testHandshake(t, clientConfig, serverConfig) 2472 return err 2473 } 2474 2475 func TestDowngradeCanary(t *testing.T) { 2476 if err := testDowngradeCanary(t, VersionTLS13, VersionTLS12); err == nil { 2477 t.Errorf("downgrade from TLS 1.3 to TLS 1.2 was not detected") 2478 } 2479 if testing.Short() { 2480 t.Skip("skipping the rest of the checks in short mode") 2481 } 2482 if err := testDowngradeCanary(t, VersionTLS13, VersionTLS11); err == nil { 2483 t.Errorf("downgrade from TLS 1.3 to TLS 1.1 was not detected") 2484 } 2485 if err := testDowngradeCanary(t, VersionTLS13, VersionTLS10); err == nil { 2486 t.Errorf("downgrade from TLS 1.3 to TLS 1.0 was not detected") 2487 } 2488 if err := testDowngradeCanary(t, VersionTLS12, VersionTLS11); err == nil { 2489 t.Errorf("downgrade from TLS 1.2 to TLS 1.1 was not detected") 2490 } 2491 if err := testDowngradeCanary(t, VersionTLS12, VersionTLS10); err == nil { 2492 t.Errorf("downgrade from TLS 1.2 to TLS 1.0 was not detected") 2493 } 2494 if err := testDowngradeCanary(t, VersionTLS13, VersionTLS13); err != nil { 2495 t.Errorf("server unexpectedly sent downgrade canary for TLS 1.3") 2496 } 2497 if err := testDowngradeCanary(t, VersionTLS12, VersionTLS12); err != nil { 2498 t.Errorf("client didn't ignore expected TLS 1.2 canary") 2499 } 2500 if err := testDowngradeCanary(t, VersionTLS11, VersionTLS11); err != nil { 2501 t.Errorf("client unexpectedly reacted to a canary in TLS 1.1") 2502 } 2503 if err := testDowngradeCanary(t, VersionTLS10, VersionTLS10); err != nil { 2504 t.Errorf("client unexpectedly reacted to a canary in TLS 1.0") 2505 } 2506 } 2507 2508 func TestResumptionKeepsOCSPAndSCT(t *testing.T) { 2509 t.Run("TLSv12", func(t *testing.T) { testResumptionKeepsOCSPAndSCT(t, VersionTLS12) }) 2510 t.Run("TLSv13", func(t *testing.T) { testResumptionKeepsOCSPAndSCT(t, VersionTLS13) }) 2511 } 2512 2513 func testResumptionKeepsOCSPAndSCT(t *testing.T, ver uint16) { 2514 issuer, err := x509.ParseCertificate(testRSACertificateIssuer) 2515 if err != nil { 2516 t.Fatalf("failed to parse test issuer") 2517 } 2518 roots := x509.NewCertPool() 2519 roots.AddCert(issuer) 2520 clientConfig := &Config{ 2521 MaxVersion: ver, 2522 ClientSessionCache: NewLRUClientSessionCache(32), 2523 ServerName: "example.golang", 2524 RootCAs: roots, 2525 } 2526 serverConfig := testConfig.Clone() 2527 serverConfig.MaxVersion = ver 2528 serverConfig.Certificates[0].OCSPStaple = []byte{1, 2, 3} 2529 serverConfig.Certificates[0].SignedCertificateTimestamps = [][]byte{{4, 5, 6}} 2530 2531 _, ccs, err := testHandshake(t, clientConfig, serverConfig) 2532 if err != nil { 2533 t.Fatalf("handshake failed: %s", err) 2534 } 2535 // after a new session we expect to see OCSPResponse and 2536 // SignedCertificateTimestamps populated as usual 2537 if !bytes.Equal(ccs.OCSPResponse, serverConfig.Certificates[0].OCSPStaple) { 2538 t.Errorf("client ConnectionState contained unexpected OCSPResponse: wanted %v, got %v", 2539 serverConfig.Certificates[0].OCSPStaple, ccs.OCSPResponse) 2540 } 2541 if !reflect.DeepEqual(ccs.SignedCertificateTimestamps, serverConfig.Certificates[0].SignedCertificateTimestamps) { 2542 t.Errorf("client ConnectionState contained unexpected SignedCertificateTimestamps: wanted %v, got %v", 2543 serverConfig.Certificates[0].SignedCertificateTimestamps, ccs.SignedCertificateTimestamps) 2544 } 2545 2546 // if the server doesn't send any SCTs, repopulate the old SCTs 2547 oldSCTs := serverConfig.Certificates[0].SignedCertificateTimestamps 2548 serverConfig.Certificates[0].SignedCertificateTimestamps = nil 2549 _, ccs, err = testHandshake(t, clientConfig, serverConfig) 2550 if err != nil { 2551 t.Fatalf("handshake failed: %s", err) 2552 } 2553 if !ccs.DidResume { 2554 t.Fatalf("expected session to be resumed") 2555 } 2556 // after a resumed session we also expect to see OCSPResponse 2557 // and SignedCertificateTimestamps populated 2558 if !bytes.Equal(ccs.OCSPResponse, serverConfig.Certificates[0].OCSPStaple) { 2559 t.Errorf("client ConnectionState contained unexpected OCSPResponse after resumption: wanted %v, got %v", 2560 serverConfig.Certificates[0].OCSPStaple, ccs.OCSPResponse) 2561 } 2562 if !reflect.DeepEqual(ccs.SignedCertificateTimestamps, oldSCTs) { 2563 t.Errorf("client ConnectionState contained unexpected SignedCertificateTimestamps after resumption: wanted %v, got %v", 2564 oldSCTs, ccs.SignedCertificateTimestamps) 2565 } 2566 2567 // Only test overriding the SCTs for TLS 1.2, since in 1.3 2568 // the server won't send the message containing them 2569 if ver == VersionTLS13 { 2570 return 2571 } 2572 2573 // if the server changes the SCTs it sends, they should override the saved SCTs 2574 serverConfig.Certificates[0].SignedCertificateTimestamps = [][]byte{{7, 8, 9}} 2575 _, ccs, err = testHandshake(t, clientConfig, serverConfig) 2576 if err != nil { 2577 t.Fatalf("handshake failed: %s", err) 2578 } 2579 if !ccs.DidResume { 2580 t.Fatalf("expected session to be resumed") 2581 } 2582 if !reflect.DeepEqual(ccs.SignedCertificateTimestamps, serverConfig.Certificates[0].SignedCertificateTimestamps) { 2583 t.Errorf("client ConnectionState contained unexpected SignedCertificateTimestamps after resumption: wanted %v, got %v", 2584 serverConfig.Certificates[0].SignedCertificateTimestamps, ccs.SignedCertificateTimestamps) 2585 } 2586 } 2587 2588 // TestClientHandshakeContextCancellation tests that canceling 2589 // the context given to the client side conn.HandshakeContext 2590 // interrupts the in-progress handshake. 2591 func TestClientHandshakeContextCancellation(t *testing.T) { 2592 c, s := localPipe(t) 2593 ctx, cancel := context.WithCancel(context.Background()) 2594 unblockServer := make(chan struct{}) 2595 defer close(unblockServer) 2596 go func() { 2597 cancel() 2598 <-unblockServer 2599 _ = s.Close() 2600 }() 2601 cli := Client(c, testConfig) 2602 // Initiates client side handshake, which will block until the client hello is read 2603 // by the server, unless the cancellation works. 2604 err := cli.HandshakeContext(ctx) 2605 if err == nil { 2606 t.Fatal("Client handshake did not error when the context was canceled") 2607 } 2608 if err != context.Canceled { 2609 t.Errorf("Unexpected client handshake error: %v", err) 2610 } 2611 if runtime.GOARCH == "wasm" { 2612 t.Skip("conn.Close does not error as expected when called multiple times on WASM") 2613 } 2614 err = cli.Close() 2615 if err == nil { 2616 t.Error("Client connection was not closed when the context was canceled") 2617 } 2618 }