common.go 17 KB

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