github.com/icodeface/tls@v0.0.0-20230910023335-34df9250cd12/tls_test.go (about) 1 // Copyright 2012 The Go Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 package tls 6 7 import ( 8 "bytes" 9 "crypto/x509" 10 "encoding/json" 11 "errors" 12 "fmt" 13 "github.com/icodeface/tls/internal/testenv" 14 "io" 15 "io/ioutil" 16 "math" 17 "net" 18 "os" 19 "reflect" 20 "strings" 21 "sync" 22 "testing" 23 "time" 24 ) 25 26 var savedSupportedSignatureAlgorithmsTLS12 = supportedSignatureAlgorithmsTLS12 27 28 func init() { 29 // TLS 1.3 is opt-in for Go 1.12, and RSA-PSS is disabled in TLS 1.2, but we 30 // want to run most tests with both enabled. TestTLS13Switch below and the 31 // "PSS-Disabled" recordings test the disabled behavior. See Issue 30055. 32 tls13Support.Do(func() {}) // defuse the sync.Once 33 tls13Support.cached = true 34 supportedSignatureAlgorithmsTLS12 = supportedSignatureAlgorithms 35 } 36 37 var rsaCertPEM = `-----BEGIN CERTIFICATE----- 38 MIIB0zCCAX2gAwIBAgIJAI/M7BYjwB+uMA0GCSqGSIb3DQEBBQUAMEUxCzAJBgNV 39 BAYTAkFVMRMwEQYDVQQIDApTb21lLVN0YXRlMSEwHwYDVQQKDBhJbnRlcm5ldCBX 40 aWRnaXRzIFB0eSBMdGQwHhcNMTIwOTEyMjE1MjAyWhcNMTUwOTEyMjE1MjAyWjBF 41 MQswCQYDVQQGEwJBVTETMBEGA1UECAwKU29tZS1TdGF0ZTEhMB8GA1UECgwYSW50 42 ZXJuZXQgV2lkZ2l0cyBQdHkgTHRkMFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBANLJ 43 hPHhITqQbPklG3ibCVxwGMRfp/v4XqhfdQHdcVfHap6NQ5Wok/4xIA+ui35/MmNa 44 rtNuC+BdZ1tMuVCPFZcCAwEAAaNQME4wHQYDVR0OBBYEFJvKs8RfJaXTH08W+SGv 45 zQyKn0H8MB8GA1UdIwQYMBaAFJvKs8RfJaXTH08W+SGvzQyKn0H8MAwGA1UdEwQF 46 MAMBAf8wDQYJKoZIhvcNAQEFBQADQQBJlffJHybjDGxRMqaRmDhX0+6v02TUKZsW 47 r5QuVbpQhH6u+0UgcW0jp9QwpxoPTLTWGXEWBBBurxFwiCBhkQ+V 48 -----END CERTIFICATE----- 49 ` 50 51 var rsaKeyPEM = `-----BEGIN RSA PRIVATE KEY----- 52 MIIBOwIBAAJBANLJhPHhITqQbPklG3ibCVxwGMRfp/v4XqhfdQHdcVfHap6NQ5Wo 53 k/4xIA+ui35/MmNartNuC+BdZ1tMuVCPFZcCAwEAAQJAEJ2N+zsR0Xn8/Q6twa4G 54 6OB1M1WO+k+ztnX/1SvNeWu8D6GImtupLTYgjZcHufykj09jiHmjHx8u8ZZB/o1N 55 MQIhAPW+eyZo7ay3lMz1V01WVjNKK9QSn1MJlb06h/LuYv9FAiEA25WPedKgVyCW 56 SmUwbPw8fnTcpqDWE3yTO3vKcebqMSsCIBF3UmVue8YU3jybC3NxuXq3wNm34R8T 57 xVLHwDXh/6NJAiEAl2oHGGLz64BuAfjKrqwz7qMYr9HCLIe/YsoWq/olzScCIQDi 58 D2lWusoe2/nEqfDVVWGWlyJ7yOmqaVm/iNUN9B2N2g== 59 -----END RSA PRIVATE KEY----- 60 ` 61 62 // keyPEM is the same as rsaKeyPEM, but declares itself as just 63 // "PRIVATE KEY", not "RSA PRIVATE KEY". https://golang.org/issue/4477 64 var keyPEM = `-----BEGIN PRIVATE KEY----- 65 MIIBOwIBAAJBANLJhPHhITqQbPklG3ibCVxwGMRfp/v4XqhfdQHdcVfHap6NQ5Wo 66 k/4xIA+ui35/MmNartNuC+BdZ1tMuVCPFZcCAwEAAQJAEJ2N+zsR0Xn8/Q6twa4G 67 6OB1M1WO+k+ztnX/1SvNeWu8D6GImtupLTYgjZcHufykj09jiHmjHx8u8ZZB/o1N 68 MQIhAPW+eyZo7ay3lMz1V01WVjNKK9QSn1MJlb06h/LuYv9FAiEA25WPedKgVyCW 69 SmUwbPw8fnTcpqDWE3yTO3vKcebqMSsCIBF3UmVue8YU3jybC3NxuXq3wNm34R8T 70 xVLHwDXh/6NJAiEAl2oHGGLz64BuAfjKrqwz7qMYr9HCLIe/YsoWq/olzScCIQDi 71 D2lWusoe2/nEqfDVVWGWlyJ7yOmqaVm/iNUN9B2N2g== 72 -----END PRIVATE KEY----- 73 ` 74 75 var ecdsaCertPEM = `-----BEGIN CERTIFICATE----- 76 MIIB/jCCAWICCQDscdUxw16XFDAJBgcqhkjOPQQBMEUxCzAJBgNVBAYTAkFVMRMw 77 EQYDVQQIEwpTb21lLVN0YXRlMSEwHwYDVQQKExhJbnRlcm5ldCBXaWRnaXRzIFB0 78 eSBMdGQwHhcNMTIxMTE0MTI0MDQ4WhcNMTUxMTE0MTI0MDQ4WjBFMQswCQYDVQQG 79 EwJBVTETMBEGA1UECBMKU29tZS1TdGF0ZTEhMB8GA1UEChMYSW50ZXJuZXQgV2lk 80 Z2l0cyBQdHkgTHRkMIGbMBAGByqGSM49AgEGBSuBBAAjA4GGAAQBY9+my9OoeSUR 81 lDQdV/x8LsOuLilthhiS1Tz4aGDHIPwC1mlvnf7fg5lecYpMCrLLhauAc1UJXcgl 82 01xoLuzgtAEAgv2P/jgytzRSpUYvgLBt1UA0leLYBy6mQQbrNEuqT3INapKIcUv8 83 XxYP0xMEUksLPq6Ca+CRSqTtrd/23uTnapkwCQYHKoZIzj0EAQOBigAwgYYCQXJo 84 A7Sl2nLVf+4Iu/tAX/IF4MavARKC4PPHK3zfuGfPR3oCCcsAoz3kAzOeijvd0iXb 85 H5jBImIxPL4WxQNiBTexAkF8D1EtpYuWdlVQ80/h/f4pBcGiXPqX5h2PQSQY7hP1 86 +jwM1FGS4fREIOvlBYr/SzzQRtwrvrzGYxDEDbsC0ZGRnA== 87 -----END CERTIFICATE----- 88 ` 89 90 var ecdsaKeyPEM = `-----BEGIN EC PARAMETERS----- 91 BgUrgQQAIw== 92 -----END EC PARAMETERS----- 93 -----BEGIN EC PRIVATE KEY----- 94 MIHcAgEBBEIBrsoKp0oqcv6/JovJJDoDVSGWdirrkgCWxrprGlzB9o0X8fV675X0 95 NwuBenXFfeZvVcwluO7/Q9wkYoPd/t3jGImgBwYFK4EEACOhgYkDgYYABAFj36bL 96 06h5JRGUNB1X/Hwuw64uKW2GGJLVPPhoYMcg/ALWaW+d/t+DmV5xikwKssuFq4Bz 97 VQldyCXTXGgu7OC0AQCC/Y/+ODK3NFKlRi+AsG3VQDSV4tgHLqZBBus0S6pPcg1q 98 kohxS/xfFg/TEwRSSws+roJr4JFKpO2t3/be5OdqmQ== 99 -----END EC PRIVATE KEY----- 100 ` 101 102 var keyPairTests = []struct { 103 algo string 104 cert string 105 key string 106 }{ 107 {"ECDSA", ecdsaCertPEM, ecdsaKeyPEM}, 108 {"RSA", rsaCertPEM, rsaKeyPEM}, 109 {"RSA-untyped", rsaCertPEM, keyPEM}, // golang.org/issue/4477 110 } 111 112 func TestX509KeyPair(t *testing.T) { 113 t.Parallel() 114 var pem []byte 115 for _, test := range keyPairTests { 116 pem = []byte(test.cert + test.key) 117 if _, err := X509KeyPair(pem, pem); err != nil { 118 t.Errorf("Failed to load %s cert followed by %s key: %s", test.algo, test.algo, err) 119 } 120 pem = []byte(test.key + test.cert) 121 if _, err := X509KeyPair(pem, pem); err != nil { 122 t.Errorf("Failed to load %s key followed by %s cert: %s", test.algo, test.algo, err) 123 } 124 } 125 } 126 127 func TestX509KeyPairErrors(t *testing.T) { 128 _, err := X509KeyPair([]byte(rsaKeyPEM), []byte(rsaCertPEM)) 129 if err == nil { 130 t.Fatalf("X509KeyPair didn't return an error when arguments were switched") 131 } 132 if subStr := "been switched"; !strings.Contains(err.Error(), subStr) { 133 t.Fatalf("Expected %q in the error when switching arguments to X509KeyPair, but the error was %q", subStr, err) 134 } 135 136 _, err = X509KeyPair([]byte(rsaCertPEM), []byte(rsaCertPEM)) 137 if err == nil { 138 t.Fatalf("X509KeyPair didn't return an error when both arguments were certificates") 139 } 140 if subStr := "certificate"; !strings.Contains(err.Error(), subStr) { 141 t.Fatalf("Expected %q in the error when both arguments to X509KeyPair were certificates, but the error was %q", subStr, err) 142 } 143 144 const nonsensePEM = ` 145 -----BEGIN NONSENSE----- 146 Zm9vZm9vZm9v 147 -----END NONSENSE----- 148 ` 149 150 _, err = X509KeyPair([]byte(nonsensePEM), []byte(nonsensePEM)) 151 if err == nil { 152 t.Fatalf("X509KeyPair didn't return an error when both arguments were nonsense") 153 } 154 if subStr := "NONSENSE"; !strings.Contains(err.Error(), subStr) { 155 t.Fatalf("Expected %q in the error when both arguments to X509KeyPair were nonsense, but the error was %q", subStr, err) 156 } 157 } 158 159 func TestX509MixedKeyPair(t *testing.T) { 160 if _, err := X509KeyPair([]byte(rsaCertPEM), []byte(ecdsaKeyPEM)); err == nil { 161 t.Error("Load of RSA certificate succeeded with ECDSA private key") 162 } 163 if _, err := X509KeyPair([]byte(ecdsaCertPEM), []byte(rsaKeyPEM)); err == nil { 164 t.Error("Load of ECDSA certificate succeeded with RSA private key") 165 } 166 } 167 168 func newLocalListener(t testing.TB) net.Listener { 169 ln, err := net.Listen("tcp", "127.0.0.1:0") 170 if err != nil { 171 ln, err = net.Listen("tcp6", "[::1]:0") 172 } 173 if err != nil { 174 t.Fatal(err) 175 } 176 return ln 177 } 178 179 func TestDialTimeout(t *testing.T) { 180 if testing.Short() { 181 t.Skip("skipping in short mode") 182 } 183 listener := newLocalListener(t) 184 185 addr := listener.Addr().String() 186 defer listener.Close() 187 188 complete := make(chan bool) 189 defer close(complete) 190 191 go func() { 192 conn, err := listener.Accept() 193 if err != nil { 194 t.Error(err) 195 return 196 } 197 <-complete 198 conn.Close() 199 }() 200 201 dialer := &net.Dialer{ 202 Timeout: 10 * time.Millisecond, 203 } 204 205 var err error 206 if _, err = DialWithDialer(dialer, "tcp", addr, nil); err == nil { 207 t.Fatal("DialWithTimeout completed successfully") 208 } 209 210 if !isTimeoutError(err) { 211 t.Errorf("resulting error not a timeout: %v\nType %T: %#v", err, err, err) 212 } 213 } 214 215 func isTimeoutError(err error) bool { 216 if ne, ok := err.(net.Error); ok { 217 return ne.Timeout() 218 } 219 return false 220 } 221 222 // tests that Conn.Read returns (non-zero, io.EOF) instead of 223 // (non-zero, nil) when a Close (alertCloseNotify) is sitting right 224 // behind the application data in the buffer. 225 func TestConnReadNonzeroAndEOF(t *testing.T) { 226 // This test is racy: it assumes that after a write to a 227 // localhost TCP connection, the peer TCP connection can 228 // immediately read it. Because it's racy, we skip this test 229 // in short mode, and then retry it several times with an 230 // increasing sleep in between our final write (via srv.Close 231 // below) and the following read. 232 if testing.Short() { 233 t.Skip("skipping in short mode") 234 } 235 var err error 236 for delay := time.Millisecond; delay <= 64*time.Millisecond; delay *= 2 { 237 if err = testConnReadNonzeroAndEOF(t, delay); err == nil { 238 return 239 } 240 } 241 t.Error(err) 242 } 243 244 func testConnReadNonzeroAndEOF(t *testing.T, delay time.Duration) error { 245 ln := newLocalListener(t) 246 defer ln.Close() 247 248 srvCh := make(chan *Conn, 1) 249 var serr error 250 go func() { 251 sconn, err := ln.Accept() 252 if err != nil { 253 serr = err 254 srvCh <- nil 255 return 256 } 257 serverConfig := testConfig.Clone() 258 srv := Server(sconn, serverConfig) 259 if err := srv.Handshake(); err != nil { 260 serr = fmt.Errorf("handshake: %v", err) 261 srvCh <- nil 262 return 263 } 264 srvCh <- srv 265 }() 266 267 clientConfig := testConfig.Clone() 268 // In TLS 1.3, alerts are encrypted and disguised as application data, so 269 // the opportunistic peek won't work. 270 clientConfig.MaxVersion = VersionTLS12 271 conn, err := Dial("tcp", ln.Addr().String(), clientConfig) 272 if err != nil { 273 t.Fatal(err) 274 } 275 defer conn.Close() 276 277 srv := <-srvCh 278 if srv == nil { 279 return serr 280 } 281 282 buf := make([]byte, 6) 283 284 srv.Write([]byte("foobar")) 285 n, err := conn.Read(buf) 286 if n != 6 || err != nil || string(buf) != "foobar" { 287 return fmt.Errorf("Read = %d, %v, data %q; want 6, nil, foobar", n, err, buf) 288 } 289 290 srv.Write([]byte("abcdef")) 291 srv.Close() 292 time.Sleep(delay) 293 n, err = conn.Read(buf) 294 if n != 6 || string(buf) != "abcdef" { 295 return fmt.Errorf("Read = %d, buf= %q; want 6, abcdef", n, buf) 296 } 297 if err != io.EOF { 298 return fmt.Errorf("Second Read error = %v; want io.EOF", err) 299 } 300 return nil 301 } 302 303 func TestTLSUniqueMatches(t *testing.T) { 304 ln := newLocalListener(t) 305 defer ln.Close() 306 307 serverTLSUniques := make(chan []byte) 308 go func() { 309 for i := 0; i < 2; i++ { 310 sconn, err := ln.Accept() 311 if err != nil { 312 t.Error(err) 313 return 314 } 315 serverConfig := testConfig.Clone() 316 serverConfig.MaxVersion = VersionTLS12 // TLSUnique is not defined in TLS 1.3 317 srv := Server(sconn, serverConfig) 318 if err := srv.Handshake(); err != nil { 319 t.Error(err) 320 return 321 } 322 serverTLSUniques <- srv.ConnectionState().TLSUnique 323 } 324 }() 325 326 clientConfig := testConfig.Clone() 327 clientConfig.ClientSessionCache = NewLRUClientSessionCache(1) 328 conn, err := Dial("tcp", ln.Addr().String(), clientConfig) 329 if err != nil { 330 t.Fatal(err) 331 } 332 if !bytes.Equal(conn.ConnectionState().TLSUnique, <-serverTLSUniques) { 333 t.Error("client and server channel bindings differ") 334 } 335 conn.Close() 336 337 conn, err = Dial("tcp", ln.Addr().String(), clientConfig) 338 if err != nil { 339 t.Fatal(err) 340 } 341 defer conn.Close() 342 if !conn.ConnectionState().DidResume { 343 t.Error("second session did not use resumption") 344 } 345 if !bytes.Equal(conn.ConnectionState().TLSUnique, <-serverTLSUniques) { 346 t.Error("client and server channel bindings differ when session resumption is used") 347 } 348 } 349 350 func TestVerifyHostname(t *testing.T) { 351 testenv.MustHaveExternalNetwork(t) 352 353 c, err := Dial("tcp", "www.google.com:https", nil) 354 if err != nil { 355 t.Fatal(err) 356 } 357 if err := c.VerifyHostname("www.google.com"); err != nil { 358 t.Fatalf("verify www.google.com: %v", err) 359 } 360 if err := c.VerifyHostname("www.yahoo.com"); err == nil { 361 t.Fatalf("verify www.yahoo.com succeeded") 362 } 363 364 c, err = Dial("tcp", "www.google.com:https", &Config{InsecureSkipVerify: true}) 365 if err != nil { 366 t.Fatal(err) 367 } 368 if err := c.VerifyHostname("www.google.com"); err == nil { 369 t.Fatalf("verify www.google.com succeeded with InsecureSkipVerify=true") 370 } 371 } 372 373 func TestConnCloseBreakingWrite(t *testing.T) { 374 ln := newLocalListener(t) 375 defer ln.Close() 376 377 srvCh := make(chan *Conn, 1) 378 var serr error 379 var sconn net.Conn 380 go func() { 381 var err error 382 sconn, err = ln.Accept() 383 if err != nil { 384 serr = err 385 srvCh <- nil 386 return 387 } 388 serverConfig := testConfig.Clone() 389 srv := Server(sconn, serverConfig) 390 if err := srv.Handshake(); err != nil { 391 serr = fmt.Errorf("handshake: %v", err) 392 srvCh <- nil 393 return 394 } 395 srvCh <- srv 396 }() 397 398 cconn, err := net.Dial("tcp", ln.Addr().String()) 399 if err != nil { 400 t.Fatal(err) 401 } 402 defer cconn.Close() 403 404 conn := &changeImplConn{ 405 Conn: cconn, 406 } 407 408 clientConfig := testConfig.Clone() 409 tconn := Client(conn, clientConfig) 410 if err := tconn.Handshake(); err != nil { 411 t.Fatal(err) 412 } 413 414 srv := <-srvCh 415 if srv == nil { 416 t.Fatal(serr) 417 } 418 defer sconn.Close() 419 420 connClosed := make(chan struct{}) 421 conn.closeFunc = func() error { 422 close(connClosed) 423 return nil 424 } 425 426 inWrite := make(chan bool, 1) 427 var errConnClosed = errors.New("conn closed for test") 428 conn.writeFunc = func(p []byte) (n int, err error) { 429 inWrite <- true 430 <-connClosed 431 return 0, errConnClosed 432 } 433 434 closeReturned := make(chan bool, 1) 435 go func() { 436 <-inWrite 437 tconn.Close() // test that this doesn't block forever. 438 closeReturned <- true 439 }() 440 441 _, err = tconn.Write([]byte("foo")) 442 if err != errConnClosed { 443 t.Errorf("Write error = %v; want errConnClosed", err) 444 } 445 446 <-closeReturned 447 if err := tconn.Close(); err != errClosed { 448 t.Errorf("Close error = %v; want errClosed", err) 449 } 450 } 451 452 func TestConnCloseWrite(t *testing.T) { 453 ln := newLocalListener(t) 454 defer ln.Close() 455 456 clientDoneChan := make(chan struct{}) 457 458 serverCloseWrite := func() error { 459 sconn, err := ln.Accept() 460 if err != nil { 461 return fmt.Errorf("accept: %v", err) 462 } 463 defer sconn.Close() 464 465 serverConfig := testConfig.Clone() 466 srv := Server(sconn, serverConfig) 467 if err := srv.Handshake(); err != nil { 468 return fmt.Errorf("handshake: %v", err) 469 } 470 defer srv.Close() 471 472 data, err := ioutil.ReadAll(srv) 473 if err != nil { 474 return err 475 } 476 if len(data) > 0 { 477 return fmt.Errorf("Read data = %q; want nothing", data) 478 } 479 480 if err := srv.CloseWrite(); err != nil { 481 return fmt.Errorf("server CloseWrite: %v", err) 482 } 483 484 // Wait for clientCloseWrite to finish, so we know we 485 // tested the CloseWrite before we defer the 486 // sconn.Close above, which would also cause the 487 // client to unblock like CloseWrite. 488 <-clientDoneChan 489 return nil 490 } 491 492 clientCloseWrite := func() error { 493 defer close(clientDoneChan) 494 495 clientConfig := testConfig.Clone() 496 conn, err := Dial("tcp", ln.Addr().String(), clientConfig) 497 if err != nil { 498 return err 499 } 500 if err := conn.Handshake(); err != nil { 501 return err 502 } 503 defer conn.Close() 504 505 if err := conn.CloseWrite(); err != nil { 506 return fmt.Errorf("client CloseWrite: %v", err) 507 } 508 509 if _, err := conn.Write([]byte{0}); err != errShutdown { 510 return fmt.Errorf("CloseWrite error = %v; want errShutdown", err) 511 } 512 513 data, err := ioutil.ReadAll(conn) 514 if err != nil { 515 return err 516 } 517 if len(data) > 0 { 518 return fmt.Errorf("Read data = %q; want nothing", data) 519 } 520 return nil 521 } 522 523 errChan := make(chan error, 2) 524 525 go func() { errChan <- serverCloseWrite() }() 526 go func() { errChan <- clientCloseWrite() }() 527 528 for i := 0; i < 2; i++ { 529 select { 530 case err := <-errChan: 531 if err != nil { 532 t.Fatal(err) 533 } 534 case <-time.After(10 * time.Second): 535 t.Fatal("deadlock") 536 } 537 } 538 539 // Also test CloseWrite being called before the handshake is 540 // finished: 541 { 542 ln2 := newLocalListener(t) 543 defer ln2.Close() 544 545 netConn, err := net.Dial("tcp", ln2.Addr().String()) 546 if err != nil { 547 t.Fatal(err) 548 } 549 defer netConn.Close() 550 conn := Client(netConn, testConfig.Clone()) 551 552 if err := conn.CloseWrite(); err != errEarlyCloseWrite { 553 t.Errorf("CloseWrite error = %v; want errEarlyCloseWrite", err) 554 } 555 } 556 } 557 558 func TestWarningAlertFlood(t *testing.T) { 559 ln := newLocalListener(t) 560 defer ln.Close() 561 562 server := func() error { 563 sconn, err := ln.Accept() 564 if err != nil { 565 return fmt.Errorf("accept: %v", err) 566 } 567 defer sconn.Close() 568 569 serverConfig := testConfig.Clone() 570 srv := Server(sconn, serverConfig) 571 if err := srv.Handshake(); err != nil { 572 return fmt.Errorf("handshake: %v", err) 573 } 574 defer srv.Close() 575 576 _, err = ioutil.ReadAll(srv) 577 if err == nil { 578 return errors.New("unexpected lack of error from server") 579 } 580 const expected = "too many ignored" 581 if str := err.Error(); !strings.Contains(str, expected) { 582 return fmt.Errorf("expected error containing %q, but saw: %s", expected, str) 583 } 584 585 return nil 586 } 587 588 errChan := make(chan error, 1) 589 go func() { errChan <- server() }() 590 591 clientConfig := testConfig.Clone() 592 clientConfig.MaxVersion = VersionTLS12 // there are no warning alerts in TLS 1.3 593 conn, err := Dial("tcp", ln.Addr().String(), clientConfig) 594 if err != nil { 595 t.Fatal(err) 596 } 597 defer conn.Close() 598 if err := conn.Handshake(); err != nil { 599 t.Fatal(err) 600 } 601 602 for i := 0; i < maxUselessRecords+1; i++ { 603 conn.sendAlert(alertNoRenegotiation) 604 } 605 606 if err := <-errChan; err != nil { 607 t.Fatal(err) 608 } 609 } 610 611 func TestCloneFuncFields(t *testing.T) { 612 const expectedCount = 5 613 called := 0 614 615 c1 := Config{ 616 Time: func() time.Time { 617 called |= 1 << 0 618 return time.Time{} 619 }, 620 GetCertificate: func(*ClientHelloInfo) (*Certificate, error) { 621 called |= 1 << 1 622 return nil, nil 623 }, 624 GetClientCertificate: func(*CertificateRequestInfo) (*Certificate, error) { 625 called |= 1 << 2 626 return nil, nil 627 }, 628 GetConfigForClient: func(*ClientHelloInfo) (*Config, error) { 629 called |= 1 << 3 630 return nil, nil 631 }, 632 VerifyPeerCertificate: func(rawCerts [][]byte, verifiedChains [][]*x509.Certificate) error { 633 called |= 1 << 4 634 return nil 635 }, 636 } 637 638 c2 := c1.Clone() 639 640 c2.Time() 641 c2.GetCertificate(nil) 642 c2.GetClientCertificate(nil) 643 c2.GetConfigForClient(nil) 644 c2.VerifyPeerCertificate(nil, nil) 645 646 if called != (1<<expectedCount)-1 { 647 t.Fatalf("expected %d calls but saw calls %b", expectedCount, called) 648 } 649 } 650 651 func TestCloneNonFuncFields(t *testing.T) { 652 var c1 Config 653 v := reflect.ValueOf(&c1).Elem() 654 655 typ := v.Type() 656 for i := 0; i < typ.NumField(); i++ { 657 f := v.Field(i) 658 if !f.CanSet() { 659 // unexported field; not cloned. 660 continue 661 } 662 663 // testing/quick can't handle functions or interfaces and so 664 // isn't used here. 665 switch fn := typ.Field(i).Name; fn { 666 case "Rand": 667 f.Set(reflect.ValueOf(io.Reader(os.Stdin))) 668 case "Time", "GetCertificate", "GetConfigForClient", "VerifyPeerCertificate", "GetClientCertificate": 669 // DeepEqual can't compare functions. If you add a 670 // function field to this list, you must also change 671 // TestCloneFuncFields to ensure that the func field is 672 // cloned. 673 case "Certificates": 674 f.Set(reflect.ValueOf([]Certificate{ 675 {Certificate: [][]byte{{'b'}}}, 676 })) 677 case "NameToCertificate": 678 f.Set(reflect.ValueOf(map[string]*Certificate{"a": nil})) 679 case "RootCAs", "ClientCAs": 680 f.Set(reflect.ValueOf(x509.NewCertPool())) 681 case "ClientSessionCache": 682 f.Set(reflect.ValueOf(NewLRUClientSessionCache(10))) 683 case "KeyLogWriter": 684 f.Set(reflect.ValueOf(io.Writer(os.Stdout))) 685 case "NextProtos": 686 f.Set(reflect.ValueOf([]string{"a", "b"})) 687 case "ServerName": 688 f.Set(reflect.ValueOf("b")) 689 case "ClientAuth": 690 f.Set(reflect.ValueOf(VerifyClientCertIfGiven)) 691 case "InsecureSkipVerify", "SessionTicketsDisabled", "DynamicRecordSizingDisabled", "PreferServerCipherSuites": 692 f.Set(reflect.ValueOf(true)) 693 case "MinVersion", "MaxVersion": 694 f.Set(reflect.ValueOf(uint16(VersionTLS12))) 695 case "SessionTicketKey": 696 f.Set(reflect.ValueOf([32]byte{})) 697 case "CipherSuites": 698 f.Set(reflect.ValueOf([]uint16{1, 2})) 699 case "CurvePreferences": 700 f.Set(reflect.ValueOf([]CurveID{CurveP256})) 701 case "Renegotiation": 702 f.Set(reflect.ValueOf(RenegotiateOnceAsClient)) 703 default: 704 t.Errorf("all fields must be accounted for, but saw unknown field %q", fn) 705 } 706 } 707 708 c2 := c1.Clone() 709 // DeepEqual also compares unexported fields, thus c2 needs to have run 710 // serverInit in order to be DeepEqual to c1. Cloning it and discarding 711 // the result is sufficient. 712 c2.Clone() 713 714 if !reflect.DeepEqual(&c1, c2) { 715 t.Errorf("clone failed to copy a field") 716 } 717 } 718 719 // changeImplConn is a net.Conn which can change its Write and Close 720 // methods. 721 type changeImplConn struct { 722 net.Conn 723 writeFunc func([]byte) (int, error) 724 closeFunc func() error 725 } 726 727 func (w *changeImplConn) Write(p []byte) (n int, err error) { 728 if w.writeFunc != nil { 729 return w.writeFunc(p) 730 } 731 return w.Conn.Write(p) 732 } 733 734 func (w *changeImplConn) Close() error { 735 if w.closeFunc != nil { 736 return w.closeFunc() 737 } 738 return w.Conn.Close() 739 } 740 741 func throughput(b *testing.B, version uint16, totalBytes int64, dynamicRecordSizingDisabled bool) { 742 ln := newLocalListener(b) 743 defer ln.Close() 744 745 N := b.N 746 747 // Less than 64KB because Windows appears to use a TCP rwin < 64KB. 748 // See Issue #15899. 749 const bufsize = 32 << 10 750 751 go func() { 752 buf := make([]byte, bufsize) 753 for i := 0; i < N; i++ { 754 sconn, err := ln.Accept() 755 if err != nil { 756 // panic rather than synchronize to avoid benchmark overhead 757 // (cannot call b.Fatal in goroutine) 758 panic(fmt.Errorf("accept: %v", err)) 759 } 760 serverConfig := testConfig.Clone() 761 serverConfig.CipherSuites = nil // the defaults may prefer faster ciphers 762 serverConfig.DynamicRecordSizingDisabled = dynamicRecordSizingDisabled 763 srv := Server(sconn, serverConfig) 764 if err := srv.Handshake(); err != nil { 765 panic(fmt.Errorf("handshake: %v", err)) 766 } 767 if _, err := io.CopyBuffer(srv, srv, buf); err != nil { 768 panic(fmt.Errorf("copy buffer: %v", err)) 769 } 770 } 771 }() 772 773 b.SetBytes(totalBytes) 774 clientConfig := testConfig.Clone() 775 clientConfig.CipherSuites = nil // the defaults may prefer faster ciphers 776 clientConfig.DynamicRecordSizingDisabled = dynamicRecordSizingDisabled 777 clientConfig.MaxVersion = version 778 779 buf := make([]byte, bufsize) 780 chunks := int(math.Ceil(float64(totalBytes) / float64(len(buf)))) 781 for i := 0; i < N; i++ { 782 conn, err := Dial("tcp", ln.Addr().String(), clientConfig) 783 if err != nil { 784 b.Fatal(err) 785 } 786 for j := 0; j < chunks; j++ { 787 _, err := conn.Write(buf) 788 if err != nil { 789 b.Fatal(err) 790 } 791 _, err = io.ReadFull(conn, buf) 792 if err != nil { 793 b.Fatal(err) 794 } 795 } 796 conn.Close() 797 } 798 } 799 800 func BenchmarkThroughput(b *testing.B) { 801 for _, mode := range []string{"Max", "Dynamic"} { 802 for size := 1; size <= 64; size <<= 1 { 803 name := fmt.Sprintf("%sPacket/%dMB", mode, size) 804 b.Run(name, func(b *testing.B) { 805 b.Run("TLSv12", func(b *testing.B) { 806 throughput(b, VersionTLS12, int64(size<<20), mode == "Max") 807 }) 808 b.Run("TLSv13", func(b *testing.B) { 809 throughput(b, VersionTLS13, int64(size<<20), mode == "Max") 810 }) 811 }) 812 } 813 } 814 } 815 816 type slowConn struct { 817 net.Conn 818 bps int 819 } 820 821 func (c *slowConn) Write(p []byte) (int, error) { 822 if c.bps == 0 { 823 panic("too slow") 824 } 825 t0 := time.Now() 826 wrote := 0 827 for wrote < len(p) { 828 time.Sleep(100 * time.Microsecond) 829 allowed := int(time.Since(t0).Seconds()*float64(c.bps)) / 8 830 if allowed > len(p) { 831 allowed = len(p) 832 } 833 if wrote < allowed { 834 n, err := c.Conn.Write(p[wrote:allowed]) 835 wrote += n 836 if err != nil { 837 return wrote, err 838 } 839 } 840 } 841 return len(p), nil 842 } 843 844 func latency(b *testing.B, version uint16, bps int, dynamicRecordSizingDisabled bool) { 845 ln := newLocalListener(b) 846 defer ln.Close() 847 848 N := b.N 849 850 go func() { 851 for i := 0; i < N; i++ { 852 sconn, err := ln.Accept() 853 if err != nil { 854 // panic rather than synchronize to avoid benchmark overhead 855 // (cannot call b.Fatal in goroutine) 856 panic(fmt.Errorf("accept: %v", err)) 857 } 858 serverConfig := testConfig.Clone() 859 serverConfig.DynamicRecordSizingDisabled = dynamicRecordSizingDisabled 860 srv := Server(&slowConn{sconn, bps}, serverConfig) 861 if err := srv.Handshake(); err != nil { 862 panic(fmt.Errorf("handshake: %v", err)) 863 } 864 io.Copy(srv, srv) 865 } 866 }() 867 868 clientConfig := testConfig.Clone() 869 clientConfig.DynamicRecordSizingDisabled = dynamicRecordSizingDisabled 870 clientConfig.MaxVersion = version 871 872 buf := make([]byte, 16384) 873 peek := make([]byte, 1) 874 875 for i := 0; i < N; i++ { 876 conn, err := Dial("tcp", ln.Addr().String(), clientConfig) 877 if err != nil { 878 b.Fatal(err) 879 } 880 // make sure we're connected and previous connection has stopped 881 if _, err := conn.Write(buf[:1]); err != nil { 882 b.Fatal(err) 883 } 884 if _, err := io.ReadFull(conn, peek); err != nil { 885 b.Fatal(err) 886 } 887 if _, err := conn.Write(buf); err != nil { 888 b.Fatal(err) 889 } 890 if _, err = io.ReadFull(conn, peek); err != nil { 891 b.Fatal(err) 892 } 893 conn.Close() 894 } 895 } 896 897 func BenchmarkLatency(b *testing.B) { 898 for _, mode := range []string{"Max", "Dynamic"} { 899 for _, kbps := range []int{200, 500, 1000, 2000, 5000} { 900 name := fmt.Sprintf("%sPacket/%dkbps", mode, kbps) 901 b.Run(name, func(b *testing.B) { 902 b.Run("TLSv12", func(b *testing.B) { 903 latency(b, VersionTLS12, kbps*1000, mode == "Max") 904 }) 905 b.Run("TLSv13", func(b *testing.B) { 906 latency(b, VersionTLS13, kbps*1000, mode == "Max") 907 }) 908 }) 909 } 910 } 911 } 912 913 func TestConnectionStateMarshal(t *testing.T) { 914 cs := &ConnectionState{} 915 _, err := json.Marshal(cs) 916 if err != nil { 917 t.Errorf("json.Marshal failed on ConnectionState: %v", err) 918 } 919 } 920 921 func TestConnectionState(t *testing.T) { 922 issuer, err := x509.ParseCertificate(testRSACertificateIssuer) 923 if err != nil { 924 panic(err) 925 } 926 rootCAs := x509.NewCertPool() 927 rootCAs.AddCert(issuer) 928 929 now := func() time.Time { return time.Unix(1476984729, 0) } 930 931 const alpnProtocol = "golang" 932 const serverName = "example.golang" 933 var scts = [][]byte{[]byte("dummy sct 1"), []byte("dummy sct 2")} 934 var ocsp = []byte("dummy ocsp") 935 936 for _, v := range []uint16{VersionTLS12, VersionTLS13} { 937 var name string 938 switch v { 939 case VersionTLS12: 940 name = "TLSv12" 941 case VersionTLS13: 942 name = "TLSv13" 943 } 944 t.Run(name, func(t *testing.T) { 945 config := &Config{ 946 Time: now, 947 Rand: zeroSource{}, 948 Certificates: make([]Certificate, 1), 949 MaxVersion: v, 950 RootCAs: rootCAs, 951 ClientCAs: rootCAs, 952 ClientAuth: RequireAndVerifyClientCert, 953 NextProtos: []string{alpnProtocol}, 954 ServerName: serverName, 955 } 956 config.Certificates[0].Certificate = [][]byte{testRSACertificate} 957 config.Certificates[0].PrivateKey = testRSAPrivateKey 958 config.Certificates[0].SignedCertificateTimestamps = scts 959 config.Certificates[0].OCSPStaple = ocsp 960 961 ss, cs, err := testHandshake(t, config, config) 962 if err != nil { 963 t.Fatalf("Handshake failed: %v", err) 964 } 965 966 if ss.Version != v || cs.Version != v { 967 t.Errorf("Got versions %x (server) and %x (client), expected %x", ss.Version, cs.Version, v) 968 } 969 970 if !ss.HandshakeComplete || !cs.HandshakeComplete { 971 t.Errorf("Got HandshakeComplete %v (server) and %v (client), expected true", ss.HandshakeComplete, cs.HandshakeComplete) 972 } 973 974 if ss.DidResume || cs.DidResume { 975 t.Errorf("Got DidResume %v (server) and %v (client), expected false", ss.DidResume, cs.DidResume) 976 } 977 978 if ss.CipherSuite == 0 || cs.CipherSuite == 0 { 979 t.Errorf("Got invalid cipher suite: %v (server) and %v (client)", ss.CipherSuite, cs.CipherSuite) 980 } 981 982 if ss.NegotiatedProtocol != alpnProtocol || cs.NegotiatedProtocol != alpnProtocol { 983 t.Errorf("Got negotiated protocol %q (server) and %q (client), expected %q", ss.NegotiatedProtocol, cs.NegotiatedProtocol, alpnProtocol) 984 } 985 986 if !cs.NegotiatedProtocolIsMutual { 987 t.Errorf("Got false NegotiatedProtocolIsMutual on the client side") 988 } 989 // NegotiatedProtocolIsMutual on the server side is unspecified. 990 991 if ss.ServerName != serverName { 992 t.Errorf("Got server name %q, expected %q", ss.ServerName, serverName) 993 } 994 if cs.ServerName != "" { 995 t.Errorf("Got unexpected server name on the client side") 996 } 997 998 if len(ss.PeerCertificates) != 1 || len(cs.PeerCertificates) != 1 { 999 t.Errorf("Got %d (server) and %d (client) peer certificates, expected %d", len(ss.PeerCertificates), len(cs.PeerCertificates), 1) 1000 } 1001 1002 if len(ss.VerifiedChains) != 1 || len(cs.VerifiedChains) != 1 { 1003 t.Errorf("Got %d (server) and %d (client) verified chains, expected %d", len(ss.VerifiedChains), len(cs.VerifiedChains), 1) 1004 } else if len(ss.VerifiedChains[0]) != 2 || len(cs.VerifiedChains[0]) != 2 { 1005 t.Errorf("Got %d (server) and %d (client) long verified chain, expected %d", len(ss.VerifiedChains[0]), len(cs.VerifiedChains[0]), 2) 1006 } 1007 1008 if len(cs.SignedCertificateTimestamps) != 2 { 1009 t.Errorf("Got %d SCTs, expected %d", len(cs.SignedCertificateTimestamps), 2) 1010 } 1011 if !bytes.Equal(cs.OCSPResponse, ocsp) { 1012 t.Errorf("Got OCSPs %x, expected %x", cs.OCSPResponse, ocsp) 1013 } 1014 // Only TLS 1.3 supports OCSP and SCTs on client certs. 1015 if v == VersionTLS13 { 1016 if len(ss.SignedCertificateTimestamps) != 2 { 1017 t.Errorf("Got %d client SCTs, expected %d", len(ss.SignedCertificateTimestamps), 2) 1018 } 1019 if !bytes.Equal(ss.OCSPResponse, ocsp) { 1020 t.Errorf("Got client OCSPs %x, expected %x", ss.OCSPResponse, ocsp) 1021 } 1022 } 1023 1024 if v == VersionTLS13 { 1025 if ss.TLSUnique != nil || cs.TLSUnique != nil { 1026 t.Errorf("Got TLSUnique %x (server) and %x (client), expected nil in TLS 1.3", ss.TLSUnique, cs.TLSUnique) 1027 } 1028 } else { 1029 if ss.TLSUnique == nil || cs.TLSUnique == nil { 1030 t.Errorf("Got TLSUnique %x (server) and %x (client), expected non-nil", ss.TLSUnique, cs.TLSUnique) 1031 } 1032 } 1033 }) 1034 } 1035 } 1036 1037 // TestEscapeRoute tests that the library will still work if support for TLS 1.3 1038 // is dropped later in the Go 1.12 cycle. 1039 func TestEscapeRoute(t *testing.T) { 1040 defer func(savedSupportedVersions []uint16) { 1041 supportedVersions = savedSupportedVersions 1042 }(supportedVersions) 1043 supportedVersions = []uint16{ 1044 VersionTLS12, 1045 VersionTLS11, 1046 VersionTLS10, 1047 VersionSSL30, 1048 } 1049 1050 expectVersion(t, testConfig, testConfig, VersionTLS12) 1051 } 1052 1053 func expectVersion(t *testing.T, clientConfig, serverConfig *Config, v uint16) { 1054 ss, cs, err := testHandshake(t, clientConfig, serverConfig) 1055 if err != nil { 1056 t.Fatalf("Handshake failed: %v", err) 1057 } 1058 if ss.Version != v { 1059 t.Errorf("Server negotiated version %x, expected %x", cs.Version, v) 1060 } 1061 if cs.Version != v { 1062 t.Errorf("Client negotiated version %x, expected %x", cs.Version, v) 1063 } 1064 } 1065 1066 // TestTLS13Switch checks the behavior of GODEBUG=tls13=[0|1]. See Issue 30055. 1067 func TestTLS13Switch(t *testing.T) { 1068 defer func(savedGODEBUG string) { 1069 os.Setenv("GODEBUG", savedGODEBUG) 1070 }(os.Getenv("GODEBUG")) 1071 1072 os.Setenv("GODEBUG", "tls13=0") 1073 tls13Support.Once = sync.Once{} // reset the cache 1074 1075 tls12Config := testConfig.Clone() 1076 tls12Config.MaxVersion = VersionTLS12 1077 expectVersion(t, testConfig, testConfig, VersionTLS12) 1078 expectVersion(t, tls12Config, testConfig, VersionTLS12) 1079 expectVersion(t, testConfig, tls12Config, VersionTLS12) 1080 expectVersion(t, tls12Config, tls12Config, VersionTLS12) 1081 1082 os.Setenv("GODEBUG", "tls13=1") 1083 tls13Support.Once = sync.Once{} // reset the cache 1084 1085 expectVersion(t, testConfig, testConfig, VersionTLS13) 1086 expectVersion(t, tls12Config, testConfig, VersionTLS12) 1087 expectVersion(t, testConfig, tls12Config, VersionTLS12) 1088 expectVersion(t, tls12Config, tls12Config, VersionTLS12) 1089 } 1090 1091 // Issue 28744: Ensure that we don't modify memory 1092 // that Config doesn't own such as Certificates. 1093 func TestBuildNameToCertificate_doesntModifyCertificates(t *testing.T) { 1094 c0 := Certificate{ 1095 Certificate: [][]byte{testRSACertificate}, 1096 PrivateKey: testRSAPrivateKey, 1097 } 1098 c1 := Certificate{ 1099 Certificate: [][]byte{testSNICertificate}, 1100 PrivateKey: testRSAPrivateKey, 1101 } 1102 config := testConfig.Clone() 1103 config.Certificates = []Certificate{c0, c1} 1104 1105 config.BuildNameToCertificate() 1106 got := config.Certificates 1107 want := []Certificate{c0, c1} 1108 if !reflect.DeepEqual(got, want) { 1109 t.Fatalf("Certificates were mutated by BuildNameToCertificate\nGot: %#v\nWant: %#v\n", got, want) 1110 } 1111 }