hostmap.go 22 KB

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