NodeConfig.cpp 10 KB

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