common.go 14 KB

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