common.go 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985
  1. // Package common defines code shared among file transfer packages and protocols
  2. package common
  3. import (
  4. "context"
  5. "errors"
  6. "fmt"
  7. "net"
  8. "net/http"
  9. "net/url"
  10. "os"
  11. "os/exec"
  12. "path/filepath"
  13. "strings"
  14. "sync"
  15. "sync/atomic"
  16. "time"
  17. "github.com/pires/go-proxyproto"
  18. "github.com/drakkan/sftpgo/dataprovider"
  19. "github.com/drakkan/sftpgo/httpclient"
  20. "github.com/drakkan/sftpgo/logger"
  21. "github.com/drakkan/sftpgo/metrics"
  22. "github.com/drakkan/sftpgo/utils"
  23. "github.com/drakkan/sftpgo/vfs"
  24. )
  25. // constants
  26. const (
  27. logSender = "common"
  28. uploadLogSender = "Upload"
  29. downloadLogSender = "Download"
  30. renameLogSender = "Rename"
  31. rmdirLogSender = "Rmdir"
  32. mkdirLogSender = "Mkdir"
  33. symlinkLogSender = "Symlink"
  34. removeLogSender = "Remove"
  35. chownLogSender = "Chown"
  36. chmodLogSender = "Chmod"
  37. chtimesLogSender = "Chtimes"
  38. truncateLogSender = "Truncate"
  39. operationDownload = "download"
  40. operationUpload = "upload"
  41. operationDelete = "delete"
  42. // Pre-download action name
  43. OperationPreDownload = "pre-download"
  44. // Pre-upload action name
  45. OperationPreUpload = "pre-upload"
  46. operationPreDelete = "pre-delete"
  47. operationRename = "rename"
  48. // SSH command action name
  49. OperationSSHCmd = "ssh_cmd"
  50. chtimesFormat = "2006-01-02T15:04:05" // YYYY-MM-DDTHH:MM:SS
  51. idleTimeoutCheckInterval = 3 * time.Minute
  52. )
  53. // Stat flags
  54. const (
  55. StatAttrUIDGID = 1
  56. StatAttrPerms = 2
  57. StatAttrTimes = 4
  58. StatAttrSize = 8
  59. )
  60. // Transfer types
  61. const (
  62. TransferUpload = iota
  63. TransferDownload
  64. )
  65. // Supported protocols
  66. const (
  67. ProtocolSFTP = "SFTP"
  68. ProtocolSCP = "SCP"
  69. ProtocolSSH = "SSH"
  70. ProtocolFTP = "FTP"
  71. ProtocolWebDAV = "DAV"
  72. ProtocolHTTP = "HTTP"
  73. )
  74. // Upload modes
  75. const (
  76. UploadModeStandard = iota
  77. UploadModeAtomic
  78. UploadModeAtomicWithResume
  79. )
  80. func init() {
  81. Connections.clients = clientsMap{
  82. clients: make(map[string]int),
  83. }
  84. }
  85. // errors definitions
  86. var (
  87. ErrPermissionDenied = errors.New("permission denied")
  88. ErrNotExist = errors.New("no such file or directory")
  89. ErrOpUnsupported = errors.New("operation unsupported")
  90. ErrGenericFailure = errors.New("failure")
  91. ErrQuotaExceeded = errors.New("denying write due to space limit")
  92. ErrSkipPermissionsCheck = errors.New("permission check skipped")
  93. ErrConnectionDenied = errors.New("you are not allowed to connect")
  94. ErrNoBinding = errors.New("no binding configured")
  95. ErrCrtRevoked = errors.New("your certificate has been revoked")
  96. ErrNoCredentials = errors.New("no credential provided")
  97. ErrInternalFailure = errors.New("internal failure")
  98. errNoTransfer = errors.New("requested transfer not found")
  99. errTransferMismatch = errors.New("transfer mismatch")
  100. )
  101. var (
  102. // Config is the configuration for the supported protocols
  103. Config Configuration
  104. // Connections is the list of active connections
  105. Connections ActiveConnections
  106. // QuotaScans is the list of active quota scans
  107. QuotaScans ActiveScans
  108. idleTimeoutTicker *time.Ticker
  109. idleTimeoutTickerDone chan bool
  110. supportedProtocols = []string{ProtocolSFTP, ProtocolSCP, ProtocolSSH, ProtocolFTP, ProtocolWebDAV, ProtocolHTTP}
  111. // the map key is the protocol, for each protocol we can have multiple rate limiters
  112. rateLimiters map[string][]*rateLimiter
  113. )
  114. // Initialize sets the common configuration
  115. func Initialize(c Configuration) error {
  116. Config = c
  117. Config.idleLoginTimeout = 2 * time.Minute
  118. Config.idleTimeoutAsDuration = time.Duration(Config.IdleTimeout) * time.Minute
  119. if Config.IdleTimeout > 0 {
  120. startIdleTimeoutTicker(idleTimeoutCheckInterval)
  121. }
  122. Config.defender = nil
  123. if c.DefenderConfig.Enabled {
  124. defender, err := newInMemoryDefender(&c.DefenderConfig)
  125. if err != nil {
  126. return fmt.Errorf("defender initialization error: %v", err)
  127. }
  128. logger.Info(logSender, "", "defender initialized with config %+v", c.DefenderConfig)
  129. Config.defender = defender
  130. }
  131. rateLimiters = make(map[string][]*rateLimiter)
  132. for _, rlCfg := range c.RateLimitersConfig {
  133. if rlCfg.isEnabled() {
  134. if err := rlCfg.validate(); err != nil {
  135. return fmt.Errorf("rate limiters initialization error: %v", err)
  136. }
  137. rateLimiter := rlCfg.getLimiter()
  138. for _, protocol := range rlCfg.Protocols {
  139. rateLimiters[protocol] = append(rateLimiters[protocol], rateLimiter)
  140. }
  141. }
  142. }
  143. vfs.SetTempPath(c.TempPath)
  144. dataprovider.SetTempPath(c.TempPath)
  145. return nil
  146. }
  147. // LimitRate blocks until all the configured rate limiters
  148. // allow one event to happen.
  149. // It returns an error if the time to wait exceeds the max
  150. // allowed delay
  151. func LimitRate(protocol, ip string) (time.Duration, error) {
  152. for _, limiter := range rateLimiters[protocol] {
  153. if delay, err := limiter.Wait(ip); err != nil {
  154. logger.Debug(logSender, "", "protocol %v ip %v: %v", protocol, ip, err)
  155. return delay, err
  156. }
  157. }
  158. return 0, nil
  159. }
  160. // ReloadDefender reloads the defender's block and safe lists
  161. func ReloadDefender() error {
  162. if Config.defender == nil {
  163. return nil
  164. }
  165. return Config.defender.Reload()
  166. }
  167. // IsBanned returns true if the specified IP address is banned
  168. func IsBanned(ip string) bool {
  169. if Config.defender == nil {
  170. return false
  171. }
  172. return Config.defender.IsBanned(ip)
  173. }
  174. // GetDefenderBanTime returns the ban time for the given IP
  175. // or nil if the IP is not banned or the defender is disabled
  176. func GetDefenderBanTime(ip string) *time.Time {
  177. if Config.defender == nil {
  178. return nil
  179. }
  180. return Config.defender.GetBanTime(ip)
  181. }
  182. // GetDefenderHosts returns hosts that are banned or for which some violations have been detected
  183. func GetDefenderHosts() []*DefenderEntry {
  184. if Config.defender == nil {
  185. return nil
  186. }
  187. return Config.defender.GetHosts()
  188. }
  189. // GetDefenderHost returns a defender host by ip, if any
  190. func GetDefenderHost(ip string) (*DefenderEntry, error) {
  191. if Config.defender == nil {
  192. return nil, errors.New("defender is disabled")
  193. }
  194. return Config.defender.GetHost(ip)
  195. }
  196. // DeleteDefenderHost removes the specified IP address from the defender lists
  197. func DeleteDefenderHost(ip string) bool {
  198. if Config.defender == nil {
  199. return false
  200. }
  201. return Config.defender.DeleteHost(ip)
  202. }
  203. // GetDefenderScore returns the score for the given IP
  204. func GetDefenderScore(ip string) int {
  205. if Config.defender == nil {
  206. return 0
  207. }
  208. return Config.defender.GetScore(ip)
  209. }
  210. // AddDefenderEvent adds the specified defender event for the given IP
  211. func AddDefenderEvent(ip string, event HostEvent) {
  212. if Config.defender == nil {
  213. return
  214. }
  215. Config.defender.AddEvent(ip, event)
  216. }
  217. // the ticker cannot be started/stopped from multiple goroutines
  218. func startIdleTimeoutTicker(duration time.Duration) {
  219. stopIdleTimeoutTicker()
  220. idleTimeoutTicker = time.NewTicker(duration)
  221. idleTimeoutTickerDone = make(chan bool)
  222. go func() {
  223. for {
  224. select {
  225. case <-idleTimeoutTickerDone:
  226. return
  227. case <-idleTimeoutTicker.C:
  228. Connections.checkIdles()
  229. }
  230. }
  231. }()
  232. }
  233. func stopIdleTimeoutTicker() {
  234. if idleTimeoutTicker != nil {
  235. idleTimeoutTicker.Stop()
  236. idleTimeoutTickerDone <- true
  237. idleTimeoutTicker = nil
  238. }
  239. }
  240. // ActiveTransfer defines the interface for the current active transfers
  241. type ActiveTransfer interface {
  242. GetID() uint64
  243. GetType() int
  244. GetSize() int64
  245. GetVirtualPath() string
  246. GetStartTime() time.Time
  247. SignalClose()
  248. Truncate(fsPath string, size int64) (int64, error)
  249. GetRealFsPath(fsPath string) string
  250. }
  251. // ActiveConnection defines the interface for the current active connections
  252. type ActiveConnection interface {
  253. GetID() string
  254. GetUsername() string
  255. GetRemoteAddress() string
  256. GetClientVersion() string
  257. GetProtocol() string
  258. GetConnectionTime() time.Time
  259. GetLastActivity() time.Time
  260. GetCommand() string
  261. Disconnect() error
  262. AddTransfer(t ActiveTransfer)
  263. RemoveTransfer(t ActiveTransfer)
  264. GetTransfers() []ConnectionTransfer
  265. CloseFS() error
  266. }
  267. // StatAttributes defines the attributes for set stat commands
  268. type StatAttributes struct {
  269. Mode os.FileMode
  270. Atime time.Time
  271. Mtime time.Time
  272. UID int
  273. GID int
  274. Flags int
  275. Size int64
  276. }
  277. // ConnectionTransfer defines the trasfer details to expose
  278. type ConnectionTransfer struct {
  279. ID uint64 `json:"-"`
  280. OperationType string `json:"operation_type"`
  281. StartTime int64 `json:"start_time"`
  282. Size int64 `json:"size"`
  283. VirtualPath string `json:"path"`
  284. }
  285. func (t *ConnectionTransfer) getConnectionTransferAsString() string {
  286. result := ""
  287. switch t.OperationType {
  288. case operationUpload:
  289. result += "UL "
  290. case operationDownload:
  291. result += "DL "
  292. }
  293. result += fmt.Sprintf("%#v ", t.VirtualPath)
  294. if t.Size > 0 {
  295. elapsed := time.Since(utils.GetTimeFromMsecSinceEpoch(t.StartTime))
  296. speed := float64(t.Size) / float64(utils.GetTimeAsMsSinceEpoch(time.Now())-t.StartTime)
  297. result += fmt.Sprintf("Size: %#v Elapsed: %#v Speed: \"%.1f KB/s\"", utils.ByteCountIEC(t.Size),
  298. utils.GetDurationAsString(elapsed), speed)
  299. }
  300. return result
  301. }
  302. // Configuration defines configuration parameters common to all supported protocols
  303. type Configuration struct {
  304. // Maximum idle timeout as minutes. If a client is idle for a time that exceeds this setting it will be disconnected.
  305. // 0 means disabled
  306. IdleTimeout int `json:"idle_timeout" mapstructure:"idle_timeout"`
  307. // UploadMode 0 means standard, the files are uploaded directly to the requested path.
  308. // 1 means atomic: the files are uploaded to a temporary path and renamed to the requested path
  309. // when the client ends the upload. Atomic mode avoid problems such as a web server that
  310. // serves partial files when the files are being uploaded.
  311. // In atomic mode if there is an upload error the temporary file is deleted and so the requested
  312. // upload path will not contain a partial file.
  313. // 2 means atomic with resume support: as atomic but if there is an upload error the temporary
  314. // file is renamed to the requested path and not deleted, this way a client can reconnect and resume
  315. // the upload.
  316. UploadMode int `json:"upload_mode" mapstructure:"upload_mode"`
  317. // Actions to execute for SFTP file operations and SSH commands
  318. Actions ProtocolActions `json:"actions" mapstructure:"actions"`
  319. // SetstatMode 0 means "normal mode": requests for changing permissions and owner/group are executed.
  320. // 1 means "ignore mode": requests for changing permissions and owner/group are silently ignored.
  321. // 2 means "ignore mode for cloud fs": requests for changing permissions and owner/group/time are
  322. // silently ignored for cloud based filesystem such as S3, GCS, Azure Blob
  323. SetstatMode int `json:"setstat_mode" mapstructure:"setstat_mode"`
  324. // TempPath defines the path for temporary files such as those used for atomic uploads or file pipes.
  325. // If you set this option you must make sure that the defined path exists, is accessible for writing
  326. // by the user running SFTPGo, and is on the same filesystem as the users home directories otherwise
  327. // the renaming for atomic uploads will become a copy and therefore may take a long time.
  328. // The temporary files are not namespaced. The default is generally fine. Leave empty for the default.
  329. TempPath string `json:"temp_path" mapstructure:"temp_path"`
  330. // Support for HAProxy PROXY protocol.
  331. // If you are running SFTPGo behind a proxy server such as HAProxy, AWS ELB or NGNIX, you can enable
  332. // the proxy protocol. It provides a convenient way to safely transport connection information
  333. // such as a client's address across multiple layers of NAT or TCP proxies to get the real
  334. // client IP address instead of the proxy IP. Both protocol versions 1 and 2 are supported.
  335. // - 0 means disabled
  336. // - 1 means proxy protocol enabled. Proxy header will be used and requests without proxy header will be accepted.
  337. // - 2 means proxy protocol required. Proxy header will be used and requests without proxy header will be rejected.
  338. // If the proxy protocol is enabled in SFTPGo then you have to enable the protocol in your proxy configuration too,
  339. // for example for HAProxy add "send-proxy" or "send-proxy-v2" to each server configuration line.
  340. ProxyProtocol int `json:"proxy_protocol" mapstructure:"proxy_protocol"`
  341. // List of IP addresses and IP ranges allowed to send the proxy header.
  342. // If proxy protocol is set to 1 and we receive a proxy header from an IP that is not in the list then the
  343. // connection will be accepted and the header will be ignored.
  344. // If proxy protocol is set to 2 and we receive a proxy header from an IP that is not in the list then the
  345. // connection will be rejected.
  346. ProxyAllowed []string `json:"proxy_allowed" mapstructure:"proxy_allowed"`
  347. // Absolute path to an external program or an HTTP URL to invoke as soon as SFTPGo starts.
  348. // If you define an HTTP URL it will be invoked using a `GET` request.
  349. // Please note that SFTPGo services may not yet be available when this hook is run.
  350. // Leave empty do disable.
  351. StartupHook string `json:"startup_hook" mapstructure:"startup_hook"`
  352. // Absolute path to an external program or an HTTP URL to invoke after a user connects
  353. // and before he tries to login. It allows you to reject the connection based on the source
  354. // ip address. Leave empty do disable.
  355. PostConnectHook string `json:"post_connect_hook" mapstructure:"post_connect_hook"`
  356. // Maximum number of concurrent client connections. 0 means unlimited
  357. MaxTotalConnections int `json:"max_total_connections" mapstructure:"max_total_connections"`
  358. // Maximum number of concurrent client connections from the same host (IP). 0 means unlimited
  359. MaxPerHostConnections int `json:"max_per_host_connections" mapstructure:"max_per_host_connections"`
  360. // Defender configuration
  361. DefenderConfig DefenderConfig `json:"defender" mapstructure:"defender"`
  362. // Rate limiter configurations
  363. RateLimitersConfig []RateLimiterConfig `json:"rate_limiters" mapstructure:"rate_limiters"`
  364. idleTimeoutAsDuration time.Duration
  365. idleLoginTimeout time.Duration
  366. defender Defender
  367. }
  368. // IsAtomicUploadEnabled returns true if atomic upload is enabled
  369. func (c *Configuration) IsAtomicUploadEnabled() bool {
  370. return c.UploadMode == UploadModeAtomic || c.UploadMode == UploadModeAtomicWithResume
  371. }
  372. // GetProxyListener returns a wrapper for the given listener that supports the
  373. // HAProxy Proxy Protocol or nil if the proxy protocol is not configured
  374. func (c *Configuration) GetProxyListener(listener net.Listener) (*proxyproto.Listener, error) {
  375. var proxyListener *proxyproto.Listener
  376. var err error
  377. if c.ProxyProtocol > 0 {
  378. var policyFunc func(upstream net.Addr) (proxyproto.Policy, error)
  379. if c.ProxyProtocol == 1 && len(c.ProxyAllowed) > 0 {
  380. policyFunc, err = proxyproto.LaxWhiteListPolicy(c.ProxyAllowed)
  381. if err != nil {
  382. return nil, err
  383. }
  384. }
  385. if c.ProxyProtocol == 2 {
  386. if len(c.ProxyAllowed) == 0 {
  387. policyFunc = func(upstream net.Addr) (proxyproto.Policy, error) {
  388. return proxyproto.REQUIRE, nil
  389. }
  390. } else {
  391. policyFunc, err = proxyproto.StrictWhiteListPolicy(c.ProxyAllowed)
  392. if err != nil {
  393. return nil, err
  394. }
  395. }
  396. }
  397. proxyListener = &proxyproto.Listener{
  398. Listener: listener,
  399. Policy: policyFunc,
  400. }
  401. }
  402. return proxyListener, nil
  403. }
  404. // ExecuteStartupHook runs the startup hook if defined
  405. func (c *Configuration) ExecuteStartupHook() error {
  406. if c.StartupHook == "" {
  407. return nil
  408. }
  409. if strings.HasPrefix(c.StartupHook, "http") {
  410. var url *url.URL
  411. url, err := url.Parse(c.StartupHook)
  412. if err != nil {
  413. logger.Warn(logSender, "", "Invalid startup hook %#v: %v", c.StartupHook, err)
  414. return err
  415. }
  416. startTime := time.Now()
  417. resp, err := httpclient.RetryableGet(url.String())
  418. if err != nil {
  419. logger.Warn(logSender, "", "Error executing startup hook: %v", err)
  420. return err
  421. }
  422. defer resp.Body.Close()
  423. logger.Debug(logSender, "", "Startup hook executed, elapsed: %v, response code: %v", time.Since(startTime), resp.StatusCode)
  424. return nil
  425. }
  426. if !filepath.IsAbs(c.StartupHook) {
  427. err := fmt.Errorf("invalid startup hook %#v", c.StartupHook)
  428. logger.Warn(logSender, "", "Invalid startup hook %#v", c.StartupHook)
  429. return err
  430. }
  431. startTime := time.Now()
  432. ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
  433. defer cancel()
  434. cmd := exec.CommandContext(ctx, c.StartupHook)
  435. err := cmd.Run()
  436. logger.Debug(logSender, "", "Startup hook executed, elapsed: %v, error: %v", time.Since(startTime), err)
  437. return nil
  438. }
  439. // ExecutePostConnectHook executes the post connect hook if defined
  440. func (c *Configuration) ExecutePostConnectHook(ipAddr, protocol string) error {
  441. if c.PostConnectHook == "" {
  442. return nil
  443. }
  444. if strings.HasPrefix(c.PostConnectHook, "http") {
  445. var url *url.URL
  446. url, err := url.Parse(c.PostConnectHook)
  447. if err != nil {
  448. logger.Warn(protocol, "", "Login from ip %#v denied, invalid post connect hook %#v: %v",
  449. ipAddr, c.PostConnectHook, err)
  450. return err
  451. }
  452. q := url.Query()
  453. q.Add("ip", ipAddr)
  454. q.Add("protocol", protocol)
  455. url.RawQuery = q.Encode()
  456. resp, err := httpclient.RetryableGet(url.String())
  457. if err != nil {
  458. logger.Warn(protocol, "", "Login from ip %#v denied, error executing post connect hook: %v", ipAddr, err)
  459. return err
  460. }
  461. defer resp.Body.Close()
  462. if resp.StatusCode != http.StatusOK {
  463. logger.Warn(protocol, "", "Login from ip %#v denied, post connect hook response code: %v", ipAddr, resp.StatusCode)
  464. return errUnexpectedHTTResponse
  465. }
  466. return nil
  467. }
  468. if !filepath.IsAbs(c.PostConnectHook) {
  469. err := fmt.Errorf("invalid post connect hook %#v", c.PostConnectHook)
  470. logger.Warn(protocol, "", "Login from ip %#v denied: %v", ipAddr, err)
  471. return err
  472. }
  473. ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
  474. defer cancel()
  475. cmd := exec.CommandContext(ctx, c.PostConnectHook)
  476. cmd.Env = append(os.Environ(),
  477. fmt.Sprintf("SFTPGO_CONNECTION_IP=%v", ipAddr),
  478. fmt.Sprintf("SFTPGO_CONNECTION_PROTOCOL=%v", protocol))
  479. err := cmd.Run()
  480. if err != nil {
  481. logger.Warn(protocol, "", "Login from ip %#v denied, connect hook error: %v", ipAddr, err)
  482. }
  483. return err
  484. }
  485. // SSHConnection defines an ssh connection.
  486. // Each SSH connection can open several channels for SFTP or SSH commands
  487. type SSHConnection struct {
  488. id string
  489. conn net.Conn
  490. lastActivity int64
  491. }
  492. // NewSSHConnection returns a new SSHConnection
  493. func NewSSHConnection(id string, conn net.Conn) *SSHConnection {
  494. return &SSHConnection{
  495. id: id,
  496. conn: conn,
  497. lastActivity: time.Now().UnixNano(),
  498. }
  499. }
  500. // GetID returns the ID for this SSHConnection
  501. func (c *SSHConnection) GetID() string {
  502. return c.id
  503. }
  504. // UpdateLastActivity updates last activity for this connection
  505. func (c *SSHConnection) UpdateLastActivity() {
  506. atomic.StoreInt64(&c.lastActivity, time.Now().UnixNano())
  507. }
  508. // GetLastActivity returns the last connection activity
  509. func (c *SSHConnection) GetLastActivity() time.Time {
  510. return time.Unix(0, atomic.LoadInt64(&c.lastActivity))
  511. }
  512. // Close closes the underlying network connection
  513. func (c *SSHConnection) Close() error {
  514. return c.conn.Close()
  515. }
  516. // ActiveConnections holds the currect active connections with the associated transfers
  517. type ActiveConnections struct {
  518. // clients contains both authenticated and estabilished connections and the ones waiting
  519. // for authentication
  520. clients clientsMap
  521. sync.RWMutex
  522. connections []ActiveConnection
  523. sshConnections []*SSHConnection
  524. }
  525. // GetActiveSessions returns the number of active sessions for the given username.
  526. // We return the open sessions for any protocol
  527. func (conns *ActiveConnections) GetActiveSessions(username string) int {
  528. conns.RLock()
  529. defer conns.RUnlock()
  530. numSessions := 0
  531. for _, c := range conns.connections {
  532. if c.GetUsername() == username {
  533. numSessions++
  534. }
  535. }
  536. return numSessions
  537. }
  538. // Add adds a new connection to the active ones
  539. func (conns *ActiveConnections) Add(c ActiveConnection) {
  540. conns.Lock()
  541. defer conns.Unlock()
  542. conns.connections = append(conns.connections, c)
  543. metrics.UpdateActiveConnectionsSize(len(conns.connections))
  544. logger.Debug(c.GetProtocol(), c.GetID(), "connection added, num open connections: %v", len(conns.connections))
  545. }
  546. // Swap replaces an existing connection with the given one.
  547. // This method is useful if you have to change some connection details
  548. // for example for FTP is used to update the connection once the user
  549. // authenticates
  550. func (conns *ActiveConnections) Swap(c ActiveConnection) error {
  551. conns.Lock()
  552. defer conns.Unlock()
  553. for idx, conn := range conns.connections {
  554. if conn.GetID() == c.GetID() {
  555. conn = nil
  556. conns.connections[idx] = c
  557. return nil
  558. }
  559. }
  560. return errors.New("connection to swap not found")
  561. }
  562. // Remove removes a connection from the active ones
  563. func (conns *ActiveConnections) Remove(connectionID string) {
  564. conns.Lock()
  565. defer conns.Unlock()
  566. for idx, conn := range conns.connections {
  567. if conn.GetID() == connectionID {
  568. err := conn.CloseFS()
  569. lastIdx := len(conns.connections) - 1
  570. conns.connections[idx] = conns.connections[lastIdx]
  571. conns.connections[lastIdx] = nil
  572. conns.connections = conns.connections[:lastIdx]
  573. metrics.UpdateActiveConnectionsSize(lastIdx)
  574. logger.Debug(conn.GetProtocol(), conn.GetID(), "connection removed, close fs error: %v, num open connections: %v",
  575. err, lastIdx)
  576. return
  577. }
  578. }
  579. logger.Warn(logSender, "", "connection id %#v to remove not found!", connectionID)
  580. }
  581. // Close closes an active connection.
  582. // It returns true on success
  583. func (conns *ActiveConnections) Close(connectionID string) bool {
  584. conns.RLock()
  585. result := false
  586. for _, c := range conns.connections {
  587. if c.GetID() == connectionID {
  588. defer func(conn ActiveConnection) {
  589. err := conn.Disconnect()
  590. logger.Debug(conn.GetProtocol(), conn.GetID(), "close connection requested, close err: %v", err)
  591. }(c)
  592. result = true
  593. break
  594. }
  595. }
  596. conns.RUnlock()
  597. return result
  598. }
  599. // AddSSHConnection adds a new ssh connection to the active ones
  600. func (conns *ActiveConnections) AddSSHConnection(c *SSHConnection) {
  601. conns.Lock()
  602. defer conns.Unlock()
  603. conns.sshConnections = append(conns.sshConnections, c)
  604. logger.Debug(logSender, c.GetID(), "ssh connection added, num open connections: %v", len(conns.sshConnections))
  605. }
  606. // RemoveSSHConnection removes a connection from the active ones
  607. func (conns *ActiveConnections) RemoveSSHConnection(connectionID string) {
  608. conns.Lock()
  609. defer conns.Unlock()
  610. for idx, conn := range conns.sshConnections {
  611. if conn.GetID() == connectionID {
  612. lastIdx := len(conns.sshConnections) - 1
  613. conns.sshConnections[idx] = conns.sshConnections[lastIdx]
  614. conns.sshConnections[lastIdx] = nil
  615. conns.sshConnections = conns.sshConnections[:lastIdx]
  616. logger.Debug(logSender, conn.GetID(), "ssh connection removed, num open ssh connections: %v", lastIdx)
  617. return
  618. }
  619. }
  620. logger.Warn(logSender, "", "ssh connection to remove with id %#v not found!", connectionID)
  621. }
  622. func (conns *ActiveConnections) checkIdles() {
  623. conns.RLock()
  624. for _, sshConn := range conns.sshConnections {
  625. idleTime := time.Since(sshConn.GetLastActivity())
  626. if idleTime > Config.idleTimeoutAsDuration {
  627. // we close the an ssh connection if it has no active connections associated
  628. idToMatch := fmt.Sprintf("_%v_", sshConn.GetID())
  629. toClose := true
  630. for _, conn := range conns.connections {
  631. if strings.Contains(conn.GetID(), idToMatch) {
  632. toClose = false
  633. break
  634. }
  635. }
  636. if toClose {
  637. defer func(c *SSHConnection) {
  638. err := c.Close()
  639. logger.Debug(logSender, c.GetID(), "close idle SSH connection, idle time: %v, close err: %v",
  640. time.Since(c.GetLastActivity()), err)
  641. }(sshConn)
  642. }
  643. }
  644. }
  645. for _, c := range conns.connections {
  646. idleTime := time.Since(c.GetLastActivity())
  647. isUnauthenticatedFTPUser := (c.GetProtocol() == ProtocolFTP && c.GetUsername() == "")
  648. if idleTime > Config.idleTimeoutAsDuration || (isUnauthenticatedFTPUser && idleTime > Config.idleLoginTimeout) {
  649. defer func(conn ActiveConnection, isFTPNoAuth bool) {
  650. err := conn.Disconnect()
  651. logger.Debug(conn.GetProtocol(), conn.GetID(), "close idle connection, idle time: %v, username: %#v close err: %v",
  652. time.Since(conn.GetLastActivity()), conn.GetUsername(), err)
  653. if isFTPNoAuth {
  654. ip := utils.GetIPFromRemoteAddress(c.GetRemoteAddress())
  655. logger.ConnectionFailedLog("", ip, dataprovider.LoginMethodNoAuthTryed, c.GetProtocol(), "client idle")
  656. metrics.AddNoAuthTryed()
  657. AddDefenderEvent(ip, HostEventNoLoginTried)
  658. dataprovider.ExecutePostLoginHook(&dataprovider.User{}, dataprovider.LoginMethodNoAuthTryed, ip, c.GetProtocol(),
  659. dataprovider.ErrNoAuthTryed)
  660. }
  661. }(c, isUnauthenticatedFTPUser)
  662. }
  663. }
  664. conns.RUnlock()
  665. }
  666. // AddClientConnection stores a new client connection
  667. func (conns *ActiveConnections) AddClientConnection(ipAddr string) {
  668. conns.clients.add(ipAddr)
  669. }
  670. // RemoveClientConnection removes a disconnected client from the tracked ones
  671. func (conns *ActiveConnections) RemoveClientConnection(ipAddr string) {
  672. conns.clients.remove(ipAddr)
  673. }
  674. // GetClientConnections returns the total number of client connections
  675. func (conns *ActiveConnections) GetClientConnections() int32 {
  676. return conns.clients.getTotal()
  677. }
  678. // IsNewConnectionAllowed returns false if the maximum number of concurrent allowed connections is exceeded
  679. func (conns *ActiveConnections) IsNewConnectionAllowed(ipAddr string) bool {
  680. if Config.MaxTotalConnections == 0 && Config.MaxPerHostConnections == 0 {
  681. return true
  682. }
  683. if Config.MaxPerHostConnections > 0 {
  684. if total := conns.clients.getTotalFrom(ipAddr); total > Config.MaxPerHostConnections {
  685. logger.Debug(logSender, "", "active connections from %v %v/%v", ipAddr, total, Config.MaxPerHostConnections)
  686. AddDefenderEvent(ipAddr, HostEventLimitExceeded)
  687. return false
  688. }
  689. }
  690. if Config.MaxTotalConnections > 0 {
  691. if total := conns.clients.getTotal(); total > int32(Config.MaxTotalConnections) {
  692. logger.Debug(logSender, "", "active client connections %v/%v", total, Config.MaxTotalConnections)
  693. return false
  694. }
  695. // on a single SFTP connection we could have multiple SFTP channels or commands
  696. // so we check the estabilished connections too
  697. conns.RLock()
  698. defer conns.RUnlock()
  699. return len(conns.connections) < Config.MaxTotalConnections
  700. }
  701. return true
  702. }
  703. // GetStats returns stats for active connections
  704. func (conns *ActiveConnections) GetStats() []*ConnectionStatus {
  705. conns.RLock()
  706. defer conns.RUnlock()
  707. stats := make([]*ConnectionStatus, 0, len(conns.connections))
  708. for _, c := range conns.connections {
  709. stat := &ConnectionStatus{
  710. Username: c.GetUsername(),
  711. ConnectionID: c.GetID(),
  712. ClientVersion: c.GetClientVersion(),
  713. RemoteAddress: c.GetRemoteAddress(),
  714. ConnectionTime: utils.GetTimeAsMsSinceEpoch(c.GetConnectionTime()),
  715. LastActivity: utils.GetTimeAsMsSinceEpoch(c.GetLastActivity()),
  716. Protocol: c.GetProtocol(),
  717. Command: c.GetCommand(),
  718. Transfers: c.GetTransfers(),
  719. }
  720. stats = append(stats, stat)
  721. }
  722. return stats
  723. }
  724. // ConnectionStatus returns the status for an active connection
  725. type ConnectionStatus struct {
  726. // Logged in username
  727. Username string `json:"username"`
  728. // Unique identifier for the connection
  729. ConnectionID string `json:"connection_id"`
  730. // client's version string
  731. ClientVersion string `json:"client_version,omitempty"`
  732. // Remote address for this connection
  733. RemoteAddress string `json:"remote_address"`
  734. // Connection time as unix timestamp in milliseconds
  735. ConnectionTime int64 `json:"connection_time"`
  736. // Last activity as unix timestamp in milliseconds
  737. LastActivity int64 `json:"last_activity"`
  738. // Protocol for this connection
  739. Protocol string `json:"protocol"`
  740. // active uploads/downloads
  741. Transfers []ConnectionTransfer `json:"active_transfers,omitempty"`
  742. // SSH command or WebDAV method
  743. Command string `json:"command,omitempty"`
  744. }
  745. // GetConnectionDuration returns the connection duration as string
  746. func (c *ConnectionStatus) GetConnectionDuration() string {
  747. elapsed := time.Since(utils.GetTimeFromMsecSinceEpoch(c.ConnectionTime))
  748. return utils.GetDurationAsString(elapsed)
  749. }
  750. // GetConnectionInfo returns connection info.
  751. // Protocol,Client Version and RemoteAddress are returned.
  752. func (c *ConnectionStatus) GetConnectionInfo() string {
  753. var result strings.Builder
  754. result.WriteString(fmt.Sprintf("%v. Client: %#v From: %#v", c.Protocol, c.ClientVersion, c.RemoteAddress))
  755. if c.Command == "" {
  756. return result.String()
  757. }
  758. switch c.Protocol {
  759. case ProtocolSSH, ProtocolFTP:
  760. result.WriteString(fmt.Sprintf(". Command: %#v", c.Command))
  761. case ProtocolWebDAV:
  762. result.WriteString(fmt.Sprintf(". Method: %#v", c.Command))
  763. }
  764. return result.String()
  765. }
  766. // GetTransfersAsString returns the active transfers as string
  767. func (c *ConnectionStatus) GetTransfersAsString() string {
  768. result := ""
  769. for _, t := range c.Transfers {
  770. if result != "" {
  771. result += ". "
  772. }
  773. result += t.getConnectionTransferAsString()
  774. }
  775. return result
  776. }
  777. // ActiveQuotaScan defines an active quota scan for a user home dir
  778. type ActiveQuotaScan struct {
  779. // Username to which the quota scan refers
  780. Username string `json:"username"`
  781. // quota scan start time as unix timestamp in milliseconds
  782. StartTime int64 `json:"start_time"`
  783. }
  784. // ActiveVirtualFolderQuotaScan defines an active quota scan for a virtual folder
  785. type ActiveVirtualFolderQuotaScan struct {
  786. // folder name to which the quota scan refers
  787. Name string `json:"name"`
  788. // quota scan start time as unix timestamp in milliseconds
  789. StartTime int64 `json:"start_time"`
  790. }
  791. // ActiveScans holds the active quota scans
  792. type ActiveScans struct {
  793. sync.RWMutex
  794. UserHomeScans []ActiveQuotaScan
  795. FolderScans []ActiveVirtualFolderQuotaScan
  796. }
  797. // GetUsersQuotaScans returns the active quota scans for users home directories
  798. func (s *ActiveScans) GetUsersQuotaScans() []ActiveQuotaScan {
  799. s.RLock()
  800. defer s.RUnlock()
  801. scans := make([]ActiveQuotaScan, len(s.UserHomeScans))
  802. copy(scans, s.UserHomeScans)
  803. return scans
  804. }
  805. // AddUserQuotaScan adds a user to the ones with active quota scans.
  806. // Returns false if the user has a quota scan already running
  807. func (s *ActiveScans) AddUserQuotaScan(username string) bool {
  808. s.Lock()
  809. defer s.Unlock()
  810. for _, scan := range s.UserHomeScans {
  811. if scan.Username == username {
  812. return false
  813. }
  814. }
  815. s.UserHomeScans = append(s.UserHomeScans, ActiveQuotaScan{
  816. Username: username,
  817. StartTime: utils.GetTimeAsMsSinceEpoch(time.Now()),
  818. })
  819. return true
  820. }
  821. // RemoveUserQuotaScan removes a user from the ones with active quota scans.
  822. // Returns false if the user has no active quota scans
  823. func (s *ActiveScans) RemoveUserQuotaScan(username string) bool {
  824. s.Lock()
  825. defer s.Unlock()
  826. indexToRemove := -1
  827. for i, scan := range s.UserHomeScans {
  828. if scan.Username == username {
  829. indexToRemove = i
  830. break
  831. }
  832. }
  833. if indexToRemove >= 0 {
  834. s.UserHomeScans[indexToRemove] = s.UserHomeScans[len(s.UserHomeScans)-1]
  835. s.UserHomeScans = s.UserHomeScans[:len(s.UserHomeScans)-1]
  836. return true
  837. }
  838. return false
  839. }
  840. // GetVFoldersQuotaScans returns the active quota scans for virtual folders
  841. func (s *ActiveScans) GetVFoldersQuotaScans() []ActiveVirtualFolderQuotaScan {
  842. s.RLock()
  843. defer s.RUnlock()
  844. scans := make([]ActiveVirtualFolderQuotaScan, len(s.FolderScans))
  845. copy(scans, s.FolderScans)
  846. return scans
  847. }
  848. // AddVFolderQuotaScan adds a virtual folder to the ones with active quota scans.
  849. // Returns false if the folder has a quota scan already running
  850. func (s *ActiveScans) AddVFolderQuotaScan(folderName string) bool {
  851. s.Lock()
  852. defer s.Unlock()
  853. for _, scan := range s.FolderScans {
  854. if scan.Name == folderName {
  855. return false
  856. }
  857. }
  858. s.FolderScans = append(s.FolderScans, ActiveVirtualFolderQuotaScan{
  859. Name: folderName,
  860. StartTime: utils.GetTimeAsMsSinceEpoch(time.Now()),
  861. })
  862. return true
  863. }
  864. // RemoveVFolderQuotaScan removes a folder from the ones with active quota scans.
  865. // Returns false if the folder has no active quota scans
  866. func (s *ActiveScans) RemoveVFolderQuotaScan(folderName string) bool {
  867. s.Lock()
  868. defer s.Unlock()
  869. indexToRemove := -1
  870. for i, scan := range s.FolderScans {
  871. if scan.Name == folderName {
  872. indexToRemove = i
  873. break
  874. }
  875. }
  876. if indexToRemove >= 0 {
  877. s.FolderScans[indexToRemove] = s.FolderScans[len(s.FolderScans)-1]
  878. s.FolderScans = s.FolderScans[:len(s.FolderScans)-1]
  879. return true
  880. }
  881. return false
  882. }