one.cpp 45 KB

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