common.go 17 KB

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