hostmap.go 23 KB

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