common.go 17 KB

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