From 0a7d656f4eaa1001c08b6e1fb0cbb4de78933af4 Mon Sep 17 00:00:00 2001 From: Jonathan Lassoff Date: Sat, 17 Feb 2024 22:30:05 -0800 Subject: [PATCH] Config: allow_from: allow a mix of IPs and CIDRs --- endpoints/endpoint.go | 37 ++++++++++++++++++++------------ etc/birdwatcher/birdwatcher.conf | 7 ++++-- 2 files changed, 28 insertions(+), 16 deletions(-) diff --git a/endpoints/endpoint.go b/endpoints/endpoint.go index 3dda116..2e28107 100644 --- a/endpoints/endpoint.go +++ b/endpoints/endpoint.go @@ -8,6 +8,7 @@ import ( "compress/gzip" "encoding/json" + "net" "net/http" "github.com/alice-lg/birdwatcher/bird" @@ -23,23 +24,31 @@ func CheckAccess(req *http.Request) error { return nil // AllowFrom ALL } - // Extract IP - tokens := strings.Split(req.RemoteAddr, ":") - ip := strings.Join(tokens[:len(tokens)-1], ":") - ip = strings.Replace(ip, "[", "", -1) - ip = strings.Replace(ip, "]", "", -1) - - // Check Access + ipStr, _, err := net.SplitHostPort(req.RemoteAddr) + if err != nil { + log.Println("Error parsing IP address:", err) + return fmt.Errorf("error parsing source IP address") + } + clientIP := net.ParseIP(ipStr) + if clientIP == nil { + log.Println("Invalid IP address format:", ipStr) + return fmt.Errorf("invalid source IP address format") + } for _, allowed := range Conf.AllowFrom { - if ip == allowed { - return nil + if _, allowedNet, err := net.ParseCIDR(allowed); err == nil { + if allowedNet.Contains(clientIP) { + return nil + } + } else if allowedIP := net.ParseIP(allowed); allowedIP != nil { + if allowedIP.Equal(clientIP) { + return nil + } + } else { + log.Printf("Invalid IP/CIDR format in configuration: %s\n", allowed); } } - - // Log this request - log.Println("Rejecting access from:", ip) - - return fmt.Errorf("%s is not allowed to access this service.", ip) + log.Println("Rejecting access from:", ipStr); + return fmt.Errorf("%s is not allowed to access this service", ipStr); } func CheckUseCache(req *http.Request) bool { diff --git a/etc/birdwatcher/birdwatcher.conf b/etc/birdwatcher/birdwatcher.conf index ac0bfee..2313d67 100755 --- a/etc/birdwatcher/birdwatcher.conf +++ b/etc/birdwatcher/birdwatcher.conf @@ -3,8 +3,11 @@ # [server] -# Restrict access to certain IPs. Leave empty to allow from all. -allow_from = [] +# Restrict access to certain IPs or CIDRs. Leave empty to allow from all. +allow_from = [ + "127.0.0.0/8", + "::1", +] # Allow queries that bypass the cache allow_uncached = false