common.go 48 KB

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