daemon.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410
  1. package functions
  2. import (
  3. "context"
  4. "crypto/rsa"
  5. "encoding/json"
  6. "fmt"
  7. "log"
  8. "os"
  9. "os/signal"
  10. "runtime"
  11. "strings"
  12. "sync"
  13. "syscall"
  14. "time"
  15. mqtt "github.com/eclipse/paho.mqtt.golang"
  16. "github.com/gravitl/netmaker/models"
  17. "github.com/gravitl/netmaker/netclient/auth"
  18. "github.com/gravitl/netmaker/netclient/config"
  19. "github.com/gravitl/netmaker/netclient/local"
  20. "github.com/gravitl/netmaker/netclient/ncutils"
  21. "github.com/gravitl/netmaker/netclient/wireguard"
  22. "golang.zx2c4.com/wireguard/wgctrl/wgtypes"
  23. )
  24. var messageCache = make(map[string]string, 20)
  25. const lastNodeUpdate = "lnu"
  26. const lastPeerUpdate = "lpu"
  27. func insert(network, which, cache string) {
  28. var mu sync.Mutex
  29. mu.Lock()
  30. defer mu.Unlock()
  31. messageCache[fmt.Sprintf("%s%s", network, which)] = cache
  32. }
  33. func read(network, which string) string {
  34. return messageCache[fmt.Sprintf("%s%s", network, which)]
  35. }
  36. // Daemon runs netclient daemon from command line
  37. func Daemon() error {
  38. ctx, cancel := context.WithCancel(context.Background())
  39. networks, err := ncutils.GetSystemNetworks()
  40. if err != nil {
  41. cancel()
  42. return err
  43. }
  44. for _, network := range networks {
  45. go MessageQueue(ctx, network)
  46. }
  47. quit := make(chan os.Signal, 1)
  48. signal.Notify(quit, syscall.SIGTERM, os.Interrupt)
  49. <-quit
  50. cancel()
  51. ncutils.Log("all done")
  52. return nil
  53. }
  54. // SetupMQTT creates a connection to broker and return client
  55. func SetupMQTT(cfg *config.ClientConfig) mqtt.Client {
  56. opts := mqtt.NewClientOptions()
  57. for _, server := range cfg.Node.NetworkSettings.DefaultServerAddrs {
  58. if server.Address != "" && server.IsLeader {
  59. ncutils.Log(fmt.Sprintf("adding server (%s) to listen on network %s \n", server.Address, cfg.Node.Network))
  60. opts.AddBroker(server.Address + ":1883")
  61. break
  62. }
  63. }
  64. opts.SetDefaultPublishHandler(All)
  65. client := mqtt.NewClient(opts)
  66. if token := client.Connect(); token.Wait() && token.Error() != nil {
  67. log.Fatal(token.Error())
  68. }
  69. return client
  70. }
  71. // MessageQueue sets up Message Queue and subsribes/publishes updates to/from server
  72. func MessageQueue(ctx context.Context, network string) {
  73. ncutils.Log("netclient go routine started for " + network)
  74. var cfg config.ClientConfig
  75. cfg.Network = network
  76. cfg.ReadConfig()
  77. ncutils.Log("daemon started for network:" + network)
  78. client := SetupMQTT(&cfg)
  79. if cfg.DebugOn {
  80. if token := client.Subscribe("#", 0, nil); token.Wait() && token.Error() != nil {
  81. log.Fatal(token.Error())
  82. }
  83. ncutils.Log("subscribed to all topics for debugging purposes")
  84. }
  85. if token := client.Subscribe(fmt.Sprintf("update/%s/%s", cfg.Node.Network, cfg.Node.ID), 0, mqtt.MessageHandler(NodeUpdate)); token.Wait() && token.Error() != nil {
  86. log.Fatal(token.Error())
  87. }
  88. if cfg.DebugOn {
  89. ncutils.Log(fmt.Sprintf("subscribed to node updates for node %s update/%s/%s \n", cfg.Node.Name, cfg.Node.Network, cfg.Node.ID))
  90. }
  91. if token := client.Subscribe(fmt.Sprintf("peers/%s/%s", cfg.Node.Network, cfg.Node.ID), 0, mqtt.MessageHandler(UpdatePeers)); token.Wait() && token.Error() != nil {
  92. log.Fatal(token.Error())
  93. }
  94. if cfg.DebugOn {
  95. ncutils.Log(fmt.Sprintf("subscribed to peer updates for node %s peers/%s/%s \n", cfg.Node.Name, cfg.Node.Network, cfg.Node.ID))
  96. }
  97. defer client.Disconnect(250)
  98. go Checkin(ctx, &cfg, network)
  99. <-ctx.Done()
  100. ncutils.Log("shutting down daemon")
  101. }
  102. // All -- mqtt message hander for all ('#') topics
  103. var All mqtt.MessageHandler = func(client mqtt.Client, msg mqtt.Message) {
  104. ncutils.Log("default message handler -- received message but not handling")
  105. ncutils.Log("Topic: " + string(msg.Topic()))
  106. //ncutils.Log("Message: " + string(msg.Payload()))
  107. }
  108. // NodeUpdate -- mqtt message handler for /update/<NodeID> topic
  109. func NodeUpdate(client mqtt.Client, msg mqtt.Message) {
  110. //potentiall blocking i/o so do this in a go routine
  111. go func() {
  112. var newNode models.Node
  113. var cfg config.ClientConfig
  114. var network = parseNetworkFromTopic(msg.Topic())
  115. cfg.Network = network
  116. cfg.ReadConfig()
  117. data, dataErr := decryptMsg(&cfg, msg.Payload())
  118. if dataErr != nil {
  119. return
  120. }
  121. err := json.Unmarshal(data, &newNode)
  122. if err != nil {
  123. ncutils.Log("error unmarshalling node update data" + err.Error())
  124. return
  125. }
  126. ncutils.Log("received message to update node " + newNode.Name)
  127. // see if cache hit, if so skip
  128. var currentMessage = read(newNode.Network, lastNodeUpdate)
  129. if currentMessage == string(data) {
  130. return
  131. }
  132. insert(newNode.Network, lastNodeUpdate, string(data))
  133. //check if interface name has changed if so delete.
  134. if cfg.Node.Interface != newNode.Interface {
  135. if err = wireguard.RemoveConf(cfg.Node.Interface, true); err != nil {
  136. ncutils.PrintLog("could not delete old interface "+cfg.Node.Interface+": "+err.Error(), 1)
  137. }
  138. }
  139. newNode.PullChanges = "no"
  140. //ensure that OS never changes
  141. newNode.OS = runtime.GOOS
  142. cfg.Node = newNode
  143. switch newNode.Action {
  144. case models.NODE_DELETE:
  145. if err := RemoveLocalInstance(&cfg, cfg.Network); err != nil {
  146. ncutils.PrintLog("error deleting local instance: "+err.Error(), 1)
  147. return
  148. }
  149. if token := client.Unsubscribe("update/"+newNode.ID, "update/peers/"+newNode.ID); token.Wait() && token.Error() != nil {
  150. ncutils.PrintLog("error unsubscribing during node deletion", 1)
  151. }
  152. return
  153. case models.NODE_UPDATE_KEY:
  154. if err := UpdateKeys(&cfg, client); err != nil {
  155. ncutils.PrintLog("err updating wireguard keys: "+err.Error(), 1)
  156. }
  157. case models.NODE_NOOP:
  158. default:
  159. }
  160. //Save new config
  161. if err := config.Write(&cfg, cfg.Network); err != nil {
  162. ncutils.PrintLog("error updating node configuration: "+err.Error(), 1)
  163. }
  164. nameserver := cfg.Server.CoreDNSAddr
  165. privateKey, err := wireguard.RetrievePrivKey(newNode.Network)
  166. if err != nil {
  167. ncutils.Log("error reading PrivateKey " + err.Error())
  168. return
  169. }
  170. file := ncutils.GetNetclientPathSpecific() + cfg.Node.Interface + ".conf"
  171. if err := wireguard.UpdateWgInterface(file, privateKey, nameserver, newNode); err != nil {
  172. ncutils.Log("error updating wireguard config " + err.Error())
  173. return
  174. }
  175. ncutils.Log("applyWGQuickConf to " + file)
  176. err = wireguard.ApplyWGQuickConf(file)
  177. if err != nil {
  178. ncutils.Log("error restarting wg after node update " + err.Error())
  179. return
  180. }
  181. //deal with DNS
  182. if newNode.DNSOn == "yes" {
  183. ncutils.Log("setting up DNS")
  184. if err = local.UpdateDNS(cfg.Node.Interface, cfg.Network, cfg.Server.CoreDNSAddr); err != nil {
  185. ncutils.Log("error applying dns" + err.Error())
  186. }
  187. } else {
  188. ncutils.Log("settng DNS off")
  189. _, err := ncutils.RunCmd("/usr/bin/resolvectl revert "+cfg.Node.Interface, true)
  190. if err != nil {
  191. ncutils.Log("error applying dns" + err.Error())
  192. }
  193. }
  194. }()
  195. }
  196. // UpdatePeers -- mqtt message handler for /update/peers/<NodeID> topic
  197. func UpdatePeers(client mqtt.Client, msg mqtt.Message) {
  198. go func() {
  199. var peerUpdate models.PeerUpdate
  200. var network = parseNetworkFromTopic(msg.Topic())
  201. var cfg = config.ClientConfig{}
  202. cfg.Network = network
  203. cfg.ReadConfig()
  204. data, dataErr := decryptMsg(&cfg, msg.Payload())
  205. if dataErr != nil {
  206. return
  207. }
  208. err := json.Unmarshal(data, &peerUpdate)
  209. if err != nil {
  210. ncutils.Log("error unmarshalling peer data")
  211. return
  212. }
  213. // see if cache hit, if so skip
  214. var currentMessage = read(peerUpdate.Network, lastPeerUpdate)
  215. if currentMessage == string(data) {
  216. return
  217. }
  218. insert(peerUpdate.Network, lastPeerUpdate, string(data))
  219. ncutils.Log("update peer handler")
  220. var shouldReSub = shouldResub(cfg.Node.NetworkSettings.DefaultServerAddrs, peerUpdate.ServerAddrs)
  221. if shouldReSub {
  222. Resubscribe(client, &cfg)
  223. cfg.Node.NetworkSettings.DefaultServerAddrs = peerUpdate.ServerAddrs
  224. }
  225. file := ncutils.GetNetclientPathSpecific() + cfg.Node.Interface + ".conf"
  226. err = wireguard.UpdateWgPeers(file, peerUpdate.Peers)
  227. if err != nil {
  228. ncutils.Log("error updating wireguard peers" + err.Error())
  229. return
  230. }
  231. ncutils.Log("applyWGQuickConf to " + file)
  232. err = wireguard.ApplyWGQuickConf(file)
  233. if err != nil {
  234. ncutils.Log("error restarting wg after peer update " + err.Error())
  235. return
  236. }
  237. }()
  238. }
  239. // Resubscribe --- handles resubscribing if needed
  240. func Resubscribe(client mqtt.Client, cfg *config.ClientConfig) error {
  241. if err := config.ModConfig(&cfg.Node); err == nil {
  242. ncutils.Log("resubbing on network " + cfg.Node.Network)
  243. client.Disconnect(250)
  244. client = SetupMQTT(cfg)
  245. if token := client.Subscribe("update/"+cfg.Node.ID, 0, NodeUpdate); token.Wait() && token.Error() != nil {
  246. log.Fatal(token.Error())
  247. }
  248. if cfg.DebugOn {
  249. ncutils.Log("subscribed to node updates for node " + cfg.Node.Name + " update/" + cfg.Node.ID)
  250. }
  251. if token := client.Subscribe("update/peers/"+cfg.Node.ID, 0, UpdatePeers); token.Wait() && token.Error() != nil {
  252. log.Fatal(token.Error())
  253. }
  254. ncutils.Log("finished re subbing")
  255. return nil
  256. } else {
  257. ncutils.Log("could not mod config when re-subbing")
  258. return err
  259. }
  260. }
  261. // UpdateKeys -- updates private key and returns new publickey
  262. func UpdateKeys(cfg *config.ClientConfig, client mqtt.Client) error {
  263. ncutils.Log("received message to update keys")
  264. //potentiall blocking i/o so do this in a go routine
  265. key, err := wgtypes.GeneratePrivateKey()
  266. if err != nil {
  267. ncutils.Log("error generating privatekey " + err.Error())
  268. return err
  269. }
  270. file := ncutils.GetNetclientPathSpecific() + cfg.Node.Interface + ".conf"
  271. if err := wireguard.UpdatePrivateKey(file, key.String()); err != nil {
  272. ncutils.Log("error updating wireguard key " + err.Error())
  273. return err
  274. }
  275. cfg.Node.PublicKey = key.PublicKey().String()
  276. PublishNodeUpdate(cfg)
  277. if err := config.ModConfig(&cfg.Node); err != nil {
  278. ncutils.Log("error updating local config " + err.Error())
  279. }
  280. return nil
  281. }
  282. // Checkin -- go routine that checks for public or local ip changes, publishes changes
  283. // if there are no updates, simply "pings" the server as a checkin
  284. func Checkin(ctx context.Context, cfg *config.ClientConfig, network string) {
  285. for {
  286. select {
  287. case <-ctx.Done():
  288. ncutils.Log("Checkin cancelled")
  289. return
  290. //delay should be configuraable -> use cfg.Node.NetworkSettings.DefaultCheckInInterval ??
  291. case <-time.After(time.Second * 60):
  292. ncutils.Log("Checkin running")
  293. //read latest config
  294. cfg.ReadConfig()
  295. if cfg.Node.Roaming == "yes" && cfg.Node.IsStatic != "yes" {
  296. extIP, err := ncutils.GetPublicIP()
  297. if err != nil {
  298. ncutils.PrintLog("error encountered checking ip addresses: "+err.Error(), 1)
  299. }
  300. if cfg.Node.Endpoint != extIP && extIP != "" {
  301. ncutils.PrintLog("endpoint has changed from "+cfg.Node.Endpoint+" to "+extIP, 1)
  302. cfg.Node.Endpoint = extIP
  303. PublishNodeUpdate(cfg)
  304. }
  305. intIP, err := getPrivateAddr()
  306. if err != nil {
  307. ncutils.PrintLog("error encountered checking ip addresses: "+err.Error(), 1)
  308. }
  309. if cfg.Node.LocalAddress != intIP && intIP != "" {
  310. ncutils.PrintLog("local Address has changed from "+cfg.Node.LocalAddress+" to "+intIP, 1)
  311. cfg.Node.LocalAddress = intIP
  312. PublishNodeUpdate(cfg)
  313. }
  314. } else {
  315. localIP, err := ncutils.GetLocalIP(cfg.Node.LocalRange)
  316. if err != nil {
  317. ncutils.PrintLog("error encountered checking ip addresses: "+err.Error(), 1)
  318. }
  319. if cfg.Node.Endpoint != localIP && localIP != "" {
  320. ncutils.PrintLog("endpoint has changed from "+cfg.Node.Endpoint+" to "+localIP, 1)
  321. cfg.Node.Endpoint = localIP
  322. PublishNodeUpdate(cfg)
  323. }
  324. }
  325. Hello(cfg, network)
  326. ncutils.Log("Checkin complete")
  327. }
  328. }
  329. }
  330. // PublishNodeUpdates -- saves node and pushes changes to broker
  331. func PublishNodeUpdate(cfg *config.ClientConfig) {
  332. if err := config.Write(cfg, cfg.Network); err != nil {
  333. ncutils.Log("error saving configuration" + err.Error())
  334. }
  335. data, err := json.Marshal(cfg.Node)
  336. if err != nil {
  337. ncutils.Log("error marshling node update " + err.Error())
  338. }
  339. if err = publish(cfg, fmt.Sprintf("update/%s", cfg.Node.ID), data); err != nil {
  340. ncutils.Log(fmt.Sprintf("error publishing endpoint update, %v \n", err))
  341. }
  342. }
  343. // Hello -- ping the broker to let server know node is alive and doing fine
  344. func Hello(cfg *config.ClientConfig, network string) {
  345. if err := publish(cfg, fmt.Sprintf("ping/%s", cfg.Node.ID), []byte("hello world!")); err != nil {
  346. ncutils.Log(fmt.Sprintf("error publishing ping, %v \n", err))
  347. }
  348. }
  349. func publish(cfg *config.ClientConfig, dest string, msg []byte) error {
  350. client := SetupMQTT(cfg)
  351. defer client.Disconnect(250)
  352. encrypted := ncutils.BuildMessage(msg, &cfg.Node.TrafficKeys.Server)
  353. if encrypted == "" {
  354. return fmt.Errorf("could not encrypt message")
  355. }
  356. if token := client.Publish(dest, 0, false, encrypted); token.Wait() && token.Error() != nil {
  357. return token.Error()
  358. }
  359. return nil
  360. }
  361. func parseNetworkFromTopic(topic string) string {
  362. return strings.Split(topic, "/")[1]
  363. }
  364. func decryptMsg(cfg *config.ClientConfig, msg []byte) ([]byte, error) {
  365. diskKey, trafficErr := auth.RetrieveTrafficKey(cfg.Node.Network)
  366. if trafficErr != nil {
  367. return nil, trafficErr
  368. }
  369. var trafficKey rsa.PrivateKey
  370. if err := json.Unmarshal([]byte(diskKey), &trafficKey); err != nil {
  371. return nil, err
  372. }
  373. return ncutils.DestructMessage(string(msg), &trafficKey), nil
  374. }
  375. func shouldResub(currentServers, newServers []models.ServerAddr) bool {
  376. if len(currentServers) != len(newServers) {
  377. return true
  378. }
  379. for _, srv := range currentServers {
  380. if !ncutils.ServerAddrSliceContains(newServers, srv) {
  381. return true
  382. }
  383. }
  384. return false
  385. }