ftpd.go 14 KB

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