Network.cpp 17 KB

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