hostmap.go 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888
  1. package nebula
  2. import (
  3. "encoding/json"
  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. )
  14. //const ProbeLen = 100
  15. const PromoteEvery = 1000
  16. const MaxRemotes = 10
  17. // How long we should prevent roaming back to the previous IP.
  18. // This helps prevent flapping due to packets already in flight
  19. const RoamingSuppressSeconds = 2
  20. type HostMap struct {
  21. sync.RWMutex //Because we concurrently read and write to our maps
  22. name string
  23. Indexes map[uint32]*HostInfo
  24. RemoteIndexes map[uint32]*HostInfo
  25. Hosts map[uint32]*HostInfo
  26. preferredRanges []*net.IPNet
  27. vpnCIDR *net.IPNet
  28. defaultRoute uint32
  29. unsafeRoutes *CIDRTree
  30. metricsEnabled bool
  31. }
  32. type HostInfo struct {
  33. sync.RWMutex
  34. remote *udpAddr
  35. Remotes []*HostInfoDest
  36. promoteCounter uint32
  37. ConnectionState *ConnectionState
  38. handshakeStart time.Time
  39. HandshakeReady bool
  40. HandshakeCounter int
  41. HandshakeComplete bool
  42. HandshakePacket map[uint8][]byte
  43. packetStore []*cachedPacket
  44. remoteIndexId uint32
  45. localIndexId uint32
  46. hostId uint32
  47. recvError int
  48. remoteCidr *CIDRTree
  49. // lastRebindCount is the other side of Interface.rebindCount, if these values don't match then we need to ask LH
  50. // for a punch from the remote end of this tunnel. The goal being to prime their conntrack for our traffic just like
  51. // with a handshake
  52. lastRebindCount int8
  53. lastRoam time.Time
  54. lastRoamRemote *udpAddr
  55. }
  56. type cachedPacket struct {
  57. messageType NebulaMessageType
  58. messageSubType NebulaMessageSubType
  59. callback packetCallback
  60. packet []byte
  61. }
  62. type packetCallback func(t NebulaMessageType, st NebulaMessageSubType, h *HostInfo, p, nb, out []byte)
  63. type HostInfoDest struct {
  64. addr *udpAddr
  65. //probes [ProbeLen]bool
  66. probeCounter int
  67. }
  68. type Probe struct {
  69. Addr *net.UDPAddr
  70. Counter int
  71. }
  72. func NewHostMap(name string, vpnCIDR *net.IPNet, preferredRanges []*net.IPNet) *HostMap {
  73. h := map[uint32]*HostInfo{}
  74. i := map[uint32]*HostInfo{}
  75. r := map[uint32]*HostInfo{}
  76. m := HostMap{
  77. name: name,
  78. Indexes: i,
  79. RemoteIndexes: r,
  80. Hosts: h,
  81. preferredRanges: preferredRanges,
  82. vpnCIDR: vpnCIDR,
  83. defaultRoute: 0,
  84. unsafeRoutes: NewCIDRTree(),
  85. }
  86. return &m
  87. }
  88. // UpdateStats takes a name and reports host and index counts to the stats collection system
  89. func (hm *HostMap) EmitStats(name string) {
  90. hm.RLock()
  91. hostLen := len(hm.Hosts)
  92. indexLen := len(hm.Indexes)
  93. remoteIndexLen := len(hm.RemoteIndexes)
  94. hm.RUnlock()
  95. metrics.GetOrRegisterGauge("hostmap."+name+".hosts", nil).Update(int64(hostLen))
  96. metrics.GetOrRegisterGauge("hostmap."+name+".indexes", nil).Update(int64(indexLen))
  97. metrics.GetOrRegisterGauge("hostmap."+name+".remoteIndexes", nil).Update(int64(remoteIndexLen))
  98. }
  99. func (hm *HostMap) GetIndexByVpnIP(vpnIP uint32) (uint32, error) {
  100. hm.RLock()
  101. if i, ok := hm.Hosts[vpnIP]; ok {
  102. index := i.localIndexId
  103. hm.RUnlock()
  104. return index, nil
  105. }
  106. hm.RUnlock()
  107. return 0, errors.New("vpn IP not found")
  108. }
  109. func (hm *HostMap) Add(ip uint32, hostinfo *HostInfo) {
  110. hm.Lock()
  111. hm.Hosts[ip] = hostinfo
  112. hm.Unlock()
  113. }
  114. func (hm *HostMap) AddVpnIP(vpnIP uint32) *HostInfo {
  115. h := &HostInfo{}
  116. hm.RLock()
  117. if _, ok := hm.Hosts[vpnIP]; !ok {
  118. hm.RUnlock()
  119. h = &HostInfo{
  120. Remotes: []*HostInfoDest{},
  121. promoteCounter: 0,
  122. hostId: vpnIP,
  123. HandshakePacket: make(map[uint8][]byte, 0),
  124. }
  125. hm.Lock()
  126. hm.Hosts[vpnIP] = h
  127. hm.Unlock()
  128. return h
  129. } else {
  130. h = hm.Hosts[vpnIP]
  131. hm.RUnlock()
  132. return h
  133. }
  134. }
  135. func (hm *HostMap) DeleteVpnIP(vpnIP uint32) {
  136. hm.Lock()
  137. delete(hm.Hosts, vpnIP)
  138. if len(hm.Hosts) == 0 {
  139. hm.Hosts = map[uint32]*HostInfo{}
  140. }
  141. hm.Unlock()
  142. if l.Level >= logrus.DebugLevel {
  143. l.WithField("hostMap", m{"mapName": hm.name, "vpnIp": IntIp(vpnIP), "mapTotalSize": len(hm.Hosts)}).
  144. Debug("Hostmap vpnIp deleted")
  145. }
  146. }
  147. func (hm *HostMap) AddIndex(index uint32, ci *ConnectionState) (*HostInfo, error) {
  148. hm.Lock()
  149. if _, ok := hm.Indexes[index]; !ok {
  150. h := &HostInfo{
  151. ConnectionState: ci,
  152. Remotes: []*HostInfoDest{},
  153. localIndexId: index,
  154. HandshakePacket: make(map[uint8][]byte, 0),
  155. }
  156. hm.Indexes[index] = h
  157. l.WithField("hostMap", m{"mapName": hm.name, "indexNumber": index, "mapTotalSize": len(hm.Indexes),
  158. "hostinfo": m{"existing": false, "localIndexId": h.localIndexId, "hostId": IntIp(h.hostId)}}).
  159. Debug("Hostmap index added")
  160. hm.Unlock()
  161. return h, nil
  162. }
  163. hm.Unlock()
  164. return nil, fmt.Errorf("refusing to overwrite existing index: %d", index)
  165. }
  166. func (hm *HostMap) AddIndexHostInfo(index uint32, h *HostInfo) {
  167. hm.Lock()
  168. h.localIndexId = index
  169. hm.Indexes[index] = h
  170. hm.Unlock()
  171. if l.Level > logrus.DebugLevel {
  172. l.WithField("hostMap", m{"mapName": hm.name, "indexNumber": index, "mapTotalSize": len(hm.Indexes),
  173. "hostinfo": m{"existing": true, "localIndexId": h.localIndexId, "hostId": IntIp(h.hostId)}}).
  174. Debug("Hostmap index added")
  175. }
  176. }
  177. // Only used by pendingHostMap when the remote index is not initially known
  178. func (hm *HostMap) addRemoteIndexHostInfo(index uint32, h *HostInfo) {
  179. hm.Lock()
  180. h.remoteIndexId = index
  181. hm.RemoteIndexes[index] = h
  182. hm.Unlock()
  183. if l.Level > logrus.DebugLevel {
  184. l.WithField("hostMap", m{"mapName": hm.name, "indexNumber": index, "mapTotalSize": len(hm.Indexes),
  185. "hostinfo": m{"existing": true, "localIndexId": h.localIndexId, "hostId": IntIp(h.hostId)}}).
  186. Debug("Hostmap remoteIndex added")
  187. }
  188. }
  189. func (hm *HostMap) AddVpnIPHostInfo(vpnIP uint32, h *HostInfo) {
  190. hm.Lock()
  191. h.hostId = vpnIP
  192. hm.Hosts[vpnIP] = h
  193. hm.Indexes[h.localIndexId] = h
  194. hm.RemoteIndexes[h.remoteIndexId] = h
  195. hm.Unlock()
  196. if l.Level > logrus.DebugLevel {
  197. l.WithField("hostMap", m{"mapName": hm.name, "vpnIp": IntIp(vpnIP), "mapTotalSize": len(hm.Hosts),
  198. "hostinfo": m{"existing": true, "localIndexId": h.localIndexId, "hostId": IntIp(h.hostId)}}).
  199. Debug("Hostmap vpnIp added")
  200. }
  201. }
  202. // This is only called in pendingHostmap, to cleanup an inbound handshake
  203. func (hm *HostMap) DeleteIndex(index uint32) {
  204. hm.Lock()
  205. hostinfo, ok := hm.Indexes[index]
  206. if ok {
  207. hostinfo.Lock()
  208. defer hostinfo.Unlock()
  209. delete(hm.Indexes, index)
  210. delete(hm.RemoteIndexes, hostinfo.remoteIndexId)
  211. // Check if we have an entry under hostId that matches the same hostinfo
  212. // instance. Clean it up as well if we do.
  213. var hostinfo2 *HostInfo
  214. hostinfo2, ok = hm.Hosts[hostinfo.hostId]
  215. if ok && hostinfo2 == hostinfo {
  216. delete(hm.Hosts, hostinfo.hostId)
  217. }
  218. }
  219. hm.Unlock()
  220. if l.Level >= logrus.DebugLevel {
  221. l.WithField("hostMap", m{"mapName": hm.name, "indexNumber": index, "mapTotalSize": len(hm.Indexes)}).
  222. Debug("Hostmap index deleted")
  223. }
  224. }
  225. // This is used to cleanup on recv_error
  226. func (hm *HostMap) DeleteReverseIndex(index uint32) {
  227. hm.Lock()
  228. hostinfo, ok := hm.RemoteIndexes[index]
  229. if ok {
  230. delete(hm.Indexes, hostinfo.localIndexId)
  231. delete(hm.RemoteIndexes, index)
  232. // Check if we have an entry under hostId that matches the same hostinfo
  233. // instance. Clean it up as well if we do (they might not match in pendingHostmap)
  234. var hostinfo2 *HostInfo
  235. hostinfo2, ok = hm.Hosts[hostinfo.hostId]
  236. if ok && hostinfo2 == hostinfo {
  237. delete(hm.Hosts, hostinfo.hostId)
  238. }
  239. }
  240. hm.Unlock()
  241. if l.Level >= logrus.DebugLevel {
  242. l.WithField("hostMap", m{"mapName": hm.name, "indexNumber": index, "mapTotalSize": len(hm.Indexes)}).
  243. Debug("Hostmap remote index deleted")
  244. }
  245. }
  246. func (hm *HostMap) DeleteHostInfo(hostinfo *HostInfo) {
  247. hm.Lock()
  248. // Check if this same hostId is in the hostmap with a different instance.
  249. // This could happen if we have an entry in the pending hostmap with different
  250. // index values than the one in the main hostmap.
  251. hostinfo2, ok := hm.Hosts[hostinfo.hostId]
  252. if ok && hostinfo2 != hostinfo {
  253. delete(hm.Hosts, hostinfo2.hostId)
  254. delete(hm.Indexes, hostinfo2.localIndexId)
  255. delete(hm.RemoteIndexes, hostinfo2.remoteIndexId)
  256. }
  257. delete(hm.Hosts, hostinfo.hostId)
  258. if len(hm.Hosts) == 0 {
  259. hm.Hosts = map[uint32]*HostInfo{}
  260. }
  261. delete(hm.Indexes, hostinfo.localIndexId)
  262. if len(hm.Indexes) == 0 {
  263. hm.Indexes = map[uint32]*HostInfo{}
  264. }
  265. delete(hm.RemoteIndexes, hostinfo.remoteIndexId)
  266. if len(hm.RemoteIndexes) == 0 {
  267. hm.RemoteIndexes = map[uint32]*HostInfo{}
  268. }
  269. hm.Unlock()
  270. if l.Level >= logrus.DebugLevel {
  271. l.WithField("hostMap", m{"mapName": hm.name, "mapTotalSize": len(hm.Hosts),
  272. "vpnIp": IntIp(hostinfo.hostId), "indexNumber": hostinfo.localIndexId, "remoteIndexNumber": hostinfo.remoteIndexId}).
  273. Debug("Hostmap hostInfo deleted")
  274. }
  275. }
  276. func (hm *HostMap) QueryIndex(index uint32) (*HostInfo, error) {
  277. //TODO: we probably just want ot return bool instead of error, or at least a static error
  278. hm.RLock()
  279. if h, ok := hm.Indexes[index]; ok {
  280. hm.RUnlock()
  281. return h, nil
  282. } else {
  283. hm.RUnlock()
  284. return nil, errors.New("unable to find index")
  285. }
  286. }
  287. func (hm *HostMap) QueryReverseIndex(index uint32) (*HostInfo, error) {
  288. hm.RLock()
  289. if h, ok := hm.RemoteIndexes[index]; ok {
  290. hm.RUnlock()
  291. return h, nil
  292. } else {
  293. hm.RUnlock()
  294. return nil, fmt.Errorf("unable to find reverse index or connectionstate nil in %s hostmap", hm.name)
  295. }
  296. }
  297. func (hm *HostMap) AddRemote(vpnIp uint32, remote *udpAddr) *HostInfo {
  298. hm.Lock()
  299. i, v := hm.Hosts[vpnIp]
  300. if v {
  301. i.AddRemote(*remote)
  302. } else {
  303. i = &HostInfo{
  304. Remotes: []*HostInfoDest{NewHostInfoDest(remote)},
  305. promoteCounter: 0,
  306. hostId: vpnIp,
  307. HandshakePacket: make(map[uint8][]byte, 0),
  308. }
  309. i.remote = i.Remotes[0].addr
  310. hm.Hosts[vpnIp] = i
  311. l.WithField("hostMap", m{"mapName": hm.name, "vpnIp": IntIp(vpnIp), "udpAddr": remote, "mapTotalSize": len(hm.Hosts)}).
  312. Debug("Hostmap remote ip added")
  313. }
  314. i.ForcePromoteBest(hm.preferredRanges)
  315. hm.Unlock()
  316. return i
  317. }
  318. func (hm *HostMap) QueryVpnIP(vpnIp uint32) (*HostInfo, error) {
  319. return hm.queryVpnIP(vpnIp, nil)
  320. }
  321. // PromoteBestQueryVpnIP will attempt to lazily switch to the best remote every
  322. // `PromoteEvery` calls to this function for a given host.
  323. func (hm *HostMap) PromoteBestQueryVpnIP(vpnIp uint32, ifce *Interface) (*HostInfo, error) {
  324. return hm.queryVpnIP(vpnIp, ifce)
  325. }
  326. func (hm *HostMap) queryVpnIP(vpnIp uint32, promoteIfce *Interface) (*HostInfo, error) {
  327. hm.RLock()
  328. if h, ok := hm.Hosts[vpnIp]; ok {
  329. if promoteIfce != nil {
  330. h.TryPromoteBest(hm.preferredRanges, promoteIfce)
  331. }
  332. //fmt.Println(h.remote)
  333. hm.RUnlock()
  334. return h, nil
  335. } else {
  336. //return &net.UDPAddr{}, nil, errors.New("Unable to find host")
  337. hm.RUnlock()
  338. /*
  339. if lightHouse != nil {
  340. lightHouse.Query(vpnIp)
  341. return nil, errors.New("Unable to find host")
  342. }
  343. */
  344. return nil, errors.New("unable to find host")
  345. }
  346. }
  347. func (hm *HostMap) queryUnsafeRoute(ip uint32) uint32 {
  348. r := hm.unsafeRoutes.MostSpecificContains(ip)
  349. if r != nil {
  350. return r.(uint32)
  351. } else {
  352. return 0
  353. }
  354. }
  355. func (hm *HostMap) CheckHandshakeCompleteIP(vpnIP uint32) bool {
  356. hm.RLock()
  357. if i, ok := hm.Hosts[vpnIP]; ok {
  358. if i == nil {
  359. hm.RUnlock()
  360. return false
  361. }
  362. complete := i.HandshakeComplete
  363. hm.RUnlock()
  364. return complete
  365. }
  366. hm.RUnlock()
  367. return false
  368. }
  369. func (hm *HostMap) CheckHandshakeCompleteIndex(index uint32) bool {
  370. hm.RLock()
  371. if i, ok := hm.Indexes[index]; ok {
  372. if i == nil {
  373. hm.RUnlock()
  374. return false
  375. }
  376. complete := i.HandshakeComplete
  377. hm.RUnlock()
  378. return complete
  379. }
  380. hm.RUnlock()
  381. return false
  382. }
  383. func (hm *HostMap) ClearRemotes(vpnIP uint32) {
  384. hm.Lock()
  385. i := hm.Hosts[vpnIP]
  386. if i == nil {
  387. hm.Unlock()
  388. return
  389. }
  390. i.remote = nil
  391. i.Remotes = nil
  392. hm.Unlock()
  393. }
  394. func (hm *HostMap) SetDefaultRoute(ip uint32) {
  395. hm.defaultRoute = ip
  396. }
  397. func (hm *HostMap) PunchList() []*udpAddr {
  398. var list []*udpAddr
  399. hm.RLock()
  400. for _, v := range hm.Hosts {
  401. for _, r := range v.Remotes {
  402. list = append(list, r.addr)
  403. }
  404. // if h, ok := hm.Hosts[vpnIp]; ok {
  405. // hm.Hosts[vpnIp].PromoteBest(hm.preferredRanges, false)
  406. //fmt.Println(h.remote)
  407. // }
  408. }
  409. hm.RUnlock()
  410. return list
  411. }
  412. func (hm *HostMap) Punchy(conn *udpConn) {
  413. var metricsTxPunchy metrics.Counter
  414. if hm.metricsEnabled {
  415. metricsTxPunchy = metrics.GetOrRegisterCounter("messages.tx.punchy", nil)
  416. } else {
  417. metricsTxPunchy = metrics.NilCounter{}
  418. }
  419. for {
  420. for _, addr := range hm.PunchList() {
  421. metricsTxPunchy.Inc(1)
  422. conn.WriteTo([]byte{1}, addr)
  423. }
  424. time.Sleep(time.Second * 30)
  425. }
  426. }
  427. func (hm *HostMap) addUnsafeRoutes(routes *[]route) {
  428. for _, r := range *routes {
  429. l.WithField("route", r.route).WithField("via", r.via).Warn("Adding UNSAFE Route")
  430. hm.unsafeRoutes.AddCIDR(r.route, ip2int(*r.via))
  431. }
  432. }
  433. func (i *HostInfo) MarshalJSON() ([]byte, error) {
  434. return json.Marshal(m{
  435. "remote": i.remote,
  436. "remotes": i.Remotes,
  437. "promote_counter": i.promoteCounter,
  438. "connection_state": i.ConnectionState,
  439. "handshake_start": i.handshakeStart,
  440. "handshake_ready": i.HandshakeReady,
  441. "handshake_counter": i.HandshakeCounter,
  442. "handshake_complete": i.HandshakeComplete,
  443. "handshake_packet": i.HandshakePacket,
  444. "packet_store": i.packetStore,
  445. "remote_index": i.remoteIndexId,
  446. "local_index": i.localIndexId,
  447. "host_id": int2ip(i.hostId),
  448. "receive_errors": i.recvError,
  449. "last_roam": i.lastRoam,
  450. "last_roam_remote": i.lastRoamRemote,
  451. })
  452. }
  453. func (i *HostInfo) BindConnectionState(cs *ConnectionState) {
  454. i.ConnectionState = cs
  455. }
  456. func (i *HostInfo) TryPromoteBest(preferredRanges []*net.IPNet, ifce *Interface) {
  457. if i.remote == nil {
  458. i.ForcePromoteBest(preferredRanges)
  459. return
  460. }
  461. if atomic.AddUint32(&i.promoteCounter, 1)&PromoteEvery == 0 {
  462. // return early if we are already on a preferred remote
  463. rIP := udp2ip(i.remote)
  464. for _, l := range preferredRanges {
  465. if l.Contains(rIP) {
  466. return
  467. }
  468. }
  469. // We re-query the lighthouse periodically while sending packets, so
  470. // check for new remotes in our local lighthouse cache
  471. ips := ifce.lightHouse.QueryCache(i.hostId)
  472. for _, ip := range ips {
  473. i.AddRemote(ip)
  474. }
  475. best, preferred := i.getBestRemote(preferredRanges)
  476. if preferred && !best.Equals(i.remote) {
  477. // Try to send a test packet to that host, this should
  478. // cause it to detect a roaming event and switch remotes
  479. ifce.send(test, testRequest, i.ConnectionState, i, best, []byte(""), make([]byte, 12, 12), make([]byte, mtu))
  480. }
  481. }
  482. }
  483. func (i *HostInfo) ForcePromoteBest(preferredRanges []*net.IPNet) {
  484. best, _ := i.getBestRemote(preferredRanges)
  485. if best != nil {
  486. i.remote = best
  487. }
  488. }
  489. func (i *HostInfo) getBestRemote(preferredRanges []*net.IPNet) (best *udpAddr, preferred bool) {
  490. if len(i.Remotes) > 0 {
  491. for _, r := range i.Remotes {
  492. rIP := udp2ip(r.addr)
  493. for _, l := range preferredRanges {
  494. if l.Contains(rIP) {
  495. return r.addr, true
  496. }
  497. }
  498. if best == nil || !PrivateIP(rIP) {
  499. best = r.addr
  500. }
  501. /*
  502. for _, r := range i.Remotes {
  503. // Must have > 80% probe success to be considered.
  504. //fmt.Println("GRADE:", r.addr.IP, r.Grade())
  505. if r.Grade() > float64(.8) {
  506. if localToMe.Contains(r.addr.IP) == true {
  507. best = r.addr
  508. break
  509. //i.remote = i.Remotes[c].addr
  510. } else {
  511. //}
  512. }
  513. */
  514. }
  515. return best, false
  516. }
  517. return nil, false
  518. }
  519. // rotateRemote will move remote to the next ip in the list of remote ips for this host
  520. // This is different than PromoteBest in that what is algorithmically best may not actually work.
  521. // Only known use case is when sending a stage 0 handshake.
  522. // It may be better to just send stage 0 handshakes to all known ips and sort it out in the receiver.
  523. func (i *HostInfo) rotateRemote() {
  524. // We have 0, can't rotate
  525. if len(i.Remotes) < 1 {
  526. return
  527. }
  528. if i.remote == nil {
  529. i.remote = i.Remotes[0].addr
  530. return
  531. }
  532. // We want to look at all but the very last entry since that is handled at the end
  533. for x := 0; x < len(i.Remotes)-1; x++ {
  534. // Find our current position and move to the next one in the list
  535. if i.Remotes[x].addr.Equals(i.remote) {
  536. i.remote = i.Remotes[x+1].addr
  537. return
  538. }
  539. }
  540. // Our current position was likely the last in the list, start over at 0
  541. i.remote = i.Remotes[0].addr
  542. }
  543. func (i *HostInfo) cachePacket(t NebulaMessageType, st NebulaMessageSubType, packet []byte, f packetCallback) {
  544. //TODO: return the error so we can log with more context
  545. if len(i.packetStore) < 100 {
  546. tempPacket := make([]byte, len(packet))
  547. copy(tempPacket, packet)
  548. //l.WithField("trace", string(debug.Stack())).Error("Caching packet", tempPacket)
  549. i.packetStore = append(i.packetStore, &cachedPacket{t, st, f, tempPacket})
  550. if l.Level >= logrus.DebugLevel {
  551. i.logger().
  552. WithField("length", len(i.packetStore)).
  553. WithField("stored", true).
  554. Debugf("Packet store")
  555. }
  556. } else if l.Level >= logrus.DebugLevel {
  557. i.logger().
  558. WithField("length", len(i.packetStore)).
  559. WithField("stored", false).
  560. Debugf("Packet store")
  561. }
  562. }
  563. // handshakeComplete will set the connection as ready to communicate, as well as flush any stored packets
  564. func (i *HostInfo) handshakeComplete() {
  565. //TODO: I'm not certain the distinction between handshake complete and ConnectionState being ready matters because:
  566. //TODO: HandshakeComplete means send stored packets and ConnectionState.ready means we are ready to send
  567. //TODO: if the transition from HandhsakeComplete to ConnectionState.ready happens all within this function they are identical
  568. i.ConnectionState.queueLock.Lock()
  569. i.HandshakeComplete = true
  570. //TODO: this should be managed by the handshake state machine to set it based on how many handshake were seen.
  571. // Clamping it to 2 gets us out of the woods for now
  572. atomic.StoreUint64(&i.ConnectionState.atomicMessageCounter, 2)
  573. i.logger().Debugf("Sending %d stored packets", len(i.packetStore))
  574. nb := make([]byte, 12, 12)
  575. out := make([]byte, mtu)
  576. for _, cp := range i.packetStore {
  577. cp.callback(cp.messageType, cp.messageSubType, i, cp.packet, nb, out)
  578. }
  579. i.packetStore = make([]*cachedPacket, 0)
  580. i.ConnectionState.ready = true
  581. i.ConnectionState.queueLock.Unlock()
  582. i.ConnectionState.certState = nil
  583. }
  584. func (i *HostInfo) RemoteUDPAddrs() []*udpAddr {
  585. var addrs []*udpAddr
  586. for _, r := range i.Remotes {
  587. addrs = append(addrs, r.addr)
  588. }
  589. return addrs
  590. }
  591. func (i *HostInfo) GetCert() *cert.NebulaCertificate {
  592. if i.ConnectionState != nil {
  593. return i.ConnectionState.peerCert
  594. }
  595. return nil
  596. }
  597. func (i *HostInfo) AddRemote(r udpAddr) *udpAddr {
  598. remote := &r
  599. //add := true
  600. for _, r := range i.Remotes {
  601. if r.addr.Equals(remote) {
  602. return r.addr
  603. //add = false
  604. }
  605. }
  606. // Trim this down if necessary
  607. if len(i.Remotes) > MaxRemotes {
  608. i.Remotes = i.Remotes[len(i.Remotes)-MaxRemotes:]
  609. }
  610. i.Remotes = append(i.Remotes, NewHostInfoDest(remote))
  611. return remote
  612. //l.Debugf("Added remote %s for vpn ip", remote)
  613. }
  614. func (i *HostInfo) SetRemote(remote udpAddr) {
  615. i.remote = i.AddRemote(remote)
  616. }
  617. func (i *HostInfo) ClearRemotes() {
  618. i.remote = nil
  619. i.Remotes = []*HostInfoDest{}
  620. }
  621. func (i *HostInfo) ClearConnectionState() {
  622. i.ConnectionState = nil
  623. }
  624. func (i *HostInfo) RecvErrorExceeded() bool {
  625. if i.recvError < 3 {
  626. i.recvError += 1
  627. return false
  628. }
  629. return true
  630. }
  631. func (i *HostInfo) CreateRemoteCIDR(c *cert.NebulaCertificate) {
  632. if len(c.Details.Ips) == 1 && len(c.Details.Subnets) == 0 {
  633. // Simple case, no CIDRTree needed
  634. return
  635. }
  636. remoteCidr := NewCIDRTree()
  637. for _, ip := range c.Details.Ips {
  638. remoteCidr.AddCIDR(&net.IPNet{IP: ip.IP, Mask: net.IPMask{255, 255, 255, 255}}, struct{}{})
  639. }
  640. for _, n := range c.Details.Subnets {
  641. remoteCidr.AddCIDR(n, struct{}{})
  642. }
  643. i.remoteCidr = remoteCidr
  644. }
  645. func (i *HostInfo) logger() *logrus.Entry {
  646. if i == nil {
  647. return logrus.NewEntry(l)
  648. }
  649. li := l.WithField("vpnIp", IntIp(i.hostId))
  650. if connState := i.ConnectionState; connState != nil {
  651. if peerCert := connState.peerCert; peerCert != nil {
  652. li = li.WithField("certName", peerCert.Details.Name)
  653. }
  654. }
  655. return li
  656. }
  657. //########################
  658. func NewHostInfoDest(addr *udpAddr) *HostInfoDest {
  659. i := &HostInfoDest{
  660. addr: addr,
  661. }
  662. return i
  663. }
  664. func (hid *HostInfoDest) MarshalJSON() ([]byte, error) {
  665. return json.Marshal(m{
  666. "address": hid.addr,
  667. "probe_count": hid.probeCounter,
  668. })
  669. }
  670. /*
  671. func (hm *HostMap) DebugRemotes(vpnIp uint32) string {
  672. s := "\n"
  673. for _, h := range hm.Hosts {
  674. for _, r := range h.Remotes {
  675. s += fmt.Sprintf("%s : %d ## %v\n", r.addr.IP.String(), r.addr.Port, r.probes)
  676. }
  677. }
  678. return s
  679. }
  680. func (d *HostInfoDest) Grade() float64 {
  681. c1 := ProbeLen
  682. for n := len(d.probes) - 1; n >= 0; n-- {
  683. if d.probes[n] == true {
  684. c1 -= 1
  685. }
  686. }
  687. return float64(c1) / float64(ProbeLen)
  688. }
  689. func (d *HostInfoDest) Grade() (float64, float64, float64) {
  690. c1 := ProbeLen
  691. c2 := ProbeLen / 2
  692. c2c := ProbeLen - ProbeLen/2
  693. c3 := ProbeLen / 5
  694. c3c := ProbeLen - ProbeLen/5
  695. for n := len(d.probes) - 1; n >= 0; n-- {
  696. if d.probes[n] == true {
  697. c1 -= 1
  698. if n >= c2c {
  699. c2 -= 1
  700. if n >= c3c {
  701. c3 -= 1
  702. }
  703. }
  704. }
  705. //if n >= d {
  706. }
  707. return float64(c3) / float64(ProbeLen/5), float64(c2) / float64(ProbeLen/2), float64(c1) / float64(ProbeLen)
  708. //return float64(c1) / float64(ProbeLen), float64(c2) / float64(ProbeLen/2), float64(c3) / float64(ProbeLen/5)
  709. }
  710. func (i *HostInfo) HandleReply(addr *net.UDPAddr, counter int) {
  711. for _, r := range i.Remotes {
  712. if r.addr.IP.Equal(addr.IP) && r.addr.Port == addr.Port {
  713. r.ProbeReceived(counter)
  714. }
  715. }
  716. }
  717. func (i *HostInfo) Probes() []*Probe {
  718. p := []*Probe{}
  719. for _, d := range i.Remotes {
  720. p = append(p, &Probe{Addr: d.addr, Counter: d.Probe()})
  721. }
  722. return p
  723. }
  724. func (d *HostInfoDest) Probe() int {
  725. //d.probes = append(d.probes, true)
  726. d.probeCounter++
  727. d.probes[d.probeCounter%ProbeLen] = true
  728. return d.probeCounter
  729. //return d.probeCounter
  730. }
  731. func (d *HostInfoDest) ProbeReceived(probeCount int) {
  732. if probeCount >= (d.probeCounter - ProbeLen) {
  733. //fmt.Println("PROBE WORKED", probeCount)
  734. //fmt.Println(d.addr, d.Grade())
  735. d.probes[probeCount%ProbeLen] = false
  736. }
  737. }
  738. */
  739. // Utility functions
  740. func localIps(allowList *AllowList) *[]net.IP {
  741. //FIXME: This function is pretty garbage
  742. var ips []net.IP
  743. ifaces, _ := net.Interfaces()
  744. for _, i := range ifaces {
  745. allow := allowList.AllowName(i.Name)
  746. l.WithField("interfaceName", i.Name).WithField("allow", allow).Debug("localAllowList.AllowName")
  747. if !allow {
  748. continue
  749. }
  750. addrs, _ := i.Addrs()
  751. for _, addr := range addrs {
  752. var ip net.IP
  753. switch v := addr.(type) {
  754. case *net.IPNet:
  755. //continue
  756. ip = v.IP
  757. case *net.IPAddr:
  758. ip = v.IP
  759. }
  760. if ip.To4() != nil && ip.IsLoopback() == false {
  761. allow := allowList.Allow(ip2int(ip))
  762. l.WithField("localIp", ip).WithField("allow", allow).Debug("localAllowList.Allow")
  763. if !allow {
  764. continue
  765. }
  766. ips = append(ips, ip)
  767. }
  768. }
  769. }
  770. return &ips
  771. }
  772. func PrivateIP(ip net.IP) bool {
  773. private := false
  774. _, private24BitBlock, _ := net.ParseCIDR("10.0.0.0/8")
  775. _, private20BitBlock, _ := net.ParseCIDR("172.16.0.0/12")
  776. _, private16BitBlock, _ := net.ParseCIDR("192.168.0.0/16")
  777. private = private24BitBlock.Contains(ip) || private20BitBlock.Contains(ip) || private16BitBlock.Contains(ip)
  778. return private
  779. }