common.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530
  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 keepalive = node.PersistentKeepalive
  27. var oldPeerAllowedIps = make(map[string][]net.IPNet, len(peers))
  28. var err error
  29. if ncutils.IsFreeBSD() {
  30. if devicePeers, err = ncutils.GetPeers(iface); err != nil {
  31. return err
  32. }
  33. } else {
  34. client, err := wgctrl.New()
  35. if err != nil {
  36. logger.Log(0, "failed to start wgctrl")
  37. return err
  38. }
  39. defer client.Close()
  40. device, err := client.Device(iface)
  41. if err != nil {
  42. logger.Log(0, "failed to parse interface")
  43. return err
  44. }
  45. devicePeers = device.Peers
  46. }
  47. if len(devicePeers) > 1 && len(peers) == 0 {
  48. logger.Log(1, "no peers pulled")
  49. return err
  50. }
  51. for _, peer := range peers {
  52. for _, currentPeer := range devicePeers {
  53. if currentPeer.AllowedIPs[0].String() == peer.AllowedIPs[0].String() &&
  54. currentPeer.PublicKey.String() != peer.PublicKey.String() {
  55. _, err := ncutils.RunCmd("wg set "+iface+" peer "+currentPeer.PublicKey.String()+" remove", true)
  56. if err != nil {
  57. log.Println("error removing peer", peer.Endpoint.String())
  58. }
  59. }
  60. }
  61. udpendpoint := peer.Endpoint.String()
  62. var allowedips string
  63. var iparr []string
  64. for _, ipaddr := range peer.AllowedIPs {
  65. if len(peer.AllowedIPs) > 0 && (&ipaddr) != nil {
  66. iparr = append(iparr, ipaddr.String())
  67. }
  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, 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.PrimaryAddress() == "" {
  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.PrimaryAddress())
  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.PrimaryAddress())
  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. //ipv4
  202. if node.Address != "" {
  203. _, cidr, cidrErr := net.ParseCIDR(modcfg.NetworkSettings.AddressRange)
  204. if cidrErr == nil {
  205. local.SetCIDRRoute(ifacename, node.Address, cidr)
  206. } else {
  207. logger.Log(1, "could not set cidr route properly: ", cidrErr.Error())
  208. }
  209. local.SetCurrentPeerRoutes(ifacename, node.Address, peers)
  210. }
  211. if node.Address6 != "" {
  212. //ipv6
  213. _, cidr, cidrErr := net.ParseCIDR(modcfg.NetworkSettings.AddressRange6)
  214. if cidrErr == nil {
  215. local.SetCIDRRoute(ifacename, node.Address6, cidr)
  216. } else {
  217. logger.Log(1, "could not set cidr route properly: ", cidrErr.Error())
  218. }
  219. local.SetCurrentPeerRoutes(ifacename, node.Address6, peers)
  220. }
  221. return err
  222. }
  223. // SetWGConfig - sets the WireGuard Config of a given network and checks if it needs a peer update
  224. func SetWGConfig(network string, peerupdate bool) error {
  225. cfg, err := config.ReadConfig(network)
  226. if err != nil {
  227. return err
  228. }
  229. servercfg := cfg.Server
  230. nodecfg := cfg.Node
  231. privkey, err := RetrievePrivKey(network)
  232. if err != nil {
  233. return err
  234. }
  235. if peerupdate && !ncutils.IsFreeBSD() && !(ncutils.IsLinux() && !ncutils.IsKernel()) {
  236. var iface string
  237. iface = nodecfg.Interface
  238. if ncutils.IsMac() {
  239. iface, err = local.GetMacIface(nodecfg.PrimaryAddress())
  240. if err != nil {
  241. return err
  242. }
  243. }
  244. err = SetPeers(iface, &nodecfg, []wgtypes.PeerConfig{})
  245. } else if peerupdate {
  246. err = InitWireguard(&nodecfg, privkey, []wgtypes.PeerConfig{}, true)
  247. } else {
  248. err = InitWireguard(&nodecfg, privkey, []wgtypes.PeerConfig{}, false)
  249. }
  250. if nodecfg.DNSOn == "yes" {
  251. _ = local.UpdateDNS(nodecfg.Interface, nodecfg.Network, servercfg.CoreDNSAddr)
  252. }
  253. return err
  254. }
  255. // RemoveConf - removes a configuration for a given WireGuard interface
  256. func RemoveConf(iface string, printlog bool) error {
  257. os := runtime.GOOS
  258. if ncutils.IsLinux() && !ncutils.HasWgQuick() {
  259. os = "nowgquick"
  260. }
  261. var err error
  262. switch os {
  263. case "nowgquick":
  264. err = RemoveWithoutWGQuick(iface)
  265. case "windows":
  266. err = RemoveWindowsConf(iface, printlog)
  267. case "darwin":
  268. err = RemoveConfMac(iface)
  269. default:
  270. confPath := ncutils.GetNetclientPathSpecific() + iface + ".conf"
  271. err = RemoveWGQuickConf(confPath, printlog)
  272. }
  273. return err
  274. }
  275. // ApplyConf - applys a conf on disk to WireGuard interface
  276. func ApplyConf(node *models.Node, ifacename string, confPath string) error {
  277. os := runtime.GOOS
  278. if ncutils.IsLinux() && !ncutils.HasWgQuick() {
  279. os = "nowgquick"
  280. }
  281. var err error
  282. switch os {
  283. case "windows":
  284. ApplyWindowsConf(confPath)
  285. case "darwin":
  286. ApplyMacOSConf(node, ifacename, confPath)
  287. case "nowgquick":
  288. ApplyWithoutWGQuick(node, ifacename, confPath)
  289. default:
  290. ApplyWGQuickConf(confPath, ifacename)
  291. }
  292. var nodeCfg config.ClientConfig
  293. nodeCfg.Network = node.Network
  294. nodeCfg.ReadConfig()
  295. ip, cidr, err := net.ParseCIDR(nodeCfg.NetworkSettings.AddressRange)
  296. if err == nil {
  297. local.SetCIDRRoute(node.Interface, ip.String(), cidr)
  298. }
  299. return err
  300. }
  301. // WriteWgConfig - creates a wireguard config file
  302. //func WriteWgConfig(cfg *config.ClientConfig, privateKey string, peers []wgtypes.PeerConfig) error {
  303. func WriteWgConfig(node *models.Node, privateKey string, peers []wgtypes.PeerConfig) error {
  304. options := ini.LoadOptions{
  305. AllowNonUniqueSections: true,
  306. AllowShadows: true,
  307. }
  308. wireguard := ini.Empty(options)
  309. wireguard.Section(section_interface).Key("PrivateKey").SetValue(privateKey)
  310. if node.ListenPort > 0 && node.UDPHolePunch != "yes" {
  311. wireguard.Section(section_interface).Key("ListenPort").SetValue(strconv.Itoa(int(node.ListenPort)))
  312. }
  313. if node.Address != "" {
  314. wireguard.Section(section_interface).Key("Address").SetValue(node.Address)
  315. }
  316. if node.Address6 != "" {
  317. wireguard.Section(section_interface).Key("Address").SetValue(node.Address6)
  318. }
  319. // need to figure out DNS
  320. //if node.DNSOn == "yes" {
  321. // wireguard.Section(section_interface).Key("DNS").SetValue(cfg.Server.CoreDNSAddr)
  322. //}
  323. if node.PostUp != "" {
  324. wireguard.Section(section_interface).Key("PostUp").SetValue(node.PostUp)
  325. }
  326. if node.PostDown != "" {
  327. wireguard.Section(section_interface).Key("PostDown").SetValue(node.PostDown)
  328. }
  329. if node.MTU != 0 {
  330. wireguard.Section(section_interface).Key("MTU").SetValue(strconv.FormatInt(int64(node.MTU), 10))
  331. }
  332. for i, peer := range peers {
  333. wireguard.SectionWithIndex(section_peers, i).Key("PublicKey").SetValue(peer.PublicKey.String())
  334. if peer.PresharedKey != nil {
  335. wireguard.SectionWithIndex(section_peers, i).Key("PreSharedKey").SetValue(peer.PresharedKey.String())
  336. }
  337. if peer.AllowedIPs != nil {
  338. var allowedIPs string
  339. for i, ip := range peer.AllowedIPs {
  340. if i == 0 {
  341. allowedIPs = ip.String()
  342. } else {
  343. allowedIPs = allowedIPs + ", " + ip.String()
  344. }
  345. }
  346. wireguard.SectionWithIndex(section_peers, i).Key("AllowedIps").SetValue(allowedIPs)
  347. }
  348. if peer.Endpoint != nil {
  349. wireguard.SectionWithIndex(section_peers, i).Key("Endpoint").SetValue(peer.Endpoint.String())
  350. }
  351. if peer.PersistentKeepaliveInterval != nil && peer.PersistentKeepaliveInterval.Seconds() > 0 {
  352. wireguard.SectionWithIndex(section_peers, i).Key("PersistentKeepalive").SetValue(strconv.FormatInt((int64)(peer.PersistentKeepaliveInterval.Seconds()), 10))
  353. }
  354. }
  355. if err := wireguard.SaveTo(ncutils.GetNetclientPathSpecific() + node.Interface + ".conf"); err != nil {
  356. return err
  357. }
  358. return nil
  359. }
  360. // UpdateWgPeers - updates the peers of a network
  361. func UpdateWgPeers(file string, peers []wgtypes.PeerConfig) error {
  362. options := ini.LoadOptions{
  363. AllowNonUniqueSections: true,
  364. AllowShadows: true,
  365. }
  366. wireguard, err := ini.LoadSources(options, file)
  367. if err != nil {
  368. return err
  369. }
  370. //delete the peers sections as they are going to be replaced
  371. wireguard.DeleteSection(section_peers)
  372. for i, peer := range peers {
  373. wireguard.SectionWithIndex(section_peers, i).Key("PublicKey").SetValue(peer.PublicKey.String())
  374. if peer.PresharedKey != nil {
  375. wireguard.SectionWithIndex(section_peers, i).Key("PreSharedKey").SetValue(peer.PresharedKey.String())
  376. }
  377. if peer.AllowedIPs != nil {
  378. var allowedIPs string
  379. for i, ip := range peer.AllowedIPs {
  380. if i == 0 {
  381. allowedIPs = ip.String()
  382. } else {
  383. allowedIPs = allowedIPs + ", " + ip.String()
  384. }
  385. }
  386. wireguard.SectionWithIndex(section_peers, i).Key("AllowedIps").SetValue(allowedIPs)
  387. }
  388. if peer.Endpoint != nil {
  389. wireguard.SectionWithIndex(section_peers, i).Key("Endpoint").SetValue(peer.Endpoint.String())
  390. }
  391. if peer.PersistentKeepaliveInterval != nil && peer.PersistentKeepaliveInterval.Seconds() > 0 {
  392. wireguard.SectionWithIndex(section_peers, i).Key("PersistentKeepalive").SetValue(strconv.FormatInt((int64)(peer.PersistentKeepaliveInterval.Seconds()), 10))
  393. }
  394. }
  395. if err := wireguard.SaveTo(file); err != nil {
  396. return err
  397. }
  398. return nil
  399. }
  400. // UpdateWgInterface - updates the interface section of a wireguard config file
  401. func UpdateWgInterface(file, privateKey, nameserver string, node models.Node) error {
  402. options := ini.LoadOptions{
  403. AllowNonUniqueSections: true,
  404. AllowShadows: true,
  405. }
  406. wireguard, err := ini.LoadSources(options, file)
  407. if err != nil {
  408. return err
  409. }
  410. if node.UDPHolePunch == "yes" {
  411. node.ListenPort = 0
  412. }
  413. wireguard.Section(section_interface).Key("PrivateKey").SetValue(privateKey)
  414. wireguard.Section(section_interface).Key("ListenPort").SetValue(strconv.Itoa(int(node.ListenPort)))
  415. if node.Address != "" {
  416. wireguard.Section(section_interface).Key("Address").SetValue(node.Address)
  417. }
  418. if node.Address6 != "" {
  419. wireguard.Section(section_interface).Key("Address").SetValue(node.Address6)
  420. }
  421. //if node.DNSOn == "yes" {
  422. // wireguard.Section(section_interface).Key("DNS").SetValue(nameserver)
  423. //}
  424. if node.PostUp != "" {
  425. wireguard.Section(section_interface).Key("PostUp").SetValue(node.PostUp)
  426. }
  427. if node.PostDown != "" {
  428. wireguard.Section(section_interface).Key("PostDown").SetValue(node.PostDown)
  429. }
  430. if node.MTU != 0 {
  431. wireguard.Section(section_interface).Key("MTU").SetValue(strconv.FormatInt(int64(node.MTU), 10))
  432. }
  433. if err := wireguard.SaveTo(file); err != nil {
  434. return err
  435. }
  436. return nil
  437. }
  438. // UpdatePrivateKey - updates the private key of a wireguard config file
  439. func UpdatePrivateKey(file, privateKey string) error {
  440. options := ini.LoadOptions{
  441. AllowNonUniqueSections: true,
  442. AllowShadows: true,
  443. }
  444. wireguard, err := ini.LoadSources(options, file)
  445. if err != nil {
  446. return err
  447. }
  448. wireguard.Section(section_interface).Key("PrivateKey").SetValue(privateKey)
  449. if err := wireguard.SaveTo(file); err != nil {
  450. return err
  451. }
  452. return nil
  453. }
  454. // UpdateKeepAlive - updates the persistentkeepalive of all peers
  455. func UpdateKeepAlive(file string, keepalive int32) error {
  456. options := ini.LoadOptions{
  457. AllowNonUniqueSections: true,
  458. AllowShadows: true,
  459. }
  460. wireguard, err := ini.LoadSources(options, file)
  461. if err != nil {
  462. return err
  463. }
  464. peers, err := wireguard.SectionsByName(section_peers)
  465. if err != nil {
  466. return err
  467. }
  468. newvalue := strconv.Itoa(int(keepalive))
  469. for i := range peers {
  470. wireguard.SectionWithIndex(section_peers, i).Key("PersistentKeepALive").SetValue(newvalue)
  471. }
  472. if err := wireguard.SaveTo(file); err != nil {
  473. return err
  474. }
  475. return nil
  476. }
  477. // RemoveConfGraceful - Run remove conf and wait for it to actually be gone before proceeding
  478. func RemoveConfGraceful(ifacename string) {
  479. // ensure you clear any existing interface first
  480. wgclient, err := wgctrl.New()
  481. if err != nil {
  482. logger.Log(0, "could not create wgclient")
  483. return
  484. }
  485. defer wgclient.Close()
  486. d, _ := wgclient.Device(ifacename)
  487. startTime := time.Now()
  488. for d != nil && d.Name == ifacename {
  489. if err = RemoveConf(ifacename, false); err != nil { // remove interface first
  490. if strings.Contains(err.Error(), "does not exist") {
  491. err = nil
  492. break
  493. }
  494. }
  495. time.Sleep(time.Second >> 2)
  496. d, _ = wgclient.Device(ifacename)
  497. if time.Now().After(startTime.Add(time.Second << 4)) {
  498. break
  499. }
  500. }
  501. time.Sleep(time.Second << 1)
  502. }