common.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463
  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. var ifacename string
  129. if nodecfg.Interface != "" {
  130. ifacename = nodecfg.Interface
  131. } else if node.Interface != "" {
  132. ifacename = node.Interface
  133. } else {
  134. return fmt.Errorf("no interface to configure")
  135. }
  136. if node.Address == "" {
  137. return fmt.Errorf("no address to configure")
  138. }
  139. if node.UDPHolePunch == "yes" {
  140. node.ListenPort = 0
  141. }
  142. if err := WriteWgConfig(&modcfg.Node, key.String(), peers); err != nil {
  143. ncutils.PrintLog("error writing wg conf file: "+err.Error(), 1)
  144. return err
  145. }
  146. // spin up userspace / windows interface + apply the conf file
  147. confPath := ncutils.GetNetclientPathSpecific() + ifacename + ".conf"
  148. var deviceiface = ifacename
  149. if ncutils.IsMac() { // if node is Mac (Darwin) get the tunnel name first
  150. deviceiface, err = local.GetMacIface(node.Address)
  151. if err != nil || deviceiface == "" {
  152. deviceiface = ifacename
  153. }
  154. }
  155. // ensure you clear any existing interface first
  156. d, _ := wgclient.Device(deviceiface)
  157. for d != nil && d.Name == deviceiface {
  158. if err = RemoveConf(deviceiface, false); err != nil { // remove interface first
  159. if strings.Contains(err.Error(), "does not exist") {
  160. err = nil
  161. break
  162. }
  163. }
  164. time.Sleep(time.Second >> 2)
  165. d, _ = wgclient.Device(deviceiface)
  166. }
  167. ApplyConf(node, ifacename, confPath) // Apply initially
  168. ncutils.PrintLog("waiting for interface...", 1) // ensure interface is created
  169. output, _ := ncutils.RunCmd("wg", false)
  170. starttime := time.Now()
  171. ifaceReady := strings.Contains(output, deviceiface)
  172. for !ifaceReady && !(time.Now().After(starttime.Add(time.Second << 4))) {
  173. if ncutils.IsMac() { // if node is Mac (Darwin) get the tunnel name first
  174. deviceiface, err = local.GetMacIface(node.Address)
  175. if err != nil || deviceiface == "" {
  176. deviceiface = ifacename
  177. }
  178. }
  179. output, _ = ncutils.RunCmd("wg", false)
  180. err = ApplyConf(node, node.Interface, confPath)
  181. time.Sleep(time.Second)
  182. ifaceReady = strings.Contains(output, deviceiface)
  183. }
  184. //wgclient does not work well on freebsd
  185. if node.OS == "freebsd" {
  186. if !ifaceReady {
  187. return fmt.Errorf("could not reliably create interface, please check wg installation and retry")
  188. }
  189. } else {
  190. _, devErr := wgclient.Device(deviceiface)
  191. if !ifaceReady || devErr != nil {
  192. return fmt.Errorf("could not reliably create interface, please check wg installation and retry")
  193. }
  194. }
  195. ncutils.PrintLog("interface ready - netclient.. ENGAGE", 1)
  196. if syncconf { // should never be called really.
  197. err = SyncWGQuickConf(ifacename, confPath)
  198. }
  199. if !ncutils.HasWgQuick() && ncutils.IsLinux() {
  200. err = SetPeers(ifacename, node.Address, node.PersistentKeepalive, peers)
  201. if err != nil {
  202. ncutils.PrintLog("error setting peers: "+err.Error(), 1)
  203. }
  204. time.Sleep(time.Second)
  205. }
  206. _, cidr, cidrErr := net.ParseCIDR(modcfg.NetworkSettings.AddressRange)
  207. if cidrErr == nil {
  208. local.SetCIDRRoute(ifacename, node.Address, cidr)
  209. } else {
  210. ncutils.PrintLog("could not set cidr route properly: "+cidrErr.Error(), 1)
  211. }
  212. local.SetCurrentPeerRoutes(ifacename, node.Address, peers)
  213. return err
  214. }
  215. // SetWGConfig - sets the WireGuard Config of a given network and checks if it needs a peer update
  216. func SetWGConfig(network string, peerupdate bool) error {
  217. cfg, err := config.ReadConfig(network)
  218. if err != nil {
  219. return err
  220. }
  221. servercfg := cfg.Server
  222. nodecfg := cfg.Node
  223. peers, hasGateway, gateways, err := server.GetPeers(nodecfg.MacAddress, nodecfg.Network, servercfg.GRPCAddress, nodecfg.IsDualStack == "yes", nodecfg.IsIngressGateway == "yes", nodecfg.IsServer == "yes")
  224. if err != nil {
  225. return err
  226. }
  227. privkey, err := RetrievePrivKey(network)
  228. if err != nil {
  229. return err
  230. }
  231. if peerupdate && !ncutils.IsFreeBSD() && !(ncutils.IsLinux() && !ncutils.IsKernel()) {
  232. var iface string
  233. iface = nodecfg.Interface
  234. if ncutils.IsMac() {
  235. iface, err = local.GetMacIface(nodecfg.Address)
  236. if err != nil {
  237. return err
  238. }
  239. }
  240. err = SetPeers(iface, nodecfg.Address, nodecfg.PersistentKeepalive, peers)
  241. } else if peerupdate {
  242. err = InitWireguard(&nodecfg, privkey, peers, hasGateway, gateways, true)
  243. } else {
  244. err = InitWireguard(&nodecfg, privkey, peers, hasGateway, gateways, false)
  245. }
  246. if nodecfg.DNSOn == "yes" {
  247. _ = local.UpdateDNS(nodecfg.Interface, nodecfg.Network, servercfg.CoreDNSAddr)
  248. }
  249. return err
  250. }
  251. // RemoveConf - removes a configuration for a given WireGuard interface
  252. func RemoveConf(iface string, printlog bool) error {
  253. os := runtime.GOOS
  254. if !ncutils.HasWgQuick() {
  255. os = "nowgquick"
  256. }
  257. var err error
  258. switch os {
  259. case "nowgquick":
  260. err = RemoveWithoutWGQuick(iface)
  261. case "windows":
  262. err = RemoveWindowsConf(iface, printlog)
  263. case "darwin":
  264. err = RemoveConfMac(iface)
  265. default:
  266. confPath := ncutils.GetNetclientPathSpecific() + iface + ".conf"
  267. err = RemoveWGQuickConf(confPath, printlog)
  268. }
  269. return err
  270. }
  271. // ApplyConf - applys a conf on disk to WireGuard interface
  272. func ApplyConf(node *models.Node, ifacename string, confPath string) error {
  273. os := runtime.GOOS
  274. if ncutils.IsLinux() && !ncutils.HasWgQuick() {
  275. os = "nowgquick"
  276. }
  277. var err error
  278. switch os {
  279. case "nowgquick":
  280. err = ApplyWithoutWGQuick(node, ifacename, confPath)
  281. case "windows":
  282. _ = ApplyWindowsConf(confPath)
  283. case "darwin":
  284. _ = ApplyMacOSConf(node, ifacename, confPath)
  285. default:
  286. err = ApplyWGQuickConf(confPath, ifacename)
  287. }
  288. return err
  289. }
  290. // WriteWgConfig - creates a wireguard config file
  291. //func WriteWgConfig(cfg *config.ClientConfig, privateKey string, peers []wgtypes.PeerConfig) error {
  292. func WriteWgConfig(node *models.Node, privateKey string, peers []wgtypes.PeerConfig) error {
  293. options := ini.LoadOptions{
  294. AllowNonUniqueSections: true,
  295. AllowShadows: true,
  296. }
  297. wireguard := ini.Empty(options)
  298. wireguard.Section(section_interface).Key("PrivateKey").SetValue(privateKey)
  299. if node.ListenPort > 0 && node.UDPHolePunch != "yes" {
  300. wireguard.Section(section_interface).Key("ListenPort").SetValue(strconv.Itoa(int(node.ListenPort)))
  301. }
  302. if node.Address != "" {
  303. wireguard.Section(section_interface).Key("Address").SetValue(node.Address)
  304. }
  305. if node.Address6 != "" {
  306. wireguard.Section(section_interface).Key("Address").SetValue(node.Address6)
  307. }
  308. // need to figure out DNS
  309. //if node.DNSOn == "yes" {
  310. // wireguard.Section(section_interface).Key("DNS").SetValue(cfg.Server.CoreDNSAddr)
  311. //}
  312. if node.PostUp != "" {
  313. wireguard.Section(section_interface).Key("PostUp").SetValue(node.PostUp)
  314. }
  315. if node.PostDown != "" {
  316. wireguard.Section(section_interface).Key("PostDown").SetValue(node.PostDown)
  317. }
  318. if node.MTU != 0 {
  319. wireguard.Section(section_interface).Key("MTU").SetValue(strconv.FormatInt(int64(node.MTU), 10))
  320. }
  321. for i, peer := range peers {
  322. wireguard.SectionWithIndex(section_peers, i).Key("PublicKey").SetValue(peer.PublicKey.String())
  323. if peer.PresharedKey != nil {
  324. wireguard.SectionWithIndex(section_peers, i).Key("PreSharedKey").SetValue(peer.PresharedKey.String())
  325. }
  326. if peer.AllowedIPs != nil {
  327. var allowedIPs string
  328. for i, ip := range peer.AllowedIPs {
  329. if i == 0 {
  330. allowedIPs = ip.String()
  331. } else {
  332. allowedIPs = allowedIPs + ", " + ip.String()
  333. }
  334. }
  335. wireguard.SectionWithIndex(section_peers, i).Key("AllowedIps").SetValue(allowedIPs)
  336. }
  337. if peer.Endpoint != nil {
  338. wireguard.SectionWithIndex(section_peers, i).Key("Endpoint").SetValue(peer.Endpoint.String())
  339. }
  340. if peer.PersistentKeepaliveInterval != nil && peer.PersistentKeepaliveInterval.Seconds() > 0 {
  341. wireguard.SectionWithIndex(section_peers, i).Key("PersistentKeepalive").SetValue(strconv.FormatInt((int64)(peer.PersistentKeepaliveInterval.Seconds()), 10))
  342. }
  343. }
  344. if err := wireguard.SaveTo(ncutils.GetNetclientPathSpecific() + node.Interface + ".conf"); err != nil {
  345. return err
  346. }
  347. return nil
  348. }
  349. // UpdateWgPeers - updates the peers of a network
  350. func UpdateWgPeers(file string, peers []wgtypes.PeerConfig) error {
  351. options := ini.LoadOptions{
  352. AllowNonUniqueSections: true,
  353. AllowShadows: true,
  354. }
  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. }