common.go 50 KB

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