ftpd.go 16 KB

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