common.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415
  1. package wireguard
  2. import (
  3. "errors"
  4. "io/ioutil"
  5. "log"
  6. "os/exec"
  7. "runtime"
  8. "strconv"
  9. "strings"
  10. "time"
  11. "github.com/gravitl/netmaker/models"
  12. "github.com/gravitl/netmaker/netclient/config"
  13. "github.com/gravitl/netmaker/netclient/local"
  14. "github.com/gravitl/netmaker/netclient/ncutils"
  15. "github.com/gravitl/netmaker/netclient/server"
  16. "golang.zx2c4.com/wireguard/wgctrl"
  17. "golang.zx2c4.com/wireguard/wgctrl/wgtypes"
  18. "gopkg.in/ini.v1"
  19. )
  20. // SetPeers - sets peers on a given WireGuard interface
  21. func SetPeers(iface string, keepalive int32, peers []wgtypes.PeerConfig) error {
  22. var devicePeers []wgtypes.Peer
  23. var err error
  24. if ncutils.IsFreeBSD() {
  25. if devicePeers, err = ncutils.GetPeers(iface); err != nil {
  26. return err
  27. }
  28. } else {
  29. client, err := wgctrl.New()
  30. if err != nil {
  31. ncutils.PrintLog("failed to start wgctrl", 0)
  32. return err
  33. }
  34. defer client.Close()
  35. device, err := client.Device(iface)
  36. if err != nil {
  37. ncutils.PrintLog("failed to parse interface", 0)
  38. return err
  39. }
  40. devicePeers = device.Peers
  41. }
  42. if len(devicePeers) > 1 && len(peers) == 0 {
  43. ncutils.PrintLog("no peers pulled", 1)
  44. return err
  45. }
  46. for _, peer := range peers {
  47. for _, currentPeer := range devicePeers {
  48. if currentPeer.AllowedIPs[0].String() == peer.AllowedIPs[0].String() &&
  49. currentPeer.PublicKey.String() != peer.PublicKey.String() {
  50. _, err := ncutils.RunCmd("wg set "+iface+" peer "+currentPeer.PublicKey.String()+" remove", true)
  51. if err != nil {
  52. log.Println("error removing peer", peer.Endpoint.String())
  53. }
  54. }
  55. }
  56. udpendpoint := peer.Endpoint.String()
  57. var allowedips string
  58. var iparr []string
  59. for _, ipaddr := range peer.AllowedIPs {
  60. iparr = append(iparr, ipaddr.String())
  61. }
  62. allowedips = strings.Join(iparr, ",")
  63. keepAliveString := strconv.Itoa(int(keepalive))
  64. if keepAliveString == "0" {
  65. keepAliveString = "15"
  66. }
  67. if peer.Endpoint != nil {
  68. _, err = ncutils.RunCmd("wg set "+iface+" peer "+peer.PublicKey.String()+
  69. " endpoint "+udpendpoint+
  70. " persistent-keepalive "+keepAliveString+
  71. " allowed-ips "+allowedips, true)
  72. } else {
  73. _, err = ncutils.RunCmd("wg set "+iface+" peer "+peer.PublicKey.String()+
  74. " persistent-keepalive "+keepAliveString+
  75. " allowed-ips "+allowedips, true)
  76. }
  77. if err != nil {
  78. log.Println("error setting peer", peer.PublicKey.String())
  79. }
  80. }
  81. for _, currentPeer := range devicePeers {
  82. shouldDelete := true
  83. for _, peer := range peers {
  84. if peer.AllowedIPs[0].String() == currentPeer.AllowedIPs[0].String() {
  85. shouldDelete = false
  86. }
  87. }
  88. if shouldDelete {
  89. output, err := ncutils.RunCmd("wg set "+iface+" peer "+currentPeer.PublicKey.String()+" remove", true)
  90. if err != nil {
  91. log.Println(output, "error removing peer", currentPeer.PublicKey.String())
  92. }
  93. }
  94. }
  95. return nil
  96. }
  97. // Initializes a WireGuard interface
  98. func InitWireguard(node *models.Node, privkey string, peers []wgtypes.PeerConfig, hasGateway bool, gateways []string, syncconf bool) error {
  99. key, err := wgtypes.ParseKey(privkey)
  100. if err != nil {
  101. return err
  102. }
  103. wgclient, err := wgctrl.New()
  104. if err != nil {
  105. return err
  106. }
  107. defer wgclient.Close()
  108. modcfg, err := config.ReadConfig(node.Network)
  109. if err != nil {
  110. return err
  111. }
  112. nodecfg := modcfg.Node
  113. servercfg := modcfg.Server
  114. if err != nil {
  115. log.Fatalf("failed to open client: %v", err)
  116. }
  117. var ifacename string
  118. if nodecfg.Interface != "" {
  119. ifacename = nodecfg.Interface
  120. } else if node.Interface != "" {
  121. ifacename = node.Interface
  122. } else {
  123. log.Fatal("no interface to configure")
  124. }
  125. if node.Address == "" {
  126. log.Fatal("no address to configure")
  127. }
  128. var nameserver string
  129. if ncutils.IsLinux() {
  130. if _, err := exec.LookPath("resolvconf"); err != nil {
  131. ncutils.PrintLog("resolvconf not present", 2)
  132. ncutils.PrintLog("unable to configure DNS automatically, disabling automated DNS management", 2)
  133. node.DNSOn = "no"
  134. }
  135. }
  136. if node.DNSOn == "yes" {
  137. nameserver = servercfg.CoreDNSAddr
  138. }
  139. var newConf string
  140. if node.UDPHolePunch != "yes" {
  141. newConf, _ = ncutils.CreateWireGuardConf(node, key.String(), strconv.FormatInt(int64(node.ListenPort), 10), nameserver, peers)
  142. } else {
  143. newConf, _ = ncutils.CreateWireGuardConf(node, key.String(), "", nameserver, peers)
  144. }
  145. confPath := ncutils.GetNetclientPathSpecific() + ifacename + ".conf"
  146. ncutils.PrintLog("writing wg conf file to: "+confPath, 1)
  147. err = ioutil.WriteFile(confPath, []byte(newConf), 0644)
  148. if err != nil {
  149. ncutils.PrintLog("error writing wg conf file to "+confPath+": "+err.Error(), 1)
  150. return err
  151. }
  152. if ncutils.IsWindows() {
  153. wgConfPath := ncutils.GetWGPathSpecific() + ifacename + ".conf"
  154. err = ioutil.WriteFile(wgConfPath, []byte(newConf), 0644)
  155. if err != nil {
  156. ncutils.PrintLog("error writing wg conf file to "+wgConfPath+": "+err.Error(), 1)
  157. return err
  158. }
  159. confPath = wgConfPath
  160. }
  161. // spin up userspace / windows interface + apply the conf file
  162. var deviceiface string
  163. if ncutils.IsMac() {
  164. deviceiface, err = local.GetMacIface(node.Address)
  165. if err != nil || deviceiface == "" {
  166. deviceiface = ifacename
  167. }
  168. }
  169. if syncconf {
  170. err = SyncWGQuickConf(ifacename, confPath)
  171. } else {
  172. d, _ := wgclient.Device(deviceiface)
  173. for d != nil && d.Name == deviceiface {
  174. RemoveConf(ifacename, false) // remove interface first
  175. time.Sleep(time.Second >> 2)
  176. d, _ = wgclient.Device(deviceiface)
  177. }
  178. if !ncutils.IsWindows() {
  179. err = ApplyConf(confPath)
  180. if err != nil {
  181. ncutils.PrintLog("failed to create wireguard interface", 1)
  182. return err
  183. }
  184. } else {
  185. var output string
  186. starttime := time.Now()
  187. RemoveConf(ifacename, false)
  188. time.Sleep(time.Second >> 2)
  189. ncutils.PrintLog("waiting for interface...", 1)
  190. for !strings.Contains(output, ifacename) && !(time.Now().After(starttime.Add(time.Duration(10) * time.Second))) {
  191. output, _ = ncutils.RunCmd("wg", false)
  192. err = ApplyConf(confPath)
  193. time.Sleep(time.Second)
  194. }
  195. if !strings.Contains(output, ifacename) {
  196. return errors.New("could not create wg interface for " + ifacename)
  197. }
  198. ip, mask, err := ncutils.GetNetworkIPMask(nodecfg.NetworkSettings.AddressRange)
  199. if err != nil {
  200. log.Println(err.Error())
  201. return err
  202. }
  203. ncutils.RunCmd("route add "+ip+" mask "+mask+" "+node.Address, true)
  204. time.Sleep(time.Second >> 2)
  205. ncutils.RunCmd("route change "+ip+" mask "+mask+" "+node.Address, true)
  206. }
  207. }
  208. //extra network route setting
  209. if ncutils.IsFreeBSD() {
  210. _, _ = ncutils.RunCmd("route add -net "+nodecfg.NetworkSettings.AddressRange+" -interface "+ifacename, true)
  211. } else if ncutils.IsLinux() {
  212. _, _ = ncutils.RunCmd("ip -4 route add "+nodecfg.NetworkSettings.AddressRange+" dev "+ifacename, false)
  213. }
  214. return err
  215. }
  216. // SetWGConfig - sets the WireGuard Config of a given network and checks if it needs a peer update
  217. func SetWGConfig(network string, peerupdate bool) error {
  218. cfg, err := config.ReadConfig(network)
  219. if err != nil {
  220. return err
  221. }
  222. servercfg := cfg.Server
  223. nodecfg := cfg.Node
  224. peers, hasGateway, gateways, err := server.GetPeers(nodecfg.MacAddress, nodecfg.Network, servercfg.GRPCAddress, nodecfg.IsDualStack == "yes", nodecfg.IsIngressGateway == "yes", nodecfg.IsServer == "yes")
  225. if err != nil {
  226. return err
  227. }
  228. privkey, err := RetrievePrivKey(network)
  229. if err != nil {
  230. return err
  231. }
  232. if peerupdate && !ncutils.IsFreeBSD() && !(ncutils.IsLinux() && !ncutils.IsKernel()) {
  233. var iface string
  234. iface = nodecfg.Interface
  235. if ncutils.IsMac() {
  236. iface, err = local.GetMacIface(nodecfg.Address)
  237. if err != nil {
  238. return err
  239. }
  240. }
  241. err = SetPeers(iface, nodecfg.PersistentKeepalive, peers)
  242. } else if peerupdate {
  243. err = InitWireguard(&nodecfg, privkey, peers, hasGateway, gateways, true)
  244. } else {
  245. err = InitWireguard(&nodecfg, privkey, peers, hasGateway, gateways, false)
  246. }
  247. return err
  248. }
  249. // RemoveConf - removes a configuration for a given WireGuard interface
  250. func RemoveConf(iface string, printlog bool) error {
  251. os := runtime.GOOS
  252. var err error
  253. switch os {
  254. case "windows":
  255. err = RemoveWindowsConf(iface, printlog)
  256. default:
  257. confPath := ncutils.GetNetclientPathSpecific() + iface + ".conf"
  258. err = RemoveWGQuickConf(confPath, printlog)
  259. }
  260. return err
  261. }
  262. // ApplyConf - applys a conf on disk to WireGuard interface
  263. func ApplyConf(confPath string) error {
  264. os := runtime.GOOS
  265. var err error
  266. switch os {
  267. case "windows":
  268. _ = ApplyWindowsConf(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. }