2
0

common.go 14 KB

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