tlsutils.go 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304
  1. // Copyright (C) 2019-2023 Nicola Murino
  2. //
  3. // This program is free software: you can redistribute it and/or modify
  4. // it under the terms of the GNU Affero General Public License as published
  5. // by the Free Software Foundation, version 3.
  6. //
  7. // This program is distributed in the hope that it will be useful,
  8. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. // GNU Affero General Public License for more details.
  11. //
  12. // You should have received a copy of the GNU Affero General Public License
  13. // along with this program. If not, see <https://www.gnu.org/licenses/>.
  14. package common
  15. import (
  16. "crypto/tls"
  17. "crypto/x509"
  18. "crypto/x509/pkix"
  19. "errors"
  20. "fmt"
  21. "io/fs"
  22. "math/rand"
  23. "os"
  24. "path/filepath"
  25. "sync"
  26. "time"
  27. "github.com/drakkan/sftpgo/v2/internal/logger"
  28. "github.com/drakkan/sftpgo/v2/internal/util"
  29. )
  30. const (
  31. // DefaultTLSKeyPaidID defines the id to use for non-binding specific key pairs
  32. DefaultTLSKeyPaidID = "default"
  33. )
  34. var (
  35. certAutoReload bool
  36. )
  37. // SetCertAutoReloadMode sets if the certificate must be monitored for changes and
  38. // automatically reloaded
  39. func SetCertAutoReloadMode(val bool) {
  40. certAutoReload = val
  41. logger.Debug(logSender, "", "is certificate monitoring enabled? %t", certAutoReload)
  42. }
  43. // TLSKeyPair defines the paths and the unique identifier for a TLS key pair
  44. type TLSKeyPair struct {
  45. Cert string
  46. Key string
  47. ID string
  48. }
  49. // CertManager defines a TLS certificate manager
  50. type CertManager struct {
  51. keyPairs []TLSKeyPair
  52. configDir string
  53. logSender string
  54. sync.RWMutex
  55. caCertificates []string
  56. caRevocationLists []string
  57. monitorList []string
  58. certs map[string]*tls.Certificate
  59. certsInfo map[string]fs.FileInfo
  60. rootCAs *x509.CertPool
  61. crls []*pkix.CertificateList
  62. }
  63. // Reload tries to reload certificate and CRLs
  64. func (m *CertManager) Reload() error {
  65. errCrt := m.loadCertificates()
  66. errCRLs := m.LoadCRLs()
  67. if errCrt != nil {
  68. return errCrt
  69. }
  70. return errCRLs
  71. }
  72. // LoadCertificates tries to load the configured x509 key pairs
  73. func (m *CertManager) loadCertificates() error {
  74. if len(m.keyPairs) == 0 {
  75. return errors.New("no key pairs defined")
  76. }
  77. certs := make(map[string]*tls.Certificate)
  78. for _, keyPair := range m.keyPairs {
  79. if keyPair.ID == "" {
  80. return errors.New("TLS certificate without ID")
  81. }
  82. newCert, err := tls.LoadX509KeyPair(keyPair.Cert, keyPair.Key)
  83. if err != nil {
  84. logger.Warn(m.logSender, "", "unable to load X509 key pair, cert file %q key file %q error: %v",
  85. keyPair.Cert, keyPair.Key, err)
  86. return err
  87. }
  88. if _, ok := certs[keyPair.ID]; ok {
  89. return fmt.Errorf("TLS certificate with id %q is duplicated", keyPair.ID)
  90. }
  91. logger.Debug(m.logSender, "", "TLS certificate %q successfully loaded, id %v", keyPair.Cert, keyPair.ID)
  92. certs[keyPair.ID] = &newCert
  93. if !util.Contains(m.monitorList, keyPair.Cert) {
  94. m.monitorList = append(m.monitorList, keyPair.Cert)
  95. }
  96. }
  97. m.Lock()
  98. defer m.Unlock()
  99. m.certs = certs
  100. return nil
  101. }
  102. // GetCertificateFunc returns the loaded certificate
  103. func (m *CertManager) GetCertificateFunc(certID string) func(*tls.ClientHelloInfo) (*tls.Certificate, error) {
  104. return func(_ *tls.ClientHelloInfo) (*tls.Certificate, error) {
  105. m.RLock()
  106. defer m.RUnlock()
  107. val, ok := m.certs[certID]
  108. if !ok {
  109. return nil, fmt.Errorf("no certificate for id %v", certID)
  110. }
  111. return val, nil
  112. }
  113. }
  114. // IsRevoked returns true if the specified certificate has been revoked
  115. func (m *CertManager) IsRevoked(crt *x509.Certificate, caCrt *x509.Certificate) bool {
  116. m.RLock()
  117. defer m.RUnlock()
  118. if crt == nil || caCrt == nil {
  119. logger.Warn(m.logSender, "", "unable to verify crt %v, ca crt %v", crt, caCrt)
  120. return len(m.crls) > 0
  121. }
  122. for _, crl := range m.crls {
  123. if !crl.HasExpired(time.Now()) && caCrt.CheckCRLSignature(crl) == nil { //nolint:staticcheck
  124. for _, rc := range crl.TBSCertList.RevokedCertificates {
  125. if rc.SerialNumber.Cmp(crt.SerialNumber) == 0 {
  126. return true
  127. }
  128. }
  129. }
  130. }
  131. return false
  132. }
  133. // LoadCRLs tries to load certificate revocation lists from the given paths
  134. func (m *CertManager) LoadCRLs() error {
  135. if len(m.caRevocationLists) == 0 {
  136. return nil
  137. }
  138. var crls []*pkix.CertificateList
  139. for _, revocationList := range m.caRevocationLists {
  140. if !util.IsFileInputValid(revocationList) {
  141. return fmt.Errorf("invalid root CA revocation list %q", revocationList)
  142. }
  143. if revocationList != "" && !filepath.IsAbs(revocationList) {
  144. revocationList = filepath.Join(m.configDir, revocationList)
  145. }
  146. crlBytes, err := os.ReadFile(revocationList)
  147. if err != nil {
  148. logger.Warn(m.logSender, "", "unable to read revocation list %q", revocationList)
  149. return err
  150. }
  151. crl, err := x509.ParseCRL(crlBytes) //nolint:staticcheck
  152. if err != nil {
  153. logger.Warn(m.logSender, "", "unable to parse revocation list %q", revocationList)
  154. return err
  155. }
  156. logger.Debug(m.logSender, "", "CRL %q successfully loaded", revocationList)
  157. crls = append(crls, crl)
  158. if !util.Contains(m.monitorList, revocationList) {
  159. m.monitorList = append(m.monitorList, revocationList)
  160. }
  161. }
  162. m.Lock()
  163. defer m.Unlock()
  164. m.crls = crls
  165. return nil
  166. }
  167. // GetRootCAs returns the set of root certificate authorities that servers
  168. // use if required to verify a client certificate
  169. func (m *CertManager) GetRootCAs() *x509.CertPool {
  170. m.RLock()
  171. defer m.RUnlock()
  172. return m.rootCAs
  173. }
  174. // LoadRootCAs tries to load root CA certificate authorities from the given paths
  175. func (m *CertManager) LoadRootCAs() error {
  176. if len(m.caCertificates) == 0 {
  177. return nil
  178. }
  179. rootCAs := x509.NewCertPool()
  180. for _, rootCA := range m.caCertificates {
  181. if !util.IsFileInputValid(rootCA) {
  182. return fmt.Errorf("invalid root CA certificate %q", rootCA)
  183. }
  184. if rootCA != "" && !filepath.IsAbs(rootCA) {
  185. rootCA = filepath.Join(m.configDir, rootCA)
  186. }
  187. crt, err := os.ReadFile(rootCA)
  188. if err != nil {
  189. return err
  190. }
  191. if rootCAs.AppendCertsFromPEM(crt) {
  192. logger.Debug(m.logSender, "", "TLS certificate authority %q successfully loaded", rootCA)
  193. } else {
  194. err := fmt.Errorf("unable to load TLS certificate authority %q", rootCA)
  195. logger.Warn(m.logSender, "", "%v", err)
  196. return err
  197. }
  198. }
  199. m.Lock()
  200. defer m.Unlock()
  201. m.rootCAs = rootCAs
  202. return nil
  203. }
  204. // SetCACertificates sets the root CA authorities file paths.
  205. // This should not be changed at runtime
  206. func (m *CertManager) SetCACertificates(caCertificates []string) {
  207. m.caCertificates = util.RemoveDuplicates(caCertificates, true)
  208. }
  209. // SetCARevocationLists sets the CA revocation lists file paths.
  210. // This should not be changed at runtime
  211. func (m *CertManager) SetCARevocationLists(caRevocationLists []string) {
  212. m.caRevocationLists = util.RemoveDuplicates(caRevocationLists, true)
  213. }
  214. func (m *CertManager) monitor() {
  215. certsInfo := make(map[string]fs.FileInfo)
  216. for _, crt := range m.monitorList {
  217. info, err := os.Stat(crt)
  218. if err != nil {
  219. logger.Warn(m.logSender, "", "unable to stat certificate to monitor %q: %v", crt, err)
  220. return
  221. }
  222. certsInfo[crt] = info
  223. }
  224. m.Lock()
  225. isChanged := false
  226. for k, oldInfo := range m.certsInfo {
  227. newInfo, ok := certsInfo[k]
  228. if ok {
  229. if newInfo.Size() != oldInfo.Size() || newInfo.ModTime() != oldInfo.ModTime() {
  230. logger.Debug(m.logSender, "", "change detected for certificate %q, reload required", k)
  231. isChanged = true
  232. }
  233. }
  234. }
  235. m.certsInfo = certsInfo
  236. m.Unlock()
  237. if isChanged {
  238. m.Reload() //nolint:errcheck
  239. }
  240. }
  241. // NewCertManager creates a new certificate manager
  242. func NewCertManager(keyPairs []TLSKeyPair, configDir, logSender string) (*CertManager, error) {
  243. manager := &CertManager{
  244. keyPairs: keyPairs,
  245. certs: make(map[string]*tls.Certificate),
  246. certsInfo: make(map[string]fs.FileInfo),
  247. configDir: configDir,
  248. logSender: logSender,
  249. }
  250. err := manager.loadCertificates()
  251. if err != nil {
  252. return nil, err
  253. }
  254. if certAutoReload {
  255. randSecs := rand.Intn(59)
  256. manager.monitor()
  257. _, err := eventScheduler.AddFunc(fmt.Sprintf("@every 8h0m%ds", randSecs), manager.monitor)
  258. util.PanicOnError(err)
  259. }
  260. return manager, nil
  261. }