common.go 47 KB

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