Network.cpp 15 KB

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