one.cpp 46 KB

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