common.go 17 KB

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