Network.cpp 14 KB

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