diff --git a/.env.example b/.env.example index 379cebd..e37bda9 100644 --- a/.env.example +++ b/.env.example @@ -26,4 +26,13 @@ MINIBIN_POW_DIFFICULTY=10 # comma separated options the user can select when reporting # options show in the order they are written # leading spaces WILL be included, so make sure you dont include them -MINIBIN_REPORT_OPTIONS="Malware (including links),CSAM/CSEM,Copyright Infringement,Fraud" \ No newline at end of file +MINIBIN_REPORT_OPTIONS="Malware (including links),CSAM/CSEM,Copyright Infringement,Fraud" +# chose where minibin gets the client's ip from +# available options: remote, cloudflare, xff +# remote: the ip connecting to minibin +# cloudflare: uses the CF-Connecting-IP header +# xff: uses the X-Forwarded-For header, ignores trusted proxies +MINIBIN_IP_ADDRESS_SOURCE=remote +# comma separated list of trusted CIDRs +# cloudflares: https://cloudflare.com/ips/ +MINIBIN_TRUSTED_PROXIES=127.0.0.1/32 \ No newline at end of file diff --git a/go.mod b/go.mod index fffd926..5b6410c 100644 --- a/go.mod +++ b/go.mod @@ -8,6 +8,7 @@ require ( github.com/glebarez/sqlite v1.11.0 github.com/joho/godotenv v1.5.1 golang.org/x/crypto v0.59.0 + golang.org/x/time v0.16.0 gorm.io/gorm v1.31.2 ) diff --git a/go.sum b/go.sum index 8dc027c..5b1bd46 100644 --- a/go.sum +++ b/go.sum @@ -30,6 +30,8 @@ golang.org/x/sys v0.50.0 h1:dkKZEFTEKaLr1sjhs0WiKqoi8Jj5nHbS3Njmx1UoMJs= golang.org/x/sys v0.50.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og= golang.org/x/text v0.44.0 h1:YItdp/mQNGnsmrgpcdA5yQ3bnRxCfo/Tj/iByGW9GGo= golang.org/x/text v0.44.0/go.mod h1:S4FR1waQ9LbjQTls97SyRjDaUUVkaM+cXwwuG/G+MwY= +golang.org/x/time v0.16.0 h1:vMb6ptszcQMkcwiRTAuNNU50gom6++Q/6gY2hDM6VDE= +golang.org/x/time v0.16.0/go.mod h1:rVKOqvZeKvrDKTQiAHJ7wmwP0RzleSphoEA9RcdLA0s= gorm.io/driver/sqlite v1.6.0 h1:WHRRrIiulaPiPFmDcod6prc4l2VGVWHz80KspNsxSfQ= gorm.io/driver/sqlite v1.6.0/go.mod h1:AO9V1qIQddBESngQUKWL9yoH93HIeA1X6V633rBwyT8= gorm.io/gorm v1.31.2 h1:3o8FXNo9v9S858gil+3LlZA1LkCOzgb4g5BL64FgaCo= diff --git a/internal/config/config.go b/internal/config/config.go index 938f1e2..097b4ed 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -3,7 +3,9 @@ package config import ( "fmt" "log" + "net/netip" "os" + "slices" "strconv" "strings" @@ -22,8 +24,10 @@ type Config struct { DatabasePath string // public host like "https://bin.zip", NOT the address minbin listens on - Host string - Addr string + Host string + Addr string + IPAdressSource string + TrustedProxies []netip.Prefix } func LoadConfig() (Config, error) { @@ -70,6 +74,21 @@ func LoadConfig() (Config, error) { if len(reportOptions) == 0 { return Config{}, fmt.Errorf("no valid report options set") } + ipAddressSource := envOrDefault("MINIBIN_IP_ADDRESS_SOURCE", "remote") + if !slices.Contains([]string{"remote", "cloudflare", "xff"}, ipAddressSource) { + return Config{}, fmt.Errorf("%s is not a valid MINIBIN_IP_ADDRESS_SOURCE option", ipAddressSource) + } + var trustedProxies []netip.Prefix + if rawTrusted := envOrDefault("MINIBIN_TRUSTED_PROXIES", ""); rawTrusted != "" { + for entry := range strings.SplitSeq(rawTrusted, ",") { + entry = strings.TrimSpace(entry) + prefix, err := netip.ParsePrefix(entry) + if err != nil { + return Config{}, fmt.Errorf("MINIBIN_TRUSTED_PROXIES: invalid cidr %q: %w", entry, err) + } + trustedProxies = append(trustedProxies, prefix) + } + } return Config{ UploadDir: envOrDefault("MINIBIN_UPLOAD_DIR", "uploads"), @@ -81,9 +100,11 @@ func LoadConfig() (Config, error) { PoWDifficulty: powDifficulty, ReportOptions: reportOptions, - DatabasePath: envOrDefault("MINIBIN_DATABASE_PATH", "minibin.sqlite"), - Host: envOrDefault("MINIBIN_HOST", "http://localhost:8080"), - Addr: envOrDefault("MINIBIN_ADDR", "localhost:8080"), + DatabasePath: envOrDefault("MINIBIN_DATABASE_PATH", "minibin.sqlite"), + Host: envOrDefault("MINIBIN_HOST", "http://localhost:8080"), + Addr: envOrDefault("MINIBIN_ADDR", "localhost:8080"), + IPAdressSource: ipAddressSource, + TrustedProxies: trustedProxies, }, nil } diff --git a/internal/middleware/ratelimit.go b/internal/middleware/ratelimit.go new file mode 100644 index 0000000..621e004 --- /dev/null +++ b/internal/middleware/ratelimit.go @@ -0,0 +1,65 @@ +package middleware + +import ( + "fmt" + "net/http" + "sync" + "time" + + p "git.whoswhip.dev/whoswhip/minibin/internal/pages" + "golang.org/x/time/rate" +) + +type bucket struct { + limiter *rate.Limiter + lastAccessedAt time.Time +} + +type RateLimiter struct { + buckets map[string]*bucket + refillEvery time.Duration + burst int + pages *p.Pages + resolveIP func(*http.Request) (string, error) + mu sync.Mutex +} + +func NewRateLimiter(refillEvery time.Duration, burst int, pages *p.Pages, resolveIP func(*http.Request) (string, error)) *RateLimiter { + return &RateLimiter{ + buckets: make(map[string]*bucket), + refillEvery: refillEvery, + burst: burst, + pages: pages, + resolveIP: resolveIP, + } +} + +func (rl *RateLimiter) LimitRequest(next http.HandlerFunc) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + ip, err := rl.resolveIP(r) + if err != nil { + rl.pages.HTTPError(w, r, "couldn't idenitify client address", http.StatusInternalServerError) + return + } + rl.mu.Lock() + b, ok := rl.buckets[ip] + if !ok { + b = &bucket{ + limiter: rate.NewLimiter(rate.Every(rl.refillEvery), rl.burst), + } + rl.buckets[ip] = b + } + b.lastAccessedAt = time.Now() + rl.mu.Unlock() + if !b.limiter.Allow() { + w.Header().Set("Retry-After", fmt.Sprintf("%.0f", rl.refillEvery.Seconds())) + rl.pages.HTTPError( + w, r, + fmt.Sprintf("too many requests, try again in %.0f seconds", rl.refillEvery.Seconds()), + http.StatusTooManyRequests, "429, slow down!", + ) + return + } + next(w, r) + } +} diff --git a/internal/pages/pages.go b/internal/pages/pages.go index e152abe..783be95 100644 --- a/internal/pages/pages.go +++ b/internal/pages/pages.go @@ -2,6 +2,7 @@ package pages import ( "errors" + "fmt" "html/template" "log" "math/rand/v2" @@ -137,12 +138,16 @@ func FaqHandler(pages *Pages, cfg config.Config) http.HandlerFunc { } } -func (pages *Pages) HTTPError(w http.ResponseWriter, r *http.Request, message string, status int) { +func (pages *Pages) HTTPError(w http.ResponseWriter, r *http.Request, message string, status int, title ...string) { if strings.Contains(r.Header.Get("Accept"), "text/html") { + t := fmt.Sprintf("%c", status) + if len(title) > 0 { + t = title[0] + } w.Header().Set("Content-Type", "text/html; charset=utf-8") w.WriteHeader(status) _ = pages.Templates.ExecuteTemplate(w, "result.html", map[string]any{ - "Title": status, + "Title": t, "Message": message, }) return diff --git a/internal/server/clientip.go b/internal/server/clientip.go new file mode 100644 index 0000000..0304099 --- /dev/null +++ b/internal/server/clientip.go @@ -0,0 +1,70 @@ +package server + +import ( + "fmt" + "net" + "net/http" + "net/netip" + "slices" + "strings" +) + +func newClientIPResolve(source string, trustedProxies []netip.Prefix) func(*http.Request) (string, error) { + isTrusted := func(ip netip.Addr) bool { + for _, prefix := range trustedProxies { + if prefix.Contains(ip) { + return true + } + } + return false + } + + return func(r *http.Request) (string, error) { + host, _, err := net.SplitHostPort(r.RemoteAddr) + if err != nil { + return "", err + } + + peer, err := netip.ParseAddr(host) + if err != nil { + return "", err + } + + if source == "remote" || !isTrusted(peer) { + return peer.String(), nil + } + + switch source { + case "cloudflare": + value := r.Header.Values("CF-Connecting-IP") + if len(value) != 1 { + return "", fmt.Errorf("expected a single CF-Connecting-IP header") + } + ip, err := netip.ParseAddr(value[0]) + if err != nil { + return "", fmt.Errorf("invalid CF-Connecting-IP: %w", err) + } + return ip.Unmap().String(), nil + case "xff": + values := r.Header.Values("X-Forwarded-For") + hops := strings.Split(strings.Join(values, ","), ",") + // walk backwards (right to left), while skipping trusted proxies, the first untrusted ip will be assumed to be the client ip + // https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/X-Forwarded-For#syntax + for _, hop := range slices.Backward(hops) { + if hop == "" { + continue + } + ip, err := netip.ParseAddr(strings.TrimSpace(hop)) + if err != nil { + return "", fmt.Errorf("invalid X-Forwarded-For hop: %w", err) + } + ip = ip.Unmap() + if !isTrusted(ip) { + return ip.String(), nil + } + } + return "", fmt.Errorf("no client ip in X-Forwarded-For") + } + return "", fmt.Errorf("unknown client ip source %q", source) + } +} diff --git a/internal/server/routes.go b/internal/server/routes.go index bce3645..d7d4aa1 100644 --- a/internal/server/routes.go +++ b/internal/server/routes.go @@ -3,8 +3,10 @@ package server import ( "fmt" "net/http" + "time" "git.whoswhip.dev/whoswhip/minibin/internal/config" + "git.whoswhip.dev/whoswhip/minibin/internal/middleware" "git.whoswhip.dev/whoswhip/minibin/internal/pages" "git.whoswhip.dev/whoswhip/minibin/internal/reports" "git.whoswhip.dev/whoswhip/minibin/internal/uploads" @@ -18,6 +20,7 @@ func health(w http.ResponseWriter, r *http.Request) { func NewRouter(db *gorm.DB, cfg config.Config, p *pages.Pages, tracker *uploads.AccessTracker, cStore *reports.ChallengeStore) http.Handler { mux := http.NewServeMux() + fs := http.FileServer(http.Dir("web/static")) mux.Handle("GET /css/", fs) mux.Handle("GET /js/", fs) @@ -26,20 +29,29 @@ func NewRouter(db *gorm.DB, cfg config.Config, p *pages.Pages, tracker *uploads. "/qts/", http.FileServer((http.Dir("qts"))), )) + mux.HandleFunc("GET /{$}", pages.HomeHandler(p, cfg)) mux.HandleFunc("GET /tos", pages.StaticPage(p, "tos.html")) mux.HandleFunc("GET /privacy", pages.StaticPage(p, "privacy.html")) mux.HandleFunc("GET /faq", pages.FaqHandler(p, cfg)) + + clientIpResolver := newClientIPResolve(cfg.IPAdressSource, cfg.TrustedProxies) + reportLimiter := middleware.NewRateLimiter(12*time.Second, 2, p, clientIpResolver) mux.HandleFunc("GET /report", reports.ReportPageHandler(p, cStore, cfg)) - mux.HandleFunc("POST /report", reports.ReportUploadHandler(db, cfg, p, cStore)) + mux.HandleFunc("POST /report", reportLimiter.LimitRequest(reports.ReportUploadHandler(db, cfg, p, cStore))) + u := http.NewServeMux() u.HandleFunc("GET /{id}", uploads.ContentHandler(db, cfg, tracker, p)) u.HandleFunc("GET /{id}/info", uploads.ContentInfoHandler(db, tracker, p)) mux.Handle("/", u) - mux.HandleFunc("POST /upload", uploads.UploadHandler(db, cfg, p)) - mux.HandleFunc("PUT /upload", uploads.UploadHandler(db, cfg, p)) - mux.HandleFunc("DELETE /{id}", uploads.DeleteHandler(db, cfg, p)) - mux.HandleFunc("POST /{id}/delete", uploads.DeleteHandler(db, cfg, p)) + + uploadLimiter := middleware.NewRateLimiter(6*time.Second, 3, p, clientIpResolver) + ulr := uploadLimiter.LimitRequest + mux.HandleFunc("POST /upload", ulr(uploads.UploadHandler(db, cfg, p))) + mux.HandleFunc("PUT /upload", ulr(uploads.UploadHandler(db, cfg, p))) + mux.HandleFunc("DELETE /{id}", ulr(uploads.DeleteHandler(db, cfg, p))) + mux.HandleFunc("POST /{id}/delete", ulr(uploads.DeleteHandler(db, cfg, p))) + mux.HandleFunc("GET /health", health) return mux } diff --git a/readme.md b/readme.md index 8443d08..a70aa93 100644 --- a/readme.md +++ b/readme.md @@ -41,7 +41,7 @@ goals: - ~~local access from a specifc ip or range only~~ - [ ] prometheus metrics - [x] [switch mime type detection library](https://git.whoswhip.dev/whoswhip/minibin/src/commit/47518993577f94d7cf9c0743042d2ac133055924/handlers.go#L273-L276) -- [ ] ratelimits +- [x] ratelimits - [ ] simplify rendering & serving pages (too much duplicate code rn) - [x] reports - [x] PoW challenges/captchas