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