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.

236 lines
8.4 KiB

  1. // Copyright 2014 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 th5_test
  5. import (
  6. "crypto/tls"
  7. "crypto/x509"
  8. "log"
  9. "net/http"
  10. "net/http/httptest"
  11. "os"
  12. "time"
  13. )
  14. // zeroSource is an io.Reader that returns an unlimited number of zero bytes.
  15. type zeroSource struct{}
  16. func (zeroSource) Read(b []byte) (n int, err error) {
  17. for i := range b {
  18. b[i] = 0
  19. }
  20. return len(b), nil
  21. }
  22. func ExampleDial() {
  23. // Connecting with a custom root-certificate set.
  24. const rootPEM = `
  25. -----BEGIN CERTIFICATE-----
  26. MIIEBDCCAuygAwIBAgIDAjppMA0GCSqGSIb3DQEBBQUAMEIxCzAJBgNVBAYTAlVT
  27. MRYwFAYDVQQKEw1HZW9UcnVzdCBJbmMuMRswGQYDVQQDExJHZW9UcnVzdCBHbG9i
  28. YWwgQ0EwHhcNMTMwNDA1MTUxNTU1WhcNMTUwNDA0MTUxNTU1WjBJMQswCQYDVQQG
  29. EwJVUzETMBEGA1UEChMKR29vZ2xlIEluYzElMCMGA1UEAxMcR29vZ2xlIEludGVy
  30. bmV0IEF1dGhvcml0eSBHMjCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEB
  31. AJwqBHdc2FCROgajguDYUEi8iT/xGXAaiEZ+4I/F8YnOIe5a/mENtzJEiaB0C1NP
  32. VaTOgmKV7utZX8bhBYASxF6UP7xbSDj0U/ck5vuR6RXEz/RTDfRK/J9U3n2+oGtv
  33. h8DQUB8oMANA2ghzUWx//zo8pzcGjr1LEQTrfSTe5vn8MXH7lNVg8y5Kr0LSy+rE
  34. ahqyzFPdFUuLH8gZYR/Nnag+YyuENWllhMgZxUYi+FOVvuOAShDGKuy6lyARxzmZ
  35. EASg8GF6lSWMTlJ14rbtCMoU/M4iarNOz0YDl5cDfsCx3nuvRTPPuj5xt970JSXC
  36. DTWJnZ37DhF5iR43xa+OcmkCAwEAAaOB+zCB+DAfBgNVHSMEGDAWgBTAephojYn7
  37. qwVkDBF9qn1luMrMTjAdBgNVHQ4EFgQUSt0GFhu89mi1dvWBtrtiGrpagS8wEgYD
  38. VR0TAQH/BAgwBgEB/wIBADAOBgNVHQ8BAf8EBAMCAQYwOgYDVR0fBDMwMTAvoC2g
  39. K4YpaHR0cDovL2NybC5nZW90cnVzdC5jb20vY3Jscy9ndGdsb2JhbC5jcmwwPQYI
  40. KwYBBQUHAQEEMTAvMC0GCCsGAQUFBzABhiFodHRwOi8vZ3RnbG9iYWwtb2NzcC5n
  41. ZW90cnVzdC5jb20wFwYDVR0gBBAwDjAMBgorBgEEAdZ5AgUBMA0GCSqGSIb3DQEB
  42. BQUAA4IBAQA21waAESetKhSbOHezI6B1WLuxfoNCunLaHtiONgaX4PCVOzf9G0JY
  43. /iLIa704XtE7JW4S615ndkZAkNoUyHgN7ZVm2o6Gb4ChulYylYbc3GrKBIxbf/a/
  44. zG+FA1jDaFETzf3I93k9mTXwVqO94FntT0QJo544evZG0R0SnU++0ED8Vf4GXjza
  45. HFa9llF7b1cq26KqltyMdMKVvvBulRP/F/A8rLIQjcxz++iPAsbw+zOzlTvjwsto
  46. WHPbqCRiOwY1nQ2pM714A5AuTHhdUDqB1O6gyHA43LL5Z/qHQF1hwFGPa4NrzQU6
  47. yuGnBXj8ytqU0CwIPX4WecigUCAkVDNx
  48. -----END CERTIFICATE-----`
  49. // First, create the set of root certificates. For this example we only
  50. // have one. It's also possible to omit this in order to use the
  51. // default root set of the current operating system.
  52. roots := x509.NewCertPool()
  53. ok := roots.AppendCertsFromPEM([]byte(rootPEM))
  54. if !ok {
  55. panic("failed to parse root certificate")
  56. }
  57. conn, err := tls.Dial("tcp", "mail.google.com:443", &tls.Config{
  58. RootCAs: roots,
  59. })
  60. if err != nil {
  61. panic("failed to connect: " + err.Error())
  62. }
  63. conn.Close()
  64. }
  65. func ExampleConfig_keyLogWriter_TLS12() {
  66. // Debugging TLS applications by decrypting a network traffic capture.
  67. // WARNING: Use of KeyLogWriter compromises security and should only be
  68. // used for debugging.
  69. // Dummy test HTTP server for the example with insecure random so output is
  70. // reproducible.
  71. server := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {}))
  72. server.TLS = &tls.Config{
  73. Rand: zeroSource{}, // for example only; don't do this.
  74. MaxVersion: tls.VersionTLS12,
  75. }
  76. server.StartTLS()
  77. defer server.Close()
  78. // Typically the log would go to an open file:
  79. // w, err := os.OpenFile("tls-secrets.txt", os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600)
  80. w := os.Stdout
  81. client := &http.Client{
  82. Transport: &http.Transport{
  83. TLSClientConfig: &tls.Config{
  84. KeyLogWriter: w,
  85. Rand: zeroSource{}, // for reproducible output; don't do this.
  86. InsecureSkipVerify: true, // test server certificate is not trusted.
  87. },
  88. },
  89. }
  90. resp, err := client.Get(server.URL)
  91. if err != nil {
  92. log.Fatalf("Failed to get URL: %v", err)
  93. }
  94. resp.Body.Close()
  95. // The resulting file can be used with Wireshark to decrypt the TLS
  96. // connection by setting (Pre)-Master-Secret log filename in SSL Protocol
  97. // preferences.
  98. // Output:
  99. // CLIENT_RANDOM 0000000000000000000000000000000000000000000000000000000000000000 baca0df460a688e44ce018b025183cc2353ae01f89755ef766eedd3ecc302888ee3b3a22962e45f48c20df15a98c0e80
  100. }
  101. func ExampleConfig_keyLogWriter_TLS13() {
  102. // Debugging TLS applications by decrypting a network traffic capture.
  103. // WARNING: Use of KeyLogWriter compromises security and should only be
  104. // used for debugging.
  105. // Dummy test HTTP server for the example with insecure random so output is
  106. // reproducible.
  107. server := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {}))
  108. server.TLS = &tls.Config{
  109. Rand: zeroSource{}, // for example only; don't do this.
  110. }
  111. server.StartTLS()
  112. defer server.Close()
  113. // Typically the log would go to an open file:
  114. // w, err := os.OpenFile("tls-secrets.txt", os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600)
  115. w := os.Stdout
  116. client := &http.Client{
  117. Transport: &http.Transport{
  118. TLSClientConfig: &tls.Config{
  119. KeyLogWriter: w,
  120. Rand: zeroSource{}, // for reproducible output; don't do this.
  121. InsecureSkipVerify: true, // test server certificate is not trusted.
  122. },
  123. },
  124. }
  125. resp, err := client.Get(server.URL)
  126. if err != nil {
  127. log.Fatalf("Failed to get URL: %v", err)
  128. }
  129. resp.Body.Close()
  130. // The resulting file can be used with Wireshark to decrypt the TLS
  131. // connection by setting (Pre)-Master-Secret log filename in SSL Protocol
  132. // preferences.
  133. // Output:
  134. // CLIENT_HANDSHAKE_TRAFFIC_SECRET 0000000000000000000000000000000000000000000000000000000000000000 b946c84f46f53bd410368a1fd7d53873e74bedd53b4b1a4b125be40c8b0510a1
  135. // SERVER_HANDSHAKE_TRAFFIC_SECRET 0000000000000000000000000000000000000000000000000000000000000000 b6c44e95e34cb2616ff2e9a1163577aa1aa5cb3af8df16d0fdbbbaf15f415c8e
  136. // SERVER_TRAFFIC_SECRET_0 0000000000000000000000000000000000000000000000000000000000000000 cbecc42509a124ae517f6c9aaae1961d755ab4268548b40b0c7840a9643240e8
  137. // CLIENT_TRAFFIC_SECRET_0 0000000000000000000000000000000000000000000000000000000000000000 8f6dd1476706ea8147d829347937694496a7d62d6d01de0a1b4820140d01cad0
  138. }
  139. func ExampleLoadX509KeyPair() {
  140. cert, err := tls.LoadX509KeyPair("testdata/example-cert.pem", "testdata/example-key.pem")
  141. if err != nil {
  142. log.Fatal(err)
  143. }
  144. cfg := &tls.Config{Certificates: []tls.Certificate{cert}}
  145. listener, err := tls.Listen("tcp", ":2000", cfg)
  146. if err != nil {
  147. log.Fatal(err)
  148. }
  149. _ = listener
  150. }
  151. func ExampleX509KeyPair() {
  152. certPem := []byte(`-----BEGIN CERTIFICATE-----
  153. MIIBhTCCASugAwIBAgIQIRi6zePL6mKjOipn+dNuaTAKBggqhkjOPQQDAjASMRAw
  154. DgYDVQQKEwdBY21lIENvMB4XDTE3MTAyMDE5NDMwNloXDTE4MTAyMDE5NDMwNlow
  155. EjEQMA4GA1UEChMHQWNtZSBDbzBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABD0d
  156. 7VNhbWvZLWPuj/RtHFjvtJBEwOkhbN/BnnE8rnZR8+sbwnc/KhCk3FhnpHZnQz7B
  157. 5aETbbIgmuvewdjvSBSjYzBhMA4GA1UdDwEB/wQEAwICpDATBgNVHSUEDDAKBggr
  158. BgEFBQcDATAPBgNVHRMBAf8EBTADAQH/MCkGA1UdEQQiMCCCDmxvY2FsaG9zdDo1
  159. NDUzgg4xMjcuMC4wLjE6NTQ1MzAKBggqhkjOPQQDAgNIADBFAiEA2zpJEPQyz6/l
  160. Wf86aX6PepsntZv2GYlA5UpabfT2EZICICpJ5h/iI+i341gBmLiAFQOyTDT+/wQc
  161. 6MF9+Yw1Yy0t
  162. -----END CERTIFICATE-----`)
  163. keyPem := []byte(`-----BEGIN EC PRIVATE KEY-----
  164. MHcCAQEEIIrYSSNQFaA2Hwf1duRSxKtLYX5CB04fSeQ6tF1aY/PuoAoGCCqGSM49
  165. AwEHoUQDQgAEPR3tU2Fta9ktY+6P9G0cWO+0kETA6SFs38GecTyudlHz6xvCdz8q
  166. EKTcWGekdmdDPsHloRNtsiCa697B2O9IFA==
  167. -----END EC PRIVATE KEY-----`)
  168. cert, err := tls.X509KeyPair(certPem, keyPem)
  169. if err != nil {
  170. log.Fatal(err)
  171. }
  172. cfg := &tls.Config{Certificates: []tls.Certificate{cert}}
  173. listener, err := tls.Listen("tcp", ":2000", cfg)
  174. if err != nil {
  175. log.Fatal(err)
  176. }
  177. _ = listener
  178. }
  179. func ExampleX509KeyPair_httpServer() {
  180. certPem := []byte(`-----BEGIN CERTIFICATE-----
  181. MIIBhTCCASugAwIBAgIQIRi6zePL6mKjOipn+dNuaTAKBggqhkjOPQQDAjASMRAw
  182. DgYDVQQKEwdBY21lIENvMB4XDTE3MTAyMDE5NDMwNloXDTE4MTAyMDE5NDMwNlow
  183. EjEQMA4GA1UEChMHQWNtZSBDbzBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABD0d
  184. 7VNhbWvZLWPuj/RtHFjvtJBEwOkhbN/BnnE8rnZR8+sbwnc/KhCk3FhnpHZnQz7B
  185. 5aETbbIgmuvewdjvSBSjYzBhMA4GA1UdDwEB/wQEAwICpDATBgNVHSUEDDAKBggr
  186. BgEFBQcDATAPBgNVHRMBAf8EBTADAQH/MCkGA1UdEQQiMCCCDmxvY2FsaG9zdDo1
  187. NDUzgg4xMjcuMC4wLjE6NTQ1MzAKBggqhkjOPQQDAgNIADBFAiEA2zpJEPQyz6/l
  188. Wf86aX6PepsntZv2GYlA5UpabfT2EZICICpJ5h/iI+i341gBmLiAFQOyTDT+/wQc
  189. 6MF9+Yw1Yy0t
  190. -----END CERTIFICATE-----`)
  191. keyPem := []byte(`-----BEGIN EC PRIVATE KEY-----
  192. MHcCAQEEIIrYSSNQFaA2Hwf1duRSxKtLYX5CB04fSeQ6tF1aY/PuoAoGCCqGSM49
  193. AwEHoUQDQgAEPR3tU2Fta9ktY+6P9G0cWO+0kETA6SFs38GecTyudlHz6xvCdz8q
  194. EKTcWGekdmdDPsHloRNtsiCa697B2O9IFA==
  195. -----END EC PRIVATE KEY-----`)
  196. cert, err := tls.X509KeyPair(certPem, keyPem)
  197. if err != nil {
  198. log.Fatal(err)
  199. }
  200. cfg := &tls.Config{Certificates: []tls.Certificate{cert}}
  201. srv := &http.Server{
  202. TLSConfig: cfg,
  203. ReadTimeout: time.Minute,
  204. WriteTimeout: time.Minute,
  205. }
  206. log.Fatal(srv.ListenAndServeTLS("", ""))
  207. }