kernel.go 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325
  1. package wireguard
  2. import (
  3. "fmt"
  4. "io/ioutil"
  5. "log"
  6. "os"
  7. "os/exec"
  8. "strconv"
  9. "strings"
  10. "github.com/gravitl/netmaker/models"
  11. "github.com/gravitl/netmaker/netclient/config"
  12. "github.com/gravitl/netmaker/netclient/local"
  13. "github.com/gravitl/netmaker/netclient/netclientutils"
  14. "github.com/gravitl/netmaker/netclient/server"
  15. "golang.zx2c4.com/wireguard/wgctrl"
  16. "golang.zx2c4.com/wireguard/wgctrl/wgtypes"
  17. //homedir "github.com/mitchellh/go-homedir"
  18. )
  19. func InitWireguard(node *models.Node, privkey string, peers []wgtypes.PeerConfig, hasGateway bool, gateways []string) error {
  20. key, err := wgtypes.ParseKey(privkey)
  21. if err != nil {
  22. return err
  23. }
  24. wgclient, err := wgctrl.New()
  25. if err != nil {
  26. return err
  27. }
  28. modcfg, err := config.ReadConfig(node.Network)
  29. if err != nil {
  30. return err
  31. }
  32. nodecfg := modcfg.Node
  33. servercfg := modcfg.Server
  34. if err != nil {
  35. log.Fatalf("failed to open client: %v", err)
  36. }
  37. defer wgclient.Close()
  38. ifacename := node.Interface
  39. if nodecfg.Interface != "" {
  40. ifacename = nodecfg.Interface
  41. } else if node.Interface != "" {
  42. ifacename = node.Interface
  43. } else {
  44. log.Fatal("no interface to configure")
  45. }
  46. if node.Address == "" {
  47. log.Fatal("no address to configure")
  48. }
  49. nameserver := servercfg.CoreDNSAddr
  50. network := node.Network
  51. if nodecfg.Network != "" {
  52. network = nodecfg.Network
  53. } else if node.Network != "" {
  54. network = node.Network
  55. }
  56. if !netclientutils.IsWindows() {
  57. ipExec, err := exec.LookPath("ip")
  58. if err != nil {
  59. return err
  60. }
  61. _, _ = local.RunCmd("ip link delete dev " + ifacename, false)
  62. _, _ = local.RunCmd(ipExec + " link add dev " + ifacename + " type wireguard", true)
  63. _, _ = local.RunCmd(ipExec + " address add dev " + ifacename + " " + node.Address + "/24", true)
  64. }
  65. var nodeport int
  66. nodeport = int(node.ListenPort)
  67. conf := wgtypes.Config{}
  68. if nodecfg.UDPHolePunch == "yes" &&
  69. nodecfg.IsServer == "no" &&
  70. nodecfg.IsIngressGateway != "yes" &&
  71. nodecfg.IsStatic != "yes" {
  72. conf = wgtypes.Config{
  73. PrivateKey: &key,
  74. ReplacePeers: true,
  75. Peers: peers,
  76. }
  77. } else {
  78. conf = wgtypes.Config{
  79. PrivateKey: &key,
  80. ListenPort: &nodeport,
  81. ReplacePeers: true,
  82. Peers: peers,
  83. }
  84. }
  85. if netclientutils.IsWindows() {
  86. var newConf string
  87. if node.UDPHolePunch != "yes" {
  88. newConf, _ = netclientutils.CreateUserSpaceConf(node.Address, key.String(), strconv.FormatInt(int64(node.ListenPort), 10), node.MTU, node.PersistentKeepalive, peers)
  89. } else {
  90. newConf, _ = netclientutils.CreateUserSpaceConf(node.Address, key.String(), "", node.MTU, node.PersistentKeepalive, peers)
  91. }
  92. confPath := netclientutils.GetNetclientPathSpecific() + node.Interface + ".conf"
  93. err = ioutil.WriteFile(confPath, []byte(newConf), 0644)
  94. if err != nil {
  95. return err
  96. }
  97. // spin up userspace / windows interface + apply the conf file
  98. err := local.RemoveWindowsConf(node.Interface) // remove interface first
  99. if err != nil {
  100. log.Println("attempted to remove pre-existing windows interface before updating")
  101. }
  102. local.ApplyWindowsConf(confPath)
  103. } else {
  104. ipExec, err := exec.LookPath("ip")
  105. if err != nil {
  106. return err
  107. }
  108. _, err = wgclient.Device(ifacename)
  109. if err != nil {
  110. if os.IsNotExist(err) {
  111. fmt.Println("Device does not exist: ")
  112. fmt.Println(err)
  113. } else {
  114. log.Fatalf("Unknown config error: %v", err)
  115. }
  116. }
  117. err = wgclient.ConfigureDevice(ifacename, conf)
  118. if err != nil {
  119. if os.IsNotExist(err) {
  120. fmt.Println("Device does not exist: ")
  121. fmt.Println(err)
  122. } else {
  123. fmt.Printf("This is inconvenient: %v", err)
  124. }
  125. }
  126. //=========DNS Setup==========\\
  127. if nodecfg.DNSOn == "yes" {
  128. _ = local.UpdateDNS(ifacename, network, nameserver)
  129. }
  130. //=========End DNS Setup=======\\
  131. if _, err := local.RunCmd(ipExec + " link set down dev " + ifacename, false); err != nil {
  132. netclientutils.Log("attempted to remove interface before editing")
  133. return err
  134. }
  135. if nodecfg.PostDown != "" {
  136. runcmds := strings.Split(nodecfg.PostDown, "; ")
  137. err = local.RunCmds(runcmds, true)
  138. }
  139. // set MTU of node interface
  140. if _, err := local.RunCmd(ipExec + " link set mtu " + strconv.Itoa(int(nodecfg.MTU)) + " up dev " + ifacename, true); err != nil {
  141. netclientutils.Log("failed to create interface with mtu " + ifacename)
  142. return err
  143. }
  144. if nodecfg.PostUp != "" {
  145. runcmds := strings.Split(nodecfg.PostUp, "; ")
  146. err = local.RunCmds(runcmds, true)
  147. }
  148. if hasGateway {
  149. for _, gateway := range gateways {
  150. _, _ = local.RunCmd(ipExec + " -4 route add " + gateway + " dev " + ifacename, true)
  151. }
  152. }
  153. if node.Address6 != "" && node.IsDualStack == "yes" {
  154. log.Println("[netclient] adding address: " + node.Address6, 1)
  155. _, _ = local.RunCmd(ipExec + " address add dev " + ifacename + " " + node.Address6 + "/64", true)
  156. }
  157. }
  158. return err
  159. }
  160. func SetWGKeyConfig(network string, serveraddr string) error {
  161. cfg, err := config.ReadConfig(network)
  162. if err != nil {
  163. return err
  164. }
  165. node := cfg.Node
  166. privatekey, err := wgtypes.GeneratePrivateKey()
  167. if err != nil {
  168. return err
  169. }
  170. privkeystring := privatekey.String()
  171. publickey := privatekey.PublicKey()
  172. node.PublicKey = publickey.String()
  173. err = StorePrivKey(privkeystring, network)
  174. if err != nil {
  175. return err
  176. }
  177. if node.Action == models.NODE_UPDATE_KEY {
  178. node.Action = models.NODE_NOOP
  179. }
  180. err = config.ModConfig(&node)
  181. if err != nil {
  182. return err
  183. }
  184. err = SetWGConfig(network, false)
  185. if err != nil {
  186. return err
  187. }
  188. return err
  189. }
  190. func SetWGConfig(network string, peerupdate bool) error {
  191. cfg, err := config.ReadConfig(network)
  192. if err != nil {
  193. return err
  194. }
  195. servercfg := cfg.Server
  196. nodecfg := cfg.Node
  197. peers, hasGateway, gateways, err := server.GetPeers(nodecfg.MacAddress, nodecfg.Network, servercfg.GRPCAddress, nodecfg.IsDualStack == "yes", nodecfg.IsIngressGateway == "yes")
  198. if err != nil {
  199. return err
  200. }
  201. privkey, err := RetrievePrivKey(network)
  202. if err != nil {
  203. return err
  204. }
  205. if peerupdate {
  206. err = SetPeers(nodecfg.Interface, nodecfg.PersistentKeepalive, peers)
  207. } else {
  208. err = InitWireguard(&nodecfg, privkey, peers, hasGateway, gateways)
  209. }
  210. if err != nil {
  211. return err
  212. }
  213. return err
  214. }
  215. func SetPeers(iface string, keepalive int32, peers []wgtypes.PeerConfig) error {
  216. client, err := wgctrl.New()
  217. if err != nil {
  218. log.Println("failed to start wgctrl")
  219. return err
  220. }
  221. device, err := client.Device(iface)
  222. if err != nil {
  223. log.Println("failed to parse interface")
  224. return err
  225. }
  226. devicePeers := device.Peers
  227. if len(devicePeers) > 1 && len(peers) == 0 {
  228. log.Println("no peers pulled")
  229. return err
  230. }
  231. for _, peer := range peers {
  232. for _, currentPeer := range devicePeers {
  233. if currentPeer.AllowedIPs[0].String() == peer.AllowedIPs[0].String() &&
  234. currentPeer.PublicKey.String() != peer.PublicKey.String() {
  235. _, err := local.RunCmd("wg set " + iface + " peer " + currentPeer.PublicKey.String() + " remove", true)
  236. if err != nil {
  237. log.Println("error removing peer", peer.Endpoint.String())
  238. }
  239. }
  240. }
  241. udpendpoint := peer.Endpoint.String()
  242. var allowedips string
  243. var iparr []string
  244. for _, ipaddr := range peer.AllowedIPs {
  245. iparr = append(iparr, ipaddr.String())
  246. }
  247. allowedips = strings.Join(iparr, ",")
  248. keepAliveString := strconv.Itoa(int(keepalive))
  249. if keepAliveString == "0" {
  250. keepAliveString = "5"
  251. }
  252. if peer.Endpoint != nil {
  253. _, err = local.RunCmd("wg set " + iface + " peer " + peer.PublicKey.String() +
  254. " endpoint " + udpendpoint +
  255. " persistent-keepalive " + keepAliveString +
  256. " allowed-ips " + allowedips, true)
  257. } else {
  258. _, err = local.RunCmd("wg set " + iface + " peer " + peer.PublicKey.String() +
  259. " persistent-keepalive " + keepAliveString +
  260. " allowed-ips " + allowedips, true)
  261. }
  262. if err != nil {
  263. log.Println("error setting peer", peer.PublicKey.String())
  264. }
  265. }
  266. for _, currentPeer := range devicePeers {
  267. shouldDelete := true
  268. for _, peer := range peers {
  269. if peer.AllowedIPs[0].String() == currentPeer.AllowedIPs[0].String() {
  270. shouldDelete = false
  271. }
  272. }
  273. if shouldDelete {
  274. output, err := local.RunCmd("wg set " + iface + " peer " + currentPeer.PublicKey.String() + " remove", true)
  275. if err != nil {
  276. log.Println(output, "error removing peer", currentPeer.PublicKey.String())
  277. }
  278. }
  279. }
  280. return nil
  281. }
  282. func StorePrivKey(key string, network string) error {
  283. d1 := []byte(key)
  284. err := ioutil.WriteFile(netclientutils.GetNetclientPathSpecific()+"wgkey-"+network, d1, 0644)
  285. return err
  286. }
  287. func RetrievePrivKey(network string) (string, error) {
  288. dat, err := ioutil.ReadFile(netclientutils.GetNetclientPathSpecific() + "wgkey-" + network)
  289. return string(dat), err
  290. }