2023-09-19 14:45:49 +02:00
|
|
|
package wg
|
|
|
|
|
|
|
|
import (
|
|
|
|
"net"
|
|
|
|
"os/exec"
|
|
|
|
|
2023-10-06 12:52:51 +02:00
|
|
|
logging "github.com/tim-beatham/wgmesh/pkg/log"
|
2023-09-19 14:45:49 +02:00
|
|
|
"golang.zx2c4.com/wireguard/wgctrl"
|
|
|
|
"golang.zx2c4.com/wireguard/wgctrl/wgtypes"
|
|
|
|
)
|
|
|
|
|
|
|
|
/*
|
|
|
|
* All WireGuard mesh interface called wgmesh
|
|
|
|
*/
|
|
|
|
func CreateInterface(ifName string) error {
|
|
|
|
_, err := net.InterfaceByName(ifName)
|
|
|
|
|
|
|
|
// Check if the interface exists
|
|
|
|
if err != nil {
|
|
|
|
cmd := exec.Command("/usr/bin/ip", "link", "add", "dev", ifName, "type", "wireguard")
|
|
|
|
|
|
|
|
if err := cmd.Run(); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
/*
|
|
|
|
* Create and configure a new WireGuard client
|
|
|
|
*/
|
2023-10-24 17:00:46 +02:00
|
|
|
func CreateWgInterface(client *wgctrl.Client, ifName string, port int) error {
|
2023-09-19 14:45:49 +02:00
|
|
|
err := CreateInterface(ifName)
|
|
|
|
|
|
|
|
if err != nil {
|
2023-10-24 17:00:46 +02:00
|
|
|
return err
|
2023-09-19 14:45:49 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
privateKey, err := wgtypes.GeneratePrivateKey()
|
|
|
|
|
|
|
|
if err != nil {
|
2023-10-24 17:00:46 +02:00
|
|
|
return err
|
2023-09-19 14:45:49 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
var cfg wgtypes.Config = wgtypes.Config{
|
|
|
|
PrivateKey: &privateKey,
|
2023-10-20 13:41:06 +02:00
|
|
|
ListenPort: &port,
|
2023-09-19 14:45:49 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
client.ConfigureDevice(ifName, cfg)
|
2023-10-24 17:00:46 +02:00
|
|
|
return nil
|
2023-09-19 14:45:49 +02:00
|
|
|
}
|
2023-09-21 19:43:29 +02:00
|
|
|
|
|
|
|
func EnableInterface(ifName string, ip string) error {
|
|
|
|
cmd := exec.Command("/usr/bin/ip", "link", "set", "up", "dev", ifName)
|
|
|
|
|
|
|
|
if err := cmd.Run(); err != nil {
|
2023-10-24 01:12:38 +02:00
|
|
|
logging.Log.WriteErrorf(err.Error())
|
2023-09-21 19:43:29 +02:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
hostIp, _, err := net.ParseCIDR(ip)
|
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2023-10-24 17:00:46 +02:00
|
|
|
cmd = exec.Command("/usr/bin/ip", "addr", "add", hostIp.String()+"/64", "dev", ifName)
|
2023-09-21 19:43:29 +02:00
|
|
|
|
|
|
|
if err := cmd.Run(); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|