common.go 32 KB

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