2021-05-01 12:45:37 +02:00
|
|
|
package iface
|
|
|
|
|
|
|
|
import (
|
|
|
|
log "github.com/sirupsen/logrus"
|
|
|
|
"net"
|
2021-08-29 17:48:31 +02:00
|
|
|
"os"
|
2021-05-01 12:45:37 +02:00
|
|
|
"os/exec"
|
|
|
|
"strings"
|
|
|
|
)
|
|
|
|
|
2021-06-24 11:46:33 +02:00
|
|
|
// Create Creates a new Wireguard interface, sets a given IP and brings it up.
|
|
|
|
func Create(iface string, address string) error {
|
|
|
|
return CreateWithUserspace(iface, address)
|
|
|
|
}
|
2021-05-01 12:45:37 +02:00
|
|
|
|
|
|
|
// assignAddr Adds IP address to the tunnel interface and network route based on the range provided
|
2021-06-23 16:11:54 +02:00
|
|
|
func assignAddr(address string, ifaceName string) error {
|
2021-05-01 12:45:37 +02:00
|
|
|
ip := strings.Split(address, "/")
|
2021-06-06 00:40:44 +02:00
|
|
|
cmd := exec.Command("ifconfig", ifaceName, "inet", address, ip[0])
|
2021-05-01 12:45:37 +02:00
|
|
|
if out, err := cmd.CombinedOutput(); err != nil {
|
2021-06-15 00:02:42 +02:00
|
|
|
log.Infof("Command: %v failed with output %s and error: ", cmd.String(), out)
|
2021-05-01 12:45:37 +02:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
_, resolvedNet, err := net.ParseCIDR(address)
|
2021-06-06 00:40:44 +02:00
|
|
|
err = addRoute(ifaceName, resolvedNet)
|
2021-05-01 12:45:37 +02:00
|
|
|
if err != nil {
|
|
|
|
log.Infoln("Adding route failed with error:", err)
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// addRoute Adds network route based on the range provided
|
|
|
|
func addRoute(iface string, ipNet *net.IPNet) error {
|
|
|
|
cmd := exec.Command("route", "add", "-net", ipNet.String(), "-interface", iface)
|
|
|
|
if out, err := cmd.CombinedOutput(); err != nil {
|
|
|
|
log.Printf("Command: %v failed with output %s and error: ", cmd.String(), out)
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
2021-07-19 15:02:11 +02:00
|
|
|
|
|
|
|
// Closes the tunnel interface
|
|
|
|
func Close() error {
|
2021-08-29 17:48:31 +02:00
|
|
|
name, err := tunIface.Name()
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
sockPath := "/var/run/wireguard/" + name + ".sock"
|
|
|
|
|
|
|
|
err = CloseWithUserspace()
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
if _, err := os.Stat(sockPath); err == nil {
|
|
|
|
err = os.Remove(sockPath)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return nil
|
2021-07-19 15:02:11 +02:00
|
|
|
}
|