Browse Source

Merge pull request #482 from gravitl/hotfix_v0.9.0_windowsript

Hotfix v0.9.0 windowsript
Alex 3 years ago
parent
commit
881a7ad7ae

+ 1 - 0
database/postgres.go

@@ -4,6 +4,7 @@ import (
 	"database/sql"
 	"database/sql"
 	"errors"
 	"errors"
 	"fmt"
 	"fmt"
+
 	"github.com/gravitl/netmaker/servercfg"
 	"github.com/gravitl/netmaker/servercfg"
 	_ "github.com/lib/pq"
 	_ "github.com/lib/pq"
 )
 )

+ 3 - 37
netclient/ncutils/netclientutils.go

@@ -190,42 +190,6 @@ PersistentKeepAlive = %s
 	return peersString, nil
 	return peersString, nil
 }
 }
 
 
-// CreateUserSpaceConf - creates a user space WireGuard conf
-func CreateUserSpaceConf(address string, privatekey string, listenPort string, mtu int32, fwmark int32, perskeepalive int32, peers []wgtypes.PeerConfig) (string, error) {
-	peersString, err := parsePeers(perskeepalive, peers)
-	var listenPortString string
-	var fwmarkString string
-	if mtu <= 0 {
-		mtu = 1280
-	}
-	if listenPort != "" {
-		listenPortString += "ListenPort = " + listenPort
-	}
-	if fwmark != 0 {
-		fwmarkString += "FWMark = " + strconv.Itoa(int(fwmark))
-	}
-	if err != nil {
-		return "", err
-	}
-	config := fmt.Sprintf(`[Interface]
-Address = %s
-PrivateKey = %s
-MTU = %s
-%s
-%s
-
-%s
-
-`,
-		address+"/32",
-		privatekey,
-		strconv.Itoa(int(mtu)),
-		listenPortString,
-		fwmarkString,
-		peersString)
-	return config, nil
-}
-
 // GetLocalIP - gets local ip of machine
 // GetLocalIP - gets local ip of machine
 func GetLocalIP(localrange string) (string, error) {
 func GetLocalIP(localrange string) (string, error) {
 	_, localRange, err := net.ParseCIDR(localrange)
 	_, localRange, err := net.ParseCIDR(localrange)
@@ -279,7 +243,9 @@ func GetNetworkIPMask(networkstring string) (string, string, error) {
 		return "", "", err
 		return "", "", err
 	}
 	}
 	ipstring := ip.String()
 	ipstring := ip.String()
-	maskstring := ipnet.Mask.String()
+	mask := ipnet.Mask
+	maskstring := fmt.Sprintf("%d.%d.%d.%d", mask[0], mask[1], mask[2], mask[3])
+	//maskstring := ipnet.Mask.String()
 	return ipstring, maskstring, err
 	return ipstring, maskstring, err
 }
 }
 
 

+ 44 - 9
netclient/ncutils/netclientutils_darwin.go

@@ -8,14 +8,49 @@ import (
 
 
 // RunCmd - runs a local command
 // RunCmd - runs a local command
 func RunCmd(command string, printerr bool) (string, error) {
 func RunCmd(command string, printerr bool) (string, error) {
-        args := strings.Fields(command)
-        cmd := exec.Command(args[0], args[1:]...)
-        cmd.Wait()
-        out, err := cmd.CombinedOutput()
-        if err != nil && printerr {
-                log.Println("error running command:", command)
-                log.Println(strings.TrimSuffix(string(out), "\n"))
-        }
-        return string(out), err
+	args := strings.Fields(command)
+	cmd := exec.Command(args[0], args[1:]...)
+	cmd.Wait()
+	out, err := cmd.CombinedOutput()
+	if err != nil && printerr {
+		log.Println("error running command:", command)
+		log.Println(strings.TrimSuffix(string(out), "\n"))
+	}
+	return string(out), err
 }
 }
 
 
+// CreateUserSpaceConf - creates a user space WireGuard conf
+func CreateUserSpaceConf(address string, privatekey string, listenPort string, mtu int32, fwmark int32, perskeepalive int32, peers []wgtypes.PeerConfig) (string, error) {
+	peersString, err := parsePeers(perskeepalive, peers)
+	var listenPortString string
+	var fwmarkString string
+	if mtu <= 0 {
+		mtu = 1280
+	}
+	if listenPort != "" {
+		listenPortString += "ListenPort = " + listenPort
+	}
+	if fwmark != 0 {
+		fwmarkString += "FWMark = " + strconv.Itoa(int(fwmark))
+	}
+	if err != nil {
+		return "", err
+	}
+	config := fmt.Sprintf(`[Interface]
+Address = %s
+PrivateKey = %s
+MTU = %s
+%s
+%s
+
+%s
+
+`,
+		address+"/32",
+		privatekey,
+		strconv.Itoa(int(mtu)),
+		listenPortString,
+		fwmarkString,
+		peersString)
+	return config, nil
+}

+ 36 - 0
netclient/ncutils/netclientutils_linux.go

@@ -18,3 +18,39 @@ func RunCmd(command string, printerr bool) (string, error) {
 	}
 	}
 	return string(out), err
 	return string(out), err
 }
 }
