ftpd.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464
  1. // Copyright (C) 2019 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. // Set to 1 to silently ignore any client requests to perform ASCII translations via the TYPE command.
  104. // That is, FTP clients can request ASCII translations, and SFTPGo will respond as the client expects,
  105. // but will not actually perform the translation for either uploads or downloads. This behavior can be
  106. // useful in circumstances involving older/mainframe clients and EBCDIC files.
  107. IgnoreASCIITransferType int `json:"ignore_ascii_transfer_type" mapstructure:"ignore_ascii_transfer_type"`
  108. // Debug enables the FTP debug mode. In debug mode, every FTP command will be logged
  109. Debug bool `json:"debug" mapstructure:"debug"`
  110. ciphers []uint16
  111. }
  112. func (b *Binding) setCiphers() {
  113. b.ciphers = util.GetTLSCiphersFromNames(b.TLSCipherSuites)
  114. }
  115. func (b *Binding) isMutualTLSEnabled() bool {
  116. return b.ClientAuthType == 1 || b.ClientAuthType == 2
  117. }
  118. // GetAddress returns the binding address
  119. func (b *Binding) GetAddress() string {
  120. return fmt.Sprintf("%s:%d", b.Address, b.Port)
  121. }
  122. // IsValid returns true if the binding port is > 0
  123. func (b *Binding) IsValid() bool {
  124. return b.Port > 0
  125. }
  126. func (b *Binding) isTLSModeValid() bool {
  127. return b.TLSMode >= 0 && b.TLSMode <= 2
  128. }
  129. func (b *Binding) isTLSSessionReuseValid() bool {
  130. return b.TLSSessionReuse >= 0 && b.TLSSessionReuse <= 1
  131. }
  132. func (b *Binding) checkSecuritySettings() error {
  133. if b.PassiveConnectionsSecurity < 0 || b.PassiveConnectionsSecurity > 1 {
  134. return fmt.Errorf("invalid passive_connections_security: %v", b.PassiveConnectionsSecurity)
  135. }
  136. if b.ActiveConnectionsSecurity < 0 || b.ActiveConnectionsSecurity > 1 {
  137. return fmt.Errorf("invalid active_connections_security: %v", b.ActiveConnectionsSecurity)
  138. }
  139. return nil
  140. }
  141. func (b *Binding) checkPassiveIP() error {
  142. if b.ForcePassiveIP != "" {
  143. ip, err := parsePassiveIP(b.ForcePassiveIP)
  144. if err != nil {
  145. return err
  146. }
  147. b.ForcePassiveIP = ip
  148. }
  149. for idx, passiveOverride := range b.PassiveIPOverrides {
  150. var ip string
  151. if passiveOverride.IP != "" {
  152. var err error
  153. ip, err = parsePassiveIP(passiveOverride.IP)
  154. if err != nil {
  155. return err
  156. }
  157. }
  158. if len(passiveOverride.Networks) == 0 {
  159. return errors.New("passive IP networks override cannot be empty")
  160. }
  161. checkFuncs, err := util.ParseAllowedIPAndRanges(passiveOverride.Networks)
  162. if err != nil {
  163. return fmt.Errorf("invalid passive IP networks override %+v: %w", passiveOverride.Networks, err)
  164. }
  165. b.PassiveIPOverrides[idx].IP = ip
  166. b.PassiveIPOverrides[idx].parsedNetworks = checkFuncs
  167. }
  168. return nil
  169. }
  170. func (b *Binding) getPassiveIP(cc ftpserver.ClientContext) (string, error) {
  171. if b.ForcePassiveIP != "" {
  172. return b.ForcePassiveIP, nil
  173. }
  174. if b.PassiveHost != "" {
  175. ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
  176. defer cancel()
  177. addrs, err := net.DefaultResolver.LookupIP(ctx, "ip4", b.PassiveHost)
  178. if err != nil {
  179. logger.Error(logSender, "", "unable to resolve hostname %q: %v", b.PassiveHost, err)
  180. return "", fmt.Errorf("unable to resolve hostname %q: %w", b.PassiveHost, err)
  181. }
  182. if len(addrs) > 0 {
  183. return addrs[0].String(), nil
  184. }
  185. }
  186. return strings.Split(cc.LocalAddr().String(), ":")[0], nil
  187. }
  188. func (b *Binding) passiveIPResolver(cc ftpserver.ClientContext) (string, error) {
  189. if len(b.PassiveIPOverrides) > 0 {
  190. clientIP := net.ParseIP(util.GetIPFromRemoteAddress(cc.RemoteAddr().String()))
  191. if clientIP != nil {
  192. for _, override := range b.PassiveIPOverrides {
  193. for _, fn := range override.parsedNetworks {
  194. if fn(clientIP) {
  195. if override.IP == "" {
  196. return strings.Split(cc.LocalAddr().String(), ":")[0], nil
  197. }
  198. return override.IP, nil
  199. }
  200. }
  201. }
  202. }
  203. }
  204. return b.getPassiveIP(cc)
  205. }
  206. // HasProxy returns true if the proxy protocol is active for this binding
  207. func (b *Binding) HasProxy() bool {
  208. return b.ApplyProxyConfig && common.Config.ProxyProtocol > 0
  209. }
  210. // GetTLSDescription returns the TLS mode as string
  211. func (b *Binding) GetTLSDescription() string {
  212. if certMgr == nil {
  213. return util.I18nFTPTLSDisabled
  214. }
  215. switch b.TLSMode {
  216. case 1:
  217. return util.I18nFTPTLSExplicit
  218. case 2:
  219. return util.I18nFTPTLSImplicit
  220. }
  221. if certMgr.HasCertificate(common.DefaultTLSKeyPaidID) || certMgr.HasCertificate(b.GetAddress()) {
  222. return util.I18nFTPTLSMixed
  223. }
  224. return util.I18nFTPTLSDisabled
  225. }
  226. // PortRange defines a port range
  227. type PortRange struct {
  228. // Range start
  229. Start int `json:"start" mapstructure:"start"`
  230. // Range end
  231. End int `json:"end" mapstructure:"end"`
  232. }
  233. // ServiceStatus defines the service status
  234. type ServiceStatus struct {
  235. IsActive bool `json:"is_active"`
  236. Bindings []Binding `json:"bindings"`
  237. PassivePortRange PortRange `json:"passive_port_range"`
  238. }
  239. // Configuration defines the configuration for the ftp server
  240. type Configuration struct {
  241. // Addresses and ports to bind to
  242. Bindings []Binding `json:"bindings" mapstructure:"bindings"`
  243. // The contents of the specified file, if any, are diplayed when someone connects to the server.
  244. BannerFile string `json:"banner_file" mapstructure:"banner_file"`
  245. // If files containing a certificate and matching private key for the server are provided the server will accept
  246. // both plain FTP an explicit FTP over TLS.
  247. // Certificate and key files can be reloaded on demand sending a "SIGHUP" signal on Unix based systems and a
  248. // "paramchange" request to the running service on Windows.
  249. CertificateFile string `json:"certificate_file" mapstructure:"certificate_file"`
  250. CertificateKeyFile string `json:"certificate_key_file" mapstructure:"certificate_key_file"`
  251. // CACertificates defines the set of root certificate authorities to be used to verify client certificates.
  252. CACertificates []string `json:"ca_certificates" mapstructure:"ca_certificates"`
  253. // CARevocationLists defines a set a revocation lists, one for each root CA, to be used to check
  254. // if a client certificate has been revoked
  255. CARevocationLists []string `json:"ca_revocation_lists" mapstructure:"ca_revocation_lists"`
  256. // Do not impose the port 20 for active data transfer. Enabling this option allows to run SFTPGo with less privilege
  257. ActiveTransfersPortNon20 bool `json:"active_transfers_port_non_20" mapstructure:"active_transfers_port_non_20"`
  258. // Set to true to disable active FTP
  259. DisableActiveMode bool `json:"disable_active_mode" mapstructure:"disable_active_mode"`
  260. // Set to true to enable the FTP SITE command.
  261. // We support chmod and symlink if SITE support is enabled
  262. EnableSite bool `json:"enable_site" mapstructure:"enable_site"`
  263. // Set to 1 to enable FTP commands that allow to calculate the hash value of files.
  264. // These FTP commands will be enabled: HASH, XCRC, MD5/XMD5, XSHA/XSHA1, XSHA256, XSHA512.
  265. // Please keep in mind that to calculate the hash we need to read the whole file, for
  266. // remote backends this means downloading the file, for the encrypted backend this means
  267. // decrypting the file
  268. HASHSupport int `json:"hash_support" mapstructure:"hash_support"`
  269. // Set to 1 to enable support for the non standard "COMB" FTP command.
  270. // Combine is only supported for local filesystem, for cloud backends it has
  271. // no advantage as it will download the partial files and will upload the
  272. // combined one. Cloud backends natively support multipart uploads.
  273. CombineSupport int `json:"combine_support" mapstructure:"combine_support"`
  274. // Port Range for data connections. Random if not specified
  275. PassivePortRange PortRange `json:"passive_port_range" mapstructure:"passive_port_range"`
  276. acmeDomain string
  277. }
  278. // ShouldBind returns true if there is at least a valid binding
  279. func (c *Configuration) ShouldBind() bool {
  280. for _, binding := range c.Bindings {
  281. if binding.IsValid() {
  282. return true
  283. }
  284. }
  285. return false
  286. }
  287. func (c *Configuration) getKeyPairs(configDir string) []common.TLSKeyPair {
  288. var keyPairs []common.TLSKeyPair
  289. for _, binding := range c.Bindings {
  290. certificateFile := getConfigPath(binding.CertificateFile, configDir)
  291. certificateKeyFile := getConfigPath(binding.CertificateKeyFile, configDir)
  292. if certificateFile != "" && certificateKeyFile != "" {
  293. keyPairs = append(keyPairs, common.TLSKeyPair{
  294. Cert: certificateFile,
  295. Key: certificateKeyFile,
  296. ID: binding.GetAddress(),
  297. })
  298. }
  299. }
  300. var certificateFile, certificateKeyFile string
  301. if c.acmeDomain != "" {
  302. certificateFile, certificateKeyFile = util.GetACMECertificateKeyPair(c.acmeDomain)
  303. } else {
  304. certificateFile = getConfigPath(c.CertificateFile, configDir)
  305. certificateKeyFile = getConfigPath(c.CertificateKeyFile, configDir)
  306. }
  307. if certificateFile != "" && certificateKeyFile != "" {
  308. keyPairs = append(keyPairs, common.TLSKeyPair{
  309. Cert: certificateFile,
  310. Key: certificateKeyFile,
  311. ID: common.DefaultTLSKeyPaidID,
  312. })
  313. }
  314. return keyPairs
  315. }
  316. func (c *Configuration) loadFromProvider() error {
  317. configs, err := dataprovider.GetConfigs()
  318. if err != nil {
  319. return fmt.Errorf("unable to load config from provider: %w", err)
  320. }
  321. configs.SetNilsToEmpty()
  322. if configs.ACME.Domain == "" || !configs.ACME.HasProtocol(common.ProtocolFTP) {
  323. return nil
  324. }
  325. crt, key := util.GetACMECertificateKeyPair(configs.ACME.Domain)
  326. if crt != "" && key != "" {
  327. if _, err := os.Stat(crt); err != nil {
  328. logger.Error(logSender, "", "unable to load acme cert file %q: %v", crt, err)
  329. return nil
  330. }
  331. if _, err := os.Stat(key); err != nil {
  332. logger.Error(logSender, "", "unable to load acme key file %q: %v", key, err)
  333. return nil
  334. }
  335. c.acmeDomain = configs.ACME.Domain
  336. logger.Info(logSender, "", "acme domain set to %q", c.acmeDomain)
  337. return nil
  338. }
  339. return nil
  340. }
  341. // Initialize configures and starts the FTP server
  342. func (c *Configuration) Initialize(configDir string) error {
  343. if err := c.loadFromProvider(); err != nil {
  344. return err
  345. }
  346. logger.Info(logSender, "", "initializing FTP server with config %+v", *c)
  347. if !c.ShouldBind() {
  348. return common.ErrNoBinding
  349. }
  350. keyPairs := c.getKeyPairs(configDir)
  351. if len(keyPairs) > 0 {
  352. mgr, err := common.NewCertManager(keyPairs, configDir, logSender)
  353. if err != nil {
  354. return err
  355. }
  356. mgr.SetCACertificates(c.CACertificates)
  357. if err := mgr.LoadRootCAs(); err != nil {
  358. return err
  359. }
  360. mgr.SetCARevocationLists(c.CARevocationLists)
  361. if err := mgr.LoadCRLs(); err != nil {
  362. return err
  363. }
  364. certMgr = mgr
  365. }
  366. serviceStatus = ServiceStatus{
  367. Bindings: nil,
  368. PassivePortRange: c.PassivePortRange,
  369. }
  370. exitChannel := make(chan error, 1)
  371. for idx, binding := range c.Bindings {
  372. if !binding.IsValid() {
  373. continue
  374. }
  375. server := NewServer(c, configDir, binding, idx)
  376. go func(s *Server) {
  377. ftpLogger := logger.LeveledLogger{Sender: "ftpserverlib"}
  378. ftpServer := ftpserver.NewFtpServer(s)
  379. ftpServer.Logger = ftpLogger.With("server_id", fmt.Sprintf("FTP_%v", s.ID))
  380. logger.Info(logSender, "", "starting FTP serving, binding: %v", s.binding.GetAddress())
  381. util.CheckTCP4Port(s.binding.Port)
  382. exitChannel <- ftpServer.ListenAndServe()
  383. }(server)
  384. serviceStatus.Bindings = append(serviceStatus.Bindings, binding)
  385. }
  386. serviceStatus.IsActive = true
  387. return <-exitChannel
  388. }
  389. // ReloadCertificateMgr reloads the certificate manager
  390. func ReloadCertificateMgr() error {
  391. if certMgr != nil {
  392. return certMgr.Reload()
  393. }
  394. return nil
  395. }
  396. // GetStatus returns the server status
  397. func GetStatus() ServiceStatus {
  398. return serviceStatus
  399. }
  400. func parsePassiveIP(passiveIP string) (string, error) {
  401. ip := net.ParseIP(passiveIP)
  402. if ip == nil {
  403. return "", fmt.Errorf("the provided passive IP %q is not valid", passiveIP)
  404. }
  405. ip = ip.To4()
  406. if ip == nil {
  407. return "", fmt.Errorf("the provided passive IP %q is not a valid IPv4 address", passiveIP)
  408. }
  409. return ip.String(), nil
  410. }
  411. func getConfigPath(name, configDir string) string {
  412. if !util.IsFileInputValid(name) {
  413. return ""
  414. }
  415. if name != "" && !filepath.IsAbs(name) {
  416. return filepath.Join(configDir, name)
  417. }
  418. return name
  419. }