common.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554
  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. addrString := node.Address
  309. if node.Address6 != "" {
  310. if addrString != "" {
  311. addrString += ","
  312. }
  313. addrString += node.Address6
  314. }
  315. wireguard.Section(section_interface).Key("Address").SetValue(addrString)
  316. // need to figure out DNS
  317. //if node.DNSOn == "yes" {
  318. // wireguard.Section(section_interface).Key("DNS").SetValue(cfg.Server.CoreDNSAddr)
  319. //}
  320. if node.PostUp != "" {
  321. wireguard.Section(section_interface).Key("PostUp").SetValue(node.PostUp)
  322. }
  323. if node.PostDown != "" {
  324. wireguard.Section(section_interface).Key("PostDown").SetValue(node.PostDown)
  325. }
  326. if node.MTU != 0 {
  327. wireguard.Section(section_interface).Key("MTU").SetValue(strconv.FormatInt(int64(node.MTU), 10))
  328. }
  329. for i, peer := range peers {
  330. wireguard.SectionWithIndex(section_peers, i).Key("PublicKey").SetValue(peer.PublicKey.String())
  331. if peer.PresharedKey != nil {
  332. wireguard.SectionWithIndex(section_peers, i).Key("PreSharedKey").SetValue(peer.PresharedKey.String())
  333. }
  334. if peer.AllowedIPs != nil {
  335. var allowedIPs string
  336. for i, ip := range peer.AllowedIPs {
  337. if i == 0 {
  338. allowedIPs = ip.String()
  339. } else {
  340. allowedIPs = allowedIPs + ", " + ip.String()
  341. }
  342. }
  343. wireguard.SectionWithIndex(section_peers, i).Key("AllowedIps").SetValue(allowedIPs)
  344. }
  345. if peer.Endpoint != nil {
  346. wireguard.SectionWithIndex(section_peers, i).Key("Endpoint").SetValue(peer.Endpoint.String())
  347. }
  348. if peer.PersistentKeepaliveInterval != nil && peer.PersistentKeepaliveInterval.Seconds() > 0 {
  349. wireguard.SectionWithIndex(section_peers, i).Key("PersistentKeepalive").SetValue(strconv.FormatInt((int64)(peer.PersistentKeepaliveInterval.Seconds()), 10))
  350. }
  351. }
  352. if err := wireguard.SaveTo(ncutils.GetNetclientPathSpecific() + node.Interface + ".conf"); err != nil {
  353. return err
  354. }
  355. return nil
  356. }
  357. // UpdateWgPeers - updates the peers of a network
  358. func UpdateWgPeers(file string, peers []wgtypes.PeerConfig) error {
  359. options := ini.LoadOptions{
  360. AllowNonUniqueSections: true,
  361. AllowShadows: true,
  362. }
  363. wireguard, err := ini.LoadSources(options, file)
  364. if err != nil {
  365. return err
  366. }
  367. //delete the peers sections as they are going to be replaced
  368. wireguard.DeleteSection(section_peers)
  369. for i, peer := range peers {
  370. wireguard.SectionWithIndex(section_peers, i).Key("PublicKey").SetValue(peer.PublicKey.String())
  371. if peer.PresharedKey != nil {
  372. wireguard.SectionWithIndex(section_peers, i).Key("PreSharedKey").SetValue(peer.PresharedKey.String())
  373. }
  374. if peer.AllowedIPs != nil {
  375. var allowedIPs string
  376. for i, ip := range peer.AllowedIPs {
  377. if i == 0 {
  378. allowedIPs = ip.String()
  379. } else {
  380. allowedIPs = allowedIPs + ", " + ip.String()
  381. }
  382. }
  383. wireguard.SectionWithIndex(section_peers, i).Key("AllowedIps").SetValue(allowedIPs)
  384. }
  385. if peer.Endpoint != nil {
  386. wireguard.SectionWithIndex(section_peers, i).Key("Endpoint").SetValue(peer.Endpoint.String())
  387. }
  388. if peer.PersistentKeepaliveInterval != nil && peer.PersistentKeepaliveInterval.Seconds() > 0 {
  389. wireguard.SectionWithIndex(section_peers, i).Key("PersistentKeepalive").SetValue(strconv.FormatInt((int64)(peer.PersistentKeepaliveInterval.Seconds()), 10))
  390. }
  391. }
  392. if err := wireguard.SaveTo(file); err != nil {
  393. return err
  394. }
  395. return nil
  396. }
  397. // UpdateWgInterface - updates the interface section of a wireguard config file
  398. func UpdateWgInterface(file, privateKey, nameserver string, node models.Node) error {
  399. options := ini.LoadOptions{
  400. AllowNonUniqueSections: true,
  401. AllowShadows: true,
  402. }
  403. wireguard, err := ini.LoadSources(options, file)
  404. if err != nil {
  405. return err
  406. }
  407. if node.UDPHolePunch == "yes" {
  408. node.ListenPort = 0
  409. }
  410. wireguard.Section(section_interface).Key("PrivateKey").SetValue(privateKey)
  411. wireguard.Section(section_interface).Key("ListenPort").SetValue(strconv.Itoa(int(node.ListenPort)))
  412. addrString := node.Address
  413. if node.Address6 != "" {
  414. if addrString != "" {
  415. addrString += ","
  416. }
  417. addrString += node.Address6
  418. }
  419. wireguard.Section(section_interface).Key("Address").SetValue(addrString)
  420. //if node.DNSOn == "yes" {
  421. // wireguard.Section(section_interface).Key("DNS").SetValue(nameserver)
  422. //}
  423. if node.PostUp != "" {
  424. wireguard.Section(section_interface).Key("PostUp").SetValue(node.PostUp)
  425. }
  426. if node.PostDown != "" {
  427. wireguard.Section(section_interface).Key("PostDown").SetValue(node.PostDown)
  428. }
  429. if node.MTU != 0 {
  430. wireguard.Section(section_interface).Key("MTU").SetValue(strconv.FormatInt(int64(node.MTU), 10))
  431. }
  432. if err := wireguard.SaveTo(file); err != nil {
  433. return err
  434. }
  435. return nil
  436. }
  437. // UpdatePrivateKey - updates the private key of a wireguard config file
  438. func UpdatePrivateKey(file, privateKey string) error {
  439. options := ini.LoadOptions{
  440. AllowNonUniqueSections: true,
  441. AllowShadows: true,
  442. }
  443. wireguard, err := ini.LoadSources(options, file)
  444. if err != nil {
  445. return err
  446. }
  447. wireguard.Section(section_interface).Key("PrivateKey").SetValue(privateKey)
  448. if err := wireguard.SaveTo(file); err != nil {
  449. return err
  450. }
  451. return nil
  452. }
  453. // UpdateKeepAlive - updates the persistentkeepalive of all peers
  454. func UpdateKeepAlive(file string, keepalive int32) error {
  455. options := ini.LoadOptions{
  456. AllowNonUniqueSections: true,
  457. AllowShadows: true,
  458. }
  459. wireguard, err := ini.LoadSources(options, file)
  460. if err != nil {
  461. return err
  462. }
  463. peers, err := wireguard.SectionsByName(section_peers)
  464. if err != nil {
  465. return err
  466. }
  467. newvalue := strconv.Itoa(int(keepalive))
  468. for i := range peers {
  469. wireguard.SectionWithIndex(section_peers, i).Key("PersistentKeepALive").SetValue(newvalue)
  470. }
  471. if err := wireguard.SaveTo(file); err != nil {
  472. return err
  473. }
  474. return nil
  475. }
  476. // RemoveConfGraceful - Run remove conf and wait for it to actually be gone before proceeding
  477. func RemoveConfGraceful(ifacename string) {
  478. // ensure you clear any existing interface first
  479. wgclient, err := wgctrl.New()
  480. if err != nil {
  481. logger.Log(0, "could not create wgclient")
  482. return
  483. }
  484. defer wgclient.Close()
  485. d, _ := wgclient.Device(ifacename)
  486. startTime := time.Now()
  487. for d != nil && d.Name == ifacename {
  488. if err = RemoveConf(ifacename, false); err != nil { // remove interface first
  489. if strings.Contains(err.Error(), "does not exist") {
  490. err = nil
  491. break
  492. }
  493. }
  494. time.Sleep(time.Second >> 2)
  495. d, _ = wgclient.Device(ifacename)
  496. if time.Now().After(startTime.Add(time.Second << 4)) {
  497. break
  498. }
  499. }
  500. time.Sleep(time.Second << 1)
  501. }
  502. // GetDevicePeers - gets the current device's peers
  503. func GetDevicePeers(iface string) ([]wgtypes.Peer, error) {
  504. if ncutils.IsFreeBSD() {
  505. if devicePeers, err := ncutils.GetPeers(iface); err != nil {
  506. return nil, err
  507. } else {
  508. return devicePeers, nil
  509. }
  510. } else {
  511. client, err := wgctrl.New()
  512. if err != nil {
  513. logger.Log(0, "failed to start wgctrl")
  514. return nil, err
  515. }
  516. defer client.Close()
  517. device, err := client.Device(iface)
  518. if err != nil {
  519. logger.Log(0, "failed to parse interface")
  520. return nil, err
  521. }
  522. return device.Peers, nil
  523. }
  524. }