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