Network.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436
  1. /*
  2. * ZeroTier One - Network Virtualization Everywhere
  3. * Copyright (C) 2011-2015 ZeroTier, Inc.
  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. * --
  19. *
  20. * ZeroTier may be used and distributed under the terms of the GPLv3, which
  21. * are available at: http://www.gnu.org/licenses/gpl-3.0.html
  22. *
  23. * If you would like to embed ZeroTier into a commercial application or
  24. * redistribute it in a modified binary form, please contact ZeroTier Networks
  25. * LLC. Start here: http://www.zerotier.com/
  26. */
  27. #include <stdio.h>
  28. #include <string.h>
  29. #include <stdlib.h>
  30. #include <math.h>
  31. #include "Constants.hpp"
  32. #include "Network.hpp"
  33. #include "RuntimeEnvironment.hpp"
  34. #include "Switch.hpp"
  35. #include "Packet.hpp"
  36. #include "Buffer.hpp"
  37. #include "NetworkConfigMaster.hpp"
  38. namespace ZeroTier {
  39. const ZeroTier::MulticastGroup Network::BROADCAST(ZeroTier::MAC(0xff),0);
  40. Network::Network(const RuntimeEnvironment *renv,uint64_t nwid) :
  41. RR(renv),
  42. _id(nwid),
  43. _mac(renv->identity.address(),nwid),
  44. _enabled(true),
  45. _lastConfigUpdate(0),
  46. _destroyed(false),
  47. _netconfFailure(NETCONF_FAILURE_NONE)
  48. {
  49. char confn[128],mcdbn[128];
  50. Utils::snprintf(confn,sizeof(confn),"networks.d/%.16llx.conf",_id);
  51. Utils::snprintf(mcdbn,sizeof(mcdbn),"networks.d/%.16llx.mcerts",_id);
  52. if (_id == ZT_TEST_NETWORK_ID) {
  53. applyConfiguration(NetworkConfig::createTestNetworkConfig(RR->identity.address()));
  54. // Save a one-byte CR to persist membership in the test network
  55. RR->node->dataStorePut(confn,"\n",1,false);
  56. } else {
  57. bool gotConf = false;
  58. try {
  59. std::string conf(RR->node->dataStoreGet(confn));
  60. if (conf.length()) {
  61. setConfiguration(Dictionary(conf),false);
  62. gotConf = true;
  63. }
  64. } catch ( ... ) {} // ignore invalids, we'll re-request
  65. if (!gotConf) {
  66. // Save a one-byte CR to persist membership while we request a real netconf
  67. RR->node->dataStorePut(confn,"\n",1,false);
  68. }
  69. try {
  70. std::string mcdb(RR->node->dataStoreGet(mcdbn));
  71. if (mcdb.length() > 6) {
  72. const char *p = mcdb.data();
  73. const char *e = p + mcdb.length();
  74. if (!memcmp("ZTMCD0",p,6)) {
  75. p += 6;
  76. Mutex::Lock _l(_lock);
  77. while (p != e) {
  78. CertificateOfMembership com;
  79. com.deserialize2(p,e);
  80. if (!com)
  81. break;
  82. _membershipCertificates.insert(std::pair< Address,CertificateOfMembership >(com.issuedTo(),com));
  83. }
  84. }
  85. }
  86. } catch ( ... ) {} // ignore invalid MCDB, we'll re-learn from peers
  87. }
  88. requestConfiguration();
  89. }
  90. Network::~Network()
  91. {
  92. char n[128];
  93. if (_destroyed) {
  94. Utils::snprintf(n,sizeof(n),"networks.d/%.16llx.conf",_id);
  95. RR->node->dataStoreDelete(n);
  96. Utils::snprintf(n,sizeof(n),"networks.d/%.16llx.mcerts",_id);
  97. RR->node->dataStoreDelete(n);
  98. } else {
  99. clean();
  100. std::string buf("ZTMCD0");
  101. Utils::snprintf(n,sizeof(n),"networks.d/%.16llx.mcerts",_id);
  102. Mutex::Lock _l(_lock);
  103. if ((!_config)||(_config.isPublic())||(_membershipCertificates.size() == 0)) {
  104. RR->node->dataStoreDelete(n);
  105. return;
  106. }
  107. for(std::map<Address,CertificateOfMembership>::iterator c(_membershipCertificates.begin());c!=_membershipCertificates.end();++c)
  108. c->second.serialize2(buf);
  109. RR->node->dataStorePut(n,buf,true);
  110. }
  111. }
  112. // Function object used by rescanMulticastGroups()
  113. class AnnounceMulticastGroupsToPeersWithActiveDirectPaths
  114. {
  115. public:
  116. AnnounceMulticastGroupsToPeersWithActiveDirectPaths(const RuntimeEnvironment *renv,Network *nw) :
  117. RR(renv),
  118. _now(Utils::now()),
  119. _network(nw),
  120. _supernodeAddresses(renv->topology->supernodeAddresses())
  121. {}
  122. inline void operator()(Topology &t,const SharedPtr<Peer> &p)
  123. {
  124. if ( ( (p->hasActiveDirectPath(_now)) && (_network->isAllowed(p->address())) ) || (std::find(_supernodeAddresses.begin(),_supernodeAddresses.end(),p->address()) != _supernodeAddresses.end()) ) {
  125. Packet outp(p->address(),RR->identity.address(),Packet::VERB_MULTICAST_LIKE);
  126. std::set<MulticastGroup> mgs(_network->multicastGroups());
  127. for(std::set<MulticastGroup>::iterator mg(mgs.begin());mg!=mgs.end();++mg) {
  128. if ((outp.size() + 18) > ZT_UDP_DEFAULT_PAYLOAD_MTU) {
  129. outp.armor(p->key(),true);
  130. p->send(RR,outp.data(),outp.size(),_now);
  131. outp.reset(p->address(),RR->identity.address(),Packet::VERB_MULTICAST_LIKE);
  132. }
  133. // network ID, MAC, ADI
  134. outp.append((uint64_t)_network->id());
  135. mg->mac().appendTo(outp);
  136. outp.append((uint32_t)mg->adi());
  137. }
  138. if (outp.size() > ZT_PROTO_MIN_PACKET_LENGTH) {
  139. outp.armor(p->key(),true);
  140. p->send(RR,outp.data(),outp.size(),_now);
  141. }
  142. }
  143. }
  144. private:
  145. const RuntimeEnvironment *RR;
  146. uint64_t _now;
  147. Network *_network;
  148. std::vector<Address> _supernodeAddresses;
  149. };
  150. bool Network::applyConfiguration(const SharedPtr<NetworkConfig> &conf)
  151. {
  152. Mutex::Lock _l(_lock);
  153. if (_destroyed)
  154. return false;
  155. try {
  156. if ((conf->networkId() == _id)&&(conf->issuedTo() == RR->identity.address())) {
  157. _config = conf;
  158. _lastConfigUpdate = RR->node->now();
  159. _netconfFailure = NETCONF_FAILURE_NONE;
  160. return true;
  161. } else {
  162. LOG("ignored invalid configuration for network %.16llx (configuration contains mismatched network ID or issued-to address)",(unsigned long long)_id);
  163. }
  164. } catch (std::exception &exc) {
  165. LOG("ignored invalid configuration for network %.16llx (%s)",(unsigned long long)_id,exc.what());
  166. } catch ( ... ) {
  167. LOG("ignored invalid configuration for network %.16llx (unknown exception)",(unsigned long long)_id);
  168. }
  169. return false;
  170. }
  171. int Network::setConfiguration(const Dictionary &conf,bool saveToDisk)
  172. {
  173. try {
  174. SharedPtr<NetworkConfig> newConfig(new NetworkConfig(conf)); // throws if invalid
  175. {
  176. Mutex::Lock _l(_lock);
  177. if ((_config)&&(*_config == *newConfig))
  178. return 1; // OK config, but duplicate of what we already have
  179. }
  180. if (applyConfiguration(newConfig)) {
  181. if (saveToDisk) {
  182. char n[128];
  183. Utils::snprintf(n,sizeof(n),"networks.d/%.16llx.conf",_id);
  184. RR->node->dataStorePut(n,conf.toString(),true);
  185. }
  186. return 2; // OK and configuration has changed
  187. }
  188. } catch ( ... ) {
  189. LOG("ignored invalid configuration for network %.16llx (dictionary decode failed)",(unsigned long long)_id);
  190. }
  191. return 0;
  192. }
  193. void Network::requestConfiguration()
  194. {
  195. if (_id == ZT_TEST_NETWORK_ID) // pseudo-network-ID, no netconf master
  196. return;
  197. if (controller() == RR->identity.address()) {
  198. if (RR->netconfMaster) {
  199. SharedPtr<NetworkConfig> nconf(config2());
  200. Dictionary newconf;
  201. switch(RR->netconfMaster->doNetworkConfigRequest(InetAddress(),RR->identity,_id,Dictionary(),(nconf) ? nconf->revision() : (uint64_t)0,newconf)) {
  202. case NetworkConfigMaster::NETCONF_QUERY_OK:
  203. this->setConfiguration(newconf,true);
  204. return;
  205. case NetworkConfigMaster::NETCONF_QUERY_OBJECT_NOT_FOUND:
  206. this->setNotFound();
  207. return;
  208. case NetworkConfigMaster::NETCONF_QUERY_ACCESS_DENIED:
  209. this->setAccessDenied();
  210. return;
  211. default:
  212. return;
  213. }
  214. } else {
  215. this->setNotFound();
  216. return;
  217. }
  218. }
  219. TRACE("requesting netconf for network %.16llx from netconf master %s",(unsigned long long)_id,controller().toString().c_str());
  220. Packet outp(controller(),RR->identity.address(),Packet::VERB_NETWORK_CONFIG_REQUEST);
  221. outp.append((uint64_t)_id);
  222. outp.append((uint16_t)0); // no meta-data
  223. {
  224. Mutex::Lock _l(_lock);
  225. if (_config)
  226. outp.append((uint64_t)_config->revision());
  227. else outp.append((uint64_t)0);
  228. }
  229. RR->sw->send(outp,true);
  230. }
  231. void Network::addMembershipCertificate(const CertificateOfMembership &cert,bool forceAccept)
  232. {
  233. if (!cert) // sanity check
  234. return;
  235. Mutex::Lock _l(_lock);
  236. CertificateOfMembership &old = _membershipCertificates[cert.issuedTo()];
  237. // Nothing to do if the cert hasn't changed -- we get duplicates due to zealous cert pushing
  238. if (old == cert)
  239. return;
  240. // Check signature, log and return if cert is invalid
  241. if (!forceAccept) {
  242. if (cert.signedBy() != controller()) {
  243. LOG("rejected network membership certificate for %.16llx signed by %s: signer not a controller of this network",(unsigned long long)_id,cert.signedBy().toString().c_str());
  244. return;
  245. }
  246. SharedPtr<Peer> signer(RR->topology->getPeer(cert.signedBy()));
  247. if (!signer) {
  248. // This would be rather odd, since this is our netconf master... could happen
  249. // if we get packets before we've gotten config.
  250. RR->sw->requestWhois(cert.signedBy());
  251. return;
  252. }
  253. if (!cert.verify(signer->identity())) {
  254. LOG("rejected network membership certificate for %.16llx signed by %s: signature check failed",(unsigned long long)_id,cert.signedBy().toString().c_str());
  255. return;
  256. }
  257. }
  258. // If we made it past authentication, update cert
  259. if (cert.revision() != old.revision())
  260. old = cert;
  261. }
  262. bool Network::peerNeedsOurMembershipCertificate(const Address &to,uint64_t now)
  263. {
  264. Mutex::Lock _l(_lock);
  265. if ((_config)&&(!_config->isPublic())&&(_config->com())) {
  266. uint64_t &lastPushed = _lastPushedMembershipCertificate[to];
  267. if ((now - lastPushed) > (ZT_NETWORK_AUTOCONF_DELAY / 2)) {
  268. lastPushed = now;
  269. return true;
  270. }
  271. }
  272. return false;
  273. }
  274. bool Network::isAllowed(const Address &peer) const
  275. {
  276. try {
  277. Mutex::Lock _l(_lock);
  278. if (!_config)
  279. return false;
  280. if (_config->isPublic())
  281. return true;
  282. std::map<Address,CertificateOfMembership>::const_iterator pc(_membershipCertificates.find(peer));
  283. if (pc == _membershipCertificates.end())
  284. return false; // no certificate on file
  285. return _config->com().agreesWith(pc->second); // is other cert valid against ours?
  286. } catch (std::exception &exc) {
  287. TRACE("isAllowed() check failed for peer %s: unexpected exception: %s",peer.toString().c_str(),exc.what());
  288. } catch ( ... ) {
  289. TRACE("isAllowed() check failed for peer %s: unexpected exception: unknown exception",peer.toString().c_str());
  290. }
  291. return false; // default position on any failure
  292. }
  293. void Network::clean()
  294. {
  295. uint64_t now = Utils::now();
  296. Mutex::Lock _l(_lock);
  297. if (_destroyed)
  298. return;
  299. if ((_config)&&(_config->isPublic())) {
  300. // Open (public) networks do not track certs or cert pushes at all.
  301. _membershipCertificates.clear();
  302. _lastPushedMembershipCertificate.clear();
  303. } else if (_config) {
  304. // Clean certificates that are no longer valid from the cache.
  305. for(std::map<Address,CertificateOfMembership>::iterator c=(_membershipCertificates.begin());c!=_membershipCertificates.end();) {
  306. if (_config->com().agreesWith(c->second))
  307. ++c;
  308. else _membershipCertificates.erase(c++);
  309. }
  310. // Clean entries from the last pushed tracking map if they're so old as
  311. // to be no longer relevant.
  312. uint64_t forgetIfBefore = now - (ZT_PEER_ACTIVITY_TIMEOUT * 16); // arbitrary reasonable cutoff
  313. for(std::map<Address,uint64_t>::iterator lp(_lastPushedMembershipCertificate.begin());lp!=_lastPushedMembershipCertificate.end();) {
  314. if (lp->second < forgetIfBefore)
  315. _lastPushedMembershipCertificate.erase(lp++);
  316. else ++lp;
  317. }
  318. }
  319. // Clean learned multicast groups if we haven't heard from them in a while
  320. for(std::map<MulticastGroup,uint64_t>::iterator mg(_multicastGroupsBehindMe.begin());mg!=_multicastGroupsBehindMe.end();) {
  321. if ((now - mg->second) > (ZT_MULTICAST_LIKE_EXPIRE * 2))
  322. _multicastGroupsBehindMe.erase(mg++);
  323. else ++mg;
  324. }
  325. }
  326. Network::Status Network::status() const
  327. {
  328. Mutex::Lock _l(_lock);
  329. switch(_netconfFailure) {
  330. case NETCONF_FAILURE_ACCESS_DENIED:
  331. return NETWORK_ACCESS_DENIED;
  332. case NETCONF_FAILURE_NOT_FOUND:
  333. return NETWORK_NOT_FOUND;
  334. case NETCONF_FAILURE_NONE:
  335. return ((_lastConfigUpdate > 0) ? ((_tap) ? NETWORK_OK : NETWORK_INITIALIZING) : NETWORK_WAITING_FOR_FIRST_AUTOCONF);
  336. //case NETCONF_FAILURE_INIT_FAILED:
  337. default:
  338. return NETWORK_INITIALIZATION_FAILED;
  339. }
  340. }
  341. void Network::learnBridgeRoute(const MAC &mac,const Address &addr)
  342. {
  343. Mutex::Lock _l(_lock);
  344. _remoteBridgeRoutes[mac] = addr;
  345. // If _remoteBridgeRoutes exceeds sanity limit, trim worst offenders until below -- denial of service circuit breaker
  346. while (_remoteBridgeRoutes.size() > ZT_MAX_BRIDGE_ROUTES) {
  347. std::map<Address,unsigned long> counts;
  348. Address maxAddr;
  349. unsigned long maxCount = 0;
  350. for(std::map<MAC,Address>::iterator br(_remoteBridgeRoutes.begin());br!=_remoteBridgeRoutes.end();++br) {
  351. unsigned long c = ++counts[br->second];
  352. if (c > maxCount) {
  353. maxCount = c;
  354. maxAddr = br->second;
  355. }
  356. }
  357. for(std::map<MAC,Address>::iterator br(_remoteBridgeRoutes.begin());br!=_remoteBridgeRoutes.end();) {
  358. if (br->second == maxAddr)
  359. _remoteBridgeRoutes.erase(br++);
  360. else ++br;
  361. }
  362. }
  363. }
  364. void Network::setEnabled(bool enabled)
  365. {
  366. Mutex::Lock _l(_lock);
  367. _enabled = enabled;
  368. if (_tap)
  369. _tap->setEnabled(enabled);
  370. }
  371. void Network::destroy()
  372. {
  373. Mutex::Lock _l(_lock);
  374. _enabled = false;
  375. _destroyed = true;
  376. if (_setupThread)
  377. Thread::join(_setupThread);
  378. _setupThread = Thread();
  379. if (_tap)
  380. RR->tapFactory->close(_tap,true);
  381. _tap = (EthernetTap *)0;
  382. }
  383. } // namespace ZeroTier