defenderdb.go 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177
  1. // Copyright (C) 2019 Nicola Murino
  2. //
  3. // This program is free software: you can redistribute it and/or modify
  4. // it under the terms of the GNU Affero General Public License as published
  5. // by the Free Software Foundation, version 3.
  6. //
  7. // This program is distributed in the hope that it will be useful,
  8. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. // GNU Affero General Public License for more details.
  11. //
  12. // You should have received a copy of the GNU Affero General Public License
  13. // along with this program. If not, see <https://www.gnu.org/licenses/>.
  14. package common
  15. import (
  16. "sync/atomic"
  17. "time"
  18. "github.com/drakkan/sftpgo/v2/internal/dataprovider"
  19. "github.com/drakkan/sftpgo/v2/internal/logger"
  20. "github.com/drakkan/sftpgo/v2/internal/util"
  21. )
  22. type dbDefender struct {
  23. baseDefender
  24. lastCleanup atomic.Int64
  25. }
  26. func newDBDefender(config *DefenderConfig) (Defender, error) {
  27. err := config.validate()
  28. if err != nil {
  29. return nil, err
  30. }
  31. ipList, err := dataprovider.NewIPList(dataprovider.IPListTypeDefender)
  32. if err != nil {
  33. return nil, err
  34. }
  35. defender := &dbDefender{
  36. baseDefender: baseDefender{
  37. config: config,
  38. ipList: ipList,
  39. },
  40. }
  41. defender.lastCleanup.Store(0)
  42. return defender, nil
  43. }
  44. // GetHosts returns hosts that are banned or for which some violations have been detected
  45. func (d *dbDefender) GetHosts() ([]dataprovider.DefenderEntry, error) {
  46. return dataprovider.GetDefenderHosts(d.getStartObservationTime(), d.config.EntriesHardLimit)
  47. }
  48. // GetHost returns a defender host by ip, if any
  49. func (d *dbDefender) GetHost(ip string) (dataprovider.DefenderEntry, error) {
  50. return dataprovider.GetDefenderHostByIP(ip, d.getStartObservationTime())
  51. }
  52. // IsBanned returns true if the specified IP is banned
  53. // and increase ban time if the IP is found.
  54. // This method must be called as soon as the client connects
  55. func (d *dbDefender) IsBanned(ip, protocol string) bool {
  56. if d.baseDefender.isBanned(ip, protocol) {
  57. return true
  58. }
  59. _, err := dataprovider.IsDefenderHostBanned(ip)
  60. if err != nil {
  61. // not found or another error, we allow this host
  62. return false
  63. }
  64. increment := d.config.BanTime * d.config.BanTimeIncrement / 100
  65. if increment == 0 {
  66. increment++
  67. }
  68. dataprovider.UpdateDefenderBanTime(ip, increment) //nolint:errcheck
  69. return true
  70. }
  71. // DeleteHost removes the specified IP from the defender lists
  72. func (d *dbDefender) DeleteHost(ip string) bool {
  73. if _, err := d.GetHost(ip); err != nil {
  74. return false
  75. }
  76. return dataprovider.DeleteDefenderHost(ip) == nil
  77. }
  78. // AddEvent adds an event for the given IP.
  79. // This method must be called for clients not yet banned
  80. func (d *dbDefender) AddEvent(ip, protocol string, event HostEvent) {
  81. if d.IsSafe(ip, protocol) {
  82. return
  83. }
  84. score := d.baseDefender.getScore(event)
  85. host, err := dataprovider.AddDefenderEvent(ip, score, d.getStartObservationTime())
  86. if err != nil {
  87. return
  88. }
  89. if host.Score > d.config.Threshold {
  90. banTime := time.Now().Add(time.Duration(d.config.BanTime) * time.Minute)
  91. err = dataprovider.SetDefenderBanTime(ip, util.GetTimeAsMsSinceEpoch(banTime))
  92. if err == nil {
  93. eventManager.handleIPBlockedEvent(EventParams{
  94. Event: ipBlockedEventName,
  95. IP: ip,
  96. Timestamp: time.Now().UnixNano(),
  97. Status: 1,
  98. })
  99. }
  100. }
  101. if err == nil {
  102. d.cleanup()
  103. }
  104. }
  105. // GetBanTime returns the ban time for the given IP or nil if the IP is not banned
  106. func (d *dbDefender) GetBanTime(ip string) (*time.Time, error) {
  107. host, err := d.GetHost(ip)
  108. if err != nil {
  109. return nil, err
  110. }
  111. if host.BanTime.IsZero() {
  112. return nil, nil
  113. }
  114. return &host.BanTime, nil
  115. }
  116. // GetScore returns the score for the given IP
  117. func (d *dbDefender) GetScore(ip string) (int, error) {
  118. host, err := d.GetHost(ip)
  119. if err != nil {
  120. return 0, err
  121. }
  122. return host.Score, nil
  123. }
  124. func (d *dbDefender) cleanup() {
  125. lastCleanup := d.getLastCleanup()
  126. if lastCleanup.IsZero() || lastCleanup.Add(time.Duration(d.config.ObservationTime)*time.Minute*3).Before(time.Now()) {
  127. // FIXME: this could be racy in rare cases but it is better than acquire the lock for the cleanup duration
  128. // or to always acquire a read/write lock.
  129. // Concurrent cleanups could happen anyway from multiple SFTPGo instances and should not cause any issues
  130. d.setLastCleanup(time.Now())
  131. expireTime := time.Now().Add(-time.Duration(d.config.ObservationTime+1) * time.Minute)
  132. logger.Debug(logSender, "", "cleanup defender hosts before %v, last cleanup %v", expireTime, lastCleanup)
  133. if err := dataprovider.CleanupDefender(util.GetTimeAsMsSinceEpoch(expireTime)); err != nil {
  134. logger.Error(logSender, "", "defender cleanup error, reset last cleanup to %v", lastCleanup)
  135. d.setLastCleanup(lastCleanup)
  136. }
  137. }
  138. }
  139. func (d *dbDefender) getStartObservationTime() int64 {
  140. t := time.Now().Add(-time.Duration(d.config.ObservationTime) * time.Minute)
  141. return util.GetTimeAsMsSinceEpoch(t)
  142. }
  143. func (d *dbDefender) getLastCleanup() time.Time {
  144. val := d.lastCleanup.Load()
  145. if val == 0 {
  146. return time.Time{}
  147. }
  148. return util.GetTimeFromMsecSinceEpoch(val)
  149. }
  150. func (d *dbDefender) setLastCleanup(when time.Time) {
  151. if when.IsZero() {
  152. d.lastCleanup.Store(0)
  153. return
  154. }
  155. d.lastCleanup.Store(util.GetTimeAsMsSinceEpoch(when))
  156. }