common.go 35 KB

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