renew.go 3.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147
  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. // TLSRenewer renews automatically a tls certificate with a given function.
  14. type TLSRenewer struct {
  15. sync.RWMutex
  16. RenewCertificate RenewFunc
  17. cert *tls.Certificate
  18. timer *time.Timer
  19. renewBefore time.Duration
  20. renewJitter time.Duration
  21. }
  22. type tlsRenewerOptions func(r *TLSRenewer) error
  23. // WithRenewBefore modifies a tlsRenewer by setting the renewBefore attribute.
  24. func WithRenewBefore(b time.Duration) func(r *TLSRenewer) error {
  25. return func(r *TLSRenewer) error {
  26. r.renewBefore = b
  27. return nil
  28. }
  29. }
  30. // WithRenewJitter modifies a tlsRenewer by setting the renewJitter attribute.
  31. func WithRenewJitter(j time.Duration) func(r *TLSRenewer) error {
  32. return func(r *TLSRenewer) error {
  33. r.renewJitter = j
  34. return nil
  35. }
  36. }
  37. // NewTLSRenewer creates a TLSRenewer for the given cert. It will use the given
  38. // function to get a new certificate when required.
  39. func NewTLSRenewer(cert *tls.Certificate, fn RenewFunc, opts ...tlsRenewerOptions) (*TLSRenewer, error) {
  40. r := &TLSRenewer{
  41. RenewCertificate: fn,
  42. cert: cert,
  43. }
  44. for _, f := range opts {
  45. if err := f(r); err != nil {
  46. return nil, errors.Wrap(err, "error applying options")
  47. }
  48. }
  49. period := cert.Leaf.NotAfter.Sub(cert.Leaf.NotBefore)
  50. if period < time.Minute {
  51. return nil, errors.Errorf("period must be greater than or equal to 1 Minute, but got %v.", period)
  52. }
  53. // By default we will try to renew the cert before 2/3 of the validity
  54. // period have expired.
  55. if r.renewBefore == 0 {
  56. r.renewBefore = period / 3
  57. }
  58. // By default we set the jitter to 1/20th of the validity period.
  59. if r.renewJitter == 0 {
  60. r.renewJitter = period / 20
  61. }
  62. return r, nil
  63. }
  64. // Run starts the certificate renewer for the given certificate.
  65. func (r *TLSRenewer) Run() {
  66. cert := r.getCertificate()
  67. next := r.nextRenewDuration(cert.Leaf.NotAfter)
  68. r.timer = time.AfterFunc(next, r.renewCertificate)
  69. }
  70. // RunContext starts the certificate renewer for the given certificate.
  71. func (r *TLSRenewer) RunContext(ctx context.Context) {
  72. r.Run()
  73. go func() {
  74. <-ctx.Done()
  75. r.Stop()
  76. }()
  77. }
  78. // Stop prevents the renew timer from firing.
  79. func (r *TLSRenewer) Stop() bool {
  80. return r.timer.Stop()
  81. }
  82. // GetCertificate returns the current server certificate.
  83. //
  84. // This method is set in the tls.Config GetCertificate property.
  85. func (r *TLSRenewer) GetCertificate(clientHello *tls.ClientHelloInfo) (*tls.Certificate, error) {
  86. return r.getCertificate(), nil
  87. }
  88. // GetClientCertificate returns the current client certificate.
  89. //
  90. // This method is set in the tls.Config GetClientCertificate property.
  91. func (r *TLSRenewer) GetClientCertificate(*tls.CertificateRequestInfo) (*tls.Certificate, error) {
  92. return r.getCertificate(), nil
  93. }
  94. // getCertificate returns the certificate using a read-only lock.
  95. func (r *TLSRenewer) getCertificate() *tls.Certificate {
  96. r.RLock()
  97. cert := r.cert
  98. r.RUnlock()
  99. return cert
  100. }
  101. // setCertificate updates the certificate using a read-write lock.
  102. func (r *TLSRenewer) setCertificate(cert *tls.Certificate) {
  103. r.Lock()
  104. r.cert = cert
  105. r.Unlock()
  106. }
  107. func (r *TLSRenewer) renewCertificate() {
  108. var next time.Duration
  109. cert, err := r.RenewCertificate()
  110. if err != nil {
  111. next = r.renewJitter / 2
  112. next += time.Duration(rand.Int63n(int64(next)))
  113. } else {
  114. r.setCertificate(cert)
  115. next = r.nextRenewDuration(cert.Leaf.NotAfter)
  116. }
  117. r.timer = time.AfterFunc(next, r.renewCertificate)
  118. }
  119. func (r *TLSRenewer) nextRenewDuration(notAfter time.Time) time.Duration {
  120. d := notAfter.Sub(time.Now()) - r.renewBefore
  121. n := rand.Int63n(int64(r.renewJitter))
  122. d -= time.Duration(n)
  123. if d < 0 {
  124. d = 0
  125. }
  126. return d
  127. }