common.go 14 KB

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