unix.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. package wireguard
  2. import (
  3. "io/ioutil"
  4. "github.com/gravitl/netmaker/models"
  5. "github.com/gravitl/netmaker/netclient/config"
  6. "github.com/gravitl/netmaker/netclient/ncutils"
  7. "golang.zx2c4.com/wireguard/wgctrl/wgtypes"
  8. )
  9. // SetWGKeyConfig - sets the wg conf with a new private key
  10. func SetWGKeyConfig(network string, serveraddr string) error {
  11. cfg, err := config.ReadConfig(network)
  12. if err != nil {
  13. return err
  14. }
  15. node := cfg.Node
  16. privatekey, err := wgtypes.GeneratePrivateKey()
  17. if err != nil {
  18. return err
  19. }
  20. privkeystring := privatekey.String()
  21. publickey := privatekey.PublicKey()
  22. node.PublicKey = publickey.String()
  23. err = StorePrivKey(privkeystring, network)
  24. if err != nil {
  25. return err
  26. }
  27. if node.Action == models.NODE_UPDATE_KEY {
  28. node.Action = models.NODE_NOOP
  29. }
  30. err = config.ModConfig(&node)
  31. if err != nil {
  32. return err
  33. }
  34. err = SetWGConfig(network, false)
  35. if err != nil {
  36. return err
  37. }
  38. return err
  39. }
  40. // ApplyWGQuickConf - applies wg-quick commands if os supports
  41. func ApplyWGQuickConf(confPath string) error {
  42. if _, err := ncutils.RunCmd("wg-quick up "+confPath, true); err != nil {
  43. return err
  44. }
  45. return nil
  46. }
  47. // RemoveWGQuickConf - calls wg-quick down
  48. func RemoveWGQuickConf(confPath string, printlog bool) error {
  49. if _, err := ncutils.RunCmd("wg-quick down "+confPath, printlog); err != nil {
  50. return err
  51. }
  52. return nil
  53. }
  54. // StorePrivKey - stores wg priv key on disk locally
  55. func StorePrivKey(key string, network string) error {
  56. var err error
  57. d1 := []byte(key)
  58. err = ioutil.WriteFile(ncutils.GetNetclientPathSpecific()+"wgkey-"+network, d1, 0644)
  59. return err
  60. }
  61. // RetrievePrivKey - reads wg priv key from local disk
  62. func RetrievePrivKey(network string) (string, error) {
  63. dat, err := ioutil.ReadFile(ncutils.GetNetclientPathSpecific() + "wgkey-" + network)
  64. return string(dat), err
  65. }