common.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573
  1. package wireguard
  2. import (
  3. "fmt"
  4. "log"
  5. "net"
  6. "runtime"
  7. "strconv"
  8. "strings"
  9. "time"
  10. "github.com/gravitl/netmaker/logger"
  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. "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, node *models.Node, peers []wgtypes.PeerConfig) error {
  25. var devicePeers []wgtypes.Peer
  26. var keepalive = node.PersistentKeepalive
  27. var oldPeerAllowedIps = make(map[string]bool, len(peers))
  28. var err error
  29. devicePeers, err = GetDevicePeers(iface)
  30. if err != nil {
  31. return err
  32. }
  33. if len(devicePeers) > 1 && len(peers) == 0 {
  34. logger.Log(1, "no peers pulled")
  35. return err
  36. }
  37. for _, peer := range peers {
  38. // make sure peer has AllowedIP's before comparison
  39. hasPeerIP := len(peer.AllowedIPs) > 0
  40. for _, currentPeer := range devicePeers {
  41. // make sure currenPeer has AllowedIP's before comparison
  42. hascurrentPeerIP := len(currentPeer.AllowedIPs) > 0
  43. if hasPeerIP && hascurrentPeerIP &&
  44. currentPeer.AllowedIPs[0].String() == peer.AllowedIPs[0].String() &&
  45. currentPeer.PublicKey.String() != peer.PublicKey.String() {
  46. _, err := ncutils.RunCmd("wg set "+iface+" peer "+currentPeer.PublicKey.String()+" remove", true)
  47. if err != nil {
  48. log.Println("error removing peer", peer.Endpoint.String())
  49. }
  50. }
  51. }
  52. udpendpoint := peer.Endpoint.String()
  53. var allowedips string
  54. var iparr []string
  55. for _, ipaddr := range peer.AllowedIPs {
  56. if hasPeerIP {
  57. iparr = append(iparr, ipaddr.String())
  58. }
  59. }
  60. if len(iparr) > 0 {
  61. allowedips = strings.Join(iparr, ",")
  62. }
  63. keepAliveString := strconv.Itoa(int(keepalive))
  64. if keepAliveString == "0" {
  65. keepAliveString = "15"
  66. }
  67. if node.IsServer == "yes" || peer.Endpoint == nil {
  68. _, err = ncutils.RunCmd("wg set "+iface+" peer "+peer.PublicKey.String()+
  69. " persistent-keepalive "+keepAliveString+
  70. " allowed-ips "+allowedips, true)
  71. } else {
  72. _, err = ncutils.RunCmd("wg set "+iface+" peer "+peer.PublicKey.String()+
  73. " endpoint "+udpendpoint+
  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. if len(devicePeers) > 0 {
  82. for _, currentPeer := range devicePeers {
  83. shouldDelete := true
  84. if len(peers) > 0 {
  85. for _, peer := range peers {
  86. if len(peer.AllowedIPs) > 0 && len(currentPeer.AllowedIPs) > 0 &&
  87. peer.AllowedIPs[0].String() == currentPeer.AllowedIPs[0].String() {
  88. shouldDelete = false
  89. }
  90. // re-check this if logic is not working, added in case of allowedips not working
  91. if peer.PublicKey.String() == currentPeer.PublicKey.String() {
  92. shouldDelete = false
  93. }
  94. }
  95. if shouldDelete {
  96. output, err := ncutils.RunCmd("wg set "+iface+" peer "+currentPeer.PublicKey.String()+" remove", true)
  97. if err != nil {
  98. log.Println(output, "error removing peer", currentPeer.PublicKey.String())
  99. }
  100. }
  101. for _, ip := range currentPeer.AllowedIPs {
  102. oldPeerAllowedIps[ip.String()] = true
  103. }
  104. }
  105. }
  106. }
  107. if ncutils.IsMac() {
  108. err = SetMacPeerRoutes(iface)
  109. return err
  110. } else if ncutils.IsLinux() {
  111. if len(peers) > 0 {
  112. local.SetPeerRoutes(iface, oldPeerAllowedIps, peers)
  113. }
  114. }
  115. return nil
  116. }
  117. // Initializes a WireGuard interface
  118. func InitWireguard(node *models.Node, privkey string, peers []wgtypes.PeerConfig, syncconf bool) error {
  119. key, err := wgtypes.ParseKey(privkey)
  120. if err != nil {
  121. return err
  122. }
  123. wgclient, err := wgctrl.New()
  124. if err != nil {
  125. return err
  126. }
  127. defer wgclient.Close()
  128. cfg, err := config.ReadConfig(node.Network)
  129. if err != nil {
  130. return err
  131. }
  132. //nodecfg := modcfg.Node
  133. var ifacename string
  134. if cfg.Node.Interface != "" {
  135. ifacename = cfg.Node.Interface
  136. } else if node.Interface != "" {
  137. ifacename = node.Interface
  138. } else {
  139. return fmt.Errorf("no interface to configure")
  140. }
  141. if node.PrimaryAddress() == "" {
  142. return fmt.Errorf("no address to configure")
  143. }
  144. logger.Log(1, "turn on UDP hole punching (dynamic port setting)? "+cfg.Node.UDPHolePunch)
  145. if node.UDPHolePunch == "yes" {
  146. node.ListenPort = 0
  147. } else {
  148. //get available port based on current default
  149. node.ListenPort, err = ncutils.GetFreePort(node.ListenPort)
  150. }
  151. if err := WriteWgConfig(&cfg.Node, key.String(), peers); err != nil {
  152. logger.Log(1, "error writing wg conf file: ", err.Error())
  153. return err
  154. }
  155. // spin up userspace / windows interface + apply the conf file
  156. confPath := ncutils.GetNetclientPathSpecific() + ifacename + ".conf"
  157. var deviceiface = ifacename
  158. var mErr error
  159. if ncutils.IsMac() { // if node is Mac (Darwin) get the tunnel name first
  160. deviceiface, mErr = local.GetMacIface(node.PrimaryAddress())
  161. if mErr != nil || deviceiface == "" {
  162. deviceiface = ifacename
  163. }
  164. }
  165. // ensure you clear any existing interface first
  166. RemoveConfGraceful(deviceiface)
  167. ApplyConf(node, ifacename, confPath) // Apply initially
  168. logger.Log(1, "waiting for interface...") // ensure interface is created
  169. output, _ := ncutils.RunCmd("wg", false)
  170. starttime := time.Now()
  171. ifaceReady := strings.Contains(output, deviceiface)
  172. for !ifaceReady && !(time.Now().After(starttime.Add(time.Second << 4))) {
  173. if ncutils.IsMac() { // if node is Mac (Darwin) get the tunnel name first
  174. deviceiface, mErr = local.GetMacIface(node.PrimaryAddress())
  175. if mErr != nil || deviceiface == "" {
  176. deviceiface = ifacename
  177. }
  178. }
  179. output, _ = ncutils.RunCmd("wg", false)
  180. err = ApplyConf(node, node.Interface, confPath)
  181. time.Sleep(time.Second)
  182. ifaceReady = strings.Contains(output, deviceiface)
  183. }
  184. //wgclient does not work well on freebsd
  185. if node.OS == "freebsd" {
  186. if !ifaceReady {
  187. return fmt.Errorf("could not reliably create interface, please check wg installation and retry")
  188. }
  189. } else {
  190. _, devErr := wgclient.Device(deviceiface)
  191. if !ifaceReady || devErr != nil {
  192. fmt.Printf("%v\n", devErr)
  193. return fmt.Errorf("could not reliably create interface, please check wg installation and retry")
  194. }
  195. }
  196. logger.Log(1, "interface ready - netclient.. ENGAGE")
  197. if syncconf { // should never be called really.
  198. fmt.Println("why here")
  199. err = SyncWGQuickConf(ifacename, confPath)
  200. }
  201. if !ncutils.HasWgQuick() && ncutils.IsLinux() {
  202. err = SetPeers(ifacename, node, peers)
  203. if err != nil {
  204. logger.Log(1, "error setting peers: ", err.Error())
  205. }
  206. time.Sleep(time.Second)
  207. }
  208. //ipv4
  209. if node.Address != "" {
  210. _, cidr, cidrErr := net.ParseCIDR(cfg.NetworkSettings.AddressRange)
  211. if cidrErr == nil {
  212. local.SetCIDRRoute(ifacename, node.Address, cidr)
  213. } else {
  214. logger.Log(1, "could not set cidr route properly: ", cidrErr.Error())
  215. }
  216. local.SetCurrentPeerRoutes(ifacename, node.Address, peers)
  217. }
  218. if node.Address6 != "" {
  219. //ipv6
  220. _, cidr, cidrErr := net.ParseCIDR(cfg.NetworkSettings.AddressRange6)
  221. if cidrErr == nil {
  222. local.SetCIDRRoute(ifacename, node.Address6, cidr)
  223. } else {
  224. logger.Log(1, "could not set cidr route properly: ", cidrErr.Error())
  225. }
  226. local.SetCurrentPeerRoutes(ifacename, node.Address6, peers)
  227. }
  228. return err
  229. }
  230. // SetWGConfig - sets the WireGuard Config of a given network and checks if it needs a peer update
  231. func SetWGConfig(network string, peerupdate bool, peers []wgtypes.PeerConfig) error {
  232. cfg, err := config.ReadConfig(network)
  233. if err != nil {
  234. return err
  235. }
  236. nodecfg := cfg.Node
  237. privkey, err := RetrievePrivKey(network)
  238. if err != nil {
  239. return err
  240. }
  241. if peerupdate && !ncutils.IsFreeBSD() && !(ncutils.IsLinux() && !ncutils.IsKernel()) {
  242. var iface string
  243. iface = nodecfg.Interface
  244. if ncutils.IsMac() {
  245. iface, err = local.GetMacIface(nodecfg.PrimaryAddress())
  246. if err != nil {
  247. return err
  248. }
  249. }
  250. err = SetPeers(iface, &nodecfg, peers)
  251. } else if peerupdate {
  252. err = InitWireguard(&nodecfg, privkey, peers, true)
  253. } else {
  254. err = InitWireguard(&nodecfg, privkey, peers, false)
  255. }
  256. return err
  257. }
  258. // RemoveConf - removes a configuration for a given WireGuard interface
  259. func RemoveConf(iface string, printlog bool) error {
  260. os := runtime.GOOS
  261. if ncutils.IsLinux() && !ncutils.HasWgQuick() {
  262. os = "nowgquick"
  263. }
  264. var err error
  265. switch os {
  266. case "nowgquick":
  267. err = RemoveWithoutWGQuick(iface)
  268. case "windows":
  269. err = RemoveWindowsConf(iface, printlog)
  270. case "darwin":
  271. err = RemoveConfMac(iface)
  272. default:
  273. confPath := ncutils.GetNetclientPathSpecific() + iface + ".conf"
  274. err = RemoveWGQuickConf(confPath, printlog)
  275. }
  276. return err
  277. }
  278. // ApplyConf - applys a conf on disk to WireGuard interface
  279. func ApplyConf(node *models.Node, ifacename string, confPath string) error {
  280. os := runtime.GOOS
  281. if ncutils.IsLinux() && !ncutils.HasWgQuick() {
  282. os = "nowgquick"
  283. }
  284. var err error
  285. switch os {
  286. case "windows":
  287. ApplyWindowsConf(confPath)
  288. case "darwin":
  289. ApplyMacOSConf(node, ifacename, confPath)
  290. case "nowgquick":
  291. ApplyWithoutWGQuick(node, ifacename, confPath)
  292. default:
  293. ApplyWGQuickConf(confPath, ifacename)
  294. }
  295. var nodeCfg config.ClientConfig
  296. nodeCfg.Network = node.Network
  297. nodeCfg.ReadConfig()
  298. if nodeCfg.NetworkSettings.AddressRange != "" {
  299. ip, cidr, err := net.ParseCIDR(nodeCfg.NetworkSettings.AddressRange)
  300. if err == nil {
  301. local.SetCIDRRoute(node.Interface, ip.String(), cidr)
  302. }
  303. }
  304. if nodeCfg.NetworkSettings.AddressRange6 != "" {
  305. ip, cidr, err := net.ParseCIDR(nodeCfg.NetworkSettings.AddressRange6)
  306. if err == nil {
  307. local.SetCIDRRoute(node.Interface, ip.String(), cidr)
  308. }
  309. }
  310. return err
  311. }
  312. // WriteWgConfig - creates a wireguard config file
  313. //func WriteWgConfig(cfg *config.ClientConfig, privateKey string, peers []wgtypes.PeerConfig) error {
  314. func WriteWgConfig(node *models.Node, privateKey string, peers []wgtypes.PeerConfig) error {
  315. options := ini.LoadOptions{
  316. AllowNonUniqueSections: true,
  317. AllowShadows: true,
  318. }
  319. wireguard := ini.Empty(options)
  320. wireguard.Section(section_interface).Key("PrivateKey").SetValue(privateKey)
  321. if node.ListenPort > 0 && node.UDPHolePunch != "yes" {
  322. wireguard.Section(section_interface).Key("ListenPort").SetValue(strconv.Itoa(int(node.ListenPort)))
  323. }
  324. addrString := node.Address
  325. if node.Address6 != "" {
  326. if addrString != "" {
  327. addrString += ","
  328. }
  329. addrString += node.Address6
  330. }
  331. wireguard.Section(section_interface).Key("Address").SetValue(addrString)
  332. // need to figure out DNS
  333. //if node.DNSOn == "yes" {
  334. // wireguard.Section(section_interface).Key("DNS").SetValue(cfg.Server.CoreDNSAddr)
  335. //}
  336. if node.PostUp != "" {
  337. wireguard.Section(section_interface).Key("PostUp").SetValue(node.PostUp)
  338. }
  339. if node.PostDown != "" {
  340. wireguard.Section(section_interface).Key("PostDown").SetValue(node.PostDown)
  341. }
  342. if node.MTU != 0 {
  343. wireguard.Section(section_interface).Key("MTU").SetValue(strconv.FormatInt(int64(node.MTU), 10))
  344. }
  345. for i, peer := range peers {
  346. wireguard.SectionWithIndex(section_peers, i).Key("PublicKey").SetValue(peer.PublicKey.String())
  347. if peer.PresharedKey != nil {
  348. wireguard.SectionWithIndex(section_peers, i).Key("PreSharedKey").SetValue(peer.PresharedKey.String())
  349. }
  350. if peer.AllowedIPs != nil {
  351. var allowedIPs string
  352. for i, ip := range peer.AllowedIPs {
  353. if i == 0 {
  354. allowedIPs = ip.String()
  355. } else {
  356. allowedIPs = allowedIPs + ", " + ip.String()
  357. }
  358. }
  359. wireguard.SectionWithIndex(section_peers, i).Key("AllowedIps").SetValue(allowedIPs)
  360. }
  361. if peer.Endpoint != nil {
  362. wireguard.SectionWithIndex(section_peers, i).Key("Endpoint").SetValue(peer.Endpoint.String())
  363. }
  364. if peer.PersistentKeepaliveInterval != nil && peer.PersistentKeepaliveInterval.Seconds() > 0 {
  365. wireguard.SectionWithIndex(section_peers, i).Key("PersistentKeepalive").SetValue(strconv.FormatInt((int64)(peer.PersistentKeepaliveInterval.Seconds()), 10))
  366. }
  367. }
  368. if err := wireguard.SaveTo(ncutils.GetNetclientPathSpecific() + node.Interface + ".conf"); err != nil {
  369. return err
  370. }
  371. return nil
  372. }
  373. // UpdateWgPeers - updates the peers of a network
  374. func UpdateWgPeers(file string, peers []wgtypes.PeerConfig) error {
  375. options := ini.LoadOptions{
  376. AllowNonUniqueSections: true,
  377. AllowShadows: true,
  378. }
  379. wireguard, err := ini.LoadSources(options, file)
  380. if err != nil {
  381. return err
  382. }
  383. //delete the peers sections as they are going to be replaced
  384. wireguard.DeleteSection(section_peers)
  385. for i, peer := range peers {
  386. wireguard.SectionWithIndex(section_peers, i).Key("PublicKey").SetValue(peer.PublicKey.String())
  387. if peer.PresharedKey != nil {
  388. wireguard.SectionWithIndex(section_peers, i).Key("PreSharedKey").SetValue(peer.PresharedKey.String())
  389. }
  390. if peer.AllowedIPs != nil {
  391. var allowedIPs string
  392. for i, ip := range peer.AllowedIPs {
  393. if i == 0 {
  394. allowedIPs = ip.String()
  395. } else {
  396. allowedIPs = allowedIPs + ", " + ip.String()
  397. }
  398. }
  399. wireguard.SectionWithIndex(section_peers, i).Key("AllowedIps").SetValue(allowedIPs)
  400. }
  401. if peer.Endpoint != nil {
  402. wireguard.SectionWithIndex(section_peers, i).Key("Endpoint").SetValue(peer.Endpoint.String())
  403. }
  404. if peer.PersistentKeepaliveInterval != nil && peer.PersistentKeepaliveInterval.Seconds() > 0 {
  405. wireguard.SectionWithIndex(section_peers, i).Key("PersistentKeepalive").SetValue(strconv.FormatInt((int64)(peer.PersistentKeepaliveInterval.Seconds()), 10))
  406. }
  407. }
  408. if err := wireguard.SaveTo(file); err != nil {
  409. return err
  410. }
  411. return nil
  412. }
  413. // UpdateWgInterface - updates the interface section of a wireguard config file
  414. func UpdateWgInterface(file, privateKey, nameserver string, node models.Node) error {
  415. options := ini.LoadOptions{
  416. AllowNonUniqueSections: true,
  417. AllowShadows: true,
  418. }
  419. wireguard, err := ini.LoadSources(options, file)
  420. if err != nil {
  421. return err
  422. }
  423. if node.UDPHolePunch == "yes" {
  424. node.ListenPort = 0
  425. }
  426. wireguard.Section(section_interface).Key("PrivateKey").SetValue(privateKey)
  427. wireguard.Section(section_interface).Key("ListenPort").SetValue(strconv.Itoa(int(node.ListenPort)))
  428. addrString := node.Address
  429. if node.Address6 != "" {
  430. if addrString != "" {
  431. addrString += ","
  432. }
  433. addrString += node.Address6
  434. }
  435. wireguard.Section(section_interface).Key("Address").SetValue(addrString)
  436. //if node.DNSOn == "yes" {
  437. // wireguard.Section(section_interface).Key("DNS").SetValue(nameserver)
  438. //}
  439. if node.PostUp != "" {
  440. wireguard.Section(section_interface).Key("PostUp").SetValue(node.PostUp)
  441. }
  442. if node.PostDown != "" {
  443. wireguard.Section(section_interface).Key("PostDown").SetValue(node.PostDown)
  444. }
  445. if node.MTU != 0 {
  446. wireguard.Section(section_interface).Key("MTU").SetValue(strconv.FormatInt(int64(node.MTU), 10))
  447. }
  448. if err := wireguard.SaveTo(file); err != nil {
  449. return err
  450. }
  451. return nil
  452. }
  453. // UpdatePrivateKey - updates the private key of a wireguard config file
  454. func UpdatePrivateKey(file, privateKey string) error {
  455. options := ini.LoadOptions{
  456. AllowNonUniqueSections: true,
  457. AllowShadows: true,
  458. }
  459. wireguard, err := ini.LoadSources(options, file)
  460. if err != nil {
  461. return err
  462. }
  463. wireguard.Section(section_interface).Key("PrivateKey").SetValue(privateKey)
  464. if err := wireguard.SaveTo(file); err != nil {
  465. return err
  466. }
  467. return nil
  468. }
  469. // UpdateKeepAlive - updates the persistentkeepalive of all peers
  470. func UpdateKeepAlive(file string, keepalive int32) error {
  471. options := ini.LoadOptions{
  472. AllowNonUniqueSections: true,
  473. AllowShadows: true,
  474. }
  475. wireguard, err := ini.LoadSources(options, file)
  476. if err != nil {
  477. return err
  478. }
  479. peers, err := wireguard.SectionsByName(section_peers)
  480. if err != nil {
  481. return err
  482. }
  483. newvalue := strconv.Itoa(int(keepalive))
  484. for i := range peers {
  485. wireguard.SectionWithIndex(section_peers, i).Key("PersistentKeepALive").SetValue(newvalue)
  486. }
  487. if err := wireguard.SaveTo(file); err != nil {
  488. return err
  489. }
  490. return nil
  491. }
  492. // RemoveConfGraceful - Run remove conf and wait for it to actually be gone before proceeding
  493. func RemoveConfGraceful(ifacename string) {
  494. // ensure you clear any existing interface first
  495. wgclient, err := wgctrl.New()
  496. if err != nil {
  497. logger.Log(0, "could not create wgclient")
  498. return
  499. }
  500. defer wgclient.Close()
  501. d, _ := wgclient.Device(ifacename)
  502. startTime := time.Now()
  503. for d != nil && d.Name == ifacename {
  504. if err = RemoveConf(ifacename, false); err != nil { // remove interface first
  505. if strings.Contains(err.Error(), "does not exist") {
  506. err = nil
  507. break
  508. }
  509. }
  510. time.Sleep(time.Second >> 2)
  511. d, _ = wgclient.Device(ifacename)
  512. if time.Now().After(startTime.Add(time.Second << 4)) {
  513. break
  514. }
  515. }
  516. time.Sleep(time.Second << 1)
  517. }
  518. // GetDevicePeers - gets the current device's peers
  519. func GetDevicePeers(iface string) ([]wgtypes.Peer, error) {
  520. if ncutils.IsFreeBSD() {
  521. if devicePeers, err := ncutils.GetPeers(iface); err != nil {
  522. return nil, err
  523. } else {
  524. return devicePeers, nil
  525. }
  526. } else {
  527. client, err := wgctrl.New()
  528. if err != nil {
  529. logger.Log(0, "failed to start wgctrl")
  530. return nil, err
  531. }
  532. defer client.Close()
  533. device, err := client.Device(iface)
  534. if err != nil {
  535. logger.Log(0, "failed to parse interface")
  536. return nil, err
  537. }
  538. return device.Peers, nil
  539. }
  540. }