renew.go 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190
  1. package ca
  2. import (
  3. "context"
  4. "crypto/tls"
  5. "math/rand"
  6. "sync"
  7. "time"
  8. "github.com/pkg/errors"
  9. )
  10. // RenewFunc defines the type of the functions used to get a new tls
  11. // certificate.
  12. type RenewFunc func() (*tls.Certificate, error)
  13. var minCertDuration = time.Minute
  14. // TLSRenewer automatically renews a tls certificate using a RenewFunc.
  15. type TLSRenewer struct {
  16. sync.RWMutex
  17. RenewCertificate RenewFunc
  18. cert *tls.Certificate
  19. timer *time.Timer
  20. renewBefore time.Duration
  21. renewJitter time.Duration
  22. certNotAfter time.Time
  23. }
  24. type tlsRenewerOptions func(r *TLSRenewer) error
  25. // WithRenewBefore modifies a tlsRenewer by setting the renewBefore attribute.
  26. func WithRenewBefore(b time.Duration) func(r *TLSRenewer) error {
  27. return func(r *TLSRenewer) error {
  28. r.renewBefore = b
  29. return nil
  30. }
  31. }
  32. // WithRenewJitter modifies a tlsRenewer by setting the renewJitter attribute.
  33. func WithRenewJitter(j time.Duration) func(r *TLSRenewer) error {
  34. return func(r *TLSRenewer) error {
  35. r.renewJitter = j
  36. return nil
  37. }
  38. }
  39. // NewTLSRenewer creates a TLSRenewer for the given cert. It will use the given
  40. // RenewFunc to get a new certificate when required.
  41. func NewTLSRenewer(cert *tls.Certificate, fn RenewFunc, opts ...tlsRenewerOptions) (*TLSRenewer, error) {
  42. r := &TLSRenewer{
  43. RenewCertificate: fn,
  44. cert: cert,
  45. }
  46. for _, f := range opts {
  47. if err := f(r); err != nil {
  48. return nil, errors.Wrap(err, "error applying options")
  49. }
  50. }
  51. period := cert.Leaf.NotAfter.Sub(cert.Leaf.NotBefore)
  52. if period < minCertDuration {
  53. return nil, errors.Errorf("period must be greater than or equal to %s, but got %v.", minCertDuration, period)
  54. }
  55. // By default we will try to renew the cert before 2/3 of the validity
  56. // period have expired.
  57. if r.renewBefore == 0 {
  58. r.renewBefore = period / 3
  59. }
  60. // By default we set the jitter to 1/20th of the validity period.
  61. if r.renewJitter == 0 {
  62. r.renewJitter = period / 20
  63. }
  64. return r, nil
  65. }
  66. // Run starts the certificate renewer for the given certificate.
  67. func (r *TLSRenewer) Run() {
  68. cert := r.getCertificate()
  69. next := r.nextRenewDuration(cert.Leaf.NotAfter)
  70. r.Lock()
  71. r.timer = time.AfterFunc(next, r.renewCertificate)
  72. r.Unlock()
  73. }
  74. // RunContext starts the certificate renewer for the given certificate.
  75. func (r *TLSRenewer) RunContext(ctx context.Context) {
  76. r.Run()
  77. go func() {
  78. <-ctx.Done()
  79. r.Stop()
  80. }()
  81. }
  82. // Stop prevents the renew timer from firing.
  83. func (r *TLSRenewer) Stop() bool {
  84. if r.timer != nil {
  85. return r.timer.Stop()
  86. }
  87. return true
  88. }
  89. // GetCertificate returns the current server certificate.
  90. //
  91. // This method is set in the tls.Config GetCertificate property.
  92. func (r *TLSRenewer) GetCertificate(clientHello *tls.ClientHelloInfo) (*tls.Certificate, error) {
  93. return r.getCertificate(), nil
  94. }
  95. // GetCertificateForCA returns the current server certificate. It can only be
  96. // used if the renew function creates the new certificate and do not uses a TLS
  97. // request. It's intended to be use by the certificate authority server.
  98. //
  99. // This method is set in the tls.Config GetCertificate property.
  100. func (r *TLSRenewer) GetCertificateForCA(clientHello *tls.ClientHelloInfo) (*tls.Certificate, error) {
  101. return r.getCertificateForCA(), nil
  102. }
  103. // GetClientCertificate returns the current client certificate.
  104. //
  105. // This method is set in the tls.Config GetClientCertificate property.
  106. func (r *TLSRenewer) GetClientCertificate(*tls.CertificateRequestInfo) (*tls.Certificate, error) {
  107. return r.getCertificate(), nil
  108. }
  109. // getCertificate returns the certificate using a read-only lock.
  110. //
  111. // Known issue: It cannot renew an expired certificate because the /renew
  112. // endpoint requires a valid client certificate. The certificate can expire
  113. // if the timer does not fire e.g. when the CA is run from a laptop that
  114. // enters sleep mode.
  115. func (r *TLSRenewer) getCertificate() *tls.Certificate {
  116. r.RLock()
  117. cert := r.cert
  118. r.RUnlock()
  119. return cert
  120. }
  121. // getCertificateForCA returns the certificate using a read-only lock. It will
  122. // automatically renew the certificate if it has expired.
  123. func (r *TLSRenewer) getCertificateForCA() *tls.Certificate {
  124. r.RLock()
  125. // Force certificate renewal if the timer didn't run.
  126. // This is an special case that can happen after a computer sleep.
  127. if time.Now().After(r.certNotAfter) {
  128. r.RUnlock()
  129. r.renewCertificate()
  130. r.RLock()
  131. }
  132. cert := r.cert
  133. r.RUnlock()
  134. return cert
  135. }
  136. // setCertificate updates the certificate using a read-write lock. It also
  137. // updates certNotAfter with 1m of delta; this will force the renewal of the
  138. // certificate if it is about to expire.
  139. func (r *TLSRenewer) setCertificate(cert *tls.Certificate) {
  140. r.Lock()
  141. r.cert = cert
  142. r.certNotAfter = cert.Leaf.NotAfter.Add(-1 * time.Minute)
  143. r.Unlock()
  144. }
  145. func (r *TLSRenewer) renewCertificate() {
  146. var next time.Duration
  147. cert, err := r.RenewCertificate()
  148. if err != nil {
  149. next = r.renewJitter / 2
  150. next += time.Duration(rand.Int63n(int64(next)))
  151. } else {
  152. r.setCertificate(cert)
  153. next = r.nextRenewDuration(cert.Leaf.NotAfter)
  154. }
  155. r.Lock()
  156. r.timer.Reset(next)
  157. r.Unlock()
  158. }
  159. func (r *TLSRenewer) nextRenewDuration(notAfter time.Time) time.Duration {
  160. d := time.Until(notAfter) - r.renewBefore
  161. n := rand.Int63n(int64(r.renewJitter))
  162. d -= time.Duration(n)
  163. if d < 0 {
  164. d = 0
  165. }
  166. return d
  167. }