ftpd.go 14 KB

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