Alternative TLS implementation in Go
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

917 lines
24 KiB

  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. package trs
  5. import (
  6. "bytes"
  7. "crypto/x509"
  8. "errors"
  9. "fmt"
  10. "io"
  11. "io/ioutil"
  12. "math"
  13. "net"
  14. "os"
  15. "reflect"
  16. "strings"
  17. "testing"
  18. "time"
  19. )
  20. var rsaCertPEM = `-----BEGIN CERTIFICATE-----
  21. MIIB0zCCAX2gAwIBAgIJAI/M7BYjwB+uMA0GCSqGSIb3DQEBBQUAMEUxCzAJBgNV
  22. BAYTAkFVMRMwEQYDVQQIDApTb21lLVN0YXRlMSEwHwYDVQQKDBhJbnRlcm5ldCBX
  23. aWRnaXRzIFB0eSBMdGQwHhcNMTIwOTEyMjE1MjAyWhcNMTUwOTEyMjE1MjAyWjBF
  24. MQswCQYDVQQGEwJBVTETMBEGA1UECAwKU29tZS1TdGF0ZTEhMB8GA1UECgwYSW50
  25. ZXJuZXQgV2lkZ2l0cyBQdHkgTHRkMFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBANLJ
  26. hPHhITqQbPklG3ibCVxwGMRfp/v4XqhfdQHdcVfHap6NQ5Wok/4xIA+ui35/MmNa
  27. rtNuC+BdZ1tMuVCPFZcCAwEAAaNQME4wHQYDVR0OBBYEFJvKs8RfJaXTH08W+SGv
  28. zQyKn0H8MB8GA1UdIwQYMBaAFJvKs8RfJaXTH08W+SGvzQyKn0H8MAwGA1UdEwQF
  29. MAMBAf8wDQYJKoZIhvcNAQEFBQADQQBJlffJHybjDGxRMqaRmDhX0+6v02TUKZsW
  30. r5QuVbpQhH6u+0UgcW0jp9QwpxoPTLTWGXEWBBBurxFwiCBhkQ+V
  31. -----END CERTIFICATE-----
  32. `
  33. var rsaKeyPEM = `-----BEGIN RSA PRIVATE KEY-----
  34. MIIBOwIBAAJBANLJhPHhITqQbPklG3ibCVxwGMRfp/v4XqhfdQHdcVfHap6NQ5Wo
  35. k/4xIA+ui35/MmNartNuC+BdZ1tMuVCPFZcCAwEAAQJAEJ2N+zsR0Xn8/Q6twa4G
  36. 6OB1M1WO+k+ztnX/1SvNeWu8D6GImtupLTYgjZcHufykj09jiHmjHx8u8ZZB/o1N
  37. MQIhAPW+eyZo7ay3lMz1V01WVjNKK9QSn1MJlb06h/LuYv9FAiEA25WPedKgVyCW
  38. SmUwbPw8fnTcpqDWE3yTO3vKcebqMSsCIBF3UmVue8YU3jybC3NxuXq3wNm34R8T
  39. xVLHwDXh/6NJAiEAl2oHGGLz64BuAfjKrqwz7qMYr9HCLIe/YsoWq/olzScCIQDi
  40. D2lWusoe2/nEqfDVVWGWlyJ7yOmqaVm/iNUN9B2N2g==
  41. -----END RSA PRIVATE KEY-----
  42. `
  43. // keyPEM is the same as rsaKeyPEM, but declares itself as just
  44. // "PRIVATE KEY", not "RSA PRIVATE KEY". https://golang.org/issue/4477
  45. var keyPEM = `-----BEGIN PRIVATE KEY-----
  46. MIIBOwIBAAJBANLJhPHhITqQbPklG3ibCVxwGMRfp/v4XqhfdQHdcVfHap6NQ5Wo
  47. k/4xIA+ui35/MmNartNuC+BdZ1tMuVCPFZcCAwEAAQJAEJ2N+zsR0Xn8/Q6twa4G
  48. 6OB1M1WO+k+ztnX/1SvNeWu8D6GImtupLTYgjZcHufykj09jiHmjHx8u8ZZB/o1N
  49. MQIhAPW+eyZo7ay3lMz1V01WVjNKK9QSn1MJlb06h/LuYv9FAiEA25WPedKgVyCW
  50. SmUwbPw8fnTcpqDWE3yTO3vKcebqMSsCIBF3UmVue8YU3jybC3NxuXq3wNm34R8T
  51. xVLHwDXh/6NJAiEAl2oHGGLz64BuAfjKrqwz7qMYr9HCLIe/YsoWq/olzScCIQDi
  52. D2lWusoe2/nEqfDVVWGWlyJ7yOmqaVm/iNUN9B2N2g==
  53. -----END PRIVATE KEY-----
  54. `
  55. var ecdsaCertPEM = `-----BEGIN CERTIFICATE-----
  56. MIIB/jCCAWICCQDscdUxw16XFDAJBgcqhkjOPQQBMEUxCzAJBgNVBAYTAkFVMRMw
  57. EQYDVQQIEwpTb21lLVN0YXRlMSEwHwYDVQQKExhJbnRlcm5ldCBXaWRnaXRzIFB0
  58. eSBMdGQwHhcNMTIxMTE0MTI0MDQ4WhcNMTUxMTE0MTI0MDQ4WjBFMQswCQYDVQQG
  59. EwJBVTETMBEGA1UECBMKU29tZS1TdGF0ZTEhMB8GA1UEChMYSW50ZXJuZXQgV2lk
  60. Z2l0cyBQdHkgTHRkMIGbMBAGByqGSM49AgEGBSuBBAAjA4GGAAQBY9+my9OoeSUR
  61. lDQdV/x8LsOuLilthhiS1Tz4aGDHIPwC1mlvnf7fg5lecYpMCrLLhauAc1UJXcgl
  62. 01xoLuzgtAEAgv2P/jgytzRSpUYvgLBt1UA0leLYBy6mQQbrNEuqT3INapKIcUv8
  63. XxYP0xMEUksLPq6Ca+CRSqTtrd/23uTnapkwCQYHKoZIzj0EAQOBigAwgYYCQXJo
  64. A7Sl2nLVf+4Iu/tAX/IF4MavARKC4PPHK3zfuGfPR3oCCcsAoz3kAzOeijvd0iXb
  65. H5jBImIxPL4WxQNiBTexAkF8D1EtpYuWdlVQ80/h/f4pBcGiXPqX5h2PQSQY7hP1
  66. +jwM1FGS4fREIOvlBYr/SzzQRtwrvrzGYxDEDbsC0ZGRnA==
  67. -----END CERTIFICATE-----
  68. `
  69. var ecdsaKeyPEM = `-----BEGIN EC PARAMETERS-----
  70. BgUrgQQAIw==
  71. -----END EC PARAMETERS-----
  72. -----BEGIN EC PRIVATE KEY-----
  73. MIHcAgEBBEIBrsoKp0oqcv6/JovJJDoDVSGWdirrkgCWxrprGlzB9o0X8fV675X0
  74. NwuBenXFfeZvVcwluO7/Q9wkYoPd/t3jGImgBwYFK4EEACOhgYkDgYYABAFj36bL
  75. 06h5JRGUNB1X/Hwuw64uKW2GGJLVPPhoYMcg/ALWaW+d/t+DmV5xikwKssuFq4Bz
  76. VQldyCXTXGgu7OC0AQCC/Y/+ODK3NFKlRi+AsG3VQDSV4tgHLqZBBus0S6pPcg1q
  77. kohxS/xfFg/TEwRSSws+roJr4JFKpO2t3/be5OdqmQ==
  78. -----END EC PRIVATE KEY-----
  79. `
  80. var keyPairTests = []struct {
  81. algo string
  82. cert string
  83. key string
  84. }{
  85. {"ECDSA", ecdsaCertPEM, ecdsaKeyPEM},
  86. {"RSA", rsaCertPEM, rsaKeyPEM},
  87. {"RSA-untyped", rsaCertPEM, keyPEM}, // golang.org/issue/4477
  88. }
  89. func TestX509KeyPair(t *testing.T) {
  90. t.Parallel()
  91. var pem []byte
  92. for _, test := range keyPairTests {
  93. pem = []byte(test.cert + test.key)
  94. if _, err := X509KeyPair(pem, pem); err != nil {
  95. t.Errorf("Failed to load %s cert followed by %s key: %s", test.algo, test.algo, err)
  96. }
  97. pem = []byte(test.key + test.cert)
  98. if _, err := X509KeyPair(pem, pem); err != nil {
  99. t.Errorf("Failed to load %s key followed by %s cert: %s", test.algo, test.algo, err)
  100. }
  101. }
  102. }
  103. func TestX509KeyPairErrors(t *testing.T) {
  104. _, err := X509KeyPair([]byte(rsaKeyPEM), []byte(rsaCertPEM))
  105. if err == nil {
  106. t.Fatalf("X509KeyPair didn't return an error when arguments were switched")
  107. }
  108. if subStr := "been switched"; !strings.Contains(err.Error(), subStr) {
  109. t.Fatalf("Expected %q in the error when switching arguments to X509KeyPair, but the error was %q", subStr, err)
  110. }
  111. _, err = X509KeyPair([]byte(rsaCertPEM), []byte(rsaCertPEM))
  112. if err == nil {
  113. t.Fatalf("X509KeyPair didn't return an error when both arguments were certificates")
  114. }
  115. if subStr := "certificate"; !strings.Contains(err.Error(), subStr) {
  116. t.Fatalf("Expected %q in the error when both arguments to X509KeyPair were certificates, but the error was %q", subStr, err)
  117. }
  118. const nonsensePEM = `
  119. -----BEGIN NONSENSE-----
  120. Zm9vZm9vZm9v
  121. -----END NONSENSE-----
  122. `
  123. _, err = X509KeyPair([]byte(nonsensePEM), []byte(nonsensePEM))
  124. if err == nil {
  125. t.Fatalf("X509KeyPair didn't return an error when both arguments were nonsense")
  126. }
  127. if subStr := "NONSENSE"; !strings.Contains(err.Error(), subStr) {
  128. t.Fatalf("Expected %q in the error when both arguments to X509KeyPair were nonsense, but the error was %q", subStr, err)
  129. }
  130. }
  131. func TestX509MixedKeyPair(t *testing.T) {
  132. if _, err := X509KeyPair([]byte(rsaCertPEM), []byte(ecdsaKeyPEM)); err == nil {
  133. t.Error("Load of RSA certificate succeeded with ECDSA private key")
  134. }
  135. if _, err := X509KeyPair([]byte(ecdsaCertPEM), []byte(rsaKeyPEM)); err == nil {
  136. t.Error("Load of ECDSA certificate succeeded with RSA private key")
  137. }
  138. }
  139. func newLocalListener(t testing.TB) net.Listener {
  140. ln, err := net.Listen("tcp", "127.0.0.1:0")
  141. if err != nil {
  142. ln, err = net.Listen("tcp6", "[::1]:0")
  143. }
  144. if err != nil {
  145. t.Fatal(err)
  146. }
  147. return ln
  148. }
  149. func TestDialTimeout(t *testing.T) {
  150. if testing.Short() {
  151. t.Skip("skipping in short mode")
  152. }
  153. listener := newLocalListener(t)
  154. addr := listener.Addr().String()
  155. defer listener.Close()
  156. complete := make(chan bool)
  157. defer close(complete)
  158. go func() {
  159. conn, err := listener.Accept()
  160. if err != nil {
  161. t.Error(err)
  162. return
  163. }
  164. <-complete
  165. conn.Close()
  166. }()
  167. dialer := &net.Dialer{
  168. Timeout: 10 * time.Millisecond,
  169. }
  170. var err error
  171. if _, err = DialWithDialer(dialer, "tcp", addr, nil); err == nil {
  172. t.Fatal("DialWithTimeout completed successfully")
  173. }
  174. if !isTimeoutError(err) {
  175. t.Errorf("resulting error not a timeout: %v\nType %T: %#v", err, err, err)
  176. }
  177. }
  178. func isTimeoutError(err error) bool {
  179. if ne, ok := err.(net.Error); ok {
  180. return ne.Timeout()
  181. }
  182. return false
  183. }
  184. // tests that Conn.Read returns (non-zero, io.EOF) instead of
  185. // (non-zero, nil) when a Close (alertCloseNotify) is sitting right
  186. // behind the application data in the buffer.
  187. func TestConnReadNonzeroAndEOF(t *testing.T) {
  188. // This test is racy: it assumes that after a write to a
  189. // localhost TCP connection, the peer TCP connection can
  190. // immediately read it. Because it's racy, we skip this test
  191. // in short mode, and then retry it several times with an
  192. // increasing sleep in between our final write (via srv.Close
  193. // below) and the following read.
  194. if testing.Short() {
  195. t.Skip("skipping in short mode")
  196. }
  197. var err error
  198. for delay := time.Millisecond; delay <= 64*time.Millisecond; delay *= 2 {
  199. if err = testConnReadNonzeroAndEOF(t, delay); err == nil {
  200. return
  201. }
  202. }
  203. t.Error(err)
  204. }
  205. func testConnReadNonzeroAndEOF(t *testing.T, delay time.Duration) error {
  206. ln := newLocalListener(t)
  207. defer ln.Close()
  208. srvCh := make(chan *Conn, 1)
  209. var serr error
  210. go func() {
  211. sconn, err := ln.Accept()
  212. if err != nil {
  213. serr = err
  214. srvCh <- nil
  215. return
  216. }
  217. serverConfig := testConfig.Clone()
  218. srv := Server(sconn, serverConfig)
  219. if err := srv.Handshake(); err != nil {
  220. serr = fmt.Errorf("handshake: %v", err)
  221. srvCh <- nil
  222. return
  223. }
  224. srvCh <- srv
  225. }()
  226. clientConfig := testConfig.Clone()
  227. conn, err := Dial("tcp", ln.Addr().String(), clientConfig)
  228. if err != nil {
  229. t.Fatal(err)
  230. }
  231. defer conn.Close()
  232. srv := <-srvCh
  233. if srv == nil {
  234. return serr
  235. }
  236. buf := make([]byte, 6)
  237. srv.Write([]byte("foobar"))
  238. n, err := conn.Read(buf)
  239. if n != 6 || err != nil || string(buf) != "foobar" {
  240. return fmt.Errorf("Read = %d, %v, data %q; want 6, nil, foobar", n, err, buf)
  241. }
  242. srv.Write([]byte("abcdef"))
  243. srv.Close()
  244. time.Sleep(delay)
  245. n, err = conn.Read(buf)
  246. if n != 6 || string(buf) != "abcdef" {
  247. return fmt.Errorf("Read = %d, buf= %q; want 6, abcdef", n, buf)
  248. }
  249. if err != io.EOF {
  250. return fmt.Errorf("Second Read error = %v; want io.EOF", err)
  251. }
  252. return nil
  253. }
  254. func TestTLSUniqueMatches(t *testing.T) {
  255. ln := newLocalListener(t)
  256. defer ln.Close()
  257. serverTLSUniques := make(chan []byte)
  258. go func() {
  259. for i := 0; i < 2; i++ {
  260. sconn, err := ln.Accept()
  261. if err != nil {
  262. t.Error(err)
  263. return
  264. }
  265. serverConfig := testConfig.Clone()
  266. srv := Server(sconn, serverConfig)
  267. if err := srv.Handshake(); err != nil {
  268. t.Error(err)
  269. return
  270. }
  271. serverTLSUniques <- srv.ConnectionState().TLSUnique
  272. }
  273. }()
  274. clientConfig := testConfig.Clone()
  275. clientConfig.ClientSessionCache = NewLRUClientSessionCache(1)
  276. conn, err := Dial("tcp", ln.Addr().String(), clientConfig)
  277. if err != nil {
  278. t.Fatal(err)
  279. }
  280. if !bytes.Equal(conn.ConnectionState().TLSUnique, <-serverTLSUniques) {
  281. t.Error("client and server channel bindings differ")
  282. }
  283. conn.Close()
  284. conn, err = Dial("tcp", ln.Addr().String(), clientConfig)
  285. if err != nil {
  286. t.Fatal(err)
  287. }
  288. defer conn.Close()
  289. if !conn.ConnectionState().DidResume {
  290. t.Error("second session did not use resumption")
  291. }
  292. if !bytes.Equal(conn.ConnectionState().TLSUnique, <-serverTLSUniques) {
  293. t.Error("client and server channel bindings differ when session resumption is used")
  294. }
  295. }
  296. func TestVerifyHostname(t *testing.T) {
  297. c, err := Dial("tcp", "www.google.com:https", nil)
  298. if err != nil {
  299. t.Fatal(err)
  300. }
  301. if err := c.VerifyHostname("www.google.com"); err != nil {
  302. t.Fatalf("verify www.google.com: %v", err)
  303. }
  304. if err := c.VerifyHostname("www.yahoo.com"); err == nil {
  305. t.Fatalf("verify www.yahoo.com succeeded")
  306. }
  307. c, err = Dial("tcp", "www.google.com:https", &Config{InsecureSkipVerify: true})
  308. if err != nil {
  309. t.Fatal(err)
  310. }
  311. if err := c.VerifyHostname("www.google.com"); err == nil {
  312. t.Fatalf("verify www.google.com succeeded with InsecureSkipVerify=true")
  313. }
  314. if err := c.VerifyHostname("www.yahoo.com"); err == nil {
  315. t.Fatalf("verify www.google.com succeeded with InsecureSkipVerify=true")
  316. }
  317. }
  318. func TestVerifyHostnameResumed(t *testing.T) {
  319. config := &Config{
  320. ClientSessionCache: NewLRUClientSessionCache(32),
  321. // There is no "New ticket" sent in case TLS v1.3 is advertised.
  322. // Hence forcing TLSv12
  323. MaxVersion: VersionTLS12,
  324. }
  325. for i := 0; i < 2; i++ {
  326. c, err := Dial("tcp", "www.google.com:https", config)
  327. if err != nil {
  328. t.Fatalf("Dial #%d: %v", i, err)
  329. }
  330. cs := c.ConnectionState()
  331. if i > 0 && !cs.DidResume {
  332. t.Fatalf("Subsequent connection unexpectedly didn't resume")
  333. }
  334. if cs.VerifiedChains == nil {
  335. t.Fatalf("Dial #%d: cs.VerifiedChains == nil", i)
  336. }
  337. if err := c.VerifyHostname("www.google.com"); err != nil {
  338. t.Fatalf("verify www.google.com #%d: %v", i, err)
  339. }
  340. c.Close()
  341. }
  342. }
  343. func TestConnCloseBreakingWrite(t *testing.T) {
  344. ln := newLocalListener(t)
  345. defer ln.Close()
  346. srvCh := make(chan *Conn, 1)
  347. var serr error
  348. var sconn net.Conn
  349. go func() {
  350. var err error
  351. sconn, err = ln.Accept()
  352. if err != nil {
  353. serr = err
  354. srvCh <- nil
  355. return
  356. }
  357. serverConfig := testConfig.Clone()
  358. srv := Server(sconn, serverConfig)
  359. if err := srv.Handshake(); err != nil {
  360. serr = fmt.Errorf("handshake: %v", err)
  361. srvCh <- nil
  362. return
  363. }
  364. srvCh <- srv
  365. }()
  366. cconn, err := net.Dial("tcp", ln.Addr().String())
  367. if err != nil {
  368. t.Fatal(err)
  369. }
  370. defer cconn.Close()
  371. conn := &changeImplConn{
  372. Conn: cconn,
  373. }
  374. clientConfig := testConfig.Clone()
  375. tconn := Client(conn, clientConfig)
  376. if err := tconn.Handshake(); err != nil {
  377. t.Fatal(err)
  378. }
  379. srv := <-srvCh
  380. if srv == nil {
  381. t.Fatal(serr)
  382. }
  383. defer sconn.Close()
  384. connClosed := make(chan struct{})
  385. conn.closeFunc = func() error {
  386. close(connClosed)
  387. return nil
  388. }
  389. inWrite := make(chan bool, 1)
  390. var errConnClosed = errors.New("conn closed for test")
  391. conn.writeFunc = func(p []byte) (n int, err error) {
  392. inWrite <- true
  393. <-connClosed
  394. return 0, errConnClosed
  395. }
  396. closeReturned := make(chan bool, 1)
  397. go func() {
  398. <-inWrite
  399. tconn.Close() // test that this doesn't block forever.
  400. closeReturned <- true
  401. }()
  402. _, err = tconn.Write([]byte("foo"))
  403. if err != errConnClosed {
  404. t.Errorf("Write error = %v; want errConnClosed", err)
  405. }
  406. <-closeReturned
  407. if err := tconn.Close(); err != errClosed {
  408. t.Errorf("Close error = %v; want errClosed", err)
  409. }
  410. }
  411. func TestConnCloseWrite(t *testing.T) {
  412. ln := newLocalListener(t)
  413. defer ln.Close()
  414. clientDoneChan := make(chan struct{})
  415. serverCloseWrite := func() error {
  416. sconn, err := ln.Accept()
  417. if err != nil {
  418. return fmt.Errorf("accept: %v", err)
  419. }
  420. defer sconn.Close()
  421. serverConfig := testConfig.Clone()
  422. srv := Server(sconn, serverConfig)
  423. if err := srv.Handshake(); err != nil {
  424. return fmt.Errorf("handshake: %v", err)
  425. }
  426. defer srv.Close()
  427. data, err := ioutil.ReadAll(srv)
  428. if err != nil {
  429. return err
  430. }
  431. if len(data) > 0 {
  432. return fmt.Errorf("Read data = %q; want nothing", data)
  433. }
  434. if err := srv.CloseWrite(); err != nil {
  435. return fmt.Errorf("server CloseWrite: %v", err)
  436. }
  437. // Wait for clientCloseWrite to finish, so we know we
  438. // tested the CloseWrite before we defer the
  439. // sconn.Close above, which would also cause the
  440. // client to unblock like CloseWrite.
  441. <-clientDoneChan
  442. return nil
  443. }
  444. clientCloseWrite := func() error {
  445. defer close(clientDoneChan)
  446. clientConfig := testConfig.Clone()
  447. conn, err := Dial("tcp", ln.Addr().String(), clientConfig)
  448. if err != nil {
  449. return err
  450. }
  451. if err := conn.Handshake(); err != nil {
  452. return err
  453. }
  454. defer conn.Close()
  455. if err := conn.CloseWrite(); err != nil {
  456. return fmt.Errorf("client CloseWrite: %v", err)
  457. }
  458. if _, err := conn.Write([]byte{0}); err != errShutdown {
  459. return fmt.Errorf("CloseWrite error = %v; want errShutdown", err)
  460. }
  461. data, err := ioutil.ReadAll(conn)
  462. if err != nil {
  463. return err
  464. }
  465. if len(data) > 0 {
  466. return fmt.Errorf("Read data = %q; want nothing", data)
  467. }
  468. return nil
  469. }
  470. errChan := make(chan error, 2)
  471. go func() { errChan <- serverCloseWrite() }()
  472. go func() { errChan <- clientCloseWrite() }()
  473. for i := 0; i < 2; i++ {
  474. select {
  475. case err := <-errChan:
  476. if err != nil {
  477. t.Fatal(err)
  478. }
  479. case <-time.After(10 * time.Second):
  480. t.Fatal("deadlock")
  481. }
  482. }
  483. // Also test CloseWrite being called before the handshake is
  484. // finished:
  485. {
  486. ln2 := newLocalListener(t)
  487. defer ln2.Close()
  488. netConn, err := net.Dial("tcp", ln2.Addr().String())
  489. if err != nil {
  490. t.Fatal(err)
  491. }
  492. defer netConn.Close()
  493. conn := Client(netConn, testConfig.Clone())
  494. if err := conn.CloseWrite(); err != errEarlyCloseWrite {
  495. t.Errorf("CloseWrite error = %v; want errEarlyCloseWrite", err)
  496. }
  497. }
  498. }
  499. func TestWarningAlertFlood(t *testing.T) {
  500. ln := newLocalListener(t)
  501. defer ln.Close()
  502. server := func() error {
  503. sconn, err := ln.Accept()
  504. if err != nil {
  505. return fmt.Errorf("accept: %v", err)
  506. }
  507. defer sconn.Close()
  508. serverConfig := testConfig.Clone()
  509. srv := Server(sconn, serverConfig)
  510. if err := srv.Handshake(); err != nil {
  511. return fmt.Errorf("handshake: %v", err)
  512. }
  513. defer srv.Close()
  514. _, err = ioutil.ReadAll(srv)
  515. if err == nil {
  516. return errors.New("unexpected lack of error from server")
  517. }
  518. const expected = "too many warn"
  519. if str := err.Error(); !strings.Contains(str, expected) {
  520. return fmt.Errorf("expected error containing %q, but saw: %s", expected, str)
  521. }
  522. return nil
  523. }
  524. errChan := make(chan error, 1)
  525. go func() { errChan <- server() }()
  526. clientConfig := testConfig.Clone()
  527. conn, err := Dial("tcp", ln.Addr().String(), clientConfig)
  528. if err != nil {
  529. t.Fatal(err)
  530. }
  531. defer conn.Close()
  532. if err := conn.Handshake(); err != nil {
  533. t.Fatal(err)
  534. }
  535. for i := 0; i < maxWarnAlertCount+1; i++ {
  536. conn.sendAlert(alertNoRenegotiation)
  537. }
  538. if err := <-errChan; err != nil {
  539. t.Fatal(err)
  540. }
  541. }
  542. func TestCloneFuncFields(t *testing.T) {
  543. const expectedCount = 5
  544. called := 0
  545. c1 := Config{
  546. Time: func() time.Time {
  547. called |= 1 << 0
  548. return time.Time{}
  549. },
  550. GetCertificate: func(*ClientHelloInfo) (*Certificate, error) {
  551. called |= 1 << 1
  552. return nil, nil
  553. },
  554. GetClientCertificate: func(*CertificateRequestInfo) (*Certificate, error) {
  555. called |= 1 << 2
  556. return nil, nil
  557. },
  558. GetConfigForClient: func(*ClientHelloInfo) (*Config, error) {
  559. called |= 1 << 3
  560. return nil, nil
  561. },
  562. VerifyPeerCertificate: func(rawCerts [][]byte, verifiedChains [][]*x509.Certificate) error {
  563. called |= 1 << 4
  564. return nil
  565. },
  566. }
  567. c2 := c1.Clone()
  568. c2.Time()
  569. c2.GetCertificate(nil)
  570. c2.GetClientCertificate(nil)
  571. c2.GetConfigForClient(nil)
  572. c2.VerifyPeerCertificate(nil, nil)
  573. if called != (1<<expectedCount)-1 {
  574. t.Fatalf("expected %d calls but saw calls %b", expectedCount, called)
  575. }
  576. }
  577. func TestCloneNonFuncFields(t *testing.T) {
  578. var c1 Config
  579. v := reflect.ValueOf(&c1).Elem()
  580. typ := v.Type()
  581. for i := 0; i < typ.NumField(); i++ {
  582. f := v.Field(i)
  583. if !f.CanSet() {
  584. // unexported field; not cloned.
  585. continue
  586. }
  587. // testing/quick can't handle functions or interfaces and so
  588. // isn't used here.
  589. switch fn := typ.Field(i).Name; fn {
  590. case "Rand":
  591. f.Set(reflect.ValueOf(io.Reader(os.Stdin)))
  592. case "Time", "GetCertificate", "GetConfigForClient", "VerifyPeerCertificate", "GetClientCertificate", "GetDelegatedCredential":
  593. // DeepEqual can't compare functions. If you add a
  594. // function field to this list, you must also change
  595. // TestCloneFuncFields to ensure that the func field is
  596. // cloned.
  597. case "Certificates":
  598. f.Set(reflect.ValueOf([]Certificate{
  599. {Certificate: [][]byte{{'b'}}},
  600. }))
  601. case "NameToCertificate":
  602. f.Set(reflect.ValueOf(map[string]*Certificate{"a": nil}))
  603. case "RootCAs", "ClientCAs":
  604. f.Set(reflect.ValueOf(x509.NewCertPool()))
  605. case "ClientSessionCache":
  606. f.Set(reflect.ValueOf(NewLRUClientSessionCache(10)))
  607. case "KeyLogWriter":
  608. f.Set(reflect.ValueOf(io.Writer(os.Stdout)))
  609. case "NextProtos":
  610. f.Set(reflect.ValueOf([]string{"a", "b"}))
  611. case "ServerName":
  612. f.Set(reflect.ValueOf("b"))
  613. case "ClientAuth":
  614. f.Set(reflect.ValueOf(VerifyClientCertIfGiven))
  615. case "InsecureSkipVerify", "SessionTicketsDisabled", "DynamicRecordSizingDisabled", "PreferServerCipherSuites", "Accept0RTTData":
  616. f.Set(reflect.ValueOf(true))
  617. case "MinVersion", "MaxVersion":
  618. f.Set(reflect.ValueOf(uint16(VersionTLS12)))
  619. case "SessionTicketKey":
  620. f.Set(reflect.ValueOf([32]byte{}))
  621. case "CipherSuites":
  622. f.Set(reflect.ValueOf([]uint16{1, 2}))
  623. case "CurvePreferences":
  624. f.Set(reflect.ValueOf([]CurveID{CurveP256}))
  625. case "Renegotiation":
  626. f.Set(reflect.ValueOf(RenegotiateOnceAsClient))
  627. case "Max0RTTDataSize":
  628. f.Set(reflect.ValueOf(uint32(0)))
  629. case "SessionTicketSealer":
  630. // TODO
  631. case "AcceptDelegatedCredential":
  632. f.Set(reflect.ValueOf(false))
  633. case "UseExtendedMasterSecret":
  634. f.Set(reflect.ValueOf(false))
  635. default:
  636. t.Errorf("all fields must be accounted for, but saw unknown field %q", fn)
  637. }
  638. }
  639. c2 := c1.Clone()
  640. // DeepEqual also compares unexported fields, thus c2 needs to have run
  641. // serverInit in order to be DeepEqual to c1. Cloning it and discarding
  642. // the result is sufficient.
  643. c2.Clone()
  644. if !reflect.DeepEqual(&c1, c2) {
  645. t.Errorf("clone failed to copy a field")
  646. }
  647. }
  648. // changeImplConn is a net.Conn which can change its Write and Close
  649. // methods.
  650. type changeImplConn struct {
  651. net.Conn
  652. writeFunc func([]byte) (int, error)
  653. closeFunc func() error
  654. }
  655. func (w *changeImplConn) Write(p []byte) (n int, err error) {
  656. if w.writeFunc != nil {
  657. return w.writeFunc(p)
  658. }
  659. return w.Conn.Write(p)
  660. }
  661. func (w *changeImplConn) Close() error {
  662. if w.closeFunc != nil {
  663. return w.closeFunc()
  664. }
  665. return w.Conn.Close()
  666. }
  667. func throughput(b *testing.B, totalBytes int64, dynamicRecordSizingDisabled bool) {
  668. ln := newLocalListener(b)
  669. defer ln.Close()
  670. N := b.N
  671. // Less than 64KB because Windows appears to use a TCP rwin < 64KB.
  672. // See Issue #15899.
  673. const bufsize = 32 << 10
  674. go func() {
  675. buf := make([]byte, bufsize)
  676. for i := 0; i < N; i++ {
  677. sconn, err := ln.Accept()
  678. if err != nil {
  679. // panic rather than synchronize to avoid benchmark overhead
  680. // (cannot call b.Fatal in goroutine)
  681. panic(fmt.Errorf("accept: %v", err))
  682. }
  683. serverConfig := testConfig.Clone()
  684. serverConfig.CipherSuites = nil // the defaults may prefer faster ciphers
  685. serverConfig.DynamicRecordSizingDisabled = dynamicRecordSizingDisabled
  686. srv := Server(sconn, serverConfig)
  687. if err := srv.Handshake(); err != nil {
  688. panic(fmt.Errorf("handshake: %v", err))
  689. }
  690. if _, err := io.CopyBuffer(srv, srv, buf); err != nil {
  691. panic(fmt.Errorf("copy buffer: %v", err))
  692. }
  693. }
  694. }()
  695. b.SetBytes(totalBytes)
  696. clientConfig := testConfig.Clone()
  697. clientConfig.CipherSuites = nil // the defaults may prefer faster ciphers
  698. clientConfig.DynamicRecordSizingDisabled = dynamicRecordSizingDisabled
  699. buf := make([]byte, bufsize)
  700. chunks := int(math.Ceil(float64(totalBytes) / float64(len(buf))))
  701. for i := 0; i < N; i++ {
  702. conn, err := Dial("tcp", ln.Addr().String(), clientConfig)
  703. if err != nil {
  704. b.Fatal(err)
  705. }
  706. for j := 0; j < chunks; j++ {
  707. _, err := conn.Write(buf)
  708. if err != nil {
  709. b.Fatal(err)
  710. }
  711. _, err = io.ReadFull(conn, buf)
  712. if err != nil {
  713. b.Fatal(err)
  714. }
  715. }
  716. conn.Close()
  717. }
  718. }
  719. func BenchmarkThroughput(b *testing.B) {
  720. for _, mode := range []string{"Max", "Dynamic"} {
  721. for size := 1; size <= 64; size <<= 1 {
  722. name := fmt.Sprintf("%sPacket/%dMB", mode, size)
  723. b.Run(name, func(b *testing.B) {
  724. throughput(b, int64(size<<20), mode == "Max")
  725. })
  726. }
  727. }
  728. }
  729. type slowConn struct {
  730. net.Conn
  731. bps int
  732. }
  733. func (c *slowConn) Write(p []byte) (int, error) {
  734. if c.bps == 0 {
  735. panic("too slow")
  736. }
  737. t0 := time.Now()
  738. wrote := 0
  739. for wrote < len(p) {
  740. time.Sleep(100 * time.Microsecond)
  741. allowed := int(time.Since(t0).Seconds()*float64(c.bps)) / 8
  742. if allowed > len(p) {
  743. allowed = len(p)
  744. }
  745. if wrote < allowed {
  746. n, err := c.Conn.Write(p[wrote:allowed])
  747. wrote += n
  748. if err != nil {
  749. return wrote, err
  750. }
  751. }
  752. }
  753. return len(p), nil
  754. }
  755. func latency(b *testing.B, bps int, dynamicRecordSizingDisabled bool) {
  756. ln := newLocalListener(b)
  757. defer ln.Close()
  758. N := b.N
  759. go func() {
  760. for i := 0; i < N; i++ {
  761. sconn, err := ln.Accept()
  762. if err != nil {
  763. // panic rather than synchronize to avoid benchmark overhead
  764. // (cannot call b.Fatal in goroutine)
  765. panic(fmt.Errorf("accept: %v", err))
  766. }
  767. serverConfig := testConfig.Clone()
  768. serverConfig.DynamicRecordSizingDisabled = dynamicRecordSizingDisabled
  769. srv := Server(&slowConn{sconn, bps}, serverConfig)
  770. if err := srv.Handshake(); err != nil {
  771. panic(fmt.Errorf("handshake: %v", err))
  772. }
  773. io.Copy(srv, srv)
  774. }
  775. }()
  776. clientConfig := testConfig.Clone()
  777. clientConfig.DynamicRecordSizingDisabled = dynamicRecordSizingDisabled
  778. buf := make([]byte, 16384)
  779. peek := make([]byte, 1)
  780. for i := 0; i < N; i++ {
  781. conn, err := Dial("tcp", ln.Addr().String(), clientConfig)
  782. if err != nil {
  783. b.Fatal(err)
  784. }
  785. // make sure we're connected and previous connection has stopped
  786. if _, err := conn.Write(buf[:1]); err != nil {
  787. b.Fatal(err)
  788. }
  789. if _, err := io.ReadFull(conn, peek); err != nil {
  790. b.Fatal(err)
  791. }
  792. if _, err := conn.Write(buf); err != nil {
  793. b.Fatal(err)
  794. }
  795. if _, err = io.ReadFull(conn, peek); err != nil {
  796. b.Fatal(err)
  797. }
  798. conn.Close()
  799. }
  800. }
  801. func BenchmarkLatency(b *testing.B) {
  802. for _, mode := range []string{"Max", "Dynamic"} {
  803. for _, kbps := range []int{200, 500, 1000, 2000, 5000} {
  804. name := fmt.Sprintf("%sPacket/%dkbps", mode, kbps)
  805. b.Run(name, func(b *testing.B) {
  806. latency(b, kbps*1000, mode == "Max")
  807. })
  808. }
  809. }
  810. }