server.go 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137
  1. package main
  2. import (
  3. "crypto/tls"
  4. "crypto/x509"
  5. "errors"
  6. "fmt"
  7. "io/ioutil"
  8. "log"
  9. "net/http"
  10. "sync"
  11. "time"
  12. )
  13. const (
  14. autocertFile = "/var/run/autocert.step.sm/site.crt"
  15. autocertKey = "/var/run/autocert.step.sm/site.key"
  16. autocertRoot = "/var/run/autocert.step.sm/root.crt"
  17. tickFrequency = 15 * time.Second
  18. )
  19. // Uses techniques from https://diogomonica.com/2017/01/11/hitless-tls-certificate-rotation-in-go/
  20. // to automatically rotate certificates when they're renewed.
  21. type rotator struct {
  22. sync.RWMutex
  23. certificate *tls.Certificate
  24. }
  25. func (r *rotator) getCertificate(hello *tls.ClientHelloInfo) (*tls.Certificate, error) {
  26. r.RLock()
  27. defer r.RUnlock()
  28. return r.certificate, nil
  29. }
  30. func (r *rotator) loadCertificate(certFile, keyFile string) error {
  31. r.Lock()
  32. defer r.Unlock()
  33. c, err := tls.LoadX509KeyPair(certFile, keyFile)
  34. if err != nil {
  35. return err
  36. }
  37. r.certificate = &c
  38. return nil
  39. }
  40. func loadRootCertPool() (*x509.CertPool, error) {
  41. root, err := ioutil.ReadFile(autocertRoot)
  42. if err != nil {
  43. return nil, err
  44. }
  45. pool := x509.NewCertPool()
  46. if ok := pool.AppendCertsFromPEM(root); !ok {
  47. return nil, errors.New("Missing or invalid root certificate")
  48. }
  49. return pool, nil
  50. }
  51. func main() {
  52. mux := http.NewServeMux()
  53. mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
  54. if r.TLS == nil || len(r.TLS.PeerCertificates) == 0 {
  55. fmt.Fprintf(w, "Unauthenticated")
  56. } else {
  57. name := r.TLS.PeerCertificates[0].Subject.CommonName
  58. fmt.Fprintf(w, "Hello, %s!\n", name)
  59. }
  60. })
  61. mux.HandleFunc("/healthz", func(w http.ResponseWriter, r *http.Request) {
  62. fmt.Fprintf(w, "Ok\n")
  63. })
  64. roots, err := loadRootCertPool()
  65. if err != nil {
  66. log.Fatal(err)
  67. }
  68. r := &rotator{}
  69. cfg := &tls.Config{
  70. ClientAuth: tls.RequireAndVerifyClientCert,
  71. ClientCAs: roots,
  72. MinVersion: tls.VersionTLS12,
  73. CurvePreferences: []tls.CurveID{tls.CurveP521, tls.CurveP384, tls.CurveP256},
  74. PreferServerCipherSuites: true,
  75. CipherSuites: []uint16{
  76. tls.TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305,
  77. tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
  78. },
  79. GetCertificate: r.getCertificate,
  80. }
  81. srv := &http.Server{
  82. Addr: ":443",
  83. Handler: mux,
  84. TLSConfig: cfg,
  85. }
  86. // Load certificate
  87. err = r.loadCertificate(autocertFile, autocertKey)
  88. if err != nil {
  89. log.Fatal("Error loading certificate and key", err)
  90. }
  91. // Schedule periodic re-load of certificate
  92. // A real implementation can use something like
  93. // https://github.com/fsnotify/fsnotify
  94. done := make(chan struct{})
  95. go func() {
  96. ticker := time.NewTicker(tickFrequency)
  97. defer ticker.Stop()
  98. for {
  99. select {
  100. case <-ticker.C:
  101. fmt.Println("Checking for new certificate...")
  102. err := r.loadCertificate(autocertFile, autocertKey)
  103. if err != nil {
  104. log.Println("Error loading certificate and key", err)
  105. }
  106. case <-done:
  107. return
  108. }
  109. }
  110. }()
  111. defer close(done)
  112. log.Println("Listening no :443")
  113. // Start serving HTTPS
  114. err = srv.ListenAndServeTLS("", "")
  115. if err != nil {
  116. log.Fatal("ListenAndServerTLS: ", err)
  117. }
  118. }