common.go 17 KB

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