netmaker/netclient/wireguard/kernel.go

441 lines
10 KiB
Go
Raw Normal View History

2021-05-26 00:48:04 +08:00
package wireguard
import (
2021-07-27 22:48:58 +08:00
"github.com/davecgh/go-spew/spew"
2021-05-26 00:48:04 +08:00
"context"
2021-07-26 02:22:20 +08:00
"crypto/tls"
"errors"
"fmt"
"io/ioutil"
2021-05-26 00:48:04 +08:00
"log"
"net"
"os"
"os/exec"
2021-07-26 02:22:20 +08:00
"strconv"
"strings"
nodepb "github.com/gravitl/netmaker/grpc"
"github.com/gravitl/netmaker/models"
"github.com/gravitl/netmaker/netclient/auth"
"github.com/gravitl/netmaker/netclient/config"
"github.com/gravitl/netmaker/netclient/local"
"github.com/gravitl/netmaker/netclient/server"
2021-05-26 00:48:04 +08:00
"golang.zx2c4.com/wireguard/wgctrl"
"golang.zx2c4.com/wireguard/wgctrl/wgtypes"
2021-07-26 02:22:20 +08:00
"google.golang.org/grpc"
"google.golang.org/grpc/credentials"
"google.golang.org/grpc/metadata"
2021-05-26 00:48:04 +08:00
//homedir "github.com/mitchellh/go-homedir"
)
2021-07-26 02:22:20 +08:00
2021-05-28 02:54:24 +08:00
func InitGRPCWireguard(client models.IntClient) error {
2021-07-26 02:22:20 +08:00
//spew.Dump(client)
2021-06-02 23:00:10 +08:00
key, err := wgtypes.ParseKey(client.PrivateKey)
2021-07-26 02:22:20 +08:00
if err != nil {
return err
}
serverkey, err := wgtypes.ParseKey(client.ServerKey)
if err != nil {
return err
}
2021-06-02 06:40:04 +08:00
serverport, err := strconv.Atoi(client.ServerWGPort)
2021-07-26 02:22:20 +08:00
if err != nil {
return err
}
wgclient, err := wgctrl.New()
if err != nil {
log.Fatalf("failed to open client: %v", err)
}
defer wgclient.Close()
ifacename := "grpc-wg-001"
if client.Address6 == "" && client.Address == "" {
return errors.New("no address to configure")
}
cmdIPDevLinkAdd := exec.Command("ip", "link", "add", "dev", ifacename, "type", "wireguard")
2021-05-30 03:12:15 +08:00
cmdIPAddrAdd := exec.Command("ip", "address", "add", "dev", ifacename, client.Address+"/24")
cmdIPAddr6Add := exec.Command("ip", "address", "add", "dev", ifacename, client.Address6+"/64")
currentiface, err := net.InterfaceByName(ifacename)
2021-07-26 02:22:20 +08:00
if err != nil {
err = cmdIPDevLinkAdd.Run()
if err != nil && !strings.Contains(err.Error(), "exists") {
log.Println("Error creating interface")
}
}
match := false
match6 := false
addrs, _ := currentiface.Addrs()
2021-05-26 04:09:49 +08:00
//Add IPv4Address (make into separate function)
2021-07-26 02:22:20 +08:00
for _, a := range addrs {
if strings.Contains(a.String(), client.Address) {
match = true
}
if strings.Contains(a.String(), client.Address6) {
match6 = true
}
}
if !match && client.Address != "" {
2021-05-26 04:09:49 +08:00
err = cmdIPAddrAdd.Run()
2021-07-26 02:22:20 +08:00
if err != nil {
log.Println("Error adding ipv4 address")
fmt.Println(err)
}
}
if !match6 && client.Address6 != "" {
err = cmdIPAddr6Add.Run()
if err != nil {
log.Println("Error adding ipv6 address")
fmt.Println(err)
}
}
2021-05-26 04:09:49 +08:00
var peers []wgtypes.PeerConfig
2021-07-26 02:22:20 +08:00
var peeraddr = net.IPNet{
IP: net.ParseIP(client.ServerPrivateAddress),
Mask: net.CIDRMask(32, 32),
}
2021-05-26 04:09:49 +08:00
var allowedips []net.IPNet
2021-07-26 02:22:20 +08:00
allowedips = append(allowedips, peeraddr)
2021-06-02 06:40:04 +08:00
net.ParseIP(client.ServerPublicEndpoint)
2021-05-26 04:09:49 +08:00
peer := wgtypes.PeerConfig{
2021-07-26 02:22:20 +08:00
PublicKey: serverkey,
Endpoint: &net.UDPAddr{
IP: net.ParseIP(client.ServerPublicEndpoint),
Port: serverport,
},
ReplaceAllowedIPs: true,
AllowedIPs: allowedips,
}
2021-05-26 04:09:49 +08:00
peers = append(peers, peer)
2021-07-26 02:22:20 +08:00
conf := wgtypes.Config{
PrivateKey: &key,
ReplacePeers: true,
Peers: peers,
}
_, err = wgclient.Device(ifacename)
if err != nil {
if os.IsNotExist(err) {
log.Println("Device does not exist: ")
log.Println(err)
} else {
return err
}
}
2021-06-02 23:00:10 +08:00
//spew.Dump(conf)
2021-07-26 02:22:20 +08:00
err = wgclient.ConfigureDevice(ifacename, conf)
if err != nil {
if os.IsNotExist(err) {
log.Println("Device does not exist: ")
log.Println(err)
} else {
log.Printf("This is inconvenient: %v", err)
}
}
cmdIPLinkUp := exec.Command("ip", "link", "set", "up", "dev", ifacename)
cmdIPLinkDown := exec.Command("ip", "link", "set", "down", "dev", ifacename)
err = cmdIPLinkDown.Run()
err = cmdIPLinkUp.Run()
if err != nil {
return err
}
2021-05-30 03:12:15 +08:00
2021-05-26 04:09:49 +08:00
return err
}
2021-07-26 02:22:20 +08:00
func InitWireguard(node *nodepb.Node, privkey string, peers []wgtypes.PeerConfig, hasGateway bool, gateways []string) error {
2021-05-26 00:48:04 +08:00
ipExec, err := exec.LookPath("ip")
2021-07-26 02:22:20 +08:00
if err != nil {
2021-05-26 00:48:04 +08:00
return err
}
key, err := wgtypes.ParseKey(privkey)
2021-07-26 02:22:20 +08:00
if err != nil {
return err
}
2021-05-26 00:48:04 +08:00
2021-07-26 02:22:20 +08:00
wgclient, err := wgctrl.New()
if err != nil {
return err
}
2021-05-26 00:48:04 +08:00
modcfg, err := config.ReadConfig(node.Nodenetwork)
2021-05-26 04:09:49 +08:00
if err != nil {
2021-07-26 02:22:20 +08:00
return err
}
2021-05-26 00:48:04 +08:00
nodecfg := modcfg.Node
servercfg := modcfg.Server
2021-07-26 02:22:20 +08:00
if err != nil {
log.Fatalf("failed to open client: %v", err)
}
defer wgclient.Close()
2021-05-26 00:48:04 +08:00
ifacename := node.Interface
if nodecfg.Interface != "" {
ifacename = nodecfg.Interface
} else if node.Interface != "" {
ifacename = node.Interface
2021-07-26 02:22:20 +08:00
} else {
2021-05-26 00:48:04 +08:00
log.Fatal("no interface to configure")
}
if node.Address == "" {
log.Fatal("no address to configure")
}
2021-07-16 03:14:48 +08:00
nameserver := servercfg.CoreDNSAddr
2021-05-26 00:48:04 +08:00
network := node.Nodenetwork
2021-07-26 02:22:20 +08:00
if nodecfg.Network != "" {
network = nodecfg.Network
} else if node.Nodenetwork != "" {
network = node.Nodenetwork
}
cmdIPDevLinkAdd := &exec.Cmd{
Path: ipExec,
Args: []string{ipExec, "link", "add", "dev", ifacename, "type", "wireguard"},
Stdout: os.Stdout,
Stderr: os.Stdout,
2021-05-26 00:48:04 +08:00
}
2021-07-26 02:22:20 +08:00
cmdIPAddrAdd := &exec.Cmd{
Path: ipExec,
Args: []string{ipExec, "address", "add", "dev", ifacename, node.Address + "/24"},
Stdout: os.Stdout,
Stderr: os.Stdout,
}
currentiface, err := net.InterfaceByName(ifacename)
if err != nil {
err = cmdIPDevLinkAdd.Run()
if err != nil && !strings.Contains(err.Error(), "exists") {
fmt.Println("Error creating interface")
//fmt.Println(err.Error())
//return err
}
2021-05-26 00:48:04 +08:00
}
match := false
addrs, _ := currentiface.Addrs()
for _, a := range addrs {
2021-07-26 02:22:20 +08:00
if strings.Contains(a.String(), node.Address) {
2021-05-26 00:48:04 +08:00
match = true
}
}
if !match {
2021-07-26 02:22:20 +08:00
err = cmdIPAddrAdd.Run()
if err != nil {
fmt.Println("Error adding address")
//return err
}
2021-05-26 00:48:04 +08:00
}
var nodeport int
nodeport = int(node.Listenport)
2021-07-26 02:22:20 +08:00
conf := wgtypes.Config{}
2021-07-27 01:57:50 +08:00
if nodecfg.UDPHolePunch == "yes" && nodecfg.Name != "netmaker" {
2021-07-26 02:22:20 +08:00
conf = wgtypes.Config{
PrivateKey: &key,
ReplacePeers: true,
Peers: peers,
}
} else {
conf = wgtypes.Config{
PrivateKey: &key,
ListenPort: &nodeport,
ReplacePeers: true,
Peers: peers,
}
2021-05-26 00:48:04 +08:00
}
_, err = wgclient.Device(ifacename)
2021-07-26 02:22:20 +08:00
if err != nil {
if os.IsNotExist(err) {
fmt.Println("Device does not exist: ")
fmt.Println(err)
} else {
log.Fatalf("Unknown config error: %v", err)
}
}
2021-05-26 00:48:04 +08:00
err = wgclient.ConfigureDevice(ifacename, conf)
if err != nil {
if os.IsNotExist(err) {
fmt.Println("Device does not exist: ")
fmt.Println(err)
} else {
fmt.Printf("This is inconvenient: %v", err)
}
}
//=========DNS Setup==========\\
2021-07-28 10:23:20 +08:00
log.Println("NODECFG.DNS:",nodecfg.DNS)
2021-05-26 00:48:04 +08:00
if nodecfg.DNS == "on" {
2021-06-03 12:55:39 +08:00
_ = local.UpdateDNS(ifacename, network, nameserver)
2021-05-26 00:48:04 +08:00
}
2021-07-26 02:22:20 +08:00
//=========End DNS Setup=======\\
2021-06-02 23:00:10 +08:00
2021-07-26 02:22:20 +08:00
cmdIPLinkUp := &exec.Cmd{
Path: ipExec,
Args: []string{ipExec, "link", "set", "up", "dev", ifacename},
Stdout: os.Stdout,
Stderr: os.Stdout,
}
2021-06-02 23:00:10 +08:00
2021-07-26 02:22:20 +08:00
cmdIPLinkDown := &exec.Cmd{
Path: ipExec,
Args: []string{ipExec, "link", "set", "down", "dev", ifacename},
Stdout: os.Stdout,
Stderr: os.Stdout,
}
err = cmdIPLinkDown.Run()
if nodecfg.PostDown != "" {
2021-05-26 00:48:04 +08:00
runcmds := strings.Split(nodecfg.PostDown, "; ")
err = local.RunCmds(runcmds)
if err != nil {
fmt.Println("Error encountered running PostDown: " + err.Error())
}
}
err = cmdIPLinkUp.Run()
2021-07-26 02:22:20 +08:00
if err != nil {
return err
}
2021-05-26 00:48:04 +08:00
if nodecfg.PostUp != "" {
2021-07-26 02:22:20 +08:00
runcmds := strings.Split(nodecfg.PostUp, "; ")
err = local.RunCmds(runcmds)
2021-05-26 00:48:04 +08:00
if err != nil {
2021-07-26 02:22:20 +08:00
fmt.Println("Error encountered running PostUp: " + err.Error())
}
}
if hasGateway {
2021-07-27 22:48:58 +08:00
spew.Dump(gateways)
2021-07-26 02:22:20 +08:00
for _, gateway := range gateways {
2021-07-27 22:48:58 +08:00
log.Println("Gateway:")
spew.Dump(gateway)
2021-07-26 02:22:20 +08:00
out, err := exec.Command(ipExec, "-4", "route", "add", gateway, "dev", ifacename).Output()
fmt.Println(string(out))
if err != nil {
fmt.Println("Error encountered adding gateway: " + err.Error())
}
2021-05-26 00:48:04 +08:00
}
}
2021-07-26 02:22:20 +08:00
if node.Address6 != "" && node.Isdualstack {
2021-05-26 00:48:04 +08:00
fmt.Println("Adding address: " + node.Address6)
2021-07-26 02:22:20 +08:00
out, err := exec.Command(ipExec, "address", "add", "dev", ifacename, node.Address6+"/64").Output()
if err != nil {
fmt.Println(out)
fmt.Println("Error encountered adding ipv6: " + err.Error())
}
2021-05-26 00:48:04 +08:00
}
2021-06-02 23:00:10 +08:00
2021-05-26 00:48:04 +08:00
return err
}
func SetWGKeyConfig(network string, serveraddr string) error {
2021-07-26 02:22:20 +08:00
ctx := context.Background()
var header metadata.MD
2021-05-26 00:48:04 +08:00
2021-07-26 02:22:20 +08:00
cfg, err := config.ReadConfig(network)
if err != nil {
return err
}
2021-07-11 22:18:31 +08:00
2021-07-26 02:22:20 +08:00
var wcclient nodepb.NodeServiceClient
var requestOpts grpc.DialOption
requestOpts = grpc.WithInsecure()
if cfg.Server.GRPCSSL == "on" {
h2creds := credentials.NewTLS(&tls.Config{NextProtos: []string{"h2"}})
requestOpts = grpc.WithTransportCredentials(h2creds)
}
2021-07-11 22:18:31 +08:00
conn, err := grpc.Dial(serveraddr, requestOpts)
2021-07-26 02:22:20 +08:00
if err != nil {
fmt.Printf("Cant dial GRPC server: %v", err)
return err
}
wcclient = nodepb.NewNodeServiceClient(conn)
ctx, err = auth.SetJWT(wcclient, network)
if err != nil {
fmt.Printf("Failed to authenticate: %v", err)
return err
}
2021-05-26 00:48:04 +08:00
node := server.GetNode(network)
privatekey, err := wgtypes.GeneratePrivateKey()
if err != nil {
return err
}
privkeystring := privatekey.String()
publickey := privatekey.PublicKey()
node.Publickey = publickey.String()
err = StorePrivKey(privkeystring, network)
2021-07-26 02:22:20 +08:00
if err != nil {
return err
}
err = config.ModConfig(&node)
if err != nil {
return err
}
2021-05-26 00:48:04 +08:00
postnode := server.GetNode(network)
2021-07-26 02:22:20 +08:00
req := &nodepb.UpdateNodeReq{
Node: &postnode,
}
_, err = wcclient.UpdateNode(ctx, req, grpc.Header(&header))
if err != nil {
return err
}
err = SetWGConfig(network)
if err != nil {
return err
log.Fatalf("Error: %v", err)
}
2021-05-26 00:48:04 +08:00
2021-07-26 02:22:20 +08:00
return err
}
2021-05-26 00:48:04 +08:00
func SetWGConfig(network string) error {
2021-07-26 02:22:20 +08:00
cfg, err := config.ReadConfig(network)
if err != nil {
return err
}
2021-05-26 00:48:04 +08:00
servercfg := cfg.Server
2021-07-26 02:22:20 +08:00
nodecfg := cfg.Node
node := server.GetNode(network)
2021-05-26 00:48:04 +08:00
2021-05-26 04:09:49 +08:00
peers, hasGateway, gateways, err := server.GetPeers(node.Macaddress, nodecfg.Network, servercfg.GRPCAddress, node.Isdualstack, node.Isingressgateway)
2021-07-26 02:22:20 +08:00
if err != nil {
return err
}
2021-05-26 00:48:04 +08:00
privkey, err := RetrievePrivKey(network)
2021-07-26 02:22:20 +08:00
if err != nil {
return err
}
2021-05-26 00:48:04 +08:00
2021-07-26 02:22:20 +08:00
err = InitWireguard(&node, privkey, peers, hasGateway, gateways)
if err != nil {
return err
}
2021-05-26 00:48:04 +08:00
return err
}
2021-07-26 02:22:20 +08:00
func StorePrivKey(key string, network string) error {
2021-05-26 00:48:04 +08:00
d1 := []byte(key)
2021-07-26 02:22:20 +08:00
err := ioutil.WriteFile("/etc/netclient/wgkey-"+network, d1, 0644)
2021-05-26 00:48:04 +08:00
return err
}
func RetrievePrivKey(network string) (string, error) {
dat, err := ioutil.ReadFile("/etc/netclient/wgkey-" + network)
return string(dat), err
}