809620340e
Four fixes hardening the secrets and rate-limit posture a prior audit left or that regressed: X-Forwarded-For rate-limit bypass + memory DoS (ratelimit.go): clientIP returned the raw XFF header, so an attacker rotating it minted unlimited distinct limiter keys — never tripping the limit and growing the visitors map without bound. XFF is now honored only when the immediate peer is a configured trusted proxy (UPTOP_TRUSTED_PROXIES, CIDRs or bare IPs), using the right-most non-trusted hop; otherwise the key is the real RemoteAddr. The visitors map is bounded with LRU eviction as defense in depth. Export redaction denylist -> per-provider allowlist (server.go): the old six-key denylist missed the actual credentials — the webhook URL for discord/slack/webhook/ntfy/gotify and api_key for opsgenie — exporting them in the clear. redactByProvider keeps only known-safe keys per provider type and redacts everything else, so unknown/new keys fail safe. ImportData plaintext secrets (sqlstore.go): import inserted raw json.Marshal(settings), bypassing the encryption AddAlert/UpdateAlert use. It now routes through marshalSettings, so a restore with UPTOP_ENCRYPTION_KEY set stores enc:-prefixed ciphertext, not plaintext. Alert error credential leak (alert.go): provider Send returned the raw *url.Error, whose URL carries the secret (Telegram bot token in the path, webhook secrets in the URL); it was persisted to AlertHealth.LastError and shown in the TUI. sanitizeError strips the URL, keeping the operation and underlying cause. Tests cover trusted/untrusted XFF + spoofed-bypass + map bound, the allowlist per provider, encrypted-on-import round-trip, and URL-stripped errors. README documents UPTOP_TRUSTED_PROXIES. Full suite green under -race; golangci-lint clean.
154 lines
3.4 KiB
Go
154 lines
3.4 KiB
Go
package server
|
|
|
|
import (
|
|
"net"
|
|
"net/http"
|
|
"strings"
|
|
"sync"
|
|
"time"
|
|
)
|
|
|
|
// maxVisitors caps the rate-limiter map so a flood of distinct keys can't grow
|
|
// it without bound. With the trusted-proxy gate below, keys come from real peer
|
|
// addresses, so this is a defense-in-depth ceiling rather than the primary
|
|
// guard.
|
|
const maxVisitors = 10000
|
|
|
|
type visitor struct {
|
|
tokens float64
|
|
lastSeen time.Time
|
|
}
|
|
|
|
type RateLimiter struct {
|
|
mu sync.Mutex
|
|
visitors map[string]*visitor
|
|
rate float64
|
|
burst float64
|
|
trusted []*net.IPNet
|
|
}
|
|
|
|
func NewRateLimiter(requestsPerMinute int, trusted []*net.IPNet) *RateLimiter {
|
|
rl := &RateLimiter{
|
|
visitors: make(map[string]*visitor),
|
|
rate: float64(requestsPerMinute) / 60.0,
|
|
burst: float64(requestsPerMinute),
|
|
trusted: trusted,
|
|
}
|
|
go rl.cleanup()
|
|
return rl
|
|
}
|
|
|
|
func (rl *RateLimiter) Allow(ip string) bool {
|
|
rl.mu.Lock()
|
|
defer rl.mu.Unlock()
|
|
|
|
v, exists := rl.visitors[ip]
|
|
now := time.Now()
|
|
|
|
if !exists {
|
|
if len(rl.visitors) >= maxVisitors {
|
|
rl.evictOldest()
|
|
}
|
|
rl.visitors[ip] = &visitor{tokens: rl.burst - 1, lastSeen: now}
|
|
return true
|
|
}
|
|
|
|
elapsed := now.Sub(v.lastSeen).Seconds()
|
|
v.tokens += elapsed * rl.rate
|
|
if v.tokens > rl.burst {
|
|
v.tokens = rl.burst
|
|
}
|
|
v.lastSeen = now
|
|
|
|
if v.tokens < 1 {
|
|
return false
|
|
}
|
|
v.tokens--
|
|
return true
|
|
}
|
|
|
|
// evictOldest removes the least-recently-seen visitor. Called only when the map
|
|
// is at capacity, so the O(n) scan is rare. Caller holds rl.mu.
|
|
func (rl *RateLimiter) evictOldest() {
|
|
var oldestKey string
|
|
var oldest time.Time
|
|
for k, v := range rl.visitors {
|
|
if oldestKey == "" || v.lastSeen.Before(oldest) {
|
|
oldestKey = k
|
|
oldest = v.lastSeen
|
|
}
|
|
}
|
|
if oldestKey != "" {
|
|
delete(rl.visitors, oldestKey)
|
|
}
|
|
}
|
|
|
|
func (rl *RateLimiter) cleanup() {
|
|
for {
|
|
time.Sleep(5 * time.Minute)
|
|
rl.mu.Lock()
|
|
cutoff := time.Now().Add(-10 * time.Minute)
|
|
for ip, v := range rl.visitors {
|
|
if v.lastSeen.Before(cutoff) {
|
|
delete(rl.visitors, ip)
|
|
}
|
|
}
|
|
rl.mu.Unlock()
|
|
}
|
|
}
|
|
|
|
// clientIP determines the rate-limit key for a request. X-Forwarded-For is only
|
|
// honored when the immediate peer (RemoteAddr) is a configured trusted proxy;
|
|
// otherwise the header is attacker-controlled and ignored, so a spoofed XFF
|
|
// can't mint unlimited distinct keys (rate-limit bypass + memory DoS). When the
|
|
// peer is trusted, the right-most address that is not itself a trusted proxy is
|
|
// the real client (RFC 7239 right-most-untrusted-hop).
|
|
func clientIP(r *http.Request, trusted []*net.IPNet) string {
|
|
host, _, err := net.SplitHostPort(r.RemoteAddr)
|
|
if err != nil {
|
|
host = r.RemoteAddr
|
|
}
|
|
|
|
if len(trusted) == 0 || !ipInCIDRs(net.ParseIP(host), trusted) {
|
|
return host
|
|
}
|
|
|
|
xff := r.Header.Get("X-Forwarded-For")
|
|
if xff == "" {
|
|
return host
|
|
}
|
|
parts := strings.Split(xff, ",")
|
|
for i := len(parts) - 1; i >= 0; i-- {
|
|
ip := net.ParseIP(strings.TrimSpace(parts[i]))
|
|
if ip == nil {
|
|
continue
|
|
}
|
|
if !ipInCIDRs(ip, trusted) {
|
|
return ip.String()
|
|
}
|
|
}
|
|
return host
|
|
}
|
|
|
|
func ipInCIDRs(ip net.IP, cidrs []*net.IPNet) bool {
|
|
if ip == nil {
|
|
return false
|
|
}
|
|
for _, c := range cidrs {
|
|
if c.Contains(ip) {
|
|
return true
|
|
}
|
|
}
|
|
return false
|
|
}
|
|
|
|
func RateLimit(limiter *RateLimiter, next http.HandlerFunc) http.HandlerFunc {
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
|
if !limiter.Allow(clientIP(r, limiter.trusted)) {
|
|
http.Error(w, "Rate limit exceeded", http.StatusTooManyRequests)
|
|
return
|
|
}
|
|
next(w, r)
|
|
}
|
|
}
|