+
+// CreateUserSpaceConf - creates a user space WireGuard conf
+func CreateUserSpaceConf(address string, privatekey string, listenPort string, mtu int32, fwmark int32, perskeepalive int32, peers []wgtypes.PeerConfig) (string, error) {
+	peersString, err := parsePeers(perskeepalive, peers)
+	var listenPortString string
+	var fwmarkString string
+	if mtu <= 0 {
+		mtu = 1280
+	}
+	if listenPort != "" {
+		listenPortString += "ListenPort = " + listenPort
+	}
+	if fwmark != 0 {
+		fwmarkString += "FWMark = " + strconv.Itoa(int(fwmark))
+	}
+	if err != nil {
+		return "", err
+	}
+	config := fmt.Sprintf(`[Interface]
+Address = %s
+PrivateKey = %s
+MTU = %s
+%s
+%s
+
+%s
+
+`,
+		address+"/32",
+		privatekey,
+		strconv.Itoa(int(mtu)),
+		listenPortString,
+		fwmarkString,
+		peersString)
+	return config, nil
+}

+ 54 - 0
netclient/ncutils/netclientutils_windows.go

@@ -1,9 +1,15 @@
 package ncutils
 package ncutils
 
 
 import (
 import (
+	"fmt"
 	"log"
 	"log"
+	"os"
 	"os/exec"
 	"os/exec"
+	"strconv"
 	"strings"
 	"strings"
+	"syscall"
+
+	"golang.zx2c4.com/wireguard/wgctrl/wgtypes"
 )
 )
 
 
 // RunCmd - runs a local command
 // RunCmd - runs a local command
@@ -11,6 +17,7 @@ func RunCmd(command string, printerr bool) (string, error) {
 	args := strings.Fields(command)
 	args := strings.Fields(command)
 	cmd := exec.Command(args[0], args[1:]...)
 	cmd := exec.Command(args[0], args[1:]...)
 	cmd.Wait()
 	cmd.Wait()
+	//cmd.SysProcAttr = &syscall.SysProcAttr{CmdLine: "/C \"" + command + "\""}
 	out, err := cmd.CombinedOutput()
 	out, err := cmd.CombinedOutput()
 	if err != nil && printerr {
 	if err != nil && printerr {
 		log.Println("error running command:", command)
 		log.Println("error running command:", command)
@@ -18,3 +25,50 @@ func RunCmd(command string, printerr bool) (string, error) {
 	}
 	}
 	return string(out), err
 	return string(out), err
 }
 }
+
+// RunCmd - runs a local command
+func RunCmdFormatted(command string, printerr bool) (string, error) {
+	var comSpec = os.Getenv("COMSPEC")
+	if comSpec == "" {
+		comSpec = os.Getenv("SystemRoot") + "\\System32\\cmd.exe"
+	}
+	cmd := exec.Command(comSpec)
+	cmd.SysProcAttr = &syscall.SysProcAttr{CmdLine: "/C \"" + command + "\""}
+	cmd.Wait()
+	out, err := cmd.CombinedOutput()
+	if err != nil && printerr {
+		log.Println("error running command:", command)
+		log.Println(strings.TrimSuffix(string(out), "\n"))
+	}
+	return string(out), err
+}
+
+// CreateUserSpaceConf - creates a user space WireGuard conf
+func CreateUserSpaceConf(address string, privatekey string, listenPort string, mtu int32, fwmark int32, perskeepalive int32, peers []wgtypes.PeerConfig) (string, error) {
+	peersString, err := parsePeers(perskeepalive, peers)
+	var listenPortString string
+	if mtu <= 0 {
+		mtu = 1280
+	}
+	if listenPort != "" {
+		listenPortString += "ListenPort = " + listenPort
+	}
+	if err != nil {
+		return "", err
+	}
+	config := fmt.Sprintf(`[Interface]
+Address = %s
+PrivateKey = %s
+MTU = %s
+%s
+
+%s
+
+`,
+		address+"/32",
+		privatekey,
+		strconv.Itoa(int(mtu)),
+		listenPortString,
+		peersString)
+	return config, nil
+}

