hostmap.go 24 KB

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