common.go 15 KB

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