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