1
0

ftpd.go 16 KB

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