tlsutils.go 8.3 KB

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