hostmap.go 21 KB

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