common.go 17 KB

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