SelfAwareness.cpp 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217
  1. /*
  2. * ZeroTier One - Network Virtualization Everywhere
  3. * Copyright (C) 2011-2016 ZeroTier, Inc. https://www.zerotier.com/
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation, either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. */
  18. #include <stdio.h>
  19. #include <stdlib.h>
  20. #include <string.h>
  21. #include <set>
  22. #include <vector>
  23. #include "Constants.hpp"
  24. #include "SelfAwareness.hpp"
  25. #include "RuntimeEnvironment.hpp"
  26. #include "Node.hpp"
  27. #include "Topology.hpp"
  28. #include "Packet.hpp"
  29. #include "Peer.hpp"
  30. #include "Switch.hpp"
  31. // Entry timeout -- make it fairly long since this is just to prevent stale buildup
  32. #define ZT_SELFAWARENESS_ENTRY_TIMEOUT 3600000
  33. namespace ZeroTier {
  34. class _ResetWithinScope
  35. {
  36. public:
  37. _ResetWithinScope(uint64_t now,InetAddress::IpScope scope) :
  38. _now(now),
  39. _scope(scope) {}
  40. inline void operator()(Topology &t,const SharedPtr<Peer> &p)
  41. {
  42. if (p->resetWithinScope(_scope,_now))
  43. peersReset.push_back(p);
  44. }
  45. std::vector< SharedPtr<Peer> > peersReset;
  46. private:
  47. uint64_t _now;
  48. InetAddress::IpScope _scope;
  49. };
  50. SelfAwareness::SelfAwareness(const RuntimeEnvironment *renv) :
  51. RR(renv),
  52. _phy(32)
  53. {
  54. }
  55. SelfAwareness::~SelfAwareness()
  56. {
  57. }
  58. void SelfAwareness::iam(const Address &reporter,const InetAddress &receivedOnLocalAddress,const InetAddress &reporterPhysicalAddress,const InetAddress &myPhysicalAddress,bool trusted,uint64_t now)
  59. {
  60. const InetAddress::IpScope scope = myPhysicalAddress.ipScope();
  61. if ((scope != reporterPhysicalAddress.ipScope())||(scope == InetAddress::IP_SCOPE_NONE)||(scope == InetAddress::IP_SCOPE_LOOPBACK)||(scope == InetAddress::IP_SCOPE_MULTICAST))
  62. return;
  63. Mutex::Lock _l(_phy_m);
  64. PhySurfaceEntry &entry = _phy[PhySurfaceKey(reporter,receivedOnLocalAddress,reporterPhysicalAddress,scope)];
  65. if ( (trusted) && ((now - entry.ts) < ZT_SELFAWARENESS_ENTRY_TIMEOUT) && (!entry.mySurface.ipsEqual(myPhysicalAddress)) ) {
  66. // Changes to external surface reported by trusted peers causes path reset in this scope
  67. TRACE("physical address %s for scope %u as seen from %s(%s) differs from %s, resetting paths in scope",myPhysicalAddress.toString().c_str(),(unsigned int)scope,reporter.toString().c_str(),reporterPhysicalAddress.toString().c_str(),entry.mySurface.toString().c_str());
  68. entry.mySurface = myPhysicalAddress;
  69. entry.ts = now;
  70. entry.trusted = trusted;
  71. // Erase all entries in this scope that were not reported from this remote address to prevent 'thrashing'
  72. // due to multiple reports of endpoint change.
  73. // Don't use 'entry' after this since hash table gets modified.
  74. {
  75. Hashtable< PhySurfaceKey,PhySurfaceEntry >::Iterator i(_phy);
  76. PhySurfaceKey *k = (PhySurfaceKey *)0;
  77. PhySurfaceEntry *e = (PhySurfaceEntry *)0;
  78. while (i.next(k,e)) {
  79. if ((k->reporterPhysicalAddress != reporterPhysicalAddress)&&(k->scope == scope))
  80. _phy.erase(*k);
  81. }
  82. }
  83. // Reset all paths within this scope
  84. _ResetWithinScope rset(now,(InetAddress::IpScope)scope);
  85. RR->topology->eachPeer<_ResetWithinScope &>(rset);
  86. // Send a NOP to all peers for whom we forgot a path. This will cause direct
  87. // links to be re-established if possible, possibly using a root server or some
  88. // other relay.
  89. for(std::vector< SharedPtr<Peer> >::const_iterator p(rset.peersReset.begin());p!=rset.peersReset.end();++p) {
  90. if ((*p)->activelyTransferringFrames(now)) {
  91. Packet outp((*p)->address(),RR->identity.address(),Packet::VERB_NOP);
  92. RR->sw->send(outp,true);
  93. }
  94. }
  95. } else {
  96. // Otherwise just update DB to use to determine external surface info
  97. entry.mySurface = myPhysicalAddress;
  98. entry.ts = now;
  99. entry.trusted = trusted;
  100. }
  101. }
  102. void SelfAwareness::clean(uint64_t now)
  103. {
  104. Mutex::Lock _l(_phy_m);
  105. Hashtable< PhySurfaceKey,PhySurfaceEntry >::Iterator i(_phy);
  106. PhySurfaceKey *k = (PhySurfaceKey *)0;
  107. PhySurfaceEntry *e = (PhySurfaceEntry *)0;
  108. while (i.next(k,e)) {
  109. if ((now - e->ts) >= ZT_SELFAWARENESS_ENTRY_TIMEOUT)
  110. _phy.erase(*k);
  111. }
  112. }
  113. std::vector<InetAddress> SelfAwareness::getSymmetricNatPredictions()
  114. {
  115. /* This is based on ideas and strategies found here:
  116. * https://tools.ietf.org/html/draft-takeda-symmetric-nat-traversal-00
  117. *
  118. * In short: a great many symmetric NATs allocate ports sequentially.
  119. * This is common on enterprise and carrier grade NATs as well as consumer
  120. * devices. This code generates a list of "you might try this" addresses by
  121. * extrapolating likely port assignments from currently known external
  122. * global IPv4 surfaces. These can then be included in a PUSH_DIRECT_PATHS
  123. * message to another peer, causing it to possibly try these addresses and
  124. * bust our local symmetric NAT. It works often enough to be worth the
  125. * extra bit of code and does no harm in cases where it fails. */
  126. // Gather unique surfaces indexed by local received-on address and flag
  127. // us as behind a symmetric NAT if there is more than one.
  128. std::map< InetAddress,std::set<InetAddress> > surfaces;
  129. bool symmetric = false;
  130. {
  131. Mutex::Lock _l(_phy_m);
  132. Hashtable< PhySurfaceKey,PhySurfaceEntry >::Iterator i(_phy);
  133. PhySurfaceKey *k = (PhySurfaceKey *)0;
  134. PhySurfaceEntry *e = (PhySurfaceEntry *)0;
  135. InetAddress lastTrustedSurface;
  136. while (i.next(k,e)) {
  137. if ((e->mySurface.ss_family == AF_INET)&&(e->mySurface.ipScope() == InetAddress::IP_SCOPE_GLOBAL)) {
  138. std::set<InetAddress> &s = surfaces[k->receivedOnLocalAddress];
  139. /* MINOR SECURITY FIX:
  140. *
  141. * If the surface was not reported by a trusted (upstream) peer, we do
  142. * not use its report of our surface IP for symmetric NAT prediction.
  143. * Otherwise a peer could poison our external surface cache and then
  144. * use this to coax us into suggesting their IP as an endpoint. This
  145. * in turn could allow them to relay traffic for us. They could not
  146. * decrypt or otherwise mess with it, but they could DOS us or record
  147. * meta-data without anything appearing amiss.
  148. *
  149. * So for surfaces reported by untrusted peers we use the IP reported
  150. * by a trusted peer and then just use the port.
  151. *
  152. * As far as we know this has never been exploited. We discovered it
  153. * because certain weird configurations, such as load balancers and
  154. * gateways that do not preserve IP information, can coax a node into
  155. * reporting back false surface information. */
  156. if (e->trusted) {
  157. s.insert(e->mySurface);
  158. lastTrustedSurface = e->mySurface;
  159. } else if (lastTrustedSurface) {
  160. InetAddress tmp(lastTrustedSurface);
  161. tmp.setPort(e->mySurface.port());
  162. s.insert(tmp);
  163. }
  164. symmetric = symmetric||(s.size() > 1);
  165. }
  166. }
  167. }
  168. /* If we appear to be symmetrically NATed, generate and return extrapolations
  169. * of those surfaces. Since PUSH_DIRECT_PATHS is sent multiple times, we
  170. * probabilistically generate extrapolations of anywhere from +1 to +5 to
  171. * increase the odds that it will work "eventually". */
  172. if (symmetric) {
  173. std::vector<InetAddress> r;
  174. for(std::map< InetAddress,std::set<InetAddress> >::iterator si(surfaces.begin());si!=surfaces.end();++si) {
  175. for(std::set<InetAddress>::iterator i(si->second.begin());i!=si->second.end();++i) {
  176. InetAddress ipp(*i);
  177. unsigned int p = ipp.port() + 1 + ((unsigned int)RR->node->prng() & 3);
  178. if (p >= 65535)
  179. p -= 64510; // NATs seldom use ports <=1024 so wrap to 1025
  180. ipp.setPort(p);
  181. if ((si->second.count(ipp) == 0)&&(std::find(r.begin(),r.end(),ipp) == r.end())) {
  182. r.push_back(ipp);
  183. }
  184. }
  185. }
  186. return r;
  187. }
  188. return std::vector<InetAddress>();
  189. }
  190. } // namespace ZeroTier