common.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562
  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. if iparr != nil && len(iparr) > 0 {
  56. allowedips = strings.Join(iparr, ",")
  57. }
  58. keepAliveString := strconv.Itoa(int(keepalive))
  59. if keepAliveString == "0" {
  60. keepAliveString = "15"
  61. }
  62. if node.IsHub == "yes" || node.IsServer == "yes" || peer.Endpoint == nil {
  63. _, err = ncutils.RunCmd("wg set "+iface+" peer "+peer.PublicKey.String()+
  64. " persistent-keepalive "+keepAliveString+
  65. " allowed-ips "+allowedips, true)
  66. } else {
  67. _, err = ncutils.RunCmd("wg set "+iface+" peer "+peer.PublicKey.String()+
  68. " endpoint "+udpendpoint+
  69. " persistent-keepalive "+keepAliveString+
  70. " allowed-ips "+allowedips, true)
  71. }
  72. if err != nil {
  73. log.Println("error setting peer", peer.PublicKey.String())
  74. }
  75. }
  76. if devicePeers != nil && len(devicePeers) > 0 {
  77. for _, currentPeer := range devicePeers {
  78. shouldDelete := true
  79. if peers != nil && len(peers) > 0 {
  80. for _, peer := range peers {
  81. if peer.AllowedIPs[0].String() == currentPeer.AllowedIPs[0].String() {
  82. shouldDelete = false
  83. }
  84. // re-check this if logic is not working, added in case of allowedips not working
  85. if peer.PublicKey.String() == currentPeer.PublicKey.String() {
  86. shouldDelete = false
  87. }
  88. }
  89. if shouldDelete {
  90. output, err := ncutils.RunCmd("wg set "+iface+" peer "+currentPeer.PublicKey.String()+" remove", true)
  91. if err != nil {
  92. log.Println(output, "error removing peer", currentPeer.PublicKey.String())
  93. }
  94. }
  95. oldPeerAllowedIps[currentPeer.PublicKey.String()] = currentPeer.AllowedIPs
  96. }
  97. }
  98. }
  99. if ncutils.IsMac() {
  100. err = SetMacPeerRoutes(iface)
  101. return err
  102. } else if ncutils.IsLinux() {
  103. if peers != nil && len(peers) > 0 {
  104. local.SetPeerRoutes(iface, oldPeerAllowedIps, peers)
  105. }
  106. }
  107. return nil
  108. }
  109. // Initializes a WireGuard interface
  110. func InitWireguard(node *models.Node, privkey string, peers []wgtypes.PeerConfig, syncconf bool) error {
  111. key, err := wgtypes.ParseKey(privkey)
  112. if err != nil {
  113. return err
  114. }
  115. wgclient, err := wgctrl.New()
  116. if err != nil {
  117. return err
  118. }
  119. defer wgclient.Close()
  120. modcfg, err := config.ReadConfig(node.Network)
  121. if err != nil {
  122. return err
  123. }
  124. nodecfg := modcfg.Node
  125. var ifacename string
  126. if nodecfg.Interface != "" {
  127. ifacename = nodecfg.Interface
  128. } else if node.Interface != "" {
  129. ifacename = node.Interface
  130. } else {
  131. return fmt.Errorf("no interface to configure")
  132. }
  133. if node.PrimaryAddress() == "" {
  134. return fmt.Errorf("no address to configure")
  135. }
  136. if node.UDPHolePunch == "yes" {
  137. node.ListenPort = 0
  138. }
  139. if err := WriteWgConfig(&modcfg.Node, key.String(), peers); err != nil {
  140. logger.Log(1, "error writing wg conf file: ", err.Error())
  141. return err
  142. }
  143. // spin up userspace / windows interface + apply the conf file
  144. confPath := ncutils.GetNetclientPathSpecific() + ifacename + ".conf"
  145. var deviceiface = ifacename
  146. var mErr error
  147. if ncutils.IsMac() { // if node is Mac (Darwin) get the tunnel name first
  148. deviceiface, mErr = local.GetMacIface(node.PrimaryAddress())
  149. if mErr != nil || deviceiface == "" {
  150. deviceiface = ifacename
  151. }
  152. }
  153. // ensure you clear any existing interface first
  154. RemoveConfGraceful(deviceiface)
  155. ApplyConf(node, ifacename, confPath) // Apply initially
  156. logger.Log(1, "waiting for interface...") // ensure interface is created
  157. output, _ := ncutils.RunCmd("wg", false)
  158. starttime := time.Now()
  159. ifaceReady := strings.Contains(output, deviceiface)
  160. for !ifaceReady && !(time.Now().After(starttime.Add(time.Second << 4))) {
  161. if ncutils.IsMac() { // if node is Mac (Darwin) get the tunnel name first
  162. deviceiface, mErr = local.GetMacIface(node.PrimaryAddress())
  163. if mErr != nil || deviceiface == "" {
  164. deviceiface = ifacename
  165. }
  166. }
  167. output, _ = ncutils.RunCmd("wg", false)
  168. err = ApplyConf(node, node.Interface, confPath)
  169. time.Sleep(time.Second)
  170. ifaceReady = strings.Contains(output, deviceiface)
  171. }
  172. //wgclient does not work well on freebsd
  173. if node.OS == "freebsd" {
  174. if !ifaceReady {
  175. return fmt.Errorf("could not reliably create interface, please check wg installation and retry")
  176. }
  177. } else {
  178. _, devErr := wgclient.Device(deviceiface)
  179. if !ifaceReady || devErr != nil {
  180. fmt.Printf("%v\n", devErr)
  181. return fmt.Errorf("could not reliably create interface, please check wg installation and retry")
  182. }
  183. }
  184. logger.Log(1, "interface ready - netclient.. ENGAGE")
  185. if syncconf { // should never be called really.
  186. fmt.Println("why here")
  187. err = SyncWGQuickConf(ifacename, confPath)
  188. }
  189. if !ncutils.HasWgQuick() && ncutils.IsLinux() {
  190. err = SetPeers(ifacename, node, peers)
  191. if err != nil {
  192. logger.Log(1, "error setting peers: ", err.Error())
  193. }
  194. time.Sleep(time.Second)
  195. }
  196. //ipv4
  197. if node.Address != "" {
  198. _, cidr, cidrErr := net.ParseCIDR(modcfg.NetworkSettings.AddressRange)
  199. if cidrErr == nil {
  200. local.SetCIDRRoute(ifacename, node.Address, cidr)
  201. } else {
  202. logger.Log(1, "could not set cidr route properly: ", cidrErr.Error())
  203. }
  204. local.SetCurrentPeerRoutes(ifacename, node.Address, peers)
  205. }
  206. if node.Address6 != "" {
  207. //ipv6
  208. _, cidr, cidrErr := net.ParseCIDR(modcfg.NetworkSettings.AddressRange6)
  209. if cidrErr == nil {
  210. local.SetCIDRRoute(ifacename, node.Address6, cidr)
  211. } else {
  212. logger.Log(1, "could not set cidr route properly: ", cidrErr.Error())
  213. }
  214. local.SetCurrentPeerRoutes(ifacename, node.Address6, peers)
  215. }
  216. return err
  217. }
  218. // SetWGConfig - sets the WireGuard Config of a given network and checks if it needs a peer update
  219. func SetWGConfig(network string, peerupdate bool, peers []wgtypes.PeerConfig) error {
  220. cfg, err := config.ReadConfig(network)
  221. if err != nil {
  222. return err
  223. }
  224. servercfg := cfg.Server
  225. nodecfg := cfg.Node
  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.PrimaryAddress())
  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, true)
  242. } else {
  243. err = InitWireguard(&nodecfg, privkey, peers, 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. if nodeCfg.NetworkSettings.AddressRange != "" {
  291. ip, cidr, err := net.ParseCIDR(nodeCfg.NetworkSettings.AddressRange)
  292. if err == nil {
  293. local.SetCIDRRoute(node.Interface, ip.String(), cidr)
  294. }
  295. }
  296. if nodeCfg.NetworkSettings.AddressRange6 != "" {
  297. ip, cidr, err := net.ParseCIDR(nodeCfg.NetworkSettings.AddressRange6)
  298. if err == nil {
  299. local.SetCIDRRoute(node.Interface, ip.String(), cidr)
  300. }
  301. }
  302. return err
  303. }
  304. // WriteWgConfig - creates a wireguard config file
  305. //func WriteWgConfig(cfg *config.ClientConfig, privateKey string, peers []wgtypes.PeerConfig) error {
  306. func WriteWgConfig(node *models.Node, privateKey string, peers []wgtypes.PeerConfig) error {
  307. options := ini.LoadOptions{
  308. AllowNonUniqueSections: true,
  309. AllowShadows: true,
  310. }
  311. wireguard := ini.Empty(options)
  312. wireguard.Section(section_interface).Key("PrivateKey").SetValue(privateKey)
  313. if node.ListenPort > 0 && node.UDPHolePunch != "yes" {
  314. wireguard.Section(section_interface).Key("ListenPort").SetValue(strconv.Itoa(int(node.ListenPort)))
  315. }
  316. addrString := node.Address
  317. if node.Address6 != "" {
  318. if addrString != "" {
  319. addrString += ","
  320. }
  321. addrString += node.Address6
  322. }
  323. wireguard.Section(section_interface).Key("Address").SetValue(addrString)
  324. // need to figure out DNS
  325. //if node.DNSOn == "yes" {
  326. // wireguard.Section(section_interface).Key("DNS").SetValue(cfg.Server.CoreDNSAddr)
  327. //}
  328. if node.PostUp != "" {
  329. wireguard.Section(section_interface).Key("PostUp").SetValue(node.PostUp)
  330. }
  331. if node.PostDown != "" {
  332. wireguard.Section(section_interface).Key("PostDown").SetValue(node.PostDown)
  333. }
  334. if node.MTU != 0 {
  335. wireguard.Section(section_interface).Key("MTU").SetValue(strconv.FormatInt(int64(node.MTU), 10))
  336. }
  337. for i, peer := range peers {
  338. wireguard.SectionWithIndex(section_peers, i).Key("PublicKey").SetValue(peer.PublicKey.String())
  339. if peer.PresharedKey != nil {
  340. wireguard.SectionWithIndex(section_peers, i).Key("PreSharedKey").SetValue(peer.PresharedKey.String())
  341. }
  342. if peer.AllowedIPs != nil {
  343. var allowedIPs string
  344. for i, ip := range peer.AllowedIPs {
  345. if i == 0 {
  346. allowedIPs = ip.String()
  347. } else {
  348. allowedIPs = allowedIPs + ", " + ip.String()
  349. }
  350. }
  351. wireguard.SectionWithIndex(section_peers, i).Key("AllowedIps").SetValue(allowedIPs)
  352. }
  353. if peer.Endpoint != nil {
  354. wireguard.SectionWithIndex(section_peers, i).Key("Endpoint").SetValue(peer.Endpoint.String())
  355. }
  356. if peer.PersistentKeepaliveInterval != nil && peer.PersistentKeepaliveInterval.Seconds() > 0 {
  357. wireguard.SectionWithIndex(section_peers, i).Key("PersistentKeepalive").SetValue(strconv.FormatInt((int64)(peer.PersistentKeepaliveInterval.Seconds()), 10))
  358. }
  359. }
  360. if err := wireguard.SaveTo(ncutils.GetNetclientPathSpecific() + node.Interface + ".conf"); err != nil {
  361. return err
  362. }
  363. return nil
  364. }
  365. // UpdateWgPeers - updates the peers of a network
  366. func UpdateWgPeers(file string, peers []wgtypes.PeerConfig) error {
  367. options := ini.LoadOptions{
  368. AllowNonUniqueSections: true,
  369. AllowShadows: true,
  370. }
  371. wireguard, err := ini.LoadSources(options, file)
  372. if err != nil {
  373. return err
  374. }
  375. //delete the peers sections as they are going to be replaced
  376. wireguard.DeleteSection(section_peers)
  377. for i, peer := range peers {
  378. wireguard.SectionWithIndex(section_peers, i).Key("PublicKey").SetValue(peer.PublicKey.String())
  379. if peer.PresharedKey != nil {
  380. wireguard.SectionWithIndex(section_peers, i).Key("PreSharedKey").SetValue(peer.PresharedKey.String())
  381. }
  382. if peer.AllowedIPs != nil {
  383. var allowedIPs string
  384. for i, ip := range peer.AllowedIPs {
  385. if i == 0 {
  386. allowedIPs = ip.String()
  387. } else {
  388. allowedIPs = allowedIPs + ", " + ip.String()
  389. }
  390. }
  391. wireguard.SectionWithIndex(section_peers, i).Key("AllowedIps").SetValue(allowedIPs)
  392. }
  393. if peer.Endpoint != nil {
  394. wireguard.SectionWithIndex(section_peers, i).Key("Endpoint").SetValue(peer.Endpoint.String())
  395. }
  396. if peer.PersistentKeepaliveInterval != nil && peer.PersistentKeepaliveInterval.Seconds() > 0 {
  397. wireguard.SectionWithIndex(section_peers, i).Key("PersistentKeepalive").SetValue(strconv.FormatInt((int64)(peer.PersistentKeepaliveInterval.Seconds()), 10))
  398. }
  399. }
  400. if err := wireguard.SaveTo(file); err != nil {
  401. return err
  402. }
  403. return nil
  404. }
  405. // UpdateWgInterface - updates the interface section of a wireguard config file
  406. func UpdateWgInterface(file, privateKey, nameserver string, node models.Node) error {
  407. options := ini.LoadOptions{
  408. AllowNonUniqueSections: true,
  409. AllowShadows: true,
  410. }
  411. wireguard, err := ini.LoadSources(options, file)
  412. if err != nil {
  413. return err
  414. }
  415. if node.UDPHolePunch == "yes" {
  416. node.ListenPort = 0
  417. }
  418. wireguard.Section(section_interface).Key("PrivateKey").SetValue(privateKey)
  419. wireguard.Section(section_interface).Key("ListenPort").SetValue(strconv.Itoa(int(node.ListenPort)))
  420. addrString := node.Address
  421. if node.Address6 != "" {
  422. if addrString != "" {
  423. addrString += ","
  424. }
  425. addrString += node.Address6
  426. }
  427. wireguard.Section(section_interface).Key("Address").SetValue(addrString)
  428. //if node.DNSOn == "yes" {
  429. // wireguard.Section(section_interface).Key("DNS").SetValue(nameserver)
  430. //}
  431. if node.PostUp != "" {
  432. wireguard.Section(section_interface).Key("PostUp").SetValue(node.PostUp)
  433. }
  434. if node.PostDown != "" {
  435. wireguard.Section(section_interface).Key("PostDown").SetValue(node.PostDown)
  436. }
  437. if node.MTU != 0 {
  438. wireguard.Section(section_interface).Key("MTU").SetValue(strconv.FormatInt(int64(node.MTU), 10))
  439. }
  440. if err := wireguard.SaveTo(file); err != nil {
  441. return err
  442. }
  443. return nil
  444. }
  445. // UpdatePrivateKey - updates the private key of a wireguard config file
  446. func UpdatePrivateKey(file, privateKey string) 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. wireguard.Section(section_interface).Key("PrivateKey").SetValue(privateKey)
  456. if err := wireguard.SaveTo(file); err != nil {
  457. return err
  458. }
  459. return nil
  460. }
  461. // UpdateKeepAlive - updates the persistentkeepalive of all peers
  462. func UpdateKeepAlive(file string, keepalive int32) error {
  463. options := ini.LoadOptions{
  464. AllowNonUniqueSections: true,
  465. AllowShadows: true,
  466. }
  467. wireguard, err := ini.LoadSources(options, file)
  468. if err != nil {
  469. return err
  470. }
  471. peers, err := wireguard.SectionsByName(section_peers)
  472. if err != nil {
  473. return err
  474. }
  475. newvalue := strconv.Itoa(int(keepalive))
  476. for i := range peers {
  477. wireguard.SectionWithIndex(section_peers, i).Key("PersistentKeepALive").SetValue(newvalue)
  478. }
  479. if err := wireguard.SaveTo(file); err != nil {
  480. return err
  481. }
  482. return nil
  483. }
  484. // RemoveConfGraceful - Run remove conf and wait for it to actually be gone before proceeding
  485. func RemoveConfGraceful(ifacename string) {
  486. // ensure you clear any existing interface first
  487. wgclient, err := wgctrl.New()
  488. if err != nil {
  489. logger.Log(0, "could not create wgclient")
  490. return
  491. }
  492. defer wgclient.Close()
  493. d, _ := wgclient.Device(ifacename)
  494. startTime := time.Now()
  495. for d != nil && d.Name == ifacename {
  496. if err = RemoveConf(ifacename, false); err != nil { // remove interface first
  497. if strings.Contains(err.Error(), "does not exist") {
  498. err = nil
  499. break
  500. }
  501. }
  502. time.Sleep(time.Second >> 2)
  503. d, _ = wgclient.Device(ifacename)
  504. if time.Now().After(startTime.Add(time.Second << 4)) {
  505. break
  506. }
  507. }
  508. time.Sleep(time.Second << 1)
  509. }
  510. // GetDevicePeers - gets the current device's peers
  511. func GetDevicePeers(iface string) ([]wgtypes.Peer, error) {
  512. if ncutils.IsFreeBSD() {
  513. if devicePeers, err := ncutils.GetPeers(iface); err != nil {
  514. return nil, err
  515. } else {
  516. return devicePeers, nil
  517. }
  518. } else {
  519. client, err := wgctrl.New()
  520. if err != nil {
  521. logger.Log(0, "failed to start wgctrl")
  522. return nil, err
  523. }
  524. defer client.Close()
  525. device, err := client.Device(iface)
  526. if err != nil {
  527. logger.Log(0, "failed to parse interface")
  528. return nil, err
  529. }
  530. return device.Peers, nil
  531. }
  532. }