common.go 46 KB

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