common.go 15 KB

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