defender.go 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342
  1. // Copyright (C) 2019-2022 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. "encoding/json"
  17. "fmt"
  18. "net"
  19. "os"
  20. "strings"
  21. "sync"
  22. "time"
  23. "github.com/yl2chen/cidranger"
  24. "github.com/drakkan/sftpgo/v2/dataprovider"
  25. "github.com/drakkan/sftpgo/v2/logger"
  26. "github.com/drakkan/sftpgo/v2/util"
  27. )
  28. // HostEvent is the enumerable for the supported host events
  29. type HostEvent int
  30. // Supported host events
  31. const (
  32. HostEventLoginFailed HostEvent = iota
  33. HostEventUserNotFound
  34. HostEventNoLoginTried
  35. HostEventLimitExceeded
  36. )
  37. // Supported defender drivers
  38. const (
  39. DefenderDriverMemory = "memory"
  40. DefenderDriverProvider = "provider"
  41. )
  42. var (
  43. supportedDefenderDrivers = []string{DefenderDriverMemory, DefenderDriverProvider}
  44. )
  45. // Defender defines the interface that a defender must implements
  46. type Defender interface {
  47. GetHosts() ([]dataprovider.DefenderEntry, error)
  48. GetHost(ip string) (dataprovider.DefenderEntry, error)
  49. AddEvent(ip string, event HostEvent)
  50. IsBanned(ip string) bool
  51. GetBanTime(ip string) (*time.Time, error)
  52. GetScore(ip string) (int, error)
  53. DeleteHost(ip string) bool
  54. Reload() error
  55. }
  56. // DefenderConfig defines the "defender" configuration
  57. type DefenderConfig struct {
  58. // Set to true to enable the defender
  59. Enabled bool `json:"enabled" mapstructure:"enabled"`
  60. // Defender implementation to use, we support "memory" and "provider".
  61. // Using "provider" as driver you can share the defender events among
  62. // multiple SFTPGo instances. For a single instance "memory" provider will
  63. // be much faster
  64. Driver string `json:"driver" mapstructure:"driver"`
  65. // BanTime is the number of minutes that a host is banned
  66. BanTime int `json:"ban_time" mapstructure:"ban_time"`
  67. // Percentage increase of the ban time if a banned host tries to connect again
  68. BanTimeIncrement int `json:"ban_time_increment" mapstructure:"ban_time_increment"`
  69. // Threshold value for banning a client
  70. Threshold int `json:"threshold" mapstructure:"threshold"`
  71. // Score for invalid login attempts, eg. non-existent user accounts or
  72. // client disconnected for inactivity without authentication attempts
  73. ScoreInvalid int `json:"score_invalid" mapstructure:"score_invalid"`
  74. // Score for valid login attempts, eg. user accounts that exist
  75. ScoreValid int `json:"score_valid" mapstructure:"score_valid"`
  76. // Score for limit exceeded events, generated from the rate limiters or for max connections
  77. // per-host exceeded
  78. ScoreLimitExceeded int `json:"score_limit_exceeded" mapstructure:"score_limit_exceeded"`
  79. // Defines the time window, in minutes, for tracking client errors.
  80. // A host is banned if it has exceeded the defined threshold during
  81. // the last observation time minutes
  82. ObservationTime int `json:"observation_time" mapstructure:"observation_time"`
  83. // The number of banned IPs and host scores kept in memory will vary between the
  84. // soft and hard limit for the "memory" driver. For the "provider" driver the
  85. // soft limit is ignored and the hard limit is used to limit the number of entries
  86. // to return when you request for the entire host list from the defender
  87. EntriesSoftLimit int `json:"entries_soft_limit" mapstructure:"entries_soft_limit"`
  88. EntriesHardLimit int `json:"entries_hard_limit" mapstructure:"entries_hard_limit"`
  89. // Path to a file containing a list of IP addresses and/or networks to never ban
  90. SafeListFile string `json:"safelist_file" mapstructure:"safelist_file"`
  91. // Path to a file containing a list of IP addresses and/or networks to always ban
  92. BlockListFile string `json:"blocklist_file" mapstructure:"blocklist_file"`
  93. // List of IP addresses and/or networks to never ban.
  94. // For large lists prefer SafeListFile
  95. SafeList []string `json:"safelist" mapstructure:"safelist"`
  96. // List of IP addresses and/or networks to always ban.
  97. // For large lists prefer BlockListFile
  98. BlockList []string `json:"blocklist" mapstructure:"blocklist"`
  99. }
  100. type baseDefender struct {
  101. config *DefenderConfig
  102. sync.RWMutex
  103. safeList *HostList
  104. blockList *HostList
  105. }
  106. // Reload reloads block and safe lists
  107. func (d *baseDefender) Reload() error {
  108. blockList, err := loadHostListFromFile(d.config.BlockListFile)
  109. if err != nil {
  110. return err
  111. }
  112. blockList = addEntriesToList(d.config.BlockList, blockList, "blocklist")
  113. d.Lock()
  114. d.blockList = blockList
  115. d.Unlock()
  116. safeList, err := loadHostListFromFile(d.config.SafeListFile)
  117. if err != nil {
  118. return err
  119. }
  120. safeList = addEntriesToList(d.config.SafeList, safeList, "safelist")
  121. d.Lock()
  122. d.safeList = safeList
  123. d.Unlock()
  124. return nil
  125. }
  126. func (d *baseDefender) isBanned(ip string) bool {
  127. if d.blockList != nil && d.blockList.isListed(ip) {
  128. // permanent ban
  129. return true
  130. }
  131. return false
  132. }
  133. func (d *baseDefender) getScore(event HostEvent) int {
  134. var score int
  135. switch event {
  136. case HostEventLoginFailed:
  137. score = d.config.ScoreValid
  138. case HostEventLimitExceeded:
  139. score = d.config.ScoreLimitExceeded
  140. case HostEventUserNotFound, HostEventNoLoginTried:
  141. score = d.config.ScoreInvalid
  142. }
  143. return score
  144. }
  145. // HostListFile defines the structure expected for safe/block list files
  146. type HostListFile struct {
  147. IPAddresses []string `json:"addresses"`
  148. CIDRNetworks []string `json:"networks"`
  149. }
  150. // HostList defines the structure used to keep the HostListFile in memory
  151. type HostList struct {
  152. IPAddresses map[string]bool
  153. Ranges cidranger.Ranger
  154. }
  155. func (h *HostList) isListed(ip string) bool {
  156. if _, ok := h.IPAddresses[ip]; ok {
  157. return true
  158. }
  159. ok, err := h.Ranges.Contains(net.ParseIP(ip))
  160. if err != nil {
  161. return false
  162. }
  163. return ok
  164. }
  165. type hostEvent struct {
  166. dateTime time.Time
  167. score int
  168. }
  169. type hostScore struct {
  170. TotalScore int
  171. Events []hostEvent
  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 c.ScoreInvalid >= c.Threshold {
  179. return fmt.Errorf("score_invalid %v cannot be greater than threshold %v", c.ScoreInvalid, c.Threshold)
  180. }
  181. if c.ScoreValid >= c.Threshold {
  182. return fmt.Errorf("score_valid %v cannot be greater than threshold %v", c.ScoreValid, c.Threshold)
  183. }
  184. if c.ScoreLimitExceeded >= c.Threshold {
  185. return fmt.Errorf("score_limit_exceeded %v cannot be greater than threshold %v", c.ScoreLimitExceeded, c.Threshold)
  186. }
  187. if c.BanTime <= 0 {
  188. return fmt.Errorf("invalid ban_time %v", c.BanTime)
  189. }
  190. if c.BanTimeIncrement <= 0 {
  191. return fmt.Errorf("invalid ban_time_increment %v", c.BanTimeIncrement)
  192. }
  193. if c.ObservationTime <= 0 {
  194. return fmt.Errorf("invalid observation_time %v", c.ObservationTime)
  195. }
  196. if c.EntriesSoftLimit <= 0 {
  197. return fmt.Errorf("invalid entries_soft_limit %v", c.EntriesSoftLimit)
  198. }
  199. if c.EntriesHardLimit <= c.EntriesSoftLimit {
  200. return fmt.Errorf("invalid entries_hard_limit %v must be > %v", c.EntriesHardLimit, c.EntriesSoftLimit)
  201. }
  202. return nil
  203. }
  204. func loadHostListFromFile(name string) (*HostList, error) {
  205. if name == "" {
  206. return nil, nil
  207. }
  208. if !util.IsFileInputValid(name) {
  209. return nil, fmt.Errorf("invalid host list file name %#v", name)
  210. }
  211. info, err := os.Stat(name)
  212. if err != nil {
  213. return nil, err
  214. }
  215. // opinionated max size, you should avoid big host lists
  216. if info.Size() > 1048576*5 { // 5MB
  217. return nil, fmt.Errorf("host list file %#v is too big: %v bytes", name, info.Size())
  218. }
  219. content, err := os.ReadFile(name)
  220. if err != nil {
  221. return nil, fmt.Errorf("unable to read input file %#v: %v", name, err)
  222. }
  223. var hostList HostListFile
  224. err = json.Unmarshal(content, &hostList)
  225. if err != nil {
  226. return nil, err
  227. }
  228. if len(hostList.CIDRNetworks) > 0 || len(hostList.IPAddresses) > 0 {
  229. result := &HostList{
  230. IPAddresses: make(map[string]bool),
  231. Ranges: cidranger.NewPCTrieRanger(),
  232. }
  233. ipCount := 0
  234. cdrCount := 0
  235. for _, ip := range hostList.IPAddresses {
  236. if net.ParseIP(ip) == nil {
  237. logger.Warn(logSender, "", "unable to parse IP %#v", ip)
  238. continue
  239. }
  240. result.IPAddresses[ip] = true
  241. ipCount++
  242. }
  243. for _, cidrNet := range hostList.CIDRNetworks {
  244. _, network, err := net.ParseCIDR(cidrNet)
  245. if err != nil {
  246. logger.Warn(logSender, "", "unable to parse CIDR network %#v: %v", cidrNet, err)
  247. continue
  248. }
  249. err = result.Ranges.Insert(cidranger.NewBasicRangerEntry(*network))
  250. if err == nil {
  251. cdrCount++
  252. }
  253. }
  254. logger.Info(logSender, "", "list %#v loaded, ip addresses loaded: %v/%v networks loaded: %v/%v",
  255. name, ipCount, len(hostList.IPAddresses), cdrCount, len(hostList.CIDRNetworks))
  256. return result, nil
  257. }
  258. return nil, nil
  259. }
  260. func addEntriesToList(entries []string, hostList *HostList, listName string) *HostList {
  261. if len(entries) == 0 {
  262. return hostList
  263. }
  264. if hostList == nil {
  265. hostList = &HostList{
  266. IPAddresses: make(map[string]bool),
  267. Ranges: cidranger.NewPCTrieRanger(),
  268. }
  269. }
  270. ipCount := 0
  271. ipLoaded := 0
  272. cdrCount := 0
  273. cdrLoaded := 0
  274. for _, entry := range entries {
  275. entry = strings.TrimSpace(entry)
  276. if strings.LastIndex(entry, "/") > 0 {
  277. cdrCount++
  278. _, network, err := net.ParseCIDR(entry)
  279. if err != nil {
  280. logger.Warn(logSender, "", "unable to parse CIDR network %#v: %v", entry, err)
  281. continue
  282. }
  283. err = hostList.Ranges.Insert(cidranger.NewBasicRangerEntry(*network))
  284. if err == nil {
  285. cdrLoaded++
  286. }
  287. } else {
  288. ipCount++
  289. if net.ParseIP(entry) == nil {
  290. logger.Warn(logSender, "", "unable to parse IP %#v", entry)
  291. continue
  292. }
  293. hostList.IPAddresses[entry] = true
  294. ipLoaded++
  295. }
  296. }
  297. logger.Info(logSender, "", "%s from config loaded, ip addresses loaded: %v/%v networks loaded: %v/%v",
  298. listName, ipLoaded, ipCount, cdrLoaded, cdrCount)
  299. return hostList
  300. }