common.go 50 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452
  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 common defines code shared among file transfer packages and protocols
  15. package common
  16. import (
  17. "context"
  18. "errors"
  19. "fmt"
  20. "net"
  21. "net/http"
  22. "net/url"
  23. "os"
  24. "os/exec"
  25. "path/filepath"
  26. "slices"
  27. "strconv"
  28. "strings"
  29. "sync"
  30. "sync/atomic"
  31. "time"
  32. "github.com/pires/go-proxyproto"
  33. "github.com/sftpgo/sdk/plugin/notifier"
  34. "github.com/drakkan/sftpgo/v2/internal/command"
  35. "github.com/drakkan/sftpgo/v2/internal/dataprovider"
  36. "github.com/drakkan/sftpgo/v2/internal/httpclient"
  37. "github.com/drakkan/sftpgo/v2/internal/logger"
  38. "github.com/drakkan/sftpgo/v2/internal/metric"
  39. "github.com/drakkan/sftpgo/v2/internal/plugin"
  40. "github.com/drakkan/sftpgo/v2/internal/smtp"
  41. "github.com/drakkan/sftpgo/v2/internal/util"
  42. "github.com/drakkan/sftpgo/v2/internal/version"
  43. "github.com/drakkan/sftpgo/v2/internal/vfs"
  44. )
  45. // constants
  46. const (
  47. logSender = "common"
  48. uploadLogSender = "Upload"
  49. downloadLogSender = "Download"
  50. renameLogSender = "Rename"
  51. rmdirLogSender = "Rmdir"
  52. mkdirLogSender = "Mkdir"
  53. symlinkLogSender = "Symlink"
  54. removeLogSender = "Remove"
  55. chownLogSender = "Chown"
  56. chmodLogSender = "Chmod"
  57. chtimesLogSender = "Chtimes"
  58. copyLogSender = "Copy"
  59. truncateLogSender = "Truncate"
  60. operationDownload = "download"
  61. operationUpload = "upload"
  62. operationFirstDownload = "first-download"
  63. operationFirstUpload = "first-upload"
  64. operationDelete = "delete"
  65. operationCopy = "copy"
  66. // Pre-download action name
  67. OperationPreDownload = "pre-download"
  68. // Pre-upload action name
  69. OperationPreUpload = "pre-upload"
  70. operationPreDelete = "pre-delete"
  71. operationRename = "rename"
  72. operationMkdir = "mkdir"
  73. operationRmdir = "rmdir"
  74. // SSH command action name
  75. OperationSSHCmd = "ssh_cmd"
  76. chtimesFormat = "2006-01-02T15:04:05" // YYYY-MM-DDTHH:MM:SS
  77. idleTimeoutCheckInterval = 3 * time.Minute
  78. periodicTimeoutCheckInterval = 1 * time.Minute
  79. )
  80. // Stat flags
  81. const (
  82. StatAttrUIDGID = 1
  83. StatAttrPerms = 2
  84. StatAttrTimes = 4
  85. StatAttrSize = 8
  86. )
  87. // Transfer types
  88. const (
  89. TransferUpload = iota
  90. TransferDownload
  91. )
  92. // Supported protocols
  93. const (
  94. ProtocolSFTP = "SFTP"
  95. ProtocolSCP = "SCP"
  96. ProtocolSSH = "SSH"
  97. ProtocolFTP = "FTP"
  98. ProtocolWebDAV = "DAV"
  99. ProtocolHTTP = "HTTP"
  100. ProtocolHTTPShare = "HTTPShare"
  101. ProtocolDataRetention = "DataRetention"
  102. ProtocolOIDC = "OIDC"
  103. protocolEventAction = "EventAction"
  104. )
  105. // Upload modes
  106. const (
  107. UploadModeStandard = 0
  108. UploadModeAtomic = 1
  109. UploadModeAtomicWithResume = 2
  110. UploadModeS3StoreOnError = 4
  111. UploadModeGCSStoreOnError = 8
  112. UploadModeAzureBlobStoreOnError = 16
  113. )
  114. func init() {
  115. Connections.clients = clientsMap{
  116. clients: make(map[string]int),
  117. }
  118. Connections.perUserConns = make(map[string]int)
  119. Connections.mapping = make(map[string]int)
  120. Connections.sshMapping = make(map[string]int)
  121. }
  122. // errors definitions
  123. var (
  124. ErrPermissionDenied = errors.New("permission denied")
  125. ErrNotExist = errors.New("no such file or directory")
  126. ErrOpUnsupported = errors.New("operation unsupported")
  127. ErrGenericFailure = errors.New("failure")
  128. ErrQuotaExceeded = errors.New("denying write due to space limit")
  129. ErrReadQuotaExceeded = errors.New("denying read due to quota limit")
  130. ErrConnectionDenied = errors.New("you are not allowed to connect")
  131. ErrNoBinding = errors.New("no binding configured")
  132. ErrCrtRevoked = errors.New("your certificate has been revoked")
  133. ErrNoCredentials = errors.New("no credential provided")
  134. ErrInternalFailure = errors.New("internal failure")
  135. ErrTransferAborted = errors.New("transfer aborted")
  136. ErrShuttingDown = errors.New("the service is shutting down")
  137. errNoTransfer = errors.New("requested transfer not found")
  138. errTransferMismatch = errors.New("transfer mismatch")
  139. )
  140. var (
  141. // Config is the configuration for the supported protocols
  142. Config Configuration
  143. // Connections is the list of active connections
  144. Connections ActiveConnections
  145. // QuotaScans is the list of active quota scans
  146. QuotaScans ActiveScans
  147. transfersChecker TransfersChecker
  148. supportedProtocols = []string{ProtocolSFTP, ProtocolSCP, ProtocolSSH, ProtocolFTP, ProtocolWebDAV,
  149. ProtocolHTTP, ProtocolHTTPShare, ProtocolOIDC}
  150. disconnHookProtocols = []string{ProtocolSFTP, ProtocolSCP, ProtocolSSH, ProtocolFTP}
  151. // the map key is the protocol, for each protocol we can have multiple rate limiters
  152. rateLimiters map[string][]*rateLimiter
  153. isShuttingDown atomic.Bool
  154. ftpLoginCommands = []string{"PASS", "USER"}
  155. fnUpdateBranding func(*dataprovider.BrandingConfigs)
  156. )
  157. // SetUpdateBrandingFn sets the function to call to update branding configs.
  158. func SetUpdateBrandingFn(fn func(*dataprovider.BrandingConfigs)) {
  159. fnUpdateBranding = fn
  160. }
  161. // Initialize sets the common configuration
  162. func Initialize(c Configuration, isShared int) error {
  163. isShuttingDown.Store(false)
  164. util.SetUmask(c.Umask)
  165. version.SetConfig(c.ServerVersion)
  166. dataprovider.SetTZ(c.TZ)
  167. Config = c
  168. Config.Actions.ExecuteOn = util.RemoveDuplicates(Config.Actions.ExecuteOn, true)
  169. Config.Actions.ExecuteSync = util.RemoveDuplicates(Config.Actions.ExecuteSync, true)
  170. Config.ProxyAllowed = util.RemoveDuplicates(Config.ProxyAllowed, true)
  171. Config.idleLoginTimeout = 2 * time.Minute
  172. Config.idleTimeoutAsDuration = time.Duration(Config.IdleTimeout) * time.Minute
  173. startPeriodicChecks(periodicTimeoutCheckInterval, isShared)
  174. Config.defender = nil
  175. Config.allowList = nil
  176. Config.rateLimitersList = nil
  177. rateLimiters = make(map[string][]*rateLimiter)
  178. for _, rlCfg := range c.RateLimitersConfig {
  179. if rlCfg.isEnabled() {
  180. if err := rlCfg.validate(); err != nil {
  181. return fmt.Errorf("rate limiters initialization error: %w", err)
  182. }
  183. rateLimiter := rlCfg.getLimiter()
  184. for _, protocol := range rlCfg.Protocols {
  185. rateLimiters[protocol] = append(rateLimiters[protocol], rateLimiter)
  186. }
  187. }
  188. }
  189. if len(rateLimiters) > 0 {
  190. rateLimitersList, err := dataprovider.NewIPList(dataprovider.IPListTypeRateLimiterSafeList)
  191. if err != nil {
  192. return fmt.Errorf("unable to initialize ratelimiters list: %w", err)
  193. }
  194. Config.rateLimitersList = rateLimitersList
  195. }
  196. if c.DefenderConfig.Enabled {
  197. if !slices.Contains(supportedDefenderDrivers, c.DefenderConfig.Driver) {
  198. return fmt.Errorf("unsupported defender driver %q", c.DefenderConfig.Driver)
  199. }
  200. var defender Defender
  201. var err error
  202. switch c.DefenderConfig.Driver {
  203. case DefenderDriverProvider:
  204. defender, err = newDBDefender(&c.DefenderConfig)
  205. default:
  206. defender, err = newInMemoryDefender(&c.DefenderConfig)
  207. }
  208. if err != nil {
  209. return fmt.Errorf("defender initialization error: %v", err)
  210. }
  211. logger.Info(logSender, "", "defender initialized with config %+v", c.DefenderConfig)
  212. Config.defender = defender
  213. }
  214. if c.AllowListStatus > 0 {
  215. allowList, err := dataprovider.NewIPList(dataprovider.IPListTypeAllowList)
  216. if err != nil {
  217. return fmt.Errorf("unable to initialize the allow list: %w", err)
  218. }
  219. logger.Info(logSender, "", "allow list initialized")
  220. Config.allowList = allowList
  221. }
  222. if err := c.initializeProxyProtocol(); err != nil {
  223. return err
  224. }
  225. vfs.SetTempPath(c.TempPath)
  226. dataprovider.SetTempPath(c.TempPath)
  227. vfs.SetAllowSelfConnections(c.AllowSelfConnections)
  228. vfs.SetRenameMode(c.RenameMode)
  229. vfs.SetReadMetadataMode(c.Metadata.Read)
  230. vfs.SetResumeMaxSize(c.ResumeMaxSize)
  231. vfs.SetUploadMode(c.UploadMode)
  232. dataprovider.SetAllowSelfConnections(c.AllowSelfConnections)
  233. transfersChecker = getTransfersChecker(isShared)
  234. return nil
  235. }
  236. // CheckClosing returns an error if the service is closing
  237. func CheckClosing() error {
  238. if isShuttingDown.Load() {
  239. return ErrShuttingDown
  240. }
  241. return nil
  242. }
  243. // WaitForTransfers waits, for the specified grace time, for currently ongoing
  244. // client-initiated transfer sessions to completes.
  245. // A zero graceTime means no wait
  246. func WaitForTransfers(graceTime int) {
  247. if graceTime == 0 {
  248. return
  249. }
  250. if isShuttingDown.Swap(true) {
  251. return
  252. }
  253. if activeHooks.Load() == 0 && getActiveConnections() == 0 {
  254. return
  255. }
  256. graceTimer := time.NewTimer(time.Duration(graceTime) * time.Second)
  257. ticker := time.NewTicker(3 * time.Second)
  258. for {
  259. select {
  260. case <-ticker.C:
  261. hooks := activeHooks.Load()
  262. logger.Info(logSender, "", "active hooks: %d", hooks)
  263. if hooks == 0 && getActiveConnections() == 0 {
  264. logger.Info(logSender, "", "no more active connections, graceful shutdown")
  265. ticker.Stop()
  266. graceTimer.Stop()
  267. return
  268. }
  269. case <-graceTimer.C:
  270. logger.Info(logSender, "", "grace time expired, hard shutdown")
  271. ticker.Stop()
  272. return
  273. }
  274. }
  275. }
  276. // getActiveConnections returns the number of connections with active transfers
  277. func getActiveConnections() int {
  278. var activeConns int
  279. Connections.RLock()
  280. for _, c := range Connections.connections {
  281. if len(c.GetTransfers()) > 0 {
  282. activeConns++
  283. }
  284. }
  285. Connections.RUnlock()
  286. logger.Info(logSender, "", "number of connections with active transfers: %d", activeConns)
  287. return activeConns
  288. }
  289. // LimitRate blocks until all the configured rate limiters
  290. // allow one event to happen.
  291. // It returns an error if the time to wait exceeds the max
  292. // allowed delay
  293. func LimitRate(protocol, ip string) (time.Duration, error) {
  294. if Config.rateLimitersList != nil {
  295. isListed, _, err := Config.rateLimitersList.IsListed(ip, protocol)
  296. if err == nil && isListed {
  297. return 0, nil
  298. }
  299. }
  300. for _, limiter := range rateLimiters[protocol] {
  301. if delay, err := limiter.Wait(ip, protocol); err != nil {
  302. logger.Debug(logSender, "", "protocol %s ip %s: %v", protocol, ip, err)
  303. return delay, err
  304. }
  305. }
  306. return 0, nil
  307. }
  308. // Reload reloads the whitelist, the IP filter plugin and the defender's block and safe lists
  309. func Reload() error {
  310. plugin.Handler.ReloadFilter()
  311. return nil
  312. }
  313. // DelayLogin applies the configured login delay
  314. func DelayLogin(err error) {
  315. if Config.defender != nil {
  316. Config.defender.DelayLogin(err)
  317. }
  318. }
  319. // IsBanned returns true if the specified IP address is banned
  320. func IsBanned(ip, protocol string) bool {
  321. if plugin.Handler.IsIPBanned(ip, protocol) {
  322. return true
  323. }
  324. if Config.defender == nil {
  325. return false
  326. }
  327. return Config.defender.IsBanned(ip, protocol)
  328. }
  329. // GetDefenderBanTime returns the ban time for the given IP
  330. // or nil if the IP is not banned or the defender is disabled
  331. func GetDefenderBanTime(ip string) (*time.Time, error) {
  332. if Config.defender == nil {
  333. return nil, nil
  334. }
  335. return Config.defender.GetBanTime(ip)
  336. }
  337. // GetDefenderHosts returns hosts that are banned or for which some violations have been detected
  338. func GetDefenderHosts() ([]dataprovider.DefenderEntry, error) {
  339. if Config.defender == nil {
  340. return nil, nil
  341. }
  342. return Config.defender.GetHosts()
  343. }
  344. // GetDefenderHost returns a defender host by ip, if any
  345. func GetDefenderHost(ip string) (dataprovider.DefenderEntry, error) {
  346. if Config.defender == nil {
  347. return dataprovider.DefenderEntry{}, errors.New("defender is disabled")
  348. }
  349. return Config.defender.GetHost(ip)
  350. }
  351. // DeleteDefenderHost removes the specified IP address from the defender lists
  352. func DeleteDefenderHost(ip string) bool {
  353. if Config.defender == nil {
  354. return false
  355. }
  356. return Config.defender.DeleteHost(ip)
  357. }
  358. // GetDefenderScore returns the score for the given IP
  359. func GetDefenderScore(ip string) (int, error) {
  360. if Config.defender == nil {
  361. return 0, nil
  362. }
  363. return Config.defender.GetScore(ip)
  364. }
  365. // AddDefenderEvent adds the specified defender event for the given IP.
  366. // Returns true if the IP is in the defender's safe list.
  367. func AddDefenderEvent(ip, protocol string, event HostEvent) bool {
  368. if Config.defender == nil {
  369. return false
  370. }
  371. return Config.defender.AddEvent(ip, protocol, event)
  372. }
  373. func reloadProviderConfigs() {
  374. configs, err := dataprovider.GetConfigs()
  375. if err != nil {
  376. logger.Error(logSender, "", "unable to load config from provider: %v", err)
  377. return
  378. }
  379. configs.SetNilsToEmpty()
  380. if fnUpdateBranding != nil {
  381. fnUpdateBranding(configs.Branding)
  382. }
  383. if err := configs.SMTP.TryDecrypt(); err != nil {
  384. logger.Error(logSender, "", "unable to decrypt smtp config: %v", err)
  385. return
  386. }
  387. smtp.Activate(configs.SMTP)
  388. }
  389. func startPeriodicChecks(duration time.Duration, isShared int) {
  390. startEventScheduler()
  391. spec := fmt.Sprintf("@every %s", duration)
  392. _, err := eventScheduler.AddFunc(spec, Connections.checkTransfers)
  393. util.PanicOnError(err)
  394. logger.Info(logSender, "", "scheduled overquota transfers check, schedule %q", spec)
  395. if isShared == 1 {
  396. logger.Info(logSender, "", "add reload configs task")
  397. _, err := eventScheduler.AddFunc("@every 10m", reloadProviderConfigs)
  398. util.PanicOnError(err)
  399. }
  400. if Config.IdleTimeout > 0 {
  401. ratio := idleTimeoutCheckInterval / periodicTimeoutCheckInterval
  402. spec = fmt.Sprintf("@every %s", duration*ratio)
  403. _, err = eventScheduler.AddFunc(spec, Connections.checkIdles)
  404. util.PanicOnError(err)
  405. logger.Info(logSender, "", "scheduled idle connections check, schedule %q", spec)
  406. }
  407. }
  408. // ActiveTransfer defines the interface for the current active transfers
  409. type ActiveTransfer interface {
  410. GetID() int64
  411. GetType() int
  412. GetSize() int64
  413. GetDownloadedSize() int64
  414. GetUploadedSize() int64
  415. GetVirtualPath() string
  416. GetStartTime() time.Time
  417. SignalClose(err error)
  418. Truncate(fsPath string, size int64) (int64, error)
  419. GetRealFsPath(fsPath string) string
  420. SetTimes(fsPath string, atime time.Time, mtime time.Time) bool
  421. GetTruncatedSize() int64
  422. HasSizeLimit() bool
  423. }
  424. // ActiveConnection defines the interface for the current active connections
  425. type ActiveConnection interface {
  426. GetID() string
  427. GetUsername() string
  428. GetRole() string
  429. GetMaxSessions() int
  430. GetLocalAddress() string
  431. GetRemoteAddress() string
  432. GetClientVersion() string
  433. GetProtocol() string
  434. GetConnectionTime() time.Time
  435. GetLastActivity() time.Time
  436. GetCommand() string
  437. Disconnect() error
  438. AddTransfer(t ActiveTransfer)
  439. RemoveTransfer(t ActiveTransfer)
  440. GetTransfers() []ConnectionTransfer
  441. SignalTransferClose(transferID int64, err error)
  442. CloseFS() error
  443. isAccessAllowed() bool
  444. }
  445. // StatAttributes defines the attributes for set stat commands
  446. type StatAttributes struct {
  447. Mode os.FileMode
  448. Atime time.Time
  449. Mtime time.Time
  450. UID int
  451. GID int
  452. Flags int
  453. Size int64
  454. }
  455. // ConnectionTransfer defines the trasfer details
  456. type ConnectionTransfer struct {
  457. ID int64 `json:"-"`
  458. OperationType string `json:"operation_type"`
  459. StartTime int64 `json:"start_time"`
  460. Size int64 `json:"size"`
  461. VirtualPath string `json:"path"`
  462. HasSizeLimit bool `json:"-"`
  463. ULSize int64 `json:"-"`
  464. DLSize int64 `json:"-"`
  465. }
  466. // MetadataConfig defines how to handle metadata for cloud storage backends
  467. type MetadataConfig struct {
  468. // If not zero the metadata will be read before downloads and will be
  469. // available in notifications
  470. Read int `json:"read" mapstructure:"read"`
  471. }
  472. // Configuration defines configuration parameters common to all supported protocols
  473. type Configuration struct {
  474. // Maximum idle timeout as minutes. If a client is idle for a time that exceeds this setting it will be disconnected.
  475. // 0 means disabled
  476. IdleTimeout int `json:"idle_timeout" mapstructure:"idle_timeout"`
  477. // UploadMode 0 means standard, the files are uploaded directly to the requested path.
  478. // 1 means atomic: the files are uploaded to a temporary path and renamed to the requested path
  479. // when the client ends the upload. Atomic mode avoid problems such as a web server that
  480. // serves partial files when the files are being uploaded.
  481. // In atomic mode if there is an upload error the temporary file is deleted and so the requested
  482. // upload path will not contain a partial file.
  483. // 2 means atomic with resume support: as atomic but if there is an upload error the temporary
  484. // file is renamed to the requested path and not deleted, this way a client can reconnect and resume
  485. // the upload.
  486. // 4 means files for S3 backend are stored even if a client-side upload error is detected.
  487. // 8 means files for Google Cloud Storage backend are stored even if a client-side upload error is detected.
  488. // 16 means files for Azure Blob backend are stored even if a client-side upload error is detected.
  489. UploadMode int `json:"upload_mode" mapstructure:"upload_mode"`
  490. // Actions to execute for SFTP file operations and SSH commands
  491. Actions ProtocolActions `json:"actions" mapstructure:"actions"`
  492. // SetstatMode 0 means "normal mode": requests for changing permissions and owner/group are executed.
  493. // 1 means "ignore mode": requests for changing permissions and owner/group are silently ignored.
  494. // 2 means "ignore mode for cloud fs": requests for changing permissions and owner/group are
  495. // silently ignored for cloud based filesystem such as S3, GCS, Azure Blob. Requests for changing
  496. // modification times are ignored for cloud based filesystem if they are not supported.
  497. SetstatMode int `json:"setstat_mode" mapstructure:"setstat_mode"`
  498. // RenameMode defines how to handle directory renames. By default, renaming of non-empty directories
  499. // is not allowed for cloud storage providers (S3, GCS, Azure Blob). Set to 1 to enable recursive
  500. // renames for these providers, they may be slow, there is no atomic rename API like for local
  501. // filesystem, so SFTPGo will recursively list the directory contents and do a rename for each entry
  502. RenameMode int `json:"rename_mode" mapstructure:"rename_mode"`
  503. // ResumeMaxSize defines the maximum size allowed, in bytes, to resume uploads on storage backends
  504. // with immutable objects. By default, resuming uploads is not allowed for cloud storage providers
  505. // (S3, GCS, Azure Blob) because SFTPGo must rewrite the entire file.
  506. // Set to a value greater than 0 to allow resuming uploads of files smaller than or equal to the
  507. // defined size.
  508. ResumeMaxSize int64 `json:"resume_max_size" mapstructure:"resume_max_size"`
  509. // TempPath defines the path for temporary files such as those used for atomic uploads or file pipes.
  510. // If you set this option you must make sure that the defined path exists, is accessible for writing
  511. // by the user running SFTPGo, and is on the same filesystem as the users home directories otherwise
  512. // the renaming for atomic uploads will become a copy and therefore may take a long time.
  513. // The temporary files are not namespaced. The default is generally fine. Leave empty for the default.
  514. TempPath string `json:"temp_path" mapstructure:"temp_path"`
  515. // Support for HAProxy PROXY protocol.
  516. // If you are running SFTPGo behind a proxy server such as HAProxy, AWS ELB or NGNIX, you can enable
  517. // the proxy protocol. It provides a convenient way to safely transport connection information
  518. // such as a client's address across multiple layers of NAT or TCP proxies to get the real
  519. // client IP address instead of the proxy IP. Both protocol versions 1 and 2 are supported.
  520. // - 0 means disabled
  521. // - 1 means proxy protocol enabled. Proxy header will be used and requests without proxy header will be accepted.
  522. // - 2 means proxy protocol required. Proxy header will be used and requests without proxy header will be rejected.
  523. // If the proxy protocol is enabled in SFTPGo then you have to enable the protocol in your proxy configuration too,
  524. // for example for HAProxy add "send-proxy" or "send-proxy-v2" to each server configuration line.
  525. ProxyProtocol int `json:"proxy_protocol" mapstructure:"proxy_protocol"`
  526. // List of IP addresses and IP ranges allowed to send the proxy header.
  527. // If proxy protocol is set to 1 and we receive a proxy header from an IP that is not in the list then the
  528. // connection will be accepted and the header will be ignored.
  529. // If proxy protocol is set to 2 and we receive a proxy header from an IP that is not in the list then the
  530. // connection will be rejected.
  531. ProxyAllowed []string `json:"proxy_allowed" mapstructure:"proxy_allowed"`
  532. // List of IP addresses and IP ranges for which not to read the proxy header
  533. ProxySkipped []string `json:"proxy_skipped" mapstructure:"proxy_skipped"`
  534. // Absolute path to an external program or an HTTP URL to invoke as soon as SFTPGo starts.
  535. // If you define an HTTP URL it will be invoked using a `GET` request.
  536. // Please note that SFTPGo services may not yet be available when this hook is run.
  537. // Leave empty do disable.
  538. StartupHook string `json:"startup_hook" mapstructure:"startup_hook"`
  539. // Absolute path to an external program or an HTTP URL to invoke after a user connects
  540. // and before he tries to login. It allows you to reject the connection based on the source
  541. // ip address. Leave empty do disable.
  542. PostConnectHook string `json:"post_connect_hook" mapstructure:"post_connect_hook"`
  543. // Absolute path to an external program or an HTTP URL to invoke after an SSH/FTP connection ends.
  544. // Leave empty do disable.
  545. PostDisconnectHook string `json:"post_disconnect_hook" mapstructure:"post_disconnect_hook"`
  546. // Absolute path to an external program or an HTTP URL to invoke after a data retention check completes.
  547. // Leave empty do disable.
  548. DataRetentionHook string `json:"data_retention_hook" mapstructure:"data_retention_hook"`
  549. // Maximum number of concurrent client connections. 0 means unlimited
  550. MaxTotalConnections int `json:"max_total_connections" mapstructure:"max_total_connections"`
  551. // Maximum number of concurrent client connections from the same host (IP). 0 means unlimited
  552. MaxPerHostConnections int `json:"max_per_host_connections" mapstructure:"max_per_host_connections"`
  553. // Defines the status of the global allow list. 0 means disabled, 1 enabled.
  554. // If enabled, only the listed IPs/networks can access the configured services, all other
  555. // client connections will be dropped before they even try to authenticate.
  556. // Ensure to enable this setting only after adding some allowed ip/networks from the WebAdmin/REST API
  557. AllowListStatus int `json:"allowlist_status" mapstructure:"allowlist_status"`
  558. // Allow users on this instance to use other users/virtual folders on this instance as storage backend.
  559. // Enable this setting if you know what you are doing.
  560. AllowSelfConnections int `json:"allow_self_connections" mapstructure:"allow_self_connections"`
  561. // Defender configuration
  562. DefenderConfig DefenderConfig `json:"defender" mapstructure:"defender"`
  563. // Rate limiter configurations
  564. RateLimitersConfig []RateLimiterConfig `json:"rate_limiters" mapstructure:"rate_limiters"`
  565. // Umask for new uploads. Leave blank to use the system default.
  566. Umask string `json:"umask" mapstructure:"umask"`
  567. // Defines the server version
  568. ServerVersion string `json:"server_version" mapstructure:"server_version"`
  569. // TZ defines the time zone to use for the EventManager scheduler and to
  570. // control time-based access restrictions. Set to "local" to use the
  571. // server's local time, otherwise UTC will be used.
  572. TZ string `json:"tz" mapstructure:"tz"`
  573. // Metadata configuration
  574. Metadata MetadataConfig `json:"metadata" mapstructure:"metadata"`
  575. idleTimeoutAsDuration time.Duration
  576. idleLoginTimeout time.Duration
  577. defender Defender
  578. allowList *dataprovider.IPList
  579. rateLimitersList *dataprovider.IPList
  580. proxyAllowed []func(net.IP) bool
  581. proxySkipped []func(net.IP) bool
  582. }
  583. // IsAtomicUploadEnabled returns true if atomic upload is enabled
  584. func (c *Configuration) IsAtomicUploadEnabled() bool {
  585. return c.UploadMode&UploadModeAtomic != 0 || c.UploadMode&UploadModeAtomicWithResume != 0
  586. }
  587. func (c *Configuration) initializeProxyProtocol() error {
  588. if c.ProxyProtocol > 0 {
  589. allowed, err := util.ParseAllowedIPAndRanges(c.ProxyAllowed)
  590. if err != nil {
  591. return fmt.Errorf("invalid proxy allowed: %w", err)
  592. }
  593. skipped, err := util.ParseAllowedIPAndRanges(c.ProxySkipped)
  594. if err != nil {
  595. return fmt.Errorf("invalid proxy skipped: %w", err)
  596. }
  597. Config.proxyAllowed = allowed
  598. Config.proxySkipped = skipped
  599. }
  600. return nil
  601. }
  602. // GetProxyListener returns a wrapper for the given listener that supports the
  603. // HAProxy Proxy Protocol
  604. func (c *Configuration) GetProxyListener(listener net.Listener) (*proxyproto.Listener, error) {
  605. if c.ProxyProtocol > 0 {
  606. defaultPolicy := proxyproto.REQUIRE
  607. if c.ProxyProtocol == 1 {
  608. defaultPolicy = proxyproto.IGNORE
  609. }
  610. return &proxyproto.Listener{
  611. Listener: listener,
  612. Policy: getProxyPolicy(c.proxyAllowed, c.proxySkipped, defaultPolicy),
  613. ReadHeaderTimeout: 10 * time.Second,
  614. }, nil
  615. }
  616. return nil, errors.New("proxy protocol not configured")
  617. }
  618. // GetRateLimitersStatus returns the rate limiters status
  619. func (c *Configuration) GetRateLimitersStatus() (bool, []string) {
  620. enabled := false
  621. var protocols []string
  622. for _, rlCfg := range c.RateLimitersConfig {
  623. if rlCfg.isEnabled() {
  624. enabled = true
  625. protocols = append(protocols, rlCfg.Protocols...)
  626. }
  627. }
  628. return enabled, util.RemoveDuplicates(protocols, false)
  629. }
  630. // IsAllowListEnabled returns true if the global allow list is enabled
  631. func (c *Configuration) IsAllowListEnabled() bool {
  632. return c.AllowListStatus > 0
  633. }
  634. // ExecuteStartupHook runs the startup hook if defined
  635. func (c *Configuration) ExecuteStartupHook() error {
  636. if c.StartupHook == "" {
  637. return nil
  638. }
  639. if strings.HasPrefix(c.StartupHook, "http") {
  640. var url *url.URL
  641. url, err := url.Parse(c.StartupHook)
  642. if err != nil {
  643. logger.Warn(logSender, "", "Invalid startup hook %q: %v", c.StartupHook, err)
  644. return err
  645. }
  646. startTime := time.Now()
  647. resp, err := httpclient.RetryableGet(url.String())
  648. if err != nil {
  649. logger.Warn(logSender, "", "Error executing startup hook: %v", err)
  650. return err
  651. }
  652. defer resp.Body.Close()
  653. logger.Debug(logSender, "", "Startup hook executed, elapsed: %v, response code: %v", time.Since(startTime), resp.StatusCode)
  654. return nil
  655. }
  656. if !filepath.IsAbs(c.StartupHook) {
  657. err := fmt.Errorf("invalid startup hook %q", c.StartupHook)
  658. logger.Warn(logSender, "", "Invalid startup hook %q", c.StartupHook)
  659. return err
  660. }
  661. startTime := time.Now()
  662. timeout, env, args := command.GetConfig(c.StartupHook, command.HookStartup)
  663. ctx, cancel := context.WithTimeout(context.Background(), timeout)
  664. defer cancel()
  665. cmd := exec.CommandContext(ctx, c.StartupHook, args...)
  666. cmd.Env = env
  667. err := cmd.Run()
  668. logger.Debug(logSender, "", "Startup hook executed, elapsed: %s, error: %v", time.Since(startTime), err)
  669. return nil
  670. }
  671. func (c *Configuration) executePostDisconnectHook(remoteAddr, protocol, username, connID string, connectionTime time.Time) {
  672. startNewHook()
  673. defer hookEnded()
  674. ipAddr := util.GetIPFromRemoteAddress(remoteAddr)
  675. connDuration := int64(time.Since(connectionTime) / time.Millisecond)
  676. if strings.HasPrefix(c.PostDisconnectHook, "http") {
  677. var url *url.URL
  678. url, err := url.Parse(c.PostDisconnectHook)
  679. if err != nil {
  680. logger.Warn(protocol, connID, "Invalid post disconnect hook %q: %v", c.PostDisconnectHook, err)
  681. return
  682. }
  683. q := url.Query()
  684. q.Add("ip", ipAddr)
  685. q.Add("protocol", protocol)
  686. q.Add("username", username)
  687. q.Add("connection_duration", strconv.FormatInt(connDuration, 10))
  688. url.RawQuery = q.Encode()
  689. startTime := time.Now()
  690. resp, err := httpclient.RetryableGet(url.String())
  691. respCode := 0
  692. if err == nil {
  693. respCode = resp.StatusCode
  694. resp.Body.Close()
  695. }
  696. logger.Debug(protocol, connID, "Post disconnect hook response code: %v, elapsed: %v, err: %v",
  697. respCode, time.Since(startTime), err)
  698. return
  699. }
  700. if !filepath.IsAbs(c.PostDisconnectHook) {
  701. logger.Debug(protocol, connID, "invalid post disconnect hook %q", c.PostDisconnectHook)
  702. return
  703. }
  704. timeout, env, args := command.GetConfig(c.PostDisconnectHook, command.HookPostDisconnect)
  705. ctx, cancel := context.WithTimeout(context.Background(), timeout)
  706. defer cancel()
  707. startTime := time.Now()
  708. cmd := exec.CommandContext(ctx, c.PostDisconnectHook, args...)
  709. cmd.Env = append(env,
  710. fmt.Sprintf("SFTPGO_CONNECTION_IP=%s", ipAddr),
  711. fmt.Sprintf("SFTPGO_CONNECTION_USERNAME=%s", username),
  712. fmt.Sprintf("SFTPGO_CONNECTION_DURATION=%d", connDuration),
  713. fmt.Sprintf("SFTPGO_CONNECTION_PROTOCOL=%s", protocol))
  714. err := cmd.Run()
  715. logger.Debug(protocol, connID, "Post disconnect hook executed, elapsed: %s error: %v", time.Since(startTime), err)
  716. }
  717. func (c *Configuration) checkPostDisconnectHook(remoteAddr, protocol, username, connID string, connectionTime time.Time) {
  718. if c.PostDisconnectHook == "" {
  719. return
  720. }
  721. if !slices.Contains(disconnHookProtocols, protocol) {
  722. return
  723. }
  724. go c.executePostDisconnectHook(remoteAddr, protocol, username, connID, connectionTime)
  725. }
  726. // ExecutePostConnectHook executes the post connect hook if defined
  727. func (c *Configuration) ExecutePostConnectHook(ipAddr, protocol string) error {
  728. if c.PostConnectHook == "" {
  729. return nil
  730. }
  731. if strings.HasPrefix(c.PostConnectHook, "http") {
  732. var url *url.URL
  733. url, err := url.Parse(c.PostConnectHook)
  734. if err != nil {
  735. logger.Warn(protocol, "", "Login from ip %q denied, invalid post connect hook %q: %v",
  736. ipAddr, c.PostConnectHook, err)
  737. return getPermissionDeniedError(protocol)
  738. }
  739. q := url.Query()
  740. q.Add("ip", ipAddr)
  741. q.Add("protocol", protocol)
  742. url.RawQuery = q.Encode()
  743. resp, err := httpclient.RetryableGet(url.String())
  744. if err != nil {
  745. logger.Warn(protocol, "", "Login from ip %q denied, error executing post connect hook: %v", ipAddr, err)
  746. return getPermissionDeniedError(protocol)
  747. }
  748. defer resp.Body.Close()
  749. if resp.StatusCode != http.StatusOK {
  750. logger.Warn(protocol, "", "Login from ip %q denied, post connect hook response code: %v", ipAddr, resp.StatusCode)
  751. return getPermissionDeniedError(protocol)
  752. }
  753. return nil
  754. }
  755. if !filepath.IsAbs(c.PostConnectHook) {
  756. err := fmt.Errorf("invalid post connect hook %q", c.PostConnectHook)
  757. logger.Warn(protocol, "", "Login from ip %q denied: %v", ipAddr, err)
  758. return getPermissionDeniedError(protocol)
  759. }
  760. timeout, env, args := command.GetConfig(c.PostConnectHook, command.HookPostConnect)
  761. ctx, cancel := context.WithTimeout(context.Background(), timeout)
  762. defer cancel()
  763. cmd := exec.CommandContext(ctx, c.PostConnectHook, args...)
  764. cmd.Env = append(env,
  765. fmt.Sprintf("SFTPGO_CONNECTION_IP=%s", ipAddr),
  766. fmt.Sprintf("SFTPGO_CONNECTION_PROTOCOL=%s", protocol))
  767. err := cmd.Run()
  768. if err != nil {
  769. logger.Warn(protocol, "", "Login from ip %q denied, connect hook error: %v", ipAddr, err)
  770. return getPermissionDeniedError(protocol)
  771. }
  772. return nil
  773. }
  774. func getProxyPolicy(allowed, skipped []func(net.IP) bool, def proxyproto.Policy) proxyproto.PolicyFunc {
  775. return func(upstream net.Addr) (proxyproto.Policy, error) {
  776. upstreamIP, err := util.GetIPFromNetAddr(upstream)
  777. if err != nil {
  778. // Something is wrong with the source IP, better reject the
  779. // connection if a proxy header is found.
  780. return proxyproto.REJECT, err
  781. }
  782. for _, skippedFrom := range skipped {
  783. if skippedFrom(upstreamIP) {
  784. return proxyproto.SKIP, nil
  785. }
  786. }
  787. for _, allowFrom := range allowed {
  788. if allowFrom(upstreamIP) {
  789. if def == proxyproto.REQUIRE {
  790. return proxyproto.REQUIRE, nil
  791. }
  792. return proxyproto.USE, nil
  793. }
  794. }
  795. if def == proxyproto.REQUIRE {
  796. return proxyproto.REJECT, nil
  797. }
  798. return def, nil
  799. }
  800. }
  801. // SSHConnection defines an ssh connection.
  802. // Each SSH connection can open several channels for SFTP or SSH commands
  803. type SSHConnection struct {
  804. id string
  805. conn net.Conn
  806. lastActivity atomic.Int64
  807. }
  808. // NewSSHConnection returns a new SSHConnection
  809. func NewSSHConnection(id string, conn net.Conn) *SSHConnection {
  810. c := &SSHConnection{
  811. id: id,
  812. conn: conn,
  813. }
  814. c.lastActivity.Store(time.Now().UnixNano())
  815. return c
  816. }
  817. // GetID returns the ID for this SSHConnection
  818. func (c *SSHConnection) GetID() string {
  819. return c.id
  820. }
  821. // UpdateLastActivity updates last activity for this connection
  822. func (c *SSHConnection) UpdateLastActivity() {
  823. c.lastActivity.Store(time.Now().UnixNano())
  824. }
  825. // GetLastActivity returns the last connection activity
  826. func (c *SSHConnection) GetLastActivity() time.Time {
  827. return time.Unix(0, c.lastActivity.Load())
  828. }
  829. // Close closes the underlying network connection
  830. func (c *SSHConnection) Close() error {
  831. return c.conn.Close()
  832. }
  833. // ActiveConnections holds the currect active connections with the associated transfers
  834. type ActiveConnections struct {
  835. // clients contains both authenticated and estabilished connections and the ones waiting
  836. // for authentication
  837. clients clientsMap
  838. transfersCheckStatus atomic.Bool
  839. sync.RWMutex
  840. connections []ActiveConnection
  841. mapping map[string]int
  842. sshConnections []*SSHConnection
  843. sshMapping map[string]int
  844. perUserConns map[string]int
  845. }
  846. // internal method, must be called within a locked block
  847. func (conns *ActiveConnections) addUserConnection(username string) {
  848. if username == "" {
  849. return
  850. }
  851. conns.perUserConns[username]++
  852. }
  853. // internal method, must be called within a locked block
  854. func (conns *ActiveConnections) removeUserConnection(username string) {
  855. if username == "" {
  856. return
  857. }
  858. if val, ok := conns.perUserConns[username]; ok {
  859. conns.perUserConns[username]--
  860. if val > 1 {
  861. return
  862. }
  863. delete(conns.perUserConns, username)
  864. }
  865. }
  866. // GetActiveSessions returns the number of active sessions for the given username.
  867. // We return the open sessions for any protocol
  868. func (conns *ActiveConnections) GetActiveSessions(username string) int {
  869. conns.RLock()
  870. defer conns.RUnlock()
  871. return conns.perUserConns[username]
  872. }
  873. // Add adds a new connection to the active ones
  874. func (conns *ActiveConnections) Add(c ActiveConnection) error {
  875. conns.Lock()
  876. defer conns.Unlock()
  877. if username := c.GetUsername(); username != "" {
  878. if maxSessions := c.GetMaxSessions(); maxSessions > 0 {
  879. if val := conns.perUserConns[username]; val >= maxSessions {
  880. return fmt.Errorf("too many open sessions: %d/%d", val, maxSessions)
  881. }
  882. }
  883. conns.addUserConnection(username)
  884. }
  885. conns.mapping[c.GetID()] = len(conns.connections)
  886. conns.connections = append(conns.connections, c)
  887. metric.UpdateActiveConnectionsSize(len(conns.connections))
  888. logger.Debug(c.GetProtocol(), c.GetID(), "connection added, local address %q, remote address %q, num open connections: %d",
  889. c.GetLocalAddress(), c.GetRemoteAddress(), len(conns.connections))
  890. return nil
  891. }
  892. // Swap replaces an existing connection with the given one.
  893. // This method is useful if you have to change some connection details
  894. // for example for FTP is used to update the connection once the user
  895. // authenticates
  896. func (conns *ActiveConnections) Swap(c ActiveConnection) error {
  897. conns.Lock()
  898. defer conns.Unlock()
  899. if idx, ok := conns.mapping[c.GetID()]; ok {
  900. conn := conns.connections[idx]
  901. conns.removeUserConnection(conn.GetUsername())
  902. if username := c.GetUsername(); username != "" {
  903. if maxSessions := c.GetMaxSessions(); maxSessions > 0 {
  904. if val, ok := conns.perUserConns[username]; ok && val >= maxSessions {
  905. conns.addUserConnection(conn.GetUsername())
  906. return fmt.Errorf("too many open sessions: %d/%d", val, maxSessions)
  907. }
  908. }
  909. conns.addUserConnection(username)
  910. }
  911. err := conn.CloseFS()
  912. conns.connections[idx] = c
  913. logger.Debug(logSender, c.GetID(), "connection swapped, close fs error: %v", err)
  914. conn = nil
  915. return nil
  916. }
  917. return errors.New("connection to swap not found")
  918. }
  919. // Remove removes a connection from the active ones
  920. func (conns *ActiveConnections) Remove(connectionID string) {
  921. conns.Lock()
  922. defer conns.Unlock()
  923. if idx, ok := conns.mapping[connectionID]; ok {
  924. conn := conns.connections[idx]
  925. err := conn.CloseFS()
  926. lastIdx := len(conns.connections) - 1
  927. conns.connections[idx] = conns.connections[lastIdx]
  928. conns.connections[lastIdx] = nil
  929. conns.connections = conns.connections[:lastIdx]
  930. delete(conns.mapping, connectionID)
  931. if idx != lastIdx {
  932. conns.mapping[conns.connections[idx].GetID()] = idx
  933. }
  934. conns.removeUserConnection(conn.GetUsername())
  935. metric.UpdateActiveConnectionsSize(lastIdx)
  936. logger.Debug(conn.GetProtocol(), conn.GetID(), "connection removed, local address %q, remote address %q close fs error: %v, num open connections: %d",
  937. conn.GetLocalAddress(), conn.GetRemoteAddress(), err, lastIdx)
  938. if conn.GetProtocol() == ProtocolFTP && conn.GetUsername() == "" && !slices.Contains(ftpLoginCommands, conn.GetCommand()) {
  939. ip := util.GetIPFromRemoteAddress(conn.GetRemoteAddress())
  940. logger.ConnectionFailedLog("", ip, dataprovider.LoginMethodNoAuthTried, ProtocolFTP,
  941. dataprovider.ErrNoAuthTried.Error())
  942. metric.AddNoAuthTried()
  943. AddDefenderEvent(ip, ProtocolFTP, HostEventNoLoginTried)
  944. dataprovider.ExecutePostLoginHook(&dataprovider.User{}, dataprovider.LoginMethodNoAuthTried, ip,
  945. ProtocolFTP, dataprovider.ErrNoAuthTried)
  946. plugin.Handler.NotifyLogEvent(notifier.LogEventTypeNoLoginTried, ProtocolFTP, "", ip, "",
  947. dataprovider.ErrNoAuthTried)
  948. }
  949. Config.checkPostDisconnectHook(conn.GetRemoteAddress(), conn.GetProtocol(), conn.GetUsername(),
  950. conn.GetID(), conn.GetConnectionTime())
  951. return
  952. }
  953. logger.Debug(logSender, "", "connection id %q to remove not found!", connectionID)
  954. }
  955. // Close closes an active connection.
  956. // It returns true on success
  957. func (conns *ActiveConnections) Close(connectionID, role string) bool {
  958. conns.RLock()
  959. var result bool
  960. if idx, ok := conns.mapping[connectionID]; ok {
  961. c := conns.connections[idx]
  962. if role == "" || c.GetRole() == role {
  963. defer func(conn ActiveConnection) {
  964. err := conn.Disconnect()
  965. logger.Debug(conn.GetProtocol(), conn.GetID(), "close connection requested, close err: %v", err)
  966. }(c)
  967. result = true
  968. }
  969. }
  970. conns.RUnlock()
  971. return result
  972. }
  973. // AddSSHConnection adds a new ssh connection to the active ones
  974. func (conns *ActiveConnections) AddSSHConnection(c *SSHConnection) {
  975. conns.Lock()
  976. defer conns.Unlock()
  977. conns.sshMapping[c.GetID()] = len(conns.sshConnections)
  978. conns.sshConnections = append(conns.sshConnections, c)
  979. logger.Debug(logSender, c.GetID(), "ssh connection added, num open connections: %d", len(conns.sshConnections))
  980. }
  981. // RemoveSSHConnection removes a connection from the active ones
  982. func (conns *ActiveConnections) RemoveSSHConnection(connectionID string) {
  983. conns.Lock()
  984. defer conns.Unlock()
  985. if idx, ok := conns.sshMapping[connectionID]; ok {
  986. lastIdx := len(conns.sshConnections) - 1
  987. conns.sshConnections[idx] = conns.sshConnections[lastIdx]
  988. conns.sshConnections[lastIdx] = nil
  989. conns.sshConnections = conns.sshConnections[:lastIdx]
  990. delete(conns.sshMapping, connectionID)
  991. if idx != lastIdx {
  992. conns.sshMapping[conns.sshConnections[idx].GetID()] = idx
  993. }
  994. logger.Debug(logSender, connectionID, "ssh connection removed, num open ssh connections: %d", lastIdx)
  995. return
  996. }
  997. logger.Warn(logSender, "", "ssh connection to remove with id %q not found!", connectionID)
  998. }
  999. func (conns *ActiveConnections) checkIdles() {
  1000. conns.RLock()
  1001. for _, sshConn := range conns.sshConnections {
  1002. idleTime := time.Since(sshConn.GetLastActivity())
  1003. if idleTime > Config.idleTimeoutAsDuration {
  1004. // we close an SSH connection if it has no active connections associated
  1005. idToMatch := fmt.Sprintf("_%s_", sshConn.GetID())
  1006. toClose := true
  1007. for _, conn := range conns.connections {
  1008. if strings.Contains(conn.GetID(), idToMatch) {
  1009. if time.Since(conn.GetLastActivity()) <= Config.idleTimeoutAsDuration {
  1010. toClose = false
  1011. break
  1012. }
  1013. }
  1014. }
  1015. if toClose {
  1016. defer func(c *SSHConnection) {
  1017. err := c.Close()
  1018. logger.Debug(logSender, c.GetID(), "close idle SSH connection, idle time: %v, close err: %v",
  1019. time.Since(c.GetLastActivity()), err)
  1020. }(sshConn)
  1021. }
  1022. }
  1023. }
  1024. for _, c := range conns.connections {
  1025. idleTime := time.Since(c.GetLastActivity())
  1026. isUnauthenticatedFTPUser := (c.GetProtocol() == ProtocolFTP && c.GetUsername() == "")
  1027. if idleTime > Config.idleTimeoutAsDuration || (isUnauthenticatedFTPUser && idleTime > Config.idleLoginTimeout) {
  1028. defer func(conn ActiveConnection) {
  1029. err := conn.Disconnect()
  1030. logger.Debug(conn.GetProtocol(), conn.GetID(), "close idle connection, idle time: %s, username: %q close err: %v",
  1031. time.Since(conn.GetLastActivity()), conn.GetUsername(), err)
  1032. }(c)
  1033. } else if !c.isAccessAllowed() {
  1034. defer func(conn ActiveConnection) {
  1035. err := conn.Disconnect()
  1036. logger.Info(conn.GetProtocol(), conn.GetID(), "access conditions not met for user: %q close connection err: %v",
  1037. conn.GetUsername(), err)
  1038. }(c)
  1039. }
  1040. }
  1041. conns.RUnlock()
  1042. }
  1043. func (conns *ActiveConnections) checkTransfers() {
  1044. if conns.transfersCheckStatus.Load() {
  1045. logger.Warn(logSender, "", "the previous transfer check is still running, skipping execution")
  1046. return
  1047. }
  1048. conns.transfersCheckStatus.Store(true)
  1049. defer conns.transfersCheckStatus.Store(false)
  1050. conns.RLock()
  1051. if len(conns.connections) < 2 {
  1052. conns.RUnlock()
  1053. return
  1054. }
  1055. var wg sync.WaitGroup
  1056. logger.Debug(logSender, "", "start concurrent transfers check")
  1057. // update the current size for transfers to monitors
  1058. for _, c := range conns.connections {
  1059. for _, t := range c.GetTransfers() {
  1060. if t.HasSizeLimit {
  1061. wg.Add(1)
  1062. go func(transfer ConnectionTransfer, connID string) {
  1063. defer wg.Done()
  1064. transfersChecker.UpdateTransferCurrentSizes(transfer.ULSize, transfer.DLSize, transfer.ID, connID)
  1065. }(t, c.GetID())
  1066. }
  1067. }
  1068. }
  1069. conns.RUnlock()
  1070. logger.Debug(logSender, "", "waiting for the update of the transfers current size")
  1071. wg.Wait()
  1072. logger.Debug(logSender, "", "getting overquota transfers")
  1073. overquotaTransfers := transfersChecker.GetOverquotaTransfers()
  1074. logger.Debug(logSender, "", "number of overquota transfers: %v", len(overquotaTransfers))
  1075. if len(overquotaTransfers) == 0 {
  1076. return
  1077. }
  1078. conns.RLock()
  1079. defer conns.RUnlock()
  1080. for _, c := range conns.connections {
  1081. for _, overquotaTransfer := range overquotaTransfers {
  1082. if c.GetID() == overquotaTransfer.ConnID {
  1083. logger.Info(logSender, c.GetID(), "user %q is overquota, try to close transfer id %v",
  1084. c.GetUsername(), overquotaTransfer.TransferID)
  1085. var err error
  1086. if overquotaTransfer.TransferType == TransferDownload {
  1087. err = getReadQuotaExceededError(c.GetProtocol())
  1088. } else {
  1089. err = getQuotaExceededError(c.GetProtocol())
  1090. }
  1091. c.SignalTransferClose(overquotaTransfer.TransferID, err)
  1092. }
  1093. }
  1094. }
  1095. logger.Debug(logSender, "", "transfers check completed")
  1096. }
  1097. // AddClientConnection stores a new client connection
  1098. func (conns *ActiveConnections) AddClientConnection(ipAddr string) {
  1099. conns.clients.add(ipAddr)
  1100. }
  1101. // RemoveClientConnection removes a disconnected client from the tracked ones
  1102. func (conns *ActiveConnections) RemoveClientConnection(ipAddr string) {
  1103. conns.clients.remove(ipAddr)
  1104. }
  1105. // GetClientConnections returns the total number of client connections
  1106. func (conns *ActiveConnections) GetClientConnections() int32 {
  1107. return conns.clients.getTotal()
  1108. }
  1109. // IsNewConnectionAllowed returns an error if the maximum number of concurrent allowed
  1110. // connections is exceeded or a whitelist is defined and the specified ipAddr is not listed
  1111. // or the service is shutting down
  1112. func (conns *ActiveConnections) IsNewConnectionAllowed(ipAddr, protocol string) error {
  1113. if isShuttingDown.Load() {
  1114. return ErrShuttingDown
  1115. }
  1116. if Config.allowList != nil {
  1117. isListed, _, err := Config.allowList.IsListed(ipAddr, protocol)
  1118. if err != nil {
  1119. logger.Error(logSender, "", "unable to query allow list, connection denied, ip %q, protocol %s, err: %v",
  1120. ipAddr, protocol, err)
  1121. return ErrConnectionDenied
  1122. }
  1123. if !isListed {
  1124. return ErrConnectionDenied
  1125. }
  1126. }
  1127. if Config.MaxTotalConnections == 0 && Config.MaxPerHostConnections == 0 {
  1128. return nil
  1129. }
  1130. if Config.MaxPerHostConnections > 0 {
  1131. if total := conns.clients.getTotalFrom(ipAddr); total > Config.MaxPerHostConnections {
  1132. if !AddDefenderEvent(ipAddr, protocol, HostEventLimitExceeded) {
  1133. logger.Warn(logSender, "", "connection denied, active connections from IP %q: %d/%d",
  1134. ipAddr, total, Config.MaxPerHostConnections)
  1135. return ErrConnectionDenied
  1136. }
  1137. logger.Info(logSender, "", "active connections from safe IP %q: %d", ipAddr, total)
  1138. }
  1139. }
  1140. if Config.MaxTotalConnections > 0 {
  1141. if total := conns.clients.getTotal(); total > int32(Config.MaxTotalConnections) {
  1142. logger.Info(logSender, "", "active client connections %d/%d", total, Config.MaxTotalConnections)
  1143. return ErrConnectionDenied
  1144. }
  1145. // on a single SFTP connection we could have multiple SFTP channels or commands
  1146. // so we check the estabilished connections too
  1147. conns.RLock()
  1148. defer conns.RUnlock()
  1149. if sess := len(conns.connections); sess >= Config.MaxTotalConnections {
  1150. logger.Info(logSender, "", "active client sessions %d/%d", sess, Config.MaxTotalConnections)
  1151. return ErrConnectionDenied
  1152. }
  1153. }
  1154. return nil
  1155. }
  1156. // GetStats returns stats for active connections
  1157. func (conns *ActiveConnections) GetStats(role string) []ConnectionStatus {
  1158. conns.RLock()
  1159. defer conns.RUnlock()
  1160. stats := make([]ConnectionStatus, 0, len(conns.connections))
  1161. node := dataprovider.GetNodeName()
  1162. for _, c := range conns.connections {
  1163. if role == "" || c.GetRole() == role {
  1164. stat := ConnectionStatus{
  1165. Username: c.GetUsername(),
  1166. ConnectionID: c.GetID(),
  1167. ClientVersion: c.GetClientVersion(),
  1168. RemoteAddress: c.GetRemoteAddress(),
  1169. ConnectionTime: util.GetTimeAsMsSinceEpoch(c.GetConnectionTime()),
  1170. LastActivity: util.GetTimeAsMsSinceEpoch(c.GetLastActivity()),
  1171. CurrentTime: util.GetTimeAsMsSinceEpoch(time.Now()),
  1172. Protocol: c.GetProtocol(),
  1173. Command: c.GetCommand(),
  1174. Transfers: c.GetTransfers(),
  1175. Node: node,
  1176. }
  1177. stats = append(stats, stat)
  1178. }
  1179. }
  1180. return stats
  1181. }
  1182. // ConnectionStatus returns the status for an active connection
  1183. type ConnectionStatus struct {
  1184. // Logged in username
  1185. Username string `json:"username"`
  1186. // Unique identifier for the connection
  1187. ConnectionID string `json:"connection_id"`
  1188. // client's version string
  1189. ClientVersion string `json:"client_version,omitempty"`
  1190. // Remote address for this connection
  1191. RemoteAddress string `json:"remote_address"`
  1192. // Connection time as unix timestamp in milliseconds
  1193. ConnectionTime int64 `json:"connection_time"`
  1194. // Last activity as unix timestamp in milliseconds
  1195. LastActivity int64 `json:"last_activity"`
  1196. // Current time as unix timestamp in milliseconds
  1197. CurrentTime int64 `json:"current_time"`
  1198. // Protocol for this connection
  1199. Protocol string `json:"protocol"`
  1200. // active uploads/downloads
  1201. Transfers []ConnectionTransfer `json:"active_transfers,omitempty"`
  1202. // SSH command or WebDAV method
  1203. Command string `json:"command,omitempty"`
  1204. // Node identifier, omitted for single node installations
  1205. Node string `json:"node,omitempty"`
  1206. }
  1207. // ActiveQuotaScan defines an active quota scan for a user
  1208. type ActiveQuotaScan struct {
  1209. // Username to which the quota scan refers
  1210. Username string `json:"username"`
  1211. // quota scan start time as unix timestamp in milliseconds
  1212. StartTime int64 `json:"start_time"`
  1213. Role string `json:"-"`
  1214. }
  1215. // ActiveVirtualFolderQuotaScan defines an active quota scan for a virtual folder
  1216. type ActiveVirtualFolderQuotaScan struct {
  1217. // folder name to which the quota scan refers
  1218. Name string `json:"name"`
  1219. // quota scan start time as unix timestamp in milliseconds
  1220. StartTime int64 `json:"start_time"`
  1221. }
  1222. // ActiveScans holds the active quota scans
  1223. type ActiveScans struct {
  1224. sync.RWMutex
  1225. UserScans []ActiveQuotaScan
  1226. FolderScans []ActiveVirtualFolderQuotaScan
  1227. }
  1228. // GetUsersQuotaScans returns the active users quota scans
  1229. func (s *ActiveScans) GetUsersQuotaScans(role string) []ActiveQuotaScan {
  1230. s.RLock()
  1231. defer s.RUnlock()
  1232. scans := make([]ActiveQuotaScan, 0, len(s.UserScans))
  1233. for _, scan := range s.UserScans {
  1234. if role == "" || role == scan.Role {
  1235. scans = append(scans, ActiveQuotaScan{
  1236. Username: scan.Username,
  1237. StartTime: scan.StartTime,
  1238. })
  1239. }
  1240. }
  1241. return scans
  1242. }
  1243. // AddUserQuotaScan adds a user to the ones with active quota scans.
  1244. // Returns false if the user has a quota scan already running
  1245. func (s *ActiveScans) AddUserQuotaScan(username, role string) bool {
  1246. s.Lock()
  1247. defer s.Unlock()
  1248. for _, scan := range s.UserScans {
  1249. if scan.Username == username {
  1250. return false
  1251. }
  1252. }
  1253. s.UserScans = append(s.UserScans, ActiveQuotaScan{
  1254. Username: username,
  1255. StartTime: util.GetTimeAsMsSinceEpoch(time.Now()),
  1256. Role: role,
  1257. })
  1258. return true
  1259. }
  1260. // RemoveUserQuotaScan removes a user from the ones with active quota scans.
  1261. // Returns false if the user has no active quota scans
  1262. func (s *ActiveScans) RemoveUserQuotaScan(username string) bool {
  1263. s.Lock()
  1264. defer s.Unlock()
  1265. for idx, scan := range s.UserScans {
  1266. if scan.Username == username {
  1267. lastIdx := len(s.UserScans) - 1
  1268. s.UserScans[idx] = s.UserScans[lastIdx]
  1269. s.UserScans = s.UserScans[:lastIdx]
  1270. return true
  1271. }
  1272. }
  1273. return false
  1274. }
  1275. // GetVFoldersQuotaScans returns the active quota scans for virtual folders
  1276. func (s *ActiveScans) GetVFoldersQuotaScans() []ActiveVirtualFolderQuotaScan {
  1277. s.RLock()
  1278. defer s.RUnlock()
  1279. scans := make([]ActiveVirtualFolderQuotaScan, len(s.FolderScans))
  1280. copy(scans, s.FolderScans)
  1281. return scans
  1282. }
  1283. // AddVFolderQuotaScan adds a virtual folder to the ones with active quota scans.
  1284. // Returns false if the folder has a quota scan already running
  1285. func (s *ActiveScans) AddVFolderQuotaScan(folderName string) bool {
  1286. s.Lock()
  1287. defer s.Unlock()
  1288. for _, scan := range s.FolderScans {
  1289. if scan.Name == folderName {
  1290. return false
  1291. }
  1292. }
  1293. s.FolderScans = append(s.FolderScans, ActiveVirtualFolderQuotaScan{
  1294. Name: folderName,
  1295. StartTime: util.GetTimeAsMsSinceEpoch(time.Now()),
  1296. })
  1297. return true
  1298. }
  1299. // RemoveVFolderQuotaScan removes a folder from the ones with active quota scans.
  1300. // Returns false if the folder has no active quota scans
  1301. func (s *ActiveScans) RemoveVFolderQuotaScan(folderName string) bool {
  1302. s.Lock()
  1303. defer s.Unlock()
  1304. for idx, scan := range s.FolderScans {
  1305. if scan.Name == folderName {
  1306. lastIdx := len(s.FolderScans) - 1
  1307. s.FolderScans[idx] = s.FolderScans[lastIdx]
  1308. s.FolderScans = s.FolderScans[:lastIdx]
  1309. return true
  1310. }
  1311. }
  1312. return false
  1313. }