common.go 50 KB

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