ftpd.go 12 KB

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