Skip to content

Commit

Permalink
all: ratelimit subnet len
Browse files Browse the repository at this point in the history
  • Loading branch information
schzhn committed Oct 30, 2023
1 parent 39f15ce commit 1a98437
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 0 deletions.
6 changes: 6 additions & 0 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,9 @@ type Options struct {
// Anti-DNS amplification measures
// --

RatelimitSubnetLenV4 int `yaml:"ratelimit-subnet-len-v4" long:"ratelimit-subnet-len-v4"`
RatelimitSubnetLenV6 int `yaml:"ratelimit-subnet-len-v6" long:"ratelimit-subnet-len-v6"`

// Ratelimit value
Ratelimit int `yaml:"ratelimit" short:"r" long:"ratelimit" description:"Ratelimit (requests per second)"`

Expand Down Expand Up @@ -320,6 +323,9 @@ func runPprof(options *Options) {
func createProxyConfig(options *Options) proxy.Config {
// Create the config
config := proxy.Config{
RatelimitSubnetLenV4: options.RatelimitSubnetLenV4,
RatelimitSubnetLenV6: options.RatelimitSubnetLenV6,

Ratelimit: options.Ratelimit,
CacheEnabled: options.Cache,
CacheSizeBytes: options.CacheSizeBytes,
Expand Down
3 changes: 3 additions & 0 deletions proxy/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,9 @@ type Config struct {
// Rate-limiting and anti-DNS amplification measures
// --

RatelimitSubnetLenV4 int
RatelimitSubnetLenV6 int

Ratelimit int // max number of requests per second from a given IP (0 to disable)
RatelimitWhitelist []string // a list of whitelisted client IP addresses
RefuseAny bool // if true, refuse ANY requests
Expand Down
10 changes: 10 additions & 0 deletions proxy/ratelimit.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,16 @@ func (p *Proxy) isRatelimited(addr net.Addr) (ok bool) {
}
}

var mask net.IPMask
if len(ip) == net.IPv4len {
mask = net.CIDRMask(p.RatelimitSubnetLenV4, 32)
} else {
mask = net.CIDRMask(p.RatelimitSubnetLenV6, 128)
}

ip = ip.Mask(mask)
ipStr = ip.String()

value := p.limiterForIP(ipStr)
rl, ok := value.(*rate.RateLimiter)
if !ok {
Expand Down

0 comments on commit 1a98437

Please sign in to comment.