mesh.go 24 KB

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