defender.go 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232
  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. "fmt"
  17. "time"
  18. "github.com/drakkan/sftpgo/v2/internal/dataprovider"
  19. "github.com/drakkan/sftpgo/v2/internal/logger"
  20. )
  21. // HostEvent is the enumerable for the supported host events
  22. type HostEvent string
  23. // Supported host events
  24. const (
  25. HostEventLoginFailed HostEvent = "LoginFailed"
  26. HostEventUserNotFound HostEvent = "UserNotFound"
  27. HostEventNoLoginTried HostEvent = "NoLoginTried"
  28. HostEventLimitExceeded HostEvent = "LimitExceeded"
  29. )
  30. // Supported defender drivers
  31. const (
  32. DefenderDriverMemory = "memory"
  33. DefenderDriverProvider = "provider"
  34. )
  35. var (
  36. supportedDefenderDrivers = []string{DefenderDriverMemory, DefenderDriverProvider}
  37. )
  38. // Defender defines the interface that a defender must implements
  39. type Defender interface {
  40. GetHosts() ([]dataprovider.DefenderEntry, error)
  41. GetHost(ip string) (dataprovider.DefenderEntry, error)
  42. AddEvent(ip, protocol string, event HostEvent) bool
  43. IsBanned(ip, protocol string) bool
  44. IsSafe(ip, protocol string) bool
  45. GetBanTime(ip string) (*time.Time, error)
  46. GetScore(ip string) (int, error)
  47. DeleteHost(ip string) bool
  48. }
  49. // DefenderConfig defines the "defender" configuration
  50. type DefenderConfig struct {
  51. // Set to true to enable the defender
  52. Enabled bool `json:"enabled" mapstructure:"enabled"`
  53. // Defender implementation to use, we support "memory" and "provider".
  54. // Using "provider" as driver you can share the defender events among
  55. // multiple SFTPGo instances. For a single instance "memory" provider will
  56. // be much faster
  57. Driver string `json:"driver" mapstructure:"driver"`
  58. // BanTime is the number of minutes that a host is banned
  59. BanTime int `json:"ban_time" mapstructure:"ban_time"`
  60. // Percentage increase of the ban time if a banned host tries to connect again
  61. BanTimeIncrement int `json:"ban_time_increment" mapstructure:"ban_time_increment"`
  62. // Threshold value for banning a client
  63. Threshold int `json:"threshold" mapstructure:"threshold"`
  64. // Score for invalid login attempts, eg. non-existent user accounts
  65. ScoreInvalid int `json:"score_invalid" mapstructure:"score_invalid"`
  66. // Score for valid login attempts, eg. user accounts that exist
  67. ScoreValid int `json:"score_valid" mapstructure:"score_valid"`
  68. // Score for limit exceeded events, generated from the rate limiters or for max connections
  69. // per-host exceeded
  70. ScoreLimitExceeded int `json:"score_limit_exceeded" mapstructure:"score_limit_exceeded"`
  71. // ScoreNoAuth defines the score for clients disconnected without authentication
  72. // attempts
  73. ScoreNoAuth int `json:"score_no_auth" mapstructure:"score_no_auth"`
  74. // Defines the time window, in minutes, for tracking client errors.
  75. // A host is banned if it has exceeded the defined threshold during
  76. // the last observation time minutes
  77. ObservationTime int `json:"observation_time" mapstructure:"observation_time"`
  78. // The number of banned IPs and host scores kept in memory will vary between the
  79. // soft and hard limit for the "memory" driver. For the "provider" driver the
  80. // soft limit is ignored and the hard limit is used to limit the number of entries
  81. // to return when you request for the entire host list from the defender
  82. EntriesSoftLimit int `json:"entries_soft_limit" mapstructure:"entries_soft_limit"`
  83. EntriesHardLimit int `json:"entries_hard_limit" mapstructure:"entries_hard_limit"`
  84. }
  85. type baseDefender struct {
  86. config *DefenderConfig
  87. ipList *dataprovider.IPList
  88. }
  89. func (d *baseDefender) isBanned(ip, protocol string) bool {
  90. isListed, mode, err := d.ipList.IsListed(ip, protocol)
  91. if err != nil {
  92. return false
  93. }
  94. if isListed && mode == dataprovider.ListModeDeny {
  95. return true
  96. }
  97. return false
  98. }
  99. func (d *baseDefender) IsSafe(ip, protocol string) bool {
  100. isListed, mode, err := d.ipList.IsListed(ip, protocol)
  101. if err == nil && isListed && mode == dataprovider.ListModeAllow {
  102. return true
  103. }
  104. return false
  105. }
  106. func (d *baseDefender) getScore(event HostEvent) int {
  107. var score int
  108. switch event {
  109. case HostEventLoginFailed:
  110. score = d.config.ScoreValid
  111. case HostEventLimitExceeded:
  112. score = d.config.ScoreLimitExceeded
  113. case HostEventUserNotFound:
  114. score = d.config.ScoreInvalid
  115. case HostEventNoLoginTried:
  116. score = d.config.ScoreNoAuth
  117. }
  118. return score
  119. }
  120. // logEvent logs a defender event that changes a host's score
  121. func (d *baseDefender) logEvent(ip, protocol string, event HostEvent, totalScore int) {
  122. // ignore events which do not change the host score
  123. eventScore := d.getScore(event)
  124. if eventScore == 0 {
  125. return
  126. }
  127. logger.GetLogger().Debug().
  128. Timestamp().
  129. Str("sender", "defender").
  130. Str("client_ip", ip).
  131. Str("protocol", protocol).
  132. Str("event", string(event)).
  133. Int("increase_score_by", eventScore).
  134. Int("score", totalScore).
  135. Send()
  136. }
  137. // logBan logs a host's ban due to a too high host score
  138. func (d *baseDefender) logBan(ip, protocol string) {
  139. logger.GetLogger().Info().
  140. Timestamp().
  141. Str("sender", "defender").
  142. Str("client_ip", ip).
  143. Str("protocol", protocol).
  144. Str("event", "banned").
  145. Send()
  146. }
  147. type hostEvent struct {
  148. dateTime time.Time
  149. score int
  150. }
  151. type hostScore struct {
  152. TotalScore int
  153. Events []hostEvent
  154. }
  155. func (c *DefenderConfig) checkScores() error {
  156. if c.ScoreInvalid < 0 {
  157. c.ScoreInvalid = 0
  158. }
  159. if c.ScoreValid < 0 {
  160. c.ScoreValid = 0
  161. }
  162. if c.ScoreLimitExceeded < 0 {
  163. c.ScoreLimitExceeded = 0
  164. }
  165. if c.ScoreNoAuth < 0 {
  166. c.ScoreNoAuth = 0
  167. }
  168. if c.ScoreInvalid == 0 && c.ScoreValid == 0 && c.ScoreLimitExceeded == 0 && c.ScoreNoAuth == 0 {
  169. return fmt.Errorf("invalid defender configuration: all scores are disabled")
  170. }
  171. return nil
  172. }
  173. // validate returns an error if the configuration is invalid
  174. func (c *DefenderConfig) validate() error {
  175. if !c.Enabled {
  176. return nil
  177. }
  178. if err := c.checkScores(); err != nil {
  179. return err
  180. }
  181. if c.ScoreInvalid >= c.Threshold {
  182. return fmt.Errorf("score_invalid %d cannot be greater than threshold %d", c.ScoreInvalid, c.Threshold)
  183. }
  184. if c.ScoreValid >= c.Threshold {
  185. return fmt.Errorf("score_valid %d cannot be greater than threshold %d", c.ScoreValid, c.Threshold)
  186. }
  187. if c.ScoreLimitExceeded >= c.Threshold {
  188. return fmt.Errorf("score_limit_exceeded %d cannot be greater than threshold %d", c.ScoreLimitExceeded, c.Threshold)
  189. }
  190. if c.ScoreNoAuth >= c.Threshold {
  191. return fmt.Errorf("score_no_auth %d cannot be greater than threshold %d", c.ScoreNoAuth, c.Threshold)
  192. }
  193. if c.BanTime <= 0 {
  194. return fmt.Errorf("invalid ban_time %v", c.BanTime)
  195. }
  196. if c.BanTimeIncrement <= 0 {
  197. return fmt.Errorf("invalid ban_time_increment %v", c.BanTimeIncrement)
  198. }
  199. if c.ObservationTime <= 0 {
  200. return fmt.Errorf("invalid observation_time %v", c.ObservationTime)
  201. }
  202. if c.EntriesSoftLimit <= 0 {
  203. return fmt.Errorf("invalid entries_soft_limit %v", c.EntriesSoftLimit)
  204. }
  205. if c.EntriesHardLimit <= c.EntriesSoftLimit {
  206. return fmt.Errorf("invalid entries_hard_limit %v must be > %v", c.EntriesHardLimit, c.EntriesSoftLimit)
  207. }
  208. return nil
  209. }