4
0

renew.go 5.4 KB

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