common.go 51 KB

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