reloader.go 3.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129
  1. package tlscert
  2. import (
  3. "crypto/tls"
  4. "crypto/x509"
  5. "os"
  6. "sync"
  7. "time"
  8. )
  9. // reintentoTrasFallo: tras un intento de recarga fallido (p. ej. acme.sh a
  10. // medio de escribir el par), no se vuelve a tocar disco hasta pasado este
  11. // tiempo, para no martillear el filesystem en cada handshake.
  12. const reintentoTrasFallo = 30 * time.Second
  13. // Reloader sirve el par cert/clave de un usuario (#769) recargándolo del
  14. // disco cuando cambia: GetCertificate repuebla la caché si el mtime de
  15. // alguno de los dos ficheros avanza. Si la recarga falla, sigue sirviendo el
  16. // último par válido (una renovación a medio escribir no debe tumbar el
  17. // listener). El path on-box autofirmado NO usa esto: el agente fija el SPKI
  18. // en el pairing y ahí la recarga en caliente rompería el pin.
  19. type Reloader struct {
  20. certPath string
  21. keyPath string
  22. mu sync.Mutex
  23. cert *tls.Certificate
  24. mtime time.Time
  25. ultimoFallo time.Time
  26. }
  27. // NewReloader carga el par inicial; si no existe o no parsea, devuelve error
  28. // (mismo contrato que Load: nunca genera un autofirmado en rutas del usuario).
  29. func NewReloader(certPath, keyPath string) (*Reloader, error) {
  30. r := &Reloader{certPath: certPath, keyPath: keyPath}
  31. if err := r.reload(); err != nil {
  32. return nil, err
  33. }
  34. return r, nil
  35. }
  36. // Config devuelve el tls.Config del listener con GetCertificate (recarga en
  37. // caliente por mtime) en lugar de una lista estática de Certificates.
  38. func (r *Reloader) Config() *tls.Config {
  39. return &tls.Config{
  40. GetCertificate: r.GetCertificate,
  41. MinVersion: tls.VersionTLS12,
  42. }
  43. }
  44. // GetCertificate implementa tls.Config.GetCertificate: sirve la caché y, si
  45. // el mtime de algún fichero avanzó, repuebla desde disco antes.
  46. func (r *Reloader) GetCertificate(*tls.ClientHelloInfo) (*tls.Certificate, error) {
  47. r.mu.Lock()
  48. defer r.mu.Unlock()
  49. mt, err := maxMtime(r.certPath, r.keyPath)
  50. if err != nil {
  51. return r.cert, nil // stat fallando: servir lo cacheado
  52. }
  53. if mt.After(r.mtime) && time.Since(r.ultimoFallo) > reintentoTrasFallo {
  54. if err := r.reload(); err != nil {
  55. r.ultimoFallo = time.Now() // par a medio escribir: reintentar luego
  56. return r.cert, nil
  57. }
  58. }
  59. return r.cert, nil
  60. }
  61. // Fingerprint is the SPKI fingerprint of the certificate being served now,
  62. // after picking up a renewal as a handshake would. It is read live because
  63. // renewals often change the key (certbot issues a new one unless told
  64. // --reuse-key), and a value captured at start-up would hand agents a pin
  65. // the server no longer matches. Empty if the served pair cannot be parsed.
  66. func (r *Reloader) Fingerprint() string {
  67. if leaf := r.Leaf(); leaf != nil {
  68. return Fingerprint(leaf)
  69. }
  70. return ""
  71. }
  72. // Leaf devuelve la hoja que se está sirviendo ahora (#1756), para que el
  73. // estado de HTTPS pueda mostrar sus nombres y su caducidad. Pasa por
  74. // GetCertificate, así que también recarga si el par cambió en disco.
  75. func (r *Reloader) Leaf() *x509.Certificate {
  76. cert, _ := r.GetCertificate(nil)
  77. if cert == nil || len(cert.Certificate) == 0 {
  78. return nil
  79. }
  80. if cert.Leaf != nil {
  81. return cert.Leaf
  82. }
  83. leaf, err := x509.ParseCertificate(cert.Certificate[0])
  84. if err != nil {
  85. return nil
  86. }
  87. return leaf
  88. }
  89. // reload repuebla la caché desde disco. Debe llamarse con r.mu tomado.
  90. func (r *Reloader) reload() error {
  91. cert, err := tls.LoadX509KeyPair(r.certPath, r.keyPath)
  92. if err != nil {
  93. return err
  94. }
  95. mt, err := maxMtime(r.certPath, r.keyPath)
  96. if err != nil {
  97. return err
  98. }
  99. r.cert = &cert
  100. r.mtime = mt
  101. r.ultimoFallo = time.Time{}
  102. return nil
  103. }
  104. // maxMtime devuelve el mtime más reciente de los dos ficheros.
  105. func maxMtime(certPath, keyPath string) (time.Time, error) {
  106. sc, err := os.Stat(certPath)
  107. if err != nil {
  108. return time.Time{}, err
  109. }
  110. sk, err := os.Stat(keyPath)
  111. if err != nil {
  112. return time.Time{}, err
  113. }
  114. if sk.ModTime().After(sc.ModTime()) {
  115. return sk.ModTime(), nil
  116. }
  117. return sc.ModTime(), nil
  118. }