mesh.go 25 KB

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