common.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475
  1. package wireguard
  2. import (
  3. "fmt"
  4. "log"
  5. "net"
  6. "runtime"
  7. "strconv"
  8. "strings"
  9. "time"
  10. "github.com/gravitl/netmaker/models"
  11. "github.com/gravitl/netmaker/netclient/config"
  12. "github.com/gravitl/netmaker/netclient/local"
  13. "github.com/gravitl/netmaker/netclient/ncutils"
  14. "github.com/gravitl/netmaker/netclient/server"
  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 currentNodeAddr = node.Address
  27. var keepalive = node.PersistentKeepalive
  28. var oldPeerAllowedIps = make(map[string][]net.IPNet, len(peers))
  29. var err error
  30. if ncutils.IsFreeBSD() {
  31. if devicePeers, err = ncutils.GetPeers(iface); err != nil {
  32. return err
  33. }
  34. } else {
  35. client, err := wgctrl.New()
  36. if err != nil {
  37. ncutils.PrintLog("failed to start wgctrl", 0)
  38. return err
  39. }
  40. defer client.Close()
  41. device, err := client.Device(iface)
  42. if err != nil {
  43. ncutils.PrintLog("failed to parse interface", 0)
  44. return err
  45. }
  46. devicePeers = device.Peers
  47. }
  48. if len(devicePeers) > 1 && len(peers) == 0 {
  49. ncutils.PrintLog("no peers pulled", 1)
  50. return err
  51. }
  52. for _, peer := range peers {
  53. for _, currentPeer := range devicePeers {
  54. if currentPeer.AllowedIPs[0].String() == peer.AllowedIPs[0].String() &&
  55. currentPeer.PublicKey.String() != peer.PublicKey.String() {
  56. _, err := ncutils.RunCmd("wg set "+iface+" peer "+currentPeer.PublicKey.String()+" remove", true)
  57. if err != nil {
  58. log.Println("error removing peer", peer.Endpoint.String())
  59. }
  60. }
  61. }
  62. udpendpoint := peer.Endpoint.String()
  63. var allowedips string
  64. var iparr []string
  65. for _, ipaddr := range peer.AllowedIPs {
  66. iparr = append(iparr, ipaddr.String())
  67. }
  68. allowedips = strings.Join(iparr, ",")
  69. keepAliveString := strconv.Itoa(int(keepalive))
  70. if keepAliveString == "0" {
  71. keepAliveString = "15"
  72. }
  73. if node.IsHub == "yes" || peer.Endpoint == nil {
  74. _, err = ncutils.RunCmd("wg set "+iface+" peer "+peer.PublicKey.String()+
  75. " persistent-keepalive "+keepAliveString+
  76. " allowed-ips "+allowedips, true)
  77. } else {
  78. _, err = ncutils.RunCmd("wg set "+iface+" peer "+peer.PublicKey.String()+
  79. " endpoint "+udpendpoint+
  80. " persistent-keepalive "+keepAliveString+
  81. " allowed-ips "+allowedips, true)
  82. }
  83. if err != nil {
  84. log.Println("error setting peer", peer.PublicKey.String())
  85. }
  86. }
  87. for _, currentPeer := range devicePeers {
  88. shouldDelete := true
  89. for _, peer := range peers {
  90. if peer.AllowedIPs[0].String() == currentPeer.AllowedIPs[0].String() {
  91. shouldDelete = false
  92. }
  93. // re-check this if logic is not working, added in case of allowedips not working
  94. if peer.PublicKey.String() == currentPeer.PublicKey.String() {
  95. shouldDelete = false
  96. }
  97. }
  98. if shouldDelete {
  99. output, err := ncutils.RunCmd("wg set "+iface+" peer "+currentPeer.PublicKey.String()+" remove", true)
  100. if err != nil {
  101. log.Println(output, "error removing peer", currentPeer.PublicKey.String())
  102. }
  103. }
  104. oldPeerAllowedIps[currentPeer.PublicKey.String()] = currentPeer.AllowedIPs
  105. }
  106. if ncutils.IsMac() {
  107. err = SetMacPeerRoutes(iface)
  108. return err
  109. } else if ncutils.IsLinux() {
  110. local.SetPeerRoutes(iface, currentNodeAddr, oldPeerAllowedIps, peers)
  111. }
  112. return nil
  113. }
  114. // Initializes a WireGuard interface
  115. func InitWireguard(node *models.Node, privkey string, peers []wgtypes.PeerConfig, hasGateway bool, gateways []string, syncconf bool) error {
  116. key, err := wgtypes.ParseKey(privkey)
  117. if err != nil {
  118. return err
  119. }
  120. wgclient, err := wgctrl.New()
  121. if err != nil {
  122. return err
  123. }
  124. defer wgclient.Close()
  125. modcfg, err := config.ReadConfig(node.Network)
  126. if err != nil {
  127. return err
  128. }
  129. nodecfg := modcfg.Node
  130. var ifacename string
  131. if nodecfg.Interface != "" {
  132. ifacename = nodecfg.Interface
  133. } else if node.Interface != "" {
  134. ifacename = node.Interface
  135. } else {
  136. return fmt.Errorf("no interface to configure")
  137. }
  138. if node.Address == "" {
  139. return fmt.Errorf("no address to configure")
  140. }
  141. if node.UDPHolePunch == "yes" {
  142. node.ListenPort = 0
  143. }
  144. if err := WriteWgConfig(&modcfg.Node, key.String(), peers); err != nil {
  145. ncutils.PrintLog("error writing wg conf file: "+err.Error(), 1)
  146. return err
  147. }
  148. // spin up userspace / windows interface + apply the conf file
  149. confPath := ncutils.GetNetclientPathSpecific() + ifacename + ".conf"
  150. var deviceiface = ifacename
  151. if ncutils.IsMac() { // if node is Mac (Darwin) get the tunnel name first
  152. deviceiface, err = local.GetMacIface(node.Address)
  153. if err != nil || deviceiface == "" {
  154. deviceiface = ifacename
  155. }
  156. }
  157. // ensure you clear any existing interface first
  158. d, _ := wgclient.Device(deviceiface)
  159. for d != nil && d.Name == deviceiface {
  160. if err = RemoveConf(deviceiface, false); err != nil { // remove interface first
  161. if strings.Contains(err.Error(), "does not exist") {
  162. err = nil
  163. break
  164. }
  165. }
  166. time.Sleep(time.Second >> 2)
  167. d, _ = wgclient.Device(deviceiface)
  168. }
  169. ApplyConf(node, ifacename, confPath) // Apply initially
  170. ncutils.PrintLog("waiting for interface...", 1) // ensure interface is created
  171. output, _ := ncutils.RunCmd("wg", false)
  172. starttime := time.Now()
  173. ifaceReady := strings.Contains(output, deviceiface)
  174. for !ifaceReady && !(time.Now().After(starttime.Add(time.Second << 4))) {
  175. if ncutils.IsMac() { // if node is Mac (Darwin) get the tunnel name first
  176. deviceiface, err = local.GetMacIface(node.Address)
  177. if err != nil || deviceiface == "" {
  178. deviceiface = ifacename
  179. }
  180. }
  181. output, _ = ncutils.RunCmd("wg", false)
  182. err = ApplyConf(node, node.Interface, confPath)
  183. time.Sleep(time.Second)
  184. ifaceReady = strings.Contains(output, deviceiface)
  185. }
  186. //wgclient does not work well on freebsd
  187. if node.OS == "freebsd" {
  188. if !ifaceReady {
  189. return fmt.Errorf("could not reliably create interface, please check wg installation and retry")
  190. }
  191. } else {
  192. _, devErr := wgclient.Device(deviceiface)
  193. if !ifaceReady || devErr != nil {
  194. return fmt.Errorf("could not reliably create interface, please check wg installation and retry")
  195. }
  196. }
  197. ncutils.PrintLog("interface ready - netclient.. ENGAGE", 1)
  198. if syncconf { // should never be called really.
  199. err = SyncWGQuickConf(ifacename, confPath)
  200. }
  201. if !ncutils.HasWgQuick() && ncutils.IsLinux() {
  202. err = SetPeers(ifacename, node, peers)
  203. if err != nil {
  204. ncutils.PrintLog("error setting peers: "+err.Error(), 1)
  205. }
  206. time.Sleep(time.Second)
  207. }
  208. _, cidr, cidrErr := net.ParseCIDR(modcfg.NetworkSettings.AddressRange)
  209. if cidrErr == nil {
  210. local.SetCIDRRoute(ifacename, node.Address, cidr)
  211. } else {
  212. ncutils.PrintLog("could not set cidr route properly: "+cidrErr.Error(), 1)
  213. }
  214. local.SetCurrentPeerRoutes(ifacename, node.Address, peers)
  215. return err
  216. }
  217. // SetWGConfig - sets the WireGuard Config of a given network and checks if it needs a peer update
  218. func SetWGConfig(network string, peerupdate bool) error {
  219. cfg, err := config.ReadConfig(network)
  220. if err != nil {
  221. return err
  222. }
  223. servercfg := cfg.Server
  224. nodecfg := cfg.Node
  225. peers, hasGateway, gateways, err := server.GetPeers(nodecfg.MacAddress, nodecfg.Network, servercfg.GRPCAddress, nodecfg.IsDualStack == "yes", nodecfg.IsIngressGateway == "yes", nodecfg.IsServer == "yes")
  226. if err != nil {
  227. return err
  228. }
  229. privkey, err := RetrievePrivKey(network)
  230. if err != nil {
  231. return err
  232. }
  233. if peerupdate && !ncutils.IsFreeBSD() && !(ncutils.IsLinux() && !ncutils.IsKernel()) {
  234. var iface string
  235. iface = nodecfg.Interface
  236. if ncutils.IsMac() {
  237. iface, err = local.GetMacIface(nodecfg.Address)
  238. if err != nil {
  239. return err
  240. }
  241. }
  242. err = SetPeers(iface, &nodecfg, peers)
  243. } else if peerupdate {
  244. err = InitWireguard(&nodecfg, privkey, peers, hasGateway, gateways, true)
  245. } else {
  246. err = InitWireguard(&nodecfg, privkey, peers, hasGateway, gateways, false)
  247. }
  248. if nodecfg.DNSOn == "yes" {
  249. _ = local.UpdateDNS(nodecfg.Interface, nodecfg.Network, servercfg.CoreDNSAddr)
  250. }
  251. return err
  252. }
  253. // RemoveConf - removes a configuration for a given WireGuard interface
  254. func RemoveConf(iface string, printlog bool) error {
  255. os := runtime.GOOS
  256. if !ncutils.HasWgQuick() {
  257. os = "nowgquick"
  258. }
  259. var err error
  260. switch os {
  261. case "nowgquick":
  262. err = RemoveWithoutWGQuick(iface)
  263. case "windows":
  264. err = RemoveWindowsConf(iface, printlog)
  265. case "darwin":
  266. err = RemoveConfMac(iface)
  267. default:
  268. confPath := ncutils.GetNetclientPathSpecific() + iface + ".conf"
  269. err = RemoveWGQuickConf(confPath, printlog)
  270. }
  271. return err
  272. }
  273. // ApplyConf - applys a conf on disk to WireGuard interface
  274. func ApplyConf(node *models.Node, ifacename string, confPath string) error {
  275. os := runtime.GOOS
  276. if ncutils.IsLinux() && !ncutils.HasWgQuick() {
  277. os = "nowgquick"
  278. }
  279. var err error
  280. switch os {
  281. case "nowgquick":
  282. ApplyWithoutWGQuick(node, ifacename, confPath)
  283. case "windows":
  284. ApplyWindowsConf(confPath)
  285. case "darwin":
  286. ApplyMacOSConf(node, ifacename, confPath)
  287. default:
  288. ApplyWGQuickConf(confPath, ifacename)
  289. }
  290. var nodeCfg config.ClientConfig
  291. nodeCfg.Network = node.Network
  292. nodeCfg.ReadConfig()
  293. ip, cidr, err := net.ParseCIDR(nodeCfg.NetworkSettings.AddressRange)
  294. if err == nil {
  295. local.SetCIDRRoute(node.Interface, ip.String(), cidr)
  296. }
  297. return err
  298. }
  299. // WriteWgConfig - creates a wireguard config file
  300. //func WriteWgConfig(cfg *config.ClientConfig, privateKey string, peers []wgtypes.PeerConfig) error {
  301. func WriteWgConfig(node *models.Node, privateKey string, peers []wgtypes.PeerConfig) error {
  302. options := ini.LoadOptions{
  303. AllowNonUniqueSections: true,
  304. AllowShadows: true,
  305. }
  306. wireguard := ini.Empty(options)
  307. wireguard.Section(section_interface).Key("PrivateKey").SetValue(privateKey)
  308. if node.ListenPort > 0 && node.UDPHolePunch != "yes" {
  309. wireguard.Section(section_interface).Key("ListenPort").SetValue(strconv.Itoa(int(node.ListenPort)))
  310. }
  311. if node.Address != "" {
  312. wireguard.Section(section_interface).Key("Address").SetValue(node.Address)
  313. }
  314. if node.Address6 != "" {
  315. wireguard.Section(section_interface).Key("Address").SetValue(node.Address6)
  316. }
  317. // need to figure out DNS
  318. //if node.DNSOn == "yes" {
  319. // wireguard.Section(section_interface).Key("DNS").SetValue(cfg.Server.CoreDNSAddr)
  320. //}
  321. if node.PostUp != "" {
  322. wireguard.Section(section_interface).Key("PostUp").SetValue(node.PostUp)
  323. }
  324. if node.PostDown != "" {
  325. wireguard.Section(section_interface).Key("PostDown").SetValue(node.PostDown)
  326. }
  327. if node.MTU != 0 {
  328. wireguard.Section(section_interface).Key("MTU").SetValue(strconv.FormatInt(int64(node.MTU), 10))
  329. }
  330. for i, peer := range peers {
  331. wireguard.SectionWithIndex(section_peers, i).Key("PublicKey").SetValue(peer.PublicKey.String())
  332. if peer.PresharedKey != nil {
  333. wireguard.SectionWithIndex(section_peers, i).Key("PreSharedKey").SetValue(peer.PresharedKey.String())
  334. }
  335. if peer.AllowedIPs != nil {
  336. var allowedIPs string
  337. for i, ip := range peer.AllowedIPs {
  338. if i == 0 {
  339. allowedIPs = ip.String()
  340. } else {
  341. allowedIPs = allowedIPs + ", " + ip.String()
  342. }
  343. }
  344. wireguard.SectionWithIndex(section_peers, i).Key("AllowedIps").SetValue(allowedIPs)
  345. }
  346. if peer.Endpoint != nil {
  347. wireguard.SectionWithIndex(section_peers, i).Key("Endpoint").SetValue(peer.Endpoint.String())
  348. }
  349. if peer.PersistentKeepaliveInterval != nil && peer.PersistentKeepaliveInterval.Seconds() > 0 {
  350. wireguard.SectionWithIndex(section_peers, i).Key("PersistentKeepalive").SetValue(strconv.FormatInt((int64)(peer.PersistentKeepaliveInterval.Seconds()), 10))
  351. }
  352. }
  353. if err := wireguard.SaveTo(ncutils.GetNetclientPathSpecific() + node.Interface + ".conf"); err != nil {
  354. return err
  355. }
  356. return nil
  357. }
  358. // UpdateWgPeers - updates the peers of a network
  359. func UpdateWgPeers(file string, peers []wgtypes.PeerConfig) error {
  360. options := ini.LoadOptions{
  361. AllowNonUniqueSections: true,
  362. AllowShadows: true,
  363. }
  364. wireguard, err := ini.LoadSources(options, file)
  365. if err != nil {
  366. return err
  367. }
  368. //delete the peers sections as they are going to be replaced
  369. wireguard.DeleteSection(section_peers)
  370. for i, peer := range peers {
  371. wireguard.SectionWithIndex(section_peers, i).Key("PublicKey").SetValue(peer.PublicKey.String())
  372. if peer.PresharedKey != nil {
  373. wireguard.SectionWithIndex(section_peers, i).Key("PreSharedKey").SetValue(peer.PresharedKey.String())
  374. }
  375. if peer.AllowedIPs != nil {
  376. var allowedIPs string
  377. for i, ip := range peer.AllowedIPs {
  378. if i == 0 {
  379. allowedIPs = ip.String()
  380. } else {
  381. allowedIPs = allowedIPs + ", " + ip.String()
  382. }
  383. }
  384. wireguard.SectionWithIndex(section_peers, i).Key("AllowedIps").SetValue(allowedIPs)
  385. }
  386. if peer.Endpoint != nil {
  387. wireguard.SectionWithIndex(section_peers, i).Key("Endpoint").SetValue(peer.Endpoint.String())
  388. }
  389. if peer.PersistentKeepaliveInterval != nil && peer.PersistentKeepaliveInterval.Seconds() > 0 {
  390. wireguard.SectionWithIndex(section_peers, i).Key("PersistentKeepalive").SetValue(strconv.FormatInt((int64)(peer.PersistentKeepaliveInterval.Seconds()), 10))
  391. }
  392. }
  393. if err := wireguard.SaveTo(file); err != nil {
  394. return err
  395. }
  396. return nil
  397. }
  398. // UpdateWgInterface - updates the interface section of a wireguard config file
  399. func UpdateWgInterface(file, privateKey, nameserver string, node models.Node) error {
  400. options := ini.LoadOptions{
  401. AllowNonUniqueSections: true,
  402. AllowShadows: true,
  403. }
  404. wireguard, err := ini.LoadSources(options, file)
  405. if err != nil {
  406. return err
  407. }
  408. if node.UDPHolePunch == "yes" {
  409. node.ListenPort = 0
  410. }
  411. wireguard.Section(section_interface).Key("PrivateKey").SetValue(privateKey)
  412. wireguard.Section(section_interface).Key("ListenPort").SetValue(strconv.Itoa(int(node.ListenPort)))
  413. if node.Address != "" {
  414. wireguard.Section(section_interface).Key("Address").SetValue(node.Address)
  415. }
  416. if node.Address6 != "" {
  417. wireguard.Section(section_interface).Key("Address").SetValue(node.Address6)
  418. }
  419. //if node.DNSOn == "yes" {
  420. // wireguard.Section(section_interface).Key("DNS").SetValue(nameserver)
  421. //}
  422. if node.PostUp != "" {
  423. wireguard.Section(section_interface).Key("PostUp").SetValue(node.PostUp)
  424. }
  425. if node.PostDown != "" {
  426. wireguard.Section(section_interface).Key("PostDown").SetValue(node.PostDown)
  427. }
  428. if node.MTU != 0 {
  429. wireguard.Section(section_interface).Key("MTU").SetValue(strconv.FormatInt(int64(node.MTU), 10))
  430. }
  431. if err := wireguard.SaveTo(file); err != nil {
  432. return err
  433. }
  434. return nil
  435. }
  436. // UpdatePrivateKey - updates the private key of a wireguard config file
  437. func UpdatePrivateKey(file, privateKey string) error {
  438. options := ini.LoadOptions{
  439. AllowNonUniqueSections: true,
  440. AllowShadows: true,
  441. }
  442. wireguard, err := ini.LoadSources(options, file)
  443. if err != nil {
  444. return err
  445. }
  446. wireguard.Section(section_interface).Key("PrivateKey").SetValue(privateKey)
  447. if err := wireguard.SaveTo(file); err != nil {
  448. return err
  449. }
  450. return nil
  451. }