common.go 50 KB

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