common.go 46 KB

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