common.go 49 KB

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