Network.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322
  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 <openssl/sha.h>
  32. #include "RuntimeEnvironment.hpp"
  33. #include "NodeConfig.hpp"
  34. #include "Network.hpp"
  35. #include "Switch.hpp"
  36. #include "Packet.hpp"
  37. #include "Utils.hpp"
  38. namespace ZeroTier {
  39. void Network::Certificate::_shaForSignature(unsigned char *dig) const
  40. {
  41. SHA256_CTX sha;
  42. SHA256_Init(&sha);
  43. unsigned char zero = 0;
  44. for(const_iterator i(begin());i!=end();++i) {
  45. SHA256_Update(&sha,&zero,1);
  46. SHA256_Update(&sha,(const unsigned char *)i->first.data(),i->first.length());
  47. SHA256_Update(&sha,&zero,1);
  48. SHA256_Update(&sha,(const unsigned char *)i->second.data(),i->second.length());
  49. SHA256_Update(&sha,&zero,1);
  50. }
  51. SHA256_Final(dig,&sha);
  52. }
  53. static const std::string _DELTA_PREFIX("~");
  54. bool Network::Certificate::qualifyMembership(const Network::Certificate &mc) const
  55. {
  56. // Note: optimization probably needed here, probably via some kind of
  57. // memoization / dynamic programming. But make it work first, then make
  58. // it fast.
  59. for(const_iterator myField(begin());myField!=end();++myField) {
  60. if (!((myField->first.length() > 1)&&(myField->first[0] == '~'))) { // ~fields are max delta range specs
  61. // If they lack the same field, comparison fails.
  62. const_iterator theirField(mc.find(myField->first));
  63. if (theirField == mc.end())
  64. return false;
  65. const_iterator deltaField(find(_DELTA_PREFIX + myField->first));
  66. if (deltaField == end()) {
  67. // If there is no delta, compare on simple equality
  68. if (myField->second != theirField->second)
  69. return false;
  70. } else {
  71. // Otherwise compare range with max delta. Presence of a dot in delta
  72. // indicates a floating point comparison. Otherwise an integer
  73. // comparison occurs.
  74. if (deltaField->second.find('.') != std::string::npos) {
  75. double my = Utils::strToDouble(myField->second.c_str());
  76. double their = Utils::strToDouble(theirField->second.c_str());
  77. double delta = Utils::strToDouble(deltaField->second.c_str());
  78. if (fabs(my - their) > delta)
  79. return false;
  80. } else {
  81. uint64_t my = Utils::hexStrToU64(myField->second.c_str());
  82. uint64_t their = Utils::hexStrToU64(theirField->second.c_str());
  83. uint64_t delta = Utils::hexStrToU64(deltaField->second.c_str());
  84. if (my > their) {
  85. if ((my - their) > delta)
  86. return false;
  87. } else {
  88. if ((their - my) > delta)
  89. return false;
  90. }
  91. }
  92. }
  93. }
  94. }
  95. return true;
  96. }
  97. // A low default global rate, fast enough for something like ARP
  98. const Network::MulticastRates::Rate Network::MulticastRates::GLOBAL_DEFAULT_RATE(256.0,-32.0,256.0,64.0);
  99. const char *Network::statusString(const Status s)
  100. throw()
  101. {
  102. switch(s) {
  103. case NETWORK_WAITING_FOR_FIRST_AUTOCONF: return "WAITING_FOR_FIRST_AUTOCONF";
  104. case NETWORK_OK: return "OK";
  105. case NETWORK_ACCESS_DENIED: return "ACCESS_DENIED";
  106. }
  107. return "(invalid)";
  108. }
  109. Network::~Network()
  110. {
  111. delete _tap;
  112. if (_destroyOnDelete) {
  113. std::string confPath(_r->homePath + ZT_PATH_SEPARATOR_S + "networks.d" + ZT_PATH_SEPARATOR_S + toString() + ".conf");
  114. std::string mcdbPath(_r->homePath + ZT_PATH_SEPARATOR_S + "networks.d" + ZT_PATH_SEPARATOR_S + toString() + ".mcerts");
  115. Utils::rm(confPath);
  116. Utils::rm(mcdbPath);
  117. } else {
  118. // Causes flush of membership certs to disk
  119. clean();
  120. }
  121. }
  122. SharedPtr<Network> Network::newInstance(const RuntimeEnvironment *renv,uint64_t id)
  123. throw(std::runtime_error)
  124. {
  125. char tag[32];
  126. Utils::snprintf(tag,sizeof(tag),"%.16llx",(unsigned long long)id);
  127. // We construct Network via a static method to ensure that it is immediately
  128. // wrapped in a SharedPtr<>. Otherwise if there is traffic on the Ethernet
  129. // tap device, a SharedPtr<> wrap can occur in the Ethernet frame handler
  130. // that then causes the Network instance to be deleted before it is finished
  131. // being constructed. C++ edge cases, how I love thee.
  132. SharedPtr<Network> nw(new Network());
  133. nw->_ready = false; // disable handling of Ethernet frames during construct
  134. nw->_r = renv;
  135. nw->_tap = new EthernetTap(renv,tag,renv->identity.address().toMAC(),ZT_IF_MTU,&_CBhandleTapData,nw.ptr());
  136. memset(nw->_etWhitelist,0,sizeof(nw->_etWhitelist));
  137. nw->_id = id;
  138. nw->_lastConfigUpdate = 0;
  139. nw->_destroyOnDelete = false;
  140. if (nw->controller() == renv->identity.address()) // sanity check, this isn't supported for now
  141. throw std::runtime_error("cannot add a network for which I am the netconf master");
  142. nw->_restoreState();
  143. nw->_ready = true; // enable handling of Ethernet frames
  144. nw->requestConfiguration();
  145. return nw;
  146. }
  147. void Network::setConfiguration(const Network::Config &conf)
  148. {
  149. Mutex::Lock _l(_lock);
  150. try {
  151. if (conf.networkId() == _id) { // sanity check
  152. //TRACE("network %.16llx got netconf:\n%s",(unsigned long long)_id,conf.toString().c_str());
  153. _configuration = conf;
  154. _myCertificate = conf.certificateOfMembership();
  155. _lastConfigUpdate = Utils::now();
  156. _tap->setIps(conf.staticAddresses());
  157. _tap->setDisplayName((std::string("ZeroTier One [") + conf.name() + "]").c_str());
  158. memset(_etWhitelist,0,sizeof(_etWhitelist));
  159. std::set<unsigned int> wl(conf.etherTypes());
  160. for(std::set<unsigned int>::const_iterator t(wl.begin());t!=wl.end();++t)
  161. _etWhitelist[*t / 8] |= (unsigned char)(1 << (*t % 8));
  162. std::string confPath(_r->homePath + ZT_PATH_SEPARATOR_S + "networks.d" + ZT_PATH_SEPARATOR_S + toString() + ".conf");
  163. if (!Utils::writeFile(confPath.c_str(),conf.toString())) {
  164. LOG("error: unable to write network configuration file at: %s",confPath.c_str());
  165. }
  166. }
  167. } catch ( ... ) {
  168. _configuration = Config();
  169. _myCertificate = Certificate();
  170. _lastConfigUpdate = 0;
  171. LOG("unexpected exception handling config for network %.16llx, retrying fetch...",(unsigned long long)_id);
  172. }
  173. }
  174. void Network::requestConfiguration()
  175. {
  176. if (controller() == _r->identity.address()) {
  177. LOG("unable to request network configuration for network %.16llx: I am the network master, cannot query self",(unsigned long long)_id);
  178. return;
  179. }
  180. TRACE("requesting netconf for network %.16llx from netconf master %s",(unsigned long long)_id,controller().toString().c_str());
  181. Packet outp(controller(),_r->identity.address(),Packet::VERB_NETWORK_CONFIG_REQUEST);
  182. outp.append((uint64_t)_id);
  183. outp.append((uint16_t)0); // no meta-data
  184. _r->sw->send(outp,true);
  185. }
  186. void Network::addMembershipCertificate(const Address &peer,const Certificate &cert)
  187. {
  188. Mutex::Lock _l(_lock);
  189. if (!_configuration.isOpen())
  190. _membershipCertificates[peer] = cert;
  191. }
  192. bool Network::isAllowed(const Address &peer) const
  193. {
  194. // Exceptions can occur if we do not yet have *our* configuration.
  195. try {
  196. Mutex::Lock _l(_lock);
  197. if (_configuration.isOpen())
  198. return true;
  199. std::map<Address,Certificate>::const_iterator pc(_membershipCertificates.find(peer));
  200. if (pc == _membershipCertificates.end())
  201. return false;
  202. return _myCertificate.qualifyMembership(pc->second);
  203. } catch (std::exception &exc) {
  204. TRACE("isAllowed() check failed for peer %s: unexpected exception: %s",peer.toString().c_str(),exc.what());
  205. } catch ( ... ) {
  206. TRACE("isAllowed() check failed for peer %s: unexpected exception: unknown exception",peer.toString().c_str());
  207. }
  208. return false;
  209. }
  210. void Network::clean()
  211. {
  212. std::string mcdbPath(_r->homePath + ZT_PATH_SEPARATOR_S + "networks.d" + ZT_PATH_SEPARATOR_S + toString() + ".mcerts");
  213. Mutex::Lock _l(_lock);
  214. if (_configuration.isOpen()) {
  215. _membershipCertificates.clear();
  216. Utils::rm(mcdbPath);
  217. } else {
  218. FILE *mcdb = fopen(mcdbPath.c_str(),"wb");
  219. bool writeError = false;
  220. if (!mcdb) {
  221. LOG("error: unable to open membership cert database at: %s",mcdbPath.c_str());
  222. } else {
  223. if ((writeError)||(fwrite("MCDB0",5,1,mcdb) != 1)) // version
  224. writeError = true;
  225. }
  226. for(std::map<Address,Certificate>::iterator i=(_membershipCertificates.begin());i!=_membershipCertificates.end();) {
  227. if (_myCertificate.qualifyMembership(i->second)) {
  228. if ((!writeError)&&(mcdb)) {
  229. char tmp[ZT_ADDRESS_LENGTH];
  230. i->first.copyTo(tmp,ZT_ADDRESS_LENGTH);
  231. if ((writeError)||(fwrite(tmp,ZT_ADDRESS_LENGTH,1,mcdb) != 1))
  232. writeError = true;
  233. std::string c(i->second.toString());
  234. uint32_t cl = Utils::hton((uint32_t)c.length());
  235. if ((writeError)||(fwrite(&cl,sizeof(cl),1,mcdb) != 1))
  236. writeError = true;
  237. if ((writeError)||(fwrite(c.data(),c.length(),1,mcdb) != 1))
  238. writeError = true;
  239. }
  240. ++i;
  241. } else _membershipCertificates.erase(i++);
  242. }
  243. if (mcdb)
  244. fclose(mcdb);
  245. if (writeError) {
  246. Utils::rm(mcdbPath);
  247. LOG("error: unable to write to membership cert database at: %s",mcdbPath.c_str());
  248. }
  249. }
  250. }
  251. Network::Status Network::status() const
  252. {
  253. Mutex::Lock _l(_lock);
  254. if (_configuration)
  255. return NETWORK_OK;
  256. return NETWORK_WAITING_FOR_FIRST_AUTOCONF;
  257. }
  258. void Network::_CBhandleTapData(void *arg,const MAC &from,const MAC &to,unsigned int etherType,const Buffer<4096> &data)
  259. {
  260. if (!((Network *)arg)->_ready)
  261. return;
  262. const RuntimeEnvironment *_r = ((Network *)arg)->_r;
  263. if (_r->shutdownInProgress)
  264. return;
  265. try {
  266. _r->sw->onLocalEthernet(SharedPtr<Network>((Network *)arg),from,to,etherType,data);
  267. } catch (std::exception &exc) {
  268. TRACE("unexpected exception handling local packet: %s",exc.what());
  269. } catch ( ... ) {
  270. TRACE("unexpected exception handling local packet");
  271. }
  272. }
  273. void Network::_restoreState()
  274. {
  275. std::string confPath(_r->homePath + ZT_PATH_SEPARATOR_S + "networks.d" + ZT_PATH_SEPARATOR_S + toString() + ".conf");
  276. std::string confs;
  277. if (Utils::readFile(confPath.c_str(),confs)) {
  278. try {
  279. if (confs.length())
  280. setConfiguration(Config(confs));
  281. } catch ( ... ) {} // ignore invalid config on disk, we will re-request
  282. } else {
  283. // If the conf file isn't present, "touch" it so we'll remember
  284. // the existence of this network.
  285. FILE *tmp = fopen(confPath.c_str(),"w");
  286. if (tmp)
  287. fclose(tmp);
  288. }
  289. // TODO: restore membership certs
  290. }
  291. } // namespace ZeroTier