+ 22 - 9
netclient/wireguard/common.go

@@ -1,6 +1,7 @@
 package wireguard
 package wireguard
 
 
 import (
 import (
+	"errors"
 	"fmt"
 	"fmt"
 	"io/ioutil"
 	"io/ioutil"
 	"log"
 	"log"
@@ -188,10 +189,9 @@ func InitWireguard(node *models.Node, privkey string, peers []wgtypes.PeerConfig
 		}
 		}
 		if ncutils.IsWindows() {
 		if ncutils.IsWindows() {
 			wgConfPath := ncutils.GetWGPathSpecific() + ifacename + ".conf"
 			wgConfPath := ncutils.GetWGPathSpecific() + ifacename + ".conf"
-			ncutils.PrintLog("error writing wg conf file to "+confPath+": "+err.Error(), 1)
 			err = ioutil.WriteFile(wgConfPath, []byte(newConf), 0644)
 			err = ioutil.WriteFile(wgConfPath, []byte(newConf), 0644)
 			if err != nil {
 			if err != nil {
-				ncutils.PrintLog("error writing wg conf file to "+confPath+": "+err.Error(), 1)
+				ncutils.PrintLog("error writing wg conf file to "+wgConfPath+": "+err.Error(), 1)
 				return err
 				return err
 			}
 			}
 			confPath = wgConfPath
 			confPath = wgConfPath
@@ -218,6 +218,25 @@ func InitWireguard(node *models.Node, privkey string, peers []wgtypes.PeerConfig
 				ncutils.PrintLog("failed to create wireguard interface", 1)
 				ncutils.PrintLog("failed to create wireguard interface", 1)
 				return err
 				return err
 			}
 			}
+			if ncutils.IsWindows() {
+				var output string
+				starttime := time.Now()
+				ncutils.PrintLog("waiting for interface...", 1)
+				for !strings.Contains(output, ifacename) && !(time.Now().After(starttime.Add(time.Duration(10) * time.Second))) {
+					output, _ = ncutils.RunCmd("wg", false)
+					time.Sleep(time.Second >> 1)
+					err = ApplyConf(confPath)
+				}
+				if !strings.Contains(output, ifacename) {
+					return errors.New("could not create wg interface for " + ifacename)
+				}
+				ip, mask, err := ncutils.GetNetworkIPMask(nodecfg.NetworkSettings.AddressRange)
+				if err != nil {
+					log.Println(err.Error())
+					return err
+				}
+				_, _ = ncutils.RunCmd("route add "+ip+" mask "+mask+" "+node.Address, true)
+			}
 		}
 		}
 	} else {
 	} else {
 		ipExec, err := exec.LookPath("ip")
 		ipExec, err := exec.LookPath("ip")
@@ -281,13 +300,7 @@ func InitWireguard(node *models.Node, privkey string, peers []wgtypes.PeerConfig
 	}
 	}
 
 
 	//extra network route setting required for freebsd and windows
 	//extra network route setting required for freebsd and windows
-	if ncutils.IsWindows() {
-		ip, mask, err := ncutils.GetNetworkIPMask(nodecfg.NetworkSettings.AddressRange)
-		if err != nil {
-			return err
-		}
-		_, _ = ncutils.RunCmd("route add "+ip+" mask "+mask+" "+node.Address, true)
-	} else if ncutils.IsFreeBSD() {
+	if ncutils.IsFreeBSD() {
 		_, _ = ncutils.RunCmd("route add -net "+nodecfg.NetworkSettings.AddressRange+" -interface "+ifacename, true)
 		_, _ = ncutils.RunCmd("route add -net "+nodecfg.NetworkSettings.AddressRange+" -interface "+ifacename, true)
 	}
 	}
 
 

+ 7 - 2
netclient/wireguard/windows.go

@@ -1,9 +1,14 @@
 package wireguard
 package wireguard
 
 
