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