common.go 17 KB

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