tlsutils.go 8.1 KB

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