mesh.go 25 KB

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