client.go 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142
  1. package main
  2. import (
  3. "crypto/tls"
  4. "crypto/x509"
  5. "errors"
  6. "fmt"
  7. "io/ioutil"
  8. "log"
  9. "net/http"
  10. "os"
  11. "strings"
  12. "sync"
  13. "time"
  14. )
  15. const (
  16. autocertFile = "/var/run/autocert.step.sm/site.crt"
  17. autocertKey = "/var/run/autocert.step.sm/site.key"
  18. autocertRoot = "/var/run/autocert.step.sm/root.crt"
  19. requestFrequency = 5 * time.Second
  20. tickFrequency = 15 * time.Second
  21. )
  22. type rotator struct {
  23. sync.RWMutex
  24. certificate *tls.Certificate
  25. }
  26. func (r *rotator) getClientCertificate(cri *tls.CertificateRequestInfo) (*tls.Certificate, error) {
  27. r.RLock()
  28. defer r.RUnlock()
  29. return r.certificate, nil
  30. }
  31. func (r *rotator) loadCertificate(certFile, keyFile string) error {
  32. r.Lock()
  33. defer r.Unlock()
  34. c, err := tls.LoadX509KeyPair(certFile, keyFile)
  35. if err != nil {
  36. return err
  37. }
  38. r.certificate = &c
  39. return nil
  40. }
  41. func loadRootCertPool() (*x509.CertPool, error) {
  42. root, err := ioutil.ReadFile(autocertRoot)
  43. if err != nil {
  44. return nil, err
  45. }
  46. pool := x509.NewCertPool()
  47. if ok := pool.AppendCertsFromPEM(root); !ok {
  48. return nil, errors.New("Missing or invalid root certificate")
  49. }
  50. return pool, nil
  51. }
  52. func main() {
  53. url := os.Getenv("HELLO_MTLS_URL")
  54. // Read the root certificate for our CA from disk
  55. roots, err := loadRootCertPool()
  56. if err != nil {
  57. log.Fatal(err)
  58. }
  59. // Load certificate
  60. r := &rotator{}
  61. if err := r.loadCertificate(autocertFile, autocertKey); err != nil {
  62. log.Fatal("error loading certificate and key", err)
  63. }
  64. // Create an HTTPS client using our cert, key & pool
  65. client := &http.Client{
  66. Transport: &http.Transport{
  67. TLSClientConfig: &tls.Config{
  68. RootCAs: roots,
  69. MinVersion: tls.VersionTLS12,
  70. CurvePreferences: []tls.CurveID{tls.CurveP521, tls.CurveP384, tls.CurveP256},
  71. CipherSuites: []uint16{
  72. tls.TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305,
  73. tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
  74. },
  75. // GetClientCertificate is called when a server requests a
  76. // certificate from a client.
  77. //
  78. // In this example keep alives will cause the certificate to
  79. // only be called once, but if we disable them,
  80. // GetClientCertificate will be called on every request.
  81. GetClientCertificate: r.getClientCertificate,
  82. },
  83. // Add this line to get the certificate on every request.
  84. // DisableKeepAlives: true,
  85. },
  86. }
  87. // Schedule periodic re-load of certificate
  88. // A real implementation can use something like
  89. // https://github.com/fsnotify/fsnotify
  90. done := make(chan struct{})
  91. go func() {
  92. ticker := time.NewTicker(tickFrequency)
  93. defer ticker.Stop()
  94. for {
  95. select {
  96. case <-ticker.C:
  97. fmt.Println("Checking for new certificate...")
  98. err := r.loadCertificate(autocertFile, autocertKey)
  99. if err != nil {
  100. log.Println("Error loading certificate and key", err)
  101. }
  102. case <-done:
  103. return
  104. }
  105. }
  106. }()
  107. defer close(done)
  108. for {
  109. // Make request
  110. r, err := client.Get(url)
  111. if err != nil {
  112. log.Fatal(err)
  113. }
  114. defer r.Body.Close()
  115. body, err := ioutil.ReadAll(r.Body)
  116. if err != nil {
  117. log.Fatal(err)
  118. }
  119. fmt.Printf("%s: %s\n", time.Now().Format(time.RFC3339), strings.Trim(string(body), "\n"))
  120. time.Sleep(requestFrequency)
  121. }
  122. }