common.go 15 KB

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