one.cpp 48 KB

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