one.cpp 61 KB

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