ftpd.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465
  1. // Copyright (C) 2019-2023 Nicola Murino
  2. //
  3. // This program is free software: you can redistribute it and/or modify
  4. // it under the terms of the GNU Affero General Public License as published
  5. // by the Free Software Foundation, version 3.
  6. //
  7. // This program is distributed in the hope that it will be useful,
  8. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. // GNU Affero General Public License for more details.
  11. //
  12. // You should have received a copy of the GNU Affero General Public License
  13. // along with this program. If not, see <https://www.gnu.org/licenses/>.
  14. // Package ftpd implements the FTP protocol
  15. package ftpd
  16. import (
  17. "context"
  18. "errors"
  19. "fmt"
  20. "net"
  21. "os"
  22. "path/filepath"
  23. "strings"
  24. "time"
  25. ftpserver "github.com/fclairamb/ftpserverlib"
  26. "github.com/drakkan/sftpgo/v2/internal/common"
  27. "github.com/drakkan/sftpgo/v2/internal/dataprovider"
  28. "github.com/drakkan/sftpgo/v2/internal/logger"
  29. "github.com/drakkan/sftpgo/v2/internal/util"
  30. )
  31. const (
  32. logSender = "ftpd"
  33. )
  34. var (
  35. certMgr *common.CertManager
  36. serviceStatus ServiceStatus
  37. )
  38. // PassiveIPOverride defines an exception for the configured passive IP
  39. type PassiveIPOverride struct {
  40. Networks []string `json:"networks" mapstructure:"networks"`
  41. // if empty the local address will be returned
  42. IP string `json:"ip" mapstructure:"ip"`
  43. parsedNetworks []func(net.IP) bool
  44. }
  45. // GetNetworksAsString returns the configured networks as string
  46. func (p *PassiveIPOverride) GetNetworksAsString() string {
  47. return strings.Join(p.Networks, ", ")
  48. }
  49. // Binding defines the configuration for a network listener
  50. type Binding struct {
  51. // The address to listen on. A blank value means listen on all available network interfaces.
  52. Address string `json:"address" mapstructure:"address"`
  53. // The port used for serving requests
  54. Port int `json:"port" mapstructure:"port"`
  55. // Apply the proxy configuration, if any, for this binding
  56. ApplyProxyConfig bool `json:"apply_proxy_config" mapstructure:"apply_proxy_config"`
  57. // Set to 1 to require TLS for both data and control connection.
  58. // Set to 2 to enable implicit TLS
  59. TLSMode int `json:"tls_mode" mapstructure:"tls_mode"`
  60. // 0 disabled, 1 required
  61. TLSSessionReuse int `json:"tls_session_reuse" mapstructure:"tls_session_reuse"`
  62. // Certificate and matching private key for this specific binding, if empty the global
  63. // ones will be used, if any
  64. CertificateFile string `json:"certificate_file" mapstructure:"certificate_file"`
  65. CertificateKeyFile string `json:"certificate_key_file" mapstructure:"certificate_key_file"`
  66. // Defines the minimum TLS version. 13 means TLS 1.3, default is TLS 1.2
  67. MinTLSVersion int `json:"min_tls_version" mapstructure:"min_tls_version"`
  68. // External IP address for passive connections.
  69. ForcePassiveIP string `json:"force_passive_ip" mapstructure:"force_passive_ip"`
  70. // PassiveIPOverrides allows to define different IP addresses for passive connections
  71. // based on the client IP address
  72. PassiveIPOverrides []PassiveIPOverride `json:"passive_ip_overrides" mapstructure:"passive_ip_overrides"`
  73. // Hostname for passive connections. This hostname will be resolved each time a passive
  74. // connection is requested and this can, depending on the DNS configuration, take a noticeable
  75. // amount of time. Enable this setting only if you have a dynamic IP address
  76. PassiveHost string `json:"passive_host" mapstructure:"passive_host"`
  77. // Set to 1 to require client certificate authentication.
  78. // Set to 2 to require a client certificate and verfify it if given. In this mode
  79. // the client is allowed not to send a certificate.
  80. // You need to define at least a certificate authority for this to work
  81. ClientAuthType int `json:"client_auth_type" mapstructure:"client_auth_type"`
  82. // TLSCipherSuites is a list of supported cipher suites for TLS version 1.2.
  83. // If CipherSuites is nil/empty, a default list of secure cipher suites
  84. // is used, with a preference order based on hardware performance.
  85. // Note that TLS 1.3 ciphersuites are not configurable.
  86. // The supported ciphersuites names are defined here:
  87. //
  88. // https://github.com/golang/go/blob/master/src/crypto/tls/cipher_suites.go#L53
  89. //
  90. // any invalid name will be silently ignored.
  91. // The order matters, the ciphers listed first will be the preferred ones.
  92. TLSCipherSuites []string `json:"tls_cipher_suites" mapstructure:"tls_cipher_suites"`
  93. // PassiveConnectionsSecurity defines the security checks for passive data connections.
  94. // Supported values:
  95. // - 0 require matching peer IP addresses of control and data connection. This is the default
  96. // - 1 disable any checks
  97. PassiveConnectionsSecurity int `json:"passive_connections_security" mapstructure:"passive_connections_security"`
  98. // ActiveConnectionsSecurity defines the security checks for active data connections.
  99. // The supported values are the same as described for PassiveConnectionsSecurity.
  100. // Please note that disabling the security checks you will make the FTP service vulnerable to bounce attacks
  101. // on active data connections, so change the default value only if you are on a trusted/internal network
  102. ActiveConnectionsSecurity int `json:"active_connections_security" mapstructure:"active_connections_security"`
  103. // Debug enables the FTP debug mode. In debug mode, every FTP command will be logged
  104. Debug bool `json:"debug" mapstructure:"debug"`
  105. ciphers []uint16
  106. }
  107. func (b *Binding) setCiphers() {
  108. b.ciphers = util.GetTLSCiphersFromNames(b.TLSCipherSuites)
  109. if len(b.ciphers) == 0 {
  110. b.ciphers = nil
  111. }
  112. }
  113. func (b *Binding) isMutualTLSEnabled() bool {
  114. return b.ClientAuthType == 1 || b.ClientAuthType == 2
  115. }
  116. // GetAddress returns the binding address
  117. func (b *Binding) GetAddress() string {
  118. return fmt.Sprintf("%s:%d", b.Address, b.Port)
  119. }
  120. // IsValid returns true if the binding port is > 0
  121. func (b *Binding) IsValid() bool {
  122. return b.Port > 0
  123. }
  124. func (b *Binding) isTLSModeValid() bool {
  125. return b.TLSMode >= 0 && b.TLSMode <= 2
  126. }
  127. func (b *Binding) isTLSSessionReuseValid() bool {
  128. return b.TLSSessionReuse >= 0 && b.TLSSessionReuse <= 1
  129. }
  130. func (b *Binding) checkSecuritySettings() error {
  131. if b.PassiveConnectionsSecurity < 0 || b.PassiveConnectionsSecurity > 1 {
  132. return fmt.Errorf("invalid passive_connections_security: %v", b.PassiveConnectionsSecurity)
  133. }
  134. if b.ActiveConnectionsSecurity < 0 || b.ActiveConnectionsSecurity > 1 {
  135. return fmt.Errorf("invalid active_connections_security: %v", b.ActiveConnectionsSecurity)
  136. }
  137. return nil
  138. }
  139. func (b *Binding) checkPassiveIP() error {
  140. if b.ForcePassiveIP != "" {
  141. ip, err := parsePassiveIP(b.ForcePassiveIP)
  142. if err != nil {
  143. return err
  144. }
  145. b.ForcePassiveIP = ip
  146. }
  147. for idx, passiveOverride := range b.PassiveIPOverrides {
  148. var ip string
  149. if passiveOverride.IP != "" {
  150. var err error
  151. ip, err = parsePassiveIP(passiveOverride.IP)
  152. if err != nil {
  153. return err
  154. }
  155. }
  156. if len(passiveOverride.Networks) == 0 {
  157. return errors.New("passive IP networks override cannot be empty")
  158. }
  159. checkFuncs, err := util.ParseAllowedIPAndRanges(passiveOverride.Networks)
  160. if err != nil {
  161. return fmt.Errorf("invalid passive IP networks override %+v: %w", passiveOverride.Networks, err)
  162. }
  163. b.PassiveIPOverrides[idx].IP = ip
  164. b.PassiveIPOverrides[idx].parsedNetworks = checkFuncs
  165. }
  166. return nil
  167. }
  168. func (b *Binding) getPassiveIP(cc ftpserver.ClientContext) (string, error) {
  169. if b.ForcePassiveIP != "" {
  170. return b.ForcePassiveIP, nil
  171. }
  172. if b.PassiveHost != "" {
  173. ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
  174. defer cancel()
  175. addrs, err := net.DefaultResolver.LookupIP(ctx, "ip4", b.PassiveHost)
  176. if err != nil {
  177. logger.Error(logSender, "", "unable to resolve hostname %q: %v", b.PassiveHost, err)
  178. return "", fmt.Errorf("unable to resolve hostname %q: %w", b.PassiveHost, err)
  179. }
  180. if len(addrs) > 0 {
  181. return addrs[0].String(), nil
  182. }
  183. }
  184. return strings.Split(cc.LocalAddr().String(), ":")[0], nil
  185. }
  186. func (b *Binding) passiveIPResolver(cc ftpserver.ClientContext) (string, error) {
  187. if len(b.PassiveIPOverrides) > 0 {
  188. clientIP := net.ParseIP(util.GetIPFromRemoteAddress(cc.RemoteAddr().String()))
  189. if clientIP != nil {
  190. for _, override := range b.PassiveIPOverrides {
  191. for _, fn := range override.parsedNetworks {
  192. if fn(clientIP) {
  193. if override.IP == "" {
  194. return strings.Split(cc.LocalAddr().String(), ":")[0], nil
  195. }
  196. return override.IP, nil
  197. }
  198. }
  199. }
  200. }
  201. }
  202. return b.getPassiveIP(cc)
  203. }
  204. // HasProxy returns true if the proxy protocol is active for this binding
  205. func (b *Binding) HasProxy() bool {
  206. return b.ApplyProxyConfig && common.Config.ProxyProtocol > 0
  207. }
  208. // GetTLSDescription returns the TLS mode as string
  209. func (b *Binding) GetTLSDescription() string {
  210. if certMgr == nil {
  211. return "Disabled"
  212. }
  213. switch b.TLSMode {
  214. case 1:
  215. return "Explicit required"
  216. case 2:
  217. return "Implicit"
  218. }
  219. if certMgr.HasCertificate(common.DefaultTLSKeyPaidID) || certMgr.HasCertificate(b.GetAddress()) {
  220. return "Plain and explicit"
  221. }
  222. return "Disabled"
  223. }
  224. // PortRange defines a port range
  225. type PortRange struct {
  226. // Range start
  227. Start int `json:"start" mapstructure:"start"`
  228. // Range end
  229. End int `json:"end" mapstructure:"end"`
  230. }
  231. // ServiceStatus defines the service status
  232. type ServiceStatus struct {
  233. IsActive bool `json:"is_active"`
  234. Bindings []Binding `json:"bindings"`
  235. PassivePortRange PortRange `json:"passive_port_range"`
  236. }
  237. // Configuration defines the configuration for the ftp server
  238. type Configuration struct {
  239. // Addresses and ports to bind to
  240. Bindings []Binding `json:"bindings" mapstructure:"bindings"`
  241. // Greeting banner displayed when a connection first comes in
  242. Banner string `json:"banner" mapstructure:"banner"`
  243. // the contents of the specified file, if any, are diplayed when someone connects to the server.
  244. // If set, it overrides the banner string provided by the banner option
  245. BannerFile string `json:"banner_file" mapstructure:"banner_file"`
  246. // If files containing a certificate and matching private key for the server are provided the server will accept
  247. // both plain FTP an explicit FTP over TLS.
  248. // Certificate and key files can be reloaded on demand sending a "SIGHUP" signal on Unix based systems and a
  249. // "paramchange" request to the running service on Windows.
  250. CertificateFile string `json:"certificate_file" mapstructure:"certificate_file"`
  251. CertificateKeyFile string `json:"certificate_key_file" mapstructure:"certificate_key_file"`
  252. // CACertificates defines the set of root certificate authorities to be used to verify client certificates.
  253. CACertificates []string `json:"ca_certificates" mapstructure:"ca_certificates"`
  254. // CARevocationLists defines a set a revocation lists, one for each root CA, to be used to check
  255. // if a client certificate has been revoked
  256. CARevocationLists []string `json:"ca_revocation_lists" mapstructure:"ca_revocation_lists"`
  257. // Do not impose the port 20 for active data transfer. Enabling this option allows to run SFTPGo with less privilege
  258. ActiveTransfersPortNon20 bool `json:"active_transfers_port_non_20" mapstructure:"active_transfers_port_non_20"`
  259. // Set to true to disable active FTP
  260. DisableActiveMode bool `json:"disable_active_mode" mapstructure:"disable_active_mode"`
  261. // Set to true to enable the FTP SITE command.
  262. // We support chmod and symlink if SITE support is enabled
  263. EnableSite bool `json:"enable_site" mapstructure:"enable_site"`
  264. // Set to 1 to enable FTP commands that allow to calculate the hash value of files.
  265. // These FTP commands will be enabled: HASH, XCRC, MD5/XMD5, XSHA/XSHA1, XSHA256, XSHA512.
  266. // Please keep in mind that to calculate the hash we need to read the whole file, for
  267. // remote backends this means downloading the file, for the encrypted backend this means
  268. // decrypting the file
  269. HASHSupport int `json:"hash_support" mapstructure:"hash_support"`
  270. // Set to 1 to enable support for the non standard "COMB" FTP command.
  271. // Combine is only supported for local filesystem, for cloud backends it has
  272. // no advantage as it will download the partial files and will upload the
  273. // combined one. Cloud backends natively support multipart uploads.
  274. CombineSupport int `json:"combine_support" mapstructure:"combine_support"`
  275. // Port Range for data connections. Random if not specified
  276. PassivePortRange PortRange `json:"passive_port_range" mapstructure:"passive_port_range"`
  277. acmeDomain string
  278. }
  279. // ShouldBind returns true if there is at least a valid binding
  280. func (c *Configuration) ShouldBind() bool {
  281. for _, binding := range c.Bindings {
  282. if binding.IsValid() {
  283. return true
  284. }
  285. }
  286. return false
  287. }
  288. func (c *Configuration) getKeyPairs(configDir string) []common.TLSKeyPair {
  289. var keyPairs []common.TLSKeyPair
  290. for _, binding := range c.Bindings {
  291. certificateFile := getConfigPath(binding.CertificateFile, configDir)
  292. certificateKeyFile := getConfigPath(binding.CertificateKeyFile, configDir)
  293. if certificateFile != "" && certificateKeyFile != "" {
  294. keyPairs = append(keyPairs, common.TLSKeyPair{
  295. Cert: certificateFile,
  296. Key: certificateKeyFile,
  297. ID: binding.GetAddress(),
  298. })
  299. }
  300. }
  301. var certificateFile, certificateKeyFile string
  302. if c.acmeDomain != "" {
  303. certificateFile, certificateKeyFile = util.GetACMECertificateKeyPair(c.acmeDomain)
  304. } else {
  305. certificateFile = getConfigPath(c.CertificateFile, configDir)
  306. certificateKeyFile = getConfigPath(c.CertificateKeyFile, configDir)
  307. }
  308. if certificateFile != "" && certificateKeyFile != "" {
  309. keyPairs = append(keyPairs, common.TLSKeyPair{
  310. Cert: certificateFile,
  311. Key: certificateKeyFile,
  312. ID: common.DefaultTLSKeyPaidID,
  313. })
  314. }
  315. return keyPairs
  316. }
  317. func (c *Configuration) loadFromProvider() error {
  318. configs, err := dataprovider.GetConfigs()
  319. if err != nil {
  320. return fmt.Errorf("unable to load config from provider: %w", err)
  321. }
  322. configs.SetNilsToEmpty()
  323. if configs.ACME.Domain == "" || !configs.ACME.HasProtocol(common.ProtocolFTP) {
  324. return nil
  325. }
  326. crt, key := util.GetACMECertificateKeyPair(configs.ACME.Domain)
  327. if crt != "" && key != "" {
  328. if _, err := os.Stat(crt); err != nil {
  329. logger.Error(logSender, "", "unable to load acme cert file %q: %v", crt, err)
  330. return nil
  331. }
  332. if _, err := os.Stat(key); err != nil {
  333. logger.Error(logSender, "", "unable to load acme key file %q: %v", key, err)
  334. return nil
  335. }
  336. c.acmeDomain = configs.ACME.Domain
  337. logger.Info(logSender, "", "acme domain set to %q", c.acmeDomain)
  338. return nil
  339. }
  340. return nil
  341. }
  342. // Initialize configures and starts the FTP server
  343. func (c *Configuration) Initialize(configDir string) error {
  344. if err := c.loadFromProvider(); err != nil {
  345. return err
  346. }
  347. logger.Info(logSender, "", "initializing FTP server with config %+v", *c)
  348. if !c.ShouldBind() {
  349. return common.ErrNoBinding
  350. }
  351. keyPairs := c.getKeyPairs(configDir)
  352. if len(keyPairs) > 0 {
  353. mgr, err := common.NewCertManager(keyPairs, configDir, logSender)
  354. if err != nil {
  355. return err
  356. }
  357. mgr.SetCACertificates(c.CACertificates)
  358. if err := mgr.LoadRootCAs(); err != nil {
  359. return err
  360. }
  361. mgr.SetCARevocationLists(c.CARevocationLists)
  362. if err := mgr.LoadCRLs(); err != nil {
  363. return err
  364. }
  365. certMgr = mgr
  366. }
  367. serviceStatus = ServiceStatus{
  368. Bindings: nil,
  369. PassivePortRange: c.PassivePortRange,
  370. }
  371. exitChannel := make(chan error, 1)
  372. for idx, binding := range c.Bindings {
  373. if !binding.IsValid() {
  374. continue
  375. }
  376. server := NewServer(c, configDir, binding, idx)
  377. go func(s *Server) {
  378. ftpLogger := logger.LeveledLogger{Sender: "ftpserverlib"}
  379. ftpServer := ftpserver.NewFtpServer(s)
  380. ftpServer.Logger = ftpLogger.With("server_id", fmt.Sprintf("FTP_%v", s.ID))
  381. logger.Info(logSender, "", "starting FTP serving, binding: %v", s.binding.GetAddress())
  382. util.CheckTCP4Port(s.binding.Port)
  383. exitChannel <- ftpServer.ListenAndServe()
  384. }(server)
  385. serviceStatus.Bindings = append(serviceStatus.Bindings, binding)
  386. }
  387. serviceStatus.IsActive = true
  388. return <-exitChannel
  389. }
  390. // ReloadCertificateMgr reloads the certificate manager
  391. func ReloadCertificateMgr() error {
  392. if certMgr != nil {
  393. return certMgr.Reload()
  394. }
  395. return nil
  396. }
  397. // GetStatus returns the server status
  398. func GetStatus() ServiceStatus {
  399. return serviceStatus
  400. }
  401. func parsePassiveIP(passiveIP string) (string, error) {
  402. ip := net.ParseIP(passiveIP)
  403. if ip == nil {
  404. return "", fmt.Errorf("the provided passive IP %q is not valid", passiveIP)
  405. }
  406. ip = ip.To4()
  407. if ip == nil {
  408. return "", fmt.Errorf("the provided passive IP %q is not a valid IPv4 address", passiveIP)
  409. }
  410. return ip.String(), nil
  411. }
  412. func getConfigPath(name, configDir string) string {
  413. if !util.IsFileInputValid(name) {
  414. return ""
  415. }
  416. if name != "" && !filepath.IsAbs(name) {
  417. return filepath.Join(configDir, name)
  418. }
  419. return name
  420. }