renew.go 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188
  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.timer = time.AfterFunc(next, r.renewCertificate)
  71. }
  72. // RunContext starts the certificate renewer for the given certificate.
  73. func (r *TLSRenewer) RunContext(ctx context.Context) {
  74. r.Run()
  75. go func() {
  76. <-ctx.Done()
  77. r.Stop()
  78. }()
  79. }
  80. // Stop prevents the renew timer from firing.
  81. func (r *TLSRenewer) Stop() bool {
  82. if r.timer != nil {
  83. return r.timer.Stop()
  84. }
  85. return true
  86. }
  87. // GetCertificate returns the current server certificate.
  88. //
  89. // This method is set in the tls.Config GetCertificate property.
  90. func (r *TLSRenewer) GetCertificate(clientHello *tls.ClientHelloInfo) (*tls.Certificate, error) {
  91. return r.getCertificate(), nil
  92. }
  93. // GetCertificateForCA returns the current server certificate. It can only be
  94. // used if the renew function creates the new certificate and do not uses a TLS
  95. // request. It's intended to be use by the certificate authority server.
  96. //
  97. // This method is set in the tls.Config GetCertificate property.
  98. func (r *TLSRenewer) GetCertificateForCA(clientHello *tls.ClientHelloInfo) (*tls.Certificate, error) {
  99. return r.getCertificateForCA(), nil
  100. }
  101. // GetClientCertificate returns the current client certificate.
  102. //
  103. // This method is set in the tls.Config GetClientCertificate property.
  104. func (r *TLSRenewer) GetClientCertificate(*tls.CertificateRequestInfo) (*tls.Certificate, error) {
  105. return r.getCertificate(), nil
  106. }
  107. // getCertificate returns the certificate using a read-only lock.
  108. //
  109. // Known issue: It cannot renew an expired certificate because the /renew
  110. // endpoint requires a valid client certificate. The certificate can expire
  111. // if the timer does not fire e.g. when the CA is run from a laptop that
  112. // enters sleep mode.
  113. func (r *TLSRenewer) getCertificate() *tls.Certificate {
  114. r.RLock()
  115. cert := r.cert
  116. r.RUnlock()
  117. return cert
  118. }
  119. // getCertificateForCA returns the certificate using a read-only lock. It will
  120. // automatically renew the certificate if it has expired.
  121. func (r *TLSRenewer) getCertificateForCA() *tls.Certificate {
  122. r.RLock()
  123. // Force certificate renewal if the timer didn't run.
  124. // This is an special case that can happen after a computer sleep.
  125. if time.Now().After(r.certNotAfter) {
  126. r.RUnlock()
  127. r.renewCertificate()
  128. r.RLock()
  129. }
  130. cert := r.cert
  131. r.RUnlock()
  132. return cert
  133. }
  134. // setCertificate updates the certificate using a read-write lock. It also
  135. // updates certNotAfter with 1m of delta; this will force the renewal of the
  136. // certificate if it is about to expire.
  137. func (r *TLSRenewer) setCertificate(cert *tls.Certificate) {
  138. r.Lock()
  139. r.cert = cert
  140. r.certNotAfter = cert.Leaf.NotAfter.Add(-1 * time.Minute)
  141. r.Unlock()
  142. }
  143. func (r *TLSRenewer) renewCertificate() {
  144. var next time.Duration
  145. cert, err := r.RenewCertificate()
  146. if err != nil {
  147. next = r.renewJitter / 2
  148. next += time.Duration(rand.Int63n(int64(next)))
  149. } else {
  150. r.setCertificate(cert)
  151. next = r.nextRenewDuration(cert.Leaf.NotAfter)
  152. }
  153. r.Lock()
  154. r.timer.Reset(next)
  155. r.Unlock()
  156. }
  157. func (r *TLSRenewer) nextRenewDuration(notAfter time.Time) time.Duration {
  158. d := time.Until(notAfter) - r.renewBefore
  159. n := rand.Int63n(int64(r.renewJitter))
  160. d -= time.Duration(n)
  161. if d < 0 {
  162. d = 0
  163. }
  164. return d
  165. }