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