Network.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
  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 = strtod(myField->second.c_str(),(char **)0);
  76. double their = strtod(theirField->second.c_str(),(char **)0);
  77. double delta = strtod(deltaField->second.c_str(),(char **)0);
  78. if (fabs(my - their) > delta)
  79. return false;
  80. } else {
  81. #ifdef __WINDOWS__
  82. int64_t my = _strtoi64(myField->second.c_str(),(char **)0,10);
  83. int64_t their = _strtoi64(theirField->second.c_str(),(char **)0,10);
  84. int64_t delta = _strtoi64(deltaField->second.c_str(),(char **)0,10);
  85. #else
  86. int64_t my = strtoll(myField->second.c_str(),(char **)0,10);
  87. int64_t their = strtoll(theirField->second.c_str(),(char **)0,10);
  88. int64_t delta = strtoll(deltaField->second.c_str(),(char **)0,10);
  89. #endif
  90. if (my > their) {
  91. if ((my - their) > delta)
  92. return false;
  93. } else {
  94. if ((their - my) > delta)
  95. return false;
  96. }
  97. }
  98. }
  99. }
  100. }
  101. return true;
  102. }
  103. const char *Network::statusString(const Status s)
  104. throw()
  105. {
  106. switch(s) {
  107. case NETWORK_WAITING_FOR_FIRST_AUTOCONF: return "WAITING_FOR_FIRST_AUTOCONF";
  108. case NETWORK_OK: return "OK";
  109. case NETWORK_ACCESS_DENIED: return "ACCESS_DENIED";
  110. }
  111. return "(invalid)";
  112. }
  113. Network::~Network()
  114. {
  115. delete _tap;
  116. if (_destroyOnDelete) {
  117. std::string confPath(_r->homePath + ZT_PATH_SEPARATOR_S + "networks.d" + ZT_PATH_SEPARATOR_S + toString() + ".conf");
  118. std::string mcdbPath(_r->homePath + ZT_PATH_SEPARATOR_S + "networks.d" + ZT_PATH_SEPARATOR_S + toString() + ".mcerts");
  119. Utils::rm(confPath);
  120. Utils::rm(mcdbPath);
  121. } else {
  122. // Causes flush of membership certs to disk
  123. clean();
  124. }
  125. }
  126. SharedPtr<Network> Network::newInstance(const RuntimeEnvironment *renv,uint64_t id)
  127. throw(std::runtime_error)
  128. {
  129. // We construct Network via a static method to ensure that it is immediately
  130. // wrapped in a SharedPtr<>. Otherwise if there is traffic on the Ethernet
  131. // tap device, a SharedPtr<> wrap can occur in the Ethernet frame handler
  132. // that then causes the Network instance to be deleted before it is finished
  133. // being constructed. C++ edge cases, how I love thee.
  134. SharedPtr<Network> nw(new Network());
  135. nw->_ready = false; // disable handling of Ethernet frames during construct
  136. nw->_r = renv;
  137. nw->_rlLimit.bytesPerSecond = ZT_MULTICAST_DEFAULT_BYTES_PER_SECOND;
  138. nw->_rlLimit.maxBalance = ZT_MULTICAST_DEFAULT_RATE_MAX_BALANCE;
  139. nw->_rlLimit.minBalance = ZT_MULTICAST_DEFAULT_RATE_MIN_BALANCE;
  140. nw->_tap = new EthernetTap(renv,renv->identity.address().toMAC(),ZT_IF_MTU,(const char *)0,&_CBhandleTapData,nw.ptr());
  141. nw->_id = id;
  142. nw->_lastConfigUpdate = 0;
  143. nw->_destroyOnDelete = false;
  144. if (nw->controller() == renv->identity.address()) // sanity check, this isn't supported for now
  145. throw std::runtime_error("cannot add a network for which I am the netconf master");
  146. nw->_restoreState();
  147. nw->_ready = true; // enable handling of Ethernet frames
  148. nw->requestConfiguration();
  149. return nw;
  150. }
  151. void Network::setConfiguration(const Network::Config &conf)
  152. {
  153. Mutex::Lock _l(_lock);
  154. if ((conf.networkId() == _id)&&(conf.peerAddress() == _r->identity.address())) { // sanity check
  155. //TRACE("network %.16llx got netconf:\n%s",(unsigned long long)_id,conf.toString().c_str());
  156. _configuration = conf;
  157. _myCertificate = conf.certificateOfMembership();
  158. _lastConfigUpdate = Utils::now();
  159. _tap->setIps(conf.staticAddresses());
  160. std::string confPath(_r->homePath + ZT_PATH_SEPARATOR_S + "networks.d" + ZT_PATH_SEPARATOR_S + toString() + ".conf");
  161. if (!Utils::writeFile(confPath.c_str(),conf.toString())) {
  162. LOG("error: unable to write network configuration file at: %s",confPath.c_str());
  163. }
  164. }
  165. }
  166. void Network::requestConfiguration()
  167. {
  168. if (controller() == _r->identity.address()) {
  169. LOG("unable to request network configuration for network %.16llx: I am the network master, cannot query self",(unsigned long long)_id);
  170. return;
  171. }
  172. TRACE("requesting netconf for network %.16llx from netconf master %s",(unsigned long long)_id,controller().toString().c_str());
  173. Packet outp(controller(),_r->identity.address(),Packet::VERB_NETWORK_CONFIG_REQUEST);
  174. outp.append((uint64_t)_id);
  175. outp.append((uint16_t)0); // no meta-data
  176. _r->sw->send(outp,true);
  177. }
  178. void Network::addMembershipCertificate(const Address &peer,const Certificate &cert)
  179. {
  180. Mutex::Lock _l(_lock);
  181. if (!_configuration.isOpen())
  182. _membershipCertificates[peer] = cert;
  183. }
  184. bool Network::isAllowed(const Address &peer) const
  185. {
  186. // Exceptions can occur if we do not yet have *our* configuration.
  187. try {
  188. Mutex::Lock _l(_lock);
  189. if (_configuration.isOpen())
  190. return true;
  191. std::map<Address,Certificate>::const_iterator pc(_membershipCertificates.find(peer));
  192. if (pc == _membershipCertificates.end())
  193. return false;
  194. return _myCertificate.qualifyMembership(pc->second);
  195. } catch (std::exception &exc) {
  196. TRACE("isAllowed() check failed for peer %s: unexpected exception: %s",peer.toString().c_str(),exc.what());
  197. } catch ( ... ) {
  198. TRACE("isAllowed() check failed for peer %s: unexpected exception: unknown exception",peer.toString().c_str());
  199. }
  200. return false;
  201. }
  202. void Network::clean()
  203. {
  204. std::string mcdbPath(_r->homePath + ZT_PATH_SEPARATOR_S + "networks.d" + ZT_PATH_SEPARATOR_S + toString() + ".mcerts");
  205. Mutex::Lock _l(_lock);
  206. if (_configuration.isOpen()) {
  207. _membershipCertificates.clear();
  208. Utils::rm(mcdbPath);
  209. } else {
  210. FILE *mcdb = fopen(mcdbPath.c_str(),"wb");
  211. bool writeError = false;
  212. if (!mcdb) {
  213. LOG("error: unable to open membership cert database at: %s",mcdbPath.c_str());
  214. } else {
  215. if ((writeError)||(fwrite("MCDB0",5,1,mcdb) != 1)) // version
  216. writeError = true;
  217. }
  218. for(std::map<Address,Certificate>::iterator i=(_membershipCertificates.begin());i!=_membershipCertificates.end();) {
  219. if (_myCertificate.qualifyMembership(i->second)) {
  220. if ((!writeError)&&(mcdb)) {
  221. char tmp[ZT_ADDRESS_LENGTH];
  222. i->first.copyTo(tmp,ZT_ADDRESS_LENGTH);
  223. if ((writeError)||(fwrite(tmp,ZT_ADDRESS_LENGTH,1,mcdb) != 1))
  224. writeError = true;
  225. std::string c(i->second.toString());
  226. uint32_t cl = Utils::hton((uint32_t)c.length());
  227. if ((writeError)||(fwrite(&cl,sizeof(cl),1,mcdb) != 1))
  228. writeError = true;
  229. if ((writeError)||(fwrite(c.data(),c.length(),1,mcdb) != 1))
  230. writeError = true;
  231. }
  232. ++i;
  233. } else _membershipCertificates.erase(i++);
  234. }
  235. if (mcdb)
  236. fclose(mcdb);
  237. if (writeError) {
  238. Utils::rm(mcdbPath);
  239. LOG("error: unable to write to membership cert database at: %s",mcdbPath.c_str());
  240. }
  241. }
  242. }
  243. Network::Status Network::status() const
  244. {
  245. Mutex::Lock _l(_lock);
  246. if (_configuration.containsAllFields())
  247. return NETWORK_OK;
  248. return NETWORK_WAITING_FOR_FIRST_AUTOCONF;
  249. }
  250. void Network::_CBhandleTapData(void *arg,const MAC &from,const MAC &to,unsigned int etherType,const Buffer<4096> &data)
  251. {
  252. if (!((Network *)arg)->_ready)
  253. return;
  254. const RuntimeEnvironment *_r = ((Network *)arg)->_r;
  255. try {
  256. _r->sw->onLocalEthernet(SharedPtr<Network>((Network *)arg),from,to,etherType,data);
  257. } catch (std::exception &exc) {
  258. TRACE("unexpected exception handling local packet: %s",exc.what());
  259. } catch ( ... ) {
  260. TRACE("unexpected exception handling local packet");
  261. }
  262. }
  263. void Network::_restoreState()
  264. {
  265. std::string confPath(_r->homePath + ZT_PATH_SEPARATOR_S + "networks.d" + ZT_PATH_SEPARATOR_S + toString() + ".conf");
  266. std::string confs;
  267. if (Utils::readFile(confPath.c_str(),confs)) {
  268. try {
  269. if (confs.length()) {
  270. Config conf(confs);
  271. if (conf.containsAllFields())
  272. setConfiguration(conf);
  273. }
  274. } catch ( ... ) {} // ignore invalid config on disk, we will re-request
  275. } else {
  276. // If the conf file isn't present, "touch" it so we'll remember
  277. // the existence of this network.
  278. FILE *tmp = fopen(confPath.c_str(),"w");
  279. if (tmp)
  280. fclose(tmp);
  281. }
  282. // TODO: restore membership certs
  283. }
  284. } // namespace ZeroTier