Merge branch 'dev'

main 0.3
Ruakij 2 years ago
commit 80ee221226

@ -7,8 +7,8 @@ import (
"time" "time"
envChecks "git.ruekov.eu/ruakij/routingtabletowg/lib/environmentchecks" envChecks "git.ruekov.eu/ruakij/routingtabletowg/lib/environmentchecks"
"git.ruekov.eu/ruakij/routingtabletowg/lib/wgchecks/netchecks" "git.ruekov.eu/ruakij/routingtabletowg/lib/wgchecks/netchecks"
"github.com/vishvananda/netlink" "github.com/vishvananda/netlink"
"golang.zx2c4.com/wireguard/wgctrl" "golang.zx2c4.com/wireguard/wgctrl"
"golang.zx2c4.com/wireguard/wgctrl/wgtypes" "golang.zx2c4.com/wireguard/wgctrl/wgtypes"
@ -18,152 +18,152 @@ var envRequired = []string{
"INTERFACE", "INTERFACE",
} }
var envDefaults = map[string]string{ var envDefaults = map[string]string{
"IPV6_FORMAT": "fc12::%02x%02x:%02x%02x/%d", "IPV6_FORMAT": "fc12::%02x%02x:%02x%02x/%d",
"FILTER_PREFIX": "100.100", "FILTER_PREFIX": "100.100",
"RECHECK_INTERVAL": "5m", "RECHECK_INTERVAL": "5m",
} }
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)
// Get the network interface object // Get the network interface object
iface := os.Getenv("INTERFACE") iface := os.Getenv("INTERFACE")
netInterface, err := netlink.LinkByName(iface) netInterface, err := netlink.LinkByName(iface)
if err != nil { if err != nil {
logger.Error.Fatal(err) logger.Error.Fatal(err)
} }
ipv6Format := os.Getenv("IPV6_FORMAT") ipv6Format := os.Getenv("IPV6_FORMAT")
ipv6TestStr := *convertIPv4ToIPv6(&ipv6Format, &net.IPNet{IP: net.IPv4(1,1,1,1), Mask: net.CIDRMask(24, net.IPv4len)}) ipv6TestStr := *convertIPv4ToIPv6(&ipv6Format, &net.IPNet{IP: net.IPv4(1, 1, 1, 1), Mask: net.CIDRMask(24, net.IPv4len)})
_, err = netlink.ParseIPNet(ipv6TestStr) _, err = netlink.ParseIPNet(ipv6TestStr)
if err != nil { if err != nil {
logger.Error.Fatalf("IPV6_FORMAT is invalid: %s", err) logger.Error.Fatalf("IPV6_FORMAT is invalid: %s", err)
} }
filterPrefix := os.Getenv("FILTER_PREFIX") filterPrefix := os.Getenv("FILTER_PREFIX")
checkIntervalStr := os.Getenv("RECHECK_INTERVAL") checkIntervalStr := os.Getenv("RECHECK_INTERVAL")
checkInterval, err := time.ParseDuration(checkIntervalStr) checkInterval, err := time.ParseDuration(checkIntervalStr)
if err != nil { if err != nil {
logger.Error.Fatalf("Couldn't parse RECHECK_INTERVAL '%s': %s", checkIntervalStr, err) logger.Error.Fatalf("Couldn't parse RECHECK_INTERVAL '%s': %s", checkIntervalStr, err)
} }
// Get the IPv4 address of the interface // Create a WireGuard client
addrs, err := netlink.AddrList(netInterface, netlink.FAMILY_V4) client, err := wgctrl.New()
if err != nil { if err != nil {
logger.Error.Fatal(err) logger.Error.Fatal(err)
} }
processedCount := 0 defer client.Close()
filteredCount := 0
for _, addr := range addrs { // Loop indefinitely
// Check filter for {
if addr.String()[:len(filterPrefix)] != filterPrefix { // Get the IPv4 addresses of the interface
filteredCount++ addrs, err := netlink.AddrList(netInterface, netlink.FAMILY_V4)
continue if err != nil {
} logger.Error.Fatal(err)
}
// Add the IPv6 address to the interface processedCount := 0
ipv6Str := *convertIPv4ToIPv6(&ipv6Format, addr.IPNet) filteredCount := 0
ipv6, err := netlink.ParseAddr(ipv6Str) for _, addr := range addrs {
if err != nil { // Check filter
logger.Warn.Printf("failed parsing converted %s -> %s : %s", addr.IPNet.String(), ipv6Str, err) if addr.String()[:len(filterPrefix)] != filterPrefix {
continue filteredCount++
} continue
}
logger.Info.Printf("Adding converted %s -> %s to interface", addr.IPNet.String(), ipv6Str)
err = netlink.AddrAdd(netInterface, ipv6) // Add the IPv6 address to the interface
if err != nil { ipv6Str := *convertIPv4ToIPv6(&ipv6Format, addr.IPNet)
switch { ipv6, err := netlink.ParseAddr(ipv6Str)
case os.IsExist(err): if err != nil {
logger.Warn.Println("Address is already set on interface") logger.Warn.Printf("failed parsing converted %s -> %s : %s", addr.IPNet.String(), ipv6Str, err)
default: continue
logger.Warn.Printf("Failed to set address on interface: %v", err) }
}
} logger.Info.Printf("Adding converted %s -> %s to interface", addr.IPNet.String(), ipv6Str)
processedCount++ err = netlink.AddrAdd(netInterface, ipv6)
} if err != nil {
if(processedCount != len(addrs)) { switch {
logger.Warn.Printf("Not all Interface-Addresses were processed. Summary: %d processed, %d filtered, %d failed", processedCount, filteredCount, len(addrs)-processedCount-filteredCount) case os.IsExist(err):
} logger.Warn.Println("Address is already set on interface")
default:
// Create a WireGuard client logger.Error.Fatalf("Failed to set address on interface: %v", err)
client, err := wgctrl.New() }
if err != nil { }
logger.Error.Fatal(err) processedCount++
} }
defer client.Close() if processedCount != len(addrs) {
logger.Warn.Printf("Not all Interface-Addresses were processed. Summary: %d processed, %d filtered, %d failed", processedCount, filteredCount, len(addrs)-processedCount-filteredCount)
// Loop indefinitely }
for {
// Get the WireGuard peers on the interface // Get the WireGuard peers on the interface
wgDevice, err := client.Device(iface) wgDevice, err := client.Device(iface)
if err != nil { if err != nil {
logger.Error.Fatalf("getting WireGuard device from interface '%s' failed: %s", iface, err) logger.Error.Fatalf("getting WireGuard device from interface '%s' failed: %s", iface, err)
} }
var wgConfig wgtypes.Config var wgConfig wgtypes.Config
wgConfig.Peers = make([]wgtypes.PeerConfig, 0, len(wgDevice.Peers)) wgConfig.Peers = make([]wgtypes.PeerConfig, 0, len(wgDevice.Peers))
for _, peer := range wgDevice.Peers { for _, peer := range wgDevice.Peers {
// Create slice for 1 expected addition // Create slice for 1 expected addition
var addAllowedIPs = make([]net.IPNet, 0, 1) var addAllowedIPs = make([]net.IPNet, 0, 1)
// Loop through the allowed-ips and add the ones starting with 100.100 // Loop through the allowed-ips and add the ones starting with 100.100
for _, allowedIP := range peer.AllowedIPs { for _, allowedIP := range peer.AllowedIPs {
if allowedIP.String()[:len(filterPrefix)] == filterPrefix { if allowedIP.String()[:len(filterPrefix)] == filterPrefix {
// Convert the IPv4 allowed-ip to an IPv6 address // Convert the IPv4 allowed-ip to an IPv6 address
ipv6Str := *convertIPv4ToIPv6(&ipv6Format, &allowedIP) ipv6Str := *convertIPv4ToIPv6(&ipv6Format, &allowedIP)
logger.Info.Printf("AllowedIP %s -> %s to peer %s", allowedIP.String(), ipv6Str, peer.PublicKey) logger.Info.Printf("AllowedIP %s -> %s to peer %s", allowedIP.String(), ipv6Str, peer.PublicKey)
ipv6, err := netlink.ParseIPNet(ipv6Str) ipv6, err := netlink.ParseIPNet(ipv6Str)
if err != nil { if err != nil {
logger.Warn.Printf("Couldnt parse IPv6 address %s of peer %s: %s", ipv6Str, peer.PublicKey, err) logger.Warn.Printf("Couldnt parse IPv6 address %s of peer %s: %s", ipv6Str, peer.PublicKey, err)
continue continue
} }
// Check if already set // Check if already set
if i, _ := netchecks.IPNetIndexByIPNet(&peer.AllowedIPs, ipv6); i != -1 { if i, _ := netchecks.IPNetIndexByIPNet(&peer.AllowedIPs, ipv6); i != -1 {
continue continue
} }
// Add the IPv6 allowed-ip to the peer // Add the IPv6 allowed-ip to the peer
addAllowedIPs = append(addAllowedIPs, *ipv6) addAllowedIPs = append(addAllowedIPs, *ipv6)
} }
} }
if(len(addAllowedIPs) > 0){ if len(addAllowedIPs) > 0 {
// Create peer-config // Create peer-config
peerConfig := wgtypes.PeerConfig{ peerConfig := wgtypes.PeerConfig{
PublicKey: peer.PublicKey, PublicKey: peer.PublicKey,
AllowedIPs: append(peer.AllowedIPs, addAllowedIPs...), AllowedIPs: append(peer.AllowedIPs, addAllowedIPs...),
} }
// Add entry // Add entry
wgConfig.Peers = append(wgConfig.Peers, peerConfig) wgConfig.Peers = append(wgConfig.Peers, peerConfig)
} }
} }
if(len(wgConfig.Peers) == 0){ if len(wgConfig.Peers) == 0 {
logger.Info.Println("No changes, skipping") logger.Info.Println("No changes, skipping")
} else { } else {
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)
} }
} }
// Sleep for x seconds before running the loop again // Sleep for x seconds before running the loop again
time.Sleep(checkInterval) time.Sleep(checkInterval)
} }
} }
func convertIPv4ToIPv6(ipv6Format *string, ipv4 *net.IPNet) (*string) { func convertIPv4ToIPv6(ipv6Format *string, ipv4 *net.IPNet) *string {
CIDR, _ := ipv4.Mask.Size() CIDR, _ := ipv4.Mask.Size()
// Run format // Run format
ipv6Str := fmt.Sprintf(*ipv6Format, (*ipv4).IP[0], (*ipv4).IP[1], (*ipv4).IP[2], (*ipv4).IP[3], net.IPv6len*8-(net.IPv4len*8-CIDR)) ipv6Str := fmt.Sprintf(*ipv6Format, (*ipv4).IP[0], (*ipv4).IP[1], (*ipv4).IP[2], (*ipv4).IP[3], net.IPv6len*8-(net.IPv4len*8-CIDR))
return &ipv6Str return &ipv6Str
} }

Loading…
Cancel
Save