common.go 13 KB

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