tlsutils.go 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
  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. "bytes"
  17. "crypto/tls"
  18. "crypto/x509"
  19. "encoding/pem"
  20. "errors"
  21. "fmt"
  22. "io/fs"
  23. "math/rand"
  24. "os"
  25. "path/filepath"
  26. "sync"
  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. pemCRLType = "X509 CRL"
  34. )
  35. var (
  36. certAutoReload bool
  37. pemCRLPrefix = []byte("-----BEGIN X509 CRL")
  38. )
  39. // SetCertAutoReloadMode sets if the certificate must be monitored for changes and
  40. // automatically reloaded
  41. func SetCertAutoReloadMode(val bool) {
  42. certAutoReload = val
  43. logger.Debug(logSender, "", "is certificate monitoring enabled? %t", certAutoReload)
  44. }
  45. // TLSKeyPair defines the paths and the unique identifier for a TLS key pair
  46. type TLSKeyPair struct {
  47. Cert string
  48. Key string
  49. ID string
  50. }
  51. // CertManager defines a TLS certificate manager
  52. type CertManager struct {
  53. keyPairs []TLSKeyPair
  54. configDir string
  55. logSender string
  56. sync.RWMutex
  57. caCertificates []string
  58. caRevocationLists []string
  59. monitorList []string
  60. certs map[string]*tls.Certificate
  61. certsInfo map[string]fs.FileInfo
  62. rootCAs *x509.CertPool
  63. crls []*x509.RevocationList
  64. }
  65. // Reload tries to reload certificate and CRLs
  66. func (m *CertManager) Reload() error {
  67. errCrt := m.loadCertificates()
  68. errCRLs := m.LoadCRLs()
  69. if errCrt != nil {
  70. return errCrt
  71. }
  72. return errCRLs
  73. }
  74. // LoadCertificates tries to load the configured x509 key pairs
  75. func (m *CertManager) loadCertificates() error {
  76. if len(m.keyPairs) == 0 {
  77. return errors.New("no key pairs defined")
  78. }
  79. certs := make(map[string]*tls.Certificate)
  80. for _, keyPair := range m.keyPairs {
  81. if keyPair.ID == "" {
  82. return errors.New("TLS certificate without ID")
  83. }
  84. newCert, err := tls.LoadX509KeyPair(keyPair.Cert, keyPair.Key)
  85. if err != nil {
  86. logger.Warn(m.logSender, "", "unable to load X509 key pair, cert file %q key file %q error: %v",
  87. keyPair.Cert, keyPair.Key, err)
  88. return err
  89. }
  90. if _, ok := certs[keyPair.ID]; ok {
  91. return fmt.Errorf("TLS certificate with id %q is duplicated", keyPair.ID)
  92. }
  93. logger.Debug(m.logSender, "", "TLS certificate %q successfully loaded, id %v", keyPair.Cert, keyPair.ID)
  94. certs[keyPair.ID] = &newCert
  95. if !util.Contains(m.monitorList, keyPair.Cert) {
  96. m.monitorList = append(m.monitorList, keyPair.Cert)
  97. }
  98. }
  99. m.Lock()
  100. defer m.Unlock()
  101. m.certs = certs
  102. return nil
  103. }
  104. // GetCertificateFunc returns the loaded certificate
  105. func (m *CertManager) GetCertificateFunc(certID string) func(*tls.ClientHelloInfo) (*tls.Certificate, error) {
  106. return func(_ *tls.ClientHelloInfo) (*tls.Certificate, error) {
  107. m.RLock()
  108. defer m.RUnlock()
  109. val, ok := m.certs[certID]
  110. if !ok {
  111. return nil, fmt.Errorf("no certificate for id %v", certID)
  112. }
  113. return val, nil
  114. }
  115. }
  116. // IsRevoked returns true if the specified certificate has been revoked
  117. func (m *CertManager) IsRevoked(crt *x509.Certificate, caCrt *x509.Certificate) bool {
  118. m.RLock()
  119. defer m.RUnlock()
  120. if crt == nil || caCrt == nil {
  121. logger.Warn(m.logSender, "", "unable to verify crt %v, ca crt %v", crt, caCrt)
  122. return len(m.crls) > 0
  123. }
  124. for _, crl := range m.crls {
  125. if crl.CheckSignatureFrom(caCrt) == nil {
  126. for _, rc := range crl.RevokedCertificates {
  127. if rc.SerialNumber.Cmp(crt.SerialNumber) == 0 {
  128. return true
  129. }
  130. }
  131. }
  132. }
  133. return false
  134. }
  135. // LoadCRLs tries to load certificate revocation lists from the given paths
  136. func (m *CertManager) LoadCRLs() error {
  137. if len(m.caRevocationLists) == 0 {
  138. return nil
  139. }
  140. var crls []*x509.RevocationList
  141. for _, revocationList := range m.caRevocationLists {
  142. if !util.IsFileInputValid(revocationList) {
  143. return fmt.Errorf("invalid root CA revocation list %q", revocationList)
  144. }
  145. if revocationList != "" && !filepath.IsAbs(revocationList) {
  146. revocationList = filepath.Join(m.configDir, revocationList)
  147. }
  148. crlBytes, err := os.ReadFile(revocationList)
  149. if err != nil {
  150. logger.Warn(m.logSender, "", "unable to read revocation list %q", revocationList)
  151. return err
  152. }
  153. if bytes.HasPrefix(crlBytes, pemCRLPrefix) {
  154. block, _ := pem.Decode(crlBytes)
  155. if block != nil && block.Type == pemCRLType {
  156. crlBytes = block.Bytes
  157. }
  158. }
  159. crl, err := x509.ParseRevocationList(crlBytes)
  160. if err != nil {
  161. logger.Warn(m.logSender, "", "unable to parse revocation list %q", revocationList)
  162. return err
  163. }
  164. logger.Debug(m.logSender, "", "CRL %q successfully loaded", revocationList)
  165. crls = append(crls, crl)
  166. if !util.Contains(m.monitorList, revocationList) {
  167. m.monitorList = append(m.monitorList, revocationList)
  168. }
  169. }
  170. m.Lock()
  171. defer m.Unlock()
  172. m.crls = crls
  173. return nil
  174. }
  175. // GetRootCAs returns the set of root certificate authorities that servers
  176. // use if required to verify a client certificate
  177. func (m *CertManager) GetRootCAs() *x509.CertPool {
  178. m.RLock()
  179. defer m.RUnlock()
  180. return m.rootCAs
  181. }
  182. // LoadRootCAs tries to load root CA certificate authorities from the given paths
  183. func (m *CertManager) LoadRootCAs() error {
  184. if len(m.caCertificates) == 0 {
  185. return nil
  186. }
  187. rootCAs := x509.NewCertPool()
  188. for _, rootCA := range m.caCertificates {
  189. if !util.IsFileInputValid(rootCA) {
  190. return fmt.Errorf("invalid root CA certificate %q", rootCA)
  191. }
  192. if rootCA != "" && !filepath.IsAbs(rootCA) {
  193. rootCA = filepath.Join(m.configDir, rootCA)
  194. }
  195. crt, err := os.ReadFile(rootCA)
  196. if err != nil {
  197. return err
  198. }
  199. if rootCAs.AppendCertsFromPEM(crt) {
  200. logger.Debug(m.logSender, "", "TLS certificate authority %q successfully loaded", rootCA)
  201. } else {
  202. err := fmt.Errorf("unable to load TLS certificate authority %q", rootCA)
  203. logger.Warn(m.logSender, "", "%v", err)
  204. return err
  205. }
  206. }
  207. m.Lock()
  208. defer m.Unlock()
  209. m.rootCAs = rootCAs
  210. return nil
  211. }
  212. // SetCACertificates sets the root CA authorities file paths.
  213. // This should not be changed at runtime
  214. func (m *CertManager) SetCACertificates(caCertificates []string) {
  215. m.caCertificates = util.RemoveDuplicates(caCertificates, true)
  216. }
  217. // SetCARevocationLists sets the CA revocation lists file paths.
  218. // This should not be changed at runtime
  219. func (m *CertManager) SetCARevocationLists(caRevocationLists []string) {
  220. m.caRevocationLists = util.RemoveDuplicates(caRevocationLists, true)
  221. }
  222. func (m *CertManager) monitor() {
  223. certsInfo := make(map[string]fs.FileInfo)
  224. for _, crt := range m.monitorList {
  225. info, err := os.Stat(crt)
  226. if err != nil {
  227. logger.Warn(m.logSender, "", "unable to stat certificate to monitor %q: %v", crt, err)
  228. return
  229. }
  230. certsInfo[crt] = info
  231. }
  232. m.Lock()
  233. isChanged := false
  234. for k, oldInfo := range m.certsInfo {
  235. newInfo, ok := certsInfo[k]
  236. if ok {
  237. if newInfo.Size() != oldInfo.Size() || newInfo.ModTime() != oldInfo.ModTime() {
  238. logger.Debug(m.logSender, "", "change detected for certificate %q, reload required", k)
  239. isChanged = true
  240. }
  241. }
  242. }
  243. m.certsInfo = certsInfo
  244. m.Unlock()
  245. if isChanged {
  246. m.Reload() //nolint:errcheck
  247. }
  248. }
  249. // NewCertManager creates a new certificate manager
  250. func NewCertManager(keyPairs []TLSKeyPair, configDir, logSender string) (*CertManager, error) {
  251. manager := &CertManager{
  252. keyPairs: keyPairs,
  253. certs: make(map[string]*tls.Certificate),
  254. certsInfo: make(map[string]fs.FileInfo),
  255. configDir: configDir,
  256. logSender: logSender,
  257. }
  258. err := manager.loadCertificates()
  259. if err != nil {
  260. return nil, err
  261. }
  262. if certAutoReload {
  263. randSecs := rand.Intn(59)
  264. manager.monitor()
  265. _, err := eventScheduler.AddFunc(fmt.Sprintf("@every 8h0m%ds", randSecs), manager.monitor)
  266. util.PanicOnError(err)
  267. }
  268. return manager, nil
  269. }