ftpd.go 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263
  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/common"
  9. "github.com/drakkan/sftpgo/logger"
  10. "github.com/drakkan/sftpgo/utils"
  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. ciphers []uint16
  49. }
  50. func (b *Binding) setCiphers() {
  51. b.ciphers = utils.GetTLSCiphersFromNames(b.TLSCipherSuites)
  52. if len(b.ciphers) == 0 {
  53. b.ciphers = nil
  54. }
  55. }
  56. func (b *Binding) isMutualTLSEnabled() bool {
  57. return b.ClientAuthType == 1 || b.ClientAuthType == 2
  58. }
  59. // GetAddress returns the binding address
  60. func (b *Binding) GetAddress() string {
  61. return fmt.Sprintf("%s:%d", b.Address, b.Port)
  62. }
  63. // IsValid returns true if the binding port is > 0
  64. func (b *Binding) IsValid() bool {
  65. return b.Port > 0
  66. }
  67. func (b *Binding) checkPassiveIP() error {
  68. if b.ForcePassiveIP != "" {
  69. ip := net.ParseIP(b.ForcePassiveIP)
  70. if ip == nil {
  71. return fmt.Errorf("the provided passive IP %#v is not valid", b.ForcePassiveIP)
  72. }
  73. ip = ip.To4()
  74. if ip == nil {
  75. return fmt.Errorf("the provided passive IP %#v is not a valid IPv4 address", b.ForcePassiveIP)
  76. }
  77. b.ForcePassiveIP = ip.String()
  78. }
  79. return nil
  80. }
  81. // HasProxy returns true if the proxy protocol is active for this binding
  82. func (b *Binding) HasProxy() bool {
  83. return b.ApplyProxyConfig && common.Config.ProxyProtocol > 0
  84. }
  85. // GetTLSDescription returns the TLS mode as string
  86. func (b *Binding) GetTLSDescription() string {
  87. if certMgr == nil {
  88. return "Disabled"
  89. }
  90. switch b.TLSMode {
  91. case 1:
  92. return "Explicit required"
  93. case 2:
  94. return "Implicit"
  95. }
  96. return "Plain and explicit"
  97. }
  98. // PortRange defines a port range
  99. type PortRange struct {
  100. // Range start
  101. Start int `json:"start" mapstructure:"start"`
  102. // Range end
  103. End int `json:"end" mapstructure:"end"`
  104. }
  105. // ServiceStatus defines the service status
  106. type ServiceStatus struct {
  107. IsActive bool `json:"is_active"`
  108. Bindings []Binding `json:"bindings"`
  109. PassivePortRange PortRange `json:"passive_port_range"`
  110. }
  111. // Configuration defines the configuration for the ftp server
  112. type Configuration struct {
  113. // Addresses and ports to bind to
  114. Bindings []Binding `json:"bindings" mapstructure:"bindings"`
  115. // Deprecated: please use Bindings
  116. BindPort int `json:"bind_port" mapstructure:"bind_port"`
  117. // Deprecated: please use Bindings
  118. BindAddress string `json:"bind_address" mapstructure:"bind_address"`
  119. // Deprecated: please use Bindings
  120. ForcePassiveIP string `json:"force_passive_ip" mapstructure:"force_passive_ip"`
  121. // Greeting banner displayed when a connection first comes in
  122. Banner string `json:"banner" mapstructure:"banner"`
  123. // the contents of the specified file, if any, are diplayed when someone connects to the server.
  124. // If set, it overrides the banner string provided by the banner option
  125. BannerFile string `json:"banner_file" mapstructure:"banner_file"`
  126. // If files containing a certificate and matching private key for the server are provided the server will accept
  127. // both plain FTP an explicit FTP over TLS.
  128. // Certificate and key files can be reloaded on demand sending a "SIGHUP" signal on Unix based systems and a
  129. // "paramchange" request to the running service on Windows.
  130. CertificateFile string `json:"certificate_file" mapstructure:"certificate_file"`
  131. CertificateKeyFile string `json:"certificate_key_file" mapstructure:"certificate_key_file"`
  132. // CACertificates defines the set of root certificate authorities to be used to verify client certificates.
  133. CACertificates []string `json:"ca_certificates" mapstructure:"ca_certificates"`
  134. // CARevocationLists defines a set a revocation lists, one for each root CA, to be used to check
  135. // if a client certificate has been revoked
  136. CARevocationLists []string `json:"ca_revocation_lists" mapstructure:"ca_revocation_lists"`
  137. // Do not impose the port 20 for active data transfer. Enabling this option allows to run SFTPGo with less privilege
  138. ActiveTransfersPortNon20 bool `json:"active_transfers_port_non_20" mapstructure:"active_transfers_port_non_20"`
  139. // Set to true to disable active FTP
  140. DisableActiveMode bool `json:"disable_active_mode" mapstructure:"disable_active_mode"`
  141. // Set to true to enable the FTP SITE command.
  142. // We support chmod and symlink if SITE support is enabled
  143. EnableSite bool `json:"enable_site" mapstructure:"enable_site"`
  144. // Set to 1 to enable FTP commands that allow to calculate the hash value of files.
  145. // These FTP commands will be enabled: HASH, XCRC, MD5/XMD5, XSHA/XSHA1, XSHA256, XSHA512.
  146. // Please keep in mind that to calculate the hash we need to read the whole file, for
  147. // remote backends this means downloading the file, for the encrypted backend this means
  148. // decrypting the file
  149. HASHSupport int `json:"hash_support" mapstructure:"hash_support"`
  150. // Set to 1 to enable support for the non standard "COMB" FTP command.
  151. // Combine is only supported for local filesystem, for cloud backends it has
  152. // no advantage as it will download the partial files and will upload the
  153. // combined one. Cloud backends natively support multipart uploads.
  154. CombineSupport int `json:"combine_support" mapstructure:"combine_support"`
  155. // Deprecated: please use Bindings
  156. TLSMode int `json:"tls_mode" mapstructure:"tls_mode"`
  157. // Port Range for data connections. Random if not specified
  158. PassivePortRange PortRange `json:"passive_port_range" mapstructure:"passive_port_range"`
  159. }
  160. // ShouldBind returns true if there is at least a valid binding
  161. func (c *Configuration) ShouldBind() bool {
  162. for _, binding := range c.Bindings {
  163. if binding.IsValid() {
  164. return true
  165. }
  166. }
  167. return false
  168. }
  169. // Initialize configures and starts the FTP server
  170. func (c *Configuration) Initialize(configDir string) error {
  171. logger.Debug(logSender, "", "initializing FTP server with config %+v", *c)
  172. if !c.ShouldBind() {
  173. return common.ErrNoBinding
  174. }
  175. certificateFile := getConfigPath(c.CertificateFile, configDir)
  176. certificateKeyFile := getConfigPath(c.CertificateKeyFile, configDir)
  177. if certificateFile != "" && certificateKeyFile != "" {
  178. mgr, err := common.NewCertManager(certificateFile, certificateKeyFile, configDir, logSender)
  179. if err != nil {
  180. return err
  181. }
  182. mgr.SetCACertificates(c.CACertificates)
  183. if err := mgr.LoadRootCAs(); err != nil {
  184. return err
  185. }
  186. mgr.SetCARevocationLists(c.CARevocationLists)
  187. if err := mgr.LoadCRLs(); err != nil {
  188. return err
  189. }
  190. certMgr = mgr
  191. }
  192. serviceStatus = ServiceStatus{
  193. Bindings: nil,
  194. PassivePortRange: c.PassivePortRange,
  195. }
  196. exitChannel := make(chan error, 1)
  197. for idx, binding := range c.Bindings {
  198. if !binding.IsValid() {
  199. continue
  200. }
  201. server := NewServer(c, configDir, binding, idx)
  202. go func(s *Server) {
  203. ftpServer := ftpserver.NewFtpServer(s)
  204. logger.Info(logSender, "", "starting FTP serving, binding: %v", s.binding.GetAddress())
  205. utils.CheckTCP4Port(s.binding.Port)
  206. exitChannel <- ftpServer.ListenAndServe()
  207. }(server)
  208. serviceStatus.Bindings = append(serviceStatus.Bindings, binding)
  209. }
  210. serviceStatus.IsActive = true
  211. return <-exitChannel
  212. }
  213. // ReloadCertificateMgr reloads the certificate manager
  214. func ReloadCertificateMgr() error {
  215. if certMgr != nil {
  216. return certMgr.Reload()
  217. }
  218. return nil
  219. }
  220. // GetStatus returns the server status
  221. func GetStatus() ServiceStatus {
  222. return serviceStatus
  223. }
  224. func getConfigPath(name, configDir string) string {
  225. if !utils.IsFileInputValid(name) {
  226. return ""
  227. }
  228. if name != "" && !filepath.IsAbs(name) {
  229. return filepath.Join(configDir, name)
  230. }
  231. return name
  232. }