one.cpp 49 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560
  1. /*
  2. * ZeroTier One - Network Virtualization Everywhere
  3. * Copyright (C) 2011-2019 ZeroTier, Inc. https://www.zerotier.com/
  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. * You can be released from the requirements of the license by purchasing
  21. * a commercial license. Buying such a license is mandatory as soon as you
  22. * develop commercial closed-source software that incorporates or links
  23. * directly against ZeroTier software without disclosing the source code
  24. * of your own application.
  25. */
  26. #include <stdio.h>
  27. #include <stdlib.h>
  28. #include <string.h>
  29. #include <stdint.h>
  30. #include <time.h>
  31. #include <errno.h>
  32. #include "node/Constants.hpp"
  33. #ifdef __WINDOWS__
  34. #include <WinSock2.h>
  35. #include <Windows.h>
  36. #include <tchar.h>
  37. #include <wchar.h>
  38. #include <lmcons.h>
  39. #include <newdev.h>
  40. #include <atlbase.h>
  41. #include "osdep/WindowsEthernetTap.hpp"
  42. #include "windows/ZeroTierOne/ServiceInstaller.h"
  43. #include "windows/ZeroTierOne/ServiceBase.h"
  44. #include "windows/ZeroTierOne/ZeroTierOneService.h"
  45. #else
  46. #include <unistd.h>
  47. #include <pwd.h>
  48. #include <fcntl.h>
  49. #include <sys/types.h>
  50. #include <sys/stat.h>
  51. #include <sys/uio.h>
  52. #include <dirent.h>
  53. #include <signal.h>
  54. #ifdef __LINUX__
  55. #include <sys/prctl.h>
  56. #include <sys/syscall.h>
  57. #include <sys/wait.h>
  58. #ifndef ZT_NO_CAPABILITIES
  59. #include <linux/capability.h>
  60. #include <linux/securebits.h>
  61. #endif
  62. #endif
  63. #endif
  64. #include <string>
  65. #include <stdexcept>
  66. #include <iostream>
  67. #include <sstream>
  68. #include <algorithm>
  69. #include "version.h"
  70. #include "include/ZeroTierOne.h"
  71. #include "node/Identity.hpp"
  72. #include "node/CertificateOfMembership.hpp"
  73. #include "node/Utils.hpp"
  74. #include "node/NetworkController.hpp"
  75. #include "node/Buffer.hpp"
  76. #include "osdep/OSUtils.hpp"
  77. #include "osdep/Http.hpp"
  78. #include "osdep/Thread.hpp"
  79. #include "service/OneService.hpp"
  80. #include "ext/json/json.hpp"
  81. #define ZT_PID_PATH "zerotier-one.pid"
  82. using namespace ZeroTier;
  83. static OneService *volatile zt1Service = (OneService *)0;
  84. #define PROGRAM_NAME "ZeroTier One"
  85. #define COPYRIGHT_NOTICE "Copyright (c) 2011-2018 ZeroTier, Inc."
  86. #define LICENSE_GRANT \
  87. "This is free software: you may copy, modify, and/or distribute this" ZT_EOL_S \
  88. "work under the terms of the GNU General Public License, version 3 or" ZT_EOL_S \
  89. "later as published by the Free Software Foundation." ZT_EOL_S \
  90. "No warranty expressed or implied." ZT_EOL_S
  91. /****************************************************************************/
  92. /* zerotier-cli personality */
  93. /****************************************************************************/
  94. // This is getting deprecated soon in favor of the stuff in cli/
  95. static void cliPrintHelp(const char *pn,FILE *out)
  96. {
  97. fprintf(out,
  98. "%s version %d.%d.%d build %d (platform %d arch %d)" ZT_EOL_S,
  99. PROGRAM_NAME,
  100. ZEROTIER_ONE_VERSION_MAJOR, ZEROTIER_ONE_VERSION_MINOR, ZEROTIER_ONE_VERSION_REVISION, ZEROTIER_ONE_VERSION_BUILD,
  101. ZT_BUILD_PLATFORM, ZT_BUILD_ARCHITECTURE);
  102. fprintf(out,
  103. COPYRIGHT_NOTICE ZT_EOL_S
  104. LICENSE_GRANT ZT_EOL_S);
  105. fprintf(out,"Usage: %s [-switches] <command/path> [<args>]" ZT_EOL_S"" ZT_EOL_S,pn);
  106. fprintf(out,"Available switches:" ZT_EOL_S);
  107. fprintf(out," -h - Display this help" ZT_EOL_S);
  108. fprintf(out," -v - Show version" ZT_EOL_S);
  109. fprintf(out," -j - Display full raw JSON output" ZT_EOL_S);
  110. fprintf(out," -D<path> - ZeroTier home path for parameter auto-detect" ZT_EOL_S);
  111. fprintf(out," -p<port> - HTTP port (default: auto)" ZT_EOL_S);
  112. fprintf(out," -T<token> - Authentication token (default: auto)" ZT_EOL_S);
  113. fprintf(out,ZT_EOL_S"Available commands:" ZT_EOL_S);
  114. fprintf(out," info - Display status info" ZT_EOL_S);
  115. fprintf(out," listpeers - List all peers" ZT_EOL_S);
  116. fprintf(out," peers - List all peers (prettier)" ZT_EOL_S);
  117. fprintf(out," listnetworks - List all networks" ZT_EOL_S);
  118. fprintf(out," join <network> - Join a network" ZT_EOL_S);
  119. fprintf(out," leave <network> - Leave a network" ZT_EOL_S);
  120. fprintf(out," set <network> <setting> - Set a network setting" ZT_EOL_S);
  121. fprintf(out," get <network> <setting> - Get a network setting" ZT_EOL_S);
  122. fprintf(out,ZT_EOL_S"Available settings:" ZT_EOL_S);
  123. fprintf(out," Settings to use with [get/set] may include property names from " ZT_EOL_S);
  124. fprintf(out," the JSON output of \"zerotier-cli -j listnetworks\". Additionally, " ZT_EOL_S);
  125. fprintf(out," (ip, ip4, ip6, ip6plane, and ip6prefix can be used). For instance:" ZT_EOL_S);
  126. fprintf(out," zerotier-cli get <nwid> ip6plane will return the 6PLANE address" ZT_EOL_S);
  127. fprintf(out," assigned to this node." ZT_EOL_S);
  128. }
  129. static std::string cliFixJsonCRs(const std::string &s)
  130. {
  131. std::string r;
  132. for(std::string::const_iterator c(s.begin());c!=s.end();++c) {
  133. if (*c == '\n')
  134. r.append(ZT_EOL_S);
  135. else r.push_back(*c);
  136. }
  137. return r;
  138. }
  139. #ifdef __WINDOWS__
  140. static int cli(int argc, _TCHAR* argv[])
  141. #else
  142. static int cli(int argc,char **argv)
  143. #endif
  144. {
  145. unsigned int port = 0;
  146. std::string homeDir,command,arg1,arg2,authToken;
  147. std::string ip("127.0.0.1");
  148. bool json = false;
  149. for(int i=1;i<argc;++i) {
  150. if (argv[i][0] == '-') {
  151. switch(argv[i][1]) {
  152. case 'q': // ignore -q used to invoke this personality
  153. if (argv[i][2]) {
  154. cliPrintHelp(argv[0],stdout);
  155. return 1;
  156. }
  157. break;
  158. case 'j':
  159. if (argv[i][2]) {
  160. cliPrintHelp(argv[0],stdout);
  161. return 1;
  162. }
  163. json = true;
  164. break;
  165. case 'p':
  166. port = Utils::strToUInt(argv[i] + 2);
  167. if ((port > 0xffff)||(port == 0)) {
  168. cliPrintHelp(argv[0],stdout);
  169. return 1;
  170. }
  171. break;
  172. case 'D':
  173. if (argv[i][2]) {
  174. homeDir = argv[i] + 2;
  175. } else {
  176. cliPrintHelp(argv[0],stdout);
  177. return 1;
  178. }
  179. break;
  180. case 'H':
  181. if (argv[i][2]) {
  182. ip = argv[i] + 2;
  183. } else {
  184. cliPrintHelp(argv[0],stdout);
  185. return 1;
  186. }
  187. break;
  188. case 'T':
  189. if (argv[i][2]) {
  190. authToken = argv[i] + 2;
  191. } else {
  192. cliPrintHelp(argv[0],stdout);
  193. return 1;
  194. }
  195. break;
  196. case 'v':
  197. if (argv[i][2]) {
  198. cliPrintHelp(argv[0],stdout);
  199. return 1;
  200. }
  201. printf("%d.%d.%d" ZT_EOL_S,ZEROTIER_ONE_VERSION_MAJOR,ZEROTIER_ONE_VERSION_MINOR,ZEROTIER_ONE_VERSION_REVISION);
  202. return 0;
  203. case 'h':
  204. case '?':
  205. default:
  206. cliPrintHelp(argv[0],stdout);
  207. return 0;
  208. }
  209. } else {
  210. if (arg1.length())
  211. arg2 = argv[i];
  212. else if (command.length())
  213. arg1 = argv[i];
  214. else command = argv[i];
  215. }
  216. }
  217. if (!homeDir.length())
  218. homeDir = OneService::platformDefaultHomePath();
  219. if ((!port)||(!authToken.length())) {
  220. if (!homeDir.length()) {
  221. fprintf(stderr,"%s: missing port or authentication token and no home directory specified to auto-detect" ZT_EOL_S,argv[0]);
  222. return 2;
  223. }
  224. if (!port) {
  225. std::string portStr;
  226. OSUtils::readFile((homeDir + ZT_PATH_SEPARATOR_S + "zerotier-one.port").c_str(),portStr);
  227. port = Utils::strToUInt(portStr.c_str());
  228. if ((port == 0)||(port > 0xffff)) {
  229. fprintf(stderr,"%s: missing port and zerotier-one.port not found in %s" ZT_EOL_S,argv[0],homeDir.c_str());
  230. return 2;
  231. }
  232. }
  233. if (!authToken.length()) {
  234. OSUtils::readFile((homeDir + ZT_PATH_SEPARATOR_S + "authtoken.secret").c_str(),authToken);
  235. #ifdef __UNIX_LIKE__
  236. if (!authToken.length()) {
  237. const char *hd = getenv("HOME");
  238. if (hd) {
  239. char p[4096];
  240. #ifdef __APPLE__
  241. OSUtils::ztsnprintf(p,sizeof(p),"%s/Library/Application Support/ZeroTier/One/authtoken.secret",hd);
  242. #else
  243. OSUtils::ztsnprintf(p,sizeof(p),"%s/.zeroTierOneAuthToken",hd);
  244. #endif
  245. OSUtils::readFile(p,authToken);
  246. }
  247. }
  248. #endif
  249. if (!authToken.length()) {
  250. fprintf(stderr,"%s: missing authentication token and authtoken.secret not found (or readable) in %s" ZT_EOL_S,argv[0],homeDir.c_str());
  251. return 2;
  252. }
  253. }
  254. }
  255. InetAddress addr;
  256. {
  257. char addrtmp[256];
  258. OSUtils::ztsnprintf(addrtmp,sizeof(addrtmp),"%s/%u",ip.c_str(),port);
  259. addr = InetAddress(addrtmp);
  260. }
  261. std::map<std::string,std::string> requestHeaders;
  262. std::map<std::string,std::string> responseHeaders;
  263. std::string responseBody;
  264. requestHeaders["X-ZT1-Auth"] = authToken;
  265. if ((command.length() > 0)&&(command[0] == '/')) {
  266. unsigned int scode = Http::GET(
  267. 1024 * 1024 * 16,
  268. 60000,
  269. (const struct sockaddr *)&addr,
  270. command.c_str(),
  271. requestHeaders,
  272. responseHeaders,
  273. responseBody);
  274. if (scode == 200) {
  275. printf("%s", cliFixJsonCRs(responseBody).c_str());
  276. return 0;
  277. } else {
  278. printf("%u %s %s" ZT_EOL_S,scode,command.c_str(),responseBody.c_str());
  279. return 1;
  280. }
  281. } else if ((command == "info")||(command == "status")) {
  282. const unsigned int scode = Http::GET(1024 * 1024 * 16,60000,(const struct sockaddr *)&addr,"/status",requestHeaders,responseHeaders,responseBody);
  283. if (scode == 0) {
  284. printf("Error connecting to the ZeroTier service: %s\n\nPlease check that the service is running and that TCP port 9993 can be contacted via 127.0.0.1." ZT_EOL_S, responseBody.c_str());
  285. return 1;
  286. }
  287. nlohmann::json j;
  288. try {
  289. j = OSUtils::jsonParse(responseBody);
  290. } catch (std::exception &exc) {
  291. printf("%u %s invalid JSON response (%s)" ZT_EOL_S,scode,command.c_str(),exc.what());
  292. return 1;
  293. } catch ( ... ) {
  294. printf("%u %s invalid JSON response (unknown exception)" ZT_EOL_S,scode,command.c_str());
  295. return 1;
  296. }
  297. if (scode == 200) {
  298. if (json) {
  299. printf("%s" ZT_EOL_S,OSUtils::jsonDump(j).c_str());
  300. } else {
  301. if (j.is_object()) {
  302. printf("200 info %s %s %s" ZT_EOL_S,
  303. OSUtils::jsonString(j["address"],"-").c_str(),
  304. OSUtils::jsonString(j["version"],"-").c_str(),
  305. ((j["tcpFallbackActive"]) ? "TUNNELED" : ((j["online"]) ? "ONLINE" : "OFFLINE")));
  306. }
  307. }
  308. return 0;
  309. } else {
  310. printf("%u %s %s" ZT_EOL_S,scode,command.c_str(),responseBody.c_str());
  311. return 1;
  312. }
  313. } else if (command == "listpeers") {
  314. const unsigned int scode = Http::GET(1024 * 1024 * 16,60000,(const struct sockaddr *)&addr,"/peer",requestHeaders,responseHeaders,responseBody);
  315. if (scode == 0) {
  316. printf("Error connecting to the ZeroTier service: %s\n\nPlease check that the service is running and that TCP port 9993 can be contacted via 127.0.0.1." ZT_EOL_S, responseBody.c_str());
  317. return 1;
  318. }
  319. nlohmann::json j;
  320. try {
  321. j = OSUtils::jsonParse(responseBody);
  322. } catch (std::exception &exc) {
  323. printf("%u %s invalid JSON response (%s)" ZT_EOL_S,scode,command.c_str(),exc.what());
  324. return 1;
  325. } catch ( ... ) {
  326. printf("%u %s invalid JSON response (unknown exception)" ZT_EOL_S,scode,command.c_str());
  327. return 1;
  328. }
  329. if (scode == 200) {
  330. if (json) {
  331. printf("%s" ZT_EOL_S,OSUtils::jsonDump(j).c_str());
  332. } else {
  333. printf("200 listpeers <ztaddr> <path> <latency> <version> <role>" ZT_EOL_S);
  334. if (j.is_array()) {
  335. for(unsigned long k=0;k<j.size();++k) {
  336. nlohmann::json &p = j[k];
  337. std::string bestPath;
  338. nlohmann::json &paths = p["paths"];
  339. if (paths.is_array()) {
  340. for(unsigned long i=0;i<paths.size();++i) {
  341. nlohmann::json &path = paths[i];
  342. if (path["preferred"]) {
  343. char tmp[256];
  344. std::string addr = path["address"];
  345. const int64_t now = OSUtils::now();
  346. OSUtils::ztsnprintf(tmp,sizeof(tmp),"%s;%lld;%lld",addr.c_str(),now - (int64_t)path["lastSend"],now - (int64_t)path["lastReceive"]);
  347. bestPath = tmp;
  348. break;
  349. }
  350. }
  351. }
  352. if (bestPath.length() == 0) bestPath = "-";
  353. char ver[128];
  354. int64_t vmaj = p["versionMajor"];
  355. int64_t vmin = p["versionMinor"];
  356. int64_t vrev = p["versionRev"];
  357. if (vmaj >= 0) {
  358. OSUtils::ztsnprintf(ver,sizeof(ver),"%lld.%lld.%lld",vmaj,vmin,vrev);
  359. } else {
  360. ver[0] = '-';
  361. ver[1] = (char)0;
  362. }
  363. printf("200 listpeers %s %s %d %s %s" ZT_EOL_S,
  364. OSUtils::jsonString(p["address"],"-").c_str(),
  365. bestPath.c_str(),
  366. (int)OSUtils::jsonInt(p["latency"],0),
  367. ver,
  368. OSUtils::jsonString(p["role"],"-").c_str());
  369. }
  370. }
  371. }
  372. return 0;
  373. } else {
  374. printf("%u %s %s" ZT_EOL_S,scode,command.c_str(),responseBody.c_str());
  375. return 1;
  376. }
  377. } else if (command == "peers") {
  378. const unsigned int scode = Http::GET(1024 * 1024 * 16,60000,(const struct sockaddr *)&addr,"/peer",requestHeaders,responseHeaders,responseBody);
  379. if (scode == 0) {
  380. printf("Error connecting to the ZeroTier service: %s\n\nPlease check that the service is running and that TCP port 9993 can be contacted via 127.0.0.1." ZT_EOL_S, responseBody.c_str());
  381. return 1;
  382. }
  383. nlohmann::json j;
  384. try {
  385. j = OSUtils::jsonParse(responseBody);
  386. } catch (std::exception &exc) {
  387. printf("%u %s invalid JSON response (%s)" ZT_EOL_S,scode,command.c_str(),exc.what());
  388. return 1;
  389. } catch ( ... ) {
  390. printf("%u %s invalid JSON response (unknown exception)" ZT_EOL_S,scode,command.c_str());
  391. return 1;
  392. }
  393. if (scode == 200) {
  394. if (json) {
  395. printf("%s" ZT_EOL_S,OSUtils::jsonDump(j).c_str());
  396. } else {
  397. printf("200 peers\n<ztaddr> <ver> <role> <lat> <link> <lastTX> <lastRX> <path>" ZT_EOL_S);
  398. if (j.is_array()) {
  399. for(unsigned long k=0;k<j.size();++k) {
  400. nlohmann::json &p = j[k];
  401. std::string bestPath;
  402. nlohmann::json &paths = p["paths"];
  403. if (paths.is_array()) {
  404. for(unsigned long i=0;i<paths.size();++i) {
  405. nlohmann::json &path = paths[i];
  406. if (path["preferred"]) {
  407. char tmp[256];
  408. std::string addr = path["address"];
  409. const int64_t now = OSUtils::now();
  410. OSUtils::ztsnprintf(tmp,sizeof(tmp),"%-8lld %-8lld %s",now - (int64_t)path["lastSend"],now - (int64_t)path["lastReceive"],addr.c_str());
  411. bestPath = std::string("DIRECT ") + tmp;
  412. break;
  413. }
  414. }
  415. }
  416. if (bestPath.length() == 0) bestPath = "RELAY";
  417. char ver[128];
  418. int64_t vmaj = p["versionMajor"];
  419. int64_t vmin = p["versionMinor"];
  420. int64_t vrev = p["versionRev"];
  421. if (vmaj >= 0) {
  422. OSUtils::ztsnprintf(ver,sizeof(ver),"%lld.%lld.%lld",vmaj,vmin,vrev);
  423. } else {
  424. ver[0] = '-';
  425. ver[1] = (char)0;
  426. }
  427. printf("%s %-6s %-6s %5d %s" ZT_EOL_S,
  428. OSUtils::jsonString(p["address"],"-").c_str(),
  429. ver,
  430. OSUtils::jsonString(p["role"],"-").c_str(),
  431. (int)OSUtils::jsonInt(p["latency"],0),
  432. bestPath.c_str());
  433. }
  434. }
  435. }
  436. return 0;
  437. } else {
  438. printf("%u %s %s" ZT_EOL_S,scode,command.c_str(),responseBody.c_str());
  439. return 1;
  440. }
  441. } else if (command == "listnetworks") {
  442. const unsigned int scode = Http::GET(1024 * 1024 * 16,60000,(const struct sockaddr *)&addr,"/network",requestHeaders,responseHeaders,responseBody);
  443. if (scode == 0) {
  444. printf("Error connecting to the ZeroTier service: %s\n\nPlease check that the service is running and that TCP port 9993 can be contacted via 127.0.0.1." ZT_EOL_S, responseBody.c_str());
  445. return 1;
  446. }
  447. nlohmann::json j;
  448. try {
  449. j = OSUtils::jsonParse(responseBody);
  450. } catch (std::exception &exc) {
  451. printf("%u %s invalid JSON response (%s)" ZT_EOL_S,scode,command.c_str(),exc.what());
  452. return 1;
  453. } catch ( ... ) {
  454. printf("%u %s invalid JSON response (unknown exception)" ZT_EOL_S,scode,command.c_str());
  455. return 1;
  456. }
  457. if (scode == 200) {
  458. if (json) {
  459. printf("%s" ZT_EOL_S,OSUtils::jsonDump(j).c_str());
  460. } else {
  461. printf("200 listnetworks <nwid> <name> <mac> <status> <type> <dev> <ZT assigned ips>" ZT_EOL_S);
  462. if (j.is_array()) {
  463. for(unsigned long i=0;i<j.size();++i) {
  464. nlohmann::json &n = j[i];
  465. if (n.is_object()) {
  466. std::string aa;
  467. nlohmann::json &assignedAddresses = n["assignedAddresses"];
  468. if (assignedAddresses.is_array()) {
  469. for(unsigned long j=0;j<assignedAddresses.size();++j) {
  470. nlohmann::json &addr = assignedAddresses[j];
  471. if (addr.is_string()) {
  472. if (aa.length() > 0) aa.push_back(',');
  473. aa.append(addr.get<std::string>());
  474. }
  475. }
  476. }
  477. if (aa.length() == 0) aa = "-";
  478. printf("200 listnetworks %s %s %s %s %s %s %s" ZT_EOL_S,
  479. OSUtils::jsonString(n["nwid"],"-").c_str(),
  480. OSUtils::jsonString(n["name"],"-").c_str(),
  481. OSUtils::jsonString(n["mac"],"-").c_str(),
  482. OSUtils::jsonString(n["status"],"-").c_str(),
  483. OSUtils::jsonString(n["type"],"-").c_str(),
  484. OSUtils::jsonString(n["portDeviceName"],"-").c_str(),
  485. aa.c_str());
  486. }
  487. }
  488. }
  489. }
  490. return 0;
  491. } else {
  492. printf("%u %s %s" ZT_EOL_S,scode,command.c_str(),responseBody.c_str());
  493. return 1;
  494. }
  495. } else if (command == "join") {
  496. if (arg1.length() != 16) {
  497. printf("invalid network id" ZT_EOL_S);
  498. return 2;
  499. }
  500. requestHeaders["Content-Type"] = "application/json";
  501. requestHeaders["Content-Length"] = "2";
  502. unsigned int scode = Http::POST(
  503. 1024 * 1024 * 16,
  504. 60000,
  505. (const struct sockaddr *)&addr,
  506. (std::string("/network/") + arg1).c_str(),
  507. requestHeaders,
  508. "{}",
  509. 2,
  510. responseHeaders,
  511. responseBody);
  512. if (scode == 200) {
  513. if (json) {
  514. printf("%s",cliFixJsonCRs(responseBody).c_str());
  515. } else {
  516. printf("200 join OK" ZT_EOL_S);
  517. }
  518. return 0;
  519. } else {
  520. printf("%u %s %s" ZT_EOL_S,scode,command.c_str(),responseBody.c_str());
  521. return 1;
  522. }
  523. } else if (command == "leave") {
  524. if (arg1.length() != 16) {
  525. printf("invalid network id" ZT_EOL_S);
  526. return 2;
  527. }
  528. unsigned int scode = Http::DEL(
  529. 1024 * 1024 * 16,
  530. 60000,
  531. (const struct sockaddr *)&addr,
  532. (std::string("/network/") + arg1).c_str(),
  533. requestHeaders,
  534. responseHeaders,
  535. responseBody);
  536. if (scode == 200) {
  537. if (json) {
  538. printf("%s",cliFixJsonCRs(responseBody).c_str());
  539. } else {
  540. printf("200 leave OK" ZT_EOL_S);
  541. }
  542. return 0;
  543. } else {
  544. printf("%u %s %s" ZT_EOL_S,scode,command.c_str(),responseBody.c_str());
  545. return 1;
  546. }
  547. } else if (command == "set") {
  548. if (arg1.length() != 16) {
  549. fprintf(stderr,"invalid format: must be a 16-digit (network) ID\n");
  550. return 2;
  551. }
  552. if (!arg2.length()) {
  553. fprintf(stderr,"invalid format: include a property name to set\n");
  554. return 2;
  555. }
  556. std::size_t eqidx = arg2.find('=');
  557. if (eqidx != std::string::npos) {
  558. if ((arg2.substr(0,eqidx) == "allowManaged")||(arg2.substr(0,eqidx) == "allowGlobal")||(arg2.substr(0,eqidx) == "allowDefault")) {
  559. char jsons[1024];
  560. OSUtils::ztsnprintf(jsons,sizeof(jsons),"{\"%s\":%s}",
  561. arg2.substr(0,eqidx).c_str(),
  562. (((arg2.substr(eqidx,2) == "=t")||(arg2.substr(eqidx,2) == "=1")) ? "true" : "false"));
  563. char cl[128];
  564. OSUtils::ztsnprintf(cl,sizeof(cl),"%u",(unsigned int)strlen(jsons));
  565. requestHeaders["Content-Type"] = "application/json";
  566. requestHeaders["Content-Length"] = cl;
  567. unsigned int scode = Http::POST(
  568. 1024 * 1024 * 16,
  569. 60000,
  570. (const struct sockaddr *)&addr,
  571. (std::string("/network/") + arg1).c_str(),
  572. requestHeaders,
  573. jsons,
  574. (unsigned long)strlen(jsons),
  575. responseHeaders,
  576. responseBody);
  577. if (scode == 200) {
  578. printf("%s",cliFixJsonCRs(responseBody).c_str());
  579. return 0;
  580. } else {
  581. printf("%u %s %s" ZT_EOL_S,scode,command.c_str(),responseBody.c_str());
  582. return 1;
  583. }
  584. }
  585. } else {
  586. cliPrintHelp(argv[0],stderr);
  587. return 2;
  588. }
  589. } else if (command == "get") {
  590. if (arg1.length() != 16) {
  591. fprintf(stderr,"invalid format: must be a 16-digit (network) ID\n");
  592. return 2;
  593. }
  594. if (!arg2.length()) {
  595. fprintf(stderr,"invalid format: include a property name to get\n");
  596. return 2;
  597. }
  598. const unsigned int scode = Http::GET(1024 * 1024 * 16,60000,(const struct sockaddr *)&addr,"/network",requestHeaders,responseHeaders,responseBody);
  599. if (scode == 0) {
  600. printf("Error connecting to the ZeroTier service: %s\n\nPlease check that the service is running and that TCP port 9993 can be contacted via 127.0.0.1." ZT_EOL_S, responseBody.c_str());
  601. return 1;
  602. }
  603. nlohmann::json j;
  604. try {
  605. j = OSUtils::jsonParse(responseBody);
  606. } catch (std::exception &exc) {
  607. printf("%u %s invalid JSON response (%s)" ZT_EOL_S,scode,command.c_str(),exc.what());
  608. return 1;
  609. } catch ( ... ) {
  610. printf("%u %s invalid JSON response (unknown exception)" ZT_EOL_S,scode,command.c_str());
  611. return 1;
  612. }
  613. bool bNetworkFound = false;
  614. if (j.is_array()) {
  615. for(unsigned long i=0;i<j.size();++i) {
  616. nlohmann::json &n = j[i];
  617. if (n.is_object()) {
  618. if (n["id"] == arg1) {
  619. bNetworkFound = true;
  620. std::string aa;
  621. if (arg2 != "ip" && arg2 != "ip4" && arg2 != "ip6" && arg2 != "ip6plane" && arg2 != "ip6prefix") {
  622. aa.append(OSUtils::jsonString(n[arg2],"-")); // Standard network property field
  623. if (aa == "-") {
  624. printf("error, unknown property name\n");
  625. break;
  626. }
  627. printf("%s\n",aa.c_str());
  628. break;
  629. }
  630. nlohmann::json &assignedAddresses = n["assignedAddresses"];
  631. if (assignedAddresses.is_array()) {
  632. int matchingIdxs[ZT_MAX_ZT_ASSIGNED_ADDRESSES];
  633. int addressCountOfType = 0;
  634. for (int k = 0; k<std::min(ZT_MAX_ZT_ASSIGNED_ADDRESSES, (int)assignedAddresses.size());++k) {
  635. nlohmann::json &addr = assignedAddresses[k];
  636. if ((arg2 == "ip4" && addr.get<std::string>().find(".") != std::string::npos)
  637. || ((arg2.find("ip6") == 0) && addr.get<std::string>().find(":") != std::string::npos)
  638. || (arg2 == "ip")
  639. ) {
  640. matchingIdxs[addressCountOfType++] = k;
  641. }
  642. }
  643. for (int k=0; k<addressCountOfType; k++) {
  644. nlohmann::json &addr = assignedAddresses[matchingIdxs[k]];
  645. if (!addr.is_string()) {
  646. continue;
  647. }
  648. if (arg2.find("ip6p") == 0) {
  649. if (arg2 == "ip6plane") {
  650. if (addr.get<std::string>().find("fc") == 0) {
  651. aa.append(addr.get<std::string>().substr(0,addr.get<std::string>().find("/")));
  652. if (k < addressCountOfType-1) aa.append("\n");
  653. }
  654. }
  655. if (arg2 == "ip6prefix") {
  656. if (addr.get<std::string>().find("fc") == 0) {
  657. aa.append(addr.get<std::string>().substr(0,addr.get<std::string>().find("/")).substr(0,24));
  658. if (k < addressCountOfType-1) aa.append("\n");
  659. }
  660. }
  661. }
  662. else {
  663. aa.append(addr.get<std::string>().substr(0,addr.get<std::string>().find("/")));
  664. if (k < addressCountOfType-1) aa.append("\n");
  665. }
  666. }
  667. }
  668. printf("%s\n",aa.c_str());
  669. }
  670. }
  671. }
  672. }
  673. if (!bNetworkFound) {
  674. fprintf(stderr,"unknown network ID, check that you are a member of the network\n");
  675. }
  676. if (scode == 200) {
  677. return 0;
  678. } else {
  679. printf("%u %s %s" ZT_EOL_S,scode,command.c_str(),responseBody.c_str());
  680. return 1;
  681. }
  682. } else {
  683. cliPrintHelp(argv[0],stderr);
  684. return 0;
  685. }
  686. return 0;
  687. }
  688. /****************************************************************************/
  689. /* zerotier-idtool personality */
  690. /****************************************************************************/
  691. static void idtoolPrintHelp(FILE *out,const char *pn)
  692. {
  693. fprintf(out,
  694. "%s version %d.%d.%d" ZT_EOL_S,
  695. PROGRAM_NAME,
  696. ZEROTIER_ONE_VERSION_MAJOR, ZEROTIER_ONE_VERSION_MINOR, ZEROTIER_ONE_VERSION_REVISION);
  697. fprintf(out,
  698. COPYRIGHT_NOTICE ZT_EOL_S
  699. LICENSE_GRANT ZT_EOL_S);
  700. fprintf(out,"Usage: %s <command> [<args>]" ZT_EOL_S"" ZT_EOL_S"Commands:" ZT_EOL_S,pn);
  701. fprintf(out," generate [<identity.secret>] [<identity.public>] [<vanity>]" ZT_EOL_S);
  702. fprintf(out," validate <identity.secret/public>" ZT_EOL_S);
  703. fprintf(out," getpublic <identity.secret>" ZT_EOL_S);
  704. fprintf(out," sign <identity.secret> <file>" ZT_EOL_S);
  705. fprintf(out," verify <identity.secret/public> <file> <signature>" ZT_EOL_S);
  706. }
  707. static Identity getIdFromArg(char *arg)
  708. {
  709. Identity id;
  710. if ((strlen(arg) > 32)&&(arg[10] == ':')) { // identity is a literal on the command line
  711. if (id.fromString(arg))
  712. return id;
  713. } else { // identity is to be read from a file
  714. std::string idser;
  715. if (OSUtils::readFile(arg,idser)) {
  716. if (id.fromString(idser.c_str()))
  717. return id;
  718. }
  719. }
  720. return Identity();
  721. }
  722. #ifdef __WINDOWS__
  723. static int idtool(int argc, _TCHAR* argv[])
  724. #else
  725. static int idtool(int argc,char **argv)
  726. #endif
  727. {
  728. if (argc < 2) {
  729. idtoolPrintHelp(stdout,argv[0]);
  730. return 1;
  731. }
  732. if (!strcmp(argv[1],"generate")) {
  733. uint64_t vanity = 0;
  734. int vanityBits = 0;
  735. if (argc >= 5) {
  736. vanity = Utils::hexStrToU64(argv[4]) & 0xffffffffffULL;
  737. vanityBits = 4 * (int)strlen(argv[4]);
  738. if (vanityBits > 40)
  739. vanityBits = 40;
  740. }
  741. Identity id;
  742. for(;;) {
  743. id.generate(Identity::C25519);
  744. if ((id.address().toInt() >> (40 - vanityBits)) == vanity) {
  745. if (vanityBits > 0) {
  746. fprintf(stderr,"vanity address: found %.10llx !\n",(unsigned long long)id.address().toInt());
  747. }
  748. break;
  749. } else {
  750. fprintf(stderr,"vanity address: tried %.10llx looking for first %d bits of %.10llx\n",(unsigned long long)id.address().toInt(),vanityBits,(unsigned long long)(vanity << (40 - vanityBits)));
  751. }
  752. }
  753. char idtmp[1024];
  754. std::string idser = id.toString(true,idtmp);
  755. if (argc >= 3) {
  756. if (!OSUtils::writeFile(argv[2],idser)) {
  757. fprintf(stderr,"Error writing to %s" ZT_EOL_S,argv[2]);
  758. return 1;
  759. } else printf("%s written" ZT_EOL_S,argv[2]);
  760. if (argc >= 4) {
  761. idser = id.toString(false,idtmp);
  762. if (!OSUtils::writeFile(argv[3],idser)) {
  763. fprintf(stderr,"Error writing to %s" ZT_EOL_S,argv[3]);
  764. return 1;
  765. } else printf("%s written" ZT_EOL_S,argv[3]);
  766. }
  767. } else printf("%s",idser.c_str());
  768. } else if (!strcmp(argv[1],"validate")) {
  769. if (argc < 3) {
  770. idtoolPrintHelp(stdout,argv[0]);
  771. return 1;
  772. }
  773. Identity id = getIdFromArg(argv[2]);
  774. if (!id) {
  775. fprintf(stderr,"Identity argument invalid or file unreadable: %s" ZT_EOL_S,argv[2]);
  776. return 1;
  777. }
  778. if (!id.locallyValidate()) {
  779. fprintf(stderr,"%s FAILED validation." ZT_EOL_S,argv[2]);
  780. return 1;
  781. } else printf("%s is a valid identity" ZT_EOL_S,argv[2]);
  782. } else if (!strcmp(argv[1],"getpublic")) {
  783. if (argc < 3) {
  784. idtoolPrintHelp(stdout,argv[0]);
  785. return 1;
  786. }
  787. Identity id = getIdFromArg(argv[2]);
  788. if (!id) {
  789. fprintf(stderr,"Identity argument invalid or file unreadable: %s" ZT_EOL_S,argv[2]);
  790. return 1;
  791. }
  792. char idtmp[1024];
  793. printf("%s",id.toString(false,idtmp));
  794. } else if (!strcmp(argv[1],"sign")) {
  795. if (argc < 4) {
  796. idtoolPrintHelp(stdout,argv[0]);
  797. return 1;
  798. }
  799. Identity id = getIdFromArg(argv[2]);
  800. if (!id) {
  801. fprintf(stderr,"Identity argument invalid or file unreadable: %s" ZT_EOL_S,argv[2]);
  802. return 1;
  803. }
  804. if (!id.hasPrivate()) {
  805. fprintf(stderr,"%s does not contain a private key (must use private to sign)" ZT_EOL_S,argv[2]);
  806. return 1;
  807. }
  808. std::string inf;
  809. if (!OSUtils::readFile(argv[3],inf)) {
  810. fprintf(stderr,"%s is not readable" ZT_EOL_S,argv[3]);
  811. return 1;
  812. }
  813. uint8_t signature[ZT_SIGNATURE_BUFFER_SIZE];
  814. const unsigned int siglen = id.sign(inf.data(),(unsigned int)inf.length(),signature,sizeof(signature));
  815. char hexbuf[256];
  816. printf("%s",Utils::hex(signature,siglen,hexbuf));
  817. } else if (!strcmp(argv[1],"verify")) {
  818. if (argc < 5) {
  819. idtoolPrintHelp(stdout,argv[0]);
  820. return 1;
  821. }
  822. Identity id = getIdFromArg(argv[2]);
  823. if (!id) {
  824. fprintf(stderr,"Identity argument invalid or file unreadable: %s" ZT_EOL_S,argv[2]);
  825. return 1;
  826. }
  827. std::string inf;
  828. if (!OSUtils::readFile(argv[3],inf)) {
  829. fprintf(stderr,"%s is not readable" ZT_EOL_S,argv[3]);
  830. return 1;
  831. }
  832. char buf[4096];
  833. std::string signature(buf,Utils::unhex(argv[4],buf,(unsigned int)sizeof(buf)));
  834. if ((signature.length() > ZT_ADDRESS_LENGTH)&&(id.verify(inf.data(),(unsigned int)inf.length(),signature.data(),(unsigned int)signature.length()))) {
  835. printf("%s signature valid" ZT_EOL_S,argv[3]);
  836. } else {
  837. signature.clear();
  838. if (OSUtils::readFile(argv[4],signature)) {
  839. signature.assign(buf,Utils::unhex(signature.c_str(),buf,(unsigned int)sizeof(buf)));
  840. if ((signature.length() > ZT_ADDRESS_LENGTH)&&(id.verify(inf.data(),(unsigned int)inf.length(),signature.data(),(unsigned int)signature.length()))) {
  841. printf("%s signature valid" ZT_EOL_S,argv[3]);
  842. } else {
  843. fprintf(stderr,"%s signature check FAILED" ZT_EOL_S,argv[3]);
  844. return 1;
  845. }
  846. } else {
  847. fprintf(stderr,"%s signature check FAILED" ZT_EOL_S,argv[3]);
  848. return 1;
  849. }
  850. }
  851. } else {
  852. idtoolPrintHelp(stdout,argv[0]);
  853. return 1;
  854. }
  855. return 0;
  856. }
  857. /****************************************************************************/
  858. /* Unix helper functions and signal handlers */
  859. /****************************************************************************/
  860. #ifdef __UNIX_LIKE__
  861. static void _sighandlerHup(int sig)
  862. {
  863. }
  864. static void _sighandlerQuit(int sig)
  865. {
  866. OneService *s = zt1Service;
  867. if (s)
  868. s->terminate();
  869. else exit(0);
  870. }
  871. #endif
  872. // Drop privileges on Linux, if supported by libc etc. and "zerotier-one" user exists on system
  873. #if defined(__LINUX__) && !defined(ZT_NO_CAPABILITIES)
  874. #ifndef PR_CAP_AMBIENT
  875. #define PR_CAP_AMBIENT 47
  876. #define PR_CAP_AMBIENT_IS_SET 1
  877. #define PR_CAP_AMBIENT_RAISE 2
  878. #define PR_CAP_AMBIENT_LOWER 3
  879. #define PR_CAP_AMBIENT_CLEAR_ALL 4
  880. #endif
  881. #define ZT_LINUX_USER "zerotier-one"
  882. #define ZT_HAVE_DROP_PRIVILEGES 1
  883. namespace {
  884. // libc doesn't export capset, it is instead located in libcap
  885. // We ignore libcap and call it manually.
  886. struct cap_header_struct {
  887. __u32 version;
  888. int pid;
  889. };
  890. struct cap_data_struct {
  891. __u32 effective;
  892. __u32 permitted;
  893. __u32 inheritable;
  894. };
  895. static inline int _zt_capset(cap_header_struct* hdrp, cap_data_struct* datap) { return syscall(SYS_capset, hdrp, datap); }
  896. static void _notDropping(const char *procName,const std::string &homeDir)
  897. {
  898. struct stat buf;
  899. if (lstat(homeDir.c_str(),&buf) < 0) {
  900. if (buf.st_uid != 0 || buf.st_gid != 0) {
  901. fprintf(stderr, "%s: FATAL: failed to drop privileges and can't run as root since privileges were previously dropped (home directory not owned by root)" ZT_EOL_S,procName);
  902. exit(1);
  903. }
  904. }
  905. fprintf(stderr, "%s: WARNING: failed to drop privileges (kernel may not support required prctl features), running as root" ZT_EOL_S,procName);
  906. }
  907. static int _setCapabilities(int flags)
  908. {
  909. cap_header_struct capheader = {_LINUX_CAPABILITY_VERSION_1, 0};
  910. cap_data_struct capdata;
  911. capdata.inheritable = capdata.permitted = capdata.effective = flags;
  912. return _zt_capset(&capheader, &capdata);
  913. }
  914. static void _recursiveChown(const char *path,uid_t uid,gid_t gid)
  915. {
  916. struct dirent de;
  917. struct dirent *dptr;
  918. lchown(path,uid,gid);
  919. DIR *d = opendir(path);
  920. if (!d)
  921. return;
  922. dptr = (struct dirent *)0;
  923. for(;;) {
  924. if (readdir_r(d,&de,&dptr) != 0)
  925. break;
  926. if (!dptr)
  927. break;
  928. if ((strcmp(dptr->d_name,".") != 0)&&(strcmp(dptr->d_name,"..") != 0)&&(strlen(dptr->d_name) > 0)) {
  929. std::string p(path);
  930. p.push_back(ZT_PATH_SEPARATOR);
  931. p.append(dptr->d_name);
  932. _recursiveChown(p.c_str(),uid,gid); // will just fail and return on regular files
  933. }
  934. }
  935. closedir(d);
  936. }
  937. static void dropPrivileges(const char *procName,const std::string &homeDir)
  938. {
  939. if (getuid() != 0)
  940. return;
  941. // dropPrivileges switches to zerotier-one user while retaining CAP_NET_ADMIN
  942. // and CAP_NET_RAW capabilities.
  943. struct passwd *targetUser = getpwnam(ZT_LINUX_USER);
  944. if (!targetUser)
  945. return;
  946. if (prctl(PR_CAP_AMBIENT, PR_CAP_AMBIENT_IS_SET, CAP_NET_RAW, 0, 0) < 0) {
  947. // Kernel has no support for ambient capabilities.
  948. _notDropping(procName,homeDir);
  949. return;
  950. }
  951. if (prctl(PR_SET_SECUREBITS, SECBIT_KEEP_CAPS | SECBIT_NOROOT) < 0) {
  952. _notDropping(procName,homeDir);
  953. return;
  954. }
  955. // Change ownership of our home directory if everything looks good (does nothing if already chown'd)
  956. _recursiveChown(homeDir.c_str(),targetUser->pw_uid,targetUser->pw_gid);
  957. if (_setCapabilities((1 << CAP_NET_ADMIN) | (1 << CAP_NET_RAW) | (1 << CAP_SETUID) | (1 << CAP_SETGID) | (1 << CAP_NET_BIND_SERVICE)) < 0) {
  958. _notDropping(procName,homeDir);
  959. return;
  960. }
  961. int oldDumpable = prctl(PR_GET_DUMPABLE);
  962. if (prctl(PR_SET_DUMPABLE, 0) < 0) {
  963. // Disable ptracing. Otherwise there is a small window when previous
  964. // compromised ZeroTier process could ptrace us, when we still have CAP_SETUID.
  965. // (this is mitigated anyway on most distros by ptrace_scope=1)
  966. fprintf(stderr,"%s: FATAL: prctl(PR_SET_DUMPABLE) failed while attempting to relinquish root permissions" ZT_EOL_S,procName);
  967. exit(1);
  968. }
  969. // Relinquish root
  970. if (setgid(targetUser->pw_gid) < 0) {
  971. perror("setgid");
  972. exit(1);
  973. }
  974. if (setuid(targetUser->pw_uid) < 0) {
  975. perror("setuid");
  976. exit(1);
  977. }
  978. if (_setCapabilities((1 << CAP_NET_ADMIN) | (1 << CAP_NET_RAW) | (1 << CAP_NET_BIND_SERVICE)) < 0) {
  979. fprintf(stderr,"%s: FATAL: unable to drop capabilities after relinquishing root" ZT_EOL_S,procName);
  980. exit(1);
  981. }
  982. if (prctl(PR_SET_DUMPABLE, oldDumpable) < 0) {
  983. fprintf(stderr,"%s: FATAL: prctl(PR_SET_DUMPABLE) failed while attempting to relinquish root permissions" ZT_EOL_S,procName);
  984. exit(1);
  985. }
  986. if (prctl(PR_CAP_AMBIENT, PR_CAP_AMBIENT_RAISE, CAP_NET_ADMIN, 0, 0) < 0) {
  987. fprintf(stderr,"%s: FATAL: prctl(PR_CAP_AMBIENT,PR_CAP_AMBIENT_RAISE,CAP_NET_ADMIN) failed while attempting to relinquish root permissions" ZT_EOL_S,procName);
  988. exit(1);
  989. }
  990. if (prctl(PR_CAP_AMBIENT, PR_CAP_AMBIENT_RAISE, CAP_NET_RAW, 0, 0) < 0) {
  991. fprintf(stderr,"%s: FATAL: prctl(PR_CAP_AMBIENT,PR_CAP_AMBIENT_RAISE,CAP_NET_RAW) failed while attempting to relinquish root permissions" ZT_EOL_S,procName);
  992. exit(1);
  993. }
  994. }
  995. } // anonymous namespace
  996. #endif // __LINUX__
  997. /****************************************************************************/
  998. /* Windows helper functions and signal handlers */
  999. /****************************************************************************/
  1000. #ifdef __WINDOWS__
  1001. // Console signal handler routine to allow CTRL+C to work, mostly for testing
  1002. static BOOL WINAPI _winConsoleCtrlHandler(DWORD dwCtrlType)
  1003. {
  1004. switch(dwCtrlType) {
  1005. case CTRL_C_EVENT:
  1006. case CTRL_BREAK_EVENT:
  1007. case CTRL_CLOSE_EVENT:
  1008. case CTRL_SHUTDOWN_EVENT:
  1009. OneService *s = zt1Service;
  1010. if (s)
  1011. s->terminate();
  1012. return TRUE;
  1013. }
  1014. return FALSE;
  1015. }
  1016. static void _winPokeAHole()
  1017. {
  1018. char myPath[MAX_PATH];
  1019. DWORD ps = GetModuleFileNameA(NULL,myPath,sizeof(myPath));
  1020. if ((ps > 0)&&(ps < (DWORD)sizeof(myPath))) {
  1021. STARTUPINFOA startupInfo;
  1022. PROCESS_INFORMATION processInfo;
  1023. startupInfo.cb = sizeof(startupInfo);
  1024. memset(&startupInfo,0,sizeof(STARTUPINFOA));
  1025. memset(&processInfo,0,sizeof(PROCESS_INFORMATION));
  1026. if (CreateProcessA(NULL,(LPSTR)(std::string("C:\\Windows\\System32\\netsh.exe advfirewall firewall delete rule name=\"ZeroTier One\" program=\"") + myPath + "\"").c_str(),NULL,NULL,FALSE,CREATE_NO_WINDOW,NULL,NULL,&startupInfo,&processInfo)) {
  1027. WaitForSingleObject(processInfo.hProcess,INFINITE);
  1028. CloseHandle(processInfo.hProcess);
  1029. CloseHandle(processInfo.hThread);
  1030. }
  1031. startupInfo.cb = sizeof(startupInfo);
  1032. memset(&startupInfo,0,sizeof(STARTUPINFOA));
  1033. memset(&processInfo,0,sizeof(PROCESS_INFORMATION));
  1034. if (CreateProcessA(NULL,(LPSTR)(std::string("C:\\Windows\\System32\\netsh.exe advfirewall firewall add rule name=\"ZeroTier One\" dir=in action=allow program=\"") + myPath + "\" enable=yes").c_str(),NULL,NULL,FALSE,CREATE_NO_WINDOW,NULL,NULL,&startupInfo,&processInfo)) {
  1035. WaitForSingleObject(processInfo.hProcess,INFINITE);
  1036. CloseHandle(processInfo.hProcess);
  1037. CloseHandle(processInfo.hThread);
  1038. }
  1039. startupInfo.cb = sizeof(startupInfo);
  1040. memset(&startupInfo,0,sizeof(STARTUPINFOA));
  1041. memset(&processInfo,0,sizeof(PROCESS_INFORMATION));
  1042. if (CreateProcessA(NULL,(LPSTR)(std::string("C:\\Windows\\System32\\netsh.exe advfirewall firewall add rule name=\"ZeroTier One\" dir=out action=allow program=\"") + myPath + "\" enable=yes").c_str(),NULL,NULL,FALSE,CREATE_NO_WINDOW,NULL,NULL,&startupInfo,&processInfo)) {
  1043. WaitForSingleObject(processInfo.hProcess,INFINITE);
  1044. CloseHandle(processInfo.hProcess);
  1045. CloseHandle(processInfo.hThread);
  1046. }
  1047. }
  1048. }
  1049. // Returns true if this is running as the local administrator
  1050. static BOOL IsCurrentUserLocalAdministrator(void)
  1051. {
  1052. BOOL fReturn = FALSE;
  1053. DWORD dwStatus;
  1054. DWORD dwAccessMask;
  1055. DWORD dwAccessDesired;
  1056. DWORD dwACLSize;
  1057. DWORD dwStructureSize = sizeof(PRIVILEGE_SET);
  1058. PACL pACL = NULL;
  1059. PSID psidAdmin = NULL;
  1060. HANDLE hToken = NULL;
  1061. HANDLE hImpersonationToken = NULL;
  1062. PRIVILEGE_SET ps;
  1063. GENERIC_MAPPING GenericMapping;
  1064. PSECURITY_DESCRIPTOR psdAdmin = NULL;
  1065. SID_IDENTIFIER_AUTHORITY SystemSidAuthority = SECURITY_NT_AUTHORITY;
  1066. const DWORD ACCESS_READ = 1;
  1067. const DWORD ACCESS_WRITE = 2;
  1068. __try
  1069. {
  1070. if (!OpenThreadToken(GetCurrentThread(), TOKEN_DUPLICATE|TOKEN_QUERY,TRUE,&hToken))
  1071. {
  1072. if (GetLastError() != ERROR_NO_TOKEN)
  1073. __leave;
  1074. if (!OpenProcessToken(GetCurrentProcess(),TOKEN_DUPLICATE|TOKEN_QUERY, &hToken))
  1075. __leave;
  1076. }
  1077. if (!DuplicateToken (hToken, SecurityImpersonation,&hImpersonationToken))
  1078. __leave;
  1079. if (!AllocateAndInitializeSid(&SystemSidAuthority, 2,
  1080. SECURITY_BUILTIN_DOMAIN_RID,
  1081. DOMAIN_ALIAS_RID_ADMINS,
  1082. 0, 0, 0, 0, 0, 0, &psidAdmin))
  1083. __leave;
  1084. psdAdmin = LocalAlloc(LPTR, SECURITY_DESCRIPTOR_MIN_LENGTH);
  1085. if (psdAdmin == NULL)
  1086. __leave;
  1087. if (!InitializeSecurityDescriptor(psdAdmin,SECURITY_DESCRIPTOR_REVISION))
  1088. __leave;
  1089. dwACLSize = sizeof(ACL) + sizeof(ACCESS_ALLOWED_ACE) + GetLengthSid(psidAdmin) - sizeof(DWORD);
  1090. pACL = (PACL)LocalAlloc(LPTR, dwACLSize);
  1091. if (pACL == NULL)
  1092. __leave;
  1093. if (!InitializeAcl(pACL, dwACLSize, ACL_REVISION2))
  1094. __leave;
  1095. dwAccessMask= ACCESS_READ | ACCESS_WRITE;
  1096. if (!AddAccessAllowedAce(pACL, ACL_REVISION2, dwAccessMask, psidAdmin))
  1097. __leave;
  1098. if (!SetSecurityDescriptorDacl(psdAdmin, TRUE, pACL, FALSE))
  1099. __leave;
  1100. SetSecurityDescriptorGroup(psdAdmin, psidAdmin, FALSE);
  1101. SetSecurityDescriptorOwner(psdAdmin, psidAdmin, FALSE);
  1102. if (!IsValidSecurityDescriptor(psdAdmin))
  1103. __leave;
  1104. dwAccessDesired = ACCESS_READ;
  1105. GenericMapping.GenericRead = ACCESS_READ;
  1106. GenericMapping.GenericWrite = ACCESS_WRITE;
  1107. GenericMapping.GenericExecute = 0;
  1108. GenericMapping.GenericAll = ACCESS_READ | ACCESS_WRITE;
  1109. if (!AccessCheck(psdAdmin, hImpersonationToken, dwAccessDesired,
  1110. &GenericMapping, &ps, &dwStructureSize, &dwStatus,
  1111. &fReturn))
  1112. {
  1113. fReturn = FALSE;
  1114. __leave;
  1115. }
  1116. }
  1117. __finally
  1118. {
  1119. // Clean up.
  1120. if (pACL) LocalFree(pACL);
  1121. if (psdAdmin) LocalFree(psdAdmin);
  1122. if (psidAdmin) FreeSid(psidAdmin);
  1123. if (hImpersonationToken) CloseHandle (hImpersonationToken);
  1124. if (hToken) CloseHandle (hToken);
  1125. }
  1126. return fReturn;
  1127. }
  1128. #endif // __WINDOWS__
  1129. /****************************************************************************/
  1130. /* main() and friends */
  1131. /****************************************************************************/
  1132. static void printHelp(const char *cn,FILE *out)
  1133. {
  1134. fprintf(out,
  1135. "%s version %d.%d.%d" ZT_EOL_S,
  1136. PROGRAM_NAME,
  1137. ZEROTIER_ONE_VERSION_MAJOR, ZEROTIER_ONE_VERSION_MINOR, ZEROTIER_ONE_VERSION_REVISION);
  1138. fprintf(out,
  1139. COPYRIGHT_NOTICE ZT_EOL_S
  1140. LICENSE_GRANT ZT_EOL_S);
  1141. fprintf(out,"Usage: %s [-switches] [home directory]" ZT_EOL_S"" ZT_EOL_S,cn);
  1142. fprintf(out,"Available switches:" ZT_EOL_S);
  1143. fprintf(out," -h - Display this help" ZT_EOL_S);
  1144. fprintf(out," -v - Show version" ZT_EOL_S);
  1145. fprintf(out," -U - Skip privilege check and do not attempt to drop privileges" ZT_EOL_S);
  1146. fprintf(out," -p<port> - Port for UDP and TCP/HTTP (default: 9993, 0 for random)" ZT_EOL_S);
  1147. #ifdef __UNIX_LIKE__
  1148. fprintf(out," -d - Fork and run as daemon (Unix-ish OSes)" ZT_EOL_S);
  1149. #endif // __UNIX_LIKE__
  1150. #ifdef __WINDOWS__
  1151. fprintf(out," -C - Run from command line instead of as service (Windows)" ZT_EOL_S);
  1152. fprintf(out," -I - Install Windows service (Windows)" ZT_EOL_S);
  1153. fprintf(out," -R - Uninstall Windows service (Windows)" ZT_EOL_S);
  1154. fprintf(out," -D - Remove all instances of Windows tap device (Windows)" ZT_EOL_S);
  1155. #endif // __WINDOWS__
  1156. fprintf(out," -i - Generate and manage identities (zerotier-idtool)" ZT_EOL_S);
  1157. fprintf(out," -q - Query API (zerotier-cli)" ZT_EOL_S);
  1158. }
  1159. class _OneServiceRunner
  1160. {
  1161. public:
  1162. _OneServiceRunner(const char *pn,const std::string &hd,unsigned int p) : progname(pn),returnValue(0),port(p),homeDir(hd) {}
  1163. void threadMain()
  1164. throw()
  1165. {
  1166. try {
  1167. for(;;) {
  1168. zt1Service = OneService::newInstance(homeDir.c_str(),port);
  1169. switch(zt1Service->run()) {
  1170. case OneService::ONE_STILL_RUNNING: // shouldn't happen, run() won't return until done
  1171. case OneService::ONE_NORMAL_TERMINATION:
  1172. break;
  1173. case OneService::ONE_UNRECOVERABLE_ERROR:
  1174. fprintf(stderr,"%s: fatal error: %s" ZT_EOL_S,progname,zt1Service->fatalErrorMessage().c_str());
  1175. returnValue = 1;
  1176. break;
  1177. case OneService::ONE_IDENTITY_COLLISION: {
  1178. delete zt1Service;
  1179. zt1Service = (OneService *)0;
  1180. std::string oldid;
  1181. OSUtils::readFile((homeDir + ZT_PATH_SEPARATOR_S + "identity.secret").c_str(),oldid);
  1182. if (oldid.length()) {
  1183. OSUtils::writeFile((homeDir + ZT_PATH_SEPARATOR_S + "identity.secret.saved_after_collision").c_str(),oldid);
  1184. OSUtils::rm((homeDir + ZT_PATH_SEPARATOR_S + "identity.secret").c_str());
  1185. OSUtils::rm((homeDir + ZT_PATH_SEPARATOR_S + "identity.public").c_str());
  1186. }
  1187. } continue; // restart!
  1188. }
  1189. break; // terminate loop -- normally we don't keep restarting
  1190. }
  1191. delete zt1Service;
  1192. zt1Service = (OneService *)0;
  1193. } catch ( ... ) {
  1194. fprintf(stderr,"%s: unexpected exception starting main OneService instance" ZT_EOL_S,progname);
  1195. returnValue = 1;
  1196. }
  1197. }
  1198. const char *progname;
  1199. unsigned int returnValue;
  1200. unsigned int port;
  1201. const std::string &homeDir;
  1202. };
  1203. #ifdef __WINDOWS__
  1204. int __cdecl _tmain(int argc, _TCHAR* argv[])
  1205. #else
  1206. int main(int argc,char **argv)
  1207. #endif
  1208. {
  1209. #ifdef __UNIX_LIKE__
  1210. signal(SIGHUP,&_sighandlerHup);
  1211. signal(SIGPIPE,SIG_IGN);
  1212. signal(SIGIO,SIG_IGN);
  1213. signal(SIGUSR1,SIG_IGN);
  1214. signal(SIGUSR2,SIG_IGN);
  1215. signal(SIGALRM,SIG_IGN);
  1216. signal(SIGINT,&_sighandlerQuit);
  1217. signal(SIGTERM,&_sighandlerQuit);
  1218. signal(SIGQUIT,&_sighandlerQuit);
  1219. signal(SIGINT,&_sighandlerQuit);
  1220. /* Ensure that there are no inherited file descriptors open from a previous
  1221. * incarnation. This is a hack to ensure that GitHub issue #61 or variants
  1222. * of it do not return, and should not do anything otherwise bad. */
  1223. {
  1224. int mfd = STDIN_FILENO;
  1225. if (STDOUT_FILENO > mfd) mfd = STDOUT_FILENO;
  1226. if (STDERR_FILENO > mfd) mfd = STDERR_FILENO;
  1227. for(int f=mfd+1;f<1024;++f)
  1228. ::close(f);
  1229. }
  1230. bool runAsDaemon = false;
  1231. #endif // __UNIX_LIKE__
  1232. #ifdef __WINDOWS__
  1233. {
  1234. WSADATA wsaData;
  1235. WSAStartup(MAKEWORD(2,2),&wsaData);
  1236. }
  1237. #ifdef ZT_WIN_RUN_IN_CONSOLE
  1238. bool winRunFromCommandLine = true;
  1239. #else
  1240. bool winRunFromCommandLine = false;
  1241. #endif
  1242. #endif // __WINDOWS__
  1243. if ((strstr(argv[0],"zerotier-idtool"))||(strstr(argv[0],"ZEROTIER-IDTOOL")))
  1244. return idtool(argc,argv);
  1245. if ((strstr(argv[0],"zerotier-cli"))||(strstr(argv[0],"ZEROTIER-CLI")))
  1246. return cli(argc,argv);
  1247. std::string homeDir;
  1248. unsigned int port = ZT_DEFAULT_PORT;
  1249. bool skipRootCheck = false;
  1250. for(int i=1;i<argc;++i) {
  1251. if (argv[i][0] == '-') {
  1252. switch(argv[i][1]) {
  1253. case 'p': // port -- for both UDP and TCP, packets and control plane
  1254. port = Utils::strToUInt(argv[i] + 2);
  1255. if (port > 0xffff) {
  1256. printHelp(argv[0],stdout);
  1257. return 1;
  1258. }
  1259. break;
  1260. #ifdef __UNIX_LIKE__
  1261. case 'd': // Run in background as daemon
  1262. runAsDaemon = true;
  1263. break;
  1264. #endif // __UNIX_LIKE__
  1265. case 'U':
  1266. skipRootCheck = true;
  1267. break;
  1268. case 'v': // Display version
  1269. printf("%d.%d.%d" ZT_EOL_S,ZEROTIER_ONE_VERSION_MAJOR,ZEROTIER_ONE_VERSION_MINOR,ZEROTIER_ONE_VERSION_REVISION);
  1270. return 0;
  1271. case 'i': // Invoke idtool personality
  1272. if (argv[i][2]) {
  1273. printHelp(argv[0],stdout);
  1274. return 0;
  1275. } else return idtool(argc-1,argv+1);
  1276. case 'q': // Invoke cli personality
  1277. if (argv[i][2]) {
  1278. printHelp(argv[0],stdout);
  1279. return 0;
  1280. } else return cli(argc,argv);
  1281. #ifdef __WINDOWS__
  1282. case 'C': // Run from command line instead of as Windows service
  1283. winRunFromCommandLine = true;
  1284. break;
  1285. case 'I': { // Install this binary as a Windows service
  1286. if (IsCurrentUserLocalAdministrator() != TRUE) {
  1287. fprintf(stderr,"%s: must be run as a local administrator." ZT_EOL_S,argv[0]);
  1288. return 1;
  1289. }
  1290. std::string ret(InstallService(ZT_SERVICE_NAME,ZT_SERVICE_DISPLAY_NAME,ZT_SERVICE_START_TYPE,ZT_SERVICE_DEPENDENCIES,ZT_SERVICE_ACCOUNT,ZT_SERVICE_PASSWORD));
  1291. if (ret.length()) {
  1292. fprintf(stderr,"%s: unable to install service: %s" ZT_EOL_S,argv[0],ret.c_str());
  1293. return 3;
  1294. }
  1295. return 0;
  1296. } break;
  1297. case 'R': { // Uninstall this binary as Windows service
  1298. if (IsCurrentUserLocalAdministrator() != TRUE) {
  1299. fprintf(stderr,"%s: must be run as a local administrator." ZT_EOL_S,argv[0]);
  1300. return 1;
  1301. }
  1302. std::string ret(UninstallService(ZT_SERVICE_NAME));
  1303. if (ret.length()) {
  1304. fprintf(stderr,"%s: unable to uninstall service: %s" ZT_EOL_S,argv[0],ret.c_str());
  1305. return 3;
  1306. }
  1307. return 0;
  1308. } break;
  1309. case 'D': {
  1310. std::string err = WindowsEthernetTap::destroyAllPersistentTapDevices();
  1311. if (err.length() > 0) {
  1312. fprintf(stderr,"%s: unable to uninstall one or more persistent tap devices: %s" ZT_EOL_S,argv[0],err.c_str());
  1313. return 3;
  1314. }
  1315. return 0;
  1316. } break;
  1317. #endif // __WINDOWS__
  1318. case 'h':
  1319. case '?':
  1320. default:
  1321. printHelp(argv[0],stdout);
  1322. return 0;
  1323. }
  1324. } else {
  1325. if (homeDir.length()) {
  1326. printHelp(argv[0],stdout);
  1327. return 0;
  1328. } else {
  1329. homeDir = argv[i];
  1330. }
  1331. }
  1332. }
  1333. if (!homeDir.length())
  1334. homeDir = OneService::platformDefaultHomePath();
  1335. if (!homeDir.length()) {
  1336. fprintf(stderr,"%s: no home path specified and no platform default available" ZT_EOL_S,argv[0]);
  1337. return 1;
  1338. } else {
  1339. std::vector<std::string> hpsp(OSUtils::split(homeDir.c_str(),ZT_PATH_SEPARATOR_S,"",""));
  1340. std::string ptmp;
  1341. if (homeDir[0] == ZT_PATH_SEPARATOR)
  1342. ptmp.push_back(ZT_PATH_SEPARATOR);
  1343. for(std::vector<std::string>::iterator pi(hpsp.begin());pi!=hpsp.end();++pi) {
  1344. if (ptmp.length() > 0)
  1345. ptmp.push_back(ZT_PATH_SEPARATOR);
  1346. ptmp.append(*pi);
  1347. if ((*pi != ".")&&(*pi != "..")) {
  1348. if (!OSUtils::mkdir(ptmp))
  1349. throw std::runtime_error("home path does not exist, and could not create");
  1350. }
  1351. }
  1352. }
  1353. // This can be removed once the new controller code has been around for many versions
  1354. if (OSUtils::fileExists((homeDir + ZT_PATH_SEPARATOR_S + "controller.db").c_str(),true)) {
  1355. fprintf(stderr,"%s: FATAL: an old controller.db exists in %s -- see instructions in controller/README.md for how to migrate!" ZT_EOL_S,argv[0],homeDir.c_str());
  1356. return 1;
  1357. }
  1358. #ifdef __UNIX_LIKE__
  1359. #ifndef ZT_ONE_NO_ROOT_CHECK
  1360. if ((!skipRootCheck)&&(getuid() != 0)) {
  1361. fprintf(stderr,"%s: must be run as root (uid 0)" ZT_EOL_S,argv[0]);
  1362. return 1;
  1363. }
  1364. #endif // !ZT_ONE_NO_ROOT_CHECK
  1365. if (runAsDaemon) {
  1366. long p = (long)fork();
  1367. if (p < 0) {
  1368. fprintf(stderr,"%s: could not fork" ZT_EOL_S,argv[0]);
  1369. return 1;
  1370. } else if (p > 0)
  1371. return 0; // forked
  1372. // else p == 0, so we are daemonized
  1373. }
  1374. #endif // __UNIX_LIKE__
  1375. #ifdef __WINDOWS__
  1376. // Uninstall legacy tap devices. New devices will automatically be installed and configured
  1377. // when tap instances are created.
  1378. WindowsEthernetTap::destroyAllLegacyPersistentTapDevices();
  1379. if (winRunFromCommandLine) {
  1380. // Running in "interactive" mode (mostly for debugging)
  1381. if (IsCurrentUserLocalAdministrator() != TRUE) {
  1382. if (!skipRootCheck) {
  1383. fprintf(stderr,"%s: must be run as a local administrator." ZT_EOL_S,argv[0]);
  1384. return 1;
  1385. }
  1386. } else {
  1387. _winPokeAHole();
  1388. }
  1389. SetConsoleCtrlHandler(&_winConsoleCtrlHandler,TRUE);
  1390. // continues on to ordinary command line execution code below...
  1391. } else {
  1392. // Running from service manager
  1393. _winPokeAHole();
  1394. ZeroTierOneService zt1WindowsService;
  1395. if (CServiceBase::Run(zt1WindowsService) == TRUE) {
  1396. return 0;
  1397. } else {
  1398. fprintf(stderr,"%s: unable to start service (try -h for help)" ZT_EOL_S,argv[0]);
  1399. return 1;
  1400. }
  1401. }
  1402. #endif // __WINDOWS__
  1403. #ifdef __UNIX_LIKE__
  1404. #ifdef ZT_HAVE_DROP_PRIVILEGES
  1405. if (!skipRootCheck)
  1406. dropPrivileges(argv[0],homeDir);
  1407. #endif
  1408. std::string pidPath(homeDir + ZT_PATH_SEPARATOR_S + ZT_PID_PATH);
  1409. {
  1410. // Write .pid file to home folder
  1411. FILE *pf = fopen(pidPath.c_str(),"w");
  1412. if (pf) {
  1413. fprintf(pf,"%ld",(long)getpid());
  1414. fclose(pf);
  1415. }
  1416. }
  1417. #endif // __UNIX_LIKE__
  1418. _OneServiceRunner thr(argv[0],homeDir,port);
  1419. thr.threadMain();
  1420. //Thread::join(Thread::start(&thr));
  1421. #ifdef __UNIX_LIKE__
  1422. OSUtils::rm(pidPath.c_str());
  1423. #endif
  1424. return thr.returnValue;
  1425. }