mesh.go 22 KB

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