hostmap.go 23 KB

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