common.go 35 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060
  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. SetTimes(fsPath string, atime time.Time, mtime time.Time) bool
  263. }
  264. // ActiveConnection defines the interface for the current active connections
  265. type ActiveConnection interface {
  266. GetID() string
  267. GetUsername() string
  268. GetLocalAddress() string
  269. GetRemoteAddress() string
  270. GetClientVersion() string
  271. GetProtocol() string
  272. GetConnectionTime() time.Time
  273. GetLastActivity() time.Time
  274. GetCommand() string
  275. Disconnect() error
  276. AddTransfer(t ActiveTransfer)
  277. RemoveTransfer(t ActiveTransfer)
  278. GetTransfers() []ConnectionTransfer
  279. CloseFS() error
  280. }
  281. // StatAttributes defines the attributes for set stat commands
  282. type StatAttributes struct {
  283. Mode os.FileMode
  284. Atime time.Time
  285. Mtime time.Time
  286. UID int
  287. GID int
  288. Flags int
  289. Size int64
  290. }
  291. // ConnectionTransfer defines the trasfer details to expose
  292. type ConnectionTransfer struct {
  293. ID uint64 `json:"-"`
  294. OperationType string `json:"operation_type"`
  295. StartTime int64 `json:"start_time"`
  296. Size int64 `json:"size"`
  297. VirtualPath string `json:"path"`
  298. }
  299. func (t *ConnectionTransfer) getConnectionTransferAsString() string {
  300. result := ""
  301. switch t.OperationType {
  302. case operationUpload:
  303. result += "UL "
  304. case operationDownload:
  305. result += "DL "
  306. }
  307. result += fmt.Sprintf("%#v ", t.VirtualPath)
  308. if t.Size > 0 {
  309. elapsed := time.Since(util.GetTimeFromMsecSinceEpoch(t.StartTime))
  310. speed := float64(t.Size) / float64(util.GetTimeAsMsSinceEpoch(time.Now())-t.StartTime)
  311. result += fmt.Sprintf("Size: %#v Elapsed: %#v Speed: \"%.1f KB/s\"", util.ByteCountIEC(t.Size),
  312. util.GetDurationAsString(elapsed), speed)
  313. }
  314. return result
  315. }
  316. // Configuration defines configuration parameters common to all supported protocols
  317. type Configuration struct {
  318. // Maximum idle timeout as minutes. If a client is idle for a time that exceeds this setting it will be disconnected.
  319. // 0 means disabled
  320. IdleTimeout int `json:"idle_timeout" mapstructure:"idle_timeout"`
  321. // UploadMode 0 means standard, the files are uploaded directly to the requested path.
  322. // 1 means atomic: the files are uploaded to a temporary path and renamed to the requested path
  323. // when the client ends the upload. Atomic mode avoid problems such as a web server that
  324. // serves partial files when the files are being uploaded.
  325. // In atomic mode if there is an upload error the temporary file is deleted and so the requested
  326. // upload path will not contain a partial file.
  327. // 2 means atomic with resume support: as atomic but if there is an upload error the temporary
  328. // file is renamed to the requested path and not deleted, this way a client can reconnect and resume
  329. // the upload.
  330. UploadMode int `json:"upload_mode" mapstructure:"upload_mode"`
  331. // Actions to execute for SFTP file operations and SSH commands
  332. Actions ProtocolActions `json:"actions" mapstructure:"actions"`
  333. // SetstatMode 0 means "normal mode": requests for changing permissions and owner/group are executed.
  334. // 1 means "ignore mode": requests for changing permissions and owner/group are silently ignored.
  335. // 2 means "ignore mode for cloud fs": requests for changing permissions and owner/group/time are
  336. // silently ignored for cloud based filesystem such as S3, GCS, Azure Blob
  337. SetstatMode int `json:"setstat_mode" mapstructure:"setstat_mode"`
  338. // TempPath defines the path for temporary files such as those used for atomic uploads or file pipes.
  339. // If you set this option you must make sure that the defined path exists, is accessible for writing
  340. // by the user running SFTPGo, and is on the same filesystem as the users home directories otherwise
  341. // the renaming for atomic uploads will become a copy and therefore may take a long time.
  342. // The temporary files are not namespaced. The default is generally fine. Leave empty for the default.
  343. TempPath string `json:"temp_path" mapstructure:"temp_path"`
  344. // Support for HAProxy PROXY protocol.
  345. // If you are running SFTPGo behind a proxy server such as HAProxy, AWS ELB or NGNIX, you can enable
  346. // the proxy protocol. It provides a convenient way to safely transport connection information
  347. // such as a client's address across multiple layers of NAT or TCP proxies to get the real
  348. // client IP address instead of the proxy IP. Both protocol versions 1 and 2 are supported.
  349. // - 0 means disabled
  350. // - 1 means proxy protocol enabled. Proxy header will be used and requests without proxy header will be accepted.
  351. // - 2 means proxy protocol required. Proxy header will be used and requests without proxy header will be rejected.
  352. // If the proxy protocol is enabled in SFTPGo then you have to enable the protocol in your proxy configuration too,
  353. // for example for HAProxy add "send-proxy" or "send-proxy-v2" to each server configuration line.
  354. ProxyProtocol int `json:"proxy_protocol" mapstructure:"proxy_protocol"`
  355. // List of IP addresses and IP ranges allowed to send the proxy header.
  356. // If proxy protocol is set to 1 and we receive a proxy header from an IP that is not in the list then the
  357. // connection will be accepted and the header will be ignored.
  358. // If proxy protocol is set to 2 and we receive a proxy header from an IP that is not in the list then the
  359. // connection will be rejected.
  360. ProxyAllowed []string `json:"proxy_allowed" mapstructure:"proxy_allowed"`
  361. // Absolute path to an external program or an HTTP URL to invoke as soon as SFTPGo starts.
  362. // If you define an HTTP URL it will be invoked using a `GET` request.
  363. // Please note that SFTPGo services may not yet be available when this hook is run.
  364. // Leave empty do disable.
  365. StartupHook string `json:"startup_hook" mapstructure:"startup_hook"`
  366. // Absolute path to an external program or an HTTP URL to invoke after a user connects
  367. // and before he tries to login. It allows you to reject the connection based on the source
  368. // ip address. Leave empty do disable.
  369. PostConnectHook string `json:"post_connect_hook" mapstructure:"post_connect_hook"`
  370. // Absolute path to an external program or an HTTP URL to invoke after an SSH/FTP connection ends.
  371. // Leave empty do disable.
  372. PostDisconnectHook string `json:"post_disconnect_hook" mapstructure:"post_disconnect_hook"`
  373. // Absolute path to an external program or an HTTP URL to invoke after a data retention check completes.
  374. // Leave empty do disable.
  375. DataRetentionHook string `json:"data_retention_hook" mapstructure:"data_retention_hook"`
  376. // Maximum number of concurrent client connections. 0 means unlimited
  377. MaxTotalConnections int `json:"max_total_connections" mapstructure:"max_total_connections"`
  378. // Maximum number of concurrent client connections from the same host (IP). 0 means unlimited
  379. MaxPerHostConnections int `json:"max_per_host_connections" mapstructure:"max_per_host_connections"`
  380. // Defender configuration
  381. DefenderConfig DefenderConfig `json:"defender" mapstructure:"defender"`
  382. // Rate limiter configurations
  383. RateLimitersConfig []RateLimiterConfig `json:"rate_limiters" mapstructure:"rate_limiters"`
  384. idleTimeoutAsDuration time.Duration
  385. idleLoginTimeout time.Duration
  386. defender Defender
  387. }
  388. // IsAtomicUploadEnabled returns true if atomic upload is enabled
  389. func (c *Configuration) IsAtomicUploadEnabled() bool {
  390. return c.UploadMode == UploadModeAtomic || c.UploadMode == UploadModeAtomicWithResume
  391. }
  392. // GetProxyListener returns a wrapper for the given listener that supports the
  393. // HAProxy Proxy Protocol
  394. func (c *Configuration) GetProxyListener(listener net.Listener) (*proxyproto.Listener, error) {
  395. var err error
  396. if c.ProxyProtocol > 0 {
  397. var policyFunc func(upstream net.Addr) (proxyproto.Policy, error)
  398. if c.ProxyProtocol == 1 && len(c.ProxyAllowed) > 0 {
  399. policyFunc, err = proxyproto.LaxWhiteListPolicy(c.ProxyAllowed)
  400. if err != nil {
  401. return nil, err
  402. }
  403. }
  404. if c.ProxyProtocol == 2 {
  405. if len(c.ProxyAllowed) == 0 {
  406. policyFunc = func(upstream net.Addr) (proxyproto.Policy, error) {
  407. return proxyproto.REQUIRE, nil
  408. }
  409. } else {
  410. policyFunc, err = proxyproto.StrictWhiteListPolicy(c.ProxyAllowed)
  411. if err != nil {
  412. return nil, err
  413. }
  414. }
  415. }
  416. return &proxyproto.Listener{
  417. Listener: listener,
  418. Policy: policyFunc,
  419. ReadHeaderTimeout: 5 * time.Second,
  420. }, nil
  421. }
  422. return nil, errors.New("proxy protocol not configured")
  423. }
  424. // ExecuteStartupHook runs the startup hook if defined
  425. func (c *Configuration) ExecuteStartupHook() error {
  426. if c.StartupHook == "" {
  427. return nil
  428. }
  429. if strings.HasPrefix(c.StartupHook, "http") {
  430. var url *url.URL
  431. url, err := url.Parse(c.StartupHook)
  432. if err != nil {
  433. logger.Warn(logSender, "", "Invalid startup hook %#v: %v", c.StartupHook, err)
  434. return err
  435. }
  436. startTime := time.Now()
  437. resp, err := httpclient.RetryableGet(url.String())
  438. if err != nil {
  439. logger.Warn(logSender, "", "Error executing startup hook: %v", err)
  440. return err
  441. }
  442. defer resp.Body.Close()
  443. logger.Debug(logSender, "", "Startup hook executed, elapsed: %v, response code: %v", time.Since(startTime), resp.StatusCode)
  444. return nil
  445. }
  446. if !filepath.IsAbs(c.StartupHook) {
  447. err := fmt.Errorf("invalid startup hook %#v", c.StartupHook)
  448. logger.Warn(logSender, "", "Invalid startup hook %#v", c.StartupHook)
  449. return err
  450. }
  451. startTime := time.Now()
  452. ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
  453. defer cancel()
  454. cmd := exec.CommandContext(ctx, c.StartupHook)
  455. err := cmd.Run()
  456. logger.Debug(logSender, "", "Startup hook executed, elapsed: %v, error: %v", time.Since(startTime), err)
  457. return nil
  458. }
  459. func (c *Configuration) executePostDisconnectHook(remoteAddr, protocol, username, connID string, connectionTime time.Time) {
  460. ipAddr := util.GetIPFromRemoteAddress(remoteAddr)
  461. connDuration := int64(time.Since(connectionTime) / time.Millisecond)
  462. if strings.HasPrefix(c.PostDisconnectHook, "http") {
  463. var url *url.URL
  464. url, err := url.Parse(c.PostDisconnectHook)
  465. if err != nil {
  466. logger.Warn(protocol, connID, "Invalid post disconnect hook %#v: %v", c.PostDisconnectHook, err)
  467. return
  468. }
  469. q := url.Query()
  470. q.Add("ip", ipAddr)
  471. q.Add("protocol", protocol)
  472. q.Add("username", username)
  473. q.Add("connection_duration", strconv.FormatInt(connDuration, 10))
  474. url.RawQuery = q.Encode()
  475. startTime := time.Now()
  476. resp, err := httpclient.RetryableGet(url.String())
  477. respCode := 0
  478. if err == nil {
  479. respCode = resp.StatusCode
  480. resp.Body.Close()
  481. }
  482. logger.Debug(protocol, connID, "Post disconnect hook response code: %v, elapsed: %v, err: %v",
  483. respCode, time.Since(startTime), err)
  484. return
  485. }
  486. if !filepath.IsAbs(c.PostDisconnectHook) {
  487. logger.Debug(protocol, connID, "invalid post disconnect hook %#v", c.PostDisconnectHook)
  488. return
  489. }
  490. ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
  491. defer cancel()
  492. startTime := time.Now()
  493. cmd := exec.CommandContext(ctx, c.PostDisconnectHook)
  494. cmd.Env = append(os.Environ(),
  495. fmt.Sprintf("SFTPGO_CONNECTION_IP=%v", ipAddr),
  496. fmt.Sprintf("SFTPGO_CONNECTION_USERNAME=%v", username),
  497. fmt.Sprintf("SFTPGO_CONNECTION_DURATION=%v", connDuration),
  498. fmt.Sprintf("SFTPGO_CONNECTION_PROTOCOL=%v", protocol))
  499. err := cmd.Run()
  500. logger.Debug(protocol, connID, "Post disconnect hook executed, elapsed: %v error: %v", time.Since(startTime), err)
  501. }
  502. func (c *Configuration) checkPostDisconnectHook(remoteAddr, protocol, username, connID string, connectionTime time.Time) {
  503. if c.PostDisconnectHook == "" {
  504. return
  505. }
  506. if !util.IsStringInSlice(protocol, disconnHookProtocols) {
  507. return
  508. }
  509. go c.executePostDisconnectHook(remoteAddr, protocol, username, connID, connectionTime)
  510. }
  511. // ExecutePostConnectHook executes the post connect hook if defined
  512. func (c *Configuration) ExecutePostConnectHook(ipAddr, protocol string) error {
  513. if c.PostConnectHook == "" {
  514. return nil
  515. }
  516. if strings.HasPrefix(c.PostConnectHook, "http") {
  517. var url *url.URL
  518. url, err := url.Parse(c.PostConnectHook)
  519. if err != nil {
  520. logger.Warn(protocol, "", "Login from ip %#v denied, invalid post connect hook %#v: %v",
  521. ipAddr, c.PostConnectHook, err)
  522. return err
  523. }
  524. q := url.Query()
  525. q.Add("ip", ipAddr)
  526. q.Add("protocol", protocol)
  527. url.RawQuery = q.Encode()
  528. resp, err := httpclient.RetryableGet(url.String())
  529. if err != nil {
  530. logger.Warn(protocol, "", "Login from ip %#v denied, error executing post connect hook: %v", ipAddr, err)
  531. return err
  532. }
  533. defer resp.Body.Close()
  534. if resp.StatusCode != http.StatusOK {
  535. logger.Warn(protocol, "", "Login from ip %#v denied, post connect hook response code: %v", ipAddr, resp.StatusCode)
  536. return errUnexpectedHTTResponse
  537. }
  538. return nil
  539. }
  540. if !filepath.IsAbs(c.PostConnectHook) {
  541. err := fmt.Errorf("invalid post connect hook %#v", c.PostConnectHook)
  542. logger.Warn(protocol, "", "Login from ip %#v denied: %v", ipAddr, err)
  543. return err
  544. }
  545. ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
  546. defer cancel()
  547. cmd := exec.CommandContext(ctx, c.PostConnectHook)
  548. cmd.Env = append(os.Environ(),
  549. fmt.Sprintf("SFTPGO_CONNECTION_IP=%v", ipAddr),
  550. fmt.Sprintf("SFTPGO_CONNECTION_PROTOCOL=%v", protocol))
  551. err := cmd.Run()
  552. if err != nil {
  553. logger.Warn(protocol, "", "Login from ip %#v denied, connect hook error: %v", ipAddr, err)
  554. }
  555. return err
  556. }
  557. // SSHConnection defines an ssh connection.
  558. // Each SSH connection can open several channels for SFTP or SSH commands
  559. type SSHConnection struct {
  560. id string
  561. conn net.Conn
  562. lastActivity int64
  563. }
  564. // NewSSHConnection returns a new SSHConnection
  565. func NewSSHConnection(id string, conn net.Conn) *SSHConnection {
  566. return &SSHConnection{
  567. id: id,
  568. conn: conn,
  569. lastActivity: time.Now().UnixNano(),
  570. }
  571. }
  572. // GetID returns the ID for this SSHConnection
  573. func (c *SSHConnection) GetID() string {
  574. return c.id
  575. }
  576. // UpdateLastActivity updates last activity for this connection
  577. func (c *SSHConnection) UpdateLastActivity() {
  578. atomic.StoreInt64(&c.lastActivity, time.Now().UnixNano())
  579. }
  580. // GetLastActivity returns the last connection activity
  581. func (c *SSHConnection) GetLastActivity() time.Time {
  582. return time.Unix(0, atomic.LoadInt64(&c.lastActivity))
  583. }
  584. // Close closes the underlying network connection
  585. func (c *SSHConnection) Close() error {
  586. return c.conn.Close()
  587. }
  588. // ActiveConnections holds the currect active connections with the associated transfers
  589. type ActiveConnections struct {
  590. // clients contains both authenticated and estabilished connections and the ones waiting
  591. // for authentication
  592. clients clientsMap
  593. sync.RWMutex
  594. connections []ActiveConnection
  595. sshConnections []*SSHConnection
  596. }
  597. // GetActiveSessions returns the number of active sessions for the given username.
  598. // We return the open sessions for any protocol
  599. func (conns *ActiveConnections) GetActiveSessions(username string) int {
  600. conns.RLock()
  601. defer conns.RUnlock()
  602. numSessions := 0
  603. for _, c := range conns.connections {
  604. if c.GetUsername() == username {
  605. numSessions++
  606. }
  607. }
  608. return numSessions
  609. }
  610. // Add adds a new connection to the active ones
  611. func (conns *ActiveConnections) Add(c ActiveConnection) {
  612. conns.Lock()
  613. defer conns.Unlock()
  614. conns.connections = append(conns.connections, c)
  615. metric.UpdateActiveConnectionsSize(len(conns.connections))
  616. logger.Debug(c.GetProtocol(), c.GetID(), "connection added, local address %#v, remote address %#v, num open connections: %v",
  617. c.GetLocalAddress(), c.GetRemoteAddress(), len(conns.connections))
  618. }
  619. // Swap replaces an existing connection with the given one.
  620. // This method is useful if you have to change some connection details
  621. // for example for FTP is used to update the connection once the user
  622. // authenticates
  623. func (conns *ActiveConnections) Swap(c ActiveConnection) error {
  624. conns.Lock()
  625. defer conns.Unlock()
  626. for idx, conn := range conns.connections {
  627. if conn.GetID() == c.GetID() {
  628. err := conn.CloseFS()
  629. conns.connections[idx] = c
  630. logger.Debug(logSender, c.GetID(), "connection swapped, close fs error: %v", err)
  631. conn = nil
  632. return nil
  633. }
  634. }
  635. return errors.New("connection to swap not found")
  636. }
  637. // Remove removes a connection from the active ones
  638. func (conns *ActiveConnections) Remove(connectionID string) {
  639. conns.Lock()
  640. defer conns.Unlock()
  641. for idx, conn := range conns.connections {
  642. if conn.GetID() == connectionID {
  643. err := conn.CloseFS()
  644. lastIdx := len(conns.connections) - 1
  645. conns.connections[idx] = conns.connections[lastIdx]
  646. conns.connections[lastIdx] = nil
  647. conns.connections = conns.connections[:lastIdx]
  648. metric.UpdateActiveConnectionsSize(lastIdx)
  649. logger.Debug(conn.GetProtocol(), conn.GetID(), "connection removed, local address %#v, remote address %#v close fs error: %v, num open connections: %v",
  650. conn.GetLocalAddress(), conn.GetRemoteAddress(), err, lastIdx)
  651. Config.checkPostDisconnectHook(conn.GetRemoteAddress(), conn.GetProtocol(), conn.GetUsername(),
  652. conn.GetID(), conn.GetConnectionTime())
  653. return
  654. }
  655. }
  656. logger.Warn(logSender, "", "connection id %#v to remove not found!", connectionID)
  657. }
  658. // Close closes an active connection.
  659. // It returns true on success
  660. func (conns *ActiveConnections) Close(connectionID string) bool {
  661. conns.RLock()
  662. result := false
  663. for _, c := range conns.connections {
  664. if c.GetID() == connectionID {
  665. defer func(conn ActiveConnection) {
  666. err := conn.Disconnect()
  667. logger.Debug(conn.GetProtocol(), conn.GetID(), "close connection requested, close err: %v", err)
  668. }(c)
  669. result = true
  670. break
  671. }
  672. }
  673. conns.RUnlock()
  674. return result
  675. }
  676. // AddSSHConnection adds a new ssh connection to the active ones
  677. func (conns *ActiveConnections) AddSSHConnection(c *SSHConnection) {
  678. conns.Lock()
  679. defer conns.Unlock()
  680. conns.sshConnections = append(conns.sshConnections, c)
  681. logger.Debug(logSender, c.GetID(), "ssh connection added, num open connections: %v", len(conns.sshConnections))
  682. }
  683. // RemoveSSHConnection removes a connection from the active ones
  684. func (conns *ActiveConnections) RemoveSSHConnection(connectionID string) {
  685. conns.Lock()
  686. defer conns.Unlock()
  687. for idx, conn := range conns.sshConnections {
  688. if conn.GetID() == connectionID {
  689. lastIdx := len(conns.sshConnections) - 1
  690. conns.sshConnections[idx] = conns.sshConnections[lastIdx]
  691. conns.sshConnections[lastIdx] = nil
  692. conns.sshConnections = conns.sshConnections[:lastIdx]
  693. logger.Debug(logSender, conn.GetID(), "ssh connection removed, num open ssh connections: %v", lastIdx)
  694. return
  695. }
  696. }
  697. logger.Warn(logSender, "", "ssh connection to remove with id %#v not found!", connectionID)
  698. }
  699. func (conns *ActiveConnections) checkIdles() {
  700. conns.RLock()
  701. for _, sshConn := range conns.sshConnections {
  702. idleTime := time.Since(sshConn.GetLastActivity())
  703. if idleTime > Config.idleTimeoutAsDuration {
  704. // we close the an ssh connection if it has no active connections associated
  705. idToMatch := fmt.Sprintf("_%v_", sshConn.GetID())
  706. toClose := true
  707. for _, conn := range conns.connections {
  708. if strings.Contains(conn.GetID(), idToMatch) {
  709. toClose = false
  710. break
  711. }
  712. }
  713. if toClose {
  714. defer func(c *SSHConnection) {
  715. err := c.Close()
  716. logger.Debug(logSender, c.GetID(), "close idle SSH connection, idle time: %v, close err: %v",
  717. time.Since(c.GetLastActivity()), err)
  718. }(sshConn)
  719. }
  720. }
  721. }
  722. for _, c := range conns.connections {
  723. idleTime := time.Since(c.GetLastActivity())
  724. isUnauthenticatedFTPUser := (c.GetProtocol() == ProtocolFTP && c.GetUsername() == "")
  725. if idleTime > Config.idleTimeoutAsDuration || (isUnauthenticatedFTPUser && idleTime > Config.idleLoginTimeout) {
  726. defer func(conn ActiveConnection, isFTPNoAuth bool) {
  727. err := conn.Disconnect()
  728. logger.Debug(conn.GetProtocol(), conn.GetID(), "close idle connection, idle time: %v, username: %#v close err: %v",
  729. time.Since(conn.GetLastActivity()), conn.GetUsername(), err)
  730. if isFTPNoAuth {
  731. ip := util.GetIPFromRemoteAddress(c.GetRemoteAddress())
  732. logger.ConnectionFailedLog("", ip, dataprovider.LoginMethodNoAuthTryed, c.GetProtocol(), "client idle")
  733. metric.AddNoAuthTryed()
  734. AddDefenderEvent(ip, HostEventNoLoginTried)
  735. dataprovider.ExecutePostLoginHook(&dataprovider.User{}, dataprovider.LoginMethodNoAuthTryed, ip, c.GetProtocol(),
  736. dataprovider.ErrNoAuthTryed)
  737. }
  738. }(c, isUnauthenticatedFTPUser)
  739. }
  740. }
  741. conns.RUnlock()
  742. }
  743. // AddClientConnection stores a new client connection
  744. func (conns *ActiveConnections) AddClientConnection(ipAddr string) {
  745. conns.clients.add(ipAddr)
  746. }
  747. // RemoveClientConnection removes a disconnected client from the tracked ones
  748. func (conns *ActiveConnections) RemoveClientConnection(ipAddr string) {
  749. conns.clients.remove(ipAddr)
  750. }
  751. // GetClientConnections returns the total number of client connections
  752. func (conns *ActiveConnections) GetClientConnections() int32 {
  753. return conns.clients.getTotal()
  754. }
  755. // IsNewConnectionAllowed returns false if the maximum number of concurrent allowed connections is exceeded
  756. func (conns *ActiveConnections) IsNewConnectionAllowed(ipAddr string) bool {
  757. if Config.MaxTotalConnections == 0 && Config.MaxPerHostConnections == 0 {
  758. return true
  759. }
  760. if Config.MaxPerHostConnections > 0 {
  761. if total := conns.clients.getTotalFrom(ipAddr); total > Config.MaxPerHostConnections {
  762. logger.Debug(logSender, "", "active connections from %v %v/%v", ipAddr, total, Config.MaxPerHostConnections)
  763. AddDefenderEvent(ipAddr, HostEventLimitExceeded)
  764. return false
  765. }
  766. }
  767. if Config.MaxTotalConnections > 0 {
  768. if total := conns.clients.getTotal(); total > int32(Config.MaxTotalConnections) {
  769. logger.Debug(logSender, "", "active client connections %v/%v", total, Config.MaxTotalConnections)
  770. return false
  771. }
  772. // on a single SFTP connection we could have multiple SFTP channels or commands
  773. // so we check the estabilished connections too
  774. conns.RLock()
  775. defer conns.RUnlock()
  776. return len(conns.connections) < Config.MaxTotalConnections
  777. }
  778. return true
  779. }
  780. // GetStats returns stats for active connections
  781. func (conns *ActiveConnections) GetStats() []*ConnectionStatus {
  782. conns.RLock()
  783. defer conns.RUnlock()
  784. stats := make([]*ConnectionStatus, 0, len(conns.connections))
  785. for _, c := range conns.connections {
  786. stat := &ConnectionStatus{
  787. Username: c.GetUsername(),
  788. ConnectionID: c.GetID(),
  789. ClientVersion: c.GetClientVersion(),
  790. RemoteAddress: c.GetRemoteAddress(),
  791. ConnectionTime: util.GetTimeAsMsSinceEpoch(c.GetConnectionTime()),
  792. LastActivity: util.GetTimeAsMsSinceEpoch(c.GetLastActivity()),
  793. Protocol: c.GetProtocol(),
  794. Command: c.GetCommand(),
  795. Transfers: c.GetTransfers(),
  796. }
  797. stats = append(stats, stat)
  798. }
  799. return stats
  800. }
  801. // ConnectionStatus returns the status for an active connection
  802. type ConnectionStatus struct {
  803. // Logged in username
  804. Username string `json:"username"`
  805. // Unique identifier for the connection
  806. ConnectionID string `json:"connection_id"`
  807. // client's version string
  808. ClientVersion string `json:"client_version,omitempty"`
  809. // Remote address for this connection
  810. RemoteAddress string `json:"remote_address"`
  811. // Connection time as unix timestamp in milliseconds
  812. ConnectionTime int64 `json:"connection_time"`
  813. // Last activity as unix timestamp in milliseconds
  814. LastActivity int64 `json:"last_activity"`
  815. // Protocol for this connection
  816. Protocol string `json:"protocol"`
  817. // active uploads/downloads
  818. Transfers []ConnectionTransfer `json:"active_transfers,omitempty"`
  819. // SSH command or WebDAV method
  820. Command string `json:"command,omitempty"`
  821. }
  822. // GetConnectionDuration returns the connection duration as string
  823. func (c *ConnectionStatus) GetConnectionDuration() string {
  824. elapsed := time.Since(util.GetTimeFromMsecSinceEpoch(c.ConnectionTime))
  825. return util.GetDurationAsString(elapsed)
  826. }
  827. // GetConnectionInfo returns connection info.
  828. // Protocol,Client Version and RemoteAddress are returned.
  829. func (c *ConnectionStatus) GetConnectionInfo() string {
  830. var result strings.Builder
  831. result.WriteString(fmt.Sprintf("%v. Client: %#v From: %#v", c.Protocol, c.ClientVersion, c.RemoteAddress))
  832. if c.Command == "" {
  833. return result.String()
  834. }
  835. switch c.Protocol {
  836. case ProtocolSSH, ProtocolFTP:
  837. result.WriteString(fmt.Sprintf(". Command: %#v", c.Command))
  838. case ProtocolWebDAV:
  839. result.WriteString(fmt.Sprintf(". Method: %#v", c.Command))
  840. }
  841. return result.String()
  842. }
  843. // GetTransfersAsString returns the active transfers as string
  844. func (c *ConnectionStatus) GetTransfersAsString() string {
  845. result := ""
  846. for _, t := range c.Transfers {
  847. if result != "" {
  848. result += ". "
  849. }
  850. result += t.getConnectionTransferAsString()
  851. }
  852. return result
  853. }
  854. // ActiveQuotaScan defines an active quota scan for a user home dir
  855. type ActiveQuotaScan struct {
  856. // Username to which the quota scan refers
  857. Username string `json:"username"`
  858. // quota scan start time as unix timestamp in milliseconds
  859. StartTime int64 `json:"start_time"`
  860. }
  861. // ActiveVirtualFolderQuotaScan defines an active quota scan for a virtual folder
  862. type ActiveVirtualFolderQuotaScan struct {
  863. // folder name to which the quota scan refers
  864. Name string `json:"name"`
  865. // quota scan start time as unix timestamp in milliseconds
  866. StartTime int64 `json:"start_time"`
  867. }
  868. // ActiveScans holds the active quota scans
  869. type ActiveScans struct {
  870. sync.RWMutex
  871. UserScans []ActiveQuotaScan
  872. FolderScans []ActiveVirtualFolderQuotaScan
  873. }
  874. // GetUsersQuotaScans returns the active quota scans for users home directories
  875. func (s *ActiveScans) GetUsersQuotaScans() []ActiveQuotaScan {
  876. s.RLock()
  877. defer s.RUnlock()
  878. scans := make([]ActiveQuotaScan, len(s.UserScans))
  879. copy(scans, s.UserScans)
  880. return scans
  881. }
  882. // AddUserQuotaScan adds a user to the ones with active quota scans.
  883. // Returns false if the user has a quota scan already running
  884. func (s *ActiveScans) AddUserQuotaScan(username string) bool {
  885. s.Lock()
  886. defer s.Unlock()
  887. for _, scan := range s.UserScans {
  888. if scan.Username == username {
  889. return false
  890. }
  891. }
  892. s.UserScans = append(s.UserScans, ActiveQuotaScan{
  893. Username: username,
  894. StartTime: util.GetTimeAsMsSinceEpoch(time.Now()),
  895. })
  896. return true
  897. }
  898. // RemoveUserQuotaScan removes a user from the ones with active quota scans.
  899. // Returns false if the user has no active quota scans
  900. func (s *ActiveScans) RemoveUserQuotaScan(username string) bool {
  901. s.Lock()
  902. defer s.Unlock()
  903. for idx, scan := range s.UserScans {
  904. if scan.Username == username {
  905. lastIdx := len(s.UserScans) - 1
  906. s.UserScans[idx] = s.UserScans[lastIdx]
  907. s.UserScans = s.UserScans[:lastIdx]
  908. return true
  909. }
  910. }
  911. return false
  912. }
  913. // GetVFoldersQuotaScans returns the active quota scans for virtual folders
  914. func (s *ActiveScans) GetVFoldersQuotaScans() []ActiveVirtualFolderQuotaScan {
  915. s.RLock()
  916. defer s.RUnlock()
  917. scans := make([]ActiveVirtualFolderQuotaScan, len(s.FolderScans))
  918. copy(scans, s.FolderScans)
  919. return scans
  920. }
  921. // AddVFolderQuotaScan adds a virtual folder to the ones with active quota scans.
  922. // Returns false if the folder has a quota scan already running
  923. func (s *ActiveScans) AddVFolderQuotaScan(folderName string) bool {
  924. s.Lock()
  925. defer s.Unlock()
  926. for _, scan := range s.FolderScans {
  927. if scan.Name == folderName {
  928. return false
  929. }
  930. }
  931. s.FolderScans = append(s.FolderScans, ActiveVirtualFolderQuotaScan{
  932. Name: folderName,
  933. StartTime: util.GetTimeAsMsSinceEpoch(time.Now()),
  934. })
  935. return true
  936. }
  937. // RemoveVFolderQuotaScan removes a folder from the ones with active quota scans.
  938. // Returns false if the folder has no active quota scans
  939. func (s *ActiveScans) RemoveVFolderQuotaScan(folderName string) bool {
  940. s.Lock()
  941. defer s.Unlock()
  942. for idx, scan := range s.FolderScans {
  943. if scan.Name == folderName {
  944. lastIdx := len(s.FolderScans) - 1
  945. s.FolderScans[idx] = s.FolderScans[lastIdx]
  946. s.FolderScans = s.FolderScans[:lastIdx]
  947. return true
  948. }
  949. }
  950. return false
  951. }