netmaker/netclient/wireguard/common.go

439 lines
14 KiB
Go
Raw Normal View History

2021-09-20 02:03:47 +08:00
package wireguard
import (
"fmt"
2021-09-20 02:03:47 +08:00
"log"
2022-02-03 11:00:59 +08:00
"net"
2021-09-20 02:03:47 +08:00
"runtime"
"strconv"
"strings"
2021-09-22 05:50:09 +08:00
"time"
2021-09-20 02:03:47 +08:00
"github.com/gravitl/netmaker/models"
"github.com/gravitl/netmaker/netclient/config"
"github.com/gravitl/netmaker/netclient/local"
"github.com/gravitl/netmaker/netclient/ncutils"
"github.com/gravitl/netmaker/netclient/server"
"golang.zx2c4.com/wireguard/wgctrl"
"golang.zx2c4.com/wireguard/wgctrl/wgtypes"
"gopkg.in/ini.v1"
2021-09-20 02:03:47 +08:00
)
2022-01-05 23:32:20 +08:00
const (
section_interface = "Interface"
section_peers = "Peer"
)
2021-10-09 03:07:12 +08:00
// SetPeers - sets peers on a given WireGuard interface
2022-02-04 08:55:12 +08:00
func SetPeers(iface, currentNodeAddr string, keepalive int32, peers []wgtypes.PeerConfig) error {
2021-11-11 05:08:29 +08:00
var devicePeers []wgtypes.Peer
2022-02-03 11:00:59 +08:00
var oldPeerAllowedIps = make(map[string][]net.IPNet, len(peers))
2021-11-11 05:08:29 +08:00
var err error
if ncutils.IsFreeBSD() {
if devicePeers, err = ncutils.GetPeers(iface); err != nil {
return err
}
} else {
2021-11-12 21:53:50 +08:00
client, err := wgctrl.New()
if err != nil {
ncutils.PrintLog("failed to start wgctrl", 0)
return err
}
2021-12-11 04:01:10 +08:00
defer client.Close()
2021-11-12 21:53:50 +08:00
device, err := client.Device(iface)
if err != nil {
ncutils.PrintLog("failed to parse interface", 0)
return err
}
devicePeers = device.Peers
2021-11-11 05:08:29 +08:00
}
2021-09-20 02:03:47 +08:00
if len(devicePeers) > 1 && len(peers) == 0 {
ncutils.PrintLog("no peers pulled", 1)
return err
}
for _, peer := range peers {
for _, currentPeer := range devicePeers {
if currentPeer.AllowedIPs[0].String() == peer.AllowedIPs[0].String() &&
currentPeer.PublicKey.String() != peer.PublicKey.String() {
2021-09-23 02:31:31 +08:00
_, err := ncutils.RunCmd("wg set "+iface+" peer "+currentPeer.PublicKey.String()+" remove", true)
2021-09-20 02:03:47 +08:00
if err != nil {
log.Println("error removing peer", peer.Endpoint.String())
}
}
}
udpendpoint := peer.Endpoint.String()
var allowedips string
var iparr []string
for _, ipaddr := range peer.AllowedIPs {
iparr = append(iparr, ipaddr.String())
}
allowedips = strings.Join(iparr, ",")
keepAliveString := strconv.Itoa(int(keepalive))
if keepAliveString == "0" {
2021-11-12 21:53:50 +08:00
keepAliveString = "15"
2021-09-20 02:03:47 +08:00
}
if peer.Endpoint != nil {
_, err = ncutils.RunCmd("wg set "+iface+" peer "+peer.PublicKey.String()+
" endpoint "+udpendpoint+
" persistent-keepalive "+keepAliveString+
" allowed-ips "+allowedips, true)
} else {
_, err = ncutils.RunCmd("wg set "+iface+" peer "+peer.PublicKey.String()+
" persistent-keepalive "+keepAliveString+
" allowed-ips "+allowedips, true)
}
if err != nil {
log.Println("error setting peer", peer.PublicKey.String())
}
}
for _, currentPeer := range devicePeers {
shouldDelete := true
for _, peer := range peers {
if peer.AllowedIPs[0].String() == currentPeer.AllowedIPs[0].String() {
shouldDelete = false
}
}
if shouldDelete {
output, err := ncutils.RunCmd("wg set "+iface+" peer "+currentPeer.PublicKey.String()+" remove", true)
if err != nil {
log.Println(output, "error removing peer", currentPeer.PublicKey.String())
}
}
2022-02-03 11:00:59 +08:00
oldPeerAllowedIps[currentPeer.PublicKey.String()] = currentPeer.AllowedIPs
2021-09-20 02:03:47 +08:00
}
2022-01-12 23:03:23 +08:00
if ncutils.IsMac() {
err = SetMacPeerRoutes(iface)
return err
2022-02-03 09:46:25 +08:00
} else if ncutils.IsLinux() {
2022-02-04 08:55:12 +08:00
local.SetPeerRoutes(iface, currentNodeAddr, oldPeerAllowedIps, peers)
2022-01-12 23:03:23 +08:00
}
2021-09-20 02:03:47 +08:00
return nil
}
2021-10-09 03:07:12 +08:00
// Initializes a WireGuard interface
2021-11-13 00:24:29 +08:00
func InitWireguard(node *models.Node, privkey string, peers []wgtypes.PeerConfig, hasGateway bool, gateways []string, syncconf bool) error {
2021-09-20 02:03:47 +08:00
key, err := wgtypes.ParseKey(privkey)
if err != nil {
return err
}
wgclient, err := wgctrl.New()
if err != nil {
return err
}
2021-12-11 04:01:10 +08:00
defer wgclient.Close()
2021-09-20 02:03:47 +08:00
modcfg, err := config.ReadConfig(node.Network)
if err != nil {
return err
}
nodecfg := modcfg.Node
if err != nil {
log.Fatalf("failed to open client: %v", err)
}
2021-09-22 02:01:52 +08:00
var ifacename string
2021-09-20 02:03:47 +08:00
if nodecfg.Interface != "" {
ifacename = nodecfg.Interface
} else if node.Interface != "" {
ifacename = node.Interface
} else {
log.Fatal("no interface to configure")
}
if node.Address == "" {
log.Fatal("no address to configure")
}
if node.UDPHolePunch == "yes" {
2022-01-22 02:15:54 +08:00
node.ListenPort = 0
2021-09-20 02:03:47 +08:00
}
2022-01-22 02:15:54 +08:00
if err := WriteWgConfig(&modcfg.Node, key.String(), peers); err != nil {
ncutils.PrintLog("error writing wg conf file: "+err.Error(), 1)
return err
}
2022-01-22 02:15:54 +08:00
// spin up userspace / windows interface + apply the conf file
2022-01-25 20:31:50 +08:00
confPath := ncutils.GetNetclientPathSpecific() + ifacename + ".conf"
var deviceiface = ifacename
if ncutils.IsMac() { // if node is Mac (Darwin) get the tunnel name first
deviceiface, err = local.GetMacIface(node.Address)
if err != nil || deviceiface == "" {
deviceiface = ifacename
}
}
// ensure you clear any existing interface first
d, _ := wgclient.Device(deviceiface)
for d != nil && d.Name == deviceiface {
RemoveConf(ifacename, false) // remove interface first
time.Sleep(time.Second >> 2)
d, _ = wgclient.Device(deviceiface)
}
ApplyConf(node, deviceiface, confPath) // Apply initially
ncutils.PrintLog("waiting for interface...", 1) // ensure interface is created
output, _ := ncutils.RunCmd("wg", false)
starttime := time.Now()
2022-02-06 03:35:34 +08:00
ifaceReady := strings.Contains(output, ifacename)
2022-02-06 03:31:58 +08:00
for !ifaceReady && !(time.Now().After(starttime.Add(time.Second << 4))) {
output, _ = ncutils.RunCmd("wg", false)
err = ApplyConf(node, ifacename, confPath)
time.Sleep(time.Second)
2022-02-06 03:35:34 +08:00
ifaceReady = strings.Contains(output, ifacename)
}
newDevice, devErr := wgclient.Device(deviceiface)
if !ifaceReady || devErr != nil {
return fmt.Errorf("could not reliably create interface, please check wg installation and retry")
}
ncutils.PrintLog("interface ready - netclient engage", 1)
if syncconf { // should never be called really.
err = SyncWGQuickConf(ifacename, confPath)
}
currentPeers := newDevice.Peers
if len(currentPeers) == 0 { // if no peers currently, apply cidr
_, cidr, cidrErr := net.ParseCIDR(modcfg.NetworkSettings.AddressRange)
if cidrErr == nil {
local.SetCIDRRoute(ifacename, node.Address, cidr)
2021-11-13 00:24:29 +08:00
} else {
ncutils.PrintLog("could not set cidr route properly: "+cidrErr.Error(), 1)
2021-09-20 02:03:47 +08:00
}
} else { // if peers, apply each
local.SetCurrentPeerRoutes(ifacename, node.Address, currentPeers[:])
2021-11-15 05:50:20 +08:00
}
2021-09-20 02:03:47 +08:00
return err
}
2021-10-09 03:07:12 +08:00
// SetWGConfig - sets the WireGuard Config of a given network and checks if it needs a peer update
2021-09-20 02:03:47 +08:00
func SetWGConfig(network string, peerupdate bool) error {
cfg, err := config.ReadConfig(network)
if err != nil {
return err
}
servercfg := cfg.Server
nodecfg := cfg.Node
2021-09-23 02:31:31 +08:00
peers, hasGateway, gateways, err := server.GetPeers(nodecfg.MacAddress, nodecfg.Network, servercfg.GRPCAddress, nodecfg.IsDualStack == "yes", nodecfg.IsIngressGateway == "yes", nodecfg.IsServer == "yes")
2021-09-20 02:03:47 +08:00
if err != nil {
return err
}
privkey, err := RetrievePrivKey(network)
if err != nil {
return err
}
if peerupdate && !ncutils.IsFreeBSD() && !(ncutils.IsLinux() && !ncutils.IsKernel()) {
2021-09-20 02:03:47 +08:00
var iface string
iface = nodecfg.Interface
if ncutils.IsMac() {
iface, err = local.GetMacIface(nodecfg.Address)
if err != nil {
return err
}
}
2022-02-04 08:55:12 +08:00
err = SetPeers(iface, nodecfg.Address, nodecfg.PersistentKeepalive, peers)
2021-11-13 00:24:29 +08:00
} else if peerupdate {
err = InitWireguard(&nodecfg, privkey, peers, hasGateway, gateways, true)
2021-09-20 02:03:47 +08:00
} else {
2021-11-13 00:24:29 +08:00
err = InitWireguard(&nodecfg, privkey, peers, hasGateway, gateways, false)
2021-09-20 02:03:47 +08:00
}
if nodecfg.DNSOn == "yes" {
_ = local.UpdateDNS(nodecfg.Interface, nodecfg.Network, servercfg.CoreDNSAddr)
}
2021-09-20 02:03:47 +08:00
return err
}
2021-10-09 03:07:12 +08:00
// RemoveConf - removes a configuration for a given WireGuard interface
2021-09-20 02:03:47 +08:00
func RemoveConf(iface string, printlog bool) error {
os := runtime.GOOS
var err error
switch os {
case "windows":
err = RemoveWindowsConf(iface, printlog)
2022-01-12 07:28:41 +08:00
case "darwin":
err = RemoveConfMac(iface)
2021-09-20 02:03:47 +08:00
default:
confPath := ncutils.GetNetclientPathSpecific() + iface + ".conf"
err = RemoveWGQuickConf(confPath, printlog)
}
return err
}
2021-10-09 03:07:12 +08:00
// ApplyConf - applys a conf on disk to WireGuard interface
func ApplyConf(node *models.Node, ifacename string, confPath string) error {
2021-09-20 02:03:47 +08:00
os := runtime.GOOS
var err error
switch os {
case "windows":
2021-09-22 04:43:05 +08:00
_ = ApplyWindowsConf(confPath)
2022-01-12 07:28:41 +08:00
case "darwin":
_ = ApplyMacOSConf(node, ifacename, confPath)
2021-09-20 02:03:47 +08:00
default:
err = ApplyWGQuickConf(confPath, ifacename)
2021-09-20 02:03:47 +08:00
}
return err
}
// WriteWgConfig - creates a wireguard config file
2022-01-22 02:15:54 +08:00
//func WriteWgConfig(cfg *config.ClientConfig, privateKey string, peers []wgtypes.PeerConfig) error {
func WriteWgConfig(node *models.Node, privateKey string, peers []wgtypes.PeerConfig) error {
options := ini.LoadOptions{
AllowNonUniqueSections: true,
AllowShadows: true,
}
wireguard := ini.Empty(options)
2022-01-05 23:32:20 +08:00
wireguard.Section(section_interface).Key("PrivateKey").SetValue(privateKey)
2022-01-31 05:26:32 +08:00
if node.ListenPort > 0 && node.UDPHolePunch != "yes" {
2022-01-22 02:15:54 +08:00
wireguard.Section(section_interface).Key("ListenPort").SetValue(strconv.Itoa(int(node.ListenPort)))
}
2022-01-22 02:15:54 +08:00
if node.Address != "" {
wireguard.Section(section_interface).Key("Address").SetValue(node.Address)
}
2022-01-22 02:15:54 +08:00
if node.Address6 != "" {
wireguard.Section(section_interface).Key("Address").SetValue(node.Address6)
}
2022-01-22 02:15:54 +08:00
// need to figure out DNS
//if node.DNSOn == "yes" {
// wireguard.Section(section_interface).Key("DNS").SetValue(cfg.Server.CoreDNSAddr)
//}
if node.PostUp != "" {
wireguard.Section(section_interface).Key("PostUp").SetValue(node.PostUp)
}
2022-01-22 02:15:54 +08:00
if node.PostDown != "" {
wireguard.Section(section_interface).Key("PostDown").SetValue(node.PostDown)
}
2022-01-24 23:58:12 +08:00
if node.MTU != 0 {
wireguard.Section(section_interface).Key("MTU").SetValue(strconv.FormatInt(int64(node.MTU), 10))
}
for i, peer := range peers {
2022-01-05 23:32:20 +08:00
wireguard.SectionWithIndex(section_peers, i).Key("PublicKey").SetValue(peer.PublicKey.String())
if peer.PresharedKey != nil {
2022-01-05 23:32:20 +08:00
wireguard.SectionWithIndex(section_peers, i).Key("PreSharedKey").SetValue(peer.PresharedKey.String())
}
if peer.AllowedIPs != nil {
var allowedIPs string
2022-01-20 04:00:03 +08:00
for i, ip := range peer.AllowedIPs {
if i == 0 {
allowedIPs = ip.String()
} else {
allowedIPs = allowedIPs + ", " + ip.String()
}
}
2022-01-05 23:32:20 +08:00
wireguard.SectionWithIndex(section_peers, i).Key("AllowedIps").SetValue(allowedIPs)
}
if peer.Endpoint != nil {
2022-01-05 23:32:20 +08:00
wireguard.SectionWithIndex(section_peers, i).Key("Endpoint").SetValue(peer.Endpoint.String())
}
2022-01-22 02:15:54 +08:00
if peer.PersistentKeepaliveInterval != nil && peer.PersistentKeepaliveInterval.Seconds() > 0 {
wireguard.SectionWithIndex(section_peers, i).Key("PersistentKeepalive").SetValue(strconv.FormatInt((int64)(peer.PersistentKeepaliveInterval.Seconds()), 10))
}
}
2022-01-22 02:15:54 +08:00
if err := wireguard.SaveTo(ncutils.GetNetclientPathSpecific() + node.Interface + ".conf"); err != nil {
return err
}
return nil
}
// UpdateWgPeers - updates the peers of a network
2022-01-23 00:38:56 +08:00
func UpdateWgPeers(file string, peers []wgtypes.PeerConfig) error {
options := ini.LoadOptions{
AllowNonUniqueSections: true,
AllowShadows: true,
}
2022-01-20 04:00:03 +08:00
ncutils.Log("updating " + file)
wireguard, err := ini.LoadSources(options, file)
if err != nil {
return err
}
2022-01-20 04:00:03 +08:00
//delete the peers sections as they are going to be replaced
wireguard.DeleteSection(section_peers)
for i, peer := range peers {
2022-01-05 23:32:20 +08:00
wireguard.SectionWithIndex(section_peers, i).Key("PublicKey").SetValue(peer.PublicKey.String())
2022-01-23 00:38:56 +08:00
if peer.PresharedKey != nil {
wireguard.SectionWithIndex(section_peers, i).Key("PreSharedKey").SetValue(peer.PresharedKey.String())
}
if peer.AllowedIPs != nil {
var allowedIPs string
2022-01-20 04:00:03 +08:00
for i, ip := range peer.AllowedIPs {
if i == 0 {
allowedIPs = ip.String()
} else {
allowedIPs = allowedIPs + ", " + ip.String()
}
}
2022-01-05 23:32:20 +08:00
wireguard.SectionWithIndex(section_peers, i).Key("AllowedIps").SetValue(allowedIPs)
}
if peer.Endpoint != nil {
2022-01-05 23:32:20 +08:00
wireguard.SectionWithIndex(section_peers, i).Key("Endpoint").SetValue(peer.Endpoint.String())
}
2022-01-22 02:15:54 +08:00
if peer.PersistentKeepaliveInterval != nil && peer.PersistentKeepaliveInterval.Seconds() > 0 {
wireguard.SectionWithIndex(section_peers, i).Key("PersistentKeepalive").SetValue(strconv.FormatInt((int64)(peer.PersistentKeepaliveInterval.Seconds()), 10))
}
}
if err := wireguard.SaveTo(file); err != nil {
return err
}
return nil
}
// UpdateWgInterface - updates the interface section of a wireguard config file
2022-01-23 00:38:56 +08:00
func UpdateWgInterface(file, privateKey, nameserver string, node models.Node) error {
options := ini.LoadOptions{
AllowNonUniqueSections: true,
AllowShadows: true,
}
wireguard, err := ini.LoadSources(options, file)
if err != nil {
return err
}
if node.UDPHolePunch == "yes" {
node.ListenPort = 0
}
2022-01-05 23:32:20 +08:00
wireguard.Section(section_interface).Key("PrivateKey").SetValue(privateKey)
wireguard.Section(section_interface).Key("ListenPort").SetValue(strconv.Itoa(int(node.ListenPort)))
if node.Address != "" {
2022-01-05 23:32:20 +08:00
wireguard.Section(section_interface).Key("Address").SetValue(node.Address)
}
if node.Address6 != "" {
2022-01-05 23:32:20 +08:00
wireguard.Section(section_interface).Key("Address").SetValue(node.Address6)
}
2022-01-25 04:46:38 +08:00
//if node.DNSOn == "yes" {
// wireguard.Section(section_interface).Key("DNS").SetValue(nameserver)
//}
if node.PostUp != "" {
2022-01-05 23:32:20 +08:00
wireguard.Section(section_interface).Key("PostUp").SetValue(node.PostUp)
}
if node.PostDown != "" {
2022-01-05 23:32:20 +08:00
wireguard.Section(section_interface).Key("PostDown").SetValue(node.PostDown)
}
2022-01-24 23:58:12 +08:00
if node.MTU != 0 {
wireguard.Section(section_interface).Key("MTU").SetValue(strconv.FormatInt(int64(node.MTU), 10))
}
if err := wireguard.SaveTo(file); err != nil {
return err
}
return nil
}
// UpdatePrivateKey - updates the private key of a wireguard config file
2022-01-23 00:38:56 +08:00
func UpdatePrivateKey(file, privateKey string) error {
options := ini.LoadOptions{
AllowNonUniqueSections: true,
AllowShadows: true,
}
wireguard, err := ini.LoadSources(options, file)
if err != nil {
return err
}
2022-01-05 23:32:20 +08:00
wireguard.Section(section_interface).Key("PrivateKey").SetValue(privateKey)
if err := wireguard.SaveTo(file); err != nil {
return err
}
return nil
}