common.go 13 KB

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