common.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414
  1. package wireguard
  2. import (
  3. "errors"
  4. "log"
  5. "os"
  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. // SetPeers - sets peers on a given WireGuard interface
  20. func SetPeers(iface string, keepalive int32, peers []wgtypes.PeerConfig) error {
  21. var devicePeers []wgtypes.Peer
  22. var err error
  23. if ncutils.IsFreeBSD() {
  24. if devicePeers, err = ncutils.GetPeers(iface); err != nil {
  25. return err
  26. }
  27. } else {
  28. client, err := wgctrl.New()
  29. if err != nil {
  30. ncutils.PrintLog("failed to start wgctrl", 0)
  31. return err
  32. }
  33. defer client.Close()
  34. device, err := client.Device(iface)
  35. if err != nil {
  36. ncutils.PrintLog("failed to parse interface", 0)
  37. return err
  38. }
  39. devicePeers = device.Peers
  40. }
  41. if len(devicePeers) > 1 && len(peers) == 0 {
  42. ncutils.PrintLog("no peers pulled", 1)
  43. return err
  44. }
  45. for _, peer := range peers {
  46. for _, currentPeer := range devicePeers {
  47. if currentPeer.AllowedIPs[0].String() == peer.AllowedIPs[0].String() &&
  48. currentPeer.PublicKey.String() != peer.PublicKey.String() {
  49. _, err := ncutils.RunCmd("wg set "+iface+" peer "+currentPeer.PublicKey.String()+" remove", true)
  50. if err != nil {
  51. log.Println("error removing peer", peer.Endpoint.String())
  52. }
  53. }
  54. }
  55. udpendpoint := peer.Endpoint.String()
  56. var allowedips string
  57. var iparr []string
  58. for _, ipaddr := range peer.AllowedIPs {
  59. iparr = append(iparr, ipaddr.String())
  60. }
  61. allowedips = strings.Join(iparr, ",")
  62. keepAliveString := strconv.Itoa(int(keepalive))
  63. if keepAliveString == "0" {
  64. keepAliveString = "15"
  65. }
  66. if peer.Endpoint != nil {
  67. _, err = ncutils.RunCmd("wg set "+iface+" peer "+peer.PublicKey.String()+
  68. " endpoint "+udpendpoint+
  69. " persistent-keepalive "+keepAliveString+
  70. " allowed-ips "+allowedips, true)
  71. } else {
  72. _, err = ncutils.RunCmd("wg set "+iface+" peer "+peer.PublicKey.String()+
  73. " persistent-keepalive "+keepAliveString+
  74. " allowed-ips "+allowedips, true)
  75. }
  76. if err != nil {
  77. log.Println("error setting peer", peer.PublicKey.String())
  78. }
  79. }
  80. for _, currentPeer := range devicePeers {
  81. shouldDelete := true
  82. for _, peer := range peers {
  83. if peer.AllowedIPs[0].String() == currentPeer.AllowedIPs[0].String() {
  84. shouldDelete = false
  85. }
  86. }
  87. if shouldDelete {
  88. output, err := ncutils.RunCmd("wg set "+iface+" peer "+currentPeer.PublicKey.String()+" remove", true)
  89. if err != nil {
  90. log.Println(output, "error removing peer", currentPeer.PublicKey.String())
  91. }
  92. }
  93. }
  94. if ncutils.IsMac() {
  95. err = SetMacPeerRoutes(iface)
  96. return err
  97. }
  98. return nil
  99. }
  100. // Initializes a WireGuard interface
  101. func InitWireguard(node *models.Node, privkey string, peers []wgtypes.PeerConfig, hasGateway bool, gateways []string, syncconf bool) error {
  102. key, err := wgtypes.ParseKey(privkey)
  103. if err != nil {
  104. return err
  105. }
  106. wgclient, err := wgctrl.New()
  107. if err != nil {
  108. return err
  109. }
  110. defer wgclient.Close()
  111. modcfg, err := config.ReadConfig(node.Network)
  112. if err != nil {
  113. return err
  114. }
  115. nodecfg := modcfg.Node
  116. if err != nil {
  117. log.Fatalf("failed to open client: %v", err)
  118. }
  119. var ifacename string
  120. if nodecfg.Interface != "" {
  121. ifacename = nodecfg.Interface
  122. } else if node.Interface != "" {
  123. ifacename = node.Interface
  124. } else {
  125. log.Fatal("no interface to configure")
  126. }
  127. if node.Address == "" {
  128. log.Fatal("no address to configure")
  129. }
  130. var newConf string
  131. if node.UDPHolePunch != "yes" {
  132. newConf, _ = ncutils.CreateWireGuardConf(node, key.String(), strconv.FormatInt(int64(node.ListenPort), 10), peers)
  133. } else {
  134. newConf, _ = ncutils.CreateWireGuardConf(node, key.String(), "", peers)
  135. }
  136. confPath := ncutils.GetNetclientPathSpecific() + ifacename + ".conf"
  137. ncutils.PrintLog("writing wg conf file to: "+confPath, 1)
  138. err = os.WriteFile(confPath, []byte(newConf), 0644)
  139. if err != nil {
  140. ncutils.PrintLog("error writing wg conf file to "+confPath+": "+err.Error(), 1)
  141. return err
  142. }
  143. if ncutils.IsWindows() {
  144. wgConfPath := ncutils.GetWGPathSpecific() + ifacename + ".conf"
  145. err = os.WriteFile(wgConfPath, []byte(newConf), 0644)
  146. if err != nil {
  147. ncutils.PrintLog("error writing wg conf file to "+wgConfPath+": "+err.Error(), 1)
  148. return err
  149. }
  150. confPath = wgConfPath
  151. }
  152. // spin up userspace / windows interface + apply the conf file
  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)
  271. }
  272. return err
  273. }
  274. // WriteWgConfig - creates a wireguard config file
  275. func WriteWgConfig(cfg config.ClientConfig, privateKey string, peers []wgtypes.Peer) error {
  276. options := ini.LoadOptions{
  277. AllowNonUniqueSections: true,
  278. AllowShadows: true,
  279. }
  280. wireguard := ini.Empty(options)
  281. wireguard.Section("Interface").Key("PrivateKey").SetValue(privateKey)
  282. wireguard.Section("Interface").Key("ListenPort").SetValue(strconv.Itoa(int(cfg.Node.ListenPort)))
  283. if cfg.Node.Address != "" {
  284. wireguard.Section("Interface").Key("Address").SetValue(cfg.Node.Address)
  285. }
  286. if cfg.Node.Address6 != "" {
  287. wireguard.Section("Interface").Key("Address").SetValue(cfg.Node.Address6)
  288. }
  289. if cfg.Node.DNSOn == "yes" {
  290. wireguard.Section("Interface").Key("DNS").SetValue(cfg.Server.CoreDNSAddr)
  291. }
  292. if cfg.Node.PostUp != "" {
  293. wireguard.Section("Interface").Key("PostUp").SetValue(cfg.Node.PostUp)
  294. }
  295. if cfg.Node.PostDown != "" {
  296. wireguard.Section("Interface").Key("PostDown").SetValue(cfg.Node.PostDown)
  297. }
  298. for i, peer := range peers {
  299. wireguard.SectionWithIndex("Peer", i).Key("PublicKey").SetValue(peer.PublicKey.String())
  300. if peer.PresharedKey.String() != "" {
  301. wireguard.SectionWithIndex("Peer", i).Key("PreSharedKey").SetValue(peer.PresharedKey.String())
  302. }
  303. if peer.AllowedIPs != nil {
  304. var allowedIPs string
  305. for _, ip := range peer.AllowedIPs {
  306. allowedIPs = allowedIPs + ", " + ip.String()
  307. }
  308. wireguard.SectionWithIndex("Peer", i).Key("AllowedIps").SetValue(allowedIPs)
  309. }
  310. if peer.Endpoint != nil {
  311. wireguard.SectionWithIndex("Peer", i).Key("Endpoint").SetValue(peer.Endpoint.String())
  312. }
  313. }
  314. if err := wireguard.SaveTo("/etc/netclient/config" + cfg.Node.Interface + ".conf"); err != nil {
  315. return err
  316. }
  317. return nil
  318. }
  319. // UpdateWgPeers - updates the peers of a network
  320. func UpdateWgPeers(wgInterface string, peers []wgtypes.Peer) error {
  321. //update to get path properly
  322. file := "/etc/netclient/config/" + wgInterface + ".conf"
  323. wireguard, err := ini.ShadowLoad(file)
  324. if err != nil {
  325. return err
  326. }
  327. for i, peer := range peers {
  328. wireguard.SectionWithIndex("Peer", i).Key("PublicKey").SetValue(peer.PublicKey.String())
  329. if peer.PresharedKey.String() != "" {
  330. wireguard.SectionWithIndex("Peer", i).Key("PreSharedKey").SetValue(peer.PresharedKey.String())
  331. }
  332. if peer.AllowedIPs != nil {
  333. var allowedIPs string
  334. for _, ip := range peer.AllowedIPs {
  335. allowedIPs = allowedIPs + ", " + ip.String()
  336. }
  337. wireguard.SectionWithIndex("Peer", i).Key("AllowedIps").SetValue(allowedIPs)
  338. }
  339. if peer.Endpoint != nil {
  340. wireguard.SectionWithIndex("Peer", i).Key("Endpoint").SetValue(peer.Endpoint.String())
  341. }
  342. }
  343. if err := wireguard.SaveTo(file); err != nil {
  344. return err
  345. }
  346. return nil
  347. }
  348. // UpdateWgInterface - updates the interface section of a wireguard config file
  349. func UpdateWgInterface(wgInterface, privateKey, nameserver string, node models.Node) error {
  350. //update to get path properly
  351. file := "/etc/netclient/config/" + wgInterface + ".conf"
  352. wireguard, err := ini.ShadowLoad(file)
  353. if err != nil {
  354. return err
  355. }
  356. wireguard.Section("Interface").Key("PrivateKey").SetValue(privateKey)
  357. wireguard.Section("Interface").Key("ListenPort").SetValue(strconv.Itoa(int(node.ListenPort)))
  358. if node.Address != "" {
  359. wireguard.Section("Interface").Key("Address").SetValue(node.Address)
  360. }
  361. if node.Address6 != "" {
  362. wireguard.Section("Interface").Key("Address").SetValue(node.Address6)
  363. }
  364. if node.DNSOn == "yes" {
  365. wireguard.Section("Interface").Key("DNS").SetValue(nameserver)
  366. }
  367. if node.PostUp != "" {
  368. wireguard.Section("Interface").Key("PostUp").SetValue(node.PostUp)
  369. }
  370. if node.PostDown != "" {
  371. wireguard.Section("Interface").Key("PostDown").SetValue(node.PostDown)
  372. }
  373. if err := wireguard.SaveTo(file); err != nil {
  374. return err
  375. }
  376. return nil
  377. }
  378. // UpdatePrivateKey - updates the private key of a wireguard config file
  379. func UpdatePrivateKey(wgInterface, privateKey string) error {
  380. //update to get path properly
  381. file := "/etc/netclient/config/" + wgInterface + ".conf"
  382. wireguard, err := ini.ShadowLoad(file)
  383. if err != nil {
  384. return err
  385. }
  386. wireguard.Section("Interface").Key("PrivateKey").SetValue(privateKey)
  387. if err := wireguard.SaveTo(file); err != nil {
  388. return err
  389. }
  390. return nil
  391. }