common.go 13 KB

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