2
0

Network.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468
  1. /*
  2. * ZeroTier One - Global Peer to Peer Ethernet
  3. * Copyright (C) 2012-2013 ZeroTier Networks LLC
  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 <algorithm>
  32. #include <utility>
  33. #include "Constants.hpp"
  34. #include "RuntimeEnvironment.hpp"
  35. #include "NodeConfig.hpp"
  36. #include "Network.hpp"
  37. #include "Switch.hpp"
  38. #include "Packet.hpp"
  39. #include "Utils.hpp"
  40. namespace ZeroTier {
  41. void Network::CertificateOfMembership::setQualifier(uint64_t id,uint64_t value,uint64_t maxDelta)
  42. {
  43. _signedBy.zero();
  44. for(std::vector<_Qualifier>::iterator q(_qualifiers.begin());q!=_qualifiers.end();++q) {
  45. if (q->id == id) {
  46. q->value = value;
  47. q->maxDelta = maxDelta;
  48. return;
  49. }
  50. }
  51. _qualifiers.push_back(_Qualifier(id,value,maxDelta));
  52. std::sort(_qualifiers.begin(),_qualifiers.end());
  53. }
  54. std::string Network::CertificateOfMembership::toString() const
  55. {
  56. std::string s;
  57. uint64_t *buf = new uint64_t[_qualifiers.size() * 3];
  58. try {
  59. unsigned int ptr = 0;
  60. for(std::vector<_Qualifier>::const_iterator q(_qualifiers.begin());q!=_qualifiers.end();++q) {
  61. buf[ptr++] = Utils::hton(q->id);
  62. buf[ptr++] = Utils::hton(q->value);
  63. buf[ptr++] = Utils::hton(q->maxDelta);
  64. }
  65. s.append(Utils::hex(buf,ptr * sizeof(uint64_t)));
  66. delete [] buf;
  67. } catch ( ... ) {
  68. delete [] buf;
  69. throw;
  70. }
  71. s.push_back(':');
  72. s.append(_signedBy.toString());
  73. if (_signedBy) {
  74. s.push_back(':');
  75. s.append(Utils::hex(_signature.data,_signature.size()));
  76. }
  77. return s;
  78. }
  79. void Network::CertificateOfMembership::fromString(const char *s)
  80. {
  81. _qualifiers.clear();
  82. _signedBy.zero();
  83. unsigned int colonAt = 0;
  84. while ((s[colonAt])&&(s[colonAt] != ':')) ++colonAt;
  85. if (colonAt) {
  86. unsigned int buflen = colonAt / 2;
  87. char *buf = new char[buflen];
  88. unsigned int bufactual = Utils::unhex(s,colonAt,buf,buflen);
  89. char *bufptr = buf;
  90. try {
  91. while (bufactual >= 24) {
  92. _qualifiers.push_back(_Qualifier());
  93. _qualifiers.back().id = Utils::ntoh(*((uint64_t *)bufptr)); bufptr += 8;
  94. _qualifiers.back().value = Utils::ntoh(*((uint64_t *)bufptr)); bufptr += 8;
  95. _qualifiers.back().maxDelta = Utils::ntoh(*((uint64_t *)bufptr)); bufptr += 8;
  96. bufactual -= 24;
  97. }
  98. } catch ( ... ) {}
  99. delete [] buf;
  100. }
  101. if (s[colonAt]) {
  102. s += colonAt + 1;
  103. colonAt = 0;
  104. while ((s[colonAt])&&(s[colonAt] != ':')) ++colonAt;
  105. if (colonAt) {
  106. char addrbuf[ZT_ADDRESS_LENGTH];
  107. if (Utils::unhex(s,colonAt,addrbuf,sizeof(addrbuf)) == ZT_ADDRESS_LENGTH)
  108. _signedBy.setTo(addrbuf,ZT_ADDRESS_LENGTH);
  109. if ((_signedBy)&&(s[colonAt])) {
  110. s += colonAt + 1;
  111. colonAt = 0;
  112. while ((s[colonAt])&&(s[colonAt] != ':')) ++colonAt;
  113. if (colonAt) {
  114. if (Utils::unhex(s,colonAt,_signature.data,_signature.size()) != _signature.size())
  115. _signedBy.zero();
  116. } else _signedBy.zero();
  117. } else _signedBy.zero();
  118. }
  119. }
  120. std::sort(_qualifiers.begin(),_qualifiers.end());
  121. std::unique(_qualifiers.begin(),_qualifiers.end());
  122. }
  123. bool Network::CertificateOfMembership::agreesWith(const CertificateOfMembership &other) const
  124. throw()
  125. {
  126. unsigned long myidx = 0;
  127. unsigned long otheridx = 0;
  128. while (myidx < _qualifiers.size()) {
  129. // Fail if we're at the end of other, since this means the field is
  130. // missing.
  131. if (otheridx >= other._qualifiers.size())
  132. return false;
  133. // Seek to corresponding tuple in other, ignoring tuples that
  134. // we may not have. If we run off the end of other, the tuple is
  135. // missing. This works because tuples are sorted by ID.
  136. while (other._qualifiers[otheridx].id != _qualifiers[myidx].id) {
  137. ++otheridx;
  138. if (otheridx >= other._qualifiers.size())
  139. return false;
  140. }
  141. // Compare to determine if the absolute value of the difference
  142. // between these two parameters is within our maxDelta.
  143. uint64_t a = _qualifiers[myidx].value;
  144. uint64_t b = other._qualifiers[myidx].value;
  145. if (a >= b) {
  146. if ((a - b) > _qualifiers[myidx].maxDelta)
  147. return false;
  148. } else {
  149. if ((b - a) > _qualifiers[myidx].maxDelta)
  150. return false;
  151. }
  152. ++myidx;
  153. }
  154. return true;
  155. }
  156. bool Network::CertificateOfMembership::sign(const Identity &with)
  157. {
  158. uint64_t *buf = new uint64_t[_qualifiers.size() * 3];
  159. unsigned int ptr = 0;
  160. for(std::vector<_Qualifier>::const_iterator q(_qualifiers.begin());q!=_qualifiers.end();++q) {
  161. buf[ptr++] = Utils::hton(q->id);
  162. buf[ptr++] = Utils::hton(q->value);
  163. buf[ptr++] = Utils::hton(q->maxDelta);
  164. }
  165. try {
  166. _signature = with.sign(buf,ptr * sizeof(uint64_t));
  167. _signedBy = with.address();
  168. delete [] buf;
  169. return true;
  170. } catch ( ... ) {
  171. _signedBy.zero();
  172. delete [] buf;
  173. return false;
  174. }
  175. }
  176. bool Network::CertificateOfMembership::verify(const Identity &id) const
  177. {
  178. if (!_signedBy)
  179. return false;
  180. if (id.address() != _signedBy)
  181. return false;
  182. uint64_t *buf = new uint64_t[_qualifiers.size() * 3];
  183. unsigned int ptr = 0;
  184. for(std::vector<_Qualifier>::const_iterator q(_qualifiers.begin());q!=_qualifiers.end();++q) {
  185. buf[ptr++] = Utils::hton(q->id);
  186. buf[ptr++] = Utils::hton(q->value);
  187. buf[ptr++] = Utils::hton(q->maxDelta);
  188. }
  189. bool valid = false;
  190. try {
  191. valid = id.verify(buf,ptr * sizeof(uint64_t),_signature);
  192. delete [] buf;
  193. } catch ( ... ) {
  194. delete [] buf;
  195. }
  196. return valid;
  197. }
  198. // ---------------------------------------------------------------------------
  199. const Network::MulticastRates::Rate Network::MulticastRates::GLOBAL_DEFAULT_RATE(65535,65535,64);
  200. const char *Network::statusString(const Status s)
  201. throw()
  202. {
  203. switch(s) {
  204. case NETWORK_WAITING_FOR_FIRST_AUTOCONF: return "WAITING_FOR_FIRST_AUTOCONF";
  205. case NETWORK_OK: return "OK";
  206. case NETWORK_ACCESS_DENIED: return "ACCESS_DENIED";
  207. }
  208. return "(invalid)";
  209. }
  210. Network::~Network()
  211. {
  212. delete _tap;
  213. if (_destroyOnDelete) {
  214. std::string confPath(_r->homePath + ZT_PATH_SEPARATOR_S + "networks.d" + ZT_PATH_SEPARATOR_S + idString() + ".conf");
  215. std::string mcdbPath(_r->homePath + ZT_PATH_SEPARATOR_S + "networks.d" + ZT_PATH_SEPARATOR_S + idString() + ".mcerts");
  216. Utils::rm(confPath);
  217. Utils::rm(mcdbPath);
  218. } else {
  219. // Causes flush of membership certs to disk
  220. clean();
  221. }
  222. }
  223. SharedPtr<Network> Network::newInstance(const RuntimeEnvironment *renv,uint64_t id)
  224. throw(std::runtime_error)
  225. {
  226. // Tag to identify tap device -- used on some OSes like Windows
  227. char tag[32];
  228. Utils::snprintf(tag,sizeof(tag),"%.16llx",(unsigned long long)id);
  229. // We construct Network via a static method to ensure that it is immediately
  230. // wrapped in a SharedPtr<>. Otherwise if there is traffic on the Ethernet
  231. // tap device, a SharedPtr<> wrap can occur in the Ethernet frame handler
  232. // that then causes the Network instance to be deleted before it is finished
  233. // being constructed. C++ edge cases, how I love thee.
  234. SharedPtr<Network> nw(new Network());
  235. nw->_ready = false; // disable handling of Ethernet frames during construct
  236. nw->_r = renv;
  237. nw->_tap = new EthernetTap(renv,tag,renv->identity.address().toMAC(),ZT_IF_MTU,&_CBhandleTapData,nw.ptr());
  238. nw->_isOpen = false;
  239. nw->_multicastPrefixBits = ZT_DEFAULT_MULTICAST_PREFIX_BITS;
  240. nw->_multicastDepth = ZT_DEFAULT_MULTICAST_DEPTH;
  241. memset(nw->_etWhitelist,0,sizeof(nw->_etWhitelist));
  242. nw->_id = id;
  243. nw->_lastConfigUpdate = 0;
  244. nw->_destroyOnDelete = false;
  245. if (nw->controller() == renv->identity.address()) // sanity check, this isn't supported for now
  246. throw std::runtime_error("cannot add a network for which I am the netconf master");
  247. nw->_restoreState();
  248. nw->_ready = true; // enable handling of Ethernet frames
  249. nw->requestConfiguration();
  250. return nw;
  251. }
  252. void Network::setConfiguration(const Network::Config &conf)
  253. {
  254. Mutex::Lock _l(_lock);
  255. try {
  256. if (conf.networkId() == _id) { // sanity check
  257. _configuration = conf;
  258. // Grab some things from conf for faster lookup and memoize them
  259. _myCertificate = conf.certificateOfMembership();
  260. _mcRates = conf.multicastRates();
  261. _staticAddresses = conf.staticAddresses();
  262. _isOpen = conf.isOpen();
  263. _multicastPrefixBits = conf.multicastPrefixBits();
  264. _multicastDepth = conf.multicastDepth();
  265. _lastConfigUpdate = Utils::now();
  266. _tap->setIps(_staticAddresses);
  267. _tap->setDisplayName((std::string("ZeroTier One [") + conf.name() + "]").c_str());
  268. // Expand ethertype whitelist into fast-lookup bit field
  269. memset(_etWhitelist,0,sizeof(_etWhitelist));
  270. std::set<unsigned int> wl(conf.etherTypes());
  271. for(std::set<unsigned int>::const_iterator t(wl.begin());t!=wl.end();++t)
  272. _etWhitelist[*t / 8] |= (unsigned char)(1 << (*t % 8));
  273. // Save most recent configuration to disk in networks.d
  274. std::string confPath(_r->homePath + ZT_PATH_SEPARATOR_S + "networks.d" + ZT_PATH_SEPARATOR_S + idString() + ".conf");
  275. if (!Utils::writeFile(confPath.c_str(),conf.toString())) {
  276. LOG("error: unable to write network configuration file at: %s",confPath.c_str());
  277. }
  278. }
  279. } catch ( ... ) {
  280. // If conf is invalid, reset everything
  281. _configuration = Config();
  282. _myCertificate = CertificateOfMembership();
  283. _mcRates = MulticastRates();
  284. _staticAddresses.clear();
  285. _isOpen = false;
  286. _lastConfigUpdate = 0;
  287. LOG("unexpected exception handling config for network %.16llx, retrying fetch...",(unsigned long long)_id);
  288. }
  289. }
  290. void Network::requestConfiguration()
  291. {
  292. if (controller() == _r->identity.address()) {
  293. // FIXME: Right now the netconf master cannot be a member of its own nets
  294. LOG("unable to request network configuration for network %.16llx: I am the network master, cannot query self",(unsigned long long)_id);
  295. return;
  296. }
  297. TRACE("requesting netconf for network %.16llx from netconf master %s",(unsigned long long)_id,controller().toString().c_str());
  298. Packet outp(controller(),_r->identity.address(),Packet::VERB_NETWORK_CONFIG_REQUEST);
  299. outp.append((uint64_t)_id);
  300. outp.append((uint16_t)0); // no meta-data
  301. _r->sw->send(outp,true);
  302. }
  303. void Network::addMembershipCertificate(const Address &peer,const CertificateOfMembership &cert)
  304. {
  305. Mutex::Lock _l(_lock);
  306. if (!_isOpen)
  307. _membershipCertificates[peer] = cert;
  308. }
  309. bool Network::isAllowed(const Address &peer) const
  310. {
  311. // Exceptions can occur if we do not yet have *our* configuration.
  312. try {
  313. Mutex::Lock _l(_lock);
  314. if (_isOpen)
  315. return true;
  316. std::map<Address,CertificateOfMembership>::const_iterator pc(_membershipCertificates.find(peer));
  317. if (pc == _membershipCertificates.end())
  318. return false;
  319. return _myCertificate.agreesWith(pc->second);
  320. } catch (std::exception &exc) {
  321. TRACE("isAllowed() check failed for peer %s: unexpected exception: %s",peer.toString().c_str(),exc.what());
  322. } catch ( ... ) {
  323. TRACE("isAllowed() check failed for peer %s: unexpected exception: unknown exception",peer.toString().c_str());
  324. }
  325. return false;
  326. }
  327. void Network::clean()
  328. {
  329. std::string mcdbPath(_r->homePath + ZT_PATH_SEPARATOR_S + "networks.d" + ZT_PATH_SEPARATOR_S + idString() + ".mcerts");
  330. Mutex::Lock _l(_lock);
  331. if ((!_id)||(_isOpen)) {
  332. _membershipCertificates.clear();
  333. Utils::rm(mcdbPath);
  334. } else {
  335. FILE *mcdb = fopen(mcdbPath.c_str(),"wb");
  336. bool writeError = false;
  337. if (!mcdb) {
  338. LOG("error: unable to open membership cert database at: %s",mcdbPath.c_str());
  339. } else {
  340. if ((writeError)||(fwrite("MCDB0",5,1,mcdb) != 1)) // version
  341. writeError = true;
  342. }
  343. for(std::map<Address,CertificateOfMembership>::iterator i=(_membershipCertificates.begin());i!=_membershipCertificates.end();) {
  344. if (_myCertificate.agreesWith(i->second)) {
  345. if ((!writeError)&&(mcdb)) {
  346. char tmp[ZT_ADDRESS_LENGTH];
  347. i->first.copyTo(tmp,ZT_ADDRESS_LENGTH);
  348. if ((writeError)||(fwrite(tmp,ZT_ADDRESS_LENGTH,1,mcdb) != 1))
  349. writeError = true;
  350. std::string c(i->second.toString());
  351. uint32_t cl = Utils::hton((uint32_t)c.length());
  352. if ((writeError)||(fwrite(&cl,sizeof(cl),1,mcdb) != 1))
  353. writeError = true;
  354. if ((writeError)||(fwrite(c.data(),c.length(),1,mcdb) != 1))
  355. writeError = true;
  356. }
  357. ++i;
  358. } else _membershipCertificates.erase(i++);
  359. }
  360. if (mcdb)
  361. fclose(mcdb);
  362. if (writeError) {
  363. Utils::rm(mcdbPath);
  364. LOG("error: unable to write to membership cert database at: %s",mcdbPath.c_str());
  365. }
  366. }
  367. }
  368. Network::Status Network::status() const
  369. {
  370. Mutex::Lock _l(_lock);
  371. if (_configuration)
  372. return NETWORK_OK;
  373. return NETWORK_WAITING_FOR_FIRST_AUTOCONF;
  374. }
  375. void Network::_CBhandleTapData(void *arg,const MAC &from,const MAC &to,unsigned int etherType,const Buffer<4096> &data)
  376. {
  377. if (!((Network *)arg)->_ready)
  378. return;
  379. const RuntimeEnvironment *_r = ((Network *)arg)->_r;
  380. if (_r->shutdownInProgress)
  381. return;
  382. try {
  383. _r->sw->onLocalEthernet(SharedPtr<Network>((Network *)arg),from,to,etherType,data);
  384. } catch (std::exception &exc) {
  385. TRACE("unexpected exception handling local packet: %s",exc.what());
  386. } catch ( ... ) {
  387. TRACE("unexpected exception handling local packet");
  388. }
  389. }
  390. void Network::_restoreState()
  391. {
  392. std::string confPath(_r->homePath + ZT_PATH_SEPARATOR_S + "networks.d" + ZT_PATH_SEPARATOR_S + idString() + ".conf");
  393. std::string confs;
  394. if (Utils::readFile(confPath.c_str(),confs)) {
  395. try {
  396. if (confs.length())
  397. setConfiguration(Config(confs));
  398. } catch ( ... ) {} // ignore invalid config on disk, we will re-request
  399. } else {
  400. // If the conf file isn't present, "touch" it so we'll remember
  401. // the existence of this network.
  402. FILE *tmp = fopen(confPath.c_str(),"w");
  403. if (tmp)
  404. fclose(tmp);
  405. }
  406. // TODO: restore membership certs
  407. }
  408. } // namespace ZeroTier