From deb699c9d01acf127800ce7eedc8d40826b11e98 Mon Sep 17 00:00:00 2001 From: Robin Jarry Date: Wed, 18 Dec 2024 15:07:50 +0100 Subject: [PATCH] config: add global internal-ipnet setting Add support for a general [sr.ht]internal-ipnet list of networks that can be considered OK for internal operations. The default is loopback addresses (127.0.0.0/8 and ::1/128) and private routable unicast addresses (192.168.0.0/16, 10.0.0.0/8 and fc00::/7) Since parsing IP networks and addresses can be costly, store the result of [sr.ht]internal-ipnet into a global list of net.IPNet and a convenience IsInternalIP() function to be called by services. Signed-off-by: Robin Jarry --- config/config.go | 31 +++++++++++++++++++++++++++++-- 1 file changed, 29 insertions(+), 2 deletions(-) diff --git a/config/config.go b/config/config.go index ed07086da389b3b323f3723101bfaa8460e010f0..ee8afab92bd28bc788b7e4fce1ceede362be5d1b 100644 --- a/config/config.go +++ b/config/config.go @@ -3,9 +3,11 @@ package config import ( "fmt" "log" + "net" "os" "path/filepath" "strconv" + "strings" "git.sr.ht/~sircmpwn/getopt" "github.com/vaughan0/go-ini" @@ -14,8 +16,9 @@ import ( ) var ( - Debug bool - Addr string + Debug bool + Addr string + InternalIPNet []net.IPNet ) // Just loads the config files @@ -79,6 +82,19 @@ func LoadConfig(defaultAddr string) ini.File { config := LoadFiles() crypto.InitCrypto(config) + + nets, ok := config.Get("sr.ht", "internal-ipnet") + if !ok { + nets = "127.0.0.0/8,192.168.0.0/16,10.0.0.0/8,::1/128,fc00::/7" + } + for _, n := range strings.Split(nets, ",") { + _, net, err := net.ParseCIDR(n) + if err != nil { + panic(fmt.Errorf("[sr.ht]internal-ipnet: %w", err)) + } + InternalIPNet = append(InternalIPNet, *net) + } + return config } @@ -110,3 +126,14 @@ func GetInt(conf ini.File, section, name string, defValue int) int { } return value } + +// Returns true if the given IP address is part of the internal networks as +// per the configuration of [sr.ht]internal-ipnet. +func IsInternalIP(ip net.IP) bool { + for _, net := range InternalIPNet { + if net.Contains(ip) { + return true + } + } + return false +}