common.go 48 KB

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