mesh.go 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800
  1. // Copyright 2019 the Kilo authors
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. // +build linux
  15. package mesh
  16. import (
  17. "bytes"
  18. "fmt"
  19. "io/ioutil"
  20. "net"
  21. "os"
  22. "sync"
  23. "time"
  24. "github.com/go-kit/kit/log"
  25. "github.com/go-kit/kit/log/level"
  26. "github.com/prometheus/client_golang/prometheus"
  27. "github.com/vishvananda/netlink"
  28. "github.com/squat/kilo/pkg/encapsulation"
  29. "github.com/squat/kilo/pkg/iproute"
  30. "github.com/squat/kilo/pkg/iptables"
  31. "github.com/squat/kilo/pkg/route"
  32. "github.com/squat/kilo/pkg/wireguard"
  33. )
  34. const (
  35. // kiloPath is the directory where Kilo stores its configuration.
  36. kiloPath = "/var/lib/kilo"
  37. // privateKeyPath is the filepath where the WireGuard private key is stored.
  38. privateKeyPath = kiloPath + "/key"
  39. // confPath is the filepath where the WireGuard configuration is stored.
  40. confPath = kiloPath + "/conf"
  41. )
  42. // Mesh is able to create Kilo network meshes.
  43. type Mesh struct {
  44. Backend
  45. cleanUpIface bool
  46. cni bool
  47. cniPath string
  48. enc encapsulation.Encapsulator
  49. externalIP *net.IPNet
  50. granularity Granularity
  51. hostname string
  52. internalIP *net.IPNet
  53. ipTables *iptables.Controller
  54. kiloIface int
  55. key []byte
  56. local bool
  57. port uint32
  58. priv []byte
  59. privIface int
  60. pub []byte
  61. resyncPeriod time.Duration
  62. stop chan struct{}
  63. subnet *net.IPNet
  64. table *route.Table
  65. wireGuardIP *net.IPNet
  66. // nodes and peers are mutable fields in the struct
  67. // and need to be guarded.
  68. nodes map[string]*Node
  69. peers map[string]*Peer
  70. mu sync.Mutex
  71. errorCounter *prometheus.CounterVec
  72. leaderGuage prometheus.Gauge
  73. nodesGuage prometheus.Gauge
  74. peersGuage prometheus.Gauge
  75. reconcileCounter prometheus.Counter
  76. logger log.Logger
  77. }
  78. // New returns a new Mesh instance.
  79. func New(backend Backend, enc encapsulation.Encapsulator, granularity Granularity, hostname string, port uint32, subnet *net.IPNet, local, cni bool, cniPath, iface string, cleanUpIface bool, createIface bool, resyncPeriod time.Duration, logger log.Logger) (*Mesh, error) {
  80. if err := os.MkdirAll(kiloPath, 0700); err != nil {
  81. return nil, fmt.Errorf("failed to create directory to store configuration: %v", err)
  82. }
  83. private, err := ioutil.ReadFile(privateKeyPath)
  84. private = bytes.Trim(private, "\n")
  85. if err != nil {
  86. level.Warn(logger).Log("msg", "no private key found on disk; generating one now")
  87. if private, err = wireguard.GenKey(); err != nil {
  88. return nil, err
  89. }
  90. }
  91. public, err := wireguard.PubKey(private)
  92. if err != nil {
  93. return nil, err
  94. }
  95. if err := ioutil.WriteFile(privateKeyPath, private, 0600); err != nil {
  96. return nil, fmt.Errorf("failed to write private key to disk: %v", err)
  97. }
  98. cniIndex, err := cniDeviceIndex()
  99. if err != nil {
  100. return nil, fmt.Errorf("failed to query netlink for CNI device: %v", err)
  101. }
  102. var kiloIface int
  103. if createIface {
  104. kiloIface, _, err = wireguard.New(iface)
  105. if err != nil {
  106. return nil, fmt.Errorf("failed to create WireGuard interface: %v", err)
  107. }
  108. } else {
  109. link, err := netlink.LinkByName(iface)
  110. if err != nil {
  111. return nil, fmt.Errorf("failed to get interface index: %v", err)
  112. }
  113. kiloIface = link.Attrs().Index
  114. }
  115. privateIP, publicIP, err := getIP(hostname, kiloIface, enc.Index(), cniIndex)
  116. if err != nil {
  117. return nil, fmt.Errorf("failed to find public IP: %v", err)
  118. }
  119. var privIface int
  120. if privateIP != nil {
  121. ifaces, err := interfacesForIP(privateIP)
  122. if err != nil {
  123. return nil, fmt.Errorf("failed to find interface for private IP: %v", err)
  124. }
  125. privIface = ifaces[0].Index
  126. if enc.Strategy() != encapsulation.Never {
  127. if err := enc.Init(privIface); err != nil {
  128. return nil, fmt.Errorf("failed to initialize encapsulator: %v", err)
  129. }
  130. }
  131. level.Debug(logger).Log("msg", fmt.Sprintf("using %s as the private IP address", privateIP.String()))
  132. } else {
  133. enc = encapsulation.Noop(enc.Strategy())
  134. level.Debug(logger).Log("msg", "running without a private IP address")
  135. }
  136. level.Debug(logger).Log("msg", fmt.Sprintf("using %s as the public IP address", publicIP.String()))
  137. ipTables, err := iptables.New(iptables.WithLogger(log.With(logger, "component", "iptables")), iptables.WithResyncPeriod(resyncPeriod))
  138. if err != nil {
  139. return nil, fmt.Errorf("failed to IP tables controller: %v", err)
  140. }
  141. return &Mesh{
  142. Backend: backend,
  143. cleanUpIface: cleanUpIface,
  144. cni: cni,
  145. cniPath: cniPath,
  146. enc: enc,
  147. externalIP: publicIP,
  148. granularity: granularity,
  149. hostname: hostname,
  150. internalIP: privateIP,
  151. ipTables: ipTables,
  152. kiloIface: kiloIface,
  153. nodes: make(map[string]*Node),
  154. peers: make(map[string]*Peer),
  155. port: port,
  156. priv: private,
  157. privIface: privIface,
  158. pub: public,
  159. resyncPeriod: resyncPeriod,
  160. local: local,
  161. stop: make(chan struct{}),
  162. subnet: subnet,
  163. table: route.NewTable(),
  164. errorCounter: prometheus.NewCounterVec(prometheus.CounterOpts{
  165. Name: "kilo_errors_total",
  166. Help: "Number of errors that occurred while administering the mesh.",
  167. }, []string{"event"}),
  168. leaderGuage: prometheus.NewGauge(prometheus.GaugeOpts{
  169. Name: "kilo_leader",
  170. Help: "Leadership status of the node.",
  171. }),
  172. nodesGuage: prometheus.NewGauge(prometheus.GaugeOpts{
  173. Name: "kilo_nodes",
  174. Help: "Number of nodes in the mesh.",
  175. }),
  176. peersGuage: prometheus.NewGauge(prometheus.GaugeOpts{
  177. Name: "kilo_peers",
  178. Help: "Number of peers in the mesh.",
  179. }),
  180. reconcileCounter: prometheus.NewCounter(prometheus.CounterOpts{
  181. Name: "kilo_reconciles_total",
  182. Help: "Number of reconciliation attempts.",
  183. }),
  184. logger: logger,
  185. }, nil
  186. }
  187. // Run starts the mesh.
  188. func (m *Mesh) Run() error {
  189. if err := m.Nodes().Init(m.stop); err != nil {
  190. return fmt.Errorf("failed to initialize node backend: %v", err)
  191. }
  192. // Try to set the CNI config quickly.
  193. if m.cni {
  194. if n, err := m.Nodes().Get(m.hostname); err == nil {
  195. m.nodes[m.hostname] = n
  196. m.updateCNIConfig()
  197. } else {
  198. level.Warn(m.logger).Log("error", fmt.Errorf("failed to get node %q: %v", m.hostname, err))
  199. }
  200. }
  201. if err := m.Peers().Init(m.stop); err != nil {
  202. return fmt.Errorf("failed to initialize peer backend: %v", err)
  203. }
  204. ipTablesErrors, err := m.ipTables.Run(m.stop)
  205. if err != nil {
  206. return fmt.Errorf("failed to watch for IP tables updates: %v", err)
  207. }
  208. routeErrors, err := m.table.Run(m.stop)
  209. if err != nil {
  210. return fmt.Errorf("failed to watch for route table updates: %v", err)
  211. }
  212. go func() {
  213. for {
  214. var err error
  215. select {
  216. case err = <-ipTablesErrors:
  217. case err = <-routeErrors:
  218. case <-m.stop:
  219. return
  220. }
  221. if err != nil {
  222. level.Error(m.logger).Log("error", err)
  223. m.errorCounter.WithLabelValues("run").Inc()
  224. }
  225. }
  226. }()
  227. defer m.cleanUp()
  228. resync := time.NewTimer(m.resyncPeriod)
  229. checkIn := time.NewTimer(checkInPeriod)
  230. nw := m.Nodes().Watch()
  231. pw := m.Peers().Watch()
  232. var ne *NodeEvent
  233. var pe *PeerEvent
  234. for {
  235. select {
  236. case ne = <-nw:
  237. m.syncNodes(ne)
  238. case pe = <-pw:
  239. m.syncPeers(pe)
  240. case <-checkIn.C:
  241. m.checkIn()
  242. checkIn.Reset(checkInPeriod)
  243. case <-resync.C:
  244. if m.cni {
  245. m.updateCNIConfig()
  246. }
  247. m.applyTopology()
  248. resync.Reset(m.resyncPeriod)
  249. case <-m.stop:
  250. return nil
  251. }
  252. }
  253. }
  254. func (m *Mesh) syncNodes(e *NodeEvent) {
  255. logger := log.With(m.logger, "event", e.Type)
  256. level.Debug(logger).Log("msg", "syncing nodes", "event", e.Type)
  257. if isSelf(m.hostname, e.Node) {
  258. level.Debug(logger).Log("msg", "processing local node", "node", e.Node)
  259. m.handleLocal(e.Node)
  260. return
  261. }
  262. var diff bool
  263. m.mu.Lock()
  264. if !e.Node.Ready() {
  265. // Trace non ready nodes with their presence in the mesh.
  266. _, ok := m.nodes[e.Node.Name]
  267. level.Debug(logger).Log("msg", "received non ready node", "node", e.Node, "in-mesh", ok)
  268. }
  269. switch e.Type {
  270. case AddEvent:
  271. fallthrough
  272. case UpdateEvent:
  273. if !nodesAreEqual(m.nodes[e.Node.Name], e.Node) {
  274. diff = true
  275. }
  276. // Even if the nodes are the same,
  277. // overwrite the old node to update the timestamp.
  278. m.nodes[e.Node.Name] = e.Node
  279. case DeleteEvent:
  280. delete(m.nodes, e.Node.Name)
  281. diff = true
  282. }
  283. m.mu.Unlock()
  284. if diff {
  285. level.Info(logger).Log("node", e.Node)
  286. m.applyTopology()
  287. }
  288. }
  289. func (m *Mesh) syncPeers(e *PeerEvent) {
  290. logger := log.With(m.logger, "event", e.Type)
  291. level.Debug(logger).Log("msg", "syncing peers", "event", e.Type)
  292. var diff bool
  293. m.mu.Lock()
  294. // Peers are indexed by public key.
  295. key := string(e.Peer.PublicKey)
  296. if !e.Peer.Ready() {
  297. // Trace non ready peer with their presence in the mesh.
  298. _, ok := m.peers[key]
  299. level.Debug(logger).Log("msg", "received non ready peer", "peer", e.Peer, "in-mesh", ok)
  300. }
  301. switch e.Type {
  302. case AddEvent:
  303. fallthrough
  304. case UpdateEvent:
  305. if e.Old != nil && key != string(e.Old.PublicKey) {
  306. delete(m.peers, string(e.Old.PublicKey))
  307. diff = true
  308. }
  309. if !peersAreEqual(m.peers[key], e.Peer) {
  310. m.peers[key] = e.Peer
  311. diff = true
  312. }
  313. case DeleteEvent:
  314. delete(m.peers, key)
  315. diff = true
  316. }
  317. m.mu.Unlock()
  318. if diff {
  319. level.Info(logger).Log("peer", e.Peer)
  320. m.applyTopology()
  321. }
  322. }
  323. // checkIn will try to update the local node's LastSeen timestamp
  324. // in the backend.
  325. func (m *Mesh) checkIn() {
  326. m.mu.Lock()
  327. defer m.mu.Unlock()
  328. n := m.nodes[m.hostname]
  329. if n == nil {
  330. level.Debug(m.logger).Log("msg", "no local node found in backend")
  331. return
  332. }
  333. oldTime := n.LastSeen
  334. n.LastSeen = time.Now().Unix()
  335. if err := m.Nodes().Set(m.hostname, n); err != nil {
  336. level.Error(m.logger).Log("error", fmt.Sprintf("failed to set local node: %v", err), "node", n)
  337. m.errorCounter.WithLabelValues("checkin").Inc()
  338. // Revert time.
  339. n.LastSeen = oldTime
  340. return
  341. }
  342. level.Debug(m.logger).Log("msg", "successfully checked in local node in backend")
  343. }
  344. func (m *Mesh) handleLocal(n *Node) {
  345. // Allow the IPs to be overridden.
  346. if n.Endpoint == nil || (n.Endpoint.DNS == "" && n.Endpoint.IP == nil) {
  347. n.Endpoint = &wireguard.Endpoint{DNSOrIP: wireguard.DNSOrIP{IP: m.externalIP.IP}, Port: m.port}
  348. }
  349. if n.InternalIP == nil && !n.NoInternalIP {
  350. n.InternalIP = m.internalIP
  351. }
  352. // Compare the given node to the calculated local node.
  353. // Take leader, location, and subnet from the argument, as these
  354. // are not determined by kilo.
  355. local := &Node{
  356. Endpoint: n.Endpoint,
  357. Key: m.pub,
  358. NoInternalIP: n.NoInternalIP,
  359. InternalIP: n.InternalIP,
  360. LastSeen: time.Now().Unix(),
  361. Leader: n.Leader,
  362. Location: n.Location,
  363. Name: m.hostname,
  364. PersistentKeepalive: n.PersistentKeepalive,
  365. Subnet: n.Subnet,
  366. WireGuardIP: m.wireGuardIP,
  367. DiscoveredEndpoints: n.DiscoveredEndpoints,
  368. AllowedLocationIPs: n.AllowedLocationIPs,
  369. }
  370. if !nodesAreEqual(n, local) {
  371. level.Debug(m.logger).Log("msg", "local node differs from backend")
  372. if err := m.Nodes().Set(m.hostname, local); err != nil {
  373. level.Error(m.logger).Log("error", fmt.Sprintf("failed to set local node: %v", err), "node", local)
  374. m.errorCounter.WithLabelValues("local").Inc()
  375. return
  376. }
  377. level.Debug(m.logger).Log("msg", "successfully reconciled local node against backend")
  378. }
  379. m.mu.Lock()
  380. n = m.nodes[m.hostname]
  381. if n == nil {
  382. n = &Node{}
  383. }
  384. m.mu.Unlock()
  385. if !nodesAreEqual(n, local) {
  386. m.mu.Lock()
  387. m.nodes[local.Name] = local
  388. m.mu.Unlock()
  389. m.applyTopology()
  390. }
  391. }
  392. func (m *Mesh) applyTopology() {
  393. m.reconcileCounter.Inc()
  394. m.mu.Lock()
  395. defer m.mu.Unlock()
  396. // If we can't resolve an endpoint, then fail and retry later.
  397. if err := m.resolveEndpoints(); err != nil {
  398. level.Error(m.logger).Log("error", err)
  399. m.errorCounter.WithLabelValues("apply").Inc()
  400. return
  401. }
  402. // Ensure only ready nodes are considered.
  403. nodes := make(map[string]*Node)
  404. var readyNodes float64
  405. for k := range m.nodes {
  406. if !m.nodes[k].Ready() {
  407. continue
  408. }
  409. // Make it point to the node without copy.
  410. nodes[k] = m.nodes[k]
  411. readyNodes++
  412. }
  413. // Ensure only ready nodes are considered.
  414. peers := make(map[string]*Peer)
  415. var readyPeers float64
  416. for k := range m.peers {
  417. if !m.peers[k].Ready() {
  418. continue
  419. }
  420. // Make it point the peer without copy.
  421. peers[k] = m.peers[k]
  422. readyPeers++
  423. }
  424. m.nodesGuage.Set(readyNodes)
  425. m.peersGuage.Set(readyPeers)
  426. // We cannot do anything with the topology until the local node is available.
  427. if nodes[m.hostname] == nil {
  428. return
  429. }
  430. // Find the Kilo interface name.
  431. link, err := linkByIndex(m.kiloIface)
  432. if err != nil {
  433. level.Error(m.logger).Log("error", err)
  434. m.errorCounter.WithLabelValues("apply").Inc()
  435. return
  436. }
  437. // Find the old configuration.
  438. oldConfRaw, err := wireguard.ShowConf(link.Attrs().Name)
  439. if err != nil {
  440. level.Error(m.logger).Log("error", err)
  441. m.errorCounter.WithLabelValues("apply").Inc()
  442. return
  443. }
  444. oldConf := wireguard.Parse(oldConfRaw)
  445. natEndpoints := discoverNATEndpoints(nodes, peers, oldConf, m.logger)
  446. nodes[m.hostname].DiscoveredEndpoints = natEndpoints
  447. t, err := NewTopology(nodes, peers, m.granularity, m.hostname, nodes[m.hostname].Endpoint.Port, m.priv, m.subnet, nodes[m.hostname].PersistentKeepalive, m.logger)
  448. if err != nil {
  449. level.Error(m.logger).Log("error", err)
  450. m.errorCounter.WithLabelValues("apply").Inc()
  451. return
  452. }
  453. // Update the node's WireGuard IP.
  454. if t.leader {
  455. m.wireGuardIP = t.wireGuardCIDR
  456. } else {
  457. m.wireGuardIP = nil
  458. }
  459. conf := t.Conf()
  460. buf, err := conf.Bytes()
  461. if err != nil {
  462. level.Error(m.logger).Log("error", err)
  463. m.errorCounter.WithLabelValues("apply").Inc()
  464. return
  465. }
  466. if err := ioutil.WriteFile(confPath, buf, 0600); err != nil {
  467. level.Error(m.logger).Log("error", err)
  468. m.errorCounter.WithLabelValues("apply").Inc()
  469. return
  470. }
  471. ipRules := t.Rules(m.cni)
  472. // If we are handling local routes, ensure the local
  473. // tunnel has an IP address and IPIP traffic is allowed.
  474. if m.enc.Strategy() != encapsulation.Never && m.local {
  475. var cidrs []*net.IPNet
  476. for _, s := range t.segments {
  477. // If the location prefix is not logicalLocation, but nodeLocation,
  478. // we don't need to set any extra rules for encapsulation anyways
  479. // because traffic will go over WireGuard.
  480. if s.location == logicalLocationPrefix+nodes[m.hostname].Location {
  481. for i := range s.privateIPs {
  482. cidrs = append(cidrs, oneAddressCIDR(s.privateIPs[i]))
  483. }
  484. break
  485. }
  486. }
  487. ipRules = append(ipRules, m.enc.Rules(cidrs)...)
  488. // If we are handling local routes, ensure the local
  489. // tunnel has an IP address.
  490. if err := m.enc.Set(oneAddressCIDR(newAllocator(*nodes[m.hostname].Subnet).next().IP)); err != nil {
  491. level.Error(m.logger).Log("error", err)
  492. m.errorCounter.WithLabelValues("apply").Inc()
  493. return
  494. }
  495. }
  496. if err := m.ipTables.Set(ipRules); err != nil {
  497. level.Error(m.logger).Log("error", err)
  498. m.errorCounter.WithLabelValues("apply").Inc()
  499. return
  500. }
  501. if t.leader {
  502. m.leaderGuage.Set(1)
  503. if err := iproute.SetAddress(m.kiloIface, t.wireGuardCIDR); err != nil {
  504. level.Error(m.logger).Log("error", err)
  505. m.errorCounter.WithLabelValues("apply").Inc()
  506. return
  507. }
  508. // Setting the WireGuard configuration interrupts existing connections
  509. // so only set the configuration if it has changed.
  510. equal := conf.Equal(oldConf)
  511. if !equal {
  512. level.Info(m.logger).Log("msg", "WireGuard configurations are different")
  513. if err := wireguard.SetConf(link.Attrs().Name, confPath); err != nil {
  514. level.Error(m.logger).Log("error", err)
  515. m.errorCounter.WithLabelValues("apply").Inc()
  516. return
  517. }
  518. }
  519. if err := iproute.Set(m.kiloIface, true); err != nil {
  520. level.Error(m.logger).Log("error", err)
  521. m.errorCounter.WithLabelValues("apply").Inc()
  522. return
  523. }
  524. } else {
  525. m.leaderGuage.Set(0)
  526. level.Debug(m.logger).Log("msg", "local node is not the leader")
  527. if err := iproute.Set(m.kiloIface, false); err != nil {
  528. level.Error(m.logger).Log("error", err)
  529. m.errorCounter.WithLabelValues("apply").Inc()
  530. return
  531. }
  532. }
  533. // We need to add routes last since they may depend
  534. // on the WireGuard interface.
  535. routes, rules := t.Routes(link.Attrs().Name, m.kiloIface, m.privIface, m.enc.Index(), m.local, m.enc)
  536. if err := m.table.Set(routes, rules); err != nil {
  537. level.Error(m.logger).Log("error", err)
  538. m.errorCounter.WithLabelValues("apply").Inc()
  539. }
  540. }
  541. // RegisterMetrics registers Prometheus metrics on the given Prometheus
  542. // registerer.
  543. func (m *Mesh) RegisterMetrics(r prometheus.Registerer) {
  544. r.MustRegister(
  545. m.errorCounter,
  546. m.leaderGuage,
  547. m.nodesGuage,
  548. m.peersGuage,
  549. m.reconcileCounter,
  550. )
  551. }
  552. // Stop stops the mesh.
  553. func (m *Mesh) Stop() {
  554. close(m.stop)
  555. }
  556. func (m *Mesh) cleanUp() {
  557. if err := m.ipTables.CleanUp(); err != nil {
  558. level.Error(m.logger).Log("error", fmt.Sprintf("failed to clean up IP tables: %v", err))
  559. m.errorCounter.WithLabelValues("cleanUp").Inc()
  560. }
  561. if err := m.table.CleanUp(); err != nil {
  562. level.Error(m.logger).Log("error", fmt.Sprintf("failed to clean up routes: %v", err))
  563. m.errorCounter.WithLabelValues("cleanUp").Inc()
  564. }
  565. if err := os.Remove(confPath); err != nil {
  566. level.Error(m.logger).Log("error", fmt.Sprintf("failed to delete configuration file: %v", err))
  567. m.errorCounter.WithLabelValues("cleanUp").Inc()
  568. }
  569. if m.cleanUpIface {
  570. if err := iproute.RemoveInterface(m.kiloIface); err != nil {
  571. level.Error(m.logger).Log("error", fmt.Sprintf("failed to remove WireGuard interface: %v", err))
  572. m.errorCounter.WithLabelValues("cleanUp").Inc()
  573. }
  574. }
  575. if err := m.Nodes().CleanUp(m.hostname); err != nil {
  576. level.Error(m.logger).Log("error", fmt.Sprintf("failed to clean up node backend: %v", err))
  577. m.errorCounter.WithLabelValues("cleanUp").Inc()
  578. }
  579. if err := m.Peers().CleanUp(m.hostname); err != nil {
  580. level.Error(m.logger).Log("error", fmt.Sprintf("failed to clean up peer backend: %v", err))
  581. m.errorCounter.WithLabelValues("cleanUp").Inc()
  582. }
  583. if err := m.enc.CleanUp(); err != nil {
  584. level.Error(m.logger).Log("error", fmt.Sprintf("failed to clean up encapsulator: %v", err))
  585. m.errorCounter.WithLabelValues("cleanUp").Inc()
  586. }
  587. }
  588. func (m *Mesh) resolveEndpoints() error {
  589. for k := range m.nodes {
  590. // Skip unready nodes, since they will not be used
  591. // in the topology anyways.
  592. if !m.nodes[k].Ready() {
  593. continue
  594. }
  595. // If the node is ready, then the endpoint is not nil
  596. // but it may not have a DNS name.
  597. if m.nodes[k].Endpoint.DNS == "" {
  598. continue
  599. }
  600. if err := resolveEndpoint(m.nodes[k].Endpoint); err != nil {
  601. return err
  602. }
  603. }
  604. for k := range m.peers {
  605. // Skip unready peers, since they will not be used
  606. // in the topology anyways.
  607. if !m.peers[k].Ready() {
  608. continue
  609. }
  610. // Peers may have nil endpoints.
  611. if m.peers[k].Endpoint == nil || m.peers[k].Endpoint.DNS == "" {
  612. continue
  613. }
  614. if err := resolveEndpoint(m.peers[k].Endpoint); err != nil {
  615. return err
  616. }
  617. }
  618. return nil
  619. }
  620. func resolveEndpoint(endpoint *wireguard.Endpoint) error {
  621. ips, err := net.LookupIP(endpoint.DNS)
  622. if err != nil {
  623. return fmt.Errorf("failed to look up DNS name %q: %v", endpoint.DNS, err)
  624. }
  625. nets := make([]*net.IPNet, len(ips), len(ips))
  626. for i := range ips {
  627. nets[i] = oneAddressCIDR(ips[i])
  628. }
  629. sortIPs(nets)
  630. if len(nets) == 0 {
  631. return fmt.Errorf("did not find any addresses for DNS name %q", endpoint.DNS)
  632. }
  633. endpoint.IP = nets[0].IP
  634. return nil
  635. }
  636. func isSelf(hostname string, node *Node) bool {
  637. return node != nil && node.Name == hostname
  638. }
  639. func nodesAreEqual(a, b *Node) bool {
  640. if (a != nil) != (b != nil) {
  641. return false
  642. }
  643. if a == b {
  644. return true
  645. }
  646. // Check the DNS name first since this package
  647. // is doing the DNS resolution.
  648. if !a.Endpoint.Equal(b.Endpoint, true) {
  649. return false
  650. }
  651. // Ignore LastSeen when comparing equality we want to check if the nodes are
  652. // equivalent. However, we do want to check if LastSeen has transitioned
  653. // between valid and invalid.
  654. return string(a.Key) == string(b.Key) && ipNetsEqual(a.WireGuardIP, b.WireGuardIP) && ipNetsEqual(a.InternalIP, b.InternalIP) && a.Leader == b.Leader && a.Location == b.Location && a.Name == b.Name && subnetsEqual(a.Subnet, b.Subnet) && a.Ready() == b.Ready() && a.PersistentKeepalive == b.PersistentKeepalive && discoveredEndpointsAreEqual(a.DiscoveredEndpoints, b.DiscoveredEndpoints) && ipNetSlicesEqual(a.AllowedLocationIPs, b.AllowedLocationIPs)
  655. }
  656. func peersAreEqual(a, b *Peer) bool {
  657. if !(a != nil) == (b != nil) {
  658. return false
  659. }
  660. if a == b {
  661. return true
  662. }
  663. // Check the DNS name first since this package
  664. // is doing the DNS resolution.
  665. if !a.Endpoint.Equal(b.Endpoint, true) {
  666. return false
  667. }
  668. if len(a.AllowedIPs) != len(b.AllowedIPs) {
  669. return false
  670. }
  671. for i := range a.AllowedIPs {
  672. if !ipNetsEqual(a.AllowedIPs[i], b.AllowedIPs[i]) {
  673. return false
  674. }
  675. }
  676. return string(a.PublicKey) == string(b.PublicKey) && string(a.PresharedKey) == string(b.PresharedKey) && a.PersistentKeepalive == b.PersistentKeepalive
  677. }
  678. func ipNetsEqual(a, b *net.IPNet) bool {
  679. if a == nil && b == nil {
  680. return true
  681. }
  682. if (a != nil) != (b != nil) {
  683. return false
  684. }
  685. if a.Mask.String() != b.Mask.String() {
  686. return false
  687. }
  688. return a.IP.Equal(b.IP)
  689. }
  690. func ipNetSlicesEqual(a, b []*net.IPNet) bool {
  691. if len(a) != len(b) {
  692. return false
  693. }
  694. for i := range a {
  695. if !ipNetsEqual(a[i], b[i]) {
  696. return false
  697. }
  698. }
  699. return true
  700. }
  701. func subnetsEqual(a, b *net.IPNet) bool {
  702. if a == nil && b == nil {
  703. return true
  704. }
  705. if (a != nil) != (b != nil) {
  706. return false
  707. }
  708. if a.Mask.String() != b.Mask.String() {
  709. return false
  710. }
  711. if !a.Contains(b.IP) {
  712. return false
  713. }
  714. if !b.Contains(a.IP) {
  715. return false
  716. }
  717. return true
  718. }
  719. func discoveredEndpointsAreEqual(a, b map[string]*wireguard.Endpoint) bool {
  720. if a == nil && b == nil {
  721. return true
  722. }
  723. if (a != nil) != (b != nil) {
  724. return false
  725. }
  726. if len(a) != len(b) {
  727. return false
  728. }
  729. for k := range a {
  730. if !a[k].Equal(b[k], false) {
  731. return false
  732. }
  733. }
  734. return true
  735. }
  736. func linkByIndex(index int) (netlink.Link, error) {
  737. link, err := netlink.LinkByIndex(index)
  738. if err != nil {
  739. return nil, fmt.Errorf("failed to get interface: %v", err)
  740. }
  741. return link, nil
  742. }
  743. // discoverNATEndpoints uses the node's WireGuard configuration to returns a list of the most recently discovered endpoints for all nodes and peers behind NAT so that they can roam.
  744. func discoverNATEndpoints(nodes map[string]*Node, peers map[string]*Peer, conf *wireguard.Conf, logger log.Logger) map[string]*wireguard.Endpoint {
  745. natEndpoints := make(map[string]*wireguard.Endpoint)
  746. keys := make(map[string]*wireguard.Peer)
  747. for i := range conf.Peers {
  748. keys[string(conf.Peers[i].PublicKey)] = conf.Peers[i]
  749. }
  750. for _, n := range nodes {
  751. if peer, ok := keys[string(n.Key)]; ok && n.PersistentKeepalive > 0 {
  752. level.Debug(logger).Log("msg", "WireGuard Update NAT Endpoint", "node", n.Name, "endpoint", peer.Endpoint, "former-endpoint", n.Endpoint, "same", n.Endpoint.Equal(peer.Endpoint, false))
  753. // Should check location leader but only available in topology ... or have topology handle that list
  754. // Better check wg latest-handshake
  755. if !n.Endpoint.Equal(peer.Endpoint, false) {
  756. natEndpoints[string(n.Key)] = peer.Endpoint
  757. }
  758. }
  759. }
  760. for _, p := range peers {
  761. if peer, ok := keys[string(p.PublicKey)]; ok && p.PersistentKeepalive > 0 {
  762. if !p.Endpoint.Equal(peer.Endpoint, false) {
  763. natEndpoints[string(p.PublicKey)] = peer.Endpoint
  764. }
  765. }
  766. }
  767. level.Debug(logger).Log("msg", "Discovered WireGuard NAT Endpoints", "DiscoveredEndpoints", natEndpoints)
  768. return natEndpoints
  769. }