-import "github.com/gravitl/netmaker/netclient/ncutils"
+import (
+	"fmt"
+
+	"github.com/gravitl/netmaker/netclient/ncutils"
+)
 
 
 func ApplyWindowsConf(confPath string) error {
 func ApplyWindowsConf(confPath string) error {
-	if _, err := ncutils.RunCmd("wireguard.exe /installtunnelservice "+confPath, false); err != nil {
+	var commandLine = fmt.Sprintf(`wireguard.exe /installtunnelservice "%s"`, confPath)
+	if _, err := ncutils.RunCmdFormatted(commandLine, false); err != nil {
 		return err
 		return err
 	}
 	}
 	return nil
 	return nil

+ 6 - 11
scripts/netclient-install.ps1

@@ -1,4 +1,6 @@
 new-module -name netclient-install -scriptblock {
 new-module -name netclient-install -scriptblock {
+    $ErrorActionPreference = "Stop"
+
     function Quit {
     function Quit {
         param(
         param(
             $Text
             $Text
@@ -23,8 +25,7 @@ new-module -name netclient-install -scriptblock {
         $outpath = "$env:userprofile\Downloads\wireguard-installer.exe"
         $outpath = "$env:userprofile\Downloads\wireguard-installer.exe"
         Invoke-WebRequest -Uri $url -OutFile $outpath
         Invoke-WebRequest -Uri $url -OutFile $outpath
         $args = @("Comma","Separated","Arguments")
         $args = @("Comma","Separated","Arguments")
-        Start-Process -Filepath "$env:userprofile\Downloads\wireguard-installer.exe" -ArgumentList $args
-        Start-Sleep -Seconds 5
+        Start-Process -Filepath "$env:userprofile\Downloads\wireguard-installer.exe" -ArgumentList $args -Wait
         $software = "WireGuard";
         $software = "WireGuard";
         $installed = (Get-ItemProperty HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\* | Where { $_.DisplayName -eq $software }) -ne $null
         $installed = (Get-ItemProperty HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\* | Where { $_.DisplayName -eq $software }) -ne $null
         If(-Not $installed) {
         If(-Not $installed) {
@@ -44,9 +45,11 @@ new-module -name netclient-install -scriptblock {
         Write-Host "https://github.com/gravitl/netmaker/releases/download/$version/netclient.exe";
         Write-Host "https://github.com/gravitl/netmaker/releases/download/$version/netclient.exe";
         $url = "https://github.com/gravitl/netmaker/releases/download/$version/netclient.exe"
         $url = "https://github.com/gravitl/netmaker/releases/download/$version/netclient.exe"
         Invoke-WebRequest -Uri $url -OutFile $outpath
         Invoke-WebRequest -Uri $url -OutFile $outpath
+        $loc = Get-Location
+        Copy-Item -Path "$env:userprofile\Downloads\netclient.exe" -Destination "$loc\netclient.exe"
     }
     }
     $NetArgs = @("join","-t",$token)
     $NetArgs = @("join","-t",$token)
-    Start-Process -Filepath $outpath -ArgumentList $NetArgs
+    Start-Process -Filepath $outpath -ArgumentList $NetArgs -Wait
     Add-MpPreference -ExclusionPath "C:\ProgramData\Netclient"
     Add-MpPreference -ExclusionPath "C:\ProgramData\Netclient"
 
 
     if ((Get-Command "netclient.exe" -ErrorAction SilentlyContinue) -eq $null) { 
     if ((Get-Command "netclient.exe" -ErrorAction SilentlyContinue) -eq $null) { 
@@ -58,15 +61,7 @@ new-module -name netclient-install -scriptblock {
             Set-ItemProperty -Path 'Registry::HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Session Manager\Environment' -Name PATH -Value $newPath
             Set-ItemProperty -Path 'Registry::HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Session Manager\Environment' -Name PATH -Value $newPath
             $env:Path += ";C:\ProgramData\Netclient\bin"
             $env:Path += ";C:\ProgramData\Netclient\bin"
         }
         }
-        '''
-        Please add netclient.exe to your path to make it permanently executable from powershell:
-            1. Open "Edit environment variables for your account"
-            2. Double click on "Path"
-            3. On a new line, add the following: C:\ProgramData\Netclient\bin
-            4. Click "Ok"
-        '''
     }
     }
-
     Write-Host "'netclient' is installed."
     Write-Host "'netclient' is installed."
     }
     }
 }
 }