hostmap.go 22 KB

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