hostmap.go 25 KB

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