NodeConfig.cpp 8.2 KB

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