This commit is contained in:
2026-10-20 15:09:00 +00:00
parent acfd556452
commit 08c871f84b
6 changed files with 67 additions and 67 deletions
+6 -5
View File
@@ -6,12 +6,13 @@ import (
) )
type Log struct { type Log struct {
Info log.Logger Info log.Logger
Warn log.Logger Warn log.Logger
Error log.Logger Error log.Logger
} }
var logger Log = Log{ var logger Log = Log{
Info: *log.New(os.Stdout, "[INFO]\t", log.Ltime|log.Lshortfile), Info: *log.New(os.Stdout, "[INFO]\t", log.Ltime|log.Lshortfile),
Warn: *log.New(os.Stderr, "[WARN]\t", log.Ltime|log.Lshortfile), Warn: *log.New(os.Stderr, "[WARN]\t", log.Ltime|log.Lshortfile),
Error: *log.New(os.Stderr, "[ERROR]\t", log.Ltime|log.Lshortfile), Error: *log.New(os.Stderr, "[ERROR]\t", log.Ltime|log.Lshortfile),
} }
+19 -19
View File
@@ -33,7 +33,7 @@ var envDefaults = map[string]string{
func main() { func main() {
// Environment-vars // Environment-vars
err := envChecks.HandleRequired(envRequired) err := envChecks.HandleRequired(envRequired)
if(err != nil){ if err != nil {
logger.Error.Fatal(err) logger.Error.Fatal(err)
} }
envChecks.HandleDefaults(envDefaults) envChecks.HandleDefaults(envDefaults)
@@ -67,7 +67,7 @@ func main() {
// Create filter // Create filter
filterOptions := FilterOptions{ filterOptions := FilterOptions{
Table: filterTable, Table: filterTable,
Protocol: filterProtocol, Protocol: filterProtocol,
} }
@@ -88,7 +88,6 @@ func main() {
logger.Error.Fatalf("Couldn't get wg-interface '%s': %s", iface, err) logger.Error.Fatalf("Couldn't get wg-interface '%s': %s", iface, err)
} }
// Subscribe to route-change events // Subscribe to route-change events
routeSubChan, routeSubDoneChan := make(chan netlink.RouteUpdate), make(chan struct{}) routeSubChan, routeSubDoneChan := make(chan netlink.RouteUpdate), make(chan struct{})
@@ -105,14 +104,14 @@ func main() {
logger.Info.Printf("Initially setting all current routes") logger.Info.Printf("Initially setting all current routes")
syncCurrentRoutesToHandler(routeSubChan, routeList) syncCurrentRoutesToHandler(routeSubChan, routeList)
if(periodicSync > 0){ if periodicSync > 0 {
go runPeriodicSync(periodicSync, link, routeSubChan) go runPeriodicSync(periodicSync, link, routeSubChan)
} }
select {} select {}
} }
func runPeriodicSync(seconds int, link netlink.Link, routeSubChan chan netlink.RouteUpdate){ func runPeriodicSync(seconds int, link netlink.Link, routeSubChan chan netlink.RouteUpdate) {
interval := time.Duration(seconds) * time.Second interval := time.Duration(seconds) * time.Second
for { for {
time.Sleep(interval) time.Sleep(interval)
@@ -128,11 +127,11 @@ func runPeriodicSync(seconds int, link netlink.Link, routeSubChan chan netlink.R
} }
} }
func syncCurrentRoutesToHandler(routeSubChan chan netlink.RouteUpdate, routeList []netlink.Route){ func syncCurrentRoutesToHandler(routeSubChan chan netlink.RouteUpdate, routeList []netlink.Route) {
for _, route := range routeList { for _, route := range routeList {
// Ignore routes with empty gateway // Ignore routes with empty gateway
if(route.Gw == nil){ if route.Gw == nil {
continue continue
} }
@@ -148,6 +147,7 @@ var routeUpdateTypeMapFromId = map[uint16]string{
unix.RTM_NEWROUTE: "+", unix.RTM_NEWROUTE: "+",
unix.RTM_DELROUTE: "-", unix.RTM_DELROUTE: "-",
} }
// TODO: Add proxy to apply filter in channels rather than.. this mess // TODO: Add proxy to apply filter in channels rather than.. this mess
func handleRouteEvents(routeSubChan <-chan netlink.RouteUpdate, filterOptions FilterOptions, iface string) { func handleRouteEvents(routeSubChan <-chan netlink.RouteUpdate, filterOptions FilterOptions, iface string) {
// Create wg-client // Create wg-client
@@ -162,20 +162,20 @@ func handleRouteEvents(routeSubChan <-chan netlink.RouteUpdate, filterOptions Fi
route := routeUpdate.Route route := routeUpdate.Route
// Check filter // Check filter
if(!CheckFilter(filterOptions, routeUpdate.Route)){ if !CheckFilter(filterOptions, routeUpdate.Route) {
continue continue
} }
// Special case for default-route // Special case for default-route
if route.Dst == nil{ if route.Dst == nil {
if route.Gw.To4() != nil { // IPv4 if route.Gw.To4() != nil { // IPv4
route.Dst = &net.IPNet{ route.Dst = &net.IPNet{
IP: net.IPv4zero, IP: net.IPv4zero,
Mask: net.CIDRMask(0, 32), Mask: net.CIDRMask(0, 32),
} }
} else { // IPv6 } else { // IPv6
route.Dst = &net.IPNet{ route.Dst = &net.IPNet{
IP: net.IPv6zero, IP: net.IPv6zero,
Mask: net.CIDRMask(0, 128), Mask: net.CIDRMask(0, 128),
} }
} }
@@ -192,10 +192,10 @@ func handleRouteEvents(routeSubChan <-chan netlink.RouteUpdate, filterOptions Fi
// Empty config for filling in switch // Empty config for filling in switch
var wgConfig wgtypes.Config var wgConfig wgtypes.Config
switch routeUpdate.Type{ switch routeUpdate.Type {
case unix.RTM_NEWROUTE: case unix.RTM_NEWROUTE:
// Check if gateway is set // Check if gateway is set
if route.Gw == nil{ if route.Gw == nil {
logger.Warn.Printf("Gateway unset, ignoring") logger.Warn.Printf("Gateway unset, ignoring")
continue continue
} }
@@ -208,7 +208,7 @@ func handleRouteEvents(routeSubChan <-chan netlink.RouteUpdate, filterOptions Fi
// Get peer containing gateway-addr // Get peer containing gateway-addr
peer, err := wgChecks.PeerByIP(&wgDevice.Peers, &route.Gw) peer, err := wgChecks.PeerByIP(&wgDevice.Peers, &route.Gw)
if(err != nil){ if err != nil {
logger.Warn.Printf("No peer found containing gw-IP '%s', ignoring", route.Gw) logger.Warn.Printf("No peer found containing gw-IP '%s', ignoring", route.Gw)
continue continue
} }
@@ -216,7 +216,7 @@ func handleRouteEvents(routeSubChan <-chan netlink.RouteUpdate, filterOptions Fi
// Set peerConfig, this will override set values for that peer // Set peerConfig, this will override set values for that peer
wgConfig.Peers = []wgtypes.PeerConfig{ wgConfig.Peers = []wgtypes.PeerConfig{
{ {
PublicKey: peer.PublicKey, PublicKey: peer.PublicKey,
AllowedIPs: append(peer.AllowedIPs, *route.Dst), AllowedIPs: append(peer.AllowedIPs, *route.Dst),
}, },
} }
@@ -224,7 +224,7 @@ func handleRouteEvents(routeSubChan <-chan netlink.RouteUpdate, filterOptions Fi
case unix.RTM_DELROUTE: case unix.RTM_DELROUTE:
// Get peer containing dst-NetIP // Get peer containing dst-NetIP
peerIndex, ipNetIndex, err := wgChecks.PeerIndexByIPNet(&wgDevice.Peers, route.Dst) peerIndex, ipNetIndex, err := wgChecks.PeerIndexByIPNet(&wgDevice.Peers, route.Dst)
if(err != nil){ if err != nil {
logger.Warn.Printf("No peer found having dst-IPNet '%s', ignoring", route.Dst) logger.Warn.Printf("No peer found having dst-IPNet '%s', ignoring", route.Dst)
continue continue
} }
@@ -237,17 +237,17 @@ func handleRouteEvents(routeSubChan <-chan netlink.RouteUpdate, filterOptions Fi
// Set peerConfig, this will override set values for that peer // Set peerConfig, this will override set values for that peer
wgConfig.Peers = []wgtypes.PeerConfig{ wgConfig.Peers = []wgtypes.PeerConfig{
{ {
PublicKey: peer.PublicKey, PublicKey: peer.PublicKey,
UpdateOnly: true, UpdateOnly: true,
ReplaceAllowedIPs: true, ReplaceAllowedIPs: true,
AllowedIPs: peer.AllowedIPs, AllowedIPs: peer.AllowedIPs,
}, },
} }
} }
err = client.ConfigureDevice(iface, wgConfig) err = client.ConfigureDevice(iface, wgConfig)
if(err != nil){ if err != nil {
logger.Error.Fatalf("Error configuring wg-device '%s': %s", iface, err) logger.Error.Fatalf("Error configuring wg-device '%s': %s", iface, err)
} }
} }
+6 -6
View File
@@ -1,25 +1,25 @@
package environmentchecks package environmentchecks
import ( import (
"os"
"fmt" "fmt"
"os"
) )
func HandleDefaults(envDefaults map[string]string){ func HandleDefaults(envDefaults map[string]string) {
for env, defaultValue := range envDefaults{ for env, defaultValue := range envDefaults {
// Check if env is set // Check if env is set
_, isSet := os.LookupEnv(env) _, isSet := os.LookupEnv(env)
if(!isSet){ if !isSet {
os.Setenv(env, defaultValue) os.Setenv(env, defaultValue)
} }
} }
} }
func HandleRequired(envRequired []string) error { func HandleRequired(envRequired []string) error {
for _, env := range envRequired{ for _, env := range envRequired {
// Check if env is set // Check if env is set
_, isSet := os.LookupEnv(env) _, isSet := os.LookupEnv(env)
if(!isSet){ if !isSet {
return fmt.Errorf("env '%s' required, but not set", env) return fmt.Errorf("env '%s' required, but not set", env)
} }
} }
+24 -24
View File
@@ -1,16 +1,16 @@
package iproute2mapping package iproute2mapping
import ( import (
"os"
"bufio" "bufio"
"strings"
"strconv"
"fmt" "fmt"
"os"
"strconv"
"strings"
) )
// Storage for mapping // Storage for mapping
var ByName = make(map[int]map[string]int) var ByName = make(map[int]map[string]int)
var ById = make(map[int]map[int]string) var ById = make(map[int]map[int]string)
// Mapping types // Mapping types
const ( const (
@@ -20,47 +20,47 @@ const (
// Paths // Paths
var filePaths = map[int]string{ var filePaths = map[int]string{
PROTOCOL: "/etc/iproute2/rt_protos", PROTOCOL: "/etc/iproute2/rt_protos",
TABLE: "/etc/iproute2/rt_tables", TABLE: "/etc/iproute2/rt_tables",
} }
// Export error-check // Export error-check
var Errors []error; var Errors []error
func init() { func init() {
var err error var err error
for mapType, filePath := range filePaths{ for mapType, filePath := range filePaths {
ByName[mapType], ById[mapType], err = readFromFile(filePath) ByName[mapType], ById[mapType], err = readFromFile(filePath)
if(err != nil){ if err != nil {
Errors = append(Errors, Errors = append(Errors,
fmt.Errorf("failed reading mapping-file '%s': %s", filePath, err), fmt.Errorf("failed reading mapping-file '%s': %s", filePath, err),
); )
} }
} }
} }
func readFromFile(filePath string) (mapByName map[string]int, mapById map[int]string, err error){ func readFromFile(filePath string) (mapByName map[string]int, mapById map[int]string, err error) {
file, err := os.Open(filePath) file, err := os.Open(filePath)
if(err != nil){ if err != nil {
return nil, nil, err; return nil, nil, err
} }
defer file.Close() defer file.Close()
scanner := bufio.NewScanner(file) scanner := bufio.NewScanner(file)
scanner.Split(bufio.ScanLines) scanner.Split(bufio.ScanLines)
mapByName = make(map[string]int) mapByName = make(map[string]int)
mapById = make(map[int]string) mapById = make(map[int]string)
// Go through file line-by-line // Go through file line-by-line
for scanner.Scan() { for scanner.Scan() {
text := scanner.Text() text := scanner.Text()
if(text == "" || strings.HasPrefix(text, "#")){ if text == "" || strings.HasPrefix(text, "#") {
continue continue
} }
id, name, err := getMappingFromText(text) id, name, err := getMappingFromText(text)
if(err != nil){ if err != nil {
// Only warn as we can continue processing the file // Only warn as we can continue processing the file
Errors = append(Errors, Errors = append(Errors,
fmt.Errorf("mappig-data invalid '%s': %s", text, err), fmt.Errorf("mappig-data invalid '%s': %s", text, err),
@@ -70,7 +70,7 @@ func readFromFile(filePath string) (mapByName map[string]int, mapById map[int]st
mapByName[name] = id mapByName[name] = id
mapById[id] = name mapById[id] = name
} }
return return
} }
@@ -80,7 +80,7 @@ func getMappingFromText(text string) (int, string, error) {
data := strings.Split(text, "\t") data := strings.Split(text, "\t")
id, err := strconv.Atoi(data[0]) id, err := strconv.Atoi(data[0])
if(err != nil){ if err != nil {
return 0, "", err return 0, "", err
} }
@@ -88,13 +88,13 @@ func getMappingFromText(text string) (int, string, error) {
} }
// Try getting an id from a name (or a string containing an id) with a specified type // Try getting an id from a name (or a string containing an id) with a specified type
func TryGetId(mappingType int, name string) (int, error){ func TryGetId(mappingType int, name string) (int, error) {
// Try to convert name to id // Try to convert name to id
id, err := strconv.Atoi(name) id, err := strconv.Atoi(name)
if(err != nil){ // name given -> Convert to id if err != nil { // name given -> Convert to id
var found bool var found bool
id, found = ByName[mappingType][name] id, found = ByName[mappingType][name]
if(!found){ if !found {
return 0, fmt.Errorf("no id found from name") return 0, fmt.Errorf("no id found from name")
} }
} }
-1
View File
@@ -1,2 +1 @@
package iproute2mapping package iproute2mapping
+2 -2
View File
@@ -19,7 +19,7 @@ func PeerIndexByIP(peers *[]wgtypes.Peer, ip *net.IP) (int, int, error) {
} }
func PeerByIP(peers *[]wgtypes.Peer, ip *net.IP) (*wgtypes.Peer, error) { func PeerByIP(peers *[]wgtypes.Peer, ip *net.IP) (*wgtypes.Peer, error) {
index, _, err := PeerIndexByIP(peers, ip) index, _, err := PeerIndexByIP(peers, ip)
if(err != nil) { if err != nil {
return nil, err return nil, err
} }
return &(*peers)[index], nil return &(*peers)[index], nil
@@ -35,7 +35,7 @@ func PeerIndexByIPNet(peers *[]wgtypes.Peer, ipNet *net.IPNet) (int, int, error)
} }
func PeerByIPNet(peers *[]wgtypes.Peer, ipNet *net.IPNet) (*wgtypes.Peer, error) { func PeerByIPNet(peers *[]wgtypes.Peer, ipNet *net.IPNet) (*wgtypes.Peer, error) {
index, _, err := PeerIndexByIPNet(peers, ipNet) index, _, err := PeerIndexByIPNet(peers, ipNet)
if(err != nil) { if err != nil {
return nil, err return nil, err
} }
return &(*peers)[index], nil return &(*peers)[index], nil