github.com/ice-blockchain/go/src@v0.0.0-20240403114104-1564d284e521/crypto/tls/handshake_server_test.go (about) 1 // Copyright 2009 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" 11 "crypto/ecdh" 12 "crypto/elliptic" 13 "crypto/rand" 14 "crypto/x509" 15 "encoding/pem" 16 "errors" 17 "fmt" 18 "io" 19 "net" 20 "os" 21 "os/exec" 22 "path/filepath" 23 "runtime" 24 "strings" 25 "testing" 26 "time" 27 ) 28 29 func testClientHello(t *testing.T, serverConfig *Config, m handshakeMessage) { 30 testClientHelloFailure(t, serverConfig, m, "") 31 } 32 33 // testFatal is a hack to prevent the compiler from complaining that there is a 34 // call to t.Fatal from a non-test goroutine 35 func testFatal(t *testing.T, err error) { 36 t.Helper() 37 t.Fatal(err) 38 } 39 40 func testClientHelloFailure(t *testing.T, serverConfig *Config, m handshakeMessage, expectedSubStr string) { 41 c, s := localPipe(t) 42 go func() { 43 cli := Client(c, testConfig) 44 if ch, ok := m.(*clientHelloMsg); ok { 45 cli.vers = ch.vers 46 } 47 if _, err := cli.writeHandshakeRecord(m, nil); err != nil { 48 testFatal(t, err) 49 } 50 c.Close() 51 }() 52 ctx := context.Background() 53 conn := Server(s, serverConfig) 54 ch, err := conn.readClientHello(ctx) 55 hs := serverHandshakeState{ 56 c: conn, 57 ctx: ctx, 58 clientHello: ch, 59 } 60 if err == nil { 61 err = hs.processClientHello() 62 } 63 if err == nil { 64 err = hs.pickCipherSuite() 65 } 66 s.Close() 67 if len(expectedSubStr) == 0 { 68 if err != nil && err != io.EOF { 69 t.Errorf("Got error: %s; expected to succeed", err) 70 } 71 } else if err == nil || !strings.Contains(err.Error(), expectedSubStr) { 72 t.Errorf("Got error: %v; expected to match substring '%s'", err, expectedSubStr) 73 } 74 } 75 76 func TestSimpleError(t *testing.T) { 77 testClientHelloFailure(t, testConfig, &serverHelloDoneMsg{}, "unexpected handshake message") 78 } 79 80 var badProtocolVersions = []uint16{0x0000, 0x0005, 0x0100, 0x0105, 0x0200, 0x0205, VersionSSL30} 81 82 func TestRejectBadProtocolVersion(t *testing.T) { 83 config := testConfig.Clone() 84 config.MinVersion = VersionSSL30 85 for _, v := range badProtocolVersions { 86 testClientHelloFailure(t, config, &clientHelloMsg{ 87 vers: v, 88 random: make([]byte, 32), 89 }, "unsupported versions") 90 } 91 testClientHelloFailure(t, config, &clientHelloMsg{ 92 vers: VersionTLS12, 93 supportedVersions: badProtocolVersions, 94 random: make([]byte, 32), 95 }, "unsupported versions") 96 } 97 98 func TestNoSuiteOverlap(t *testing.T) { 99 clientHello := &clientHelloMsg{ 100 vers: VersionTLS10, 101 random: make([]byte, 32), 102 cipherSuites: []uint16{0xff00}, 103 compressionMethods: []uint8{compressionNone}, 104 } 105 testClientHelloFailure(t, testConfig, clientHello, "no cipher suite supported by both client and server") 106 } 107 108 func TestNoCompressionOverlap(t *testing.T) { 109 clientHello := &clientHelloMsg{ 110 vers: VersionTLS10, 111 random: make([]byte, 32), 112 cipherSuites: []uint16{TLS_RSA_WITH_RC4_128_SHA}, 113 compressionMethods: []uint8{0xff}, 114 } 115 testClientHelloFailure(t, testConfig, clientHello, "client does not support uncompressed connections") 116 } 117 118 func TestNoRC4ByDefault(t *testing.T) { 119 clientHello := &clientHelloMsg{ 120 vers: VersionTLS10, 121 random: make([]byte, 32), 122 cipherSuites: []uint16{TLS_RSA_WITH_RC4_128_SHA}, 123 compressionMethods: []uint8{compressionNone}, 124 } 125 serverConfig := testConfig.Clone() 126 // Reset the enabled cipher suites to nil in order to test the 127 // defaults. 128 serverConfig.CipherSuites = nil 129 testClientHelloFailure(t, serverConfig, clientHello, "no cipher suite supported by both client and server") 130 } 131 132 func TestRejectSNIWithTrailingDot(t *testing.T) { 133 testClientHelloFailure(t, testConfig, &clientHelloMsg{ 134 vers: VersionTLS12, 135 random: make([]byte, 32), 136 serverName: "foo.com.", 137 }, "unexpected message") 138 } 139 140 func TestDontSelectECDSAWithRSAKey(t *testing.T) { 141 // Test that, even when both sides support an ECDSA cipher suite, it 142 // won't be selected if the server's private key doesn't support it. 143 clientHello := &clientHelloMsg{ 144 vers: VersionTLS10, 145 random: make([]byte, 32), 146 cipherSuites: []uint16{TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA}, 147 compressionMethods: []uint8{compressionNone}, 148 supportedCurves: []CurveID{CurveP256}, 149 supportedPoints: []uint8{pointFormatUncompressed}, 150 } 151 serverConfig := testConfig.Clone() 152 serverConfig.CipherSuites = clientHello.cipherSuites 153 serverConfig.Certificates = make([]Certificate, 1) 154 serverConfig.Certificates[0].Certificate = [][]byte{testECDSACertificate} 155 serverConfig.Certificates[0].PrivateKey = testECDSAPrivateKey 156 serverConfig.BuildNameToCertificate() 157 // First test that it *does* work when the server's key is ECDSA. 158 testClientHello(t, serverConfig, clientHello) 159 160 // Now test that switching to an RSA key causes the expected error (and 161 // not an internal error about a signing failure). 162 serverConfig.Certificates = testConfig.Certificates 163 testClientHelloFailure(t, serverConfig, clientHello, "no cipher suite supported by both client and server") 164 } 165 166 func TestDontSelectRSAWithECDSAKey(t *testing.T) { 167 // Test that, even when both sides support an RSA cipher suite, it 168 // won't be selected if the server's private key doesn't support it. 169 clientHello := &clientHelloMsg{ 170 vers: VersionTLS10, 171 random: make([]byte, 32), 172 cipherSuites: []uint16{TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA}, 173 compressionMethods: []uint8{compressionNone}, 174 supportedCurves: []CurveID{CurveP256}, 175 supportedPoints: []uint8{pointFormatUncompressed}, 176 } 177 serverConfig := testConfig.Clone() 178 serverConfig.CipherSuites = clientHello.cipherSuites 179 // First test that it *does* work when the server's key is RSA. 180 testClientHello(t, serverConfig, clientHello) 181 182 // Now test that switching to an ECDSA key causes the expected error 183 // (and not an internal error about a signing failure). 184 serverConfig.Certificates = make([]Certificate, 1) 185 serverConfig.Certificates[0].Certificate = [][]byte{testECDSACertificate} 186 serverConfig.Certificates[0].PrivateKey = testECDSAPrivateKey 187 serverConfig.BuildNameToCertificate() 188 testClientHelloFailure(t, serverConfig, clientHello, "no cipher suite supported by both client and server") 189 } 190 191 func TestRenegotiationExtension(t *testing.T) { 192 clientHello := &clientHelloMsg{ 193 vers: VersionTLS12, 194 compressionMethods: []uint8{compressionNone}, 195 random: make([]byte, 32), 196 secureRenegotiationSupported: true, 197 cipherSuites: []uint16{TLS_RSA_WITH_RC4_128_SHA}, 198 } 199 200 bufChan := make(chan []byte, 1) 201 c, s := localPipe(t) 202 203 go func() { 204 cli := Client(c, testConfig) 205 cli.vers = clientHello.vers 206 if _, err := cli.writeHandshakeRecord(clientHello, nil); err != nil { 207 testFatal(t, err) 208 } 209 210 buf := make([]byte, 1024) 211 n, err := c.Read(buf) 212 if err != nil { 213 t.Errorf("Server read returned error: %s", err) 214 return 215 } 216 c.Close() 217 bufChan <- buf[:n] 218 }() 219 220 Server(s, testConfig).Handshake() 221 buf := <-bufChan 222 223 if len(buf) < 5+4 { 224 t.Fatalf("Server returned short message of length %d", len(buf)) 225 } 226 // buf contains a TLS record, with a 5 byte record header and a 4 byte 227 // handshake header. The length of the ServerHello is taken from the 228 // handshake header. 229 serverHelloLen := int(buf[6])<<16 | int(buf[7])<<8 | int(buf[8]) 230 231 var serverHello serverHelloMsg 232 // unmarshal expects to be given the handshake header, but 233 // serverHelloLen doesn't include it. 234 if !serverHello.unmarshal(buf[5 : 9+serverHelloLen]) { 235 t.Fatalf("Failed to parse ServerHello") 236 } 237 238 if !serverHello.secureRenegotiationSupported { 239 t.Errorf("Secure renegotiation extension was not echoed.") 240 } 241 } 242 243 func TestTLS12OnlyCipherSuites(t *testing.T) { 244 // Test that a Server doesn't select a TLS 1.2-only cipher suite when 245 // the client negotiates TLS 1.1. 246 clientHello := &clientHelloMsg{ 247 vers: VersionTLS11, 248 random: make([]byte, 32), 249 cipherSuites: []uint16{ 250 // The Server, by default, will use the client's 251 // preference order. So the GCM cipher suite 252 // will be selected unless it's excluded because 253 // of the version in this ClientHello. 254 TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, 255 TLS_RSA_WITH_RC4_128_SHA, 256 }, 257 compressionMethods: []uint8{compressionNone}, 258 supportedCurves: []CurveID{CurveP256, CurveP384, CurveP521}, 259 supportedPoints: []uint8{pointFormatUncompressed}, 260 } 261 262 c, s := localPipe(t) 263 replyChan := make(chan any) 264 go func() { 265 cli := Client(c, testConfig) 266 cli.vers = clientHello.vers 267 if _, err := cli.writeHandshakeRecord(clientHello, nil); err != nil { 268 testFatal(t, err) 269 } 270 reply, err := cli.readHandshake(nil) 271 c.Close() 272 if err != nil { 273 replyChan <- err 274 } else { 275 replyChan <- reply 276 } 277 }() 278 config := testConfig.Clone() 279 config.CipherSuites = clientHello.cipherSuites 280 Server(s, config).Handshake() 281 s.Close() 282 reply := <-replyChan 283 if err, ok := reply.(error); ok { 284 t.Fatal(err) 285 } 286 serverHello, ok := reply.(*serverHelloMsg) 287 if !ok { 288 t.Fatalf("didn't get ServerHello message in reply. Got %v\n", reply) 289 } 290 if s := serverHello.cipherSuite; s != TLS_RSA_WITH_RC4_128_SHA { 291 t.Fatalf("bad cipher suite from server: %x", s) 292 } 293 } 294 295 func TestTLSPointFormats(t *testing.T) { 296 // Test that a Server returns the ec_point_format extension when ECC is 297 // negotiated, and not on a RSA handshake or if ec_point_format is missing. 298 tests := []struct { 299 name string 300 cipherSuites []uint16 301 supportedCurves []CurveID 302 supportedPoints []uint8 303 wantSupportedPoints bool 304 }{ 305 {"ECC", []uint16{TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA}, []CurveID{CurveP256}, []uint8{pointFormatUncompressed}, true}, 306 {"ECC without ec_point_format", []uint16{TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA}, []CurveID{CurveP256}, nil, false}, 307 {"ECC with extra values", []uint16{TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA}, []CurveID{CurveP256}, []uint8{13, 37, pointFormatUncompressed, 42}, true}, 308 {"RSA", []uint16{TLS_RSA_WITH_AES_256_GCM_SHA384}, nil, nil, false}, 309 {"RSA with ec_point_format", []uint16{TLS_RSA_WITH_AES_256_GCM_SHA384}, nil, []uint8{pointFormatUncompressed}, false}, 310 } 311 for _, tt := range tests { 312 t.Run(tt.name, func(t *testing.T) { 313 clientHello := &clientHelloMsg{ 314 vers: VersionTLS12, 315 random: make([]byte, 32), 316 cipherSuites: tt.cipherSuites, 317 compressionMethods: []uint8{compressionNone}, 318 supportedCurves: tt.supportedCurves, 319 supportedPoints: tt.supportedPoints, 320 } 321 322 c, s := localPipe(t) 323 replyChan := make(chan any) 324 go func() { 325 cli := Client(c, testConfig) 326 cli.vers = clientHello.vers 327 if _, err := cli.writeHandshakeRecord(clientHello, nil); err != nil { 328 testFatal(t, err) 329 } 330 reply, err := cli.readHandshake(nil) 331 c.Close() 332 if err != nil { 333 replyChan <- err 334 } else { 335 replyChan <- reply 336 } 337 }() 338 config := testConfig.Clone() 339 config.CipherSuites = clientHello.cipherSuites 340 Server(s, config).Handshake() 341 s.Close() 342 reply := <-replyChan 343 if err, ok := reply.(error); ok { 344 t.Fatal(err) 345 } 346 serverHello, ok := reply.(*serverHelloMsg) 347 if !ok { 348 t.Fatalf("didn't get ServerHello message in reply. Got %v\n", reply) 349 } 350 if tt.wantSupportedPoints { 351 if !bytes.Equal(serverHello.supportedPoints, []uint8{pointFormatUncompressed}) { 352 t.Fatal("incorrect ec_point_format extension from server") 353 } 354 } else { 355 if len(serverHello.supportedPoints) != 0 { 356 t.Fatalf("unexpected ec_point_format extension from server: %v", serverHello.supportedPoints) 357 } 358 } 359 }) 360 } 361 } 362 363 func TestAlertForwarding(t *testing.T) { 364 c, s := localPipe(t) 365 go func() { 366 Client(c, testConfig).sendAlert(alertUnknownCA) 367 c.Close() 368 }() 369 370 err := Server(s, testConfig).Handshake() 371 s.Close() 372 var opErr *net.OpError 373 if !errors.As(err, &opErr) || opErr.Err != error(alertUnknownCA) { 374 t.Errorf("Got error: %s; expected: %s", err, error(alertUnknownCA)) 375 } 376 } 377 378 func TestClose(t *testing.T) { 379 c, s := localPipe(t) 380 go c.Close() 381 382 err := Server(s, testConfig).Handshake() 383 s.Close() 384 if err != io.EOF { 385 t.Errorf("Got error: %s; expected: %s", err, io.EOF) 386 } 387 } 388 389 func TestVersion(t *testing.T) { 390 serverConfig := &Config{ 391 Certificates: testConfig.Certificates, 392 MaxVersion: VersionTLS13, 393 } 394 clientConfig := &Config{ 395 InsecureSkipVerify: true, 396 MinVersion: VersionTLS12, 397 } 398 state, _, err := testHandshake(t, clientConfig, serverConfig) 399 if err != nil { 400 t.Fatalf("handshake failed: %s", err) 401 } 402 if state.Version != VersionTLS13 { 403 t.Fatalf("incorrect version %x, should be %x", state.Version, VersionTLS11) 404 } 405 406 clientConfig.MinVersion = 0 407 serverConfig.MaxVersion = VersionTLS11 408 _, _, err = testHandshake(t, clientConfig, serverConfig) 409 if err == nil { 410 t.Fatalf("expected failure to connect with TLS 1.0/1.1") 411 } 412 } 413 414 func TestCipherSuitePreference(t *testing.T) { 415 serverConfig := &Config{ 416 CipherSuites: []uint16{TLS_RSA_WITH_RC4_128_SHA, TLS_AES_128_GCM_SHA256, 417 TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256}, 418 Certificates: testConfig.Certificates, 419 MaxVersion: VersionTLS12, 420 GetConfigForClient: func(chi *ClientHelloInfo) (*Config, error) { 421 if chi.CipherSuites[0] != TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256 { 422 t.Error("the advertised order should not depend on Config.CipherSuites") 423 } 424 if len(chi.CipherSuites) != 2+len(defaultCipherSuitesTLS13) { 425 t.Error("the advertised TLS 1.2 suites should be filtered by Config.CipherSuites") 426 } 427 return nil, nil 428 }, 429 } 430 clientConfig := &Config{ 431 CipherSuites: []uint16{TLS_RSA_WITH_AES_128_CBC_SHA, TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256}, 432 InsecureSkipVerify: true, 433 } 434 state, _, err := testHandshake(t, clientConfig, serverConfig) 435 if err != nil { 436 t.Fatalf("handshake failed: %s", err) 437 } 438 if state.CipherSuite != TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256 { 439 t.Error("the preference order should not depend on Config.CipherSuites") 440 } 441 } 442 443 func TestSCTHandshake(t *testing.T) { 444 t.Run("TLSv12", func(t *testing.T) { testSCTHandshake(t, VersionTLS12) }) 445 t.Run("TLSv13", func(t *testing.T) { testSCTHandshake(t, VersionTLS13) }) 446 } 447 448 func testSCTHandshake(t *testing.T, version uint16) { 449 expected := [][]byte{[]byte("certificate"), []byte("transparency")} 450 serverConfig := &Config{ 451 Certificates: []Certificate{{ 452 Certificate: [][]byte{testRSACertificate}, 453 PrivateKey: testRSAPrivateKey, 454 SignedCertificateTimestamps: expected, 455 }}, 456 MaxVersion: version, 457 } 458 clientConfig := &Config{ 459 InsecureSkipVerify: true, 460 } 461 _, state, err := testHandshake(t, clientConfig, serverConfig) 462 if err != nil { 463 t.Fatalf("handshake failed: %s", err) 464 } 465 actual := state.SignedCertificateTimestamps 466 if len(actual) != len(expected) { 467 t.Fatalf("got %d scts, want %d", len(actual), len(expected)) 468 } 469 for i, sct := range expected { 470 if !bytes.Equal(sct, actual[i]) { 471 t.Fatalf("SCT #%d was %x, but expected %x", i, actual[i], sct) 472 } 473 } 474 } 475 476 func TestCrossVersionResume(t *testing.T) { 477 t.Run("TLSv12", func(t *testing.T) { testCrossVersionResume(t, VersionTLS12) }) 478 t.Run("TLSv13", func(t *testing.T) { testCrossVersionResume(t, VersionTLS13) }) 479 } 480 481 func testCrossVersionResume(t *testing.T, version uint16) { 482 serverConfig := &Config{ 483 CipherSuites: []uint16{TLS_RSA_WITH_AES_128_CBC_SHA}, 484 Certificates: testConfig.Certificates, 485 } 486 clientConfig := &Config{ 487 CipherSuites: []uint16{TLS_RSA_WITH_AES_128_CBC_SHA}, 488 InsecureSkipVerify: true, 489 ClientSessionCache: NewLRUClientSessionCache(1), 490 ServerName: "servername", 491 MinVersion: VersionTLS12, 492 } 493 494 // Establish a session at TLS 1.3. 495 clientConfig.MaxVersion = VersionTLS13 496 _, _, err := testHandshake(t, clientConfig, serverConfig) 497 if err != nil { 498 t.Fatalf("handshake failed: %s", err) 499 } 500 501 // The client session cache now contains a TLS 1.3 session. 502 state, _, err := testHandshake(t, clientConfig, serverConfig) 503 if err != nil { 504 t.Fatalf("handshake failed: %s", err) 505 } 506 if !state.DidResume { 507 t.Fatalf("handshake did not resume at the same version") 508 } 509 510 // Test that the server will decline to resume at a lower version. 511 clientConfig.MaxVersion = VersionTLS12 512 state, _, err = testHandshake(t, clientConfig, serverConfig) 513 if err != nil { 514 t.Fatalf("handshake failed: %s", err) 515 } 516 if state.DidResume { 517 t.Fatalf("handshake resumed at a lower version") 518 } 519 520 // The client session cache now contains a TLS 1.2 session. 521 state, _, err = testHandshake(t, clientConfig, serverConfig) 522 if err != nil { 523 t.Fatalf("handshake failed: %s", err) 524 } 525 if !state.DidResume { 526 t.Fatalf("handshake did not resume at the same version") 527 } 528 529 // Test that the server will decline to resume at a higher version. 530 clientConfig.MaxVersion = VersionTLS13 531 state, _, err = testHandshake(t, clientConfig, serverConfig) 532 if err != nil { 533 t.Fatalf("handshake failed: %s", err) 534 } 535 if state.DidResume { 536 t.Fatalf("handshake resumed at a higher version") 537 } 538 } 539 540 // Note: see comment in handshake_test.go for details of how the reference 541 // tests work. 542 543 // serverTest represents a test of the TLS server handshake against a reference 544 // implementation. 545 type serverTest struct { 546 // name is a freeform string identifying the test and the file in which 547 // the expected results will be stored. 548 name string 549 // command, if not empty, contains a series of arguments for the 550 // command to run for the reference server. 551 command []string 552 // expectedPeerCerts contains a list of PEM blocks of expected 553 // certificates from the client. 554 expectedPeerCerts []string 555 // config, if not nil, contains a custom Config to use for this test. 556 config *Config 557 // expectHandshakeErrorIncluding, when not empty, contains a string 558 // that must be a substring of the error resulting from the handshake. 559 expectHandshakeErrorIncluding string 560 // validate, if not nil, is a function that will be called with the 561 // ConnectionState of the resulting connection. It returns false if the 562 // ConnectionState is unacceptable. 563 validate func(ConnectionState) error 564 // wait, if true, prevents this subtest from calling t.Parallel. 565 // If false, runServerTest* returns immediately. 566 wait bool 567 } 568 569 var defaultClientCommand = []string{"openssl", "s_client", "-no_ticket"} 570 571 // connFromCommand starts opens a listening socket and starts the reference 572 // client to connect to it. It returns a recordingConn that wraps the resulting 573 // connection. 574 func (test *serverTest) connFromCommand() (conn *recordingConn, child *exec.Cmd, err error) { 575 l, err := net.ListenTCP("tcp", &net.TCPAddr{ 576 IP: net.IPv4(127, 0, 0, 1), 577 Port: 0, 578 }) 579 if err != nil { 580 return nil, nil, err 581 } 582 defer l.Close() 583 584 port := l.Addr().(*net.TCPAddr).Port 585 586 var command []string 587 command = append(command, test.command...) 588 if len(command) == 0 { 589 command = defaultClientCommand 590 } 591 command = append(command, "-connect") 592 command = append(command, fmt.Sprintf("127.0.0.1:%d", port)) 593 cmd := exec.Command(command[0], command[1:]...) 594 cmd.Stdin = nil 595 var output bytes.Buffer 596 cmd.Stdout = &output 597 cmd.Stderr = &output 598 if err := cmd.Start(); err != nil { 599 return nil, nil, err 600 } 601 602 connChan := make(chan any, 1) 603 go func() { 604 tcpConn, err := l.Accept() 605 if err != nil { 606 connChan <- err 607 return 608 } 609 connChan <- tcpConn 610 }() 611 612 var tcpConn net.Conn 613 select { 614 case connOrError := <-connChan: 615 if err, ok := connOrError.(error); ok { 616 return nil, nil, err 617 } 618 tcpConn = connOrError.(net.Conn) 619 case <-time.After(2 * time.Second): 620 return nil, nil, errors.New("timed out waiting for connection from child process") 621 } 622 623 record := &recordingConn{ 624 Conn: tcpConn, 625 } 626 627 return record, cmd, nil 628 } 629 630 func (test *serverTest) dataPath() string { 631 return filepath.Join("testdata", "Server-"+test.name) 632 } 633 634 func (test *serverTest) loadData() (flows [][]byte, err error) { 635 in, err := os.Open(test.dataPath()) 636 if err != nil { 637 return nil, err 638 } 639 defer in.Close() 640 return parseTestData(in) 641 } 642 643 func (test *serverTest) run(t *testing.T, write bool) { 644 var clientConn, serverConn net.Conn 645 var recordingConn *recordingConn 646 var childProcess *exec.Cmd 647 648 if write { 649 var err error 650 recordingConn, childProcess, err = test.connFromCommand() 651 if err != nil { 652 t.Fatalf("Failed to start subcommand: %s", err) 653 } 654 serverConn = recordingConn 655 defer func() { 656 if t.Failed() { 657 t.Logf("OpenSSL output:\n\n%s", childProcess.Stdout) 658 } 659 }() 660 } else { 661 clientConn, serverConn = localPipe(t) 662 } 663 config := test.config 664 if config == nil { 665 config = testConfig 666 } 667 server := Server(serverConn, config) 668 connStateChan := make(chan ConnectionState, 1) 669 go func() { 670 _, err := server.Write([]byte("hello, world\n")) 671 if len(test.expectHandshakeErrorIncluding) > 0 { 672 if err == nil { 673 t.Errorf("Error expected, but no error returned") 674 } else if s := err.Error(); !strings.Contains(s, test.expectHandshakeErrorIncluding) { 675 t.Errorf("Error expected containing '%s' but got '%s'", test.expectHandshakeErrorIncluding, s) 676 } 677 } else { 678 if err != nil { 679 t.Logf("Error from Server.Write: '%s'", err) 680 } 681 } 682 server.Close() 683 serverConn.Close() 684 connStateChan <- server.ConnectionState() 685 }() 686 687 if !write { 688 flows, err := test.loadData() 689 if err != nil { 690 t.Fatalf("%s: failed to load data from %s", test.name, test.dataPath()) 691 } 692 for i, b := range flows { 693 if i%2 == 0 { 694 if *fast { 695 clientConn.SetWriteDeadline(time.Now().Add(1 * time.Second)) 696 } else { 697 clientConn.SetWriteDeadline(time.Now().Add(1 * time.Minute)) 698 } 699 clientConn.Write(b) 700 continue 701 } 702 bb := make([]byte, len(b)) 703 if *fast { 704 clientConn.SetReadDeadline(time.Now().Add(1 * time.Second)) 705 } else { 706 clientConn.SetReadDeadline(time.Now().Add(1 * time.Minute)) 707 } 708 n, err := io.ReadFull(clientConn, bb) 709 if err != nil { 710 t.Fatalf("%s #%d: %s\nRead %d, wanted %d, got %x, wanted %x\n", test.name, i+1, err, n, len(bb), bb[:n], b) 711 } 712 if !bytes.Equal(b, bb) { 713 t.Fatalf("%s #%d: mismatch on read: got:%x want:%x", test.name, i+1, bb, b) 714 } 715 } 716 clientConn.Close() 717 } 718 719 connState := <-connStateChan 720 peerCerts := connState.PeerCertificates 721 if len(peerCerts) == len(test.expectedPeerCerts) { 722 for i, peerCert := range peerCerts { 723 block, _ := pem.Decode([]byte(test.expectedPeerCerts[i])) 724 if !bytes.Equal(block.Bytes, peerCert.Raw) { 725 t.Fatalf("%s: mismatch on peer cert %d", test.name, i+1) 726 } 727 } 728 } else { 729 t.Fatalf("%s: mismatch on peer list length: %d (wanted) != %d (got)", test.name, len(test.expectedPeerCerts), len(peerCerts)) 730 } 731 732 if test.validate != nil { 733 if err := test.validate(connState); err != nil { 734 t.Fatalf("validate callback returned error: %s", err) 735 } 736 } 737 738 if write { 739 path := test.dataPath() 740 out, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644) 741 if err != nil { 742 t.Fatalf("Failed to create output file: %s", err) 743 } 744 defer out.Close() 745 recordingConn.Close() 746 if len(recordingConn.flows) < 3 { 747 if len(test.expectHandshakeErrorIncluding) == 0 { 748 t.Fatalf("Handshake failed") 749 } 750 } 751 recordingConn.WriteTo(out) 752 t.Logf("Wrote %s\n", path) 753 childProcess.Wait() 754 } 755 } 756 757 func runServerTestForVersion(t *testing.T, template *serverTest, version, option string) { 758 // Make a deep copy of the template before going parallel. 759 test := *template 760 if template.config != nil { 761 test.config = template.config.Clone() 762 } 763 test.name = version + "-" + test.name 764 if len(test.command) == 0 { 765 test.command = defaultClientCommand 766 } 767 test.command = append([]string(nil), test.command...) 768 test.command = append(test.command, option) 769 770 runTestAndUpdateIfNeeded(t, version, test.run, test.wait) 771 } 772 773 func runServerTestTLS10(t *testing.T, template *serverTest) { 774 runServerTestForVersion(t, template, "TLSv10", "-tls1") 775 } 776 777 func runServerTestTLS11(t *testing.T, template *serverTest) { 778 runServerTestForVersion(t, template, "TLSv11", "-tls1_1") 779 } 780 781 func runServerTestTLS12(t *testing.T, template *serverTest) { 782 runServerTestForVersion(t, template, "TLSv12", "-tls1_2") 783 } 784 785 func runServerTestTLS13(t *testing.T, template *serverTest) { 786 runServerTestForVersion(t, template, "TLSv13", "-tls1_3") 787 } 788 789 func TestHandshakeServerRSARC4(t *testing.T) { 790 test := &serverTest{ 791 name: "RSA-RC4", 792 command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "RC4-SHA"}, 793 } 794 runServerTestTLS10(t, test) 795 runServerTestTLS11(t, test) 796 runServerTestTLS12(t, test) 797 } 798 799 func TestHandshakeServerRSA3DES(t *testing.T) { 800 test := &serverTest{ 801 name: "RSA-3DES", 802 command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "DES-CBC3-SHA"}, 803 } 804 runServerTestTLS10(t, test) 805 runServerTestTLS12(t, test) 806 } 807 808 func TestHandshakeServerRSAAES(t *testing.T) { 809 test := &serverTest{ 810 name: "RSA-AES", 811 command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "AES128-SHA"}, 812 } 813 runServerTestTLS10(t, test) 814 runServerTestTLS12(t, test) 815 } 816 817 func TestHandshakeServerAESGCM(t *testing.T) { 818 test := &serverTest{ 819 name: "RSA-AES-GCM", 820 command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "ECDHE-RSA-AES128-GCM-SHA256"}, 821 } 822 runServerTestTLS12(t, test) 823 } 824 825 func TestHandshakeServerAES256GCMSHA384(t *testing.T) { 826 test := &serverTest{ 827 name: "RSA-AES256-GCM-SHA384", 828 command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "ECDHE-RSA-AES256-GCM-SHA384"}, 829 } 830 runServerTestTLS12(t, test) 831 } 832 833 func TestHandshakeServerAES128SHA256(t *testing.T) { 834 test := &serverTest{ 835 name: "AES128-SHA256", 836 command: []string{"openssl", "s_client", "-no_ticket", "-ciphersuites", "TLS_AES_128_GCM_SHA256"}, 837 } 838 runServerTestTLS13(t, test) 839 } 840 func TestHandshakeServerAES256SHA384(t *testing.T) { 841 test := &serverTest{ 842 name: "AES256-SHA384", 843 command: []string{"openssl", "s_client", "-no_ticket", "-ciphersuites", "TLS_AES_256_GCM_SHA384"}, 844 } 845 runServerTestTLS13(t, test) 846 } 847 func TestHandshakeServerCHACHA20SHA256(t *testing.T) { 848 test := &serverTest{ 849 name: "CHACHA20-SHA256", 850 command: []string{"openssl", "s_client", "-no_ticket", "-ciphersuites", "TLS_CHACHA20_POLY1305_SHA256"}, 851 } 852 runServerTestTLS13(t, test) 853 } 854 855 func TestHandshakeServerECDHEECDSAAES(t *testing.T) { 856 config := testConfig.Clone() 857 config.Certificates = make([]Certificate, 1) 858 config.Certificates[0].Certificate = [][]byte{testECDSACertificate} 859 config.Certificates[0].PrivateKey = testECDSAPrivateKey 860 config.BuildNameToCertificate() 861 862 test := &serverTest{ 863 name: "ECDHE-ECDSA-AES", 864 command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "ECDHE-ECDSA-AES256-SHA", "-ciphersuites", "TLS_AES_128_GCM_SHA256"}, 865 config: config, 866 } 867 runServerTestTLS10(t, test) 868 runServerTestTLS12(t, test) 869 runServerTestTLS13(t, test) 870 } 871 872 func TestHandshakeServerX25519(t *testing.T) { 873 config := testConfig.Clone() 874 config.CurvePreferences = []CurveID{X25519} 875 876 test := &serverTest{ 877 name: "X25519", 878 command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "ECDHE-RSA-CHACHA20-POLY1305", "-ciphersuites", "TLS_CHACHA20_POLY1305_SHA256", "-curves", "X25519"}, 879 config: config, 880 } 881 runServerTestTLS12(t, test) 882 runServerTestTLS13(t, test) 883 } 884 885 func TestHandshakeServerP256(t *testing.T) { 886 config := testConfig.Clone() 887 config.CurvePreferences = []CurveID{CurveP256} 888 889 test := &serverTest{ 890 name: "P256", 891 command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "ECDHE-RSA-CHACHA20-POLY1305", "-ciphersuites", "TLS_CHACHA20_POLY1305_SHA256", "-curves", "P-256"}, 892 config: config, 893 } 894 runServerTestTLS12(t, test) 895 runServerTestTLS13(t, test) 896 } 897 898 func TestHandshakeServerHelloRetryRequest(t *testing.T) { 899 config := testConfig.Clone() 900 config.CurvePreferences = []CurveID{CurveP256} 901 902 test := &serverTest{ 903 name: "HelloRetryRequest", 904 command: []string{"openssl", "s_client", "-no_ticket", "-ciphersuites", "TLS_CHACHA20_POLY1305_SHA256", "-curves", "X25519:P-256"}, 905 config: config, 906 } 907 runServerTestTLS13(t, test) 908 } 909 910 func TestHandshakeServerALPN(t *testing.T) { 911 config := testConfig.Clone() 912 config.NextProtos = []string{"proto1", "proto2"} 913 914 test := &serverTest{ 915 name: "ALPN", 916 // Note that this needs OpenSSL 1.0.2 because that is the first 917 // version that supports the -alpn flag. 918 command: []string{"openssl", "s_client", "-alpn", "proto2,proto1", "-cipher", "ECDHE-RSA-CHACHA20-POLY1305", "-ciphersuites", "TLS_CHACHA20_POLY1305_SHA256"}, 919 config: config, 920 validate: func(state ConnectionState) error { 921 // The server's preferences should override the client. 922 if state.NegotiatedProtocol != "proto1" { 923 return fmt.Errorf("Got protocol %q, wanted proto1", state.NegotiatedProtocol) 924 } 925 return nil 926 }, 927 } 928 runServerTestTLS12(t, test) 929 runServerTestTLS13(t, test) 930 } 931 932 func TestHandshakeServerALPNNoMatch(t *testing.T) { 933 config := testConfig.Clone() 934 config.NextProtos = []string{"proto3"} 935 936 test := &serverTest{ 937 name: "ALPN-NoMatch", 938 // Note that this needs OpenSSL 1.0.2 because that is the first 939 // version that supports the -alpn flag. 940 command: []string{"openssl", "s_client", "-alpn", "proto2,proto1", "-cipher", "ECDHE-RSA-CHACHA20-POLY1305", "-ciphersuites", "TLS_CHACHA20_POLY1305_SHA256"}, 941 config: config, 942 expectHandshakeErrorIncluding: "client requested unsupported application protocol", 943 } 944 runServerTestTLS12(t, test) 945 runServerTestTLS13(t, test) 946 } 947 948 func TestHandshakeServerALPNNotConfigured(t *testing.T) { 949 config := testConfig.Clone() 950 config.NextProtos = nil 951 952 test := &serverTest{ 953 name: "ALPN-NotConfigured", 954 // Note that this needs OpenSSL 1.0.2 because that is the first 955 // version that supports the -alpn flag. 956 command: []string{"openssl", "s_client", "-alpn", "proto2,proto1", "-cipher", "ECDHE-RSA-CHACHA20-POLY1305", "-ciphersuites", "TLS_CHACHA20_POLY1305_SHA256"}, 957 config: config, 958 validate: func(state ConnectionState) error { 959 if state.NegotiatedProtocol != "" { 960 return fmt.Errorf("Got protocol %q, wanted nothing", state.NegotiatedProtocol) 961 } 962 return nil 963 }, 964 } 965 runServerTestTLS12(t, test) 966 runServerTestTLS13(t, test) 967 } 968 969 func TestHandshakeServerALPNFallback(t *testing.T) { 970 config := testConfig.Clone() 971 config.NextProtos = []string{"proto1", "h2", "proto2"} 972 973 test := &serverTest{ 974 name: "ALPN-Fallback", 975 // Note that this needs OpenSSL 1.0.2 because that is the first 976 // version that supports the -alpn flag. 977 command: []string{"openssl", "s_client", "-alpn", "proto3,http/1.1,proto4", "-cipher", "ECDHE-RSA-CHACHA20-POLY1305", "-ciphersuites", "TLS_CHACHA20_POLY1305_SHA256"}, 978 config: config, 979 validate: func(state ConnectionState) error { 980 if state.NegotiatedProtocol != "" { 981 return fmt.Errorf("Got protocol %q, wanted nothing", state.NegotiatedProtocol) 982 } 983 return nil 984 }, 985 } 986 runServerTestTLS12(t, test) 987 runServerTestTLS13(t, test) 988 } 989 990 // TestHandshakeServerSNI involves a client sending an SNI extension of 991 // "snitest.com", which happens to match the CN of testSNICertificate. The test 992 // verifies that the server correctly selects that certificate. 993 func TestHandshakeServerSNI(t *testing.T) { 994 test := &serverTest{ 995 name: "SNI", 996 command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "AES128-SHA", "-servername", "snitest.com"}, 997 } 998 runServerTestTLS12(t, test) 999 } 1000 1001 // TestHandshakeServerSNICertForName is similar to TestHandshakeServerSNI, but 1002 // tests the dynamic GetCertificate method 1003 func TestHandshakeServerSNIGetCertificate(t *testing.T) { 1004 config := testConfig.Clone() 1005 1006 // Replace the NameToCertificate map with a GetCertificate function 1007 nameToCert := config.NameToCertificate 1008 config.NameToCertificate = nil 1009 config.GetCertificate = func(clientHello *ClientHelloInfo) (*Certificate, error) { 1010 cert := nameToCert[clientHello.ServerName] 1011 return cert, nil 1012 } 1013 test := &serverTest{ 1014 name: "SNI-GetCertificate", 1015 command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "AES128-SHA", "-servername", "snitest.com"}, 1016 config: config, 1017 } 1018 runServerTestTLS12(t, test) 1019 } 1020 1021 // TestHandshakeServerSNICertForNameNotFound is similar to 1022 // TestHandshakeServerSNICertForName, but tests to make sure that when the 1023 // GetCertificate method doesn't return a cert, we fall back to what's in 1024 // the NameToCertificate map. 1025 func TestHandshakeServerSNIGetCertificateNotFound(t *testing.T) { 1026 config := testConfig.Clone() 1027 1028 config.GetCertificate = func(clientHello *ClientHelloInfo) (*Certificate, error) { 1029 return nil, nil 1030 } 1031 test := &serverTest{ 1032 name: "SNI-GetCertificateNotFound", 1033 command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "AES128-SHA", "-servername", "snitest.com"}, 1034 config: config, 1035 } 1036 runServerTestTLS12(t, test) 1037 } 1038 1039 // TestHandshakeServerSNICertForNameError tests to make sure that errors in 1040 // GetCertificate result in a tls alert. 1041 func TestHandshakeServerSNIGetCertificateError(t *testing.T) { 1042 const errMsg = "TestHandshakeServerSNIGetCertificateError error" 1043 1044 serverConfig := testConfig.Clone() 1045 serverConfig.GetCertificate = func(clientHello *ClientHelloInfo) (*Certificate, error) { 1046 return nil, errors.New(errMsg) 1047 } 1048 1049 clientHello := &clientHelloMsg{ 1050 vers: VersionTLS10, 1051 random: make([]byte, 32), 1052 cipherSuites: []uint16{TLS_RSA_WITH_RC4_128_SHA}, 1053 compressionMethods: []uint8{compressionNone}, 1054 serverName: "test", 1055 } 1056 testClientHelloFailure(t, serverConfig, clientHello, errMsg) 1057 } 1058 1059 // TestHandshakeServerEmptyCertificates tests that GetCertificates is called in 1060 // the case that Certificates is empty, even without SNI. 1061 func TestHandshakeServerEmptyCertificates(t *testing.T) { 1062 const errMsg = "TestHandshakeServerEmptyCertificates error" 1063 1064 serverConfig := testConfig.Clone() 1065 serverConfig.GetCertificate = func(clientHello *ClientHelloInfo) (*Certificate, error) { 1066 return nil, errors.New(errMsg) 1067 } 1068 serverConfig.Certificates = nil 1069 1070 clientHello := &clientHelloMsg{ 1071 vers: VersionTLS10, 1072 random: make([]byte, 32), 1073 cipherSuites: []uint16{TLS_RSA_WITH_RC4_128_SHA}, 1074 compressionMethods: []uint8{compressionNone}, 1075 } 1076 testClientHelloFailure(t, serverConfig, clientHello, errMsg) 1077 1078 // With an empty Certificates and a nil GetCertificate, the server 1079 // should always return a “no certificates” error. 1080 serverConfig.GetCertificate = nil 1081 1082 clientHello = &clientHelloMsg{ 1083 vers: VersionTLS10, 1084 random: make([]byte, 32), 1085 cipherSuites: []uint16{TLS_RSA_WITH_RC4_128_SHA}, 1086 compressionMethods: []uint8{compressionNone}, 1087 } 1088 testClientHelloFailure(t, serverConfig, clientHello, "no certificates") 1089 } 1090 1091 func TestServerResumption(t *testing.T) { 1092 sessionFilePath := tempFile("") 1093 defer os.Remove(sessionFilePath) 1094 1095 testIssue := &serverTest{ 1096 name: "IssueTicket", 1097 command: []string{"openssl", "s_client", "-cipher", "AES128-SHA", "-ciphersuites", "TLS_AES_128_GCM_SHA256", "-sess_out", sessionFilePath}, 1098 wait: true, 1099 } 1100 testResume := &serverTest{ 1101 name: "Resume", 1102 command: []string{"openssl", "s_client", "-cipher", "AES128-SHA", "-ciphersuites", "TLS_AES_128_GCM_SHA256", "-sess_in", sessionFilePath}, 1103 validate: func(state ConnectionState) error { 1104 if !state.DidResume { 1105 return errors.New("did not resume") 1106 } 1107 return nil 1108 }, 1109 } 1110 1111 runServerTestTLS12(t, testIssue) 1112 runServerTestTLS12(t, testResume) 1113 1114 runServerTestTLS13(t, testIssue) 1115 runServerTestTLS13(t, testResume) 1116 1117 config := testConfig.Clone() 1118 config.CurvePreferences = []CurveID{CurveP256} 1119 1120 testResumeHRR := &serverTest{ 1121 name: "Resume-HelloRetryRequest", 1122 command: []string{"openssl", "s_client", "-curves", "X25519:P-256", "-cipher", "AES128-SHA", "-ciphersuites", 1123 "TLS_AES_128_GCM_SHA256", "-sess_in", sessionFilePath}, 1124 config: config, 1125 validate: func(state ConnectionState) error { 1126 if !state.DidResume { 1127 return errors.New("did not resume") 1128 } 1129 return nil 1130 }, 1131 } 1132 1133 runServerTestTLS13(t, testResumeHRR) 1134 } 1135 1136 func TestServerResumptionDisabled(t *testing.T) { 1137 sessionFilePath := tempFile("") 1138 defer os.Remove(sessionFilePath) 1139 1140 config := testConfig.Clone() 1141 1142 testIssue := &serverTest{ 1143 name: "IssueTicketPreDisable", 1144 command: []string{"openssl", "s_client", "-cipher", "AES128-SHA", "-ciphersuites", "TLS_AES_128_GCM_SHA256", "-sess_out", sessionFilePath}, 1145 config: config, 1146 wait: true, 1147 } 1148 testResume := &serverTest{ 1149 name: "ResumeDisabled", 1150 command: []string{"openssl", "s_client", "-cipher", "AES128-SHA", "-ciphersuites", "TLS_AES_128_GCM_SHA256", "-sess_in", sessionFilePath}, 1151 config: config, 1152 validate: func(state ConnectionState) error { 1153 if state.DidResume { 1154 return errors.New("resumed with SessionTicketsDisabled") 1155 } 1156 return nil 1157 }, 1158 } 1159 1160 config.SessionTicketsDisabled = false 1161 runServerTestTLS12(t, testIssue) 1162 config.SessionTicketsDisabled = true 1163 runServerTestTLS12(t, testResume) 1164 1165 config.SessionTicketsDisabled = false 1166 runServerTestTLS13(t, testIssue) 1167 config.SessionTicketsDisabled = true 1168 runServerTestTLS13(t, testResume) 1169 } 1170 1171 func TestFallbackSCSV(t *testing.T) { 1172 serverConfig := Config{ 1173 Certificates: testConfig.Certificates, 1174 MinVersion: VersionTLS11, 1175 } 1176 test := &serverTest{ 1177 name: "FallbackSCSV", 1178 config: &serverConfig, 1179 // OpenSSL 1.0.1j is needed for the -fallback_scsv option. 1180 command: []string{"openssl", "s_client", "-fallback_scsv"}, 1181 expectHandshakeErrorIncluding: "inappropriate protocol fallback", 1182 } 1183 runServerTestTLS11(t, test) 1184 } 1185 1186 func TestHandshakeServerExportKeyingMaterial(t *testing.T) { 1187 test := &serverTest{ 1188 name: "ExportKeyingMaterial", 1189 command: []string{"openssl", "s_client", "-cipher", "ECDHE-RSA-AES256-SHA", "-ciphersuites", "TLS_CHACHA20_POLY1305_SHA256"}, 1190 config: testConfig.Clone(), 1191 validate: func(state ConnectionState) error { 1192 if km, err := state.ExportKeyingMaterial("test", nil, 42); err != nil { 1193 return fmt.Errorf("ExportKeyingMaterial failed: %v", err) 1194 } else if len(km) != 42 { 1195 return fmt.Errorf("Got %d bytes from ExportKeyingMaterial, wanted %d", len(km), 42) 1196 } 1197 return nil 1198 }, 1199 } 1200 runServerTestTLS10(t, test) 1201 runServerTestTLS12(t, test) 1202 runServerTestTLS13(t, test) 1203 } 1204 1205 func TestHandshakeServerRSAPKCS1v15(t *testing.T) { 1206 test := &serverTest{ 1207 name: "RSA-RSAPKCS1v15", 1208 command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "ECDHE-RSA-CHACHA20-POLY1305", "-sigalgs", "rsa_pkcs1_sha256"}, 1209 } 1210 runServerTestTLS12(t, test) 1211 } 1212 1213 func TestHandshakeServerRSAPSS(t *testing.T) { 1214 // We send rsa_pss_rsae_sha512 first, as the test key won't fit, and we 1215 // verify the server implementation will disregard the client preference in 1216 // that case. See Issue 29793. 1217 test := &serverTest{ 1218 name: "RSA-RSAPSS", 1219 command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "ECDHE-RSA-CHACHA20-POLY1305", "-ciphersuites", "TLS_CHACHA20_POLY1305_SHA256", "-sigalgs", "rsa_pss_rsae_sha512:rsa_pss_rsae_sha256"}, 1220 } 1221 runServerTestTLS12(t, test) 1222 runServerTestTLS13(t, test) 1223 1224 test = &serverTest{ 1225 name: "RSA-RSAPSS-TooSmall", 1226 command: []string{"openssl", "s_client", "-no_ticket", "-ciphersuites", "TLS_CHACHA20_POLY1305_SHA256", "-sigalgs", "rsa_pss_rsae_sha512"}, 1227 expectHandshakeErrorIncluding: "peer doesn't support any of the certificate's signature algorithms", 1228 } 1229 runServerTestTLS13(t, test) 1230 } 1231 1232 func TestHandshakeServerEd25519(t *testing.T) { 1233 config := testConfig.Clone() 1234 config.Certificates = make([]Certificate, 1) 1235 config.Certificates[0].Certificate = [][]byte{testEd25519Certificate} 1236 config.Certificates[0].PrivateKey = testEd25519PrivateKey 1237 config.BuildNameToCertificate() 1238 1239 test := &serverTest{ 1240 name: "Ed25519", 1241 command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "ECDHE-ECDSA-CHACHA20-POLY1305", "-ciphersuites", "TLS_CHACHA20_POLY1305_SHA256"}, 1242 config: config, 1243 } 1244 runServerTestTLS12(t, test) 1245 runServerTestTLS13(t, test) 1246 } 1247 1248 func benchmarkHandshakeServer(b *testing.B, version uint16, cipherSuite uint16, curve CurveID, cert []byte, key crypto.PrivateKey) { 1249 config := testConfig.Clone() 1250 config.CipherSuites = []uint16{cipherSuite} 1251 config.CurvePreferences = []CurveID{curve} 1252 config.Certificates = make([]Certificate, 1) 1253 config.Certificates[0].Certificate = [][]byte{cert} 1254 config.Certificates[0].PrivateKey = key 1255 config.BuildNameToCertificate() 1256 1257 clientConn, serverConn := localPipe(b) 1258 serverConn = &recordingConn{Conn: serverConn} 1259 go func() { 1260 config := testConfig.Clone() 1261 config.MaxVersion = version 1262 config.CurvePreferences = []CurveID{curve} 1263 client := Client(clientConn, config) 1264 client.Handshake() 1265 }() 1266 server := Server(serverConn, config) 1267 if err := server.Handshake(); err != nil { 1268 b.Fatalf("handshake failed: %v", err) 1269 } 1270 serverConn.Close() 1271 flows := serverConn.(*recordingConn).flows 1272 1273 feeder := make(chan struct{}) 1274 clientConn, serverConn = localPipe(b) 1275 1276 go func() { 1277 for range feeder { 1278 for i, f := range flows { 1279 if i%2 == 0 { 1280 clientConn.Write(f) 1281 continue 1282 } 1283 ff := make([]byte, len(f)) 1284 n, err := io.ReadFull(clientConn, ff) 1285 if err != nil { 1286 b.Errorf("#%d: %s\nRead %d, wanted %d, got %x, wanted %x\n", i+1, err, n, len(ff), ff[:n], f) 1287 } 1288 if !bytes.Equal(f, ff) { 1289 b.Errorf("#%d: mismatch on read: got:%x want:%x", i+1, ff, f) 1290 } 1291 } 1292 } 1293 }() 1294 1295 b.ResetTimer() 1296 for i := 0; i < b.N; i++ { 1297 feeder <- struct{}{} 1298 server := Server(serverConn, config) 1299 if err := server.Handshake(); err != nil { 1300 b.Fatalf("handshake failed: %v", err) 1301 } 1302 } 1303 close(feeder) 1304 } 1305 1306 func BenchmarkHandshakeServer(b *testing.B) { 1307 b.Run("RSA", func(b *testing.B) { 1308 benchmarkHandshakeServer(b, VersionTLS12, TLS_RSA_WITH_AES_128_GCM_SHA256, 1309 0, testRSACertificate, testRSAPrivateKey) 1310 }) 1311 b.Run("ECDHE-P256-RSA", func(b *testing.B) { 1312 b.Run("TLSv13", func(b *testing.B) { 1313 benchmarkHandshakeServer(b, VersionTLS13, TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305, 1314 CurveP256, testRSACertificate, testRSAPrivateKey) 1315 }) 1316 b.Run("TLSv12", func(b *testing.B) { 1317 benchmarkHandshakeServer(b, VersionTLS12, TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305, 1318 CurveP256, testRSACertificate, testRSAPrivateKey) 1319 }) 1320 }) 1321 b.Run("ECDHE-P256-ECDSA-P256", func(b *testing.B) { 1322 b.Run("TLSv13", func(b *testing.B) { 1323 benchmarkHandshakeServer(b, VersionTLS13, TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305, 1324 CurveP256, testP256Certificate, testP256PrivateKey) 1325 }) 1326 b.Run("TLSv12", func(b *testing.B) { 1327 benchmarkHandshakeServer(b, VersionTLS12, TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305, 1328 CurveP256, testP256Certificate, testP256PrivateKey) 1329 }) 1330 }) 1331 b.Run("ECDHE-X25519-ECDSA-P256", func(b *testing.B) { 1332 b.Run("TLSv13", func(b *testing.B) { 1333 benchmarkHandshakeServer(b, VersionTLS13, TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305, 1334 X25519, testP256Certificate, testP256PrivateKey) 1335 }) 1336 b.Run("TLSv12", func(b *testing.B) { 1337 benchmarkHandshakeServer(b, VersionTLS12, TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305, 1338 X25519, testP256Certificate, testP256PrivateKey) 1339 }) 1340 }) 1341 b.Run("ECDHE-P521-ECDSA-P521", func(b *testing.B) { 1342 if testECDSAPrivateKey.PublicKey.Curve != elliptic.P521() { 1343 b.Fatal("test ECDSA key doesn't use curve P-521") 1344 } 1345 b.Run("TLSv13", func(b *testing.B) { 1346 benchmarkHandshakeServer(b, VersionTLS13, TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305, 1347 CurveP521, testECDSACertificate, testECDSAPrivateKey) 1348 }) 1349 b.Run("TLSv12", func(b *testing.B) { 1350 benchmarkHandshakeServer(b, VersionTLS12, TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305, 1351 CurveP521, testECDSACertificate, testECDSAPrivateKey) 1352 }) 1353 }) 1354 } 1355 1356 func TestClientAuth(t *testing.T) { 1357 var certPath, keyPath, ecdsaCertPath, ecdsaKeyPath, ed25519CertPath, ed25519KeyPath string 1358 1359 if *update { 1360 certPath = tempFile(clientCertificatePEM) 1361 defer os.Remove(certPath) 1362 keyPath = tempFile(clientKeyPEM) 1363 defer os.Remove(keyPath) 1364 ecdsaCertPath = tempFile(clientECDSACertificatePEM) 1365 defer os.Remove(ecdsaCertPath) 1366 ecdsaKeyPath = tempFile(clientECDSAKeyPEM) 1367 defer os.Remove(ecdsaKeyPath) 1368 ed25519CertPath = tempFile(clientEd25519CertificatePEM) 1369 defer os.Remove(ed25519CertPath) 1370 ed25519KeyPath = tempFile(clientEd25519KeyPEM) 1371 defer os.Remove(ed25519KeyPath) 1372 } else { 1373 t.Parallel() 1374 } 1375 1376 config := testConfig.Clone() 1377 config.ClientAuth = RequestClientCert 1378 1379 test := &serverTest{ 1380 name: "ClientAuthRequestedNotGiven", 1381 command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "AES128-SHA", "-ciphersuites", "TLS_AES_128_GCM_SHA256"}, 1382 config: config, 1383 } 1384 runServerTestTLS12(t, test) 1385 runServerTestTLS13(t, test) 1386 1387 test = &serverTest{ 1388 name: "ClientAuthRequestedAndGiven", 1389 command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "AES128-SHA", "-ciphersuites", "TLS_AES_128_GCM_SHA256", 1390 "-cert", certPath, "-key", keyPath, "-client_sigalgs", "rsa_pss_rsae_sha256"}, 1391 config: config, 1392 expectedPeerCerts: []string{clientCertificatePEM}, 1393 } 1394 runServerTestTLS12(t, test) 1395 runServerTestTLS13(t, test) 1396 1397 test = &serverTest{ 1398 name: "ClientAuthRequestedAndECDSAGiven", 1399 command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "AES128-SHA", "-ciphersuites", "TLS_AES_128_GCM_SHA256", 1400 "-cert", ecdsaCertPath, "-key", ecdsaKeyPath}, 1401 config: config, 1402 expectedPeerCerts: []string{clientECDSACertificatePEM}, 1403 } 1404 runServerTestTLS12(t, test) 1405 runServerTestTLS13(t, test) 1406 1407 test = &serverTest{ 1408 name: "ClientAuthRequestedAndEd25519Given", 1409 command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "AES128-SHA", "-ciphersuites", "TLS_AES_128_GCM_SHA256", 1410 "-cert", ed25519CertPath, "-key", ed25519KeyPath}, 1411 config: config, 1412 expectedPeerCerts: []string{clientEd25519CertificatePEM}, 1413 } 1414 runServerTestTLS12(t, test) 1415 runServerTestTLS13(t, test) 1416 1417 test = &serverTest{ 1418 name: "ClientAuthRequestedAndPKCS1v15Given", 1419 command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "AES128-SHA", 1420 "-cert", certPath, "-key", keyPath, "-client_sigalgs", "rsa_pkcs1_sha256"}, 1421 config: config, 1422 expectedPeerCerts: []string{clientCertificatePEM}, 1423 } 1424 runServerTestTLS12(t, test) 1425 } 1426 1427 func TestSNIGivenOnFailure(t *testing.T) { 1428 const expectedServerName = "test.testing" 1429 1430 clientHello := &clientHelloMsg{ 1431 vers: VersionTLS10, 1432 random: make([]byte, 32), 1433 cipherSuites: []uint16{TLS_RSA_WITH_RC4_128_SHA}, 1434 compressionMethods: []uint8{compressionNone}, 1435 serverName: expectedServerName, 1436 } 1437 1438 serverConfig := testConfig.Clone() 1439 // Erase the server's cipher suites to ensure the handshake fails. 1440 serverConfig.CipherSuites = nil 1441 1442 c, s := localPipe(t) 1443 go func() { 1444 cli := Client(c, testConfig) 1445 cli.vers = clientHello.vers 1446 if _, err := cli.writeHandshakeRecord(clientHello, nil); err != nil { 1447 testFatal(t, err) 1448 } 1449 c.Close() 1450 }() 1451 conn := Server(s, serverConfig) 1452 ctx := context.Background() 1453 ch, err := conn.readClientHello(ctx) 1454 hs := serverHandshakeState{ 1455 c: conn, 1456 ctx: ctx, 1457 clientHello: ch, 1458 } 1459 if err == nil { 1460 err = hs.processClientHello() 1461 } 1462 if err == nil { 1463 err = hs.pickCipherSuite() 1464 } 1465 defer s.Close() 1466 1467 if err == nil { 1468 t.Error("No error reported from server") 1469 } 1470 1471 cs := hs.c.ConnectionState() 1472 if cs.HandshakeComplete { 1473 t.Error("Handshake registered as complete") 1474 } 1475 1476 if cs.ServerName != expectedServerName { 1477 t.Errorf("Expected ServerName of %q, but got %q", expectedServerName, cs.ServerName) 1478 } 1479 } 1480 1481 var getConfigForClientTests = []struct { 1482 setup func(config *Config) 1483 callback func(clientHello *ClientHelloInfo) (*Config, error) 1484 errorSubstring string 1485 verify func(config *Config) error 1486 }{ 1487 { 1488 nil, 1489 func(clientHello *ClientHelloInfo) (*Config, error) { 1490 return nil, nil 1491 }, 1492 "", 1493 nil, 1494 }, 1495 { 1496 nil, 1497 func(clientHello *ClientHelloInfo) (*Config, error) { 1498 return nil, errors.New("should bubble up") 1499 }, 1500 "should bubble up", 1501 nil, 1502 }, 1503 { 1504 nil, 1505 func(clientHello *ClientHelloInfo) (*Config, error) { 1506 config := testConfig.Clone() 1507 // Setting a maximum version of TLS 1.1 should cause 1508 // the handshake to fail, as the client MinVersion is TLS 1.2. 1509 config.MaxVersion = VersionTLS11 1510 return config, nil 1511 }, 1512 "client offered only unsupported versions", 1513 nil, 1514 }, 1515 { 1516 func(config *Config) { 1517 for i := range config.SessionTicketKey { 1518 config.SessionTicketKey[i] = byte(i) 1519 } 1520 config.sessionTicketKeys = nil 1521 }, 1522 func(clientHello *ClientHelloInfo) (*Config, error) { 1523 config := testConfig.Clone() 1524 for i := range config.SessionTicketKey { 1525 config.SessionTicketKey[i] = 0 1526 } 1527 config.sessionTicketKeys = nil 1528 return config, nil 1529 }, 1530 "", 1531 func(config *Config) error { 1532 if config.SessionTicketKey == [32]byte{} { 1533 return fmt.Errorf("expected SessionTicketKey to be set") 1534 } 1535 return nil 1536 }, 1537 }, 1538 { 1539 func(config *Config) { 1540 var dummyKey [32]byte 1541 for i := range dummyKey { 1542 dummyKey[i] = byte(i) 1543 } 1544 1545 config.SetSessionTicketKeys([][32]byte{dummyKey}) 1546 }, 1547 func(clientHello *ClientHelloInfo) (*Config, error) { 1548 config := testConfig.Clone() 1549 config.sessionTicketKeys = nil 1550 return config, nil 1551 }, 1552 "", 1553 func(config *Config) error { 1554 if config.SessionTicketKey == [32]byte{} { 1555 return fmt.Errorf("expected SessionTicketKey to be set") 1556 } 1557 return nil 1558 }, 1559 }, 1560 } 1561 1562 func TestGetConfigForClient(t *testing.T) { 1563 serverConfig := testConfig.Clone() 1564 clientConfig := testConfig.Clone() 1565 clientConfig.MinVersion = VersionTLS12 1566 1567 for i, test := range getConfigForClientTests { 1568 if test.setup != nil { 1569 test.setup(serverConfig) 1570 } 1571 1572 var configReturned *Config 1573 serverConfig.GetConfigForClient = func(clientHello *ClientHelloInfo) (*Config, error) { 1574 config, err := test.callback(clientHello) 1575 configReturned = config 1576 return config, err 1577 } 1578 c, s := localPipe(t) 1579 done := make(chan error) 1580 1581 go func() { 1582 defer s.Close() 1583 done <- Server(s, serverConfig).Handshake() 1584 }() 1585 1586 clientErr := Client(c, clientConfig).Handshake() 1587 c.Close() 1588 1589 serverErr := <-done 1590 1591 if len(test.errorSubstring) == 0 { 1592 if serverErr != nil || clientErr != nil { 1593 t.Errorf("test[%d]: expected no error but got serverErr: %q, clientErr: %q", i, serverErr, clientErr) 1594 } 1595 if test.verify != nil { 1596 if err := test.verify(configReturned); err != nil { 1597 t.Errorf("test[%d]: verify returned error: %v", i, err) 1598 } 1599 } 1600 } else { 1601 if serverErr == nil { 1602 t.Errorf("test[%d]: expected error containing %q but got no error", i, test.errorSubstring) 1603 } else if !strings.Contains(serverErr.Error(), test.errorSubstring) { 1604 t.Errorf("test[%d]: expected error to contain %q but it was %q", i, test.errorSubstring, serverErr) 1605 } 1606 } 1607 } 1608 } 1609 1610 func TestCloseServerConnectionOnIdleClient(t *testing.T) { 1611 clientConn, serverConn := localPipe(t) 1612 server := Server(serverConn, testConfig.Clone()) 1613 go func() { 1614 clientConn.Write([]byte{'0'}) 1615 server.Close() 1616 }() 1617 server.SetReadDeadline(time.Now().Add(time.Minute)) 1618 err := server.Handshake() 1619 if err != nil { 1620 if err, ok := err.(net.Error); ok && err.Timeout() { 1621 t.Errorf("Expected a closed network connection error but got '%s'", err.Error()) 1622 } 1623 } else { 1624 t.Errorf("Error expected, but no error returned") 1625 } 1626 } 1627 1628 func TestCloneHash(t *testing.T) { 1629 h1 := crypto.SHA256.New() 1630 h1.Write([]byte("test")) 1631 s1 := h1.Sum(nil) 1632 h2 := cloneHash(h1, crypto.SHA256) 1633 s2 := h2.Sum(nil) 1634 if !bytes.Equal(s1, s2) { 1635 t.Error("cloned hash generated a different sum") 1636 } 1637 } 1638 1639 func expectError(t *testing.T, err error, sub string) { 1640 if err == nil { 1641 t.Errorf(`expected error %q, got nil`, sub) 1642 } else if !strings.Contains(err.Error(), sub) { 1643 t.Errorf(`expected error %q, got %q`, sub, err) 1644 } 1645 } 1646 1647 func TestKeyTooSmallForRSAPSS(t *testing.T) { 1648 cert, err := X509KeyPair([]byte(`-----BEGIN CERTIFICATE----- 1649 MIIBcTCCARugAwIBAgIQGjQnkCFlUqaFlt6ixyz/tDANBgkqhkiG9w0BAQsFADAS 1650 MRAwDgYDVQQKEwdBY21lIENvMB4XDTE5MDExODIzMjMyOFoXDTIwMDExODIzMjMy 1651 OFowEjEQMA4GA1UEChMHQWNtZSBDbzBcMA0GCSqGSIb3DQEBAQUAA0sAMEgCQQDd 1652 ez1rFUDwax2HTxbcnFUP9AhcgEGMHVV2nn4VVEWFJB6I8C/Nkx0XyyQlrmFYBzEQ 1653 nIPhKls4T0hFoLvjJnXpAgMBAAGjTTBLMA4GA1UdDwEB/wQEAwIFoDATBgNVHSUE 1654 DDAKBggrBgEFBQcDATAMBgNVHRMBAf8EAjAAMBYGA1UdEQQPMA2CC2V4YW1wbGUu 1655 Y29tMA0GCSqGSIb3DQEBCwUAA0EAxDuUS+BrrS3c+h+k+fQPOmOScy6yTX9mHw0Q 1656 KbucGamXYEy0URIwOdO0tQ3LHPc1YGvYSPwkDjkjqECs2Vm/AA== 1657 -----END CERTIFICATE-----`), []byte(testingKey(`-----BEGIN RSA TESTING KEY----- 1658 MIIBOgIBAAJBAN17PWsVQPBrHYdPFtycVQ/0CFyAQYwdVXaefhVURYUkHojwL82T 1659 HRfLJCWuYVgHMRCcg+EqWzhPSEWgu+MmdekCAwEAAQJBALjQYNTdXF4CFBbXwUz/ 1660 yt9QFDYT9B5WT/12jeGAe653gtYS6OOi/+eAkGmzg1GlRnw6fOfn+HYNFDORST7z 1661 4j0CIQDn2xz9hVWQEu9ee3vecNT3f60huDGTNoRhtqgweQGX0wIhAPSLj1VcRZEz 1662 nKpbtU22+PbIMSJ+e80fmY9LIPx5N4HTAiAthGSimMR9bloz0EY3GyuUEyqoDgMd 1663 hXxjuno2WesoJQIgemilbcALXpxsLmZLgcQ2KSmaVr7jb5ECx9R+hYKTw1sCIG4s 1664 T+E0J8wlH24pgwQHzy7Ko2qLwn1b5PW8ecrlvP1g 1665 -----END RSA TESTING KEY-----`))) 1666 if err != nil { 1667 t.Fatal(err) 1668 } 1669 1670 clientConn, serverConn := localPipe(t) 1671 client := Client(clientConn, testConfig) 1672 done := make(chan struct{}) 1673 go func() { 1674 config := testConfig.Clone() 1675 config.Certificates = []Certificate{cert} 1676 config.MinVersion = VersionTLS13 1677 server := Server(serverConn, config) 1678 err := server.Handshake() 1679 expectError(t, err, "key size too small") 1680 close(done) 1681 }() 1682 err = client.Handshake() 1683 expectError(t, err, "handshake failure") 1684 <-done 1685 } 1686 1687 func TestMultipleCertificates(t *testing.T) { 1688 clientConfig := testConfig.Clone() 1689 clientConfig.CipherSuites = []uint16{TLS_RSA_WITH_AES_128_GCM_SHA256} 1690 clientConfig.MaxVersion = VersionTLS12 1691 1692 serverConfig := testConfig.Clone() 1693 serverConfig.Certificates = []Certificate{{ 1694 Certificate: [][]byte{testECDSACertificate}, 1695 PrivateKey: testECDSAPrivateKey, 1696 }, { 1697 Certificate: [][]byte{testRSACertificate}, 1698 PrivateKey: testRSAPrivateKey, 1699 }} 1700 1701 _, clientState, err := testHandshake(t, clientConfig, serverConfig) 1702 if err != nil { 1703 t.Fatal(err) 1704 } 1705 if got := clientState.PeerCertificates[0].PublicKeyAlgorithm; got != x509.RSA { 1706 t.Errorf("expected RSA certificate, got %v", got) 1707 } 1708 } 1709 1710 func TestAESCipherReordering(t *testing.T) { 1711 currentAESSupport := hasAESGCMHardwareSupport 1712 defer func() { hasAESGCMHardwareSupport = currentAESSupport }() 1713 1714 tests := []struct { 1715 name string 1716 clientCiphers []uint16 1717 serverHasAESGCM bool 1718 serverCiphers []uint16 1719 expectedCipher uint16 1720 }{ 1721 { 1722 name: "server has hardware AES, client doesn't (pick ChaCha)", 1723 clientCiphers: []uint16{ 1724 TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305, 1725 TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, 1726 TLS_RSA_WITH_AES_128_CBC_SHA, 1727 }, 1728 serverHasAESGCM: true, 1729 expectedCipher: TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305, 1730 }, 1731 { 1732 name: "client prefers AES-GCM, server doesn't have hardware AES (pick ChaCha)", 1733 clientCiphers: []uint16{ 1734 TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, 1735 TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305, 1736 TLS_RSA_WITH_AES_128_CBC_SHA, 1737 }, 1738 serverHasAESGCM: false, 1739 expectedCipher: TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305, 1740 }, 1741 { 1742 name: "client prefers AES-GCM, server has hardware AES (pick AES-GCM)", 1743 clientCiphers: []uint16{ 1744 TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, 1745 TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305, 1746 TLS_RSA_WITH_AES_128_CBC_SHA, 1747 }, 1748 serverHasAESGCM: true, 1749 expectedCipher: TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, 1750 }, 1751 { 1752 name: "client prefers AES-GCM and sends GREASE, server has hardware AES (pick AES-GCM)", 1753 clientCiphers: []uint16{ 1754 0x0A0A, // GREASE value 1755 TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, 1756 TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305, 1757 TLS_RSA_WITH_AES_128_CBC_SHA, 1758 }, 1759 serverHasAESGCM: true, 1760 expectedCipher: TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, 1761 }, 1762 { 1763 name: "client prefers AES-GCM and doesn't support ChaCha, server doesn't have hardware AES (pick AES-GCM)", 1764 clientCiphers: []uint16{ 1765 TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, 1766 TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, 1767 TLS_RSA_WITH_AES_128_CBC_SHA, 1768 }, 1769 serverHasAESGCM: false, 1770 expectedCipher: TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, 1771 }, 1772 { 1773 name: "client prefers AES-GCM and AES-CBC over ChaCha, server doesn't have hardware AES (pick ChaCha)", 1774 clientCiphers: []uint16{ 1775 TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, 1776 TLS_RSA_WITH_AES_128_CBC_SHA, 1777 TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305, 1778 }, 1779 serverHasAESGCM: false, 1780 expectedCipher: TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305, 1781 }, 1782 { 1783 name: "client prefers AES-GCM over ChaCha and sends GREASE, server doesn't have hardware AES (pick ChaCha)", 1784 clientCiphers: []uint16{ 1785 0x0A0A, // GREASE value 1786 TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, 1787 TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305, 1788 TLS_RSA_WITH_AES_128_CBC_SHA, 1789 }, 1790 serverHasAESGCM: false, 1791 expectedCipher: TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305, 1792 }, 1793 { 1794 name: "client supports multiple AES-GCM, server doesn't have hardware AES and doesn't support ChaCha (AES-GCM)", 1795 clientCiphers: []uint16{ 1796 TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384, 1797 TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305, 1798 TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, 1799 }, 1800 serverHasAESGCM: false, 1801 serverCiphers: []uint16{ 1802 TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384, 1803 TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, 1804 }, 1805 expectedCipher: TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, 1806 }, 1807 { 1808 name: "client prefers AES-GCM, server has hardware but doesn't support AES (pick ChaCha)", 1809 clientCiphers: []uint16{ 1810 TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, 1811 TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305, 1812 TLS_RSA_WITH_AES_128_CBC_SHA, 1813 }, 1814 serverHasAESGCM: true, 1815 serverCiphers: []uint16{ 1816 TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305, 1817 }, 1818 expectedCipher: TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305, 1819 }, 1820 } 1821 1822 for _, tc := range tests { 1823 t.Run(tc.name, func(t *testing.T) { 1824 hasAESGCMHardwareSupport = tc.serverHasAESGCM 1825 hs := &serverHandshakeState{ 1826 c: &Conn{ 1827 config: &Config{ 1828 CipherSuites: tc.serverCiphers, 1829 }, 1830 vers: VersionTLS12, 1831 }, 1832 clientHello: &clientHelloMsg{ 1833 cipherSuites: tc.clientCiphers, 1834 vers: VersionTLS12, 1835 }, 1836 ecdheOk: true, 1837 rsaSignOk: true, 1838 rsaDecryptOk: true, 1839 } 1840 1841 err := hs.pickCipherSuite() 1842 if err != nil { 1843 t.Errorf("pickCipherSuite failed: %s", err) 1844 } 1845 1846 if tc.expectedCipher != hs.suite.id { 1847 t.Errorf("unexpected cipher chosen: want %d, got %d", tc.expectedCipher, hs.suite.id) 1848 } 1849 }) 1850 } 1851 } 1852 1853 func TestAESCipherReorderingTLS13(t *testing.T) { 1854 currentAESSupport := hasAESGCMHardwareSupport 1855 defer func() { hasAESGCMHardwareSupport = currentAESSupport }() 1856 1857 tests := []struct { 1858 name string 1859 clientCiphers []uint16 1860 serverHasAESGCM bool 1861 expectedCipher uint16 1862 }{ 1863 { 1864 name: "server has hardware AES, client doesn't (pick ChaCha)", 1865 clientCiphers: []uint16{ 1866 TLS_CHACHA20_POLY1305_SHA256, 1867 TLS_AES_128_GCM_SHA256, 1868 }, 1869 serverHasAESGCM: true, 1870 expectedCipher: TLS_CHACHA20_POLY1305_SHA256, 1871 }, 1872 { 1873 name: "neither server nor client have hardware AES (pick ChaCha)", 1874 clientCiphers: []uint16{ 1875 TLS_CHACHA20_POLY1305_SHA256, 1876 TLS_AES_128_GCM_SHA256, 1877 }, 1878 serverHasAESGCM: false, 1879 expectedCipher: TLS_CHACHA20_POLY1305_SHA256, 1880 }, 1881 { 1882 name: "client prefers AES, server doesn't have hardware (pick ChaCha)", 1883 clientCiphers: []uint16{ 1884 TLS_AES_128_GCM_SHA256, 1885 TLS_CHACHA20_POLY1305_SHA256, 1886 }, 1887 serverHasAESGCM: false, 1888 expectedCipher: TLS_CHACHA20_POLY1305_SHA256, 1889 }, 1890 { 1891 name: "client prefers AES and sends GREASE, server doesn't have hardware (pick ChaCha)", 1892 clientCiphers: []uint16{ 1893 0x0A0A, // GREASE value 1894 TLS_AES_128_GCM_SHA256, 1895 TLS_CHACHA20_POLY1305_SHA256, 1896 }, 1897 serverHasAESGCM: false, 1898 expectedCipher: TLS_CHACHA20_POLY1305_SHA256, 1899 }, 1900 { 1901 name: "client prefers AES, server has hardware AES (pick AES)", 1902 clientCiphers: []uint16{ 1903 TLS_AES_128_GCM_SHA256, 1904 TLS_CHACHA20_POLY1305_SHA256, 1905 }, 1906 serverHasAESGCM: true, 1907 expectedCipher: TLS_AES_128_GCM_SHA256, 1908 }, 1909 { 1910 name: "client prefers AES and sends GREASE, server has hardware AES (pick AES)", 1911 clientCiphers: []uint16{ 1912 0x0A0A, // GREASE value 1913 TLS_AES_128_GCM_SHA256, 1914 TLS_CHACHA20_POLY1305_SHA256, 1915 }, 1916 serverHasAESGCM: true, 1917 expectedCipher: TLS_AES_128_GCM_SHA256, 1918 }, 1919 } 1920 1921 for _, tc := range tests { 1922 t.Run(tc.name, func(t *testing.T) { 1923 hasAESGCMHardwareSupport = tc.serverHasAESGCM 1924 pk, _ := ecdh.X25519().GenerateKey(rand.Reader) 1925 hs := &serverHandshakeStateTLS13{ 1926 c: &Conn{ 1927 config: &Config{}, 1928 vers: VersionTLS13, 1929 }, 1930 clientHello: &clientHelloMsg{ 1931 cipherSuites: tc.clientCiphers, 1932 supportedVersions: []uint16{VersionTLS13}, 1933 compressionMethods: []uint8{compressionNone}, 1934 keyShares: []keyShare{{group: X25519, data: pk.PublicKey().Bytes()}}, 1935 }, 1936 } 1937 1938 err := hs.processClientHello() 1939 if err != nil { 1940 t.Errorf("pickCipherSuite failed: %s", err) 1941 } 1942 1943 if tc.expectedCipher != hs.suite.id { 1944 t.Errorf("unexpected cipher chosen: want %d, got %d", tc.expectedCipher, hs.suite.id) 1945 } 1946 }) 1947 } 1948 } 1949 1950 // TestServerHandshakeContextCancellation tests that canceling 1951 // the context given to the server side conn.HandshakeContext 1952 // interrupts the in-progress handshake. 1953 func TestServerHandshakeContextCancellation(t *testing.T) { 1954 c, s := localPipe(t) 1955 ctx, cancel := context.WithCancel(context.Background()) 1956 unblockClient := make(chan struct{}) 1957 defer close(unblockClient) 1958 go func() { 1959 cancel() 1960 <-unblockClient 1961 _ = c.Close() 1962 }() 1963 conn := Server(s, testConfig) 1964 // Initiates server side handshake, which will block until a client hello is read 1965 // unless the cancellation works. 1966 err := conn.HandshakeContext(ctx) 1967 if err == nil { 1968 t.Fatal("Server handshake did not error when the context was canceled") 1969 } 1970 if err != context.Canceled { 1971 t.Errorf("Unexpected server handshake error: %v", err) 1972 } 1973 if runtime.GOARCH == "wasm" { 1974 t.Skip("conn.Close does not error as expected when called multiple times on WASM") 1975 } 1976 err = conn.Close() 1977 if err == nil { 1978 t.Error("Server connection was not closed when the context was canceled") 1979 } 1980 } 1981 1982 // TestHandshakeContextHierarchy tests whether the contexts 1983 // available to GetClientCertificate and GetCertificate are 1984 // derived from the context provided to HandshakeContext, and 1985 // that those contexts are canceled after HandshakeContext has 1986 // returned. 1987 func TestHandshakeContextHierarchy(t *testing.T) { 1988 c, s := localPipe(t) 1989 clientErr := make(chan error, 1) 1990 clientConfig := testConfig.Clone() 1991 serverConfig := testConfig.Clone() 1992 ctx, cancel := context.WithCancel(context.Background()) 1993 defer cancel() 1994 key := struct{}{} 1995 ctx = context.WithValue(ctx, key, true) 1996 go func() { 1997 defer close(clientErr) 1998 defer c.Close() 1999 var innerCtx context.Context 2000 clientConfig.Certificates = nil 2001 clientConfig.GetClientCertificate = func(certificateRequest *CertificateRequestInfo) (*Certificate, error) { 2002 if val, ok := certificateRequest.Context().Value(key).(bool); !ok || !val { 2003 t.Errorf("GetClientCertificate context was not child of HandshakeContext") 2004 } 2005 innerCtx = certificateRequest.Context() 2006 return &Certificate{ 2007 Certificate: [][]byte{testRSACertificate}, 2008 PrivateKey: testRSAPrivateKey, 2009 }, nil 2010 } 2011 cli := Client(c, clientConfig) 2012 err := cli.HandshakeContext(ctx) 2013 if err != nil { 2014 clientErr <- err 2015 return 2016 } 2017 select { 2018 case <-innerCtx.Done(): 2019 default: 2020 t.Errorf("GetClientCertificate context was not canceled after HandshakeContext returned.") 2021 } 2022 }() 2023 var innerCtx context.Context 2024 serverConfig.Certificates = nil 2025 serverConfig.ClientAuth = RequestClientCert 2026 serverConfig.GetCertificate = func(clientHello *ClientHelloInfo) (*Certificate, error) { 2027 if val, ok := clientHello.Context().Value(key).(bool); !ok || !val { 2028 t.Errorf("GetClientCertificate context was not child of HandshakeContext") 2029 } 2030 innerCtx = clientHello.Context() 2031 return &Certificate{ 2032 Certificate: [][]byte{testRSACertificate}, 2033 PrivateKey: testRSAPrivateKey, 2034 }, nil 2035 } 2036 conn := Server(s, serverConfig) 2037 err := conn.HandshakeContext(ctx) 2038 if err != nil { 2039 t.Errorf("Unexpected server handshake error: %v", err) 2040 } 2041 select { 2042 case <-innerCtx.Done(): 2043 default: 2044 t.Errorf("GetCertificate context was not canceled after HandshakeContext returned.") 2045 } 2046 if err := <-clientErr; err != nil { 2047 t.Errorf("Unexpected client error: %v", err) 2048 } 2049 }