tlsutils.go 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243
  1. // Copyright (C) 2019-2022 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. "os"
  22. "path/filepath"
  23. "sync"
  24. "time"
  25. "github.com/drakkan/sftpgo/v2/logger"
  26. "github.com/drakkan/sftpgo/v2/util"
  27. )
  28. const (
  29. // DefaultTLSKeyPaidID defines the id to use for non-binding specific key pairs
  30. DefaultTLSKeyPaidID = "default"
  31. )
  32. // TLSKeyPair defines the paths and the unique identifier for a TLS key pair
  33. type TLSKeyPair struct {
  34. Cert string
  35. Key string
  36. ID string
  37. }
  38. // CertManager defines a TLS certificate manager
  39. type CertManager struct {
  40. keyPairs []TLSKeyPair
  41. configDir string
  42. logSender string
  43. sync.RWMutex
  44. caCertificates []string
  45. caRevocationLists []string
  46. certs map[string]*tls.Certificate
  47. rootCAs *x509.CertPool
  48. crls []*pkix.CertificateList
  49. }
  50. // Reload tries to reload certificate and CRLs
  51. func (m *CertManager) Reload() error {
  52. errCrt := m.loadCertificates()
  53. errCRLs := m.LoadCRLs()
  54. if errCrt != nil {
  55. return errCrt
  56. }
  57. return errCRLs
  58. }
  59. // LoadCertificates tries to load the configured x509 key pairs
  60. func (m *CertManager) loadCertificates() error {
  61. if len(m.keyPairs) == 0 {
  62. return errors.New("no key pairs defined")
  63. }
  64. certs := make(map[string]*tls.Certificate)
  65. for _, keyPair := range m.keyPairs {
  66. if keyPair.ID == "" {
  67. return errors.New("TLS certificate without ID")
  68. }
  69. newCert, err := tls.LoadX509KeyPair(keyPair.Cert, keyPair.Key)
  70. if err != nil {
  71. logger.Warn(m.logSender, "", "unable to load X509 key pair, cert file %#v key file %#v error: %v",
  72. keyPair.Cert, keyPair.Key, err)
  73. return err
  74. }
  75. if _, ok := certs[keyPair.ID]; ok {
  76. return fmt.Errorf("TLS certificate with id %#v is duplicated", keyPair.ID)
  77. }
  78. logger.Debug(m.logSender, "", "TLS certificate %#v successfully loaded, id %v", keyPair.Cert, keyPair.ID)
  79. certs[keyPair.ID] = &newCert
  80. }
  81. m.Lock()
  82. defer m.Unlock()
  83. m.certs = certs
  84. return nil
  85. }
  86. // GetCertificateFunc returns the loaded certificate
  87. func (m *CertManager) GetCertificateFunc(certID string) func(*tls.ClientHelloInfo) (*tls.Certificate, error) {
  88. return func(clientHello *tls.ClientHelloInfo) (*tls.Certificate, error) {
  89. m.RLock()
  90. defer m.RUnlock()
  91. val, ok := m.certs[certID]
  92. if !ok {
  93. return nil, fmt.Errorf("no certificate for id %v", certID)
  94. }
  95. return val, nil
  96. }
  97. }
  98. // IsRevoked returns true if the specified certificate has been revoked
  99. func (m *CertManager) IsRevoked(crt *x509.Certificate, caCrt *x509.Certificate) bool {
  100. m.RLock()
  101. defer m.RUnlock()
  102. if crt == nil || caCrt == nil {
  103. logger.Warn(m.logSender, "", "unable to verify crt %v ca crt %v", crt, caCrt)
  104. return len(m.crls) > 0
  105. }
  106. for _, crl := range m.crls {
  107. if !crl.HasExpired(time.Now()) && caCrt.CheckCRLSignature(crl) == nil {
  108. for _, rc := range crl.TBSCertList.RevokedCertificates {
  109. if rc.SerialNumber.Cmp(crt.SerialNumber) == 0 {
  110. return true
  111. }
  112. }
  113. }
  114. }
  115. return false
  116. }
  117. // LoadCRLs tries to load certificate revocation lists from the given paths
  118. func (m *CertManager) LoadCRLs() error {
  119. if len(m.caRevocationLists) == 0 {
  120. return nil
  121. }
  122. var crls []*pkix.CertificateList
  123. for _, revocationList := range m.caRevocationLists {
  124. if !util.IsFileInputValid(revocationList) {
  125. return fmt.Errorf("invalid root CA revocation list %#v", revocationList)
  126. }
  127. if revocationList != "" && !filepath.IsAbs(revocationList) {
  128. revocationList = filepath.Join(m.configDir, revocationList)
  129. }
  130. crlBytes, err := os.ReadFile(revocationList)
  131. if err != nil {
  132. logger.Warn(m.logSender, "unable to read revocation list %#v", revocationList)
  133. return err
  134. }
  135. crl, err := x509.ParseCRL(crlBytes)
  136. if err != nil {
  137. logger.Warn(m.logSender, "unable to parse revocation list %#v", revocationList)
  138. return err
  139. }
  140. logger.Debug(m.logSender, "", "CRL %#v successfully loaded", revocationList)
  141. crls = append(crls, crl)
  142. }
  143. m.Lock()
  144. defer m.Unlock()
  145. m.crls = crls
  146. return nil
  147. }
  148. // GetRootCAs returns the set of root certificate authorities that servers
  149. // use if required to verify a client certificate
  150. func (m *CertManager) GetRootCAs() *x509.CertPool {
  151. m.RLock()
  152. defer m.RUnlock()
  153. return m.rootCAs
  154. }
  155. // LoadRootCAs tries to load root CA certificate authorities from the given paths
  156. func (m *CertManager) LoadRootCAs() error {
  157. if len(m.caCertificates) == 0 {
  158. return nil
  159. }
  160. rootCAs := x509.NewCertPool()
  161. for _, rootCA := range m.caCertificates {
  162. if !util.IsFileInputValid(rootCA) {
  163. return fmt.Errorf("invalid root CA certificate %#v", rootCA)
  164. }
  165. if rootCA != "" && !filepath.IsAbs(rootCA) {
  166. rootCA = filepath.Join(m.configDir, rootCA)
  167. }
  168. crt, err := os.ReadFile(rootCA)
  169. if err != nil {
  170. return err
  171. }
  172. if rootCAs.AppendCertsFromPEM(crt) {
  173. logger.Debug(m.logSender, "", "TLS certificate authority %#v successfully loaded", rootCA)
  174. } else {
  175. err := fmt.Errorf("unable to load TLS certificate authority %#v", rootCA)
  176. logger.Warn(m.logSender, "", "%v", err)
  177. return err
  178. }
  179. }
  180. m.Lock()
  181. defer m.Unlock()
  182. m.rootCAs = rootCAs
  183. return nil
  184. }
  185. // SetCACertificates sets the root CA authorities file paths.
  186. // This should not be changed at runtime
  187. func (m *CertManager) SetCACertificates(caCertificates []string) {
  188. m.caCertificates = util.RemoveDuplicates(caCertificates, true)
  189. }
  190. // SetCARevocationLists sets the CA revocation lists file paths.
  191. // This should not be changed at runtime
  192. func (m *CertManager) SetCARevocationLists(caRevocationLists []string) {
  193. m.caRevocationLists = util.RemoveDuplicates(caRevocationLists, true)
  194. }
  195. // NewCertManager creates a new certificate manager
  196. func NewCertManager(keyPairs []TLSKeyPair, configDir, logSender string) (*CertManager, error) {
  197. manager := &CertManager{
  198. keyPairs: keyPairs,
  199. certs: make(map[string]*tls.Certificate),
  200. configDir: configDir,
  201. logSender: logSender,
  202. }
  203. err := manager.loadCertificates()
  204. if err != nil {
  205. return nil, err
  206. }
  207. return manager, nil
  208. }