dsnet/up.go
Andre Kelpe e782db30e9 Implements PostUp and PostDown commands using /bin/sh
This introduces PostUp and PostDown in dsnet. PostUp and PostDown allow
the user to run arbitrary commands after the device is up or down. These
are typically used to change the firewall rules via iptables. A working
example would be

...
    "PostUp" : "iptables -A FORWARD -i dsnet -j ACCEPT; iptables -A FORWARD -o dsnet -j ACCEPT; iptables -t nat -A POSTROUTING -o ens2 -j MASQUERADE ",
    "PostDown" : "iptables -D FORWARD -i dsnet -j ACCEPT; iptables -D FORWARD -o dsnet -j ACCEPT; iptables -t nat -D POSTROUTING -o ens2 -j MASQUERADE ",
...

All commands are executed by `/bin/sh` and no filtering or sandboxing is
applied. Users of this should know what they are doing.

Fixes https://github.com/naggie/dsnet/issues/16
2020-11-19 23:21:11 +01:00

65 lines
1.2 KiB
Go

package dsnet
import (
"net"
"github.com/vishvananda/netlink"
)
func Up() {
conf := MustLoadDsnetConfig()
CreateLink(conf)
ConfigureDevice(conf)
RunPostUp(conf)
}
func RunPostUp(conf *DsnetConfig) {
ShellOut(conf.PostUp, "PostUp")
}
func CreateLink(conf *DsnetConfig) {
linkAttrs := netlink.NewLinkAttrs()
linkAttrs.Name = conf.InterfaceName
link := &netlink.GenericLink{
LinkAttrs: linkAttrs,
LinkType: "wireguard",
}
err := netlink.LinkAdd(link)
if err != nil {
ExitFail("Could not add interface '%s' (%v)", conf.InterfaceName, err)
}
addr := &netlink.Addr{
IPNet: &net.IPNet{
IP: conf.IP,
Mask: conf.Network.IPNet.Mask,
},
}
err = netlink.AddrAdd(link, addr)
if err != nil {
ExitFail("Could not add addr %s to interface %s", addr.IP, err)
}
addr6 := &netlink.Addr{
IPNet: &net.IPNet{
IP: conf.IP6,
Mask: conf.Network6.IPNet.Mask,
},
}
err = netlink.AddrAdd(link, addr6)
if err != nil {
ExitFail("Could not add addr %s to interface %s", addr.IP, err)
}
// bring up interface (UNKNOWN state instead of UP, a wireguard quirk)
err = netlink.LinkSetUp(link)
if err != nil {
ExitFail("Could not bring up device '%s' (%v)", conf.InterfaceName, err)
}
}