1
0
Fork 0
mirror of https://github.com/alice-lg/birdwatcher.git synced 2025-03-09 00:00:05 +01:00

Merge pull request #57 from jof/jof/cidr-allow-from

Config: allow_from: allow a mix of IPs and CIDRs
This commit is contained in:
Annika Hannig 2024-09-27 14:17:35 +02:00 committed by GitHub
commit 47a1721ed3
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 28 additions and 16 deletions

View file

@ -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 {

View file

@ -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