NodeConfig.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359
  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 <stdint.h>
  31. #include <memory>
  32. #include <string>
  33. #include <map>
  34. #include <set>
  35. #include "Constants.hpp"
  36. #ifdef __WINDOWS__
  37. #include <WinSock2.h>
  38. #include <Windows.h>
  39. #endif
  40. #include "NodeConfig.hpp"
  41. #include "RuntimeEnvironment.hpp"
  42. #include "Defaults.hpp"
  43. #include "Utils.hpp"
  44. #include "Logger.hpp"
  45. #include "Topology.hpp"
  46. #include "Demarc.hpp"
  47. #include "InetAddress.hpp"
  48. #include "Peer.hpp"
  49. #include "Salsa20.hpp"
  50. #include "Poly1305.hpp"
  51. #include "SHA512.hpp"
  52. #include "Node.hpp"
  53. namespace ZeroTier {
  54. NodeConfig::NodeConfig(const RuntimeEnvironment *renv,const char *authToken,unsigned int controlPort)
  55. throw(std::runtime_error) :
  56. _r(renv),
  57. _controlSocket(true,controlPort,false,&_CBcontrolPacketHandler,this)
  58. {
  59. {
  60. unsigned int csk[64];
  61. SHA512::hash(csk,authToken,strlen(authToken));
  62. memcpy(_controlSocketKey,csk,32);
  63. }
  64. std::string networksFolder(_r->homePath + ZT_PATH_SEPARATOR_S + "networks.d");
  65. std::map<std::string,bool> networksDotD(Utils::listDirectory(networksFolder.c_str()));
  66. std::set<uint64_t> nwids;
  67. for(std::map<std::string,bool>::iterator d(networksDotD.begin());d!=networksDotD.end();++d) {
  68. if (!d->second) {
  69. std::string::size_type dot = d->first.rfind(".conf");
  70. if (dot != std::string::npos) {
  71. uint64_t nwid = strtoull(d->first.substr(0,dot).c_str(),(char **)0,16);
  72. // TODO: remove legacy code once out of beta
  73. if (nwid == 0x6c92786fee000001ULL) {
  74. nwid = 0xbc8f9a8ee3000001ULL;
  75. Utils::rm((networksFolder + ZT_PATH_SEPARATOR_S + d->first).c_str());
  76. }
  77. if (nwid == 0xbc8f9a8ee3000001ULL) {
  78. nwid = 0x8D93FBE886000001ULL;
  79. Utils::rm((networksFolder + ZT_PATH_SEPARATOR_S + d->first).c_str());
  80. }
  81. if (nwid > 0)
  82. nwids.insert(nwid);
  83. }
  84. }
  85. }
  86. for(std::set<uint64_t>::iterator nwid(nwids.begin());nwid!=nwids.end();++nwid) {
  87. try {
  88. SharedPtr<Network> nw(Network::newInstance(_r,*nwid));
  89. _networks[*nwid] = nw;
  90. } catch (std::exception &exc) {
  91. LOG("unable to create network %.16llx: %s",(unsigned long long)*nwid,exc.what());
  92. } catch ( ... ) {
  93. LOG("unable to create network %.16llx: (unknown exception)",(unsigned long long)*nwid);
  94. }
  95. }
  96. }
  97. NodeConfig::~NodeConfig()
  98. {
  99. }
  100. void NodeConfig::whackAllTaps()
  101. {
  102. std::vector< SharedPtr<Network> > nwlist;
  103. Mutex::Lock _l(_networks_m);
  104. for(std::map< uint64_t,SharedPtr<Network> >::const_iterator n(_networks.begin());n!=_networks.end();++n)
  105. n->second->tap().whack();
  106. }
  107. void NodeConfig::clean()
  108. {
  109. Mutex::Lock _l(_networks_m);
  110. for(std::map< uint64_t,SharedPtr<Network> >::const_iterator n(_networks.begin());n!=_networks.end();++n)
  111. n->second->clean();
  112. }
  113. // Macro used in execute()
  114. #undef _P
  115. #define _P(f,...) { r.push_back(std::string()); Utils::stdsprintf(r.back(),(f),##__VA_ARGS__); }
  116. // Used with Topology::eachPeer to dump peer stats
  117. class _DumpPeerStatistics
  118. {
  119. public:
  120. _DumpPeerStatistics(std::vector<std::string> &out) :
  121. r(out),
  122. _now(Utils::now())
  123. {
  124. }
  125. inline void operator()(Topology &t,const SharedPtr<Peer> &p)
  126. {
  127. InetAddress v4(p->ipv4ActivePath(_now));
  128. InetAddress v6(p->ipv6ActivePath(_now));
  129. _P("200 listpeers %s %s %s %u %s",
  130. p->address().toString().c_str(),
  131. ((v4) ? v4.toString().c_str() : "-"),
  132. ((v6) ? v6.toString().c_str() : "-"),
  133. (((v4)||(v6)) ? p->latency() : 0),
  134. p->remoteVersion().c_str());
  135. }
  136. private:
  137. std::vector<std::string> &r;
  138. uint64_t _now;
  139. };
  140. std::vector<std::string> NodeConfig::execute(const char *command)
  141. {
  142. std::vector<std::string> r;
  143. std::vector<std::string> cmd(Utils::split(command,"\r\n \t","\\","'"));
  144. //
  145. // Not coincidentally, response type codes correspond with HTTP
  146. // status codes.
  147. //
  148. if ((cmd.empty())||(cmd[0] == "help")) {
  149. _P("200 help help");
  150. _P("200 help listpeers");
  151. _P("200 help listnetworks");
  152. _P("200 help join <network ID>");
  153. _P("200 help leave <network ID>");
  154. _P("200 help terminate [<reason>]");
  155. } else if (cmd[0] == "listpeers") {
  156. _P("200 listpeers <ztaddr> <ipv4> <ipv6> <latency> <version>");
  157. _r->topology->eachPeer(_DumpPeerStatistics(r));
  158. } else if (cmd[0] == "listnetworks") {
  159. Mutex::Lock _l(_networks_m);
  160. _P("200 listnetworks <nwid> <status> <type> <dev> <ips>");
  161. for(std::map< uint64_t,SharedPtr<Network> >::const_iterator nw(_networks.begin());nw!=_networks.end();++nw) {
  162. std::string tmp;
  163. std::set<InetAddress> ips(nw->second->tap().ips());
  164. for(std::set<InetAddress>::iterator i(ips.begin());i!=ips.end();++i) {
  165. if (tmp.length())
  166. tmp.push_back(',');
  167. tmp.append(i->toString());
  168. }
  169. // TODO: display network status, such as "permission denied to closed
  170. // network" or "waiting".
  171. _P("200 listnetworks %.16llx %s %s %s %s",
  172. (unsigned long long)nw->first,
  173. Network::statusString(nw->second->status()),
  174. (nw->second->isOpen() ? "open" : "private"),
  175. nw->second->tap().deviceName().c_str(),
  176. ((tmp.length() > 0) ? tmp.c_str() : "-"));
  177. }
  178. } else if (cmd[0] == "join") {
  179. if (cmd.size() > 1) {
  180. uint64_t nwid = strtoull(cmd[1].c_str(),(char **)0,16);
  181. if (nwid > 0) {
  182. Mutex::Lock _l(_networks_m);
  183. if (_networks.count(nwid)) {
  184. _P("400 already a member of %.16llx",(unsigned long long)nwid);
  185. } else {
  186. try {
  187. SharedPtr<Network> nw(Network::newInstance(_r,nwid));
  188. _networks[nwid] = nw;
  189. _P("200 join %.16llx OK",(unsigned long long)nwid);
  190. } catch (std::exception &exc) {
  191. _P("500 join %.16llx ERROR: %s",(unsigned long long)nwid,exc.what());
  192. } catch ( ... ) {
  193. _P("500 join %.16llx ERROR: (unknown exception)",(unsigned long long)nwid);
  194. }
  195. }
  196. } else {
  197. _P("400 join requires a network ID (>0) in hexadecimal format");
  198. }
  199. } else {
  200. _P("400 join requires a network ID (>0) in hexadecimal format");
  201. }
  202. } else if (cmd[0] == "leave") {
  203. if (cmd.size() > 1) {
  204. Mutex::Lock _l(_networks_m);
  205. uint64_t nwid = strtoull(cmd[1].c_str(),(char **)0,16);
  206. std::map< uint64_t,SharedPtr<Network> >::iterator nw(_networks.find(nwid));
  207. if (nw == _networks.end()) {
  208. _P("404 leave %.16llx ERROR: not a member of that network",(unsigned long long)nwid);
  209. } else {
  210. nw->second->destroyOnDelete();
  211. _networks.erase(nw);
  212. }
  213. } else {
  214. _P("400 leave requires a network ID (>0) in hexadecimal format");
  215. }
  216. } else if (cmd[0] == "terminate") {
  217. if (cmd.size() > 1)
  218. _r->node->terminate(Node::NODE_NORMAL_TERMINATION,cmd[1].c_str());
  219. else _r->node->terminate(Node::NODE_NORMAL_TERMINATION,(const char *)0);
  220. } else {
  221. _P("404 %s No such command. Use 'help' for help.",cmd[0].c_str());
  222. }
  223. r.push_back(std::string()); // terminate with empty line
  224. return r;
  225. }
  226. std::vector< Buffer<ZT_NODECONFIG_MAX_PACKET_SIZE> > NodeConfig::encodeControlMessage(const void *key,unsigned long conversationId,const std::vector<std::string> &payload)
  227. throw(std::out_of_range)
  228. {
  229. char poly1305tag[ZT_POLY1305_MAC_LEN];
  230. char iv[8];
  231. char keytmp[32];
  232. std::vector< Buffer<ZT_NODECONFIG_MAX_PACKET_SIZE> > packets;
  233. Buffer<ZT_NODECONFIG_MAX_PACKET_SIZE> packet;
  234. packet.setSize(16); // room for poly1305 auth tag and IV
  235. packet.append((uint32_t)(conversationId & 0xffffffff));
  236. for(unsigned int i=0;i<payload.size();++i) {
  237. packet.append(payload[i]); // will throw if too big
  238. packet.append((unsigned char)0);
  239. if (((i + 1) >= payload.size())||((packet.size() + payload[i + 1].length() + 1) >= packet.capacity())) {
  240. Utils::getSecureRandom(iv,8);
  241. memcpy(packet.field(8,8),iv,8);
  242. Salsa20 s20(key,256,iv);
  243. s20.encrypt(packet.field(16,packet.size() - 16),packet.field(16,packet.size() - 16),packet.size() - 16);
  244. memcpy(keytmp,key,32);
  245. for(unsigned int i=0;i<8;++i)
  246. keytmp[i] ^= iv[i]; // can't reuse poly1305 keys, so mangle key with IV each time
  247. Poly1305::compute(poly1305tag,packet.field(16,packet.size() - 16),packet.size() - 16,keytmp);
  248. memcpy(packet.field(0,8),poly1305tag,8);
  249. packets.push_back(packet);
  250. packet.setSize(16); // room for poly1305 auth tag and IV
  251. packet.append((uint32_t)(conversationId & 0xffffffff));
  252. }
  253. }
  254. return packets;
  255. }
  256. bool NodeConfig::decodeControlMessagePacket(const void *key,const void *data,unsigned int len,unsigned long &conversationId,std::vector<std::string> &payload)
  257. {
  258. char poly1305tag[ZT_POLY1305_MAC_LEN];
  259. char keytmp[32];
  260. char iv[8];
  261. try {
  262. if (len < 20)
  263. return false;
  264. Buffer<ZT_NODECONFIG_MAX_PACKET_SIZE> packet(data,len);
  265. memcpy(keytmp,key,32);
  266. memcpy(iv,packet.field(8,8),8);
  267. for(unsigned int i=0;i<8;++i)
  268. keytmp[i] ^= iv[i];
  269. Poly1305::compute(poly1305tag,packet.field(16,packet.size() - 16),packet.size() - 16,keytmp);
  270. if (!Utils::secureEq(packet.field(0,8),poly1305tag,8))
  271. return false;
  272. Salsa20 s20(key,256,packet.field(8,8));
  273. s20.decrypt(packet.field(16,packet.size() - 16),packet.field(16,packet.size() - 16),packet.size() - 16);
  274. conversationId = packet.at<uint32_t>(16);
  275. const char *pl = ((const char *)packet.data()) + 20;
  276. unsigned int pll = packet.size() - 20;
  277. for(unsigned int i=0;i<pll;) {
  278. unsigned int eos = i;
  279. while ((eos < pll)&&(pl[eos]))
  280. ++eos;
  281. if (eos >= i) {
  282. payload.push_back(std::string(pl + i,eos - i));
  283. i = eos + 1;
  284. } else break;
  285. }
  286. return true;
  287. } catch ( ... ) {
  288. return false;
  289. }
  290. }
  291. void NodeConfig::_CBcontrolPacketHandler(UdpSocket *sock,void *arg,const InetAddress &remoteAddr,const void *data,unsigned int len)
  292. {
  293. NodeConfig *nc = (NodeConfig *)arg;
  294. const RuntimeEnvironment *_r = nc->_r;
  295. try {
  296. unsigned long convId = 0;
  297. std::vector<std::string> commands;
  298. if (!decodeControlMessagePacket(nc->_controlSocketKey,data,len,convId,commands)) {
  299. TRACE("control bus packet from %s failed decode, discarded",remoteAddr.toString().c_str());
  300. return;
  301. }
  302. TRACE("control bus packet from %s, contains %d commands",remoteAddr.toString().c_str(),(int)commands.size());
  303. for(std::vector<std::string>::iterator c(commands.begin());c!=commands.end();++c) {
  304. std::vector< Buffer<ZT_NODECONFIG_MAX_PACKET_SIZE> > resultPackets(encodeControlMessage(nc->_controlSocketKey,convId,nc->execute(c->c_str())));
  305. for(std::vector< Buffer<ZT_NODECONFIG_MAX_PACKET_SIZE> >::iterator p(resultPackets.begin());p!=resultPackets.end();++p)
  306. sock->send(remoteAddr,p->data(),p->size(),-1);
  307. }
  308. } catch (std::exception &exc) {
  309. TRACE("exception handling control bus packet from %s: %s",remoteAddr.toString().c_str(),exc.what());
  310. } catch ( ... ) {
  311. TRACE("exception handling control bus packet from %s: (unknown)",remoteAddr.toString().c_str());
  312. }
  313. }
  314. } // namespace ZeroTier