NodeConfig.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425
  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 "Packet.hpp"
  48. #include "InetAddress.hpp"
  49. #include "Peer.hpp"
  50. #include "Salsa20.hpp"
  51. #include "Poly1305.hpp"
  52. #include "SHA512.hpp"
  53. #include "Node.hpp"
  54. #include "SoftwareUpdater.hpp"
  55. namespace ZeroTier {
  56. NodeConfig::NodeConfig(const RuntimeEnvironment *renv,const char *authToken,unsigned int controlPort) :
  57. _r(renv),
  58. _controlSocket(true,controlPort,false,&_CBcontrolPacketHandler,this)
  59. {
  60. {
  61. unsigned int csk[64];
  62. SHA512::hash(csk,authToken,(unsigned int)strlen(authToken));
  63. memcpy(_controlSocketKey,csk,32);
  64. }
  65. {
  66. Mutex::Lock _llc(_localConfig_m);
  67. _readLocalConfig();
  68. }
  69. std::string networksFolder(_r->homePath + ZT_PATH_SEPARATOR_S + "networks.d");
  70. std::map<std::string,bool> networksDotD(Utils::listDirectory(networksFolder.c_str()));
  71. std::vector<uint64_t> configuredNets;
  72. for(std::map<std::string,bool>::iterator d(networksDotD.begin());d!=networksDotD.end();++d) {
  73. if (!d->second) {
  74. std::string::size_type dot = d->first.rfind(".conf");
  75. if (dot != std::string::npos) {
  76. uint64_t nwid = Utils::hexStrToU64(d->first.substr(0,dot).c_str());
  77. if ((nwid > 0)&&(std::find(configuredNets.begin(),configuredNets.end(),nwid) == configuredNets.end()))
  78. configuredNets.push_back(nwid);
  79. }
  80. }
  81. }
  82. for(std::vector<uint64_t>::iterator n(configuredNets.begin());n!=configuredNets.end();++n) {
  83. try {
  84. _networks[*n] = Network::newInstance(_r,*n);
  85. } catch (std::exception &exc) {
  86. LOG("unable to create network %.16llx: %s",(unsigned long long)*n,exc.what());
  87. } catch ( ... ) {
  88. LOG("unable to create network %.16llx: (unknown exception)",(unsigned long long)*n);
  89. }
  90. }
  91. }
  92. NodeConfig::~NodeConfig()
  93. {
  94. _writeLocalConfig();
  95. }
  96. void NodeConfig::putLocalConfig(const std::string &key,const char *value)
  97. {
  98. Mutex::Lock _l(_localConfig_m);
  99. _localConfig[key] = value;
  100. _writeLocalConfig();
  101. }
  102. void NodeConfig::putLocalConfig(const std::string &key,const std::string &value)
  103. {
  104. Mutex::Lock _l(_localConfig_m);
  105. _localConfig[key] = value;
  106. _writeLocalConfig();
  107. }
  108. std::string NodeConfig::getLocalConfig(const std::string &key) const
  109. {
  110. Mutex::Lock _l(_localConfig_m);
  111. Dictionary::const_iterator i(_localConfig.find(key));
  112. if (i == _localConfig.end())
  113. return std::string();
  114. return i->second;
  115. }
  116. void NodeConfig::clean()
  117. {
  118. Mutex::Lock _l(_networks_m);
  119. for(std::map< uint64_t,SharedPtr<Network> >::const_iterator n(_networks.begin());n!=_networks.end();++n)
  120. n->second->clean();
  121. }
  122. /////////////////////////////////////////////////////////////////////////////
  123. // UDP localhost control bus
  124. // Macro used in execute() to push lines onto the return packet
  125. #undef _P
  126. #define _P(f,...) { r.push_back(std::string()); Utils::stdsprintf(r.back(),(f),##__VA_ARGS__); }
  127. // Used with Topology::eachPeer to dump peer stats
  128. class _DumpPeerStatistics
  129. {
  130. public:
  131. _DumpPeerStatistics(std::vector<std::string> &out) :
  132. r(out),
  133. _now(Utils::now())
  134. {
  135. }
  136. inline void operator()(Topology &t,const SharedPtr<Peer> &p)
  137. {
  138. InetAddress v4(p->ipv4ActivePath(_now));
  139. InetAddress v6(p->ipv6ActivePath(_now));
  140. if ((v4)||(v6)) {
  141. _P("200 listpeers %s %s %s %u %s",
  142. p->address().toString().c_str(),
  143. ((v4) ? v4.toString().c_str() : "-"),
  144. ((v6) ? v6.toString().c_str() : "-"),
  145. p->latency(),
  146. p->remoteVersion().c_str());
  147. } else {
  148. _P("200 listpeers %s - - - %s",
  149. p->address().toString().c_str(),
  150. p->remoteVersion().c_str());
  151. }
  152. }
  153. private:
  154. std::vector<std::string> &r;
  155. uint64_t _now;
  156. };
  157. std::vector<std::string> NodeConfig::execute(const char *command)
  158. {
  159. std::vector<std::string> r;
  160. std::vector<std::string> cmd(Utils::split(command,"\r\n \t","\\","'"));
  161. /* Not coincidentally, response type codes correspond with HTTP
  162. * status codes. Technically a little arbitrary, but would maybe
  163. * make things easier if we wanted to slap some kind of web API
  164. * in front of this thing. */
  165. if ((cmd.empty())||(cmd[0] == "help")) {
  166. _P("200 help help");
  167. _P("200 help info");
  168. _P("200 help listpeers");
  169. _P("200 help listnetworks");
  170. _P("200 help join <network ID>");
  171. _P("200 help leave <network ID>");
  172. _P("200 help terminate [<reason>]");
  173. _P("200 help updatecheck");
  174. } else if (cmd[0] == "info") {
  175. bool isOnline = false;
  176. uint64_t now = Utils::now();
  177. std::vector< SharedPtr<Peer> > snp(_r->topology->supernodePeers());
  178. for(std::vector< SharedPtr<Peer> >::const_iterator sn(snp.begin());sn!=snp.end();++sn) {
  179. if ((*sn)->hasActiveDirectPath(now)) {
  180. isOnline = true;
  181. break;
  182. }
  183. }
  184. _P("200 info %s %s %s",_r->identity.address().toString().c_str(),(isOnline ? "ONLINE" : "OFFLINE"),Node::versionString());
  185. } else if (cmd[0] == "listpeers") {
  186. _P("200 listpeers <ztaddr> <ipv4> <ipv6> <latency> <version>");
  187. _r->topology->eachPeer(_DumpPeerStatistics(r));
  188. } else if (cmd[0] == "listnetworks") {
  189. Mutex::Lock _l(_networks_m);
  190. _P("200 listnetworks <nwid> <name> <status> <config age> <type> <dev> <ips>");
  191. for(std::map< uint64_t,SharedPtr<Network> >::const_iterator nw(_networks.begin());nw!=_networks.end();++nw) {
  192. std::string tmp;
  193. std::set<InetAddress> ips(nw->second->ips());
  194. for(std::set<InetAddress>::iterator i(ips.begin());i!=ips.end();++i) {
  195. if (tmp.length())
  196. tmp.push_back(',');
  197. tmp.append(i->toString());
  198. }
  199. SharedPtr<NetworkConfig> nconf(nw->second->config2());
  200. long long age = (nconf) ? ((long long)Utils::now() - (long long)nconf->timestamp()) : (long long)0;
  201. if (age < 0)
  202. age = 0;
  203. age /= 1000;
  204. std::string dn(nw->second->tapDeviceName());
  205. _P("200 listnetworks %.16llx %s %s %lld %s %s %s",
  206. (unsigned long long)nw->first,
  207. ((nconf) ? nconf->name().c_str() : "?"),
  208. Network::statusString(nw->second->status()),
  209. age,
  210. ((nconf) ? (nconf->isOpen() ? "public" : "private") : "?"),
  211. (dn.length() > 0) ? dn.c_str() : "?",
  212. ((tmp.length() > 0) ? tmp.c_str() : "-"));
  213. }
  214. } else if (cmd[0] == "join") {
  215. if (cmd.size() > 1) {
  216. uint64_t nwid = Utils::hexStrToU64(cmd[1].c_str());
  217. if (nwid > 0) {
  218. Mutex::Lock _l(_networks_m);
  219. if (_networks.count(nwid)) {
  220. _P("409 already a member of %.16llx",(unsigned long long)nwid);
  221. } else {
  222. try {
  223. SharedPtr<Network> nw(Network::newInstance(_r,nwid));
  224. _networks[nwid] = nw;
  225. _P("200 join %.16llx OK",(unsigned long long)nwid);
  226. } catch (std::exception &exc) {
  227. _P("500 join %.16llx ERROR: %s",(unsigned long long)nwid,exc.what());
  228. } catch ( ... ) {
  229. _P("500 join %.16llx ERROR: (unknown exception)",(unsigned long long)nwid);
  230. }
  231. }
  232. } else {
  233. _P("400 join requires a network ID (>0) in hexadecimal format");
  234. }
  235. } else {
  236. _P("400 join requires a network ID (>0) in hexadecimal format");
  237. }
  238. } else if (cmd[0] == "leave") {
  239. if (cmd.size() > 1) {
  240. Mutex::Lock _l(_networks_m);
  241. uint64_t nwid = Utils::hexStrToU64(cmd[1].c_str());
  242. std::map< uint64_t,SharedPtr<Network> >::iterator nw(_networks.find(nwid));
  243. if (nw == _networks.end()) {
  244. _P("404 leave %.16llx ERROR: not a member of that network",(unsigned long long)nwid);
  245. } else {
  246. nw->second->destroyOnDelete();
  247. _networks.erase(nw);
  248. }
  249. } else {
  250. _P("400 leave requires a network ID (>0) in hexadecimal format");
  251. }
  252. } else if (cmd[0] == "terminate") {
  253. if (cmd.size() > 1)
  254. _r->node->terminate(Node::NODE_NORMAL_TERMINATION,cmd[1].c_str());
  255. else _r->node->terminate(Node::NODE_NORMAL_TERMINATION,(const char *)0);
  256. } else if (cmd[0] == "updatecheck") {
  257. if (_r->updater) {
  258. _P("200 checking for software updates now at: %s",ZT_DEFAULTS.updateLatestNfoURL.c_str());
  259. _r->updater->checkNow();
  260. } else {
  261. _P("500 software updates are not enabled");
  262. }
  263. } else {
  264. _P("404 %s No such command. Use 'help' for help.",cmd[0].c_str());
  265. }
  266. r.push_back(std::string()); // terminate with empty line
  267. return r;
  268. }
  269. std::vector< Buffer<ZT_NODECONFIG_MAX_PACKET_SIZE> > NodeConfig::encodeControlMessage(const void *key,unsigned long conversationId,const std::vector<std::string> &payload)
  270. {
  271. char poly1305tag[ZT_POLY1305_MAC_LEN];
  272. char iv[8];
  273. char keytmp[32];
  274. std::vector< Buffer<ZT_NODECONFIG_MAX_PACKET_SIZE> > packets;
  275. Buffer<ZT_NODECONFIG_MAX_PACKET_SIZE> packet;
  276. packet.setSize(16); // room for poly1305 auth tag and IV
  277. packet.append((uint32_t)(conversationId & 0xffffffff));
  278. for(unsigned int i=0;i<payload.size();++i) {
  279. packet.append(payload[i]); // will throw if too big
  280. packet.append((unsigned char)0);
  281. if (((i + 1) >= payload.size())||((packet.size() + payload[i + 1].length() + 1) >= packet.capacity())) {
  282. Utils::getSecureRandom(iv,8);
  283. memcpy(packet.field(8,8),iv,8);
  284. Salsa20 s20(key,256,iv,ZT_PROTO_SALSA20_ROUNDS);
  285. s20.encrypt(packet.field(16,packet.size() - 16),packet.field(16,packet.size() - 16),packet.size() - 16);
  286. memcpy(keytmp,key,32);
  287. for(unsigned int i=0;i<8;++i)
  288. keytmp[i] ^= iv[i]; // can't reuse poly1305 keys, so mangle key with IV each time
  289. Poly1305::compute(poly1305tag,packet.field(16,packet.size() - 16),packet.size() - 16,keytmp);
  290. memcpy(packet.field(0,8),poly1305tag,8);
  291. packets.push_back(packet);
  292. packet.setSize(16); // room for poly1305 auth tag and IV
  293. packet.append((uint32_t)(conversationId & 0xffffffff));
  294. }
  295. }
  296. return packets;
  297. }
  298. bool NodeConfig::decodeControlMessagePacket(const void *key,const void *data,unsigned int len,unsigned long &conversationId,std::vector<std::string> &payload)
  299. {
  300. char poly1305tag[ZT_POLY1305_MAC_LEN];
  301. char keytmp[32];
  302. char iv[8];
  303. try {
  304. if (len < 20)
  305. return false;
  306. Buffer<ZT_NODECONFIG_MAX_PACKET_SIZE> packet(data,len);
  307. memcpy(keytmp,key,32);
  308. memcpy(iv,packet.field(8,8),8);
  309. for(unsigned int i=0;i<8;++i)
  310. keytmp[i] ^= iv[i];
  311. Poly1305::compute(poly1305tag,packet.field(16,packet.size() - 16),packet.size() - 16,keytmp);
  312. if (!Utils::secureEq(packet.field(0,8),poly1305tag,8))
  313. return false;
  314. Salsa20 s20(key,256,packet.field(8,8),ZT_PROTO_SALSA20_ROUNDS);
  315. s20.decrypt(packet.field(16,packet.size() - 16),packet.field(16,packet.size() - 16),packet.size() - 16);
  316. conversationId = packet.at<uint32_t>(16);
  317. const char *pl = ((const char *)packet.data()) + 20;
  318. unsigned int pll = packet.size() - 20;
  319. for(unsigned int i=0;i<pll;) {
  320. unsigned int eos = i;
  321. while ((eos < pll)&&(pl[eos]))
  322. ++eos;
  323. if (eos >= i) {
  324. payload.push_back(std::string(pl + i,eos - i));
  325. i = eos + 1;
  326. } else break;
  327. }
  328. return true;
  329. } catch ( ... ) {
  330. return false;
  331. }
  332. }
  333. void NodeConfig::_CBcontrolPacketHandler(UdpSocket *sock,void *arg,const InetAddress &remoteAddr,const void *data,unsigned int len)
  334. {
  335. NodeConfig *nc = (NodeConfig *)arg;
  336. #ifdef ZT_TRACE
  337. const RuntimeEnvironment *_r = nc->_r;
  338. #endif
  339. try {
  340. unsigned long convId = 0;
  341. std::vector<std::string> commands;
  342. if (!decodeControlMessagePacket(nc->_controlSocketKey,data,len,convId,commands)) {
  343. TRACE("control bus packet from %s failed decode, discarded",remoteAddr.toString().c_str());
  344. return;
  345. }
  346. TRACE("control bus packet from %s, contains %d commands",remoteAddr.toString().c_str(),(int)commands.size());
  347. for(std::vector<std::string>::iterator c(commands.begin());c!=commands.end();++c) {
  348. std::vector< Buffer<ZT_NODECONFIG_MAX_PACKET_SIZE> > resultPackets(encodeControlMessage(nc->_controlSocketKey,convId,nc->execute(c->c_str())));
  349. for(std::vector< Buffer<ZT_NODECONFIG_MAX_PACKET_SIZE> >::iterator p(resultPackets.begin());p!=resultPackets.end();++p)
  350. sock->send(remoteAddr,p->data(),p->size(),-1);
  351. }
  352. } catch (std::exception &exc) {
  353. TRACE("exception handling control bus packet from %s: %s",remoteAddr.toString().c_str(),exc.what());
  354. } catch ( ... ) {
  355. TRACE("exception handling control bus packet from %s: (unknown)",remoteAddr.toString().c_str());
  356. }
  357. }
  358. /////////////////////////////////////////////////////////////////////////////
  359. void NodeConfig::_readLocalConfig()
  360. {
  361. // assumes _localConfig_m is locked
  362. std::string localDotConf(_r->homePath + ZT_PATH_SEPARATOR_S + "local.conf");
  363. std::string buf;
  364. if (Utils::readFile(localDotConf.c_str(),buf))
  365. _localConfig.fromString(buf.c_str());
  366. }
  367. void NodeConfig::_writeLocalConfig()
  368. {
  369. // assumes _localConfig_m is locked
  370. Utils::writeFile(((_r->homePath + ZT_PATH_SEPARATOR_S + "local.conf")).c_str(),_localConfig.toString());
  371. }
  372. } // namespace ZeroTier