common.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550
  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. for _, currentPeer := range devicePeers {
  39. if currentPeer.AllowedIPs[0].String() == peer.AllowedIPs[0].String() &&
  40. currentPeer.PublicKey.String() != peer.PublicKey.String() {
  41. _, err := ncutils.RunCmd("wg set "+iface+" peer "+currentPeer.PublicKey.String()+" remove", true)
  42. if err != nil {
  43. log.Println("error removing peer", peer.Endpoint.String())
  44. }
  45. }
  46. }
  47. udpendpoint := peer.Endpoint.String()
  48. var allowedips string
  49. var iparr []string
  50. for _, ipaddr := range peer.AllowedIPs {
  51. if len(peer.AllowedIPs) > 0 && (&ipaddr) != nil {
  52. iparr = append(iparr, ipaddr.String())
  53. }
  54. }
  55. allowedips = strings.Join(iparr, ",")
  56. keepAliveString := strconv.Itoa(int(keepalive))
  57. if keepAliveString == "0" {
  58. keepAliveString = "15"
  59. }
  60. if node.IsHub == "yes" || node.IsServer == "yes" || peer.Endpoint == nil {
  61. _, err = ncutils.RunCmd("wg set "+iface+" peer "+peer.PublicKey.String()+
  62. " persistent-keepalive "+keepAliveString+
  63. " allowed-ips "+allowedips, true)
  64. } else {
  65. _, err = ncutils.RunCmd("wg set "+iface+" peer "+peer.PublicKey.String()+
  66. " endpoint "+udpendpoint+
  67. " persistent-keepalive "+keepAliveString+
  68. " allowed-ips "+allowedips, true)
  69. }
  70. if err != nil {
  71. log.Println("error setting peer", peer.PublicKey.String())
  72. }
  73. }
  74. for _, currentPeer := range devicePeers {
  75. shouldDelete := true
  76. for _, peer := range peers {
  77. if peer.AllowedIPs[0].String() == currentPeer.AllowedIPs[0].String() {
  78. shouldDelete = false
  79. }
  80. // re-check this if logic is not working, added in case of allowedips not working
  81. if peer.PublicKey.String() == currentPeer.PublicKey.String() {
  82. shouldDelete = false
  83. }
  84. }
  85. if shouldDelete {
  86. output, err := ncutils.RunCmd("wg set "+iface+" peer "+currentPeer.PublicKey.String()+" remove", true)
  87. if err != nil {
  88. log.Println(output, "error removing peer", currentPeer.PublicKey.String())
  89. }
  90. }
  91. oldPeerAllowedIps[currentPeer.PublicKey.String()] = currentPeer.AllowedIPs
  92. }
  93. if ncutils.IsMac() {
  94. err = SetMacPeerRoutes(iface)
  95. return err
  96. } else if ncutils.IsLinux() {
  97. local.SetPeerRoutes(iface, oldPeerAllowedIps, peers)
  98. }
  99. return nil
  100. }
  101. // Initializes a WireGuard interface
  102. func InitWireguard(node *models.Node, privkey string, peers []wgtypes.PeerConfig, syncconf bool) error {
  103. key, err := wgtypes.ParseKey(privkey)
  104. if err != nil {
  105. return err
  106. }
  107. wgclient, err := wgctrl.New()
  108. if err != nil {
  109. return err
  110. }
  111. defer wgclient.Close()
  112. modcfg, err := config.ReadConfig(node.Network)
  113. if err != nil {
  114. return err
  115. }
  116. nodecfg := modcfg.Node
  117. var ifacename string
  118. if nodecfg.Interface != "" {
  119. ifacename = nodecfg.Interface
  120. } else if node.Interface != "" {
  121. ifacename = node.Interface
  122. } else {
  123. return fmt.Errorf("no interface to configure")
  124. }
  125. if node.PrimaryAddress() == "" {
  126. return fmt.Errorf("no address to configure")
  127. }
  128. if node.UDPHolePunch == "yes" {
  129. node.ListenPort = 0
  130. }
  131. if err := WriteWgConfig(&modcfg.Node, key.String(), peers); err != nil {
  132. logger.Log(1, "error writing wg conf file: ", err.Error())
  133. return err
  134. }
  135. // spin up userspace / windows interface + apply the conf file
  136. confPath := ncutils.GetNetclientPathSpecific() + ifacename + ".conf"
  137. var deviceiface = ifacename
  138. var mErr error
  139. if ncutils.IsMac() { // if node is Mac (Darwin) get the tunnel name first
  140. deviceiface, mErr = local.GetMacIface(node.PrimaryAddress())
  141. if mErr != nil || deviceiface == "" {
  142. deviceiface = ifacename
  143. }
  144. }
  145. // ensure you clear any existing interface first
  146. RemoveConfGraceful(deviceiface)
  147. ApplyConf(node, ifacename, confPath) // Apply initially
  148. logger.Log(1, "waiting for interface...") // ensure interface is created
  149. output, _ := ncutils.RunCmd("wg", false)
  150. starttime := time.Now()
  151. ifaceReady := strings.Contains(output, deviceiface)
  152. for !ifaceReady && !(time.Now().After(starttime.Add(time.Second << 4))) {
  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. output, _ = ncutils.RunCmd("wg", false)
  160. err = ApplyConf(node, node.Interface, confPath)
  161. time.Sleep(time.Second)
  162. ifaceReady = strings.Contains(output, deviceiface)
  163. }
  164. //wgclient does not work well on freebsd
  165. if node.OS == "freebsd" {
  166. if !ifaceReady {
  167. return fmt.Errorf("could not reliably create interface, please check wg installation and retry")
  168. }
  169. } else {
  170. _, devErr := wgclient.Device(deviceiface)
  171. if !ifaceReady || devErr != nil {
  172. fmt.Printf("%v\n", devErr)
  173. return fmt.Errorf("could not reliably create interface, please check wg installation and retry")
  174. }
  175. }
  176. logger.Log(1, "interface ready - netclient.. ENGAGE")
  177. if syncconf { // should never be called really.
  178. fmt.Println("why here")
  179. err = SyncWGQuickConf(ifacename, confPath)
  180. }
  181. if !ncutils.HasWgQuick() && ncutils.IsLinux() {
  182. err = SetPeers(ifacename, node, peers)
  183. if err != nil {
  184. logger.Log(1, "error setting peers: ", err.Error())
  185. }
  186. time.Sleep(time.Second)
  187. }
  188. //ipv4
  189. if node.Address != "" {
  190. _, cidr, cidrErr := net.ParseCIDR(modcfg.NetworkSettings.AddressRange)
  191. if cidrErr == nil {
  192. local.SetCIDRRoute(ifacename, node.Address, cidr)
  193. } else {
  194. logger.Log(1, "could not set cidr route properly: ", cidrErr.Error())
  195. }
  196. local.SetCurrentPeerRoutes(ifacename, node.Address, peers)
  197. }
  198. if node.Address6 != "" {
  199. //ipv6
  200. _, cidr, cidrErr := net.ParseCIDR(modcfg.NetworkSettings.AddressRange6)
  201. if cidrErr == nil {
  202. local.SetCIDRRoute(ifacename, node.Address6, cidr)
  203. } else {
  204. logger.Log(1, "could not set cidr route properly: ", cidrErr.Error())
  205. }
  206. local.SetCurrentPeerRoutes(ifacename, node.Address6, peers)
  207. }
  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, peers []wgtypes.PeerConfig) error {
  212. cfg, err := config.ReadConfig(network)
  213. if err != nil {
  214. return err
  215. }
  216. servercfg := cfg.Server
  217. nodecfg := cfg.Node
  218. privkey, err := RetrievePrivKey(network)
  219. if err != nil {
  220. return err
  221. }
  222. if peerupdate && !ncutils.IsFreeBSD() && !(ncutils.IsLinux() && !ncutils.IsKernel()) {
  223. var iface string
  224. iface = nodecfg.Interface
  225. if ncutils.IsMac() {
  226. iface, err = local.GetMacIface(nodecfg.PrimaryAddress())
  227. if err != nil {
  228. return err
  229. }
  230. }
  231. err = SetPeers(iface, &nodecfg, peers)
  232. } else if peerupdate {
  233. err = InitWireguard(&nodecfg, privkey, peers, true)
  234. } else {
  235. err = InitWireguard(&nodecfg, privkey, peers, false)
  236. }
  237. if nodecfg.DNSOn == "yes" {
  238. _ = local.UpdateDNS(nodecfg.Interface, nodecfg.Network, servercfg.CoreDNSAddr)
  239. }
  240. return err
  241. }
  242. // RemoveConf - removes a configuration for a given WireGuard interface
  243. func RemoveConf(iface string, printlog bool) error {
  244. os := runtime.GOOS
  245. if ncutils.IsLinux() && !ncutils.HasWgQuick() {
  246. os = "nowgquick"
  247. }
  248. var err error
  249. switch os {
  250. case "nowgquick":
  251. err = RemoveWithoutWGQuick(iface)
  252. case "windows":
  253. err = RemoveWindowsConf(iface, printlog)
  254. case "darwin":
  255. err = RemoveConfMac(iface)
  256. default:
  257. confPath := ncutils.GetNetclientPathSpecific() + iface + ".conf"
  258. err = RemoveWGQuickConf(confPath, printlog)
  259. }
  260. return err
  261. }
  262. // ApplyConf - applys a conf on disk to WireGuard interface
  263. func ApplyConf(node *models.Node, ifacename string, confPath string) error {
  264. os := runtime.GOOS
  265. if ncutils.IsLinux() && !ncutils.HasWgQuick() {
  266. os = "nowgquick"
  267. }
  268. var err error
  269. switch os {
  270. case "windows":
  271. ApplyWindowsConf(confPath)
  272. case "darwin":
  273. ApplyMacOSConf(node, ifacename, confPath)
  274. case "nowgquick":
  275. ApplyWithoutWGQuick(node, ifacename, confPath)
  276. default:
  277. ApplyWGQuickConf(confPath, ifacename)
  278. }
  279. var nodeCfg config.ClientConfig
  280. nodeCfg.Network = node.Network
  281. nodeCfg.ReadConfig()
  282. if nodeCfg.NetworkSettings.AddressRange != "" {
  283. ip, cidr, err := net.ParseCIDR(nodeCfg.NetworkSettings.AddressRange)
  284. if err == nil {
  285. local.SetCIDRRoute(node.Interface, ip.String(), cidr)
  286. }
  287. }
  288. if nodeCfg.NetworkSettings.AddressRange6 != "" {
  289. ip, cidr, err := net.ParseCIDR(nodeCfg.NetworkSettings.AddressRange6)
  290. if err == nil {
  291. local.SetCIDRRoute(node.Interface, ip.String(), cidr)
  292. }
  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. }
  498. // GetDevicePeers - gets the current device's peers
  499. func GetDevicePeers(iface string) ([]wgtypes.Peer, error) {
  500. if ncutils.IsFreeBSD() {
  501. if devicePeers, err := ncutils.GetPeers(iface); err != nil {
  502. return nil, err
  503. } else {
  504. return devicePeers, nil
  505. }
  506. } else {
  507. client, err := wgctrl.New()
  508. if err != nil {
  509. logger.Log(0, "failed to start wgctrl")
  510. return nil, err
  511. }
  512. defer client.Close()
  513. device, err := client.Device(iface)
  514. if err != nil {
  515. logger.Log(0, "failed to parse interface")
  516. return nil, err
  517. }
  518. return device.Peers, nil
  519. }
  520. }