tlsutils.go 5.7 KB

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