2021-09-20 02:03:47 +08:00
|
|
|
package wireguard
|
|
|
|
|
|
|
|
import (
|
2022-01-04 08:09:19 +08:00
|
|
|
"fmt"
|
2021-11-13 02:03:31 +08:00
|
|
|
"os"
|
2021-11-13 00:24:29 +08:00
|
|
|
|
2022-03-20 23:12:05 +08:00
|
|
|
"github.com/gravitl/netmaker/logger"
|
2021-09-20 02:03:47 +08:00
|
|
|
"github.com/gravitl/netmaker/netclient/ncutils"
|
|
|
|
)
|
|
|
|
|
2021-10-09 03:07:12 +08:00
|
|
|
// ApplyWGQuickConf - applies wg-quick commands if os supports
|
2022-08-20 00:08:31 +08:00
|
|
|
func ApplyWGQuickConf(confPath, ifacename string, isConnected bool) error {
|
2022-02-02 13:18:02 +08:00
|
|
|
if ncutils.IsWindows() {
|
2022-10-13 23:30:21 +08:00
|
|
|
return ApplyWindowsConf(confPath, ifacename, isConnected)
|
2022-02-02 13:18:02 +08:00
|
|
|
} else {
|
|
|
|
_, err := os.Stat(confPath)
|
|
|
|
if err != nil {
|
2022-03-20 23:12:05 +08:00
|
|
|
logger.Log(0, confPath+" does not exist "+err.Error())
|
2022-02-02 13:18:02 +08:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
if ncutils.IfaceExists(ifacename) {
|
|
|
|
ncutils.RunCmd("wg-quick down "+confPath, true)
|
|
|
|
}
|
2022-08-20 00:08:31 +08:00
|
|
|
if !isConnected {
|
|
|
|
return nil
|
|
|
|
}
|
2022-02-02 13:18:02 +08:00
|
|
|
_, err = ncutils.RunCmd("wg-quick up "+confPath, true)
|
2022-02-17 09:19:51 +08:00
|
|
|
|
2022-01-20 04:00:03 +08:00
|
|
|
return err
|
|
|
|
}
|
2021-11-13 00:24:29 +08:00
|
|
|
}
|
|
|
|
|
2021-10-09 03:07:12 +08:00
|
|
|
// RemoveWGQuickConf - calls wg-quick down
|
2021-09-20 02:03:47 +08:00
|
|
|
func RemoveWGQuickConf(confPath string, printlog bool) error {
|
2022-01-04 08:09:19 +08:00
|
|
|
_, err := ncutils.RunCmd(fmt.Sprintf("wg-quick down %s", confPath), printlog)
|
2021-11-13 00:24:29 +08:00
|
|
|
return err
|
2021-09-20 02:03:47 +08:00
|
|
|
}
|
|
|
|
|
2021-10-09 03:07:12 +08:00
|
|
|
// StorePrivKey - stores wg priv key on disk locally
|
2021-09-20 02:03:47 +08:00
|
|
|
func StorePrivKey(key string, network string) error {
|
2021-10-13 03:44:19 +08:00
|
|
|
var err error
|
2021-09-20 02:03:47 +08:00
|
|
|
d1 := []byte(key)
|
2022-02-02 00:03:14 +08:00
|
|
|
err = os.WriteFile(ncutils.GetNetclientPathSpecific()+"wgkey-"+network, d1, 0600)
|
2021-09-20 02:03:47 +08:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2021-10-09 03:07:12 +08:00
|
|
|
// RetrievePrivKey - reads wg priv key from local disk
|
2021-09-20 02:03:47 +08:00
|
|
|
func RetrievePrivKey(network string) (string, error) {
|
2022-02-06 03:26:19 +08:00
|
|
|
dat, err := ncutils.GetFileWithRetry(ncutils.GetNetclientPathSpecific()+"wgkey-"+network, 2)
|
2021-09-20 02:03:47 +08:00
|
|
|
return string(dat), err
|
|
|
|
}
|