common.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556
  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(cfg *config.ClientConfig, privateKey string, peers []wgtypes.PeerConfig) error {
  300. func WriteWgConfig(node *models.Node, privateKey string, peers []wgtypes.PeerConfig) error {
  301. options := ini.LoadOptions{
  302. AllowNonUniqueSections: true,
  303. AllowShadows: true,
  304. }
  305. wireguard := ini.Empty(options)
  306. wireguard.Section(section_interface).Key("PrivateKey").SetValue(privateKey)
  307. if node.ListenPort > 0 && node.UDPHolePunch != "yes" {
  308. wireguard.Section(section_interface).Key("ListenPort").SetValue(strconv.Itoa(int(node.ListenPort)))
  309. }
  310. addrString := node.Address
  311. if node.Address6 != "" {
  312. if addrString != "" {
  313. addrString += ","
  314. }
  315. addrString += node.Address6
  316. }
  317. wireguard.Section(section_interface).Key("Address").SetValue(addrString)
  318. // need to figure out DNS
  319. //if node.DNSOn == "yes" {
  320. // wireguard.Section(section_interface).Key("DNS").SetValue(cfg.Server.CoreDNSAddr)
  321. //}
  322. if node.PostUp != "" {
  323. wireguard.Section(section_interface).Key("PostUp").SetValue(node.PostUp)
  324. }
  325. if node.PostDown != "" {
  326. wireguard.Section(section_interface).Key("PostDown").SetValue(node.PostDown)
  327. }
  328. if node.MTU != 0 {
  329. wireguard.Section(section_interface).Key("MTU").SetValue(strconv.FormatInt(int64(node.MTU), 10))
  330. }
  331. for i, peer := range peers {
  332. wireguard.SectionWithIndex(section_peers, i).Key("PublicKey").SetValue(peer.PublicKey.String())
  333. if peer.PresharedKey != nil {
  334. wireguard.SectionWithIndex(section_peers, i).Key("PreSharedKey").SetValue(peer.PresharedKey.String())
  335. }
  336. if peer.AllowedIPs != nil {
  337. var allowedIPs string
  338. for i, ip := range peer.AllowedIPs {
  339. if i == 0 {
  340. allowedIPs = ip.String()
  341. } else {
  342. allowedIPs = allowedIPs + ", " + ip.String()
  343. }
  344. }
  345. wireguard.SectionWithIndex(section_peers, i).Key("AllowedIps").SetValue(allowedIPs)
  346. }
  347. if peer.Endpoint != nil {
  348. wireguard.SectionWithIndex(section_peers, i).Key("Endpoint").SetValue(peer.Endpoint.String())
  349. }
  350. if peer.PersistentKeepaliveInterval != nil && peer.PersistentKeepaliveInterval.Seconds() > 0 {
  351. wireguard.SectionWithIndex(section_peers, i).Key("PersistentKeepalive").SetValue(strconv.FormatInt((int64)(peer.PersistentKeepaliveInterval.Seconds()), 10))
  352. }
  353. }
  354. if err := wireguard.SaveTo(ncutils.GetNetclientPathSpecific() + node.Interface + ".conf"); err != nil {
  355. return err
  356. }
  357. return nil
  358. }
  359. // UpdateWgPeers - updates the peers of a network
  360. func UpdateWgPeers(file string, peers []wgtypes.PeerConfig) error {
  361. options := ini.LoadOptions{
  362. AllowNonUniqueSections: true,
  363. AllowShadows: true,
  364. }
  365. wireguard, err := ini.LoadSources(options, file)
  366. if err != nil {
  367. return 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. }
  387. if peer.Endpoint != nil {
  388. wireguard.SectionWithIndex(section_peers, i).Key("Endpoint").SetValue(peer.Endpoint.String())
  389. }
  390. if peer.PersistentKeepaliveInterval != nil && peer.PersistentKeepaliveInterval.Seconds() > 0 {
  391. wireguard.SectionWithIndex(section_peers, i).Key("PersistentKeepalive").SetValue(strconv.FormatInt((int64)(peer.PersistentKeepaliveInterval.Seconds()), 10))
  392. }
  393. }
  394. if err := wireguard.SaveTo(file); err != nil {
  395. return err
  396. }
  397. return nil
  398. }
  399. // UpdateWgInterface - updates the interface section of a wireguard config file
  400. func UpdateWgInterface(file, privateKey, nameserver string, node models.Node) error {
  401. options := ini.LoadOptions{
  402. AllowNonUniqueSections: true,
  403. AllowShadows: true,
  404. }
  405. wireguard, err := ini.LoadSources(options, file)
  406. if err != nil {
  407. return err
  408. }
  409. if node.UDPHolePunch == "yes" {
  410. node.ListenPort = 0
  411. }
  412. wireguard.Section(section_interface).Key("PrivateKey").SetValue(privateKey)
  413. wireguard.Section(section_interface).Key("ListenPort").SetValue(strconv.Itoa(int(node.ListenPort)))
  414. addrString := node.Address
  415. if node.Address6 != "" {
  416. if addrString != "" {
  417. addrString += ","
  418. }
  419. addrString += node.Address6
  420. }
  421. wireguard.Section(section_interface).Key("Address").SetValue(addrString)
  422. //if node.DNSOn == "yes" {
  423. // wireguard.Section(section_interface).Key("DNS").SetValue(nameserver)
  424. //}
  425. if node.PostUp != "" {
  426. wireguard.Section(section_interface).Key("PostUp").SetValue(node.PostUp)
  427. }
  428. if node.PostDown != "" {
  429. wireguard.Section(section_interface).Key("PostDown").SetValue(node.PostDown)
  430. }
  431. if node.MTU != 0 {
  432. wireguard.Section(section_interface).Key("MTU").SetValue(strconv.FormatInt(int64(node.MTU), 10))
  433. }
  434. if err := wireguard.SaveTo(file); err != nil {
  435. return err
  436. }
  437. return nil
  438. }
  439. // UpdatePrivateKey - updates the private key of a wireguard config file
  440. func UpdatePrivateKey(file, privateKey string) error {
  441. options := ini.LoadOptions{
  442. AllowNonUniqueSections: true,
  443. AllowShadows: true,
  444. }
  445. wireguard, err := ini.LoadSources(options, file)
  446. if err != nil {
  447. return err
  448. }
  449. wireguard.Section(section_interface).Key("PrivateKey").SetValue(privateKey)
  450. if err := wireguard.SaveTo(file); err != nil {
  451. return err
  452. }
  453. return nil
  454. }
  455. // UpdateKeepAlive - updates the persistentkeepalive of all peers
  456. func UpdateKeepAlive(file string, keepalive int32) error {
  457. options := ini.LoadOptions{
  458. AllowNonUniqueSections: true,
  459. AllowShadows: true,
  460. }
  461. wireguard, err := ini.LoadSources(options, file)
  462. if err != nil {
  463. return err
  464. }
  465. peers, err := wireguard.SectionsByName(section_peers)
  466. if err != nil {
  467. return err
  468. }
  469. newvalue := strconv.Itoa(int(keepalive))
  470. for i := range peers {
  471. wireguard.SectionWithIndex(section_peers, i).Key("PersistentKeepALive").SetValue(newvalue)
  472. }
  473. if err := wireguard.SaveTo(file); err != nil {
  474. return err
  475. }
  476. return nil
  477. }
  478. // RemoveConfGraceful - Run remove conf and wait for it to actually be gone before proceeding
  479. func RemoveConfGraceful(ifacename string) {
  480. // ensure you clear any existing interface first
  481. wgclient, err := wgctrl.New()
  482. if err != nil {
  483. logger.Log(0, "could not create wgclient")
  484. return
  485. }
  486. defer wgclient.Close()
  487. d, _ := wgclient.Device(ifacename)
  488. startTime := time.Now()
  489. for d != nil && d.Name == ifacename {
  490. if err = RemoveConf(ifacename, false); err != nil { // remove interface first
  491. if strings.Contains(err.Error(), "does not exist") {
  492. err = nil
  493. break
  494. }
  495. }
  496. time.Sleep(time.Second >> 2)
  497. d, _ = wgclient.Device(ifacename)
  498. if time.Now().After(startTime.Add(time.Second << 4)) {
  499. break
  500. }
  501. }
  502. time.Sleep(time.Second << 1)
  503. }
  504. // GetDevicePeers - gets the current device's peers
  505. func GetDevicePeers(iface string) ([]wgtypes.Peer, error) {
  506. if ncutils.IsFreeBSD() {
  507. if devicePeers, err := ncutils.GetPeers(iface); err != nil {
  508. return nil, err
  509. } else {
  510. return devicePeers, nil
  511. }
  512. } else {
  513. client, err := wgctrl.New()
  514. if err != nil {
  515. logger.Log(0, "failed to start wgctrl")
  516. return nil, err
  517. }
  518. defer client.Close()
  519. device, err := client.Device(iface)
  520. if err != nil {
  521. logger.Log(0, "failed to parse interface", iface)
  522. return nil, err
  523. }
  524. return device.Peers, nil
  525. }
  526. }