one.cpp 45 KB

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