2
0

common.go 13 KB

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