common.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440
  1. package wireguard
  2. import (
  3. "fmt"
  4. "log"
  5. "net"
  6. "runtime"
  7. "strconv"
  8. "strings"
  9. "time"
  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/ncutils"
  14. "github.com/gravitl/netmaker/netclient/server"
  15. "golang.zx2c4.com/wireguard/wgctrl"
  16. "golang.zx2c4.com/wireguard/wgctrl/wgtypes"
  17. "gopkg.in/ini.v1"
  18. )
  19. const (
  20. section_interface = "Interface"
  21. section_peers = "Peer"
  22. )
  23. // SetPeers - sets peers on a given WireGuard interface
  24. func SetPeers(iface, currentNodeAddr string, keepalive int32, peers []wgtypes.PeerConfig) error {
  25. var devicePeers []wgtypes.Peer
  26. var oldPeerAllowedIps = make(map[string][]net.IPNet, len(peers))
  27. var err error
  28. if ncutils.IsFreeBSD() {
  29. if devicePeers, err = ncutils.GetPeers(iface); err != nil {
  30. return err
  31. }
  32. } else {
  33. client, err := wgctrl.New()
  34. if err != nil {
  35. ncutils.PrintLog("failed to start wgctrl", 0)
  36. return err
  37. }
  38. defer client.Close()
  39. device, err := client.Device(iface)
  40. if err != nil {
  41. ncutils.PrintLog("failed to parse interface", 0)
  42. return err
  43. }
  44. devicePeers = device.Peers
  45. }
  46. if len(devicePeers) > 1 && len(peers) == 0 {
  47. ncutils.PrintLog("no peers pulled", 1)
  48. return err
  49. }
  50. for _, peer := range peers {
  51. for _, currentPeer := range devicePeers {
  52. if currentPeer.AllowedIPs[0].String() == peer.AllowedIPs[0].String() &&
  53. currentPeer.PublicKey.String() != peer.PublicKey.String() {
  54. _, err := ncutils.RunCmd("wg set "+iface+" peer "+currentPeer.PublicKey.String()+" remove", true)
  55. if err != nil {
  56. log.Println("error removing peer", peer.Endpoint.String())
  57. }
  58. }
  59. }
  60. udpendpoint := peer.Endpoint.String()
  61. var allowedips string
  62. var iparr []string
  63. for _, ipaddr := range peer.AllowedIPs {
  64. iparr = append(iparr, ipaddr.String())
  65. }
  66. allowedips = strings.Join(iparr, ",")
  67. keepAliveString := strconv.Itoa(int(keepalive))
  68. if keepAliveString == "0" {
  69. keepAliveString = "15"
  70. }
  71. if peer.Endpoint != nil {
  72. _, err = ncutils.RunCmd("wg set "+iface+" peer "+peer.PublicKey.String()+
  73. " endpoint "+udpendpoint+
  74. " persistent-keepalive "+keepAliveString+
  75. " allowed-ips "+allowedips, true)
  76. } else {
  77. _, err = ncutils.RunCmd("wg set "+iface+" peer "+peer.PublicKey.String()+
  78. " persistent-keepalive "+keepAliveString+
  79. " allowed-ips "+allowedips, true)
  80. }
  81. if err != nil {
  82. log.Println("error setting peer", peer.PublicKey.String())
  83. }
  84. }
  85. for _, currentPeer := range devicePeers {
  86. shouldDelete := true
  87. for _, peer := range peers {
  88. if peer.AllowedIPs[0].String() == currentPeer.AllowedIPs[0].String() {
  89. shouldDelete = false
  90. }
  91. }
  92. if shouldDelete {
  93. output, err := ncutils.RunCmd("wg set "+iface+" peer "+currentPeer.PublicKey.String()+" remove", true)
  94. if err != nil {
  95. log.Println(output, "error removing peer", currentPeer.PublicKey.String())
  96. }
  97. }
  98. oldPeerAllowedIps[currentPeer.PublicKey.String()] = currentPeer.AllowedIPs
  99. }
  100. if ncutils.IsMac() {
  101. err = SetMacPeerRoutes(iface)
  102. return err
  103. } else if ncutils.IsLinux() {
  104. local.SetPeerRoutes(iface, currentNodeAddr, oldPeerAllowedIps, peers)
  105. }
  106. return nil
  107. }
  108. // Initializes a WireGuard interface
  109. func InitWireguard(node *models.Node, privkey string, peers []wgtypes.PeerConfig, hasGateway bool, gateways []string, syncconf bool) error {
  110. key, err := wgtypes.ParseKey(privkey)
  111. if err != nil {
  112. return err
  113. }
  114. wgclient, err := wgctrl.New()
  115. if err != nil {
  116. return err
  117. }
  118. defer wgclient.Close()
  119. modcfg, err := config.ReadConfig(node.Network)
  120. if err != nil {
  121. return err
  122. }
  123. nodecfg := modcfg.Node
  124. if err != nil {
  125. log.Fatalf("failed to open client: %v", err)
  126. }
  127. var ifacename string
  128. if nodecfg.Interface != "" {
  129. ifacename = nodecfg.Interface
  130. } else if node.Interface != "" {
  131. ifacename = node.Interface
  132. } else {
  133. log.Fatal("no interface to configure")
  134. }
  135. if node.Address == "" {
  136. log.Fatal("no address to configure")
  137. }
  138. if node.UDPHolePunch == "yes" {
  139. node.ListenPort = 0
  140. }
  141. if err := WriteWgConfig(&modcfg.Node, key.String(), peers); err != nil {
  142. ncutils.PrintLog("error writing wg conf file: "+err.Error(), 1)
  143. return err
  144. }
  145. // spin up userspace / windows interface + apply the conf file
  146. confPath := ncutils.GetNetclientPathSpecific() + ifacename + ".conf"
  147. var deviceiface = ifacename
  148. if ncutils.IsMac() { // if node is Mac (Darwin) get the tunnel name first
  149. deviceiface, err = local.GetMacIface(node.Address)
  150. if err != nil || deviceiface == "" {
  151. deviceiface = ifacename
  152. }
  153. }
  154. // ensure you clear any existing interface first
  155. d, _ := wgclient.Device(deviceiface)
  156. for d != nil && d.Name == deviceiface {
  157. RemoveConf(ifacename, false) // remove interface first
  158. time.Sleep(time.Second >> 2)
  159. d, _ = wgclient.Device(deviceiface)
  160. }
  161. ApplyConf(node, deviceiface, confPath) // Apply initially
  162. ncutils.PrintLog("waiting for interface...", 1) // ensure interface is created
  163. output, _ := ncutils.RunCmd("wg", false)
  164. starttime := time.Now()
  165. ifaceReady := strings.Contains(output, ifacename)
  166. for !ifaceReady && !(time.Now().After(starttime.Add(time.Second << 4))) {
  167. output, _ = ncutils.RunCmd("wg", false)
  168. err = ApplyConf(node, ifacename, confPath)
  169. time.Sleep(time.Second)
  170. ifaceReady = strings.Contains(output, ifacename)
  171. }
  172. //wgclient does not work well on freebsd
  173. if node.OS == "freebsd" {
  174. if !ifaceReady {
  175. return fmt.Errorf("could not reliably create interface, please check wg installation and retry")
  176. }
  177. } else {
  178. _, devErr := wgclient.Device(deviceiface)
  179. if !ifaceReady || devErr != nil {
  180. return fmt.Errorf("could not reliably create interface, please check wg installation and retry")
  181. }
  182. }
  183. ncutils.PrintLog("interface ready - netclient engage", 1)
  184. if syncconf { // should never be called really.
  185. err = SyncWGQuickConf(ifacename, confPath)
  186. }
  187. _, cidr, cidrErr := net.ParseCIDR(modcfg.NetworkSettings.AddressRange)
  188. if cidrErr == nil {
  189. local.SetCIDRRoute(ifacename, node.Address, cidr)
  190. } else {
  191. ncutils.PrintLog("could not set cidr route properly: "+cidrErr.Error(), 1)
  192. }
  193. local.SetCurrentPeerRoutes(ifacename, node.Address, peers)
  194. return err
  195. }
  196. // SetWGConfig - sets the WireGuard Config of a given network and checks if it needs a peer update
  197. func SetWGConfig(network string, peerupdate bool) error {
  198. cfg, err := config.ReadConfig(network)
  199. if err != nil {
  200. return err
  201. }
  202. servercfg := cfg.Server
  203. nodecfg := cfg.Node
  204. peers, hasGateway, gateways, err := server.GetPeers(nodecfg.MacAddress, nodecfg.Network, servercfg.GRPCAddress, nodecfg.IsDualStack == "yes", nodecfg.IsIngressGateway == "yes", nodecfg.IsServer == "yes")
  205. if err != nil {
  206. return err
  207. }
  208. privkey, err := RetrievePrivKey(network)
  209. if err != nil {
  210. return err
  211. }
  212. if peerupdate && !ncutils.IsFreeBSD() && !(ncutils.IsLinux() && !ncutils.IsKernel()) {
  213. var iface string
  214. iface = nodecfg.Interface
  215. if ncutils.IsMac() {
  216. iface, err = local.GetMacIface(nodecfg.Address)
  217. if err != nil {
  218. return err
  219. }
  220. }
  221. err = SetPeers(iface, nodecfg.Address, nodecfg.PersistentKeepalive, peers)
  222. } else if peerupdate {
  223. err = InitWireguard(&nodecfg, privkey, peers, hasGateway, gateways, true)
  224. } else {
  225. err = InitWireguard(&nodecfg, privkey, peers, hasGateway, gateways, false)
  226. }
  227. if nodecfg.DNSOn == "yes" {
  228. _ = local.UpdateDNS(nodecfg.Interface, nodecfg.Network, servercfg.CoreDNSAddr)
  229. }
  230. return err
  231. }
  232. // RemoveConf - removes a configuration for a given WireGuard interface
  233. func RemoveConf(iface string, printlog bool) error {
  234. os := runtime.GOOS
  235. var err error
  236. switch os {
  237. case "windows":
  238. err = RemoveWindowsConf(iface, printlog)
  239. case "darwin":
  240. err = RemoveConfMac(iface)
  241. default:
  242. confPath := ncutils.GetNetclientPathSpecific() + iface + ".conf"
  243. err = RemoveWGQuickConf(confPath, printlog)
  244. }
  245. return err
  246. }
  247. // ApplyConf - applys a conf on disk to WireGuard interface
  248. func ApplyConf(node *models.Node, ifacename string, confPath string) error {
  249. os := runtime.GOOS
  250. var err error
  251. switch os {
  252. case "windows":
  253. _ = ApplyWindowsConf(confPath)
  254. case "darwin":
  255. _ = ApplyMacOSConf(node, ifacename, confPath)
  256. default:
  257. err = ApplyWGQuickConf(confPath, ifacename)
  258. }
  259. return err
  260. }
  261. // WriteWgConfig - creates a wireguard config file
  262. //func WriteWgConfig(cfg *config.ClientConfig, privateKey string, peers []wgtypes.PeerConfig) error {
  263. func WriteWgConfig(node *models.Node, privateKey string, peers []wgtypes.PeerConfig) error {
  264. options := ini.LoadOptions{
  265. AllowNonUniqueSections: true,
  266. AllowShadows: true,
  267. }
  268. wireguard := ini.Empty(options)
  269. wireguard.Section(section_interface).Key("PrivateKey").SetValue(privateKey)
  270. if node.ListenPort > 0 && node.UDPHolePunch != "yes" {
  271. wireguard.Section(section_interface).Key("ListenPort").SetValue(strconv.Itoa(int(node.ListenPort)))
  272. }
  273. if node.Address != "" {
  274. wireguard.Section(section_interface).Key("Address").SetValue(node.Address)
  275. }
  276. if node.Address6 != "" {
  277. wireguard.Section(section_interface).Key("Address").SetValue(node.Address6)
  278. }
  279. // need to figure out DNS
  280. //if node.DNSOn == "yes" {
  281. // wireguard.Section(section_interface).Key("DNS").SetValue(cfg.Server.CoreDNSAddr)
  282. //}
  283. if node.PostUp != "" {
  284. wireguard.Section(section_interface).Key("PostUp").SetValue(node.PostUp)
  285. }
  286. if node.PostDown != "" {
  287. wireguard.Section(section_interface).Key("PostDown").SetValue(node.PostDown)
  288. }
  289. if node.MTU != 0 {
  290. wireguard.Section(section_interface).Key("MTU").SetValue(strconv.FormatInt(int64(node.MTU), 10))
  291. }
  292. for i, peer := range peers {
  293. wireguard.SectionWithIndex(section_peers, i).Key("PublicKey").SetValue(peer.PublicKey.String())
  294. if peer.PresharedKey != nil {
  295. wireguard.SectionWithIndex(section_peers, i).Key("PreSharedKey").SetValue(peer.PresharedKey.String())
  296. }
  297. if peer.AllowedIPs != nil {
  298. var allowedIPs string
  299. for i, ip := range peer.AllowedIPs {
  300. if i == 0 {
  301. allowedIPs = ip.String()
  302. } else {
  303. allowedIPs = allowedIPs + ", " + ip.String()
  304. }
  305. }
  306. wireguard.SectionWithIndex(section_peers, i).Key("AllowedIps").SetValue(allowedIPs)
  307. }
  308. if peer.Endpoint != nil {
  309. wireguard.SectionWithIndex(section_peers, i).Key("Endpoint").SetValue(peer.Endpoint.String())
  310. }
  311. if peer.PersistentKeepaliveInterval != nil && peer.PersistentKeepaliveInterval.Seconds() > 0 {
  312. wireguard.SectionWithIndex(section_peers, i).Key("PersistentKeepalive").SetValue(strconv.FormatInt((int64)(peer.PersistentKeepaliveInterval.Seconds()), 10))
  313. }
  314. }
  315. if err := wireguard.SaveTo(ncutils.GetNetclientPathSpecific() + node.Interface + ".conf"); err != nil {
  316. return err
  317. }
  318. return nil
  319. }
  320. // UpdateWgPeers - updates the peers of a network
  321. func UpdateWgPeers(file string, peers []wgtypes.PeerConfig) error {
  322. options := ini.LoadOptions{
  323. AllowNonUniqueSections: true,
  324. AllowShadows: true,
  325. }
  326. ncutils.Log("updating " + file)
  327. wireguard, err := ini.LoadSources(options, file)
  328. if err != nil {
  329. return err
  330. }
  331. //delete the peers sections as they are going to be replaced
  332. wireguard.DeleteSection(section_peers)
  333. for i, peer := range peers {
  334. wireguard.SectionWithIndex(section_peers, i).Key("PublicKey").SetValue(peer.PublicKey.String())
  335. if peer.PresharedKey != nil {
  336. wireguard.SectionWithIndex(section_peers, i).Key("PreSharedKey").SetValue(peer.PresharedKey.String())
  337. }
  338. if peer.AllowedIPs != nil {
  339. var allowedIPs string
  340. for i, ip := range peer.AllowedIPs {
  341. if i == 0 {
  342. allowedIPs = ip.String()
  343. } else {
  344. allowedIPs = allowedIPs + ", " + ip.String()
  345. }
  346. }
  347. wireguard.SectionWithIndex(section_peers, i).Key("AllowedIps").SetValue(allowedIPs)
  348. }
  349. if peer.Endpoint != nil {
  350. wireguard.SectionWithIndex(section_peers, i).Key("Endpoint").SetValue(peer.Endpoint.String())
  351. }
  352. if peer.PersistentKeepaliveInterval != nil && peer.PersistentKeepaliveInterval.Seconds() > 0 {
  353. wireguard.SectionWithIndex(section_peers, i).Key("PersistentKeepalive").SetValue(strconv.FormatInt((int64)(peer.PersistentKeepaliveInterval.Seconds()), 10))
  354. }
  355. }
  356. if err := wireguard.SaveTo(file); err != nil {
  357. return err
  358. }
  359. return nil
  360. }
  361. // UpdateWgInterface - updates the interface section of a wireguard config file
  362. func UpdateWgInterface(file, privateKey, nameserver string, node models.Node) error {
  363. options := ini.LoadOptions{
  364. AllowNonUniqueSections: true,
  365. AllowShadows: true,
  366. }
  367. wireguard, err := ini.LoadSources(options, file)
  368. if err != nil {
  369. return err
  370. }
  371. if node.UDPHolePunch == "yes" {
  372. node.ListenPort = 0
  373. }
  374. wireguard.Section(section_interface).Key("PrivateKey").SetValue(privateKey)
  375. wireguard.Section(section_interface).Key("ListenPort").SetValue(strconv.Itoa(int(node.ListenPort)))
  376. if node.Address != "" {
  377. wireguard.Section(section_interface).Key("Address").SetValue(node.Address)
  378. }
  379. if node.Address6 != "" {
  380. wireguard.Section(section_interface).Key("Address").SetValue(node.Address6)
  381. }
  382. //if node.DNSOn == "yes" {
  383. // wireguard.Section(section_interface).Key("DNS").SetValue(nameserver)
  384. //}
  385. if node.PostUp != "" {
  386. wireguard.Section(section_interface).Key("PostUp").SetValue(node.PostUp)
  387. }
  388. if node.PostDown != "" {
  389. wireguard.Section(section_interface).Key("PostDown").SetValue(node.PostDown)
  390. }
  391. if node.MTU != 0 {
  392. wireguard.Section(section_interface).Key("MTU").SetValue(strconv.FormatInt(int64(node.MTU), 10))
  393. }
  394. if err := wireguard.SaveTo(file); err != nil {
  395. return err
  396. }
  397. return nil
  398. }
  399. // UpdatePrivateKey - updates the private key of a wireguard config file
  400. func UpdatePrivateKey(file, privateKey string) error {
  401. options := ini.LoadOptions{
  402. AllowNonUniqueSections: true,
  403. AllowShadows: true,
  404. }
  405. wireguard, err := ini.LoadSources(options, file)
  406. if err != nil {
  407. return err
  408. }
  409. wireguard.Section(section_interface).Key("PrivateKey").SetValue(privateKey)
  410. if err := wireguard.SaveTo(file); err != nil {
  411. return err
  412. }
  413. return nil
  414. }