one.cpp 48 KB

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