common.go 48 KB

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