common.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465
  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. ncutils.PrintLog("error removing peer: "+currentPeer.Endpoint.String(), 1)
  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. ncutils.PrintLog("error setting peer: "+peer.PublicKey.String(), 1)
  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. return fmt.Errorf("no interface to configure")
  152. }
  153. if node.Address == "" {
  154. return fmt.Errorf("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. err = RemoveConf(deviceiface, false) // remove interface first
  176. if strings.Contains(err.Error(), "does not exist") {
  177. err = nil
  178. break
  179. }
  180. time.Sleep(time.Second >> 2)
  181. d, _ = wgclient.Device(deviceiface)
  182. }
  183. ApplyConf(node, deviceiface, confPath) // Apply initially
  184. ncutils.PrintLog("waiting for interface...", 1) // ensure interface is created
  185. output, _ := ncutils.RunCmd("wg", false)
  186. starttime := time.Now()
  187. ifaceReady := strings.Contains(output, deviceiface)
  188. for !ifaceReady && !(time.Now().After(starttime.Add(time.Second << 4))) {
  189. if ncutils.IsMac() { // if node is Mac (Darwin) get the tunnel name first
  190. deviceiface, err = local.GetMacIface(node.Address)
  191. if err != nil || deviceiface == "" {
  192. deviceiface = ifacename
  193. }
  194. }
  195. output, _ = ncutils.RunCmd("wg", false)
  196. err = ApplyConf(node, deviceiface, confPath)
  197. time.Sleep(time.Second)
  198. ifaceReady = strings.Contains(output, deviceiface)
  199. }
  200. //wgclient does not work well on freebsd
  201. if node.OS == "freebsd" {
  202. if !ifaceReady {
  203. return fmt.Errorf("could not reliably create interface, please check wg installation and retry")
  204. }
  205. } else {
  206. _, devErr := wgclient.Device(deviceiface)
  207. if !ifaceReady || devErr != nil {
  208. return fmt.Errorf("could not reliably create interface, please check wg installation and retry")
  209. }
  210. }
  211. ncutils.PrintLog("interface ready - netclient engage", 1)
  212. if syncconf { // should never be called really.
  213. err = SyncWGQuickConf(ifacename, confPath)
  214. }
  215. _, cidr, cidrErr := net.ParseCIDR(modcfg.NetworkSettings.AddressRange)
  216. if cidrErr == nil {
  217. local.SetCIDRRoute(ifacename, node.Address, cidr)
  218. } else {
  219. ncutils.PrintLog("could not set cidr route properly: "+cidrErr.Error(), 1)
  220. }
  221. local.SetCurrentPeerRoutes(ifacename, node.Address, peers)
  222. return err
  223. }
  224. // SetWGConfig - sets the WireGuard Config of a given network and checks if it needs a peer update
  225. func SetWGConfig(network string, peerupdate bool) error {
  226. cfg, err := config.ReadConfig(network)
  227. if err != nil {
  228. return err
  229. }
  230. servercfg := cfg.Server
  231. nodecfg := cfg.Node
  232. peers, hasGateway, gateways, err := server.GetPeers(nodecfg.MacAddress, nodecfg.Network, servercfg.GRPCAddress, nodecfg.IsDualStack == "yes", nodecfg.IsIngressGateway == "yes", nodecfg.IsServer == "yes")
  233. if err != nil {
  234. return err
  235. }
  236. privkey, err := RetrievePrivKey(network)
  237. if err != nil {
  238. return err
  239. }
  240. if peerupdate && !ncutils.IsFreeBSD() && !(ncutils.IsLinux() && !ncutils.IsKernel()) {
  241. var iface string
  242. iface = nodecfg.Interface
  243. if ncutils.IsMac() {
  244. iface, err = local.GetMacIface(nodecfg.Address)
  245. if err != nil {
  246. return err
  247. }
  248. }
  249. err = SetPeers(iface, nodecfg.Address, nodecfg.PersistentKeepalive, peers)
  250. } else if peerupdate {
  251. err = InitWireguard(&nodecfg, privkey, peers, hasGateway, gateways, true)
  252. } else {
  253. err = InitWireguard(&nodecfg, privkey, peers, hasGateway, gateways, false)
  254. }
  255. if nodecfg.DNSOn == "yes" {
  256. _ = local.UpdateDNS(nodecfg.Interface, nodecfg.Network, servercfg.CoreDNSAddr)
  257. }
  258. return err
  259. }
  260. // RemoveConf - removes a configuration for a given WireGuard interface
  261. func RemoveConf(iface string, printlog bool) error {
  262. os := runtime.GOOS
  263. var err error
  264. switch os {
  265. case "windows":
  266. err = RemoveWindowsConf(iface, printlog)
  267. case "darwin":
  268. err = RemoveConfMac(iface)
  269. default:
  270. confPath := ncutils.GetNetclientPathSpecific() + iface + ".conf"
  271. err = RemoveWGQuickConf(confPath, printlog)
  272. }
  273. return err
  274. }
  275. // ApplyConf - applys a conf on disk to WireGuard interface
  276. func ApplyConf(node *models.Node, ifacename string, confPath string) error {
  277. os := runtime.GOOS
  278. var err error
  279. switch os {
  280. case "windows":
  281. _ = ApplyWindowsConf(confPath)
  282. case "darwin":
  283. _ = ApplyMacOSConf(node, ifacename, confPath)
  284. default:
  285. err = ApplyWGQuickConf(confPath, ifacename)
  286. }
  287. return err
  288. }
  289. // WriteWgConfig - creates a wireguard config file
  290. //func WriteWgConfig(cfg *config.ClientConfig, privateKey string, peers []wgtypes.PeerConfig) error {
  291. func WriteWgConfig(node *models.Node, privateKey string, peers []wgtypes.PeerConfig) error {
  292. options := ini.LoadOptions{
  293. AllowNonUniqueSections: true,
  294. AllowShadows: true,
  295. }
  296. wireguard := ini.Empty(options)
  297. wireguard.Section(section_interface).Key("PrivateKey").SetValue(privateKey)
  298. if node.ListenPort > 0 && node.UDPHolePunch != "yes" {
  299. wireguard.Section(section_interface).Key("ListenPort").SetValue(strconv.Itoa(int(node.ListenPort)))
  300. }
  301. if node.Address != "" {
  302. wireguard.Section(section_interface).Key("Address").SetValue(node.Address)
  303. }
  304. if node.Address6 != "" {
  305. wireguard.Section(section_interface).Key("Address").SetValue(node.Address6)
  306. }
  307. // need to figure out DNS
  308. //if node.DNSOn == "yes" {
  309. // wireguard.Section(section_interface).Key("DNS").SetValue(cfg.Server.CoreDNSAddr)
  310. //}
  311. if node.PostUp != "" {
  312. wireguard.Section(section_interface).Key("PostUp").SetValue(node.PostUp)
  313. }
  314. if node.PostDown != "" {
  315. wireguard.Section(section_interface).Key("PostDown").SetValue(node.PostDown)
  316. }
  317. if node.MTU != 0 {
  318. wireguard.Section(section_interface).Key("MTU").SetValue(strconv.FormatInt(int64(node.MTU), 10))
  319. }
  320. for i, peer := range peers {
  321. wireguard.SectionWithIndex(section_peers, i).Key("PublicKey").SetValue(peer.PublicKey.String())
  322. if peer.PresharedKey != nil {
  323. wireguard.SectionWithIndex(section_peers, i).Key("PreSharedKey").SetValue(peer.PresharedKey.String())
  324. }
  325. if peer.AllowedIPs != nil {
  326. var allowedIPs string
  327. for i, ip := range peer.AllowedIPs {
  328. if i == 0 {
  329. allowedIPs = ip.String()
  330. } else {
  331. allowedIPs = allowedIPs + ", " + ip.String()
  332. }
  333. }
  334. wireguard.SectionWithIndex(section_peers, i).Key("AllowedIps").SetValue(allowedIPs)
  335. }
  336. if peer.Endpoint != nil {
  337. wireguard.SectionWithIndex(section_peers, i).Key("Endpoint").SetValue(peer.Endpoint.String())
  338. }
  339. if peer.PersistentKeepaliveInterval != nil && peer.PersistentKeepaliveInterval.Seconds() > 0 {
  340. wireguard.SectionWithIndex(section_peers, i).Key("PersistentKeepalive").SetValue(strconv.FormatInt((int64)(peer.PersistentKeepaliveInterval.Seconds()), 10))
  341. }
  342. }
  343. if err := wireguard.SaveTo(ncutils.GetNetclientPathSpecific() + node.Interface + ".conf"); err != nil {
  344. return err
  345. }
  346. return nil
  347. }
  348. // UpdateWgPeers - updates the peers of a network
  349. func UpdateWgPeers(file string, peers []wgtypes.PeerConfig) error {
  350. options := ini.LoadOptions{
  351. AllowNonUniqueSections: true,
  352. AllowShadows: true,
  353. }
  354. ncutils.Log("updating " + file)
  355. wireguard, err := ini.LoadSources(options, file)
  356. if err != nil {
  357. return err
  358. }
  359. //delete the peers sections as they are going to be replaced
  360. wireguard.DeleteSection(section_peers)
  361. for i, peer := range peers {
  362. wireguard.SectionWithIndex(section_peers, i).Key("PublicKey").SetValue(peer.PublicKey.String())
  363. if peer.PresharedKey != nil {
  364. wireguard.SectionWithIndex(section_peers, i).Key("PreSharedKey").SetValue(peer.PresharedKey.String())
  365. }
  366. if peer.AllowedIPs != nil {
  367. var allowedIPs string
  368. for i, ip := range peer.AllowedIPs {
  369. if i == 0 {
  370. allowedIPs = ip.String()
  371. } else {
  372. allowedIPs = allowedIPs + ", " + ip.String()
  373. }
  374. }
  375. wireguard.SectionWithIndex(section_peers, i).Key("AllowedIps").SetValue(allowedIPs)
  376. }
  377. if peer.Endpoint != nil {
  378. wireguard.SectionWithIndex(section_peers, i).Key("Endpoint").SetValue(peer.Endpoint.String())
  379. }
  380. if peer.PersistentKeepaliveInterval != nil && peer.PersistentKeepaliveInterval.Seconds() > 0 {
  381. wireguard.SectionWithIndex(section_peers, i).Key("PersistentKeepalive").SetValue(strconv.FormatInt((int64)(peer.PersistentKeepaliveInterval.Seconds()), 10))
  382. }
  383. }
  384. if err := wireguard.SaveTo(file); err != nil {
  385. return err
  386. }
  387. return nil
  388. }
  389. // UpdateWgInterface - updates the interface section of a wireguard config file
  390. func UpdateWgInterface(file, privateKey, nameserver string, node models.Node) error {
  391. options := ini.LoadOptions{
  392. AllowNonUniqueSections: true,
  393. AllowShadows: true,
  394. }
  395. wireguard, err := ini.LoadSources(options, file)
  396. if err != nil {
  397. return err
  398. }
  399. if node.UDPHolePunch == "yes" {
  400. node.ListenPort = 0
  401. }
  402. wireguard.Section(section_interface).Key("PrivateKey").SetValue(privateKey)
  403. wireguard.Section(section_interface).Key("ListenPort").SetValue(strconv.Itoa(int(node.ListenPort)))
  404. if node.Address != "" {
  405. wireguard.Section(section_interface).Key("Address").SetValue(node.Address)
  406. }
  407. if node.Address6 != "" {
  408. wireguard.Section(section_interface).Key("Address").SetValue(node.Address6)
  409. }
  410. //if node.DNSOn == "yes" {
  411. // wireguard.Section(section_interface).Key("DNS").SetValue(nameserver)
  412. //}
  413. if node.PostUp != "" {
  414. wireguard.Section(section_interface).Key("PostUp").SetValue(node.PostUp)
  415. }
  416. if node.PostDown != "" {
  417. wireguard.Section(section_interface).Key("PostDown").SetValue(node.PostDown)
  418. }
  419. if node.MTU != 0 {
  420. wireguard.Section(section_interface).Key("MTU").SetValue(strconv.FormatInt(int64(node.MTU), 10))
  421. }
  422. if err := wireguard.SaveTo(file); err != nil {
  423. return err
  424. }
  425. return nil
  426. }
  427. // UpdatePrivateKey - updates the private key of a wireguard config file
  428. func UpdatePrivateKey(file, privateKey string) error {
  429. options := ini.LoadOptions{
  430. AllowNonUniqueSections: true,
  431. AllowShadows: true,
  432. }
  433. wireguard, err := ini.LoadSources(options, file)
  434. if err != nil {
  435. return err
  436. }
  437. wireguard.Section(section_interface).Key("PrivateKey").SetValue(privateKey)
  438. if err := wireguard.SaveTo(file); err != nil {
  439. return err
  440. }
  441. return nil
  442. }