common.go 16 KB

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