gitee.com/ks-custle/core-gm@v0.0.0-20230922171213-b83bdd97b62c/gmtls/tls_test.go (about) 1 // Copyright (c) 2022 zhaochun 2 // core-gm is licensed under Mulan PSL v2. 3 // You can use this software according to the terms and conditions of the Mulan PSL v2. 4 // You may obtain a copy of Mulan PSL v2 at: 5 // http://license.coscl.org.cn/MulanPSL2 6 // THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. 7 // See the Mulan PSL v2 for more details. 8 9 /* 10 gmtls是基于`golang/go`的`tls`包实现的国密改造版本。 11 对应版权声明: thrid_licenses/github.com/golang/go/LICENSE 12 */ 13 14 package gmtls 15 16 import ( 17 "bytes" 18 "context" 19 "crypto" 20 "encoding/json" 21 "errors" 22 "fmt" 23 "io" 24 "math" 25 "net" 26 "os" 27 "reflect" 28 "sort" 29 "strings" 30 "testing" 31 "time" 32 33 "gitee.com/ks-custle/core-gm/internal/testenv" 34 "gitee.com/ks-custle/core-gm/x509" 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 = testingKey(`-----BEGIN RSA TESTING 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 TESTING 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 = testingKey(`-----BEGIN TESTING 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 TESTING 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 = testingKey(`-----BEGIN EC PARAMETERS----- 91 BgUrgQQAIw== 92 -----END EC PARAMETERS----- 93 -----BEGIN EC TESTING 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 TESTING 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 func(listener net.Listener) { 187 err := listener.Close() 188 if err != nil { 189 panic(err) 190 } 191 }(listener) 192 193 complete := make(chan bool) 194 defer close(complete) 195 196 go func() { 197 conn, err := listener.Accept() 198 if err != nil { 199 t.Error(err) 200 return 201 } 202 <-complete 203 _ = conn.Close() 204 }() 205 206 dialer := &net.Dialer{ 207 Timeout: 10 * time.Millisecond, 208 } 209 210 var err error 211 if _, err = DialWithDialer(dialer, "tcp", addr, nil); err == nil { 212 t.Fatal("DialWithTimeout completed successfully") 213 } 214 215 if !isTimeoutError(err) { 216 t.Errorf("resulting error not a timeout: %v\nType %T: %#v", err, err, err) 217 } 218 } 219 220 func TestDeadlineOnWrite(t *testing.T) { 221 if testing.Short() { 222 t.Skip("skipping in short mode") 223 } 224 225 ln := newLocalListener(t) 226 defer func(ln net.Listener) { 227 err := ln.Close() 228 if err != nil { 229 panic(err) 230 } 231 }(ln) 232 233 srvCh := make(chan *Conn, 1) 234 235 go func() { 236 sconn, err := ln.Accept() 237 if err != nil { 238 srvCh <- nil 239 return 240 } 241 srv := Server(sconn, testConfig.Clone()) 242 if err := srv.Handshake(); err != nil { 243 srvCh <- nil 244 return 245 } 246 srvCh <- srv 247 }() 248 249 clientConfig := testConfig.Clone() 250 // clientConfig.MaxVersion = VersionTLS12 251 clientConfig.MaxVersion = VersionGMSSL 252 conn, err := Dial("tcp", ln.Addr().String(), clientConfig) 253 if err != nil { 254 t.Fatal(err) 255 } 256 defer func(conn *Conn) { 257 err := conn.Close() 258 if err != nil { 259 panic(err) 260 } 261 }(conn) 262 263 srv := <-srvCh 264 if srv == nil { 265 t.Error(err) 266 } 267 268 // Make sure the client/server is setup correctly and is able to do a typical Write/Read 269 buf := make([]byte, 6) 270 if _, err := srv.Write([]byte("foobar")); err != nil { 271 t.Errorf("Write err: %v", err) 272 } 273 if n, err := conn.Read(buf); n != 6 || err != nil || string(buf) != "foobar" { 274 t.Errorf("Read = %d, %v, data %q; want 6, nil, foobar", n, err, buf) 275 } 276 277 // Set a deadline which should cause Write to timeout 278 if err = srv.SetDeadline(time.Now()); err != nil { 279 t.Fatalf("SetDeadline(time.Now()) err: %v", err) 280 } 281 if _, err = srv.Write([]byte("should fail")); err == nil { 282 t.Fatal("Write should have timed out") 283 } 284 285 // Clear deadline and make sure it still times out 286 if err = srv.SetDeadline(time.Time{}); err != nil { 287 t.Fatalf("SetDeadline(time.Time{}) err: %v", err) 288 } 289 if _, err = srv.Write([]byte("This connection is permanently broken")); err == nil { 290 t.Fatal("Write which previously failed should still time out") 291 } 292 293 // Verify the error 294 if ne := err.(net.Error); ne.Temporary() != false { 295 t.Error("Write timed out but incorrectly classified the error as Temporary") 296 } 297 if !isTimeoutError(err) { 298 t.Error("Write timed out but did not classify the error as a Timeout") 299 } 300 } 301 302 type readerFunc func([]byte) (int, error) 303 304 func (f readerFunc) Read(b []byte) (int, error) { return f(b) } 305 306 // TestDialer tests that tls.Dialer.DialContext can abort in the middle of a handshake. 307 // (The other cases are all handled by the existing dial tests in this package, which 308 // all also flow through the same code shared code paths) 309 func TestDialer(t *testing.T) { 310 ln := newLocalListener(t) 311 defer func(ln net.Listener) { 312 err := ln.Close() 313 if err != nil { 314 panic(err) 315 } 316 }(ln) 317 318 unblockServer := make(chan struct{}) // close-only 319 defer close(unblockServer) 320 go func() { 321 conn, err := ln.Accept() 322 if err != nil { 323 return 324 } 325 defer func(conn net.Conn) { 326 err := conn.Close() 327 if err != nil { 328 panic(err) 329 } 330 }(conn) 331 <-unblockServer 332 }() 333 334 ctx, cancel := context.WithCancel(context.Background()) 335 d := Dialer{Config: &Config{ 336 Rand: readerFunc(func(b []byte) (n int, err error) { 337 // By the time crypto/tls wants randomness, that means it has a TCP 338 // connection, so we're past the Dialer's dial and now blocked 339 // in a handshake. Cancel our context and see if we get unstuck. 340 // (Our TCP listener above never reads or writes, so the Handshake 341 // would otherwise be stuck forever) 342 cancel() 343 return len(b), nil 344 }), 345 ServerName: "foo", 346 }} 347 _, err := d.DialContext(ctx, "tcp", ln.Addr().String()) 348 if err != context.Canceled { 349 t.Errorf("err = %v; want context.Canceled", err) 350 } 351 } 352 353 func isTimeoutError(err error) bool { 354 if ne, ok := err.(net.Error); ok { 355 return ne.Timeout() 356 } 357 return false 358 } 359 360 // tests that Conn.Read returns (non-zero, io.EOF) instead of 361 // (non-zero, nil) when a Close (alertCloseNotify) is sitting right 362 // behind the application data in the buffer. 363 func TestConnReadNonzeroAndEOF(t *testing.T) { 364 // This test is racy: it assumes that after a write to a 365 // localhost TCP connection, the peer TCP connection can 366 // immediately read it. Because it's racy, we skip this test 367 // in short mode, and then retry it several times with an 368 // increasing sleep in between our final write (via srv.Close 369 // below) and the following read. 370 if testing.Short() { 371 t.Skip("skipping in short mode") 372 } 373 var err error 374 for delay := time.Millisecond; delay <= 64*time.Millisecond; delay *= 2 { 375 if err = testConnReadNonzeroAndEOF(t, delay); err == nil { 376 return 377 } 378 } 379 t.Error(err) 380 } 381 382 func testConnReadNonzeroAndEOF(t *testing.T, delay time.Duration) error { 383 ln := newLocalListener(t) 384 defer func(ln net.Listener) { 385 err := ln.Close() 386 if err != nil { 387 panic(err) 388 } 389 }(ln) 390 391 srvCh := make(chan *Conn, 1) 392 var serr error 393 go func() { 394 sconn, err := ln.Accept() 395 if err != nil { 396 serr = err 397 srvCh <- nil 398 return 399 } 400 serverConfig := testConfig.Clone() 401 srv := Server(sconn, serverConfig) 402 if err := srv.Handshake(); err != nil { 403 serr = fmt.Errorf("handshake: %v", err) 404 srvCh <- nil 405 return 406 } 407 srvCh <- srv 408 }() 409 410 clientConfig := testConfig.Clone() 411 // In TLS 1.3, alerts are encrypted and disguised as application data, so 412 // the opportunistic peek won't work. 413 clientConfig.MaxVersion = VersionTLS12 414 conn, err := Dial("tcp", ln.Addr().String(), clientConfig) 415 if err != nil { 416 t.Fatal(err) 417 } 418 defer func(conn *Conn) { 419 err := conn.Close() 420 if err != nil { 421 panic(err) 422 } 423 }(conn) 424 425 srv := <-srvCh 426 if srv == nil { 427 return serr 428 } 429 430 buf := make([]byte, 6) 431 432 _, _ = srv.Write([]byte("foobar")) 433 n, err := conn.Read(buf) 434 if n != 6 || err != nil || string(buf) != "foobar" { 435 //goland:noinspection GoErrorStringFormat 436 return fmt.Errorf("Read = %d, %v, data %q; want 6, nil, foobar", n, err, buf) 437 } 438 439 _, _ = srv.Write([]byte("abcdef")) 440 _ = srv.Close() 441 time.Sleep(delay) 442 n, err = conn.Read(buf) 443 if n != 6 || string(buf) != "abcdef" { 444 //goland:noinspection GoErrorStringFormat 445 return fmt.Errorf("Read = %d, buf= %q; want 6, abcdef", n, buf) 446 } 447 if err != io.EOF { 448 //goland:noinspection GoErrorStringFormat 449 return fmt.Errorf("Second Read error = %v; want io.EOF", err) 450 } 451 return nil 452 } 453 454 func TestTLSUniqueMatches(t *testing.T) { 455 ln := newLocalListener(t) 456 defer func(ln net.Listener) { 457 err := ln.Close() 458 if err != nil { 459 panic(err) 460 } 461 }(ln) 462 463 serverTLSUniques := make(chan []byte) 464 parentDone := make(chan struct{}) 465 childDone := make(chan struct{}) 466 defer close(parentDone) 467 go func() { 468 defer close(childDone) 469 for i := 0; i < 2; i++ { 470 sconn, err := ln.Accept() 471 if err != nil { 472 t.Error(err) 473 return 474 } 475 serverConfig := testConfig.Clone() 476 serverConfig.MaxVersion = VersionTLS12 // TLSUnique is not defined in TLS 1.3 477 srv := Server(sconn, serverConfig) 478 if err := srv.Handshake(); err != nil { 479 t.Error(err) 480 return 481 } 482 select { 483 case <-parentDone: 484 return 485 case serverTLSUniques <- srv.ConnectionState().TLSUnique: 486 } 487 } 488 }() 489 490 clientConfig := testConfig.Clone() 491 clientConfig.ClientSessionCache = NewLRUClientSessionCache(1) 492 conn, err := Dial("tcp", ln.Addr().String(), clientConfig) 493 if err != nil { 494 t.Fatal(err) 495 } 496 497 var serverTLSUniquesValue []byte 498 select { 499 case <-childDone: 500 return 501 case serverTLSUniquesValue = <-serverTLSUniques: 502 } 503 504 if !bytes.Equal(conn.ConnectionState().TLSUnique, serverTLSUniquesValue) { 505 t.Error("client and server channel bindings differ") 506 } 507 _ = conn.Close() 508 509 conn, err = Dial("tcp", ln.Addr().String(), clientConfig) 510 if err != nil { 511 t.Fatal(err) 512 } 513 defer func(conn *Conn) { 514 err := conn.Close() 515 if err != nil { 516 panic(err) 517 } 518 }(conn) 519 if !conn.ConnectionState().DidResume { 520 t.Error("second session did not use resumption") 521 } 522 523 select { 524 case <-childDone: 525 return 526 case serverTLSUniquesValue = <-serverTLSUniques: 527 } 528 529 if !bytes.Equal(conn.ConnectionState().TLSUnique, serverTLSUniquesValue) { 530 t.Error("client and server channel bindings differ when session resumption is used") 531 } 532 } 533 534 func TestVerifyHostname(t *testing.T) { 535 // 想找个国内的支持tls1.3的站点,但是大部分都还只支持tls1.2,好不容易找到一个思否是支持tls1.3的。 536 // github等国外网站倒是支持tls1.3,奈何访问不稳定。 537 uri := "segmentfault.com" 538 539 testenv.MustHaveExternalNetwork(t) 540 clientConfig := &Config{ 541 CurvePreferences: []CurveID{CurveP256}, 542 // MaxVersion: VersionTLS12, 543 } 544 fmt.Println("---------- 访问 https://" + uri + " ----------") 545 c, err := Dial("tcp", uri+":https", clientConfig) 546 if err != nil { 547 t.Fatal(err) 548 } 549 if err := c.VerifyHostname(uri); err != nil { 550 t.Fatalf("verify %s: %v", uri, err) 551 } 552 if err := c.VerifyHostname("test.com"); err == nil { 553 t.Fatalf("verify test.com succeeded") 554 } 555 556 fmt.Println("---------- 访问 https://" + uri + " 不做证书检查 ----------") 557 clientConfig.InsecureSkipVerify = true 558 c, err = Dial("tcp", uri+":https", clientConfig) 559 if err != nil { 560 t.Fatal(err) 561 } 562 if err := c.VerifyHostname(uri); err == nil { 563 t.Fatalf("verify %s succeeded with InsecureSkipVerify=true", uri) 564 } 565 } 566 567 func TestConnCloseBreakingWrite(t *testing.T) { 568 ln := newLocalListener(t) 569 defer func(ln net.Listener) { 570 err := ln.Close() 571 if err != nil { 572 panic(err) 573 } 574 }(ln) 575 576 srvCh := make(chan *Conn, 1) 577 var serr error 578 var sconn net.Conn 579 go func() { 580 var err error 581 sconn, err = ln.Accept() 582 if err != nil { 583 serr = err 584 srvCh <- nil 585 return 586 } 587 serverConfig := testConfig.Clone() 588 srv := Server(sconn, serverConfig) 589 if err := srv.Handshake(); err != nil { 590 serr = fmt.Errorf("handshake: %v", err) 591 srvCh <- nil 592 return 593 } 594 srvCh <- srv 595 }() 596 597 cconn, err := net.Dial("tcp", ln.Addr().String()) 598 if err != nil { 599 t.Fatal(err) 600 } 601 defer func(cconn net.Conn) { 602 err := cconn.Close() 603 if err != nil { 604 panic(err) 605 } 606 }(cconn) 607 608 conn := &changeImplConn{ 609 Conn: cconn, 610 } 611 612 clientConfig := testConfig.Clone() 613 tconn := Client(conn, clientConfig) 614 if err := tconn.Handshake(); err != nil { 615 t.Fatal(err) 616 } 617 618 srv := <-srvCh 619 if srv == nil { 620 t.Fatal(serr) 621 } 622 defer func(sconn net.Conn) { 623 err := sconn.Close() 624 if err != nil { 625 panic(err) 626 } 627 }(sconn) 628 629 connClosed := make(chan struct{}) 630 conn.closeFunc = func() error { 631 close(connClosed) 632 return nil 633 } 634 635 inWrite := make(chan bool, 1) 636 var errConnClosed = errors.New("conn closed for test") 637 conn.writeFunc = func(p []byte) (n int, err error) { 638 inWrite <- true 639 <-connClosed 640 return 0, errConnClosed 641 } 642 643 closeReturned := make(chan bool, 1) 644 go func() { 645 <-inWrite 646 _ = tconn.Close() // test that this doesn't block forever. 647 closeReturned <- true 648 }() 649 650 _, err = tconn.Write([]byte("foo")) 651 if err != errConnClosed { 652 t.Errorf("Write error = %v; want errConnClosed", err) 653 } 654 655 <-closeReturned 656 if err := tconn.Close(); err != net.ErrClosed { 657 t.Errorf("Close error = %v; want net.ErrClosed", err) 658 } 659 } 660 661 func TestConnCloseWrite(t *testing.T) { 662 ln := newLocalListener(t) 663 defer func(ln net.Listener) { 664 err := ln.Close() 665 if err != nil { 666 panic(err) 667 } 668 }(ln) 669 670 clientDoneChan := make(chan struct{}) 671 672 serverCloseWrite := func() error { 673 sconn, err := ln.Accept() 674 if err != nil { 675 return fmt.Errorf("accept: %v", err) 676 } 677 defer func(sconn net.Conn) { 678 err := sconn.Close() 679 if err != nil { 680 panic(err) 681 } 682 }(sconn) 683 684 serverConfig := testConfig.Clone() 685 srv := Server(sconn, serverConfig) 686 if err := srv.Handshake(); err != nil { 687 return fmt.Errorf("handshake: %v", err) 688 } 689 defer func(srv *Conn) { 690 err := srv.Close() 691 if err != nil { 692 panic(err) 693 } 694 }(srv) 695 696 data, err := io.ReadAll(srv) 697 if err != nil { 698 return err 699 } 700 if len(data) > 0 { 701 //goland:noinspection GoErrorStringFormat 702 return fmt.Errorf("Read data = %q; want nothing", data) 703 } 704 705 if err := srv.CloseWrite(); err != nil { 706 return fmt.Errorf("server CloseWrite: %v", err) 707 } 708 709 // Wait for clientCloseWrite to finish, so we know we 710 // tested the CloseWrite before we defer the 711 // sconn.Close above, which would also cause the 712 // client to unblock like CloseWrite. 713 <-clientDoneChan 714 return nil 715 } 716 717 clientCloseWrite := func() error { 718 defer close(clientDoneChan) 719 720 clientConfig := testConfig.Clone() 721 conn, err := Dial("tcp", ln.Addr().String(), clientConfig) 722 if err != nil { 723 return err 724 } 725 if err := conn.Handshake(); err != nil { 726 return err 727 } 728 defer func(conn *Conn) { 729 err := conn.Close() 730 if err != nil { 731 panic(err) 732 } 733 }(conn) 734 735 if err := conn.CloseWrite(); err != nil { 736 return fmt.Errorf("client CloseWrite: %v", err) 737 } 738 739 if _, err := conn.Write([]byte{0}); err != errShutdown { 740 return fmt.Errorf("CloseWrite error = %v; want errShutdown", err) 741 } 742 743 data, err := io.ReadAll(conn) 744 if err != nil { 745 return err 746 } 747 if len(data) > 0 { 748 //goland:noinspection GoErrorStringFormat 749 return fmt.Errorf("Read data = %q; want nothing", data) 750 } 751 return nil 752 } 753 754 errChan := make(chan error, 2) 755 756 go func() { errChan <- serverCloseWrite() }() 757 go func() { errChan <- clientCloseWrite() }() 758 759 for i := 0; i < 2; i++ { 760 select { 761 case err := <-errChan: 762 if err != nil { 763 t.Fatal(err) 764 } 765 case <-time.After(10 * time.Second): 766 t.Fatal("deadlock") 767 } 768 } 769 770 // Also test CloseWrite being called before the handshake is 771 // finished: 772 { 773 ln2 := newLocalListener(t) 774 defer func(ln2 net.Listener) { 775 err := ln2.Close() 776 if err != nil { 777 panic(err) 778 } 779 }(ln2) 780 781 netConn, err := net.Dial("tcp", ln2.Addr().String()) 782 if err != nil { 783 t.Fatal(err) 784 } 785 defer func(netConn net.Conn) { 786 err := netConn.Close() 787 if err != nil { 788 panic(err) 789 } 790 }(netConn) 791 conn := Client(netConn, testConfig.Clone()) 792 793 if err := conn.CloseWrite(); err != errEarlyCloseWrite { 794 t.Errorf("CloseWrite error = %v; want errEarlyCloseWrite", err) 795 } 796 } 797 } 798 799 func TestWarningAlertFlood(t *testing.T) { 800 ln := newLocalListener(t) 801 defer func(ln net.Listener) { 802 err := ln.Close() 803 if err != nil { 804 panic(err) 805 } 806 }(ln) 807 808 server := func() error { 809 sconn, err := ln.Accept() 810 if err != nil { 811 return fmt.Errorf("accept: %v", err) 812 } 813 defer func(sconn net.Conn) { 814 err := sconn.Close() 815 if err != nil { 816 panic(err) 817 } 818 }(sconn) 819 820 serverConfig := testConfig.Clone() 821 srv := Server(sconn, serverConfig) 822 if err := srv.Handshake(); err != nil { 823 return fmt.Errorf("handshake: %v", err) 824 } 825 defer func(srv *Conn) { 826 err := srv.Close() 827 if err != nil { 828 panic(err) 829 } 830 }(srv) 831 832 _, err = io.ReadAll(srv) 833 if err == nil { 834 return errors.New("unexpected lack of error from server") 835 } 836 const expected = "too many ignored" 837 if str := err.Error(); !strings.Contains(str, expected) { 838 return fmt.Errorf("expected error containing %q, but saw: %s", expected, str) 839 } 840 841 return nil 842 } 843 844 errChan := make(chan error, 1) 845 go func() { errChan <- server() }() 846 847 clientConfig := testConfig.Clone() 848 clientConfig.MaxVersion = VersionTLS12 // there are no warning alerts in TLS 1.3 849 conn, err := Dial("tcp", ln.Addr().String(), clientConfig) 850 if err != nil { 851 t.Fatal(err) 852 } 853 defer func(conn *Conn) { 854 err := conn.Close() 855 if err != nil { 856 panic(err) 857 } 858 }(conn) 859 if err := conn.Handshake(); err != nil { 860 t.Fatal(err) 861 } 862 863 for i := 0; i < maxUselessRecords+1; i++ { 864 _ = conn.sendAlert(alertNoRenegotiation) 865 } 866 867 if err := <-errChan; err != nil { 868 t.Fatal(err) 869 } 870 } 871 872 func TestCloneFuncFields(t *testing.T) { 873 const expectedCount = 6 874 called := 0 875 876 c1 := Config{ 877 Time: func() time.Time { 878 called |= 1 << 0 879 return time.Time{} 880 }, 881 GetCertificate: func(*ClientHelloInfo) (*Certificate, error) { 882 called |= 1 << 1 883 return nil, nil 884 }, 885 GetClientCertificate: func(*CertificateRequestInfo) (*Certificate, error) { 886 called |= 1 << 2 887 return nil, nil 888 }, 889 GetConfigForClient: func(*ClientHelloInfo) (*Config, error) { 890 called |= 1 << 3 891 return nil, nil 892 }, 893 VerifyPeerCertificate: func(rawCerts [][]byte, verifiedChains [][]*x509.Certificate) error { 894 called |= 1 << 4 895 return nil 896 }, 897 VerifyConnection: func(ConnectionState) error { 898 called |= 1 << 5 899 return nil 900 }, 901 } 902 903 c2 := c1.Clone() 904 905 c2.Time() 906 _, _ = c2.GetCertificate(nil) 907 _, _ = c2.GetClientCertificate(nil) 908 _, _ = c2.GetConfigForClient(nil) 909 _ = c2.VerifyPeerCertificate(nil, nil) 910 _ = c2.VerifyConnection(ConnectionState{}) 911 912 if called != (1<<expectedCount)-1 { 913 t.Fatalf("expected %d calls but saw calls %b", expectedCount, called) 914 } 915 } 916 917 func TestCloneNonFuncFields(t *testing.T) { 918 var c1 Config 919 v := reflect.ValueOf(&c1).Elem() 920 921 typ := v.Type() 922 for i := 0; i < typ.NumField(); i++ { 923 f := v.Field(i) 924 // testing/quick can't handle functions or interfaces and so 925 // isn't used here. 926 switch fn := typ.Field(i).Name; fn { 927 case "Rand": 928 f.Set(reflect.ValueOf(io.Reader(os.Stdin))) 929 case "Time", "GetCertificate", "GetConfigForClient", "VerifyPeerCertificate", "VerifyConnection", "GetClientCertificate": 930 // DeepEqual can't compare functions. If you add a 931 // function field to this list, you must also change 932 // TestCloneFuncFields to ensure that the func field is 933 // cloned. 934 case "Certificates": 935 f.Set(reflect.ValueOf([]Certificate{ 936 {Certificate: [][]byte{{'b'}}}, 937 })) 938 case "NameToCertificate": 939 f.Set(reflect.ValueOf(map[string]*Certificate{"a": nil})) 940 case "RootCAs", "ClientCAs": 941 f.Set(reflect.ValueOf(x509.NewCertPool())) 942 case "ClientSessionCache": 943 f.Set(reflect.ValueOf(NewLRUClientSessionCache(10))) 944 case "KeyLogWriter": 945 f.Set(reflect.ValueOf(io.Writer(os.Stdout))) 946 case "NextProtos": 947 f.Set(reflect.ValueOf([]string{"a", "b"})) 948 case "ServerName": 949 f.Set(reflect.ValueOf("b")) 950 case "ClientAuth": 951 f.Set(reflect.ValueOf(VerifyClientCertIfGiven)) 952 case "InsecureSkipVerify", "SessionTicketsDisabled", "DynamicRecordSizingDisabled", "PreferServerCipherSuites": 953 f.Set(reflect.ValueOf(true)) 954 case "MinVersion", "MaxVersion": 955 f.Set(reflect.ValueOf(uint16(VersionTLS12))) 956 case "SessionTicketKey": 957 f.Set(reflect.ValueOf([32]byte{})) 958 case "CipherSuites": 959 f.Set(reflect.ValueOf([]uint16{1, 2})) 960 case "CurvePreferences": 961 f.Set(reflect.ValueOf([]CurveID{CurveP256})) 962 case "Renegotiation": 963 f.Set(reflect.ValueOf(RenegotiateOnceAsClient)) 964 case "mutex", "autoSessionTicketKeys", "sessionTicketKeys": 965 continue // these are unexported fields that are handled separately 966 default: 967 t.Errorf("all fields must be accounted for, but saw unknown field %q", fn) 968 } 969 } 970 // Set the unexported fields related to session ticket keys, which are copied with Clone(). 971 c1.autoSessionTicketKeys = []ticketKey{c1.ticketKeyFromBytes(c1.SessionTicketKey)} 972 c1.sessionTicketKeys = []ticketKey{c1.ticketKeyFromBytes(c1.SessionTicketKey)} 973 974 c2 := c1.Clone() 975 if !reflect.DeepEqual(&c1, c2) { 976 t.Errorf("clone failed to copy a field") 977 } 978 } 979 980 func TestCloneNilConfig(t *testing.T) { 981 var config *Config 982 if cc := config.Clone(); cc != nil { 983 t.Fatalf("Clone with nil should return nil, got: %+v", cc) 984 } 985 } 986 987 // changeImplConn is a net.Conn which can change its Write and Close 988 // methods. 989 type changeImplConn struct { 990 net.Conn 991 writeFunc func([]byte) (int, error) 992 closeFunc func() error 993 } 994 995 func (w *changeImplConn) Write(p []byte) (n int, err error) { 996 if w.writeFunc != nil { 997 return w.writeFunc(p) 998 } 999 return w.Conn.Write(p) 1000 } 1001 1002 func (w *changeImplConn) Close() error { 1003 if w.closeFunc != nil { 1004 return w.closeFunc() 1005 } 1006 return w.Conn.Close() 1007 } 1008 1009 func throughput(b *testing.B, version uint16, totalBytes int64, dynamicRecordSizingDisabled bool) { 1010 ln := newLocalListener(b) 1011 defer func(ln net.Listener) { 1012 err := ln.Close() 1013 if err != nil { 1014 panic(err) 1015 } 1016 }(ln) 1017 1018 N := b.N 1019 1020 // Less than 64KB because Windows appears to use a TCP rwin < 64KB. 1021 // See Issue #15899. 1022 const bufsize = 32 << 10 1023 1024 go func() { 1025 buf := make([]byte, bufsize) 1026 for i := 0; i < N; i++ { 1027 sconn, err := ln.Accept() 1028 if err != nil { 1029 // panic rather than synchronize to avoid benchmark overhead 1030 // (cannot call b.Fatal in goroutine) 1031 panic(fmt.Errorf("accept: %v", err)) 1032 } 1033 serverConfig := testConfig.Clone() 1034 serverConfig.CipherSuites = nil // the defaults may prefer faster ciphers 1035 serverConfig.DynamicRecordSizingDisabled = dynamicRecordSizingDisabled 1036 srv := Server(sconn, serverConfig) 1037 if err := srv.Handshake(); err != nil { 1038 panic(fmt.Errorf("handshake: %v", err)) 1039 } 1040 if _, err := io.CopyBuffer(srv, srv, buf); err != nil { 1041 panic(fmt.Errorf("copy buffer: %v", err)) 1042 } 1043 } 1044 }() 1045 1046 b.SetBytes(totalBytes) 1047 clientConfig := testConfig.Clone() 1048 clientConfig.CipherSuites = nil // the defaults may prefer faster ciphers 1049 clientConfig.DynamicRecordSizingDisabled = dynamicRecordSizingDisabled 1050 clientConfig.MaxVersion = version 1051 1052 buf := make([]byte, bufsize) 1053 chunks := int(math.Ceil(float64(totalBytes) / float64(len(buf)))) 1054 for i := 0; i < N; i++ { 1055 conn, err := Dial("tcp", ln.Addr().String(), clientConfig) 1056 if err != nil { 1057 b.Fatal(err) 1058 } 1059 for j := 0; j < chunks; j++ { 1060 _, err := conn.Write(buf) 1061 if err != nil { 1062 b.Fatal(err) 1063 } 1064 _, err = io.ReadFull(conn, buf) 1065 if err != nil { 1066 b.Fatal(err) 1067 } 1068 } 1069 _ = conn.Close() 1070 } 1071 } 1072 1073 func BenchmarkThroughput(b *testing.B) { 1074 for _, mode := range []string{"Max", "Dynamic"} { 1075 for size := 1; size <= 64; size <<= 1 { 1076 name := fmt.Sprintf("%sPacket/%dMB", mode, size) 1077 b.Run(name, func(b *testing.B) { 1078 b.Run("TLSv12", func(b *testing.B) { 1079 throughput(b, VersionTLS12, int64(size<<20), mode == "Max") 1080 }) 1081 b.Run("TLSv13", func(b *testing.B) { 1082 throughput(b, VersionTLS13, int64(size<<20), mode == "Max") 1083 }) 1084 }) 1085 } 1086 } 1087 } 1088 1089 type slowConn struct { 1090 net.Conn 1091 bps int 1092 } 1093 1094 func (c *slowConn) Write(p []byte) (int, error) { 1095 if c.bps == 0 { 1096 panic("too slow") 1097 } 1098 t0 := time.Now() 1099 wrote := 0 1100 for wrote < len(p) { 1101 time.Sleep(100 * time.Microsecond) 1102 allowed := int(time.Since(t0).Seconds()*float64(c.bps)) / 8 1103 if allowed > len(p) { 1104 allowed = len(p) 1105 } 1106 if wrote < allowed { 1107 n, err := c.Conn.Write(p[wrote:allowed]) 1108 wrote += n 1109 if err != nil { 1110 return wrote, err 1111 } 1112 } 1113 } 1114 return len(p), nil 1115 } 1116 1117 func latency(b *testing.B, version uint16, bps int, dynamicRecordSizingDisabled bool) { 1118 ln := newLocalListener(b) 1119 defer func(ln net.Listener) { 1120 err := ln.Close() 1121 if err != nil { 1122 panic(err) 1123 } 1124 }(ln) 1125 1126 N := b.N 1127 1128 go func() { 1129 for i := 0; i < N; i++ { 1130 sconn, err := ln.Accept() 1131 if err != nil { 1132 // panic rather than synchronize to avoid benchmark overhead 1133 // (cannot call b.Fatal in goroutine) 1134 panic(fmt.Errorf("accept: %v", err)) 1135 } 1136 serverConfig := testConfig.Clone() 1137 serverConfig.DynamicRecordSizingDisabled = dynamicRecordSizingDisabled 1138 srv := Server(&slowConn{sconn, bps}, serverConfig) 1139 if err := srv.Handshake(); err != nil { 1140 panic(fmt.Errorf("handshake: %v", err)) 1141 } 1142 _, _ = io.Copy(srv, srv) 1143 } 1144 }() 1145 1146 clientConfig := testConfig.Clone() 1147 clientConfig.DynamicRecordSizingDisabled = dynamicRecordSizingDisabled 1148 clientConfig.MaxVersion = version 1149 1150 buf := make([]byte, 16384) 1151 peek := make([]byte, 1) 1152 1153 for i := 0; i < N; i++ { 1154 conn, err := Dial("tcp", ln.Addr().String(), clientConfig) 1155 if err != nil { 1156 b.Fatal(err) 1157 } 1158 // make sure we're connected and previous connection has stopped 1159 if _, err := conn.Write(buf[:1]); err != nil { 1160 b.Fatal(err) 1161 } 1162 if _, err := io.ReadFull(conn, peek); err != nil { 1163 b.Fatal(err) 1164 } 1165 if _, err := conn.Write(buf); err != nil { 1166 b.Fatal(err) 1167 } 1168 if _, err = io.ReadFull(conn, peek); err != nil { 1169 b.Fatal(err) 1170 } 1171 _ = conn.Close() 1172 } 1173 } 1174 1175 func BenchmarkLatency(b *testing.B) { 1176 for _, mode := range []string{"Max", "Dynamic"} { 1177 for _, kbps := range []int{200, 500, 1000, 2000, 5000} { 1178 name := fmt.Sprintf("%sPacket/%dkbps", mode, kbps) 1179 b.Run(name, func(b *testing.B) { 1180 b.Run("TLSv12", func(b *testing.B) { 1181 latency(b, VersionTLS12, kbps*1000, mode == "Max") 1182 }) 1183 b.Run("TLSv13", func(b *testing.B) { 1184 latency(b, VersionTLS13, kbps*1000, mode == "Max") 1185 }) 1186 }) 1187 } 1188 } 1189 } 1190 1191 func TestConnectionStateMarshal(t *testing.T) { 1192 cs := &ConnectionState{} 1193 _, err := json.Marshal(cs) 1194 if err != nil { 1195 t.Errorf("json.Marshal failed on ConnectionState: %v", err) 1196 } 1197 } 1198 1199 func TestConnectionState(t *testing.T) { 1200 issuer, err := x509.ParseCertificate(testRSACertificateIssuer) 1201 if err != nil { 1202 panic(err) 1203 } 1204 rootCAs := x509.NewCertPool() 1205 rootCAs.AddCert(issuer) 1206 1207 now := func() time.Time { return time.Unix(1476984729, 0) } 1208 1209 const alpnProtocol = "golang" 1210 const serverName = "example.golang" 1211 var scts = [][]byte{[]byte("dummy sct 1"), []byte("dummy sct 2")} 1212 var ocsp = []byte("dummy ocsp") 1213 1214 for _, v := range []uint16{VersionTLS12, VersionTLS13} { 1215 var name string 1216 switch v { 1217 case VersionTLS12: 1218 name = "TLSv12" 1219 case VersionTLS13: 1220 name = "TLSv13" 1221 } 1222 t.Run(name, func(t *testing.T) { 1223 config := &Config{ 1224 Time: now, 1225 Rand: zeroSource{}, 1226 Certificates: make([]Certificate, 1), 1227 MaxVersion: v, 1228 RootCAs: rootCAs, 1229 ClientCAs: rootCAs, 1230 ClientAuth: RequireAndVerifyClientCert, 1231 NextProtos: []string{alpnProtocol}, 1232 ServerName: serverName, 1233 } 1234 config.Certificates[0].Certificate = [][]byte{testRSACertificate} 1235 config.Certificates[0].PrivateKey = testRSAPrivateKey 1236 config.Certificates[0].SignedCertificateTimestamps = scts 1237 config.Certificates[0].OCSPStaple = ocsp 1238 1239 ss, cs, err := testHandshake(t, config, config) 1240 if err != nil { 1241 t.Fatalf("Handshake failed: %v", err) 1242 } 1243 1244 if ss.Version != v || cs.Version != v { 1245 t.Errorf("Got versions %x (server) and %x (client), expected %x", ss.Version, cs.Version, v) 1246 } 1247 1248 if !ss.HandshakeComplete || !cs.HandshakeComplete { 1249 t.Errorf("Got HandshakeComplete %v (server) and %v (client), expected true", ss.HandshakeComplete, cs.HandshakeComplete) 1250 } 1251 1252 if ss.DidResume || cs.DidResume { 1253 t.Errorf("Got DidResume %v (server) and %v (client), expected false", ss.DidResume, cs.DidResume) 1254 } 1255 1256 if ss.CipherSuite == 0 || cs.CipherSuite == 0 { 1257 t.Errorf("Got invalid cipher suite: %v (server) and %v (client)", ss.CipherSuite, cs.CipherSuite) 1258 } 1259 1260 if ss.NegotiatedProtocol != alpnProtocol || cs.NegotiatedProtocol != alpnProtocol { 1261 t.Errorf("Got negotiated protocol %q (server) and %q (client), expected %q", ss.NegotiatedProtocol, cs.NegotiatedProtocol, alpnProtocol) 1262 } 1263 1264 if !cs.NegotiatedProtocolIsMutual { 1265 t.Errorf("Got false NegotiatedProtocolIsMutual on the client side") 1266 } 1267 // NegotiatedProtocolIsMutual on the server side is unspecified. 1268 1269 if ss.ServerName != serverName { 1270 t.Errorf("Got server name %q, expected %q", ss.ServerName, serverName) 1271 } 1272 if cs.ServerName != serverName { 1273 t.Errorf("Got server name on client connection %q, expected %q", cs.ServerName, serverName) 1274 } 1275 1276 if len(ss.PeerCertificates) != 1 || len(cs.PeerCertificates) != 1 { 1277 t.Errorf("Got %d (server) and %d (client) peer certificates, expected %d", len(ss.PeerCertificates), len(cs.PeerCertificates), 1) 1278 } 1279 1280 if len(ss.VerifiedChains) != 1 || len(cs.VerifiedChains) != 1 { 1281 t.Errorf("Got %d (server) and %d (client) verified chains, expected %d", len(ss.VerifiedChains), len(cs.VerifiedChains), 1) 1282 } else if len(ss.VerifiedChains[0]) != 2 || len(cs.VerifiedChains[0]) != 2 { 1283 t.Errorf("Got %d (server) and %d (client) long verified chain, expected %d", len(ss.VerifiedChains[0]), len(cs.VerifiedChains[0]), 2) 1284 } 1285 1286 if len(cs.SignedCertificateTimestamps) != 2 { 1287 t.Errorf("Got %d SCTs, expected %d", len(cs.SignedCertificateTimestamps), 2) 1288 } 1289 if !bytes.Equal(cs.OCSPResponse, ocsp) { 1290 t.Errorf("Got OCSPs %x, expected %x", cs.OCSPResponse, ocsp) 1291 } 1292 // Only TLS 1.3 supports OCSP and SCTs on client certs. 1293 if v == VersionTLS13 { 1294 if len(ss.SignedCertificateTimestamps) != 2 { 1295 t.Errorf("Got %d client SCTs, expected %d", len(ss.SignedCertificateTimestamps), 2) 1296 } 1297 if !bytes.Equal(ss.OCSPResponse, ocsp) { 1298 t.Errorf("Got client OCSPs %x, expected %x", ss.OCSPResponse, ocsp) 1299 } 1300 } 1301 1302 if v == VersionTLS13 { 1303 if ss.TLSUnique != nil || cs.TLSUnique != nil { 1304 t.Errorf("Got TLSUnique %x (server) and %x (client), expected nil in TLS 1.3", ss.TLSUnique, cs.TLSUnique) 1305 } 1306 } else { 1307 if ss.TLSUnique == nil || cs.TLSUnique == nil { 1308 t.Errorf("Got TLSUnique %x (server) and %x (client), expected non-nil", ss.TLSUnique, cs.TLSUnique) 1309 } 1310 } 1311 }) 1312 } 1313 } 1314 1315 // Issue 28744: Ensure that we don't modify memory 1316 // that Config doesn't own such as Certificates. 1317 func TestBuildNameToCertificate_doesntModifyCertificates(t *testing.T) { 1318 c0 := Certificate{ 1319 Certificate: [][]byte{testRSACertificate}, 1320 PrivateKey: testRSAPrivateKey, 1321 } 1322 c1 := Certificate{ 1323 Certificate: [][]byte{testSNICertificate}, 1324 PrivateKey: testRSAPrivateKey, 1325 } 1326 config := testConfig.Clone() 1327 config.Certificates = []Certificate{c0, c1} 1328 1329 config.BuildNameToCertificate() 1330 got := config.Certificates 1331 want := []Certificate{c0, c1} 1332 if !reflect.DeepEqual(got, want) { 1333 t.Fatalf("Certificates were mutated by BuildNameToCertificate\nGot: %#v\nWant: %#v\n", got, want) 1334 } 1335 } 1336 1337 func testingKey(s string) string { return strings.ReplaceAll(s, "TESTING KEY", "PRIVATE KEY") } 1338 1339 func TestClientHelloInfo_SupportsCertificate(t *testing.T) { 1340 rsaCert := &Certificate{ 1341 Certificate: [][]byte{testRSACertificate}, 1342 PrivateKey: testRSAPrivateKey, 1343 } 1344 pkcs1Cert := &Certificate{ 1345 Certificate: [][]byte{testRSACertificate}, 1346 PrivateKey: testRSAPrivateKey, 1347 SupportedSignatureAlgorithms: []SignatureScheme{PKCS1WithSHA1, PKCS1WithSHA256}, 1348 } 1349 ecdsaCert := &Certificate{ 1350 // ECDSA P-256 certificate 1351 Certificate: [][]byte{testP256Certificate}, 1352 PrivateKey: testP256PrivateKey, 1353 } 1354 ed25519Cert := &Certificate{ 1355 Certificate: [][]byte{testEd25519Certificate}, 1356 PrivateKey: testEd25519PrivateKey, 1357 } 1358 1359 tests := []struct { 1360 c *Certificate 1361 chi *ClientHelloInfo 1362 wantErr string 1363 }{ 1364 {rsaCert, &ClientHelloInfo{ 1365 ServerName: "example.golang", 1366 SignatureSchemes: []SignatureScheme{PSSWithSHA256}, 1367 SupportedVersions: []uint16{VersionTLS13}, 1368 }, ""}, 1369 {ecdsaCert, &ClientHelloInfo{ 1370 SignatureSchemes: []SignatureScheme{PSSWithSHA256, ECDSAWithP256AndSHA256}, 1371 SupportedVersions: []uint16{VersionTLS13, VersionTLS12}, 1372 }, ""}, 1373 {rsaCert, &ClientHelloInfo{ 1374 ServerName: "example.com", 1375 SignatureSchemes: []SignatureScheme{PSSWithSHA256}, 1376 SupportedVersions: []uint16{VersionTLS13}, 1377 }, "not valid for requested server name"}, 1378 {ecdsaCert, &ClientHelloInfo{ 1379 SignatureSchemes: []SignatureScheme{ECDSAWithP384AndSHA384}, 1380 SupportedVersions: []uint16{VersionTLS13}, 1381 }, "signature algorithms"}, 1382 {pkcs1Cert, &ClientHelloInfo{ 1383 SignatureSchemes: []SignatureScheme{PSSWithSHA256, ECDSAWithP256AndSHA256}, 1384 SupportedVersions: []uint16{VersionTLS13}, 1385 }, "signature algorithms"}, 1386 1387 {rsaCert, &ClientHelloInfo{ 1388 CipherSuites: []uint16{TLS_RSA_WITH_AES_128_GCM_SHA256}, 1389 SignatureSchemes: []SignatureScheme{PKCS1WithSHA1}, 1390 SupportedVersions: []uint16{VersionTLS13, VersionTLS12}, 1391 }, "signature algorithms"}, 1392 {rsaCert, &ClientHelloInfo{ 1393 CipherSuites: []uint16{TLS_RSA_WITH_AES_128_GCM_SHA256}, 1394 SignatureSchemes: []SignatureScheme{PKCS1WithSHA1}, 1395 SupportedVersions: []uint16{VersionTLS13, VersionTLS12}, 1396 config: &Config{ 1397 MaxVersion: VersionTLS12, 1398 }, 1399 }, ""}, // Check that mutual version selection works. 1400 1401 {ecdsaCert, &ClientHelloInfo{ 1402 CipherSuites: []uint16{TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256}, 1403 SupportedCurves: []CurveID{CurveP256}, 1404 SupportedPoints: []uint8{pointFormatUncompressed}, 1405 SignatureSchemes: []SignatureScheme{ECDSAWithP256AndSHA256}, 1406 SupportedVersions: []uint16{VersionTLS12}, 1407 }, ""}, 1408 {ecdsaCert, &ClientHelloInfo{ 1409 CipherSuites: []uint16{TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256}, 1410 SupportedCurves: []CurveID{CurveP256}, 1411 SupportedPoints: []uint8{pointFormatUncompressed}, 1412 SignatureSchemes: []SignatureScheme{ECDSAWithP384AndSHA384}, 1413 SupportedVersions: []uint16{VersionTLS12}, 1414 }, ""}, // TLS 1.2 does not restrict curves based on the SignatureScheme. 1415 {ecdsaCert, &ClientHelloInfo{ 1416 CipherSuites: []uint16{TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256}, 1417 SupportedCurves: []CurveID{CurveP256}, 1418 SupportedPoints: []uint8{pointFormatUncompressed}, 1419 SignatureSchemes: nil, 1420 SupportedVersions: []uint16{VersionTLS12}, 1421 }, ""}, // TLS 1.2 comes with default signature schemes. 1422 {ecdsaCert, &ClientHelloInfo{ 1423 CipherSuites: []uint16{TLS_RSA_WITH_AES_128_GCM_SHA256}, 1424 SupportedCurves: []CurveID{CurveP256}, 1425 SupportedPoints: []uint8{pointFormatUncompressed}, 1426 SignatureSchemes: []SignatureScheme{ECDSAWithP256AndSHA256}, 1427 SupportedVersions: []uint16{VersionTLS12}, 1428 }, "cipher suite"}, 1429 {ecdsaCert, &ClientHelloInfo{ 1430 CipherSuites: []uint16{TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256}, 1431 SupportedCurves: []CurveID{CurveP256}, 1432 SupportedPoints: []uint8{pointFormatUncompressed}, 1433 SignatureSchemes: []SignatureScheme{ECDSAWithP256AndSHA256}, 1434 SupportedVersions: []uint16{VersionTLS12}, 1435 config: &Config{ 1436 CipherSuites: []uint16{TLS_RSA_WITH_AES_128_GCM_SHA256}, 1437 }, 1438 }, "cipher suite"}, 1439 {ecdsaCert, &ClientHelloInfo{ 1440 CipherSuites: []uint16{TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256}, 1441 SupportedCurves: []CurveID{CurveP384}, 1442 SupportedPoints: []uint8{pointFormatUncompressed}, 1443 SignatureSchemes: []SignatureScheme{ECDSAWithP256AndSHA256}, 1444 SupportedVersions: []uint16{VersionTLS12}, 1445 }, "certificate curve"}, 1446 {ecdsaCert, &ClientHelloInfo{ 1447 CipherSuites: []uint16{TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256}, 1448 SupportedCurves: []CurveID{CurveP256}, 1449 SupportedPoints: []uint8{1}, 1450 SignatureSchemes: []SignatureScheme{ECDSAWithP256AndSHA256}, 1451 SupportedVersions: []uint16{VersionTLS12}, 1452 }, "doesn't support ECDHE"}, 1453 {ecdsaCert, &ClientHelloInfo{ 1454 CipherSuites: []uint16{TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256}, 1455 SupportedCurves: []CurveID{CurveP256}, 1456 SupportedPoints: []uint8{pointFormatUncompressed}, 1457 SignatureSchemes: []SignatureScheme{PSSWithSHA256}, 1458 SupportedVersions: []uint16{VersionTLS12}, 1459 }, "signature algorithms"}, 1460 1461 {ed25519Cert, &ClientHelloInfo{ 1462 CipherSuites: []uint16{TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256}, 1463 SupportedCurves: []CurveID{CurveP256}, // only relevant for ECDHE support 1464 SupportedPoints: []uint8{pointFormatUncompressed}, 1465 SignatureSchemes: []SignatureScheme{Ed25519}, 1466 SupportedVersions: []uint16{VersionTLS12}, 1467 }, ""}, 1468 {ed25519Cert, &ClientHelloInfo{ 1469 CipherSuites: []uint16{TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256}, 1470 SupportedCurves: []CurveID{CurveP256}, // only relevant for ECDHE support 1471 SupportedPoints: []uint8{pointFormatUncompressed}, 1472 SignatureSchemes: []SignatureScheme{Ed25519}, 1473 SupportedVersions: []uint16{VersionTLS10}, 1474 }, "doesn't support Ed25519"}, 1475 {ed25519Cert, &ClientHelloInfo{ 1476 CipherSuites: []uint16{TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256}, 1477 SupportedCurves: []CurveID{}, 1478 SupportedPoints: []uint8{pointFormatUncompressed}, 1479 SignatureSchemes: []SignatureScheme{Ed25519}, 1480 SupportedVersions: []uint16{VersionTLS12}, 1481 }, "doesn't support ECDHE"}, 1482 1483 {rsaCert, &ClientHelloInfo{ 1484 CipherSuites: []uint16{TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA}, 1485 SupportedCurves: []CurveID{CurveP256}, // only relevant for ECDHE support 1486 SupportedPoints: []uint8{pointFormatUncompressed}, 1487 SupportedVersions: []uint16{VersionTLS10}, 1488 }, ""}, 1489 {rsaCert, &ClientHelloInfo{ 1490 CipherSuites: []uint16{TLS_RSA_WITH_AES_128_GCM_SHA256}, 1491 SupportedVersions: []uint16{VersionTLS12}, 1492 }, ""}, // static RSA fallback 1493 } 1494 for i, tt := range tests { 1495 err := tt.chi.SupportsCertificate(tt.c) 1496 switch { 1497 case tt.wantErr == "" && err != nil: 1498 t.Errorf("%d: unexpected error: %v", i, err) 1499 case tt.wantErr != "" && err == nil: 1500 t.Errorf("%d: unexpected success", i) 1501 case tt.wantErr != "" && !strings.Contains(err.Error(), tt.wantErr): 1502 t.Errorf("%d: got error %q, expected %q", i, err, tt.wantErr) 1503 } 1504 } 1505 } 1506 1507 func TestCipherSuites(t *testing.T) { 1508 var lastID uint16 1509 for _, c := range CipherSuites() { 1510 if lastID > c.ID { 1511 t.Errorf("CipherSuites are not ordered by ID: got %#04x after %#04x", c.ID, lastID) 1512 } else { 1513 lastID = c.ID 1514 } 1515 1516 if c.Insecure { 1517 t.Errorf("%#04x: Insecure CipherSuite returned by CipherSuites()", c.ID) 1518 } 1519 } 1520 lastID = 0 1521 for _, c := range InsecureCipherSuites() { 1522 if lastID > c.ID { 1523 t.Errorf("InsecureCipherSuites are not ordered by ID: got %#04x after %#04x", c.ID, lastID) 1524 } else { 1525 lastID = c.ID 1526 } 1527 1528 if !c.Insecure { 1529 t.Errorf("%#04x: not Insecure CipherSuite returned by InsecureCipherSuites()", c.ID) 1530 } 1531 } 1532 1533 CipherSuiteByID := func(id uint16) *CipherSuite { 1534 for _, c := range CipherSuites() { 1535 if c.ID == id { 1536 return c 1537 } 1538 } 1539 for _, c := range InsecureCipherSuites() { 1540 if c.ID == id { 1541 return c 1542 } 1543 } 1544 return nil 1545 } 1546 1547 for _, c := range cipherSuites { 1548 cc := CipherSuiteByID(c.id) 1549 if cc == nil { 1550 t.Errorf("%#04x: no CipherSuite entry", c.id) 1551 continue 1552 } 1553 1554 if tls12Only := c.flags&suiteTLS12 != 0; tls12Only && len(cc.SupportedVersions) != 1 { 1555 t.Errorf("%#04x: suite is TLS 1.2 only, but SupportedVersions is %v", c.id, cc.SupportedVersions) 1556 } else if !tls12Only && len(cc.SupportedVersions) != 3 { 1557 t.Errorf("%#04x: suite TLS 1.0-1.2, but SupportedVersions is %v", c.id, cc.SupportedVersions) 1558 } 1559 1560 if got := CipherSuiteName(c.id); got != cc.Name { 1561 t.Errorf("%#04x: unexpected CipherSuiteName: got %q, expected %q", c.id, got, cc.Name) 1562 } 1563 } 1564 for _, c := range cipherSuitesTLS13 { 1565 cc := CipherSuiteByID(c.id) 1566 if cc == nil { 1567 t.Errorf("%#04x: no CipherSuite entry", c.id) 1568 continue 1569 } 1570 1571 if cc.Insecure { 1572 t.Errorf("%#04x: Insecure %v, expected false", c.id, cc.Insecure) 1573 } 1574 if len(cc.SupportedVersions) <= 0 { 1575 t.Errorf("%#04x: suite is TLS 1.3 only, but SupportedVersions is %v", c.id, cc.SupportedVersions) 1576 } 1577 for _, version := range cc.SupportedVersions { 1578 if version != VersionTLS13 && version != VersionGMSSL { 1579 t.Errorf("%#04x: suite is TLS 1.3 only, but SupportedVersions is %v", c.id, cc.SupportedVersions) 1580 } 1581 } 1582 // if len(cc.SupportedVersions) != 1 || cc.SupportedVersions[0] != VersionTLS13 { 1583 // t.Errorf("%#04x: suite is TLS 1.3 only, but SupportedVersions is %v", c.id, cc.SupportedVersions) 1584 // } 1585 1586 if got := CipherSuiteName(c.id); got != cc.Name { 1587 t.Errorf("%#04x: unexpected CipherSuiteName: got %q, expected %q", c.id, got, cc.Name) 1588 } 1589 } 1590 1591 if got := CipherSuiteName(0xabc); got != "0x0ABC" { 1592 t.Errorf("unexpected fallback CipherSuiteName: got %q, expected 0x0ABC", got) 1593 } 1594 1595 if len(cipherSuitesPreferenceOrder) != len(cipherSuites) { 1596 t.Errorf("cipherSuitesPreferenceOrder is not the same size as cipherSuites") 1597 } 1598 if len(cipherSuitesPreferenceOrderNoAES) != len(cipherSuitesPreferenceOrder) { 1599 t.Errorf("cipherSuitesPreferenceOrderNoAES is not the same size as cipherSuitesPreferenceOrder") 1600 } 1601 1602 // Check that disabled suites are at the end of the preference lists, and 1603 // that they are marked insecure. 1604 for i, id := range disabledCipherSuites { 1605 offset := len(cipherSuitesPreferenceOrder) - len(disabledCipherSuites) 1606 if cipherSuitesPreferenceOrder[offset+i] != id { 1607 t.Errorf("disabledCipherSuites[%d]: not at the end of cipherSuitesPreferenceOrder", i) 1608 } 1609 if cipherSuitesPreferenceOrderNoAES[offset+i] != id { 1610 t.Errorf("disabledCipherSuites[%d]: not at the end of cipherSuitesPreferenceOrderNoAES", i) 1611 } 1612 c := CipherSuiteByID(id) 1613 if c == nil { 1614 t.Errorf("%#04x: no CipherSuite entry", id) 1615 continue 1616 } 1617 if !c.Insecure { 1618 t.Errorf("%#04x: disabled by default but not marked insecure", id) 1619 } 1620 } 1621 1622 for i, prefOrder := range [][]uint16{cipherSuitesPreferenceOrder, cipherSuitesPreferenceOrderNoAES} { 1623 // Check that insecure and HTTP/2 bad cipher suites are at the end of 1624 // the preference lists. 1625 var sawInsecure, sawBad bool 1626 for _, id := range prefOrder { 1627 c := CipherSuiteByID(id) 1628 if c == nil { 1629 t.Errorf("%#04x: no CipherSuite entry", id) 1630 continue 1631 } 1632 1633 if c.Insecure { 1634 sawInsecure = true 1635 } else if sawInsecure { 1636 t.Errorf("%#04x: secure suite after insecure one(s)", id) 1637 } 1638 1639 if http2isBadCipher(id) { 1640 sawBad = true 1641 } else if sawBad { 1642 t.Errorf("%#04x: non-bad suite after bad HTTP/2 one(s)", id) 1643 } 1644 } 1645 1646 // Check that the list is sorted according to the documented criteria. 1647 isBetter := func(a, b int) bool { 1648 aSuite, bSuite := cipherSuiteByID(prefOrder[a]), cipherSuiteByID(prefOrder[b]) 1649 aName, bName := CipherSuiteName(prefOrder[a]), CipherSuiteName(prefOrder[b]) 1650 // * < RC4 1651 if !strings.Contains(aName, "RC4") && strings.Contains(bName, "RC4") { 1652 return true 1653 } else if strings.Contains(aName, "RC4") && !strings.Contains(bName, "RC4") { 1654 return false 1655 } 1656 // * < CBC_SHA256 1657 if !strings.Contains(aName, "CBC_SHA256") && strings.Contains(bName, "CBC_SHA256") { 1658 return true 1659 } else if strings.Contains(aName, "CBC_SHA256") && !strings.Contains(bName, "CBC_SHA256") { 1660 return false 1661 } 1662 // * < 3DES 1663 if !strings.Contains(aName, "3DES") && strings.Contains(bName, "3DES") { 1664 return true 1665 } else if strings.Contains(aName, "3DES") && !strings.Contains(bName, "3DES") { 1666 return false 1667 } 1668 // ECDHE < * 1669 if aSuite.flags&suiteECDHE != 0 && bSuite.flags&suiteECDHE == 0 { 1670 return true 1671 } else if aSuite.flags&suiteECDHE == 0 && bSuite.flags&suiteECDHE != 0 { 1672 return false 1673 } 1674 // AEAD < CBC 1675 if aSuite.aead != nil && bSuite.aead == nil { 1676 return true 1677 } else if aSuite.aead == nil && bSuite.aead != nil { 1678 return false 1679 } 1680 // AES < ChaCha20 1681 if strings.Contains(aName, "AES") && strings.Contains(bName, "CHACHA20") { 1682 return i == 0 // true for cipherSuitesPreferenceOrder 1683 } else if strings.Contains(aName, "CHACHA20") && strings.Contains(bName, "AES") { 1684 return i != 0 // true for cipherSuitesPreferenceOrderNoAES 1685 } 1686 // AES-128 < AES-256 1687 if strings.Contains(aName, "AES_128") && strings.Contains(bName, "AES_256") { 1688 return true 1689 } else if strings.Contains(aName, "AES_256") && strings.Contains(bName, "AES_128") { 1690 return false 1691 } 1692 // ECDSA < RSA 1693 if aSuite.flags&suiteECSign != 0 && bSuite.flags&suiteECSign == 0 { 1694 return true 1695 } else if aSuite.flags&suiteECSign == 0 && bSuite.flags&suiteECSign != 0 { 1696 return false 1697 } 1698 t.Fatalf("two ciphersuites are equal by all criteria: %v and %v", aName, bName) 1699 //goland:noinspection GoUnreachableCode 1700 panic("unreachable") 1701 } 1702 if !sort.SliceIsSorted(prefOrder, isBetter) { 1703 t.Error("preference order is not sorted according to the rules") 1704 } 1705 } 1706 } 1707 1708 // http2isBadCipher is copied from net/http. 1709 // TODO: if it ends up exposed somewhere, use that instead. 1710 func http2isBadCipher(cipher uint16) bool { 1711 switch cipher { 1712 case TLS_RSA_WITH_RC4_128_SHA, 1713 TLS_RSA_WITH_3DES_EDE_CBC_SHA, 1714 TLS_RSA_WITH_AES_128_CBC_SHA, 1715 TLS_RSA_WITH_AES_256_CBC_SHA, 1716 TLS_RSA_WITH_AES_128_CBC_SHA256, 1717 TLS_RSA_WITH_AES_128_GCM_SHA256, 1718 TLS_RSA_WITH_AES_256_GCM_SHA384, 1719 TLS_ECDHE_ECDSA_WITH_RC4_128_SHA, 1720 TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, 1721 TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, 1722 TLS_ECDHE_RSA_WITH_RC4_128_SHA, 1723 TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA, 1724 TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, 1725 TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA, 1726 TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256, 1727 TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256: 1728 return true 1729 default: 1730 return false 1731 } 1732 } 1733 1734 type brokenSigner struct{ crypto.Signer } 1735 1736 func (s brokenSigner) Sign(rand io.Reader, digest []byte, opts crypto.SignerOpts) (signature []byte, err error) { 1737 // Replace opts with opts.HashFunc(), so rsa.PSSOptions are discarded. 1738 return s.Signer.Sign(rand, digest, opts.HashFunc()) 1739 } 1740 1741 // TestPKCS1OnlyCert uses a client certificate with a broken crypto.Signer that 1742 // always makes PKCS #1 v1.5 signatures, so can't be used with RSA-PSS. 1743 func TestPKCS1OnlyCert(t *testing.T) { 1744 clientConfig := testConfig.Clone() 1745 clientConfig.Certificates = []Certificate{{ 1746 Certificate: [][]byte{testRSACertificate}, 1747 PrivateKey: brokenSigner{testRSAPrivateKey}, 1748 }} 1749 serverConfig := testConfig.Clone() 1750 serverConfig.MaxVersion = VersionTLS12 // TLS 1.3 doesn't support PKCS #1 v1.5 1751 serverConfig.ClientAuth = RequireAnyClientCert 1752 1753 // If RSA-PSS is selected, the handshake should fail. 1754 if _, _, err := testHandshake(t, clientConfig, serverConfig); err == nil { 1755 t.Fatal("expected broken certificate to cause connection to fail") 1756 } 1757 1758 clientConfig.Certificates[0].SupportedSignatureAlgorithms = 1759 []SignatureScheme{PKCS1WithSHA1, PKCS1WithSHA256} 1760 1761 // But if the certificate restricts supported algorithms, RSA-PSS should not 1762 // be selected, and the handshake should succeed. 1763 if _, _, err := testHandshake(t, clientConfig, serverConfig); err != nil { 1764 t.Error(err) 1765 } 1766 }