github.com/twelsh-aw/go/src@v0.0.0-20230516233729-a56fe86a7c81/crypto/tls/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 "context" 10 "crypto" 11 "crypto/x509" 12 "encoding/json" 13 "errors" 14 "fmt" 15 "internal/testenv" 16 "io" 17 "math" 18 "net" 19 "os" 20 "reflect" 21 "sort" 22 "strings" 23 "testing" 24 "time" 25 ) 26 27 var rsaCertPEM = `-----BEGIN CERTIFICATE----- 28 MIIB0zCCAX2gAwIBAgIJAI/M7BYjwB+uMA0GCSqGSIb3DQEBBQUAMEUxCzAJBgNV 29 BAYTAkFVMRMwEQYDVQQIDApTb21lLVN0YXRlMSEwHwYDVQQKDBhJbnRlcm5ldCBX 30 aWRnaXRzIFB0eSBMdGQwHhcNMTIwOTEyMjE1MjAyWhcNMTUwOTEyMjE1MjAyWjBF 31 MQswCQYDVQQGEwJBVTETMBEGA1UECAwKU29tZS1TdGF0ZTEhMB8GA1UECgwYSW50 32 ZXJuZXQgV2lkZ2l0cyBQdHkgTHRkMFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBANLJ 33 hPHhITqQbPklG3ibCVxwGMRfp/v4XqhfdQHdcVfHap6NQ5Wok/4xIA+ui35/MmNa 34 rtNuC+BdZ1tMuVCPFZcCAwEAAaNQME4wHQYDVR0OBBYEFJvKs8RfJaXTH08W+SGv 35 zQyKn0H8MB8GA1UdIwQYMBaAFJvKs8RfJaXTH08W+SGvzQyKn0H8MAwGA1UdEwQF 36 MAMBAf8wDQYJKoZIhvcNAQEFBQADQQBJlffJHybjDGxRMqaRmDhX0+6v02TUKZsW 37 r5QuVbpQhH6u+0UgcW0jp9QwpxoPTLTWGXEWBBBurxFwiCBhkQ+V 38 -----END CERTIFICATE----- 39 ` 40 41 var rsaKeyPEM = testingKey(`-----BEGIN RSA TESTING KEY----- 42 MIIBOwIBAAJBANLJhPHhITqQbPklG3ibCVxwGMRfp/v4XqhfdQHdcVfHap6NQ5Wo 43 k/4xIA+ui35/MmNartNuC+BdZ1tMuVCPFZcCAwEAAQJAEJ2N+zsR0Xn8/Q6twa4G 44 6OB1M1WO+k+ztnX/1SvNeWu8D6GImtupLTYgjZcHufykj09jiHmjHx8u8ZZB/o1N 45 MQIhAPW+eyZo7ay3lMz1V01WVjNKK9QSn1MJlb06h/LuYv9FAiEA25WPedKgVyCW 46 SmUwbPw8fnTcpqDWE3yTO3vKcebqMSsCIBF3UmVue8YU3jybC3NxuXq3wNm34R8T 47 xVLHwDXh/6NJAiEAl2oHGGLz64BuAfjKrqwz7qMYr9HCLIe/YsoWq/olzScCIQDi 48 D2lWusoe2/nEqfDVVWGWlyJ7yOmqaVm/iNUN9B2N2g== 49 -----END RSA TESTING KEY----- 50 `) 51 52 // keyPEM is the same as rsaKeyPEM, but declares itself as just 53 // "PRIVATE KEY", not "RSA PRIVATE KEY". https://golang.org/issue/4477 54 var keyPEM = testingKey(`-----BEGIN TESTING KEY----- 55 MIIBOwIBAAJBANLJhPHhITqQbPklG3ibCVxwGMRfp/v4XqhfdQHdcVfHap6NQ5Wo 56 k/4xIA+ui35/MmNartNuC+BdZ1tMuVCPFZcCAwEAAQJAEJ2N+zsR0Xn8/Q6twa4G 57 6OB1M1WO+k+ztnX/1SvNeWu8D6GImtupLTYgjZcHufykj09jiHmjHx8u8ZZB/o1N 58 MQIhAPW+eyZo7ay3lMz1V01WVjNKK9QSn1MJlb06h/LuYv9FAiEA25WPedKgVyCW 59 SmUwbPw8fnTcpqDWE3yTO3vKcebqMSsCIBF3UmVue8YU3jybC3NxuXq3wNm34R8T 60 xVLHwDXh/6NJAiEAl2oHGGLz64BuAfjKrqwz7qMYr9HCLIe/YsoWq/olzScCIQDi 61 D2lWusoe2/nEqfDVVWGWlyJ7yOmqaVm/iNUN9B2N2g== 62 -----END TESTING KEY----- 63 `) 64 65 var ecdsaCertPEM = `-----BEGIN CERTIFICATE----- 66 MIIB/jCCAWICCQDscdUxw16XFDAJBgcqhkjOPQQBMEUxCzAJBgNVBAYTAkFVMRMw 67 EQYDVQQIEwpTb21lLVN0YXRlMSEwHwYDVQQKExhJbnRlcm5ldCBXaWRnaXRzIFB0 68 eSBMdGQwHhcNMTIxMTE0MTI0MDQ4WhcNMTUxMTE0MTI0MDQ4WjBFMQswCQYDVQQG 69 EwJBVTETMBEGA1UECBMKU29tZS1TdGF0ZTEhMB8GA1UEChMYSW50ZXJuZXQgV2lk 70 Z2l0cyBQdHkgTHRkMIGbMBAGByqGSM49AgEGBSuBBAAjA4GGAAQBY9+my9OoeSUR 71 lDQdV/x8LsOuLilthhiS1Tz4aGDHIPwC1mlvnf7fg5lecYpMCrLLhauAc1UJXcgl 72 01xoLuzgtAEAgv2P/jgytzRSpUYvgLBt1UA0leLYBy6mQQbrNEuqT3INapKIcUv8 73 XxYP0xMEUksLPq6Ca+CRSqTtrd/23uTnapkwCQYHKoZIzj0EAQOBigAwgYYCQXJo 74 A7Sl2nLVf+4Iu/tAX/IF4MavARKC4PPHK3zfuGfPR3oCCcsAoz3kAzOeijvd0iXb 75 H5jBImIxPL4WxQNiBTexAkF8D1EtpYuWdlVQ80/h/f4pBcGiXPqX5h2PQSQY7hP1 76 +jwM1FGS4fREIOvlBYr/SzzQRtwrvrzGYxDEDbsC0ZGRnA== 77 -----END CERTIFICATE----- 78 ` 79 80 var ecdsaKeyPEM = testingKey(`-----BEGIN EC PARAMETERS----- 81 BgUrgQQAIw== 82 -----END EC PARAMETERS----- 83 -----BEGIN EC TESTING KEY----- 84 MIHcAgEBBEIBrsoKp0oqcv6/JovJJDoDVSGWdirrkgCWxrprGlzB9o0X8fV675X0 85 NwuBenXFfeZvVcwluO7/Q9wkYoPd/t3jGImgBwYFK4EEACOhgYkDgYYABAFj36bL 86 06h5JRGUNB1X/Hwuw64uKW2GGJLVPPhoYMcg/ALWaW+d/t+DmV5xikwKssuFq4Bz 87 VQldyCXTXGgu7OC0AQCC/Y/+ODK3NFKlRi+AsG3VQDSV4tgHLqZBBus0S6pPcg1q 88 kohxS/xfFg/TEwRSSws+roJr4JFKpO2t3/be5OdqmQ== 89 -----END EC TESTING KEY----- 90 `) 91 92 var keyPairTests = []struct { 93 algo string 94 cert string 95 key string 96 }{ 97 {"ECDSA", ecdsaCertPEM, ecdsaKeyPEM}, 98 {"RSA", rsaCertPEM, rsaKeyPEM}, 99 {"RSA-untyped", rsaCertPEM, keyPEM}, // golang.org/issue/4477 100 } 101 102 func TestX509KeyPair(t *testing.T) { 103 t.Parallel() 104 var pem []byte 105 for _, test := range keyPairTests { 106 pem = []byte(test.cert + test.key) 107 if _, err := X509KeyPair(pem, pem); err != nil { 108 t.Errorf("Failed to load %s cert followed by %s key: %s", test.algo, test.algo, err) 109 } 110 pem = []byte(test.key + test.cert) 111 if _, err := X509KeyPair(pem, pem); err != nil { 112 t.Errorf("Failed to load %s key followed by %s cert: %s", test.algo, test.algo, err) 113 } 114 } 115 } 116 117 func TestX509KeyPairErrors(t *testing.T) { 118 _, err := X509KeyPair([]byte(rsaKeyPEM), []byte(rsaCertPEM)) 119 if err == nil { 120 t.Fatalf("X509KeyPair didn't return an error when arguments were switched") 121 } 122 if subStr := "been switched"; !strings.Contains(err.Error(), subStr) { 123 t.Fatalf("Expected %q in the error when switching arguments to X509KeyPair, but the error was %q", subStr, err) 124 } 125 126 _, err = X509KeyPair([]byte(rsaCertPEM), []byte(rsaCertPEM)) 127 if err == nil { 128 t.Fatalf("X509KeyPair didn't return an error when both arguments were certificates") 129 } 130 if subStr := "certificate"; !strings.Contains(err.Error(), subStr) { 131 t.Fatalf("Expected %q in the error when both arguments to X509KeyPair were certificates, but the error was %q", subStr, err) 132 } 133 134 const nonsensePEM = ` 135 -----BEGIN NONSENSE----- 136 Zm9vZm9vZm9v 137 -----END NONSENSE----- 138 ` 139 140 _, err = X509KeyPair([]byte(nonsensePEM), []byte(nonsensePEM)) 141 if err == nil { 142 t.Fatalf("X509KeyPair didn't return an error when both arguments were nonsense") 143 } 144 if subStr := "NONSENSE"; !strings.Contains(err.Error(), subStr) { 145 t.Fatalf("Expected %q in the error when both arguments to X509KeyPair were nonsense, but the error was %q", subStr, err) 146 } 147 } 148 149 func TestX509MixedKeyPair(t *testing.T) { 150 if _, err := X509KeyPair([]byte(rsaCertPEM), []byte(ecdsaKeyPEM)); err == nil { 151 t.Error("Load of RSA certificate succeeded with ECDSA private key") 152 } 153 if _, err := X509KeyPair([]byte(ecdsaCertPEM), []byte(rsaKeyPEM)); err == nil { 154 t.Error("Load of ECDSA certificate succeeded with RSA private key") 155 } 156 } 157 158 func newLocalListener(t testing.TB) net.Listener { 159 ln, err := net.Listen("tcp", "127.0.0.1:0") 160 if err != nil { 161 ln, err = net.Listen("tcp6", "[::1]:0") 162 } 163 if err != nil { 164 t.Fatal(err) 165 } 166 return ln 167 } 168 169 func TestDialTimeout(t *testing.T) { 170 if testing.Short() { 171 t.Skip("skipping in short mode") 172 } 173 174 timeout := 100 * time.Microsecond 175 for !t.Failed() { 176 acceptc := make(chan net.Conn) 177 listener := newLocalListener(t) 178 go func() { 179 for { 180 conn, err := listener.Accept() 181 if err != nil { 182 close(acceptc) 183 return 184 } 185 acceptc <- conn 186 } 187 }() 188 189 addr := listener.Addr().String() 190 dialer := &net.Dialer{ 191 Timeout: timeout, 192 } 193 if conn, err := DialWithDialer(dialer, "tcp", addr, nil); err == nil { 194 conn.Close() 195 t.Errorf("DialWithTimeout unexpectedly completed successfully") 196 } else if !isTimeoutError(err) { 197 t.Errorf("resulting error not a timeout: %v\nType %T: %#v", err, err, err) 198 } 199 200 listener.Close() 201 202 // We're looking for a timeout during the handshake, so check that the 203 // Listener actually accepted the connection to initiate it. (If the server 204 // takes too long to accept the connection, we might cancel before the 205 // underlying net.Conn is ever dialed — without ever attempting a 206 // handshake.) 207 lconn, ok := <-acceptc 208 if ok { 209 // The Listener accepted a connection, so assume that it was from our 210 // Dial: we triggered the timeout at the point where we wanted it! 211 t.Logf("Listener accepted a connection from %s", lconn.RemoteAddr()) 212 lconn.Close() 213 } 214 // Close any spurious extra connecitions from the listener. (This is 215 // possible if there are, for example, stray Dial calls from other tests.) 216 for extraConn := range acceptc { 217 t.Logf("spurious extra connection from %s", extraConn.RemoteAddr()) 218 extraConn.Close() 219 } 220 if ok { 221 break 222 } 223 224 t.Logf("with timeout %v, DialWithDialer returned before listener accepted any connections; retrying", timeout) 225 timeout *= 2 226 } 227 } 228 229 func TestDeadlineOnWrite(t *testing.T) { 230 if testing.Short() { 231 t.Skip("skipping in short mode") 232 } 233 234 ln := newLocalListener(t) 235 defer ln.Close() 236 237 srvCh := make(chan *Conn, 1) 238 239 go func() { 240 sconn, err := ln.Accept() 241 if err != nil { 242 srvCh <- nil 243 return 244 } 245 srv := Server(sconn, testConfig.Clone()) 246 if err := srv.Handshake(); err != nil { 247 srvCh <- nil 248 return 249 } 250 srvCh <- srv 251 }() 252 253 clientConfig := testConfig.Clone() 254 clientConfig.MaxVersion = VersionTLS12 255 conn, err := Dial("tcp", ln.Addr().String(), clientConfig) 256 if err != nil { 257 t.Fatal(err) 258 } 259 defer conn.Close() 260 261 srv := <-srvCh 262 if srv == nil { 263 t.Error(err) 264 } 265 266 // Make sure the client/server is setup correctly and is able to do a typical Write/Read 267 buf := make([]byte, 6) 268 if _, err := srv.Write([]byte("foobar")); err != nil { 269 t.Errorf("Write err: %v", err) 270 } 271 if n, err := conn.Read(buf); n != 6 || err != nil || string(buf) != "foobar" { 272 t.Errorf("Read = %d, %v, data %q; want 6, nil, foobar", n, err, buf) 273 } 274 275 // Set a deadline which should cause Write to timeout 276 if err = srv.SetDeadline(time.Now()); err != nil { 277 t.Fatalf("SetDeadline(time.Now()) err: %v", err) 278 } 279 if _, err = srv.Write([]byte("should fail")); err == nil { 280 t.Fatal("Write should have timed out") 281 } 282 283 // Clear deadline and make sure it still times out 284 if err = srv.SetDeadline(time.Time{}); err != nil { 285 t.Fatalf("SetDeadline(time.Time{}) err: %v", err) 286 } 287 if _, err = srv.Write([]byte("This connection is permanently broken")); err == nil { 288 t.Fatal("Write which previously failed should still time out") 289 } 290 291 // Verify the error 292 if ne := err.(net.Error); ne.Temporary() != false { 293 t.Error("Write timed out but incorrectly classified the error as Temporary") 294 } 295 if !isTimeoutError(err) { 296 t.Error("Write timed out but did not classify the error as a Timeout") 297 } 298 } 299 300 type readerFunc func([]byte) (int, error) 301 302 func (f readerFunc) Read(b []byte) (int, error) { return f(b) } 303 304 // TestDialer tests that tls.Dialer.DialContext can abort in the middle of a handshake. 305 // (The other cases are all handled by the existing dial tests in this package, which 306 // all also flow through the same code shared code paths) 307 func TestDialer(t *testing.T) { 308 ln := newLocalListener(t) 309 defer ln.Close() 310 311 unblockServer := make(chan struct{}) // close-only 312 defer close(unblockServer) 313 go func() { 314 conn, err := ln.Accept() 315 if err != nil { 316 return 317 } 318 defer conn.Close() 319 <-unblockServer 320 }() 321 322 ctx, cancel := context.WithCancel(context.Background()) 323 d := Dialer{Config: &Config{ 324 Rand: readerFunc(func(b []byte) (n int, err error) { 325 // By the time crypto/tls wants randomness, that means it has a TCP 326 // connection, so we're past the Dialer's dial and now blocked 327 // in a handshake. Cancel our context and see if we get unstuck. 328 // (Our TCP listener above never reads or writes, so the Handshake 329 // would otherwise be stuck forever) 330 cancel() 331 return len(b), nil 332 }), 333 ServerName: "foo", 334 }} 335 _, err := d.DialContext(ctx, "tcp", ln.Addr().String()) 336 if err != context.Canceled { 337 t.Errorf("err = %v; want context.Canceled", err) 338 } 339 } 340 341 func isTimeoutError(err error) bool { 342 if ne, ok := err.(net.Error); ok { 343 return ne.Timeout() 344 } 345 return false 346 } 347 348 // tests that Conn.Read returns (non-zero, io.EOF) instead of 349 // (non-zero, nil) when a Close (alertCloseNotify) is sitting right 350 // behind the application data in the buffer. 351 func TestConnReadNonzeroAndEOF(t *testing.T) { 352 // This test is racy: it assumes that after a write to a 353 // localhost TCP connection, the peer TCP connection can 354 // immediately read it. Because it's racy, we skip this test 355 // in short mode, and then retry it several times with an 356 // increasing sleep in between our final write (via srv.Close 357 // below) and the following read. 358 if testing.Short() { 359 t.Skip("skipping in short mode") 360 } 361 var err error 362 for delay := time.Millisecond; delay <= 64*time.Millisecond; delay *= 2 { 363 if err = testConnReadNonzeroAndEOF(t, delay); err == nil { 364 return 365 } 366 } 367 t.Error(err) 368 } 369 370 func testConnReadNonzeroAndEOF(t *testing.T, delay time.Duration) error { 371 ln := newLocalListener(t) 372 defer ln.Close() 373 374 srvCh := make(chan *Conn, 1) 375 var serr error 376 go func() { 377 sconn, err := ln.Accept() 378 if err != nil { 379 serr = err 380 srvCh <- nil 381 return 382 } 383 serverConfig := testConfig.Clone() 384 srv := Server(sconn, serverConfig) 385 if err := srv.Handshake(); err != nil { 386 serr = fmt.Errorf("handshake: %v", err) 387 srvCh <- nil 388 return 389 } 390 srvCh <- srv 391 }() 392 393 clientConfig := testConfig.Clone() 394 // In TLS 1.3, alerts are encrypted and disguised as application data, so 395 // the opportunistic peek won't work. 396 clientConfig.MaxVersion = VersionTLS12 397 conn, err := Dial("tcp", ln.Addr().String(), clientConfig) 398 if err != nil { 399 t.Fatal(err) 400 } 401 defer conn.Close() 402 403 srv := <-srvCh 404 if srv == nil { 405 return serr 406 } 407 408 buf := make([]byte, 6) 409 410 srv.Write([]byte("foobar")) 411 n, err := conn.Read(buf) 412 if n != 6 || err != nil || string(buf) != "foobar" { 413 return fmt.Errorf("Read = %d, %v, data %q; want 6, nil, foobar", n, err, buf) 414 } 415 416 srv.Write([]byte("abcdef")) 417 srv.Close() 418 time.Sleep(delay) 419 n, err = conn.Read(buf) 420 if n != 6 || string(buf) != "abcdef" { 421 return fmt.Errorf("Read = %d, buf= %q; want 6, abcdef", n, buf) 422 } 423 if err != io.EOF { 424 return fmt.Errorf("Second Read error = %v; want io.EOF", err) 425 } 426 return nil 427 } 428 429 func TestTLSUniqueMatches(t *testing.T) { 430 ln := newLocalListener(t) 431 defer ln.Close() 432 433 serverTLSUniques := make(chan []byte) 434 parentDone := make(chan struct{}) 435 childDone := make(chan struct{}) 436 defer close(parentDone) 437 go func() { 438 defer close(childDone) 439 for i := 0; i < 2; i++ { 440 sconn, err := ln.Accept() 441 if err != nil { 442 t.Error(err) 443 return 444 } 445 serverConfig := testConfig.Clone() 446 serverConfig.MaxVersion = VersionTLS12 // TLSUnique is not defined in TLS 1.3 447 srv := Server(sconn, serverConfig) 448 if err := srv.Handshake(); err != nil { 449 t.Error(err) 450 return 451 } 452 select { 453 case <-parentDone: 454 return 455 case serverTLSUniques <- srv.ConnectionState().TLSUnique: 456 } 457 } 458 }() 459 460 clientConfig := testConfig.Clone() 461 clientConfig.ClientSessionCache = NewLRUClientSessionCache(1) 462 conn, err := Dial("tcp", ln.Addr().String(), clientConfig) 463 if err != nil { 464 t.Fatal(err) 465 } 466 467 var serverTLSUniquesValue []byte 468 select { 469 case <-childDone: 470 return 471 case serverTLSUniquesValue = <-serverTLSUniques: 472 } 473 474 if !bytes.Equal(conn.ConnectionState().TLSUnique, serverTLSUniquesValue) { 475 t.Error("client and server channel bindings differ") 476 } 477 conn.Close() 478 479 conn, err = Dial("tcp", ln.Addr().String(), clientConfig) 480 if err != nil { 481 t.Fatal(err) 482 } 483 defer conn.Close() 484 if !conn.ConnectionState().DidResume { 485 t.Error("second session did not use resumption") 486 } 487 488 select { 489 case <-childDone: 490 return 491 case serverTLSUniquesValue = <-serverTLSUniques: 492 } 493 494 if !bytes.Equal(conn.ConnectionState().TLSUnique, serverTLSUniquesValue) { 495 t.Error("client and server channel bindings differ when session resumption is used") 496 } 497 } 498 499 func TestVerifyHostname(t *testing.T) { 500 testenv.MustHaveExternalNetwork(t) 501 502 c, err := Dial("tcp", "www.google.com:https", nil) 503 if err != nil { 504 t.Fatal(err) 505 } 506 if err := c.VerifyHostname("www.google.com"); err != nil { 507 t.Fatalf("verify www.google.com: %v", err) 508 } 509 if err := c.VerifyHostname("www.yahoo.com"); err == nil { 510 t.Fatalf("verify www.yahoo.com succeeded") 511 } 512 513 c, err = Dial("tcp", "www.google.com:https", &Config{InsecureSkipVerify: true}) 514 if err != nil { 515 t.Fatal(err) 516 } 517 if err := c.VerifyHostname("www.google.com"); err == nil { 518 t.Fatalf("verify www.google.com succeeded with InsecureSkipVerify=true") 519 } 520 } 521 522 func TestConnCloseBreakingWrite(t *testing.T) { 523 ln := newLocalListener(t) 524 defer ln.Close() 525 526 srvCh := make(chan *Conn, 1) 527 var serr error 528 var sconn net.Conn 529 go func() { 530 var err error 531 sconn, err = ln.Accept() 532 if err != nil { 533 serr = err 534 srvCh <- nil 535 return 536 } 537 serverConfig := testConfig.Clone() 538 srv := Server(sconn, serverConfig) 539 if err := srv.Handshake(); err != nil { 540 serr = fmt.Errorf("handshake: %v", err) 541 srvCh <- nil 542 return 543 } 544 srvCh <- srv 545 }() 546 547 cconn, err := net.Dial("tcp", ln.Addr().String()) 548 if err != nil { 549 t.Fatal(err) 550 } 551 defer cconn.Close() 552 553 conn := &changeImplConn{ 554 Conn: cconn, 555 } 556 557 clientConfig := testConfig.Clone() 558 tconn := Client(conn, clientConfig) 559 if err := tconn.Handshake(); err != nil { 560 t.Fatal(err) 561 } 562 563 srv := <-srvCh 564 if srv == nil { 565 t.Fatal(serr) 566 } 567 defer sconn.Close() 568 569 connClosed := make(chan struct{}) 570 conn.closeFunc = func() error { 571 close(connClosed) 572 return nil 573 } 574 575 inWrite := make(chan bool, 1) 576 var errConnClosed = errors.New("conn closed for test") 577 conn.writeFunc = func(p []byte) (n int, err error) { 578 inWrite <- true 579 <-connClosed 580 return 0, errConnClosed 581 } 582 583 closeReturned := make(chan bool, 1) 584 go func() { 585 <-inWrite 586 tconn.Close() // test that this doesn't block forever. 587 closeReturned <- true 588 }() 589 590 _, err = tconn.Write([]byte("foo")) 591 if err != errConnClosed { 592 t.Errorf("Write error = %v; want errConnClosed", err) 593 } 594 595 <-closeReturned 596 if err := tconn.Close(); err != net.ErrClosed { 597 t.Errorf("Close error = %v; want net.ErrClosed", err) 598 } 599 } 600 601 func TestConnCloseWrite(t *testing.T) { 602 ln := newLocalListener(t) 603 defer ln.Close() 604 605 clientDoneChan := make(chan struct{}) 606 607 serverCloseWrite := func() error { 608 sconn, err := ln.Accept() 609 if err != nil { 610 return fmt.Errorf("accept: %v", err) 611 } 612 defer sconn.Close() 613 614 serverConfig := testConfig.Clone() 615 srv := Server(sconn, serverConfig) 616 if err := srv.Handshake(); err != nil { 617 return fmt.Errorf("handshake: %v", err) 618 } 619 defer srv.Close() 620 621 data, err := io.ReadAll(srv) 622 if err != nil { 623 return err 624 } 625 if len(data) > 0 { 626 return fmt.Errorf("Read data = %q; want nothing", data) 627 } 628 629 if err := srv.CloseWrite(); err != nil { 630 return fmt.Errorf("server CloseWrite: %v", err) 631 } 632 633 // Wait for clientCloseWrite to finish, so we know we 634 // tested the CloseWrite before we defer the 635 // sconn.Close above, which would also cause the 636 // client to unblock like CloseWrite. 637 <-clientDoneChan 638 return nil 639 } 640 641 clientCloseWrite := func() error { 642 defer close(clientDoneChan) 643 644 clientConfig := testConfig.Clone() 645 conn, err := Dial("tcp", ln.Addr().String(), clientConfig) 646 if err != nil { 647 return err 648 } 649 if err := conn.Handshake(); err != nil { 650 return err 651 } 652 defer conn.Close() 653 654 if err := conn.CloseWrite(); err != nil { 655 return fmt.Errorf("client CloseWrite: %v", err) 656 } 657 658 if _, err := conn.Write([]byte{0}); err != errShutdown { 659 return fmt.Errorf("CloseWrite error = %v; want errShutdown", err) 660 } 661 662 data, err := io.ReadAll(conn) 663 if err != nil { 664 return err 665 } 666 if len(data) > 0 { 667 return fmt.Errorf("Read data = %q; want nothing", data) 668 } 669 return nil 670 } 671 672 errChan := make(chan error, 2) 673 674 go func() { errChan <- serverCloseWrite() }() 675 go func() { errChan <- clientCloseWrite() }() 676 677 for i := 0; i < 2; i++ { 678 select { 679 case err := <-errChan: 680 if err != nil { 681 t.Fatal(err) 682 } 683 case <-time.After(10 * time.Second): 684 t.Fatal("deadlock") 685 } 686 } 687 688 // Also test CloseWrite being called before the handshake is 689 // finished: 690 { 691 ln2 := newLocalListener(t) 692 defer ln2.Close() 693 694 netConn, err := net.Dial("tcp", ln2.Addr().String()) 695 if err != nil { 696 t.Fatal(err) 697 } 698 defer netConn.Close() 699 conn := Client(netConn, testConfig.Clone()) 700 701 if err := conn.CloseWrite(); err != errEarlyCloseWrite { 702 t.Errorf("CloseWrite error = %v; want errEarlyCloseWrite", err) 703 } 704 } 705 } 706 707 func TestWarningAlertFlood(t *testing.T) { 708 ln := newLocalListener(t) 709 defer ln.Close() 710 711 server := func() error { 712 sconn, err := ln.Accept() 713 if err != nil { 714 return fmt.Errorf("accept: %v", err) 715 } 716 defer sconn.Close() 717 718 serverConfig := testConfig.Clone() 719 srv := Server(sconn, serverConfig) 720 if err := srv.Handshake(); err != nil { 721 return fmt.Errorf("handshake: %v", err) 722 } 723 defer srv.Close() 724 725 _, err = io.ReadAll(srv) 726 if err == nil { 727 return errors.New("unexpected lack of error from server") 728 } 729 const expected = "too many ignored" 730 if str := err.Error(); !strings.Contains(str, expected) { 731 return fmt.Errorf("expected error containing %q, but saw: %s", expected, str) 732 } 733 734 return nil 735 } 736 737 errChan := make(chan error, 1) 738 go func() { errChan <- server() }() 739 740 clientConfig := testConfig.Clone() 741 clientConfig.MaxVersion = VersionTLS12 // there are no warning alerts in TLS 1.3 742 conn, err := Dial("tcp", ln.Addr().String(), clientConfig) 743 if err != nil { 744 t.Fatal(err) 745 } 746 defer conn.Close() 747 if err := conn.Handshake(); err != nil { 748 t.Fatal(err) 749 } 750 751 for i := 0; i < maxUselessRecords+1; i++ { 752 conn.sendAlert(alertNoRenegotiation) 753 } 754 755 if err := <-errChan; err != nil { 756 t.Fatal(err) 757 } 758 } 759 760 func TestCloneFuncFields(t *testing.T) { 761 const expectedCount = 6 762 called := 0 763 764 c1 := Config{ 765 Time: func() time.Time { 766 called |= 1 << 0 767 return time.Time{} 768 }, 769 GetCertificate: func(*ClientHelloInfo) (*Certificate, error) { 770 called |= 1 << 1 771 return nil, nil 772 }, 773 GetClientCertificate: func(*CertificateRequestInfo) (*Certificate, error) { 774 called |= 1 << 2 775 return nil, nil 776 }, 777 GetConfigForClient: func(*ClientHelloInfo) (*Config, error) { 778 called |= 1 << 3 779 return nil, nil 780 }, 781 VerifyPeerCertificate: func(rawCerts [][]byte, verifiedChains [][]*x509.Certificate) error { 782 called |= 1 << 4 783 return nil 784 }, 785 VerifyConnection: func(ConnectionState) error { 786 called |= 1 << 5 787 return nil 788 }, 789 } 790 791 c2 := c1.Clone() 792 793 c2.Time() 794 c2.GetCertificate(nil) 795 c2.GetClientCertificate(nil) 796 c2.GetConfigForClient(nil) 797 c2.VerifyPeerCertificate(nil, nil) 798 c2.VerifyConnection(ConnectionState{}) 799 800 if called != (1<<expectedCount)-1 { 801 t.Fatalf("expected %d calls but saw calls %b", expectedCount, called) 802 } 803 } 804 805 func TestCloneNonFuncFields(t *testing.T) { 806 var c1 Config 807 v := reflect.ValueOf(&c1).Elem() 808 809 typ := v.Type() 810 for i := 0; i < typ.NumField(); i++ { 811 f := v.Field(i) 812 // testing/quick can't handle functions or interfaces and so 813 // isn't used here. 814 switch fn := typ.Field(i).Name; fn { 815 case "Rand": 816 f.Set(reflect.ValueOf(io.Reader(os.Stdin))) 817 case "Time", "GetCertificate", "GetConfigForClient", "VerifyPeerCertificate", "VerifyConnection", "GetClientCertificate": 818 // DeepEqual can't compare functions. If you add a 819 // function field to this list, you must also change 820 // TestCloneFuncFields to ensure that the func field is 821 // cloned. 822 case "Certificates": 823 f.Set(reflect.ValueOf([]Certificate{ 824 {Certificate: [][]byte{{'b'}}}, 825 })) 826 case "NameToCertificate": 827 f.Set(reflect.ValueOf(map[string]*Certificate{"a": nil})) 828 case "RootCAs", "ClientCAs": 829 f.Set(reflect.ValueOf(x509.NewCertPool())) 830 case "ClientSessionCache": 831 f.Set(reflect.ValueOf(NewLRUClientSessionCache(10))) 832 case "KeyLogWriter": 833 f.Set(reflect.ValueOf(io.Writer(os.Stdout))) 834 case "NextProtos": 835 f.Set(reflect.ValueOf([]string{"a", "b"})) 836 case "ServerName": 837 f.Set(reflect.ValueOf("b")) 838 case "ClientAuth": 839 f.Set(reflect.ValueOf(VerifyClientCertIfGiven)) 840 case "InsecureSkipVerify", "SessionTicketsDisabled", "DynamicRecordSizingDisabled", "PreferServerCipherSuites": 841 f.Set(reflect.ValueOf(true)) 842 case "MinVersion", "MaxVersion": 843 f.Set(reflect.ValueOf(uint16(VersionTLS12))) 844 case "SessionTicketKey": 845 f.Set(reflect.ValueOf([32]byte{})) 846 case "CipherSuites": 847 f.Set(reflect.ValueOf([]uint16{1, 2})) 848 case "CurvePreferences": 849 f.Set(reflect.ValueOf([]CurveID{CurveP256})) 850 case "Renegotiation": 851 f.Set(reflect.ValueOf(RenegotiateOnceAsClient)) 852 case "mutex", "autoSessionTicketKeys", "sessionTicketKeys": 853 continue // these are unexported fields that are handled separately 854 default: 855 t.Errorf("all fields must be accounted for, but saw unknown field %q", fn) 856 } 857 } 858 // Set the unexported fields related to session ticket keys, which are copied with Clone(). 859 c1.autoSessionTicketKeys = []ticketKey{c1.ticketKeyFromBytes(c1.SessionTicketKey)} 860 c1.sessionTicketKeys = []ticketKey{c1.ticketKeyFromBytes(c1.SessionTicketKey)} 861 862 c2 := c1.Clone() 863 if !reflect.DeepEqual(&c1, c2) { 864 t.Errorf("clone failed to copy a field") 865 } 866 } 867 868 func TestCloneNilConfig(t *testing.T) { 869 var config *Config 870 if cc := config.Clone(); cc != nil { 871 t.Fatalf("Clone with nil should return nil, got: %+v", cc) 872 } 873 } 874 875 // changeImplConn is a net.Conn which can change its Write and Close 876 // methods. 877 type changeImplConn struct { 878 net.Conn 879 writeFunc func([]byte) (int, error) 880 closeFunc func() error 881 } 882 883 func (w *changeImplConn) Write(p []byte) (n int, err error) { 884 if w.writeFunc != nil { 885 return w.writeFunc(p) 886 } 887 return w.Conn.Write(p) 888 } 889 890 func (w *changeImplConn) Close() error { 891 if w.closeFunc != nil { 892 return w.closeFunc() 893 } 894 return w.Conn.Close() 895 } 896 897 func throughput(b *testing.B, version uint16, totalBytes int64, dynamicRecordSizingDisabled bool) { 898 ln := newLocalListener(b) 899 defer ln.Close() 900 901 N := b.N 902 903 // Less than 64KB because Windows appears to use a TCP rwin < 64KB. 904 // See Issue #15899. 905 const bufsize = 32 << 10 906 907 go func() { 908 buf := make([]byte, bufsize) 909 for i := 0; i < N; i++ { 910 sconn, err := ln.Accept() 911 if err != nil { 912 // panic rather than synchronize to avoid benchmark overhead 913 // (cannot call b.Fatal in goroutine) 914 panic(fmt.Errorf("accept: %v", err)) 915 } 916 serverConfig := testConfig.Clone() 917 serverConfig.CipherSuites = nil // the defaults may prefer faster ciphers 918 serverConfig.DynamicRecordSizingDisabled = dynamicRecordSizingDisabled 919 srv := Server(sconn, serverConfig) 920 if err := srv.Handshake(); err != nil { 921 panic(fmt.Errorf("handshake: %v", err)) 922 } 923 if _, err := io.CopyBuffer(srv, srv, buf); err != nil { 924 panic(fmt.Errorf("copy buffer: %v", err)) 925 } 926 } 927 }() 928 929 b.SetBytes(totalBytes) 930 clientConfig := testConfig.Clone() 931 clientConfig.CipherSuites = nil // the defaults may prefer faster ciphers 932 clientConfig.DynamicRecordSizingDisabled = dynamicRecordSizingDisabled 933 clientConfig.MaxVersion = version 934 935 buf := make([]byte, bufsize) 936 chunks := int(math.Ceil(float64(totalBytes) / float64(len(buf)))) 937 for i := 0; i < N; i++ { 938 conn, err := Dial("tcp", ln.Addr().String(), clientConfig) 939 if err != nil { 940 b.Fatal(err) 941 } 942 for j := 0; j < chunks; j++ { 943 _, err := conn.Write(buf) 944 if err != nil { 945 b.Fatal(err) 946 } 947 _, err = io.ReadFull(conn, buf) 948 if err != nil { 949 b.Fatal(err) 950 } 951 } 952 conn.Close() 953 } 954 } 955 956 func BenchmarkThroughput(b *testing.B) { 957 for _, mode := range []string{"Max", "Dynamic"} { 958 for size := 1; size <= 64; size <<= 1 { 959 name := fmt.Sprintf("%sPacket/%dMB", mode, size) 960 b.Run(name, func(b *testing.B) { 961 b.Run("TLSv12", func(b *testing.B) { 962 throughput(b, VersionTLS12, int64(size<<20), mode == "Max") 963 }) 964 b.Run("TLSv13", func(b *testing.B) { 965 throughput(b, VersionTLS13, int64(size<<20), mode == "Max") 966 }) 967 }) 968 } 969 } 970 } 971 972 type slowConn struct { 973 net.Conn 974 bps int 975 } 976 977 func (c *slowConn) Write(p []byte) (int, error) { 978 if c.bps == 0 { 979 panic("too slow") 980 } 981 t0 := time.Now() 982 wrote := 0 983 for wrote < len(p) { 984 time.Sleep(100 * time.Microsecond) 985 allowed := int(time.Since(t0).Seconds()*float64(c.bps)) / 8 986 if allowed > len(p) { 987 allowed = len(p) 988 } 989 if wrote < allowed { 990 n, err := c.Conn.Write(p[wrote:allowed]) 991 wrote += n 992 if err != nil { 993 return wrote, err 994 } 995 } 996 } 997 return len(p), nil 998 } 999 1000 func latency(b *testing.B, version uint16, bps int, dynamicRecordSizingDisabled bool) { 1001 ln := newLocalListener(b) 1002 defer ln.Close() 1003 1004 N := b.N 1005 1006 go func() { 1007 for i := 0; i < N; i++ { 1008 sconn, err := ln.Accept() 1009 if err != nil { 1010 // panic rather than synchronize to avoid benchmark overhead 1011 // (cannot call b.Fatal in goroutine) 1012 panic(fmt.Errorf("accept: %v", err)) 1013 } 1014 serverConfig := testConfig.Clone() 1015 serverConfig.DynamicRecordSizingDisabled = dynamicRecordSizingDisabled 1016 srv := Server(&slowConn{sconn, bps}, serverConfig) 1017 if err := srv.Handshake(); err != nil { 1018 panic(fmt.Errorf("handshake: %v", err)) 1019 } 1020 io.Copy(srv, srv) 1021 } 1022 }() 1023 1024 clientConfig := testConfig.Clone() 1025 clientConfig.DynamicRecordSizingDisabled = dynamicRecordSizingDisabled 1026 clientConfig.MaxVersion = version 1027 1028 buf := make([]byte, 16384) 1029 peek := make([]byte, 1) 1030 1031 for i := 0; i < N; i++ { 1032 conn, err := Dial("tcp", ln.Addr().String(), clientConfig) 1033 if err != nil { 1034 b.Fatal(err) 1035 } 1036 // make sure we're connected and previous connection has stopped 1037 if _, err := conn.Write(buf[:1]); err != nil { 1038 b.Fatal(err) 1039 } 1040 if _, err := io.ReadFull(conn, peek); err != nil { 1041 b.Fatal(err) 1042 } 1043 if _, err := conn.Write(buf); err != nil { 1044 b.Fatal(err) 1045 } 1046 if _, err = io.ReadFull(conn, peek); err != nil { 1047 b.Fatal(err) 1048 } 1049 conn.Close() 1050 } 1051 } 1052 1053 func BenchmarkLatency(b *testing.B) { 1054 for _, mode := range []string{"Max", "Dynamic"} { 1055 for _, kbps := range []int{200, 500, 1000, 2000, 5000} { 1056 name := fmt.Sprintf("%sPacket/%dkbps", mode, kbps) 1057 b.Run(name, func(b *testing.B) { 1058 b.Run("TLSv12", func(b *testing.B) { 1059 latency(b, VersionTLS12, kbps*1000, mode == "Max") 1060 }) 1061 b.Run("TLSv13", func(b *testing.B) { 1062 latency(b, VersionTLS13, kbps*1000, mode == "Max") 1063 }) 1064 }) 1065 } 1066 } 1067 } 1068 1069 func TestConnectionStateMarshal(t *testing.T) { 1070 cs := &ConnectionState{} 1071 _, err := json.Marshal(cs) 1072 if err != nil { 1073 t.Errorf("json.Marshal failed on ConnectionState: %v", err) 1074 } 1075 } 1076 1077 func TestConnectionState(t *testing.T) { 1078 issuer, err := x509.ParseCertificate(testRSACertificateIssuer) 1079 if err != nil { 1080 panic(err) 1081 } 1082 rootCAs := x509.NewCertPool() 1083 rootCAs.AddCert(issuer) 1084 1085 now := func() time.Time { return time.Unix(1476984729, 0) } 1086 1087 const alpnProtocol = "golang" 1088 const serverName = "example.golang" 1089 var scts = [][]byte{[]byte("dummy sct 1"), []byte("dummy sct 2")} 1090 var ocsp = []byte("dummy ocsp") 1091 1092 for _, v := range []uint16{VersionTLS12, VersionTLS13} { 1093 var name string 1094 switch v { 1095 case VersionTLS12: 1096 name = "TLSv12" 1097 case VersionTLS13: 1098 name = "TLSv13" 1099 } 1100 t.Run(name, func(t *testing.T) { 1101 config := &Config{ 1102 Time: now, 1103 Rand: zeroSource{}, 1104 Certificates: make([]Certificate, 1), 1105 MaxVersion: v, 1106 RootCAs: rootCAs, 1107 ClientCAs: rootCAs, 1108 ClientAuth: RequireAndVerifyClientCert, 1109 NextProtos: []string{alpnProtocol}, 1110 ServerName: serverName, 1111 } 1112 config.Certificates[0].Certificate = [][]byte{testRSACertificate} 1113 config.Certificates[0].PrivateKey = testRSAPrivateKey 1114 config.Certificates[0].SignedCertificateTimestamps = scts 1115 config.Certificates[0].OCSPStaple = ocsp 1116 1117 ss, cs, err := testHandshake(t, config, config) 1118 if err != nil { 1119 t.Fatalf("Handshake failed: %v", err) 1120 } 1121 1122 if ss.Version != v || cs.Version != v { 1123 t.Errorf("Got versions %x (server) and %x (client), expected %x", ss.Version, cs.Version, v) 1124 } 1125 1126 if !ss.HandshakeComplete || !cs.HandshakeComplete { 1127 t.Errorf("Got HandshakeComplete %v (server) and %v (client), expected true", ss.HandshakeComplete, cs.HandshakeComplete) 1128 } 1129 1130 if ss.DidResume || cs.DidResume { 1131 t.Errorf("Got DidResume %v (server) and %v (client), expected false", ss.DidResume, cs.DidResume) 1132 } 1133 1134 if ss.CipherSuite == 0 || cs.CipherSuite == 0 { 1135 t.Errorf("Got invalid cipher suite: %v (server) and %v (client)", ss.CipherSuite, cs.CipherSuite) 1136 } 1137 1138 if ss.NegotiatedProtocol != alpnProtocol || cs.NegotiatedProtocol != alpnProtocol { 1139 t.Errorf("Got negotiated protocol %q (server) and %q (client), expected %q", ss.NegotiatedProtocol, cs.NegotiatedProtocol, alpnProtocol) 1140 } 1141 1142 if !cs.NegotiatedProtocolIsMutual { 1143 t.Errorf("Got false NegotiatedProtocolIsMutual on the client side") 1144 } 1145 // NegotiatedProtocolIsMutual on the server side is unspecified. 1146 1147 if ss.ServerName != serverName { 1148 t.Errorf("Got server name %q, expected %q", ss.ServerName, serverName) 1149 } 1150 if cs.ServerName != serverName { 1151 t.Errorf("Got server name on client connection %q, expected %q", cs.ServerName, serverName) 1152 } 1153 1154 if len(ss.PeerCertificates) != 1 || len(cs.PeerCertificates) != 1 { 1155 t.Errorf("Got %d (server) and %d (client) peer certificates, expected %d", len(ss.PeerCertificates), len(cs.PeerCertificates), 1) 1156 } 1157 1158 if len(ss.VerifiedChains) != 1 || len(cs.VerifiedChains) != 1 { 1159 t.Errorf("Got %d (server) and %d (client) verified chains, expected %d", len(ss.VerifiedChains), len(cs.VerifiedChains), 1) 1160 } else if len(ss.VerifiedChains[0]) != 2 || len(cs.VerifiedChains[0]) != 2 { 1161 t.Errorf("Got %d (server) and %d (client) long verified chain, expected %d", len(ss.VerifiedChains[0]), len(cs.VerifiedChains[0]), 2) 1162 } 1163 1164 if len(cs.SignedCertificateTimestamps) != 2 { 1165 t.Errorf("Got %d SCTs, expected %d", len(cs.SignedCertificateTimestamps), 2) 1166 } 1167 if !bytes.Equal(cs.OCSPResponse, ocsp) { 1168 t.Errorf("Got OCSPs %x, expected %x", cs.OCSPResponse, ocsp) 1169 } 1170 // Only TLS 1.3 supports OCSP and SCTs on client certs. 1171 if v == VersionTLS13 { 1172 if len(ss.SignedCertificateTimestamps) != 2 { 1173 t.Errorf("Got %d client SCTs, expected %d", len(ss.SignedCertificateTimestamps), 2) 1174 } 1175 if !bytes.Equal(ss.OCSPResponse, ocsp) { 1176 t.Errorf("Got client OCSPs %x, expected %x", ss.OCSPResponse, ocsp) 1177 } 1178 } 1179 1180 if v == VersionTLS13 { 1181 if ss.TLSUnique != nil || cs.TLSUnique != nil { 1182 t.Errorf("Got TLSUnique %x (server) and %x (client), expected nil in TLS 1.3", ss.TLSUnique, cs.TLSUnique) 1183 } 1184 } else { 1185 if ss.TLSUnique == nil || cs.TLSUnique == nil { 1186 t.Errorf("Got TLSUnique %x (server) and %x (client), expected non-nil", ss.TLSUnique, cs.TLSUnique) 1187 } 1188 } 1189 }) 1190 } 1191 } 1192 1193 // Issue 28744: Ensure that we don't modify memory 1194 // that Config doesn't own such as Certificates. 1195 func TestBuildNameToCertificate_doesntModifyCertificates(t *testing.T) { 1196 c0 := Certificate{ 1197 Certificate: [][]byte{testRSACertificate}, 1198 PrivateKey: testRSAPrivateKey, 1199 } 1200 c1 := Certificate{ 1201 Certificate: [][]byte{testSNICertificate}, 1202 PrivateKey: testRSAPrivateKey, 1203 } 1204 config := testConfig.Clone() 1205 config.Certificates = []Certificate{c0, c1} 1206 1207 config.BuildNameToCertificate() 1208 got := config.Certificates 1209 want := []Certificate{c0, c1} 1210 if !reflect.DeepEqual(got, want) { 1211 t.Fatalf("Certificates were mutated by BuildNameToCertificate\nGot: %#v\nWant: %#v\n", got, want) 1212 } 1213 } 1214 1215 func testingKey(s string) string { return strings.ReplaceAll(s, "TESTING KEY", "PRIVATE KEY") } 1216 1217 func TestClientHelloInfo_SupportsCertificate(t *testing.T) { 1218 rsaCert := &Certificate{ 1219 Certificate: [][]byte{testRSACertificate}, 1220 PrivateKey: testRSAPrivateKey, 1221 } 1222 pkcs1Cert := &Certificate{ 1223 Certificate: [][]byte{testRSACertificate}, 1224 PrivateKey: testRSAPrivateKey, 1225 SupportedSignatureAlgorithms: []SignatureScheme{PKCS1WithSHA1, PKCS1WithSHA256}, 1226 } 1227 ecdsaCert := &Certificate{ 1228 // ECDSA P-256 certificate 1229 Certificate: [][]byte{testP256Certificate}, 1230 PrivateKey: testP256PrivateKey, 1231 } 1232 ed25519Cert := &Certificate{ 1233 Certificate: [][]byte{testEd25519Certificate}, 1234 PrivateKey: testEd25519PrivateKey, 1235 } 1236 1237 tests := []struct { 1238 c *Certificate 1239 chi *ClientHelloInfo 1240 wantErr string 1241 }{ 1242 {rsaCert, &ClientHelloInfo{ 1243 ServerName: "example.golang", 1244 SignatureSchemes: []SignatureScheme{PSSWithSHA256}, 1245 SupportedVersions: []uint16{VersionTLS13}, 1246 }, ""}, 1247 {ecdsaCert, &ClientHelloInfo{ 1248 SignatureSchemes: []SignatureScheme{PSSWithSHA256, ECDSAWithP256AndSHA256}, 1249 SupportedVersions: []uint16{VersionTLS13, VersionTLS12}, 1250 }, ""}, 1251 {rsaCert, &ClientHelloInfo{ 1252 ServerName: "example.com", 1253 SignatureSchemes: []SignatureScheme{PSSWithSHA256}, 1254 SupportedVersions: []uint16{VersionTLS13}, 1255 }, "not valid for requested server name"}, 1256 {ecdsaCert, &ClientHelloInfo{ 1257 SignatureSchemes: []SignatureScheme{ECDSAWithP384AndSHA384}, 1258 SupportedVersions: []uint16{VersionTLS13}, 1259 }, "signature algorithms"}, 1260 {pkcs1Cert, &ClientHelloInfo{ 1261 SignatureSchemes: []SignatureScheme{PSSWithSHA256, ECDSAWithP256AndSHA256}, 1262 SupportedVersions: []uint16{VersionTLS13}, 1263 }, "signature algorithms"}, 1264 1265 {rsaCert, &ClientHelloInfo{ 1266 CipherSuites: []uint16{TLS_RSA_WITH_AES_128_GCM_SHA256}, 1267 SignatureSchemes: []SignatureScheme{PKCS1WithSHA1}, 1268 SupportedVersions: []uint16{VersionTLS13, VersionTLS12}, 1269 }, "signature algorithms"}, 1270 {rsaCert, &ClientHelloInfo{ 1271 CipherSuites: []uint16{TLS_RSA_WITH_AES_128_GCM_SHA256}, 1272 SignatureSchemes: []SignatureScheme{PKCS1WithSHA1}, 1273 SupportedVersions: []uint16{VersionTLS13, VersionTLS12}, 1274 config: &Config{ 1275 MaxVersion: VersionTLS12, 1276 }, 1277 }, ""}, // Check that mutual version selection works. 1278 1279 {ecdsaCert, &ClientHelloInfo{ 1280 CipherSuites: []uint16{TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256}, 1281 SupportedCurves: []CurveID{CurveP256}, 1282 SupportedPoints: []uint8{pointFormatUncompressed}, 1283 SignatureSchemes: []SignatureScheme{ECDSAWithP256AndSHA256}, 1284 SupportedVersions: []uint16{VersionTLS12}, 1285 }, ""}, 1286 {ecdsaCert, &ClientHelloInfo{ 1287 CipherSuites: []uint16{TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256}, 1288 SupportedCurves: []CurveID{CurveP256}, 1289 SupportedPoints: []uint8{pointFormatUncompressed}, 1290 SignatureSchemes: []SignatureScheme{ECDSAWithP384AndSHA384}, 1291 SupportedVersions: []uint16{VersionTLS12}, 1292 }, ""}, // TLS 1.2 does not restrict curves based on the SignatureScheme. 1293 {ecdsaCert, &ClientHelloInfo{ 1294 CipherSuites: []uint16{TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256}, 1295 SupportedCurves: []CurveID{CurveP256}, 1296 SupportedPoints: []uint8{pointFormatUncompressed}, 1297 SignatureSchemes: nil, 1298 SupportedVersions: []uint16{VersionTLS12}, 1299 }, ""}, // TLS 1.2 comes with default signature schemes. 1300 {ecdsaCert, &ClientHelloInfo{ 1301 CipherSuites: []uint16{TLS_RSA_WITH_AES_128_GCM_SHA256}, 1302 SupportedCurves: []CurveID{CurveP256}, 1303 SupportedPoints: []uint8{pointFormatUncompressed}, 1304 SignatureSchemes: []SignatureScheme{ECDSAWithP256AndSHA256}, 1305 SupportedVersions: []uint16{VersionTLS12}, 1306 }, "cipher suite"}, 1307 {ecdsaCert, &ClientHelloInfo{ 1308 CipherSuites: []uint16{TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256}, 1309 SupportedCurves: []CurveID{CurveP256}, 1310 SupportedPoints: []uint8{pointFormatUncompressed}, 1311 SignatureSchemes: []SignatureScheme{ECDSAWithP256AndSHA256}, 1312 SupportedVersions: []uint16{VersionTLS12}, 1313 config: &Config{ 1314 CipherSuites: []uint16{TLS_RSA_WITH_AES_128_GCM_SHA256}, 1315 }, 1316 }, "cipher suite"}, 1317 {ecdsaCert, &ClientHelloInfo{ 1318 CipherSuites: []uint16{TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256}, 1319 SupportedCurves: []CurveID{CurveP384}, 1320 SupportedPoints: []uint8{pointFormatUncompressed}, 1321 SignatureSchemes: []SignatureScheme{ECDSAWithP256AndSHA256}, 1322 SupportedVersions: []uint16{VersionTLS12}, 1323 }, "certificate curve"}, 1324 {ecdsaCert, &ClientHelloInfo{ 1325 CipherSuites: []uint16{TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256}, 1326 SupportedCurves: []CurveID{CurveP256}, 1327 SupportedPoints: []uint8{1}, 1328 SignatureSchemes: []SignatureScheme{ECDSAWithP256AndSHA256}, 1329 SupportedVersions: []uint16{VersionTLS12}, 1330 }, "doesn't support ECDHE"}, 1331 {ecdsaCert, &ClientHelloInfo{ 1332 CipherSuites: []uint16{TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256}, 1333 SupportedCurves: []CurveID{CurveP256}, 1334 SupportedPoints: []uint8{pointFormatUncompressed}, 1335 SignatureSchemes: []SignatureScheme{PSSWithSHA256}, 1336 SupportedVersions: []uint16{VersionTLS12}, 1337 }, "signature algorithms"}, 1338 1339 {ed25519Cert, &ClientHelloInfo{ 1340 CipherSuites: []uint16{TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256}, 1341 SupportedCurves: []CurveID{CurveP256}, // only relevant for ECDHE support 1342 SupportedPoints: []uint8{pointFormatUncompressed}, 1343 SignatureSchemes: []SignatureScheme{Ed25519}, 1344 SupportedVersions: []uint16{VersionTLS12}, 1345 }, ""}, 1346 {ed25519Cert, &ClientHelloInfo{ 1347 CipherSuites: []uint16{TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256}, 1348 SupportedCurves: []CurveID{CurveP256}, // only relevant for ECDHE support 1349 SupportedPoints: []uint8{pointFormatUncompressed}, 1350 SignatureSchemes: []SignatureScheme{Ed25519}, 1351 SupportedVersions: []uint16{VersionTLS10}, 1352 }, "doesn't support Ed25519"}, 1353 {ed25519Cert, &ClientHelloInfo{ 1354 CipherSuites: []uint16{TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256}, 1355 SupportedCurves: []CurveID{}, 1356 SupportedPoints: []uint8{pointFormatUncompressed}, 1357 SignatureSchemes: []SignatureScheme{Ed25519}, 1358 SupportedVersions: []uint16{VersionTLS12}, 1359 }, "doesn't support ECDHE"}, 1360 1361 {rsaCert, &ClientHelloInfo{ 1362 CipherSuites: []uint16{TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA}, 1363 SupportedCurves: []CurveID{CurveP256}, // only relevant for ECDHE support 1364 SupportedPoints: []uint8{pointFormatUncompressed}, 1365 SupportedVersions: []uint16{VersionTLS10}, 1366 }, ""}, 1367 {rsaCert, &ClientHelloInfo{ 1368 CipherSuites: []uint16{TLS_RSA_WITH_AES_128_GCM_SHA256}, 1369 SupportedVersions: []uint16{VersionTLS12}, 1370 }, ""}, // static RSA fallback 1371 } 1372 for i, tt := range tests { 1373 err := tt.chi.SupportsCertificate(tt.c) 1374 switch { 1375 case tt.wantErr == "" && err != nil: 1376 t.Errorf("%d: unexpected error: %v", i, err) 1377 case tt.wantErr != "" && err == nil: 1378 t.Errorf("%d: unexpected success", i) 1379 case tt.wantErr != "" && !strings.Contains(err.Error(), tt.wantErr): 1380 t.Errorf("%d: got error %q, expected %q", i, err, tt.wantErr) 1381 } 1382 } 1383 } 1384 1385 func TestCipherSuites(t *testing.T) { 1386 var lastID uint16 1387 for _, c := range CipherSuites() { 1388 if lastID > c.ID { 1389 t.Errorf("CipherSuites are not ordered by ID: got %#04x after %#04x", c.ID, lastID) 1390 } else { 1391 lastID = c.ID 1392 } 1393 1394 if c.Insecure { 1395 t.Errorf("%#04x: Insecure CipherSuite returned by CipherSuites()", c.ID) 1396 } 1397 } 1398 lastID = 0 1399 for _, c := range InsecureCipherSuites() { 1400 if lastID > c.ID { 1401 t.Errorf("InsecureCipherSuites are not ordered by ID: got %#04x after %#04x", c.ID, lastID) 1402 } else { 1403 lastID = c.ID 1404 } 1405 1406 if !c.Insecure { 1407 t.Errorf("%#04x: not Insecure CipherSuite returned by InsecureCipherSuites()", c.ID) 1408 } 1409 } 1410 1411 CipherSuiteByID := func(id uint16) *CipherSuite { 1412 for _, c := range CipherSuites() { 1413 if c.ID == id { 1414 return c 1415 } 1416 } 1417 for _, c := range InsecureCipherSuites() { 1418 if c.ID == id { 1419 return c 1420 } 1421 } 1422 return nil 1423 } 1424 1425 for _, c := range cipherSuites { 1426 cc := CipherSuiteByID(c.id) 1427 if cc == nil { 1428 t.Errorf("%#04x: no CipherSuite entry", c.id) 1429 continue 1430 } 1431 1432 if tls12Only := c.flags&suiteTLS12 != 0; tls12Only && len(cc.SupportedVersions) != 1 { 1433 t.Errorf("%#04x: suite is TLS 1.2 only, but SupportedVersions is %v", c.id, cc.SupportedVersions) 1434 } else if !tls12Only && len(cc.SupportedVersions) != 3 { 1435 t.Errorf("%#04x: suite TLS 1.0-1.2, but SupportedVersions is %v", c.id, cc.SupportedVersions) 1436 } 1437 1438 if got := CipherSuiteName(c.id); got != cc.Name { 1439 t.Errorf("%#04x: unexpected CipherSuiteName: got %q, expected %q", c.id, got, cc.Name) 1440 } 1441 } 1442 for _, c := range cipherSuitesTLS13 { 1443 cc := CipherSuiteByID(c.id) 1444 if cc == nil { 1445 t.Errorf("%#04x: no CipherSuite entry", c.id) 1446 continue 1447 } 1448 1449 if cc.Insecure { 1450 t.Errorf("%#04x: Insecure %v, expected false", c.id, cc.Insecure) 1451 } 1452 if len(cc.SupportedVersions) != 1 || cc.SupportedVersions[0] != VersionTLS13 { 1453 t.Errorf("%#04x: suite is TLS 1.3 only, but SupportedVersions is %v", c.id, cc.SupportedVersions) 1454 } 1455 1456 if got := CipherSuiteName(c.id); got != cc.Name { 1457 t.Errorf("%#04x: unexpected CipherSuiteName: got %q, expected %q", c.id, got, cc.Name) 1458 } 1459 } 1460 1461 if got := CipherSuiteName(0xabc); got != "0x0ABC" { 1462 t.Errorf("unexpected fallback CipherSuiteName: got %q, expected 0x0ABC", got) 1463 } 1464 1465 if len(cipherSuitesPreferenceOrder) != len(cipherSuites) { 1466 t.Errorf("cipherSuitesPreferenceOrder is not the same size as cipherSuites") 1467 } 1468 if len(cipherSuitesPreferenceOrderNoAES) != len(cipherSuitesPreferenceOrder) { 1469 t.Errorf("cipherSuitesPreferenceOrderNoAES is not the same size as cipherSuitesPreferenceOrder") 1470 } 1471 1472 // Check that disabled suites are at the end of the preference lists, and 1473 // that they are marked insecure. 1474 for i, id := range disabledCipherSuites { 1475 offset := len(cipherSuitesPreferenceOrder) - len(disabledCipherSuites) 1476 if cipherSuitesPreferenceOrder[offset+i] != id { 1477 t.Errorf("disabledCipherSuites[%d]: not at the end of cipherSuitesPreferenceOrder", i) 1478 } 1479 if cipherSuitesPreferenceOrderNoAES[offset+i] != id { 1480 t.Errorf("disabledCipherSuites[%d]: not at the end of cipherSuitesPreferenceOrderNoAES", i) 1481 } 1482 c := CipherSuiteByID(id) 1483 if c == nil { 1484 t.Errorf("%#04x: no CipherSuite entry", id) 1485 continue 1486 } 1487 if !c.Insecure { 1488 t.Errorf("%#04x: disabled by default but not marked insecure", id) 1489 } 1490 } 1491 1492 for i, prefOrder := range [][]uint16{cipherSuitesPreferenceOrder, cipherSuitesPreferenceOrderNoAES} { 1493 // Check that insecure and HTTP/2 bad cipher suites are at the end of 1494 // the preference lists. 1495 var sawInsecure, sawBad bool 1496 for _, id := range prefOrder { 1497 c := CipherSuiteByID(id) 1498 if c == nil { 1499 t.Errorf("%#04x: no CipherSuite entry", id) 1500 continue 1501 } 1502 1503 if c.Insecure { 1504 sawInsecure = true 1505 } else if sawInsecure { 1506 t.Errorf("%#04x: secure suite after insecure one(s)", id) 1507 } 1508 1509 if http2isBadCipher(id) { 1510 sawBad = true 1511 } else if sawBad { 1512 t.Errorf("%#04x: non-bad suite after bad HTTP/2 one(s)", id) 1513 } 1514 } 1515 1516 // Check that the list is sorted according to the documented criteria. 1517 isBetter := func(a, b int) bool { 1518 aSuite, bSuite := cipherSuiteByID(prefOrder[a]), cipherSuiteByID(prefOrder[b]) 1519 aName, bName := CipherSuiteName(prefOrder[a]), CipherSuiteName(prefOrder[b]) 1520 // * < RC4 1521 if !strings.Contains(aName, "RC4") && strings.Contains(bName, "RC4") { 1522 return true 1523 } else if strings.Contains(aName, "RC4") && !strings.Contains(bName, "RC4") { 1524 return false 1525 } 1526 // * < CBC_SHA256 1527 if !strings.Contains(aName, "CBC_SHA256") && strings.Contains(bName, "CBC_SHA256") { 1528 return true 1529 } else if strings.Contains(aName, "CBC_SHA256") && !strings.Contains(bName, "CBC_SHA256") { 1530 return false 1531 } 1532 // * < 3DES 1533 if !strings.Contains(aName, "3DES") && strings.Contains(bName, "3DES") { 1534 return true 1535 } else if strings.Contains(aName, "3DES") && !strings.Contains(bName, "3DES") { 1536 return false 1537 } 1538 // ECDHE < * 1539 if aSuite.flags&suiteECDHE != 0 && bSuite.flags&suiteECDHE == 0 { 1540 return true 1541 } else if aSuite.flags&suiteECDHE == 0 && bSuite.flags&suiteECDHE != 0 { 1542 return false 1543 } 1544 // AEAD < CBC 1545 if aSuite.aead != nil && bSuite.aead == nil { 1546 return true 1547 } else if aSuite.aead == nil && bSuite.aead != nil { 1548 return false 1549 } 1550 // AES < ChaCha20 1551 if strings.Contains(aName, "AES") && strings.Contains(bName, "CHACHA20") { 1552 return i == 0 // true for cipherSuitesPreferenceOrder 1553 } else if strings.Contains(aName, "CHACHA20") && strings.Contains(bName, "AES") { 1554 return i != 0 // true for cipherSuitesPreferenceOrderNoAES 1555 } 1556 // AES-128 < AES-256 1557 if strings.Contains(aName, "AES_128") && strings.Contains(bName, "AES_256") { 1558 return true 1559 } else if strings.Contains(aName, "AES_256") && strings.Contains(bName, "AES_128") { 1560 return false 1561 } 1562 // ECDSA < RSA 1563 if aSuite.flags&suiteECSign != 0 && bSuite.flags&suiteECSign == 0 { 1564 return true 1565 } else if aSuite.flags&suiteECSign == 0 && bSuite.flags&suiteECSign != 0 { 1566 return false 1567 } 1568 t.Fatalf("two ciphersuites are equal by all criteria: %v and %v", aName, bName) 1569 panic("unreachable") 1570 } 1571 if !sort.SliceIsSorted(prefOrder, isBetter) { 1572 t.Error("preference order is not sorted according to the rules") 1573 } 1574 } 1575 } 1576 1577 // http2isBadCipher is copied from net/http. 1578 // TODO: if it ends up exposed somewhere, use that instead. 1579 func http2isBadCipher(cipher uint16) bool { 1580 switch cipher { 1581 case TLS_RSA_WITH_RC4_128_SHA, 1582 TLS_RSA_WITH_3DES_EDE_CBC_SHA, 1583 TLS_RSA_WITH_AES_128_CBC_SHA, 1584 TLS_RSA_WITH_AES_256_CBC_SHA, 1585 TLS_RSA_WITH_AES_128_CBC_SHA256, 1586 TLS_RSA_WITH_AES_128_GCM_SHA256, 1587 TLS_RSA_WITH_AES_256_GCM_SHA384, 1588 TLS_ECDHE_ECDSA_WITH_RC4_128_SHA, 1589 TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, 1590 TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, 1591 TLS_ECDHE_RSA_WITH_RC4_128_SHA, 1592 TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA, 1593 TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, 1594 TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA, 1595 TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256, 1596 TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256: 1597 return true 1598 default: 1599 return false 1600 } 1601 } 1602 1603 type brokenSigner struct{ crypto.Signer } 1604 1605 func (s brokenSigner) Sign(rand io.Reader, digest []byte, opts crypto.SignerOpts) (signature []byte, err error) { 1606 // Replace opts with opts.HashFunc(), so rsa.PSSOptions are discarded. 1607 return s.Signer.Sign(rand, digest, opts.HashFunc()) 1608 } 1609 1610 // TestPKCS1OnlyCert uses a client certificate with a broken crypto.Signer that 1611 // always makes PKCS #1 v1.5 signatures, so can't be used with RSA-PSS. 1612 func TestPKCS1OnlyCert(t *testing.T) { 1613 clientConfig := testConfig.Clone() 1614 clientConfig.Certificates = []Certificate{{ 1615 Certificate: [][]byte{testRSACertificate}, 1616 PrivateKey: brokenSigner{testRSAPrivateKey}, 1617 }} 1618 serverConfig := testConfig.Clone() 1619 serverConfig.MaxVersion = VersionTLS12 // TLS 1.3 doesn't support PKCS #1 v1.5 1620 serverConfig.ClientAuth = RequireAnyClientCert 1621 1622 // If RSA-PSS is selected, the handshake should fail. 1623 if _, _, err := testHandshake(t, clientConfig, serverConfig); err == nil { 1624 t.Fatal("expected broken certificate to cause connection to fail") 1625 } 1626 1627 clientConfig.Certificates[0].SupportedSignatureAlgorithms = 1628 []SignatureScheme{PKCS1WithSHA1, PKCS1WithSHA256} 1629 1630 // But if the certificate restricts supported algorithms, RSA-PSS should not 1631 // be selected, and the handshake should succeed. 1632 if _, _, err := testHandshake(t, clientConfig, serverConfig); err != nil { 1633 t.Error(err) 1634 } 1635 }