ftpd.go 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259
  1. // Package ftpd implements the FTP protocol
  2. package ftpd
  3. import (
  4. "fmt"
  5. "net"
  6. "path/filepath"
  7. ftpserver "github.com/fclairamb/ftpserverlib"
  8. "github.com/drakkan/sftpgo/v2/common"
  9. "github.com/drakkan/sftpgo/v2/logger"
  10. "github.com/drakkan/sftpgo/v2/util"
  11. )
  12. const (
  13. logSender = "ftpd"
  14. )
  15. var (
  16. certMgr *common.CertManager
  17. serviceStatus ServiceStatus
  18. )
  19. // Binding defines the configuration for a network listener
  20. type Binding struct {
  21. // The address to listen on. A blank value means listen on all available network interfaces.
  22. Address string `json:"address" mapstructure:"address"`
  23. // The port used for serving requests
  24. Port int `json:"port" mapstructure:"port"`
  25. // Apply the proxy configuration, if any, for this binding
  26. ApplyProxyConfig bool `json:"apply_proxy_config" mapstructure:"apply_proxy_config"`
  27. // Set to 1 to require TLS for both data and control connection.
  28. // Set to 2 to enable implicit TLS
  29. TLSMode int `json:"tls_mode" mapstructure:"tls_mode"`
  30. // External IP address to expose for passive connections.
  31. ForcePassiveIP string `json:"force_passive_ip" mapstructure:"force_passive_ip"`
  32. // Set to 1 to require client certificate authentication.
  33. // Set to 2 to require a client certificate and verfify it if given. In this mode
  34. // the client is allowed not to send a certificate.
  35. // You need to define at least a certificate authority for this to work
  36. ClientAuthType int `json:"client_auth_type" mapstructure:"client_auth_type"`
  37. // TLSCipherSuites is a list of supported cipher suites for TLS version 1.2.
  38. // If CipherSuites is nil/empty, a default list of secure cipher suites
  39. // is used, with a preference order based on hardware performance.
  40. // Note that TLS 1.3 ciphersuites are not configurable.
  41. // The supported ciphersuites names are defined here:
  42. //
  43. // https://github.com/golang/go/blob/master/src/crypto/tls/cipher_suites.go#L52
  44. //
  45. // any invalid name will be silently ignored.
  46. // The order matters, the ciphers listed first will be the preferred ones.
  47. TLSCipherSuites []string `json:"tls_cipher_suites" mapstructure:"tls_cipher_suites"`
  48. // Debug enables the FTP debug mode. In debug mode, every FTP command will be logged
  49. Debug bool `json:"debug" mapstructure:"debug"`
  50. ciphers []uint16
  51. }
  52. func (b *Binding) setCiphers() {
  53. b.ciphers = util.GetTLSCiphersFromNames(b.TLSCipherSuites)
  54. if len(b.ciphers) == 0 {
  55. b.ciphers = nil
  56. }
  57. }
  58. func (b *Binding) isMutualTLSEnabled() bool {
  59. return b.ClientAuthType == 1 || b.ClientAuthType == 2
  60. }
  61. // GetAddress returns the binding address
  62. func (b *Binding) GetAddress() string {
  63. return fmt.Sprintf("%s:%d", b.Address, b.Port)
  64. }
  65. // IsValid returns true if the binding port is > 0
  66. func (b *Binding) IsValid() bool {
  67. return b.Port > 0
  68. }
  69. func (b *Binding) checkPassiveIP() error {
  70. if b.ForcePassiveIP != "" {
  71. ip := net.ParseIP(b.ForcePassiveIP)
  72. if ip == nil {
  73. return fmt.Errorf("the provided passive IP %#v is not valid", b.ForcePassiveIP)
  74. }
  75. ip = ip.To4()
  76. if ip == nil {
  77. return fmt.Errorf("the provided passive IP %#v is not a valid IPv4 address", b.ForcePassiveIP)
  78. }
  79. b.ForcePassiveIP = ip.String()
  80. }
  81. return nil
  82. }
  83. // HasProxy returns true if the proxy protocol is active for this binding
  84. func (b *Binding) HasProxy() bool {
  85. return b.ApplyProxyConfig && common.Config.ProxyProtocol > 0
  86. }
  87. // GetTLSDescription returns the TLS mode as string
  88. func (b *Binding) GetTLSDescription() string {
  89. if certMgr == nil {
  90. return "Disabled"
  91. }
  92. switch b.TLSMode {
  93. case 1:
  94. return "Explicit required"
  95. case 2:
  96. return "Implicit"
  97. }
  98. return "Plain and explicit"
  99. }
  100. // PortRange defines a port range
  101. type PortRange struct {
  102. // Range start
  103. Start int `json:"start" mapstructure:"start"`
  104. // Range end
  105. End int `json:"end" mapstructure:"end"`
  106. }
  107. // ServiceStatus defines the service status
  108. type ServiceStatus struct {
  109. IsActive bool `json:"is_active"`
  110. Bindings []Binding `json:"bindings"`
  111. PassivePortRange PortRange `json:"passive_port_range"`
  112. }
  113. // Configuration defines the configuration for the ftp server
  114. type Configuration struct {
  115. // Addresses and ports to bind to
  116. Bindings []Binding `json:"bindings" mapstructure:"bindings"`
  117. // Greeting banner displayed when a connection first comes in
  118. Banner string `json:"banner" mapstructure:"banner"`
  119. // the contents of the specified file, if any, are diplayed when someone connects to the server.
  120. // If set, it overrides the banner string provided by the banner option
  121. BannerFile string `json:"banner_file" mapstructure:"banner_file"`
  122. // If files containing a certificate and matching private key for the server are provided the server will accept
  123. // both plain FTP an explicit FTP over TLS.
  124. // Certificate and key files can be reloaded on demand sending a "SIGHUP" signal on Unix based systems and a
  125. // "paramchange" request to the running service on Windows.
  126. CertificateFile string `json:"certificate_file" mapstructure:"certificate_file"`
  127. CertificateKeyFile string `json:"certificate_key_file" mapstructure:"certificate_key_file"`
  128. // CACertificates defines the set of root certificate authorities to be used to verify client certificates.
  129. CACertificates []string `json:"ca_certificates" mapstructure:"ca_certificates"`
  130. // CARevocationLists defines a set a revocation lists, one for each root CA, to be used to check
  131. // if a client certificate has been revoked
  132. CARevocationLists []string `json:"ca_revocation_lists" mapstructure:"ca_revocation_lists"`
  133. // Do not impose the port 20 for active data transfer. Enabling this option allows to run SFTPGo with less privilege
  134. ActiveTransfersPortNon20 bool `json:"active_transfers_port_non_20" mapstructure:"active_transfers_port_non_20"`
  135. // Set to true to disable active FTP
  136. DisableActiveMode bool `json:"disable_active_mode" mapstructure:"disable_active_mode"`
  137. // Set to true to enable the FTP SITE command.
  138. // We support chmod and symlink if SITE support is enabled
  139. EnableSite bool `json:"enable_site" mapstructure:"enable_site"`
  140. // Set to 1 to enable FTP commands that allow to calculate the hash value of files.
  141. // These FTP commands will be enabled: HASH, XCRC, MD5/XMD5, XSHA/XSHA1, XSHA256, XSHA512.
  142. // Please keep in mind that to calculate the hash we need to read the whole file, for
  143. // remote backends this means downloading the file, for the encrypted backend this means
  144. // decrypting the file
  145. HASHSupport int `json:"hash_support" mapstructure:"hash_support"`
  146. // Set to 1 to enable support for the non standard "COMB" FTP command.
  147. // Combine is only supported for local filesystem, for cloud backends it has
  148. // no advantage as it will download the partial files and will upload the
  149. // combined one. Cloud backends natively support multipart uploads.
  150. CombineSupport int `json:"combine_support" mapstructure:"combine_support"`
  151. // Port Range for data connections. Random if not specified
  152. PassivePortRange PortRange `json:"passive_port_range" mapstructure:"passive_port_range"`
  153. }
  154. // ShouldBind returns true if there is at least a valid binding
  155. func (c *Configuration) ShouldBind() bool {
  156. for _, binding := range c.Bindings {
  157. if binding.IsValid() {
  158. return true
  159. }
  160. }
  161. return false
  162. }
  163. // Initialize configures and starts the FTP server
  164. func (c *Configuration) Initialize(configDir string) error {
  165. logger.Debug(logSender, "", "initializing FTP server with config %+v", *c)
  166. if !c.ShouldBind() {
  167. return common.ErrNoBinding
  168. }
  169. certificateFile := getConfigPath(c.CertificateFile, configDir)
  170. certificateKeyFile := getConfigPath(c.CertificateKeyFile, configDir)
  171. if certificateFile != "" && certificateKeyFile != "" {
  172. mgr, err := common.NewCertManager(certificateFile, certificateKeyFile, configDir, logSender)
  173. if err != nil {
  174. return err
  175. }
  176. mgr.SetCACertificates(c.CACertificates)
  177. if err := mgr.LoadRootCAs(); err != nil {
  178. return err
  179. }
  180. mgr.SetCARevocationLists(c.CARevocationLists)
  181. if err := mgr.LoadCRLs(); err != nil {
  182. return err
  183. }
  184. certMgr = mgr
  185. }
  186. serviceStatus = ServiceStatus{
  187. Bindings: nil,
  188. PassivePortRange: c.PassivePortRange,
  189. }
  190. exitChannel := make(chan error, 1)
  191. for idx, binding := range c.Bindings {
  192. if !binding.IsValid() {
  193. continue
  194. }
  195. server := NewServer(c, configDir, binding, idx)
  196. go func(s *Server) {
  197. ftpLogger := logger.LeveledLogger{Sender: "ftpserverlib"}
  198. ftpServer := ftpserver.NewFtpServer(s)
  199. ftpServer.Logger = ftpLogger.With("server_id", fmt.Sprintf("FTP_%v", s.ID))
  200. logger.Info(logSender, "", "starting FTP serving, binding: %v", s.binding.GetAddress())
  201. util.CheckTCP4Port(s.binding.Port)
  202. exitChannel <- ftpServer.ListenAndServe()
  203. }(server)
  204. serviceStatus.Bindings = append(serviceStatus.Bindings, binding)
  205. }
  206. serviceStatus.IsActive = true
  207. return <-exitChannel
  208. }
  209. // ReloadCertificateMgr reloads the certificate manager
  210. func ReloadCertificateMgr() error {
  211. if certMgr != nil {
  212. return certMgr.Reload()
  213. }
  214. return nil
  215. }
  216. // GetStatus returns the server status
  217. func GetStatus() ServiceStatus {
  218. return serviceStatus
  219. }
  220. func getConfigPath(name, configDir string) string {
  221. if !util.IsFileInputValid(name) {
  222. return ""
  223. }
  224. if name != "" && !filepath.IsAbs(name) {
  225. return filepath.Join(configDir, name)
  226. }
  227. return name
  228. }