common.go 50 KB

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