common.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523
  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, hasGateway bool, gateways []string, 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. ifaceReady := strings.Contains(output, deviceiface)
  164. maxRetries := 10
  165. for ticker, attempts := time.NewTicker(time.Second<<4), 0; !strings.Contains(output, deviceiface); <-ticker.C {
  166. if attempts >= maxRetries {
  167. break
  168. }
  169. if ncutils.IsMac() { // if node is Mac (Darwin) get the tunnel name first
  170. deviceiface, err = local.GetMacIface(node.Address)
  171. if err != nil || deviceiface == "" {
  172. deviceiface = ifacename
  173. }
  174. }
  175. output, _ = ncutils.RunCmd("wg", false)
  176. err = ApplyConf(node, node.Interface, confPath)
  177. time.Sleep(time.Second)
  178. ifaceReady = strings.Contains(output, deviceiface)
  179. attempts += 1
  180. }
  181. //wgclient does not work well on freebsd
  182. if node.OS == "freebsd" {
  183. if !ifaceReady {
  184. return fmt.Errorf("could not reliably create interface, please check wg installation and retry")
  185. }
  186. } else {
  187. _, devErr := wgclient.Device(deviceiface)
  188. if !ifaceReady || devErr != nil {
  189. fmt.Printf("%v\n", devErr)
  190. return fmt.Errorf("could not reliably create interface, please check wg installation and retry")
  191. }
  192. }
  193. logger.Log(1, "interface ready - netclient.. ENGAGE")
  194. if syncconf { // should never be called really.
  195. fmt.Println("why here")
  196. err = SyncWGQuickConf(ifacename, confPath)
  197. }
  198. if !ncutils.HasWgQuick() && ncutils.IsLinux() {
  199. err = SetPeers(ifacename, node, peers)
  200. if err != nil {
  201. logger.Log(1, "error setting peers: ", err.Error())
  202. }
  203. time.Sleep(time.Second)
  204. }
  205. _, cidr, cidrErr := net.ParseCIDR(modcfg.NetworkSettings.AddressRange)
  206. if cidrErr == nil {
  207. local.SetCIDRRoute(ifacename, node.Address, cidr)
  208. } else {
  209. logger.Log(1, "could not set cidr route properly: ", cidrErr.Error())
  210. }
  211. local.SetCurrentPeerRoutes(ifacename, node.Address, peers)
  212. return err
  213. }
  214. // SetWGConfig - sets the WireGuard Config of a given network and checks if it needs a peer update
  215. func SetWGConfig(network string, peerupdate bool) error {
  216. cfg, err := config.ReadConfig(network)
  217. if err != nil {
  218. return err
  219. }
  220. servercfg := cfg.Server
  221. nodecfg := cfg.Node
  222. peers, hasGateway, gateways, err := server.GetPeers(nodecfg.MacAddress, nodecfg.Network, servercfg.GRPCAddress, nodecfg.IsDualStack == "yes", nodecfg.IsIngressGateway == "yes", nodecfg.IsServer == "yes")
  223. if err != nil {
  224. return err
  225. }
  226. privkey, err := RetrievePrivKey(network)
  227. if err != nil {
  228. return err
  229. }
  230. if peerupdate && !ncutils.IsFreeBSD() && !(ncutils.IsLinux() && !ncutils.IsKernel()) {
  231. var iface string
  232. iface = nodecfg.Interface
  233. if ncutils.IsMac() {
  234. iface, err = local.GetMacIface(nodecfg.Address)
  235. if err != nil {
  236. return err
  237. }
  238. }
  239. err = SetPeers(iface, &nodecfg, peers)
  240. } else if peerupdate {
  241. err = InitWireguard(&nodecfg, privkey, peers, hasGateway, gateways, true)
  242. } else {
  243. err = InitWireguard(&nodecfg, privkey, peers, hasGateway, gateways, false)
  244. }
  245. if nodecfg.DNSOn == "yes" {
  246. _ = local.UpdateDNS(nodecfg.Interface, nodecfg.Network, servercfg.CoreDNSAddr)
  247. }
  248. return err
  249. }
  250. // RemoveConf - removes a configuration for a given WireGuard interface
  251. func RemoveConf(iface string, printlog bool) error {
  252. os := runtime.GOOS
  253. if ncutils.IsLinux() && !ncutils.HasWgQuick() {
  254. os = "nowgquick"
  255. }
  256. var err error
  257. switch os {
  258. case "nowgquick":
  259. err = RemoveWithoutWGQuick(iface)
  260. case "windows":
  261. err = RemoveWindowsConf(iface, printlog)
  262. case "darwin":
  263. err = RemoveConfMac(iface)
  264. default:
  265. confPath := ncutils.GetNetclientPathSpecific() + iface + ".conf"
  266. err = RemoveWGQuickConf(confPath, printlog)
  267. }
  268. return err
  269. }
  270. // ApplyConf - applys a conf on disk to WireGuard interface
  271. func ApplyConf(node *models.Node, ifacename string, confPath string) error {
  272. os := runtime.GOOS
  273. if ncutils.IsLinux() && !ncutils.HasWgQuick() {
  274. os = "nowgquick"
  275. }
  276. var err error
  277. switch os {
  278. case "windows":
  279. ApplyWindowsConf(confPath)
  280. case "darwin":
  281. ApplyMacOSConf(node, ifacename, confPath)
  282. case "nowgquick":
  283. ApplyWithoutWGQuick(node, ifacename, confPath)
  284. default:
  285. ApplyWGQuickConf(confPath, ifacename)
  286. }
  287. var nodeCfg config.ClientConfig
  288. nodeCfg.Network = node.Network
  289. nodeCfg.ReadConfig()
  290. ip, cidr, err := net.ParseCIDR(nodeCfg.NetworkSettings.AddressRange)
  291. if err == nil {
  292. local.SetCIDRRoute(node.Interface, ip.String(), cidr)
  293. }
  294. return err
  295. }
  296. // WriteWgConfig - creates a wireguard config file
  297. //func WriteWgConfig(cfg *config.ClientConfig, privateKey string, peers []wgtypes.PeerConfig) error {
  298. func WriteWgConfig(node *models.Node, privateKey string, peers []wgtypes.PeerConfig) error {
  299. options := ini.LoadOptions{
  300. AllowNonUniqueSections: true,
  301. AllowShadows: true,
  302. }
  303. wireguard := ini.Empty(options)
  304. wireguard.Section(section_interface).Key("PrivateKey").SetValue(privateKey)
  305. if node.ListenPort > 0 && node.UDPHolePunch != "yes" {
  306. wireguard.Section(section_interface).Key("ListenPort").SetValue(strconv.Itoa(int(node.ListenPort)))
  307. }
  308. if node.Address != "" {
  309. wireguard.Section(section_interface).Key("Address").SetValue(node.Address)
  310. }
  311. if node.Address6 != "" {
  312. wireguard.Section(section_interface).Key("Address").SetValue(node.Address6)
  313. }
  314. // need to figure out DNS
  315. //if node.DNSOn == "yes" {
  316. // wireguard.Section(section_interface).Key("DNS").SetValue(cfg.Server.CoreDNSAddr)
  317. //}
  318. if node.PostUp != "" {
  319. wireguard.Section(section_interface).Key("PostUp").SetValue(node.PostUp)
  320. }
  321. if node.PostDown != "" {
  322. wireguard.Section(section_interface).Key("PostDown").SetValue(node.PostDown)
  323. }
  324. if node.MTU != 0 {
  325. wireguard.Section(section_interface).Key("MTU").SetValue(strconv.FormatInt(int64(node.MTU), 10))
  326. }
  327. for i, peer := range peers {
  328. wireguard.SectionWithIndex(section_peers, i).Key("PublicKey").SetValue(peer.PublicKey.String())
  329. if peer.PresharedKey != nil {
  330. wireguard.SectionWithIndex(section_peers, i).Key("PreSharedKey").SetValue(peer.PresharedKey.String())
  331. }
  332. if peer.AllowedIPs != nil {
  333. var allowedIPs string
  334. for i, ip := range peer.AllowedIPs {
  335. if i == 0 {
  336. allowedIPs = ip.String()
  337. } else {
  338. allowedIPs = allowedIPs + ", " + ip.String()
  339. }
  340. }
  341. wireguard.SectionWithIndex(section_peers, i).Key("AllowedIps").SetValue(allowedIPs)
  342. }
  343. if peer.Endpoint != nil {
  344. wireguard.SectionWithIndex(section_peers, i).Key("Endpoint").SetValue(peer.Endpoint.String())
  345. }
  346. if peer.PersistentKeepaliveInterval != nil && peer.PersistentKeepaliveInterval.Seconds() > 0 {
  347. wireguard.SectionWithIndex(section_peers, i).Key("PersistentKeepalive").SetValue(strconv.FormatInt((int64)(peer.PersistentKeepaliveInterval.Seconds()), 10))
  348. }
  349. }
  350. if err := wireguard.SaveTo(ncutils.GetNetclientPathSpecific() + node.Interface + ".conf"); err != nil {
  351. return err
  352. }
  353. return nil
  354. }
  355. // UpdateWgPeers - updates the peers of a network
  356. func UpdateWgPeers(file string, peers []wgtypes.PeerConfig) error {
  357. options := ini.LoadOptions{
  358. AllowNonUniqueSections: true,
  359. AllowShadows: true,
  360. }
  361. wireguard, err := ini.LoadSources(options, file)
  362. if err != nil {
  363. return err
  364. }
  365. //delete the peers sections as they are going to be replaced
  366. wireguard.DeleteSection(section_peers)
  367. for i, peer := range peers {
  368. wireguard.SectionWithIndex(section_peers, i).Key("PublicKey").SetValue(peer.PublicKey.String())
  369. if peer.PresharedKey != nil {
  370. wireguard.SectionWithIndex(section_peers, i).Key("PreSharedKey").SetValue(peer.PresharedKey.String())
  371. }
  372. if peer.AllowedIPs != nil {
  373. var allowedIPs string
  374. for i, ip := range peer.AllowedIPs {
  375. if i == 0 {
  376. allowedIPs = ip.String()
  377. } else {
  378. allowedIPs = allowedIPs + ", " + ip.String()
  379. }
  380. }
  381. wireguard.SectionWithIndex(section_peers, i).Key("AllowedIps").SetValue(allowedIPs)
  382. }
  383. if peer.Endpoint != nil {
  384. wireguard.SectionWithIndex(section_peers, i).Key("Endpoint").SetValue(peer.Endpoint.String())
  385. }
  386. if peer.PersistentKeepaliveInterval != nil && peer.PersistentKeepaliveInterval.Seconds() > 0 {
  387. wireguard.SectionWithIndex(section_peers, i).Key("PersistentKeepalive").SetValue(strconv.FormatInt((int64)(peer.PersistentKeepaliveInterval.Seconds()), 10))
  388. }
  389. }
  390. if err := wireguard.SaveTo(file); err != nil {
  391. return err
  392. }
  393. return nil
  394. }
  395. // UpdateWgInterface - updates the interface section of a wireguard config file
  396. func UpdateWgInterface(file, privateKey, nameserver string, node models.Node) error {
  397. options := ini.LoadOptions{
  398. AllowNonUniqueSections: true,
  399. AllowShadows: true,
  400. }
  401. wireguard, err := ini.LoadSources(options, file)
  402. if err != nil {
  403. return err
  404. }
  405. if node.UDPHolePunch == "yes" {
  406. node.ListenPort = 0
  407. }
  408. wireguard.Section(section_interface).Key("PrivateKey").SetValue(privateKey)
  409. wireguard.Section(section_interface).Key("ListenPort").SetValue(strconv.Itoa(int(node.ListenPort)))
  410. if node.Address != "" {
  411. wireguard.Section(section_interface).Key("Address").SetValue(node.Address)
  412. }
  413. if node.Address6 != "" {
  414. wireguard.Section(section_interface).Key("Address").SetValue(node.Address6)
  415. }
  416. //if node.DNSOn == "yes" {
  417. // wireguard.Section(section_interface).Key("DNS").SetValue(nameserver)
  418. //}
  419. if node.PostUp != "" {
  420. wireguard.Section(section_interface).Key("PostUp").SetValue(node.PostUp)
  421. }
  422. if node.PostDown != "" {
  423. wireguard.Section(section_interface).Key("PostDown").SetValue(node.PostDown)
  424. }
  425. if node.MTU != 0 {
  426. wireguard.Section(section_interface).Key("MTU").SetValue(strconv.FormatInt(int64(node.MTU), 10))
  427. }
  428. if err := wireguard.SaveTo(file); err != nil {
  429. return err
  430. }
  431. return nil
  432. }
  433. // UpdatePrivateKey - updates the private key of a wireguard config file
  434. func UpdatePrivateKey(file, privateKey string) error {
  435. options := ini.LoadOptions{
  436. AllowNonUniqueSections: true,
  437. AllowShadows: true,
  438. }
  439. wireguard, err := ini.LoadSources(options, file)
  440. if err != nil {
  441. return err
  442. }
  443. wireguard.Section(section_interface).Key("PrivateKey").SetValue(privateKey)
  444. if err := wireguard.SaveTo(file); err != nil {
  445. return err
  446. }
  447. return nil
  448. }
  449. // UpdateKeepAlive - updates the persistentkeepalive of all peers
  450. func UpdateKeepAlive(file string, keepalive int32) error {
  451. options := ini.LoadOptions{
  452. AllowNonUniqueSections: true,
  453. AllowShadows: true,
  454. }
  455. wireguard, err := ini.LoadSources(options, file)
  456. if err != nil {
  457. return err
  458. }
  459. peers, err := wireguard.SectionsByName(section_peers)
  460. if err != nil {
  461. return err
  462. }
  463. newvalue := strconv.Itoa(int(keepalive))
  464. for i := range peers {
  465. wireguard.SectionWithIndex(section_peers, i).Key("PersistentKeepALive").SetValue(newvalue)
  466. }
  467. if err := wireguard.SaveTo(file); err != nil {
  468. return err
  469. }
  470. return nil
  471. }
  472. // RemoveConfGraceful - Run remove conf and wait for it to actually be gone before proceeding
  473. func RemoveConfGraceful(ifacename string) {
  474. // ensure you clear any existing interface first
  475. wgclient, err := wgctrl.New()
  476. if err != nil {
  477. logger.Log(0, "could not create wgclient")
  478. return
  479. }
  480. defer wgclient.Close()
  481. d, _ := wgclient.Device(ifacename)
  482. startTime := time.Now()
  483. for d != nil && d.Name == ifacename {
  484. if err = RemoveConf(ifacename, false); err != nil { // remove interface first
  485. if strings.Contains(err.Error(), "does not exist") {
  486. err = nil
  487. break
  488. }
  489. }
  490. time.Sleep(time.Second >> 2)
  491. d, _ = wgclient.Device(ifacename)
  492. if time.Now().After(startTime.Add(time.Second << 4)) {
  493. break
  494. }
  495. }
  496. time.Sleep(time.Second << 1)
  497. }