common.go 14 KB

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