3
0
mirror of https://github.com/ergochat/ergo.git synced 2024-11-24 21:09:30 +01:00
ergo/irc/connection_limits/limiter.go

281 lines
7.2 KiB
Go
Raw Permalink Normal View History

2017-03-27 14:15:02 +02:00
// Copyright (c) 2016-2017 Daniel Oaks <daniel@danieloaks.net>
// released under the MIT license
package connection_limits
import (
2020-12-08 03:21:10 +01:00
"crypto/md5"
"errors"
"fmt"
2017-10-09 07:47:04 +02:00
"sync"
"time"
2019-02-05 06:19:03 +01:00
2021-05-25 06:34:38 +02:00
"github.com/ergochat/ergo/irc/flatip"
"github.com/ergochat/ergo/irc/utils"
)
var (
ErrLimitExceeded = errors.New("too many concurrent connections")
ErrThrottleExceeded = errors.New("too many recent connection attempts")
)
type CustomLimitConfig struct {
Nets []string
MaxConcurrent int `yaml:"max-concurrent-connections"`
MaxPerWindow int `yaml:"max-connections-per-window"`
}
// tuples the key-value pair of a CIDR and its custom limit/throttle values
type customLimit struct {
2020-12-08 03:21:10 +01:00
name [16]byte
2021-01-22 13:27:10 +01:00
customID string // operator-configured identifier for a custom net
maxConcurrent int
maxPerWindow int
2020-12-08 03:21:10 +01:00
nets []flatip.IPNet
}
type limiterKey struct {
maskedIP flatip.IP
prefixLen uint8 // 0 for the fake nets we generate for custom limits
}
// LimiterConfig controls the automated connection limits.
2019-11-18 23:30:54 +01:00
// rawLimiterConfig contains all the YAML-visible fields;
// LimiterConfig contains additional denormalized private fields
2019-11-18 23:30:54 +01:00
type rawLimiterConfig struct {
2019-11-24 03:09:31 +01:00
Count bool
MaxConcurrent int `yaml:"max-concurrent-connections"`
Throttle bool
Window time.Duration
MaxPerWindow int `yaml:"max-connections-per-window"`
CidrLenIPv4 int `yaml:"cidr-len-ipv4"`
CidrLenIPv6 int `yaml:"cidr-len-ipv6"`
Exempted []string
CustomLimits map[string]CustomLimitConfig `yaml:"custom-limits"`
}
type LimiterConfig struct {
2019-11-18 23:30:54 +01:00
rawLimiterConfig
2020-12-08 03:21:10 +01:00
exemptedNets []flatip.IPNet
customLimits []customLimit
}
func (config *LimiterConfig) UnmarshalYAML(unmarshal func(interface{}) error) (err error) {
2019-11-18 23:30:54 +01:00
if err = unmarshal(&config.rawLimiterConfig); err != nil {
return err
}
return config.postprocess()
}
func (config *LimiterConfig) postprocess() (err error) {
2020-12-08 03:21:10 +01:00
exemptedNets, err := utils.ParseNetList(config.Exempted)
if err != nil {
return fmt.Errorf("Could not parse limiter exemption list: %v", err.Error())
}
2020-12-08 03:21:10 +01:00
config.exemptedNets = make([]flatip.IPNet, len(exemptedNets))
for i, exempted := range exemptedNets {
config.exemptedNets[i] = flatip.FromNetIPNet(exempted)
}
for identifier, customLimitConf := range config.CustomLimits {
2020-12-08 03:21:10 +01:00
nets := make([]flatip.IPNet, len(customLimitConf.Nets))
for i, netStr := range customLimitConf.Nets {
2020-12-08 03:21:10 +01:00
normalizedNet, err := flatip.ParseToNormalizedNet(netStr)
if err != nil {
return fmt.Errorf("Bad net %s in custom-limits block %s: %w", netStr, identifier, err)
}
nets[i] = normalizedNet
}
if len(customLimitConf.Nets) == 0 {
// see #1421: this is the legacy config format where the
// dictionary key of the block is a CIDR string
2020-12-08 03:21:10 +01:00
normalizedNet, err := flatip.ParseToNormalizedNet(identifier)
if err != nil {
return fmt.Errorf("Custom limit block %s has no defined nets", identifier)
}
2020-12-08 03:21:10 +01:00
nets = []flatip.IPNet{normalizedNet}
}
config.customLimits = append(config.customLimits, customLimit{
maxConcurrent: customLimitConf.MaxConcurrent,
maxPerWindow: customLimitConf.MaxPerWindow,
2020-12-08 03:21:10 +01:00
name: md5.Sum([]byte(identifier)),
2021-01-22 13:27:10 +01:00
customID: identifier,
nets: nets,
})
}
return nil
}
// Limiter manages the automated client connection limits.
type Limiter struct {
2017-10-09 07:47:04 +02:00
sync.Mutex
config *LimiterConfig
// IP/CIDR -> count of clients connected from there:
2020-12-08 03:21:10 +01:00
limiter map[limiterKey]int
// IP/CIDR -> throttle state:
2020-12-08 03:21:10 +01:00
throttler map[limiterKey]ThrottleDetails
}
// addrToKey canonicalizes `addr` to a string key, and returns
// the relevant connection limit and throttle max-per-window values
2021-01-22 13:27:10 +01:00
func (cl *Limiter) addrToKey(addr flatip.IP) (key limiterKey, customID string, limit int, throttle int) {
for _, custom := range cl.config.customLimits {
for _, net := range custom.nets {
if net.Contains(addr) {
2021-01-22 13:27:10 +01:00
return limiterKey{maskedIP: custom.name, prefixLen: 0}, custom.customID, custom.maxConcurrent, custom.maxPerWindow
}
}
}
2020-12-08 03:21:10 +01:00
var prefixLen int
if addr.IsIPv4() {
2020-12-08 03:21:10 +01:00
prefixLen = cl.config.CidrLenIPv4
addr = addr.Mask(prefixLen, 32)
2020-12-08 03:21:10 +01:00
prefixLen += 96
} else {
2020-12-08 03:21:10 +01:00
prefixLen = cl.config.CidrLenIPv6
addr = addr.Mask(prefixLen, 128)
}
2020-12-08 03:21:10 +01:00
2021-01-22 13:27:10 +01:00
return limiterKey{maskedIP: addr, prefixLen: uint8(prefixLen)}, "", cl.config.MaxConcurrent, cl.config.MaxPerWindow
}
// AddClient adds a client to our population if possible. If we can't, throws an error instead.
func (cl *Limiter) AddClient(addr flatip.IP) error {
2017-10-09 07:47:04 +02:00
cl.Lock()
defer cl.Unlock()
// we don't track populations for exempted addresses or nets - this is by design
if flatip.IPInNets(addr, cl.config.exemptedNets) {
return nil
}
2021-01-22 13:27:10 +01:00
addrString, _, maxConcurrent, maxPerWindow := cl.addrToKey(addr)
// check limiter
var count int
if cl.config.Count {
count = cl.limiter[addrString] + 1
if count > maxConcurrent {
return ErrLimitExceeded
}
}
if cl.config.Throttle {
details := cl.throttler[addrString] // retrieve mutable throttle state from the map
// add in constant state to process the limiting operation
g := GenericThrottle{
ThrottleDetails: details,
Duration: cl.config.Window,
Limit: maxPerWindow,
}
throttled, _ := g.Touch() // actually check the limit
cl.throttler[addrString] = g.ThrottleDetails // store modified mutable state
if throttled {
// back out the limiter add
return ErrThrottleExceeded
}
}
// success, record in limiter
2019-11-24 03:09:31 +01:00
if cl.config.Count {
cl.limiter[addrString] = count
}
return nil
}
// RemoveClient removes the given address from our population
func (cl *Limiter) RemoveClient(addr flatip.IP) {
2017-10-09 07:47:04 +02:00
cl.Lock()
defer cl.Unlock()
if !cl.config.Count || flatip.IPInNets(addr, cl.config.exemptedNets) {
return
}
2021-01-22 13:27:10 +01:00
addrString, _, _, _ := cl.addrToKey(addr)
count := cl.limiter[addrString]
count -= 1
if count < 0 {
count = 0
}
cl.limiter[addrString] = count
}
2021-01-19 14:49:45 +01:00
type LimiterStatus struct {
Exempt bool
Count int
MaxCount int
Throttle int
MaxPerWindow int
ThrottleDuration time.Duration
}
2021-01-22 13:27:10 +01:00
func (cl *Limiter) Status(addr flatip.IP) (netName string, status LimiterStatus) {
2021-01-19 14:49:45 +01:00
cl.Lock()
defer cl.Unlock()
if flatip.IPInNets(addr, cl.config.exemptedNets) {
status.Exempt = true
return
}
status.ThrottleDuration = cl.config.Window
2021-01-22 13:27:10 +01:00
limiterKey, customID, maxConcurrent, maxPerWindow := cl.addrToKey(addr)
2021-01-19 14:49:45 +01:00
status.MaxCount = maxConcurrent
status.MaxPerWindow = maxPerWindow
2021-01-22 13:27:10 +01:00
status.Count = cl.limiter[limiterKey]
status.Throttle = cl.throttler[limiterKey].Count
netName = customID
if netName == "" {
netName = flatip.IPNet{
IP: limiterKey.maskedIP,
PrefixLen: limiterKey.prefixLen,
}.String()
}
2021-01-19 14:49:45 +01:00
return
}
// ResetThrottle resets the throttle count for an IP
func (cl *Limiter) ResetThrottle(addr flatip.IP) {
cl.Lock()
defer cl.Unlock()
if !cl.config.Throttle || flatip.IPInNets(addr, cl.config.exemptedNets) {
return
}
2021-01-22 13:27:10 +01:00
addrString, _, _, _ := cl.addrToKey(addr)
delete(cl.throttler, addrString)
}
// ApplyConfig atomically applies a config update to a connection limit handler
func (cl *Limiter) ApplyConfig(config *LimiterConfig) {
2017-10-09 07:47:04 +02:00
cl.Lock()
defer cl.Unlock()
if cl.limiter == nil {
2020-12-08 03:21:10 +01:00
cl.limiter = make(map[limiterKey]int)
2019-05-12 10:30:48 +02:00
}
if cl.throttler == nil {
2020-12-08 03:21:10 +01:00
cl.throttler = make(map[limiterKey]ThrottleDetails)
2018-02-25 11:17:39 +01:00
}
2017-10-09 07:47:04 +02:00
cl.config = config
}