hostmap.go 21 KB

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