Network.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443
  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. if (_destroyed) {
  93. char n[128];
  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. _dumpMembershipCerts();
  101. }
  102. }
  103. // Function object used by rescanMulticastGroups()
  104. class AnnounceMulticastGroupsToPeersWithActiveDirectPaths
  105. {
  106. public:
  107. AnnounceMulticastGroupsToPeersWithActiveDirectPaths(const RuntimeEnvironment *renv,Network *nw) :
  108. RR(renv),
  109. _now(Utils::now()),
  110. _network(nw),
  111. _supernodeAddresses(renv->topology->supernodeAddresses())
  112. {}
  113. inline void operator()(Topology &t,const SharedPtr<Peer> &p)
  114. {
  115. if ( ( (p->hasActiveDirectPath(_now)) && (_network->isAllowed(p->address())) ) || (std::find(_supernodeAddresses.begin(),_supernodeAddresses.end(),p->address()) != _supernodeAddresses.end()) ) {
  116. Packet outp(p->address(),RR->identity.address(),Packet::VERB_MULTICAST_LIKE);
  117. std::set<MulticastGroup> mgs(_network->multicastGroups());
  118. for(std::set<MulticastGroup>::iterator mg(mgs.begin());mg!=mgs.end();++mg) {
  119. if ((outp.size() + 18) > ZT_UDP_DEFAULT_PAYLOAD_MTU) {
  120. outp.armor(p->key(),true);
  121. p->send(RR,outp.data(),outp.size(),_now);
  122. outp.reset(p->address(),RR->identity.address(),Packet::VERB_MULTICAST_LIKE);
  123. }
  124. // network ID, MAC, ADI
  125. outp.append((uint64_t)_network->id());
  126. mg->mac().appendTo(outp);
  127. outp.append((uint32_t)mg->adi());
  128. }
  129. if (outp.size() > ZT_PROTO_MIN_PACKET_LENGTH) {
  130. outp.armor(p->key(),true);
  131. p->send(RR,outp.data(),outp.size(),_now);
  132. }
  133. }
  134. }
  135. private:
  136. const RuntimeEnvironment *RR;
  137. uint64_t _now;
  138. Network *_network;
  139. std::vector<Address> _supernodeAddresses;
  140. };
  141. bool Network::applyConfiguration(const SharedPtr<NetworkConfig> &conf)
  142. {
  143. Mutex::Lock _l(_lock);
  144. if (_destroyed)
  145. return false;
  146. try {
  147. if ((conf->networkId() == _id)&&(conf->issuedTo() == RR->identity.address())) {
  148. _config = conf;
  149. _lastConfigUpdate = RR->node->now();
  150. _netconfFailure = NETCONF_FAILURE_NONE;
  151. return true;
  152. } else {
  153. LOG("ignored invalid configuration for network %.16llx (configuration contains mismatched network ID or issued-to address)",(unsigned long long)_id);
  154. }
  155. } catch (std::exception &exc) {
  156. LOG("ignored invalid configuration for network %.16llx (%s)",(unsigned long long)_id,exc.what());
  157. } catch ( ... ) {
  158. LOG("ignored invalid configuration for network %.16llx (unknown exception)",(unsigned long long)_id);
  159. }
  160. return false;
  161. }
  162. int Network::setConfiguration(const Dictionary &conf,bool saveToDisk)
  163. {
  164. try {
  165. SharedPtr<NetworkConfig> newConfig(new NetworkConfig(conf)); // throws if invalid
  166. {
  167. Mutex::Lock _l(_lock);
  168. if ((_config)&&(*_config == *newConfig))
  169. return 1; // OK config, but duplicate of what we already have
  170. }
  171. if (applyConfiguration(newConfig)) {
  172. if (saveToDisk) {
  173. char n[128];
  174. Utils::snprintf(n,sizeof(n),"networks.d/%.16llx.conf",_id);
  175. RR->node->dataStorePut(n,conf.toString(),true);
  176. }
  177. return 2; // OK and configuration has changed
  178. }
  179. } catch ( ... ) {
  180. LOG("ignored invalid configuration for network %.16llx (dictionary decode failed)",(unsigned long long)_id);
  181. }
  182. return 0;
  183. }
  184. void Network::requestConfiguration()
  185. {
  186. if (_id == ZT_TEST_NETWORK_ID) // pseudo-network-ID, no netconf master
  187. return;
  188. if (controller() == RR->identity.address()) {
  189. if (RR->netconfMaster) {
  190. SharedPtr<NetworkConfig> nconf(config2());
  191. Dictionary newconf;
  192. switch(RR->netconfMaster->doNetworkConfigRequest(InetAddress(),RR->identity,_id,Dictionary(),(nconf) ? nconf->revision() : (uint64_t)0,newconf)) {
  193. case NetworkConfigMaster::NETCONF_QUERY_OK:
  194. this->setConfiguration(newconf,true);
  195. return;
  196. case NetworkConfigMaster::NETCONF_QUERY_OBJECT_NOT_FOUND:
  197. this->setNotFound();
  198. return;
  199. case NetworkConfigMaster::NETCONF_QUERY_ACCESS_DENIED:
  200. this->setAccessDenied();
  201. return;
  202. default:
  203. return;
  204. }
  205. } else {
  206. this->setNotFound();
  207. return;
  208. }
  209. }
  210. TRACE("requesting netconf for network %.16llx from netconf master %s",(unsigned long long)_id,controller().toString().c_str());
  211. Packet outp(controller(),RR->identity.address(),Packet::VERB_NETWORK_CONFIG_REQUEST);
  212. outp.append((uint64_t)_id);
  213. outp.append((uint16_t)0); // no meta-data
  214. {
  215. Mutex::Lock _l(_lock);
  216. if (_config)
  217. outp.append((uint64_t)_config->revision());
  218. else outp.append((uint64_t)0);
  219. }
  220. RR->sw->send(outp,true);
  221. }
  222. void Network::addMembershipCertificate(const CertificateOfMembership &cert,bool forceAccept)
  223. {
  224. if (!cert) // sanity check
  225. return;
  226. Mutex::Lock _l(_lock);
  227. CertificateOfMembership &old = _membershipCertificates[cert.issuedTo()];
  228. // Nothing to do if the cert hasn't changed -- we get duplicates due to zealous cert pushing
  229. if (old == cert)
  230. return;
  231. // Check signature, log and return if cert is invalid
  232. if (!forceAccept) {
  233. if (cert.signedBy() != controller()) {
  234. 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());
  235. return;
  236. }
  237. SharedPtr<Peer> signer(RR->topology->getPeer(cert.signedBy()));
  238. if (!signer) {
  239. // This would be rather odd, since this is our netconf master... could happen
  240. // if we get packets before we've gotten config.
  241. RR->sw->requestWhois(cert.signedBy());
  242. return;
  243. }
  244. if (!cert.verify(signer->identity())) {
  245. LOG("rejected network membership certificate for %.16llx signed by %s: signature check failed",(unsigned long long)_id,cert.signedBy().toString().c_str());
  246. return;
  247. }
  248. }
  249. // If we made it past authentication, update cert
  250. if (cert.revision() != old.revision())
  251. old = cert;
  252. }
  253. bool Network::peerNeedsOurMembershipCertificate(const Address &to,uint64_t now)
  254. {
  255. Mutex::Lock _l(_lock);
  256. if ((_config)&&(!_config->isPublic())&&(_config->com())) {
  257. uint64_t &lastPushed = _lastPushedMembershipCertificate[to];
  258. if ((now - lastPushed) > (ZT_NETWORK_AUTOCONF_DELAY / 2)) {
  259. lastPushed = now;
  260. return true;
  261. }
  262. }
  263. return false;
  264. }
  265. bool Network::isAllowed(const Address &peer) const
  266. {
  267. try {
  268. Mutex::Lock _l(_lock);
  269. if (!_config)
  270. return false;
  271. if (_config->isPublic())
  272. return true;
  273. std::map<Address,CertificateOfMembership>::const_iterator pc(_membershipCertificates.find(peer));
  274. if (pc == _membershipCertificates.end())
  275. return false; // no certificate on file
  276. return _config->com().agreesWith(pc->second); // is other cert valid against ours?
  277. } catch (std::exception &exc) {
  278. TRACE("isAllowed() check failed for peer %s: unexpected exception: %s",peer.toString().c_str(),exc.what());
  279. } catch ( ... ) {
  280. TRACE("isAllowed() check failed for peer %s: unexpected exception: unknown exception",peer.toString().c_str());
  281. }
  282. return false; // default position on any failure
  283. }
  284. void Network::clean()
  285. {
  286. uint64_t now = Utils::now();
  287. Mutex::Lock _l(_lock);
  288. if (_destroyed)
  289. return;
  290. if ((_config)&&(_config->isPublic())) {
  291. // Open (public) networks do not track certs or cert pushes at all.
  292. _membershipCertificates.clear();
  293. _lastPushedMembershipCertificate.clear();
  294. } else if (_config) {
  295. // Clean certificates that are no longer valid from the cache.
  296. for(std::map<Address,CertificateOfMembership>::iterator c=(_membershipCertificates.begin());c!=_membershipCertificates.end();) {
  297. if (_config->com().agreesWith(c->second))
  298. ++c;
  299. else _membershipCertificates.erase(c++);
  300. }
  301. // Clean entries from the last pushed tracking map if they're so old as
  302. // to be no longer relevant.
  303. uint64_t forgetIfBefore = now - (ZT_PEER_ACTIVITY_TIMEOUT * 16); // arbitrary reasonable cutoff
  304. for(std::map<Address,uint64_t>::iterator lp(_lastPushedMembershipCertificate.begin());lp!=_lastPushedMembershipCertificate.end();) {
  305. if (lp->second < forgetIfBefore)
  306. _lastPushedMembershipCertificate.erase(lp++);
  307. else ++lp;
  308. }
  309. }
  310. // Clean learned multicast groups if we haven't heard from them in a while
  311. for(std::map<MulticastGroup,uint64_t>::iterator mg(_multicastGroupsBehindMe.begin());mg!=_multicastGroupsBehindMe.end();) {
  312. if ((now - mg->second) > (ZT_MULTICAST_LIKE_EXPIRE * 2))
  313. _multicastGroupsBehindMe.erase(mg++);
  314. else ++mg;
  315. }
  316. }
  317. Network::Status Network::status() const
  318. {
  319. Mutex::Lock _l(_lock);
  320. switch(_netconfFailure) {
  321. case NETCONF_FAILURE_ACCESS_DENIED:
  322. return NETWORK_ACCESS_DENIED;
  323. case NETCONF_FAILURE_NOT_FOUND:
  324. return NETWORK_NOT_FOUND;
  325. case NETCONF_FAILURE_NONE:
  326. return ((_lastConfigUpdate > 0) ? ((_tap) ? NETWORK_OK : NETWORK_INITIALIZING) : NETWORK_WAITING_FOR_FIRST_AUTOCONF);
  327. //case NETCONF_FAILURE_INIT_FAILED:
  328. default:
  329. return NETWORK_INITIALIZATION_FAILED;
  330. }
  331. }
  332. void Network::learnBridgeRoute(const MAC &mac,const Address &addr)
  333. {
  334. Mutex::Lock _l(_lock);
  335. _remoteBridgeRoutes[mac] = addr;
  336. // If _remoteBridgeRoutes exceeds sanity limit, trim worst offenders until below -- denial of service circuit breaker
  337. while (_remoteBridgeRoutes.size() > ZT_MAX_BRIDGE_ROUTES) {
  338. std::map<Address,unsigned long> counts;
  339. Address maxAddr;
  340. unsigned long maxCount = 0;
  341. for(std::map<MAC,Address>::iterator br(_remoteBridgeRoutes.begin());br!=_remoteBridgeRoutes.end();++br) {
  342. unsigned long c = ++counts[br->second];
  343. if (c > maxCount) {
  344. maxCount = c;
  345. maxAddr = br->second;
  346. }
  347. }
  348. for(std::map<MAC,Address>::iterator br(_remoteBridgeRoutes.begin());br!=_remoteBridgeRoutes.end();) {
  349. if (br->second == maxAddr)
  350. _remoteBridgeRoutes.erase(br++);
  351. else ++br;
  352. }
  353. }
  354. }
  355. void Network::setEnabled(bool enabled)
  356. {
  357. Mutex::Lock _l(_lock);
  358. _enabled = enabled;
  359. if (_tap)
  360. _tap->setEnabled(enabled);
  361. }
  362. void Network::destroy()
  363. {
  364. Mutex::Lock _l(_lock);
  365. _enabled = false;
  366. _destroyed = true;
  367. if (_setupThread)
  368. Thread::join(_setupThread);
  369. _setupThread = Thread();
  370. if (_tap)
  371. RR->tapFactory->close(_tap,true);
  372. _tap = (EthernetTap *)0;
  373. }
  374. void Network::_dumpMembershipCerts()
  375. {
  376. char n[128];
  377. std::string buf("ZTMCD0");
  378. Utils::snprintf(n,sizeof(n),"networks.d/%.16llx.mcerts",_id);
  379. Mutex::Lock _l(_lock);
  380. if ((!_config)||(_config.isPublic())||(_membershipCertificates.size() == 0)) {
  381. RR->node->dataStoreDelete(n);
  382. return;
  383. }
  384. for(std::map<Address,CertificateOfMembership>::iterator c(_membershipCertificates.begin());c!=_membershipCertificates.end();++c)
  385. c->second.serialize2(buf);
  386. RR->node->dataStorePut(n,buf,true);
  387. }
  388. } // namespace ZeroTier