common.go 14 KB

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