Network.cpp 16 KB

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