ftpd.go 10 KB

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