hostmap.go 21 KB

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