hostmap.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765
  1. package nebula
  2. import (
  3. "errors"
  4. "net"
  5. "sync"
  6. "sync/atomic"
  7. "time"
  8. "github.com/rcrowley/go-metrics"
  9. "github.com/sirupsen/logrus"
  10. "github.com/slackhq/nebula/cert"
  11. "github.com/slackhq/nebula/cidr"
  12. "github.com/slackhq/nebula/header"
  13. "github.com/slackhq/nebula/iputil"
  14. "github.com/slackhq/nebula/udp"
  15. )
  16. // const ProbeLen = 100
  17. const PromoteEvery = 1000
  18. const ReQueryEvery = 5000
  19. const MaxRemotes = 10
  20. // MaxHostInfosPerVpnIp is the max number of hostinfos we will track for a given vpn ip
  21. // 5 allows for an initial handshake and each host pair re-handshaking twice
  22. const MaxHostInfosPerVpnIp = 5
  23. // How long we should prevent roaming back to the previous IP.
  24. // This helps prevent flapping due to packets already in flight
  25. const RoamingSuppressSeconds = 2
  26. const (
  27. Requested = iota
  28. PeerRequested
  29. Established
  30. )
  31. const (
  32. Unknowntype = iota
  33. ForwardingType
  34. TerminalType
  35. )
  36. type Relay struct {
  37. Type int
  38. State int
  39. LocalIndex uint32
  40. RemoteIndex uint32
  41. PeerIp iputil.VpnIp
  42. }
  43. type HostMap struct {
  44. sync.RWMutex //Because we concurrently read and write to our maps
  45. Indexes map[uint32]*HostInfo
  46. Relays map[uint32]*HostInfo // Maps a Relay IDX to a Relay HostInfo object
  47. RemoteIndexes map[uint32]*HostInfo
  48. Hosts map[iputil.VpnIp]*HostInfo
  49. preferredRanges []*net.IPNet
  50. vpnCIDR *net.IPNet
  51. metricsEnabled bool
  52. l *logrus.Logger
  53. }
  54. // For synchronization, treat the pointed-to Relay struct as immutable. To edit the Relay
  55. // struct, make a copy of an existing value, edit the fileds in the copy, and
  56. // then store a pointer to the new copy in both realyForBy* maps.
  57. type RelayState struct {
  58. sync.RWMutex
  59. relays map[iputil.VpnIp]struct{} // Set of VpnIp's of Hosts to use as relays to access this peer
  60. relayForByIp map[iputil.VpnIp]*Relay // Maps VpnIps of peers for which this HostInfo is a relay to some Relay info
  61. relayForByIdx map[uint32]*Relay // Maps a local index to some Relay info
  62. }
  63. func (rs *RelayState) DeleteRelay(ip iputil.VpnIp) {
  64. rs.Lock()
  65. defer rs.Unlock()
  66. delete(rs.relays, ip)
  67. }
  68. func (rs *RelayState) CopyAllRelayFor() []*Relay {
  69. rs.RLock()
  70. defer rs.RUnlock()
  71. ret := make([]*Relay, 0, len(rs.relayForByIdx))
  72. for _, r := range rs.relayForByIdx {
  73. ret = append(ret, r)
  74. }
  75. return ret
  76. }
  77. func (rs *RelayState) GetRelayForByIp(ip iputil.VpnIp) (*Relay, bool) {
  78. rs.RLock()
  79. defer rs.RUnlock()
  80. r, ok := rs.relayForByIp[ip]
  81. return r, ok
  82. }
  83. func (rs *RelayState) InsertRelayTo(ip iputil.VpnIp) {
  84. rs.Lock()
  85. defer rs.Unlock()
  86. rs.relays[ip] = struct{}{}
  87. }
  88. func (rs *RelayState) CopyRelayIps() []iputil.VpnIp {
  89. rs.RLock()
  90. defer rs.RUnlock()
  91. ret := make([]iputil.VpnIp, 0, len(rs.relays))
  92. for ip := range rs.relays {
  93. ret = append(ret, ip)
  94. }
  95. return ret
  96. }
  97. func (rs *RelayState) CopyRelayForIps() []iputil.VpnIp {
  98. rs.RLock()
  99. defer rs.RUnlock()
  100. currentRelays := make([]iputil.VpnIp, 0, len(rs.relayForByIp))
  101. for relayIp := range rs.relayForByIp {
  102. currentRelays = append(currentRelays, relayIp)
  103. }
  104. return currentRelays
  105. }
  106. func (rs *RelayState) CopyRelayForIdxs() []uint32 {
  107. rs.RLock()
  108. defer rs.RUnlock()
  109. ret := make([]uint32, 0, len(rs.relayForByIdx))
  110. for i := range rs.relayForByIdx {
  111. ret = append(ret, i)
  112. }
  113. return ret
  114. }
  115. func (rs *RelayState) RemoveRelay(localIdx uint32) (iputil.VpnIp, bool) {
  116. rs.Lock()
  117. defer rs.Unlock()
  118. r, ok := rs.relayForByIdx[localIdx]
  119. if !ok {
  120. return iputil.VpnIp(0), false
  121. }
  122. delete(rs.relayForByIdx, localIdx)
  123. delete(rs.relayForByIp, r.PeerIp)
  124. return r.PeerIp, true
  125. }
  126. func (rs *RelayState) CompleteRelayByIP(vpnIp iputil.VpnIp, remoteIdx uint32) bool {
  127. rs.Lock()
  128. defer rs.Unlock()
  129. r, ok := rs.relayForByIp[vpnIp]
  130. if !ok {
  131. return false
  132. }
  133. newRelay := *r
  134. newRelay.State = Established
  135. newRelay.RemoteIndex = remoteIdx
  136. rs.relayForByIdx[r.LocalIndex] = &newRelay
  137. rs.relayForByIp[r.PeerIp] = &newRelay
  138. return true
  139. }
  140. func (rs *RelayState) CompleteRelayByIdx(localIdx uint32, remoteIdx uint32) (*Relay, bool) {
  141. rs.Lock()
  142. defer rs.Unlock()
  143. r, ok := rs.relayForByIdx[localIdx]
  144. if !ok {
  145. return nil, false
  146. }
  147. newRelay := *r
  148. newRelay.State = Established
  149. newRelay.RemoteIndex = remoteIdx
  150. rs.relayForByIdx[r.LocalIndex] = &newRelay
  151. rs.relayForByIp[r.PeerIp] = &newRelay
  152. return &newRelay, true
  153. }
  154. func (rs *RelayState) QueryRelayForByIp(vpnIp iputil.VpnIp) (*Relay, bool) {
  155. rs.RLock()
  156. defer rs.RUnlock()
  157. r, ok := rs.relayForByIp[vpnIp]
  158. return r, ok
  159. }
  160. func (rs *RelayState) QueryRelayForByIdx(idx uint32) (*Relay, bool) {
  161. rs.RLock()
  162. defer rs.RUnlock()
  163. r, ok := rs.relayForByIdx[idx]
  164. return r, ok
  165. }
  166. func (rs *RelayState) InsertRelay(ip iputil.VpnIp, idx uint32, r *Relay) {
  167. rs.Lock()
  168. defer rs.Unlock()
  169. rs.relayForByIp[ip] = r
  170. rs.relayForByIdx[idx] = r
  171. }
  172. type HostInfo struct {
  173. sync.RWMutex
  174. remote *udp.Addr
  175. remotes *RemoteList
  176. promoteCounter atomic.Uint32
  177. ConnectionState *ConnectionState
  178. handshakeStart time.Time //todo: this an entry in the handshake manager
  179. HandshakeReady bool //todo: being in the manager means you are ready
  180. HandshakeCounter int //todo: another handshake manager entry
  181. HandshakeLastRemotes []*udp.Addr //todo: another handshake manager entry, which remotes we sent to last time
  182. HandshakeComplete bool //todo: this should go away in favor of ConnectionState.ready
  183. HandshakePacket map[uint8][]byte
  184. packetStore []*cachedPacket //todo: this is other handshake manager entry
  185. remoteIndexId uint32
  186. localIndexId uint32
  187. vpnIp iputil.VpnIp
  188. recvError int
  189. remoteCidr *cidr.Tree4
  190. relayState RelayState
  191. // lastRebindCount is the other side of Interface.rebindCount, if these values don't match then we need to ask LH
  192. // for a punch from the remote end of this tunnel. The goal being to prime their conntrack for our traffic just like
  193. // with a handshake
  194. lastRebindCount int8
  195. // lastHandshakeTime records the time the remote side told us about at the stage when the handshake was completed locally
  196. // Stage 1 packet will contain it if I am a responder, stage 2 packet if I am an initiator
  197. // This is used to avoid an attack where a handshake packet is replayed after some time
  198. lastHandshakeTime uint64
  199. lastRoam time.Time
  200. lastRoamRemote *udp.Addr
  201. // Used to track other hostinfos for this vpn ip since only 1 can be primary
  202. // Synchronised via hostmap lock and not the hostinfo lock.
  203. next, prev *HostInfo
  204. }
  205. type ViaSender struct {
  206. relayHI *HostInfo // relayHI is the host info object of the relay
  207. remoteIdx uint32 // remoteIdx is the index included in the header of the received packet
  208. relay *Relay // relay contains the rest of the relay information, including the PeerIP of the host trying to communicate with us.
  209. }
  210. type cachedPacket struct {
  211. messageType header.MessageType
  212. messageSubType header.MessageSubType
  213. callback packetCallback
  214. packet []byte
  215. }
  216. type packetCallback func(t header.MessageType, st header.MessageSubType, h *HostInfo, p, nb, out []byte)
  217. type cachedPacketMetrics struct {
  218. sent metrics.Counter
  219. dropped metrics.Counter
  220. }
  221. func NewHostMap(l *logrus.Logger, vpnCIDR *net.IPNet, preferredRanges []*net.IPNet) *HostMap {
  222. h := map[iputil.VpnIp]*HostInfo{}
  223. i := map[uint32]*HostInfo{}
  224. r := map[uint32]*HostInfo{}
  225. relays := map[uint32]*HostInfo{}
  226. m := HostMap{
  227. Indexes: i,
  228. Relays: relays,
  229. RemoteIndexes: r,
  230. Hosts: h,
  231. preferredRanges: preferredRanges,
  232. vpnCIDR: vpnCIDR,
  233. l: l,
  234. }
  235. return &m
  236. }
  237. // EmitStats reports host, index, and relay counts to the stats collection system
  238. func (hm *HostMap) EmitStats() {
  239. hm.RLock()
  240. hostLen := len(hm.Hosts)
  241. indexLen := len(hm.Indexes)
  242. remoteIndexLen := len(hm.RemoteIndexes)
  243. relaysLen := len(hm.Relays)
  244. hm.RUnlock()
  245. metrics.GetOrRegisterGauge("hostmap.main.hosts", nil).Update(int64(hostLen))
  246. metrics.GetOrRegisterGauge("hostmap.main.indexes", nil).Update(int64(indexLen))
  247. metrics.GetOrRegisterGauge("hostmap.main.remoteIndexes", nil).Update(int64(remoteIndexLen))
  248. metrics.GetOrRegisterGauge("hostmap.main.relayIndexes", nil).Update(int64(relaysLen))
  249. }
  250. func (hm *HostMap) RemoveRelay(localIdx uint32) {
  251. hm.Lock()
  252. _, ok := hm.Relays[localIdx]
  253. if !ok {
  254. hm.Unlock()
  255. return
  256. }
  257. delete(hm.Relays, localIdx)
  258. hm.Unlock()
  259. }
  260. // DeleteHostInfo will fully unlink the hostinfo and return true if it was the final hostinfo for this vpn ip
  261. func (hm *HostMap) DeleteHostInfo(hostinfo *HostInfo) bool {
  262. // Delete the host itself, ensuring it's not modified anymore
  263. hm.Lock()
  264. // If we have a previous or next hostinfo then we are not the last one for this vpn ip
  265. final := (hostinfo.next == nil && hostinfo.prev == nil)
  266. hm.unlockedDeleteHostInfo(hostinfo)
  267. hm.Unlock()
  268. return final
  269. }
  270. func (hm *HostMap) MakePrimary(hostinfo *HostInfo) {
  271. hm.Lock()
  272. defer hm.Unlock()
  273. hm.unlockedMakePrimary(hostinfo)
  274. }
  275. func (hm *HostMap) unlockedMakePrimary(hostinfo *HostInfo) {
  276. oldHostinfo := hm.Hosts[hostinfo.vpnIp]
  277. if oldHostinfo == hostinfo {
  278. return
  279. }
  280. if hostinfo.prev != nil {
  281. hostinfo.prev.next = hostinfo.next
  282. }
  283. if hostinfo.next != nil {
  284. hostinfo.next.prev = hostinfo.prev
  285. }
  286. hm.Hosts[hostinfo.vpnIp] = hostinfo
  287. if oldHostinfo == nil {
  288. return
  289. }
  290. hostinfo.next = oldHostinfo
  291. oldHostinfo.prev = hostinfo
  292. hostinfo.prev = nil
  293. }
  294. func (hm *HostMap) unlockedDeleteHostInfo(hostinfo *HostInfo) {
  295. primary, ok := hm.Hosts[hostinfo.vpnIp]
  296. if ok && primary == hostinfo {
  297. // The vpnIp pointer points to the same hostinfo as the local index id, we can remove it
  298. delete(hm.Hosts, hostinfo.vpnIp)
  299. if len(hm.Hosts) == 0 {
  300. hm.Hosts = map[iputil.VpnIp]*HostInfo{}
  301. }
  302. if hostinfo.next != nil {
  303. // We had more than 1 hostinfo at this vpnip, promote the next in the list to primary
  304. hm.Hosts[hostinfo.vpnIp] = hostinfo.next
  305. // It is primary, there is no previous hostinfo now
  306. hostinfo.next.prev = nil
  307. }
  308. } else {
  309. // Relink if we were in the middle of multiple hostinfos for this vpn ip
  310. if hostinfo.prev != nil {
  311. hostinfo.prev.next = hostinfo.next
  312. }
  313. if hostinfo.next != nil {
  314. hostinfo.next.prev = hostinfo.prev
  315. }
  316. }
  317. hostinfo.next = nil
  318. hostinfo.prev = nil
  319. // The remote index uses index ids outside our control so lets make sure we are only removing
  320. // the remote index pointer here if it points to the hostinfo we are deleting
  321. hostinfo2, ok := hm.RemoteIndexes[hostinfo.remoteIndexId]
  322. if ok && hostinfo2 == hostinfo {
  323. delete(hm.RemoteIndexes, hostinfo.remoteIndexId)
  324. if len(hm.RemoteIndexes) == 0 {
  325. hm.RemoteIndexes = map[uint32]*HostInfo{}
  326. }
  327. }
  328. delete(hm.Indexes, hostinfo.localIndexId)
  329. if len(hm.Indexes) == 0 {
  330. hm.Indexes = map[uint32]*HostInfo{}
  331. }
  332. if hm.l.Level >= logrus.DebugLevel {
  333. hm.l.WithField("hostMap", m{"mapTotalSize": len(hm.Hosts),
  334. "vpnIp": hostinfo.vpnIp, "indexNumber": hostinfo.localIndexId, "remoteIndexNumber": hostinfo.remoteIndexId}).
  335. Debug("Hostmap hostInfo deleted")
  336. }
  337. for _, localRelayIdx := range hostinfo.relayState.CopyRelayForIdxs() {
  338. delete(hm.Relays, localRelayIdx)
  339. }
  340. }
  341. func (hm *HostMap) QueryIndex(index uint32) *HostInfo {
  342. hm.RLock()
  343. if h, ok := hm.Indexes[index]; ok {
  344. hm.RUnlock()
  345. return h
  346. } else {
  347. hm.RUnlock()
  348. return nil
  349. }
  350. }
  351. func (hm *HostMap) QueryRelayIndex(index uint32) *HostInfo {
  352. //TODO: we probably just want to return bool instead of error, or at least a static error
  353. hm.RLock()
  354. if h, ok := hm.Relays[index]; ok {
  355. hm.RUnlock()
  356. return h
  357. } else {
  358. hm.RUnlock()
  359. return nil
  360. }
  361. }
  362. func (hm *HostMap) QueryReverseIndex(index uint32) *HostInfo {
  363. hm.RLock()
  364. if h, ok := hm.RemoteIndexes[index]; ok {
  365. hm.RUnlock()
  366. return h
  367. } else {
  368. hm.RUnlock()
  369. return nil
  370. }
  371. }
  372. func (hm *HostMap) QueryVpnIp(vpnIp iputil.VpnIp) *HostInfo {
  373. return hm.queryVpnIp(vpnIp, nil)
  374. }
  375. func (hm *HostMap) QueryVpnIpRelayFor(targetIp, relayHostIp iputil.VpnIp) (*HostInfo, *Relay, error) {
  376. hm.RLock()
  377. defer hm.RUnlock()
  378. h, ok := hm.Hosts[relayHostIp]
  379. if !ok {
  380. return nil, nil, errors.New("unable to find host")
  381. }
  382. for h != nil {
  383. r, ok := h.relayState.QueryRelayForByIp(targetIp)
  384. if ok && r.State == Established {
  385. return h, r, nil
  386. }
  387. h = h.next
  388. }
  389. return nil, nil, errors.New("unable to find host with relay")
  390. }
  391. // PromoteBestQueryVpnIp will attempt to lazily switch to the best remote every
  392. // `PromoteEvery` calls to this function for a given host.
  393. func (hm *HostMap) PromoteBestQueryVpnIp(vpnIp iputil.VpnIp, ifce *Interface) *HostInfo {
  394. return hm.queryVpnIp(vpnIp, ifce)
  395. }
  396. func (hm *HostMap) queryVpnIp(vpnIp iputil.VpnIp, promoteIfce *Interface) *HostInfo {
  397. hm.RLock()
  398. if h, ok := hm.Hosts[vpnIp]; ok {
  399. hm.RUnlock()
  400. // Do not attempt promotion if you are a lighthouse
  401. if promoteIfce != nil && !promoteIfce.lightHouse.amLighthouse {
  402. h.TryPromoteBest(hm.preferredRanges, promoteIfce)
  403. }
  404. return h
  405. }
  406. hm.RUnlock()
  407. return nil
  408. }
  409. // unlockedAddHostInfo assumes you have a write-lock and will add a hostinfo object to the hostmap Indexes and RemoteIndexes maps.
  410. // If an entry exists for the Hosts table (vpnIp -> hostinfo) then the provided hostinfo will be made primary
  411. func (hm *HostMap) unlockedAddHostInfo(hostinfo *HostInfo, f *Interface) {
  412. if f.serveDns {
  413. remoteCert := hostinfo.ConnectionState.peerCert
  414. dnsR.Add(remoteCert.Details.Name+".", remoteCert.Details.Ips[0].IP.String())
  415. }
  416. existing := hm.Hosts[hostinfo.vpnIp]
  417. hm.Hosts[hostinfo.vpnIp] = hostinfo
  418. if existing != nil {
  419. hostinfo.next = existing
  420. existing.prev = hostinfo
  421. }
  422. hm.Indexes[hostinfo.localIndexId] = hostinfo
  423. hm.RemoteIndexes[hostinfo.remoteIndexId] = hostinfo
  424. if hm.l.Level >= logrus.DebugLevel {
  425. hm.l.WithField("hostMap", m{"vpnIp": hostinfo.vpnIp, "mapTotalSize": len(hm.Hosts),
  426. "hostinfo": m{"existing": true, "localIndexId": hostinfo.localIndexId, "hostId": hostinfo.vpnIp}}).
  427. Debug("Hostmap vpnIp added")
  428. }
  429. i := 1
  430. check := hostinfo
  431. for check != nil {
  432. if i > MaxHostInfosPerVpnIp {
  433. hm.unlockedDeleteHostInfo(check)
  434. }
  435. check = check.next
  436. i++
  437. }
  438. }
  439. func (hm *HostMap) GetPreferredRanges() []*net.IPNet {
  440. return hm.preferredRanges
  441. }
  442. func (hm *HostMap) ForEachVpnIp(f controlEach) {
  443. hm.RLock()
  444. defer hm.RUnlock()
  445. for _, v := range hm.Hosts {
  446. f(v)
  447. }
  448. }
  449. func (hm *HostMap) ForEachIndex(f controlEach) {
  450. hm.RLock()
  451. defer hm.RUnlock()
  452. for _, v := range hm.Indexes {
  453. f(v)
  454. }
  455. }
  456. // TryPromoteBest handles re-querying lighthouses and probing for better paths
  457. // NOTE: It is an error to call this if you are a lighthouse since they should not roam clients!
  458. func (i *HostInfo) TryPromoteBest(preferredRanges []*net.IPNet, ifce *Interface) {
  459. c := i.promoteCounter.Add(1)
  460. if c%PromoteEvery == 0 {
  461. // The lock here is currently protecting i.remote access
  462. i.RLock()
  463. remote := i.remote
  464. i.RUnlock()
  465. // return early if we are already on a preferred remote
  466. if remote != nil {
  467. rIP := remote.IP
  468. for _, l := range preferredRanges {
  469. if l.Contains(rIP) {
  470. return
  471. }
  472. }
  473. }
  474. i.remotes.ForEach(preferredRanges, func(addr *udp.Addr, preferred bool) {
  475. if remote != nil && (addr == nil || !preferred) {
  476. return
  477. }
  478. // Try to send a test packet to that host, this should
  479. // cause it to detect a roaming event and switch remotes
  480. ifce.sendTo(header.Test, header.TestRequest, i.ConnectionState, i, addr, []byte(""), make([]byte, 12, 12), make([]byte, mtu))
  481. })
  482. }
  483. // Re query our lighthouses for new remotes occasionally
  484. if c%ReQueryEvery == 0 && ifce.lightHouse != nil {
  485. ifce.lightHouse.QueryServer(i.vpnIp, ifce)
  486. }
  487. }
  488. func (i *HostInfo) cachePacket(l *logrus.Logger, t header.MessageType, st header.MessageSubType, packet []byte, f packetCallback, m *cachedPacketMetrics) {
  489. //TODO: return the error so we can log with more context
  490. if len(i.packetStore) < 100 {
  491. tempPacket := make([]byte, len(packet))
  492. copy(tempPacket, packet)
  493. //l.WithField("trace", string(debug.Stack())).Error("Caching packet", tempPacket)
  494. i.packetStore = append(i.packetStore, &cachedPacket{t, st, f, tempPacket})
  495. if l.Level >= logrus.DebugLevel {
  496. i.logger(l).
  497. WithField("length", len(i.packetStore)).
  498. WithField("stored", true).
  499. Debugf("Packet store")
  500. }
  501. } else if l.Level >= logrus.DebugLevel {
  502. m.dropped.Inc(1)
  503. i.logger(l).
  504. WithField("length", len(i.packetStore)).
  505. WithField("stored", false).
  506. Debugf("Packet store")
  507. }
  508. }
  509. // handshakeComplete will set the connection as ready to communicate, as well as flush any stored packets
  510. func (i *HostInfo) handshakeComplete(l *logrus.Logger, m *cachedPacketMetrics) {
  511. //TODO: I'm not certain the distinction between handshake complete and ConnectionState being ready matters because:
  512. //TODO: HandshakeComplete means send stored packets and ConnectionState.ready means we are ready to send
  513. //TODO: if the transition from HandhsakeComplete to ConnectionState.ready happens all within this function they are identical
  514. i.ConnectionState.queueLock.Lock()
  515. i.HandshakeComplete = true
  516. //TODO: this should be managed by the handshake state machine to set it based on how many handshake were seen.
  517. // Clamping it to 2 gets us out of the woods for now
  518. i.ConnectionState.messageCounter.Store(2)
  519. if l.Level >= logrus.DebugLevel {
  520. i.logger(l).Debugf("Sending %d stored packets", len(i.packetStore))
  521. }
  522. if len(i.packetStore) > 0 {
  523. nb := make([]byte, 12, 12)
  524. out := make([]byte, mtu)
  525. for _, cp := range i.packetStore {
  526. cp.callback(cp.messageType, cp.messageSubType, i, cp.packet, nb, out)
  527. }
  528. m.sent.Inc(int64(len(i.packetStore)))
  529. }
  530. i.remotes.ResetBlockedRemotes()
  531. i.packetStore = make([]*cachedPacket, 0)
  532. i.ConnectionState.ready = true
  533. i.ConnectionState.queueLock.Unlock()
  534. }
  535. func (i *HostInfo) GetCert() *cert.NebulaCertificate {
  536. if i.ConnectionState != nil {
  537. return i.ConnectionState.peerCert
  538. }
  539. return nil
  540. }
  541. func (i *HostInfo) SetRemote(remote *udp.Addr) {
  542. // We copy here because we likely got this remote from a source that reuses the object
  543. if !i.remote.Equals(remote) {
  544. i.remote = remote.Copy()
  545. i.remotes.LearnRemote(i.vpnIp, remote.Copy())
  546. }
  547. }
  548. // SetRemoteIfPreferred returns true if the remote was changed. The lastRoam
  549. // time on the HostInfo will also be updated.
  550. func (i *HostInfo) SetRemoteIfPreferred(hm *HostMap, newRemote *udp.Addr) bool {
  551. if newRemote == nil {
  552. // relays have nil udp Addrs
  553. return false
  554. }
  555. currentRemote := i.remote
  556. if currentRemote == nil {
  557. i.SetRemote(newRemote)
  558. return true
  559. }
  560. // NOTE: We do this loop here instead of calling `isPreferred` in
  561. // remote_list.go so that we only have to loop over preferredRanges once.
  562. newIsPreferred := false
  563. for _, l := range hm.preferredRanges {
  564. // return early if we are already on a preferred remote
  565. if l.Contains(currentRemote.IP) {
  566. return false
  567. }
  568. if l.Contains(newRemote.IP) {
  569. newIsPreferred = true
  570. }
  571. }
  572. if newIsPreferred {
  573. // Consider this a roaming event
  574. i.lastRoam = time.Now()
  575. i.lastRoamRemote = currentRemote.Copy()
  576. i.SetRemote(newRemote)
  577. return true
  578. }
  579. return false
  580. }
  581. func (i *HostInfo) RecvErrorExceeded() bool {
  582. if i.recvError < 3 {
  583. i.recvError += 1
  584. return false
  585. }
  586. return true
  587. }
  588. func (i *HostInfo) CreateRemoteCIDR(c *cert.NebulaCertificate) {
  589. if len(c.Details.Ips) == 1 && len(c.Details.Subnets) == 0 {
  590. // Simple case, no CIDRTree needed
  591. return
  592. }
  593. remoteCidr := cidr.NewTree4()
  594. for _, ip := range c.Details.Ips {
  595. remoteCidr.AddCIDR(&net.IPNet{IP: ip.IP, Mask: net.IPMask{255, 255, 255, 255}}, struct{}{})
  596. }
  597. for _, n := range c.Details.Subnets {
  598. remoteCidr.AddCIDR(n, struct{}{})
  599. }
  600. i.remoteCidr = remoteCidr
  601. }
  602. func (i *HostInfo) logger(l *logrus.Logger) *logrus.Entry {
  603. if i == nil {
  604. return logrus.NewEntry(l)
  605. }
  606. li := l.WithField("vpnIp", i.vpnIp).
  607. WithField("localIndex", i.localIndexId).
  608. WithField("remoteIndex", i.remoteIndexId)
  609. if connState := i.ConnectionState; connState != nil {
  610. if peerCert := connState.peerCert; peerCert != nil {
  611. li = li.WithField("certName", peerCert.Details.Name)
  612. }
  613. }
  614. return li
  615. }
  616. // Utility functions
  617. func localIps(l *logrus.Logger, allowList *LocalAllowList) *[]net.IP {
  618. //FIXME: This function is pretty garbage
  619. var ips []net.IP
  620. ifaces, _ := net.Interfaces()
  621. for _, i := range ifaces {
  622. allow := allowList.AllowName(i.Name)
  623. if l.Level >= logrus.TraceLevel {
  624. l.WithField("interfaceName", i.Name).WithField("allow", allow).Trace("localAllowList.AllowName")
  625. }
  626. if !allow {
  627. continue
  628. }
  629. addrs, _ := i.Addrs()
  630. for _, addr := range addrs {
  631. var ip net.IP
  632. switch v := addr.(type) {
  633. case *net.IPNet:
  634. //continue
  635. ip = v.IP
  636. case *net.IPAddr:
  637. ip = v.IP
  638. }
  639. //TODO: Filtering out link local for now, this is probably the most correct thing
  640. //TODO: Would be nice to filter out SLAAC MAC based ips as well
  641. if ip.IsLoopback() == false && !ip.IsLinkLocalUnicast() {
  642. allow := allowList.Allow(ip)
  643. if l.Level >= logrus.TraceLevel {
  644. l.WithField("localIp", ip).WithField("allow", allow).Trace("localAllowList.Allow")
  645. }
  646. if !allow {
  647. continue
  648. }
  649. ips = append(ips, ip)
  650. }
  651. }
  652. }
  653. return &ips
  654. }