NodeConfig.cpp 11 KB

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