renew.go 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199
  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. renewMutex 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. certNotAfter: cert.Leaf.NotAfter.Add(-1 * time.Minute),
  46. }
  47. for _, f := range opts {
  48. if err := f(r); err != nil {
  49. return nil, errors.Wrap(err, "error applying options")
  50. }
  51. }
  52. // Use the current time to calculate the initial period. Using a notBefore
  53. // in the past might set a renewBefore too large, causing continuous
  54. // renewals due to the negative values in nextRenewDuration.
  55. period := cert.Leaf.NotAfter.Sub(time.Now().Truncate(time.Second))
  56. if period < minCertDuration {
  57. return nil, errors.Errorf("period must be greater than or equal to %s, but got %v.", minCertDuration, period)
  58. }
  59. // By default we will try to renew the cert before 2/3 of the validity
  60. // period have expired.
  61. if r.renewBefore == 0 {
  62. r.renewBefore = period / 3
  63. }
  64. // By default we set the jitter to 1/20th of the validity period.
  65. if r.renewJitter == 0 {
  66. r.renewJitter = period / 20
  67. }
  68. return r, nil
  69. }
  70. // Run starts the certificate renewer for the given certificate.
  71. func (r *TLSRenewer) Run() {
  72. cert := r.getCertificate()
  73. next := r.nextRenewDuration(cert.Leaf.NotAfter)
  74. r.renewMutex.Lock()
  75. r.timer = time.AfterFunc(next, r.renewCertificate)
  76. r.renewMutex.Unlock()
  77. }
  78. // RunContext starts the certificate renewer for the given certificate.
  79. func (r *TLSRenewer) RunContext(ctx context.Context) {
  80. r.Run()
  81. go func() {
  82. <-ctx.Done()
  83. r.Stop()
  84. }()
  85. }
  86. // Stop prevents the renew timer from firing.
  87. func (r *TLSRenewer) Stop() bool {
  88. if r.timer != nil {
  89. return r.timer.Stop()
  90. }
  91. return true
  92. }
  93. // GetCertificate returns the current server certificate.
  94. //
  95. // This method is set in the tls.Config GetCertificate property.
  96. func (r *TLSRenewer) GetCertificate(*tls.ClientHelloInfo) (*tls.Certificate, error) {
  97. return r.getCertificate(), nil
  98. }
  99. // GetCertificateForCA returns the current server certificate. It can only be
  100. // used if the renew function creates the new certificate and do not uses a TLS
  101. // request. It's intended to be use by the certificate authority server.
  102. //
  103. // This method is set in the tls.Config GetCertificate property.
  104. func (r *TLSRenewer) GetCertificateForCA(*tls.ClientHelloInfo) (*tls.Certificate, error) {
  105. return r.getCertificateForCA(), nil
  106. }
  107. // GetClientCertificate returns the current client certificate.
  108. //
  109. // This method is set in the tls.Config GetClientCertificate property.
  110. func (r *TLSRenewer) GetClientCertificate(*tls.CertificateRequestInfo) (*tls.Certificate, error) {
  111. return r.getCertificate(), nil
  112. }
  113. // getCertificate returns the certificate using a read-only lock.
  114. //
  115. // Known issue: It cannot renew an expired certificate because the /renew
  116. // endpoint requires a valid client certificate. The certificate can expire
  117. // if the timer does not fire e.g. when the CA is run from a laptop that
  118. // enters sleep mode.
  119. func (r *TLSRenewer) getCertificate() *tls.Certificate {
  120. r.renewMutex.RLock()
  121. cert := r.cert
  122. r.renewMutex.RUnlock()
  123. return cert
  124. }
  125. // getCertificateForCA returns the certificate using a read-only lock. It will
  126. // automatically renew the certificate if it has expired.
  127. func (r *TLSRenewer) getCertificateForCA() *tls.Certificate {
  128. r.renewMutex.RLock()
  129. // Force certificate renewal if the timer didn't run.
  130. // This is an special case that can happen after a computer sleep.
  131. if time.Now().After(r.certNotAfter) {
  132. r.renewMutex.RUnlock()
  133. r.renewCertificate()
  134. r.renewMutex.RLock()
  135. }
  136. cert := r.cert
  137. r.renewMutex.RUnlock()
  138. return cert
  139. }
  140. // setCertificate updates the certificate using a read-write lock. It also
  141. // updates certNotAfter with 1m of delta; this will force the renewal of the
  142. // certificate if it is about to expire.
  143. func (r *TLSRenewer) setCertificate(cert *tls.Certificate) {
  144. r.renewMutex.Lock()
  145. r.cert = cert
  146. r.certNotAfter = cert.Leaf.NotAfter.Add(-1 * time.Minute)
  147. r.renewMutex.Unlock()
  148. }
  149. func (r *TLSRenewer) renewCertificate() {
  150. var next time.Duration
  151. cert, err := r.RenewCertificate()
  152. if err != nil {
  153. next = r.renewJitter / 2
  154. next += time.Duration(mathRandInt63n(int64(next)))
  155. } else {
  156. r.setCertificate(cert)
  157. next = r.nextRenewDuration(cert.Leaf.NotAfter)
  158. }
  159. r.renewMutex.Lock()
  160. r.timer.Reset(next)
  161. r.renewMutex.Unlock()
  162. }
  163. func (r *TLSRenewer) nextRenewDuration(notAfter time.Time) time.Duration {
  164. d := time.Until(notAfter).Truncate(time.Second) - r.renewBefore
  165. n := mathRandInt63n(int64(r.renewJitter))
  166. d -= time.Duration(n)
  167. if d < 0 {
  168. d = 0
  169. }
  170. return d
  171. }
  172. //nolint:gosec // not used for cryptographic security
  173. func mathRandInt63n(n int64) int64 {
  174. return rand.Int63n(n)
  175. }