common.go 16 KB

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