| 1 |
// Package ban implements the abuse ban-feed: it tracks per-prefix weighted "strikes" from rejected |
| 2 |
// requests and appends breaching prefixes to a ban file that fail2ban tails. Keying by prefix (not |
| 3 |
// by visitor) makes the accounting match the unit fail2ban bans, even for shared account visitors. |
| 4 |
package ban |
| 5 |
|
| 6 |
import ( |
| 7 |
"fmt" |
| 8 |
"net/netip" |
| 9 |
"os" |
| 10 |
"sync" |
| 11 |
"time" |
| 12 |
|
| 13 |
"golang.org/x/time/rate" |
| 14 |
"heckel.io/ntfy/v2/log" |
| 15 |
) |
| 16 |
|
| 17 |
const ( |
| 18 |
tag = "ban" |
| 19 |
pruneInterval = 10 * time.Minute |
| 20 |
writeInterval = 3 * time.Second |
| 21 |
) |
| 22 |
|
| 23 |
// Config is the Service's config, kept separate from server.Config to avoid an import cycle. |
| 24 |
type Config struct { |
| 25 |
File string // Ban file that fail2ban tails (must be non-empty; the caller decides whether the feature is enabled) |
| 26 |
Window time.Duration // Rolling window over which weighted strikes are counted |
| 27 |
Threshold int // Weighted strikes per Window before a prefix is banned |
| 28 |
Weights Weights // Code matcher -> strike weight (0 = exempt) |
| 29 |
PrefixBitsIPv4 int // Mask width for the ban unit, e.g. 32 (matches rate-limiting granularity) |
| 30 |
PrefixBitsIPv6 int // Mask width for the ban unit, e.g. 64 |
| 31 |
} |
| 32 |
|
| 33 |
// tracker is the per-prefix strike state: a weighted breach detector plus timestamps for pruning and throttling. |
| 34 |
type tracker struct { |
| 35 |
limiter *rate.Limiter |
| 36 |
seen time.Time // Last strike, for pruning idle prefixes |
| 37 |
emitted time.Time // Last ban-line write for this prefix, throttles re-emits to once per Window |
| 38 |
} |
| 39 |
|
| 40 |
// Service owns the ban-feed: per-prefix strike accounting, buffered file writes, and idle-prefix |
| 41 |
// pruning. The caller owns the enable/disable decision -- only construct a Service when the feature |
| 42 |
// is on (see server.New, which builds one only when a ban file is configured). |
| 43 |
type Service struct { |
| 44 |
conf *Config |
| 45 |
mu sync.Mutex // Guards trackers and pending |
| 46 |
trackers map[netip.Prefix]*tracker |
| 47 |
pending []string // Formatted ban lines buffered by Record, flushed to the ban file by runWriteLoop |
| 48 |
writeDone chan struct{} // Closed when runWriteLoop exits after its final flush |
| 49 |
closeChan chan struct{} |
| 50 |
closeOnce sync.Once |
| 51 |
} |
| 52 |
|
| 53 |
// NewService builds a Service and starts its background loops. The caller must only call it when the |
| 54 |
// feature is enabled (conf non-nil, File non-empty); the Service does not model a disabled state. |
| 55 |
func NewService(conf *Config) *Service { |
| 56 |
s := &Service{ |
| 57 |
conf: conf, |
| 58 |
trackers: make(map[netip.Prefix]*tracker), |
| 59 |
closeChan: make(chan struct{}), |
| 60 |
writeDone: make(chan struct{}), |
| 61 |
} |
| 62 |
go s.runPruneLoop() |
| 63 |
go s.runWriteLoop() |
| 64 |
return s |
| 65 |
} |
| 66 |
|
| 67 |
// Record counts one rejection against the IP's prefix bucket and, on breach, buffers a ban line |
| 68 |
// (throttled to once per Window per prefix). No-ops for a non-4xx/5xx status or a zero-weight code. |
| 69 |
func (s *Service) Record(ip netip.Addr, httpCode, errorCode int) { |
| 70 |
if httpCode < 400 { |
| 71 |
return |
| 72 |
} |
| 73 |
weight := s.conf.Weights.WeightFor(errorCode) |
| 74 |
if weight == 0 { |
| 75 |
return // Weight 0: exempt, no strike |
| 76 |
} |
| 77 |
prefix := s.prefix(ip) |
| 78 |
now := time.Now() |
| 79 |
|
| 80 |
s.mu.Lock() |
| 81 |
defer s.mu.Unlock() |
| 82 |
t := s.trackers[prefix] |
| 83 |
if t == nil { |
| 84 |
t = &tracker{limiter: rate.NewLimiter(rate.Limit(float64(s.conf.Threshold)/s.conf.Window.Seconds()), s.conf.Threshold)} |
| 85 |
s.trackers[prefix] = t |
| 86 |
} |
| 87 |
t.seen = now |
| 88 |
if t.limiter.AllowN(now, weight) { |
| 89 |
return // Within the strike budget, no breach |
| 90 |
} |
| 91 |
if !t.emitted.IsZero() && now.Sub(t.emitted) < s.conf.Window { |
| 92 |
return // Already emitted this prefix within the window (one ban line per prefix per window) |
| 93 |
} |
| 94 |
t.emitted = now |
| 95 |
s.pending = append(s.pending, formatBanLine(now, ip, prefix, httpCode, errorCode)) |
| 96 |
} |
| 97 |
|
| 98 |
// prefix masks ip to the ban unit (PrefixBitsIPv4/IPv6) -- what fail2ban bans, e.g. a whole /64. |
| 99 |
func (s *Service) prefix(ip netip.Addr) netip.Prefix { |
| 100 |
if ip.Is4() { |
| 101 |
return netip.PrefixFrom(ip, s.conf.PrefixBitsIPv4).Masked() |
| 102 |
} |
| 103 |
return netip.PrefixFrom(ip, s.conf.PrefixBitsIPv6).Masked() |
| 104 |
} |
| 105 |
|
| 106 |
// formatBanLine builds the "<RFC3339-UTC> <ip> <prefix> <http> <ntfy>" line the fail2ban filter |
| 107 |
// parses. The timestamp is captured at breach time, not flush time. |
| 108 |
func formatBanLine(t time.Time, ip netip.Addr, prefix netip.Prefix, httpCode, errorCode int) string { |
| 109 |
return fmt.Sprintf("%s %s %s %d %d\n", t.UTC().Format(time.RFC3339), ip.String(), prefix.String(), httpCode, errorCode) |
| 110 |
} |
| 111 |
|
| 112 |
// runPruneLoop prunes idle prefixes until Close. |
| 113 |
func (s *Service) runPruneLoop() { |
| 114 |
ticker := time.NewTicker(pruneInterval) |
| 115 |
defer ticker.Stop() |
| 116 |
for { |
| 117 |
select { |
| 118 |
case <-ticker.C: |
| 119 |
s.prune() |
| 120 |
case <-s.closeChan: |
| 121 |
return |
| 122 |
} |
| 123 |
} |
| 124 |
} |
| 125 |
|
| 126 |
// runWriteLoop flushes buffered ban lines every writeInterval, plus a final flush on Close. |
| 127 |
func (s *Service) runWriteLoop() { |
| 128 |
defer close(s.writeDone) |
| 129 |
ticker := time.NewTicker(writeInterval) |
| 130 |
defer ticker.Stop() |
| 131 |
for { |
| 132 |
select { |
| 133 |
case <-ticker.C: |
| 134 |
s.flush() |
| 135 |
case <-s.closeChan: |
| 136 |
s.flush() |
| 137 |
return |
| 138 |
} |
| 139 |
} |
| 140 |
} |
| 141 |
|
| 142 |
// flush appends the buffered lines to the file in one open/write. Best-effort: a batch is dropped on |
| 143 |
// error. Concurrent calls are safe -- pending is drained under mu, so only one flush writes a batch. |
| 144 |
func (s *Service) flush() { |
| 145 |
s.mu.Lock() |
| 146 |
lines := s.pending |
| 147 |
s.pending = nil |
| 148 |
s.mu.Unlock() |
| 149 |
if len(lines) == 0 { |
| 150 |
return |
| 151 |
} |
| 152 |
f, err := os.OpenFile(s.conf.File, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644) |
| 153 |
if err != nil { |
| 154 |
log.Tag(tag).Err(err).Warn("Cannot open ban file %s, dropped %d ban(s)", s.conf.File, len(lines)) |
| 155 |
return |
| 156 |
} |
| 157 |
defer f.Close() |
| 158 |
for i, line := range lines { |
| 159 |
if _, err := f.WriteString(line); err != nil { |
| 160 |
log.Tag(tag).Err(err).Warn("Cannot write to ban file %s, dropped %d ban(s)", s.conf.File, len(lines)-i) |
| 161 |
return |
| 162 |
} |
| 163 |
} |
| 164 |
} |
| 165 |
|
| 166 |
// prune drops prefixes idle for a full Window -- their bucket has refilled, so forgetting them is a |
| 167 |
// no-op that bounds memory under a flood of distinct IPs. |
| 168 |
func (s *Service) prune() { |
| 169 |
now := time.Now() |
| 170 |
s.mu.Lock() |
| 171 |
defer s.mu.Unlock() |
| 172 |
for prefix, t := range s.trackers { |
| 173 |
if now.Sub(t.seen) >= s.conf.Window { |
| 174 |
delete(s.trackers, prefix) |
| 175 |
} |
| 176 |
} |
| 177 |
} |
| 178 |
|
| 179 |
// Close stops the loops and blocks until the final flush completes. Idempotent. |
| 180 |
func (s *Service) Close() { |
| 181 |
s.closeOnce.Do(func() { |
| 182 |
close(s.closeChan) |
| 183 |
<-s.writeDone |
| 184 |
}) |
| 185 |
} |