common.go 16 KB

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